Cotton code
419 lines · 21.8 KB · KotlinRaw
package com.cottondb.healthimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.borderimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.ColumnScopeimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.RowScopeimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.heightInimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.LazyListScopeimport androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.runtime.Composableimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.produceStateimport androidx.compose.runtime.rememberimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.platform.testTagimport androidx.compose.ui.text.style.TextAlignimport com.cottondb.look.Cardimport com.cottondb.look.CardRowimport com.cottondb.look.Dividerimport com.cottondb.look.Gapimport com.cottondb.look.Glyphimport com.cottondb.look.GlyphButtonimport com.cottondb.look.LButtonimport com.cottondb.look.LFieldimport com.cottondb.look.LLinkimport com.cottondb.look.LTextimport com.cottondb.look.SectionTitleimport com.cottondb.look.labelimport com.cottondb.look.uiimport com.cottondb.shell.arrimport com.cottondb.shell.objimport com.cottondb.shell.strimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.put// Every layout choice the shapes leave open is the iPhone's (MATCH-IOS.md), so the two phones are one// design: a row is its title over its detail with what it says at the trailing edge and a chevron; a value is coloured// by its state, its mark a pill only when the state is not neutral; a screen stood on has a back bar with its title./** The core's answer to [method], asked again whenever [state] moves on (another person, an act done). */@Composableprivate fun answer(state: HealthState, method: String, request: JsonObject): JsonObject? =    produceState<JsonObject?>(null, state.revision, state.person, request) { value = state.ask(method, request) }.value// ── Labs ────────────────────────────────────────────────────────────────────────────────────────────────────────────/** Labs (`health.labs`): search, the strip (out of range now, changed most), the panels in medical order, Other. */@Composablefun LabsScreen(state: HealthState) {    val v = ui    var q by remember { mutableStateOf("") }    val request = state.asking("health.labs", buildJsonObject { if (q.isNotBlank()) put("q", q.trim()) })    val labs = answer(state, "health.labs", request)    Page(Modifier.testTag("health-labs")) {        item { Title(labs?.str("title") ?: state.line("labs.title")) }        item { Switcher(state) }        item {            LField(q, { q = it }, labs?.str("search"), Modifier.padding(start = v.space("gutter"), end = v.space("gutter"), top = v.space("m")), tag = "health-search",                leading = { Glyph("search", v.c.tertiary, v.space("l")) })        }        val shown = labs ?: return@Page        shown.obj("empty")?.let { empty -> item { Empty(state, empty) }; return@Page }        shown.obj("strip")?.let { strip ->            rows(strip.str("outTitle"), null, strip.arr("out")) { ParameterLine(state, it, null) }            rows(strip.str("changedTitle"), null, strip.arr("changed")) { change -> change.obj("row")?.let { ParameterLine(state, it, change.str("change")) } }        }        shown.arr("panels").forEach { panel -> rows(panel.str("name"), panel.str("detail"), panel.arr("rows")) { ParameterLine(state, it, null) } }        shown.obj("other")?.let { other -> rows(other.str("name"), other.str("detail"), other.arr("rows")) { ParameterLine(state, it, null) } }    }}/** One parameter: its name over its day (or the change said), the small trend, the latest value and its state. */@Composableprivate fun ParameterLine(state: HealthState, row: JsonObject, change: String?) {    Line(row.str("name").orEmpty(), change ?: row.str("day"), "health-parameter-${row.str("id")}", { row.obj("act")?.let(state::run) }) {        Trend(row.arr("trend"))        Valued(row.obj("latest"), row.obj("mark"))    }}// ── Parameter ───────────────────────────────────────────────────────────────────────────────────────────────────────/** A parameter's whole history (`health.parameter`): the plain line, the chart with the lab's band, every reading. */@Composablefun ParameterScreen(state: HealthState, request: JsonObject) {    val v = ui    val shown = answer(state, "health.parameter", request)    Column(Modifier.fillMaxSize().background(v.c.background).testTag("health-parameter")) {        TopBar(state, shown?.str("title").orEmpty())        Page {            val p = shown ?: return@Page            item { Heading(p.str("title").orEmpty()) }            p.str("line")?.takeIf { it.isNotEmpty() }?.let { line -> item { Inset(top = "s") { LText(line, "body", v.c.secondary) } } }            val empty = p.obj("empty")            if (empty != null) item { Empty(state, empty) } else {                item { Inset(top = "l") { History(p.arr("points"), p.obj("band")) } }                p.obj("band")?.str("said")?.let { said -> item { Inset { LText(said, "row_detail", v.c.secondary) } } }                rows(state.line("parameter.readings"), null, p.arr("readings")) { ReadingLine(state, it) }            }            p.str("loinc")?.let { loinc ->                item { Inset(top = "xl") { LText(loinc, "row_detail", v.c.tertiary) } }                p.str("attribution")?.let { attribution -> item { Inset(top = "xs") { LText(attribution, "row_detail", v.c.tertiary) } } }            }            item { Gap("xxxl") }        }    }}/** One reading: its day over its lab, as printed, the range and the method; its value and state; it opens its report. */@Composableprivate fun ReadingLine(state: HealthState, reading: JsonObject) {    val detail = listOfNotNull(reading.str("lab"), reading.str("original"), reading.str("interval"), reading.str("method")).filter { it.isNotEmpty() }.joinToString(SEPARATOR)    Line(reading.str("day").orEmpty(), detail, null, { reading.obj("act")?.let(state::run) }) { Valued(reading.obj("said"), reading.obj("mark")) }}// ── Reports ─────────────────────────────────────────────────────────────────────────────────────────────────────────/** Reports (`health.reports`): Add a report as a + at the title, then every report by date, newest first. */@Composablefun ReportsScreen(state: HealthState) {    val v = ui    val shown = answer(state, "health.reports", state.asking("health.reports"))    Page(Modifier.testTag("health-reports")) {        item {            Title(shown?.str("title") ?: state.line("reports.title")) {                shown?.obj("add")?.let { add -> GlyphButton("plus", add.label(), tag = "health-add-report") { state.run(add) } }            }        }        item { Switcher(state) }        val r = shown ?: return@Page        r.obj("empty")?.let { empty -> item { Empty(state, empty) }; return@Page }        rows(null, null, r.arr("rows")) { row ->            Line(row.str("title").orEmpty(), listOfNotNull(row.str("day"), row.str("detail")).joinToString(SEPARATOR), "health-report-${row.str("id")}", { row.obj("act")?.let(state::run) }) {                Pill(row.obj("status"))            }        }        item { Gap("xxxl") }    }}/** A report as printed (`health.report`): a partial's notice, Open the PDF, its facts, then its panels in order. */@Composablefun ReportScreen(state: HealthState, request: JsonObject) {    val v = ui    val shown = answer(state, "health.report", request)    Column(Modifier.fillMaxSize().background(v.c.background).testTag("health-report")) {        TopBar(state, shown?.str("title").orEmpty())        Page {            val r = shown ?: return@Page            item { Heading(r.str("title").orEmpty()) }            r.str("day")?.let { day -> item { Inset(top = "xxs") { LText(day, "row_detail", v.c.secondary) } } }            r.str("notice")?.let { notice ->                item {                    Inset(top = "l") {                        val shape = RoundedCornerShape(v.corner("row"))                        Box(Modifier.fillMaxWidth().clip(shape).background(v.c.wash("attention"), shape).padding(v.space("m")).testTag("health-report-notice")) {                            LText(notice, "body", v.c.tone("attention"))                        }                    }                }            }            r.obj("pdf")?.let { pdf -> item { Inset(top = "l") { LButton(pdf.label(), "neutral", Modifier.fillMaxWidth(), tag = "health-report-pdf") { state.run(pdf) } } } }            val facts = r.arr("facts")            if (facts.isNotEmpty()) {                rows(null, null, facts) { fact ->                    Row(Modifier.fillMaxWidth().padding(horizontal = v.space("l"), vertical = v.space("m")), horizontalArrangement = Arrangement.spacedBy(v.space("m"))) {                        LText(fact.str("label").orEmpty(), "row_detail", v.c.secondary)                        Box(Modifier.weight(1f), contentAlignment = Alignment.CenterEnd) {                            LText(fact.str("value").orEmpty(), "row_title", style = v.type("row_title").copy(textAlign = TextAlign.End))                        }                    }                }            }            r.arr("sections").forEach { section ->                rows(section.str("title"), null, section.arr("rows")) { line ->                    val detail = listOfNotNull(line.str("range")?.takeIf { it.isNotEmpty() }, line.str("method")).joinToString(SEPARATOR)                    Line(line.str("name").orEmpty(), detail, null, { line.obj("act")?.let(state::run) }) { Valued(line.obj("said"), line.obj("mark")) }                }            }            item { Gap("xxxl") }        }    }}// ── Body ────────────────────────────────────────────────────────────────────────────────────────────────────────────/** Body (`health.body`): the owner's measures by section; for anyone else, only what their reports printed. */@Composablefun BodyScreen(state: HealthState) {    val shown = answer(state, "health.body", state.asking("health.body"))    Page(Modifier.testTag("health-body")) {        item {            Title(shown?.str("title") ?: state.line("body.title")) {                // Read Apple Health at the title, the owner's alone: the core answers none on Android.                shown?.obj("connect")?.takeIf { shown.obj("empty") == null }?.let { connect -> LButton(connect.label(), "neutral", tag = "health-body-connect") { state.run(connect) } }            }        }        item { Switcher(state) }        val b = shown ?: return@Page        b.obj("empty")?.let { empty -> item { Empty(state, empty) }; return@Page }        b.arr("sections").forEach { section ->            rows(section.str("title"), null, section.arr("rows")) { row ->                Line(row.str("label").orEmpty(), row.str("day"), "health-metric-${row.str("metric")}", { row.obj("act")?.let(state::run) }) {                    Trend(row.arr("trend"))                    Valued(row.obj("latest"), null)                }            }        }        item { Gap("xxxl") }    }}/** One metric's history (`health.metric`): a report's readings and Apple Health's on one line, a legend where both are. */@Composablefun MetricScreen(state: HealthState, request: JsonObject) {    val v = ui    val shown = answer(state, "health.metric", request)    Column(Modifier.fillMaxSize().background(v.c.background).testTag("health-metric")) {        TopBar(state, shown?.str("title").orEmpty())        Page {            val m = shown ?: return@Page            item { Heading(m.str("title").orEmpty()) }            m.str("unit")?.takeIf { it.isNotEmpty() }?.let { unit -> item { Inset(top = "xxs") { LText(unit, "row_detail", v.c.secondary) } } }            val points = m.arr("points")            item { Inset(top = "l") { History(points, null) } }            val sources = points.mapNotNull { it.str("source") }.toSet()            if (SOURCE_LAB in sources && SOURCE_APPLE in sources) {                item {                    Inset(top = "s") {                        Row(horizontalArrangement = Arrangement.spacedBy(v.space("l"))) {                            Legend(filled = true, state.line("body.from_apple"))                            Legend(filled = false, state.line("body.from_report"))                        }                    }                }            }            rows(state.line("body.readings"), null, m.arr("readings")) { ReadingLine(state, it) }            item { Gap("xxxl") }        }    }}/** Which source a point is: filled for Apple Health, ringed for a lab report (as the chart draws them). */@Composableprivate fun Legend(filled: Boolean, label: String) {    val v = ui    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(v.space("xs"))) {        val dot = Modifier.size(v.space("chart_point")).clip(CircleShape)        Box(if (filled) dot.background(v.c[ROLE_POINT]) else dot.border(v.space("xxs"), v.c[ROLE_POINT], CircleShape))        LText(label, "row_detail", v.c.secondary, lines = 1)    }}// ── Settings ────────────────────────────────────────────────────────────────────────────────────────────────────────/** Settings (`health.settings`): the people (sex, date of birth, this is me), names not yet known, what these records are. */@Composablefun SettingsScreen(state: HealthState) {    val v = ui    val shown = answer(state, "health.settings", state.asking("health.settings"))    Page(Modifier.testTag("health-settings")) {        item { Title(shown?.str("title") ?: state.line("settings.title")) }        shown?.arr("sections")?.forEach { section ->            rows(section.str("title"), null, section.arr("rows")) { row ->                Column(Modifier.fillMaxWidth().padding(horizontal = v.space("l"), vertical = v.space("m")).testTag("health-setting-${row.str("id")}")) {                    LText(row.str("label").orEmpty(), "row_title")                    row.str("detail")?.let { Gap("xxs"); LText(it, "row_detail", v.c.secondary) }                    val acts = row.arr("acts")                    if (acts.isNotEmpty()) {                        Gap("xs")                        Row(horizontalArrangement = Arrangement.spacedBy(v.space("xs"))) {                            acts.forEach { act -> LLink(act.label(), "accent", tag = "health-act-${act.str("id")}") { state.run(act) } }                        }                    }                }            }        }        item { Gap("xxxl") }    }}// ── pieces ──────────────────────────────────────────────────────────────────────────────────────────────────────────/** A screen's scrolling column on the look's ground. */@Composableprivate fun Page(modifier: Modifier = Modifier, content: LazyListScope.() -> Unit) {    val v = ui    LazyColumn(modifier.fillMaxSize().background(v.c.background), content = content)}/** A place's large title, with what stands at its trailing edge (Reports' +, Body's Read Apple Health). */@Composableprivate fun Title(text: String, trailing: @Composable RowScope.() -> Unit = {}) {    val v = ui    Row(        Modifier.fillMaxWidth().padding(start = v.space("gutter"), end = v.space("gutter") - v.space("m"), top = v.space("l")).heightIn(min = v.space("tap")),        verticalAlignment = Alignment.CenterVertically,    ) {        LText(text, "large_title", modifier = Modifier.weight(1f))        trailing()    }}/** A screen stood on: back, and its title in the headline, as the iPhone's top bar. */@Composableprivate fun TopBar(state: HealthState, title: String) {    val v = ui    Row(        Modifier.fillMaxWidth().padding(horizontal = v.space("gutter") - v.space("m")).heightIn(min = v.space("tap")),        verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(v.space("s")),    ) {        GlyphButton("back", state.line("acts.back"), tag = "health-back") { state.back() }        LText(title, "headline", lines = 1, modifier = Modifier.weight(1f))    }}/** A stood-on screen's own title, in the look's `title`. */@Composableprivate fun Heading(text: String) = Inset(top = "s") { LText(text, "title") }/** Content inset by the gutter, [top] the look's space above it. */@Composableprivate fun Inset(top: String? = null, content: @Composable () -> Unit) {    val v = ui    Box(Modifier.fillMaxWidth().padding(start = v.space("gutter"), end = v.space("gutter"), top = top?.let { v.space(it) } ?: v.space("xxs") * 0)) { content() }}/** A run of rows under a section heading, in one card, divided by hairlines inset by the row's padding. */private fun <T> LazyListScope.rows(title: String?, detail: String?, rows: List<T>, row: @Composable ColumnScope.(T) -> Unit) {    if (rows.isEmpty()) return    // A run with no heading (a report's facts, the Reports list) stands a gap below what is above it.    if (title != null) item { SectionTitle(title, detail) } else item { Gap("l") }    item {        Card {            rows.forEachIndexed { i, one ->                if (i > 0) Divider()                row(one)            }        }    }}/** A row that opens what it names: its title over its detail, what it says at the trailing edge, a chevron. */@Composableprivate fun Line(title: String, detail: String?, tag: String?, open: () -> Unit, trailing: @Composable RowScope.() -> Unit) {    val v = ui    CardRow(tag?.let { Modifier.testTag(it) } ?: Modifier, onClick = open, trailing = {        Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(v.space("m"))) {            trailing()            Glyph("chevron", v.c.tertiary, v.space("l"))        }    }) {        LText(title, "row_title", lines = 2)        detail?.takeIf { it.isNotEmpty() }?.let { Gap("xxs"); LText(it, "row_detail", v.c.secondary, lines = 2) }    }}/** A value as printed and its state: the number coloured by the state, its unit smaller beside it; a pill when not neutral. */@Composableprivate fun Valued(said: JsonObject?, mark: JsonObject?) {    val v = ui    val text = said?.str("text") ?: return    val tone = mark?.str("tone")    Column(horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(v.space("xxs"))) {        Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(v.space("xxs"))) {            LText(text, if (said.str("mono") == "true") "value" else "row_title", if (tone == null || tone == "neutral") v.c.text else v.c.tone(tone), lines = 1)            said.str("unit")?.takeIf { it.isNotEmpty() }?.let { LText(it, "unit", v.c.secondary, lines = 1) }        }        if (tone != null && tone != "neutral") Pill(mark)    }}/** A state's word on its wash (`Mark {id, label, tone}`): the only colour a row carries. */@Composableprivate fun Pill(mark: JsonObject?) {    val v = ui    val label = mark?.str("label") ?: return    val tone = mark.str("tone")    val shape = RoundedCornerShape(v.corner("chip"))    Box(Modifier.clip(shape).background(v.c.wash(tone), shape).padding(horizontal = v.space("s"), vertical = v.space("xxs"))) {        LText(label, "label", if (tone == null || tone == "neutral") v.c.secondary else v.c.tone(tone), lines = 1)    }}/** An answer's `empty {title, body, act?}`. */@Composableprivate fun Empty(state: HealthState, empty: JsonObject) {    val v = ui    Column(Modifier.fillMaxWidth().padding(horizontal = v.space("gutter"), vertical = v.space("xxl")).testTag("health-empty"), verticalArrangement = Arrangement.spacedBy(v.space("m"))) {        LText(empty.str("title").orEmpty(), "headline")        LText(empty.str("body").orEmpty(), "body", v.c.secondary)        empty.obj("act")?.let { act -> LButton(act.label(), "accent", tag = "health-empty-${act.str("id")}") { state.run(act) } }    }}/** Between a row's parts, as the core's own details join theirs. */private const val SEPARATOR = " · "/** A point's source (`Point.source`). */internal const val SOURCE_LAB = "lab"internal const val SOURCE_APPLE = "apple_health"/** The look's role for a chart's points. */internal const val ROLE_POINT = "trend_point"