From 9b24645e7fd3b8f071d80d0a5583f4d5213c1707 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 01:36:34 +0000 Subject: [PATCH] Header becomes the door to My Health, with shortcuts on the tabs The greeting moves to the eyebrow and the header's main line becomes a tappable health status (HealthHeadline): lab markers outside range in the latest report, then a radar sign, then "learning you", then the weakest health area. It opens Lab reports, What changed or My Health. One line, ellipsised, and it keeps its last text while the next one is read. Sleep, Vitals and Activity each get one in-context row into My Health. Today's bottom "My Health & Trends" card is removed. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- AGENTS.md | 7 ++ app/src/main/assets/i18n/pt-BR.json | 17 +++++ .../com/pulseloop/service/HealthHeadline.kt | 72 ++++++++++++++++++ .../java/com/pulseloop/ui/PulseLoopApp.kt | 24 ++++++ .../com/pulseloop/ui/components/AppChrome.kt | 61 ++++++++++++--- .../pulseloop/ui/screens/ActivityScreen.kt | 6 ++ .../com/pulseloop/ui/screens/MyHealthUi.kt | 13 ++-- .../java/com/pulseloop/ui/screens/Screens.kt | 7 ++ .../com/pulseloop/ui/screens/SleepScreen.kt | 6 ++ .../com/pulseloop/ui/screens/TodayScreen.kt | 6 +- .../pulseloop/service/HealthHeadlineTest.kt | 74 +++++++++++++++++++ 11 files changed, 272 insertions(+), 21 deletions(-) create mode 100644 app/src/main/java/com/pulseloop/service/HealthHeadline.kt create mode 100644 app/src/test/java/com/pulseloop/service/HealthHeadlineTest.kt diff --git a/AGENTS.md b/AGENTS.md index 9935238f..1e8634f0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1209,6 +1209,13 @@ clutter came from ignoring one of them: - **Inside a screen, summary first, detail on tap.** A screen leads with one summary and its primary action; everything else is a row that opens. A new section added inline at full weight is how My Health became a wall. +- **My Health's door is the header, on every tab** (`AppHeader` + `service/HealthHeadline.kt`). + The greeting is the eyebrow; under it one line says the most important thing first: lab + markers outside their range in the latest report (opens Lab reports), then a radar sign (opens + What changed), then "Learning you" before the 14-night baseline, then the weakest health area. + It points at what to look at and never names a condition. It is one line, ellipsised, and keeps + its last text while the next is read, so the header never changes height or blanks. Sleep, + Vitals and Activity each end with one in-context row into My Health; Today has none. - **One open section per screen.** Today shows two rows of tiles and folds the rest behind "Show all metrics"; My Health keeps health areas open and folds Trends, Habits and Stress into closed sections (`Section(summary = …)`), and the radar to one line unless it flags something. diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index 3aa70270..1960a8cd 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -33,6 +33,7 @@ ". Your usual day: {0}": ". Seu dia habitual: {0}", "1 bowl": "1 tigela", "1 cup": "1 xícara", + "1 lab marker to review": "1 marcador de exame para revisar", "1 ladle (100 g)": "1 concha (100 g)", "1 medium": "1 médio", "1 or 2": "1 ou 2", @@ -164,6 +165,7 @@ "Alcohol: estimated clear for feeding around {0}": "Álcool: estimativa de liberação para amamentar por volta de {0}", "Alcoólicos Anônimos": "Alcoólicos Anônimos", "Alerts when your ring's battery runs low": "Alerta quando a bateria do anel estiver baixa", + "All health areas steady": "Todas as áreas estáveis", "All models from {0} ({1})": "Todos os modelos de {0} ({1})", "All three hold. LAM is about 98% effective only while all three do.": "As três condições valem. A LAM tem cerca de 98% de eficácia somente enquanto as três valerem.", "All-day heart rate": "Frequência cardíaca o dia todo", @@ -281,6 +283,7 @@ "Breathe": "Respirar", "Breathe in": "Inspire", "Breathe out": "Expire", + "Breathing rate above your usual": "Respiração acima do seu normal", "Breathing sessions and how you recover": "Sessões de respiração e como você se recupera", "Breathing sessions this week": "Sessões de respiração nesta semana", "Bring it on": "Manda ver", @@ -606,6 +609,7 @@ "Fell asleep": "Adormeceu", "Female": "Feminino", "Fever of 38 °C or higher": "Febre de 38 °C ou mais", + "Fewer steps than usual": "Menos passos que o normal", "Filter models": "Filtrar modelos", "Filter, e.g. claude": "Filtrar, ex.: claude", "Find ring": "Encontrar anel", @@ -670,6 +674,7 @@ "HR, SpO₂, HRV & stress": "HR, SpO₂, HRV e estresse", "HRV": "HRV", "HRV balance": "Equilíbrio de HRV", + "HRV below your usual": "VFC abaixo do seu normal", "HRV is exported as RMSSD — Health Connect has no SDNN type, and the rings' metric is vendor-undocumented.": "A HRV é exportada como RMSSD — o Health Connect não tem um tipo SDNN, e a métrica dos anéis não é documentada pelo fabricante.", "HRV is personal. Wear your ring for about a week to learn your baseline.": "A HRV é pessoal. Use seu anel por cerca de uma semana para aprendermos sua linha de base.", "HRV lower than usual": "HRV mais baixa que o normal", @@ -734,8 +739,10 @@ "How much you were awake once asleep. Some waking is normal; long or frequent wake-ups lower this.": "Quanto tempo você ficou acordado depois de adormecer. Despertar um pouco é normal; despertares longos ou frequentes reduzem esta nota.", "How often the ring measures in the background. Shorter heart-rate intervals give finer history at the cost of battery.": "Com que frequência o anel mede em segundo plano. Intervalos menores de frequência cardíaca dão um histórico mais detalhado, mas gastam mais bateria.", "How often you exercised this week. Three or more sessions a week is a good target.": "Com que frequência você se exercitou nesta semana. Três ou mais sessões por semana é uma boa meta.", + "How the month went": "Como foi o mês", "How your last months went: health areas, trends and habits": "Como foram seus últimos meses: áreas da saúde, tendências e hábitos", "How your ring compares with {0}, the device you chose to trust. This is agreement between two consumer devices, not a lab measurement.": "Como seu anel se compara com {0}, o dispositivo em que você escolheu confiar. É a concordância entre dois aparelhos de consumo, não uma medição de laboratório.", + "How your vitals moved, and your exams, in My Health": "Como seus sinais vitais mudaram e seus exames, em Minha saúde", "Human milk banks (rBLH)": "Bancos de leite humano (rBLH)", "I don't see sleep data for last night. Wear your ring overnight and sync in the morning so I can compare your sleep against your baseline.": "Não vejo dados de sono da noite passada. Use o anel durante a noite e sincronize de manhã para eu comparar seu sono com sua linha de base.", "I only have {0} tracked {1} for this {2}. Wear the ring overnight for a few more nights and I'll build a reliable {3}ly picture.": "Só tenho {0} {1} registradas para este período ({2}). Use o anel à noite por mais algumas noites e vou montar uma visão confiável por {3}.", @@ -820,6 +827,7 @@ "Lean {0} {1}": "Massa magra {0} {1}", "Learned from nights you woke recovered": "Aprendido com noites em que você acordou recuperado", "Learning": "Aprendendo", + "Learning you · {0} of {1} nights": "Conhecendo você · {0} de {1} noites", "Learning your baseline: {0} of {1} nights. Keep wearing your ring to bed.": "Aprendendo sua linha de base: {0} de {1} noites. Continue dormindo com o anel.", "Learning your dry nights: {0} of {1}. Then PulseLoop shows what each drink does to your sleep.": "Aprendendo suas noites sem álcool: {0} de {1}. Depois o PulseLoop mostra o que cada bebida faz com seu sono.", "Learning your normal: {0} of {1} nights.": "Aprendendo seu normal: {0} de {1} noites.", @@ -1082,6 +1090,7 @@ "Open": "Abrir", "Open Drinks: this week, your plan and what drinking does to your nights": "Abrir Bebidas: esta semana, seu plano e o que beber faz com suas noites", "Open Health Connect": "Abrir Health Connect", + "Open My Health": "Abrir Minha saúde", "Open Nutrition Log": "Abrir registro de nutrição", "Open PulseLoop to sync": "Abra o PulseLoop para sincronizar", "Open Settings": "Abrir Configurações", @@ -1262,6 +1271,7 @@ "Rest days let your body adapt to training. One or two easier days a week is enough for most people.": "Dias de descanso permitem que o corpo se adapte ao treino. Um ou dois dias mais leves por semana bastam para a maioria das pessoas.", "Restfulness": "Tranquilidade", "Resting HR": "FC em repouso", + "Resting HR above your usual": "FC de repouso acima do normal", "Resting calibrating": "Calibrando repouso", "Resting heart rate": "Frequência cardíaca em repouso", "Resting heart rate often drops below your old normal around week 7 and takes months to settle; HRV tends to climb back. Differences between women are large.": "A frequência cardíaca em repouso costuma cair abaixo do seu normal antigo por volta da semana 7 e leva meses para se estabilizar; o HRV tende a voltar a subir. As diferenças entre mulheres são grandes.", @@ -1327,6 +1337,7 @@ "See result": "Ver resultado", "See what affects you": "Veja o que afeta você", "See what drinking does to your own nights": "Veja o que beber faz com suas próprias noites", + "See your last 90 days": "Veja seus últimos 90 dias", "See your vitals": "Ver seus sinais vitais", "Send": "Enviar", "Send Test Check-in Now": "Enviar check-in de teste agora", @@ -1520,6 +1531,7 @@ "Team or racket sports": "Esportes coletivos ou de raquete", "Tell the coach, and it plans with your scale, ring and food data.": "Conte ao coach, e ele planeja com os dados da sua balança, do anel e da alimentação.", "Temperature": "Temperatura", + "Temperature above your usual": "Temperatura acima do seu normal", "Temperature trend": "Tendência de temperatura", "Ten quick questions about the last 7 days, used by health services worldwide to spot postpartum depression early.": "Dez perguntas rápidas sobre os últimos 7 dias, usadas por serviços de saúde no mundo todo para identificar cedo a depressão pós-parto.", "That PDF has no pages to read.": "Esse PDF não tem páginas para ler.", @@ -1605,6 +1617,7 @@ "Treats a low resting heart rate as a sign of fitness rather than a concern, and relaxes the low-HR threshold.": "Trata uma frequência cardíaca em repouso baixa como sinal de condicionamento, e não de preocupação, e flexibiliza o limite de HR baixa.", "Trend": "Tendência", "Trends": "Tendências", + "Trends & lab reports": "Tendências e exames", "Trigger real-time ring readings": "Acionar leituras do anel em tempo real", "Trouble breathing, chest pain or a racing heart": "Falta de ar, dor no peito ou coração acelerado", "Try again": "Tentar novamente", @@ -1764,6 +1777,7 @@ "You're {0} step{1} away from Developer options.": "Faltam {0} passo{1} para as Opções do desenvolvedor.", "You've reached today's target. Water or tea if you're hungry": "Você atingiu a meta de hoje. Água ou chá se estiver com fome", "Your HRV dipped this week. Lighter days and consistent sleep help it recover.": "Sua HRV caiu esta semana. Dias mais leves e sono regular ajudam a recuperá-la.", + "Your activity trend and habits, in My Health": "Sua tendência de atividade e hábitos, em Minha saúde", "Your age, sex, height and weight let the ring compute accurate calories (and, on 56ff/Jring rings, blood sugar). Blood pressure is measured directly by the sensor.": "Sua idade, sexo, altura e peso permitem que o anel calcule as calorias com precisão (e, nos anéis 56ff/Jring, a glicose). A pressão arterial é medida diretamente pelo sensor.", "Your answers stay on this phone. They aren't in backups, diagnostics or Health Connect.": "Suas respostas ficam neste celular. Não entram em backups, diagnósticos nem no Health Connect.", "Your answers suggest drinking at a level that is likely affecting your health. Please talk to a doctor. If you drink most days, don't stop all at once: stopping suddenly can be dangerous, and a doctor can help you cut down safely.": "Suas respostas sugerem um consumo de álcool que provavelmente está afetando sua saúde. Converse com um médico. Se você bebe na maioria dos dias, não pare de uma vez: parar de repente pode ser perigoso, e um médico pode ajudar você a reduzir com segurança.", @@ -1801,6 +1815,7 @@ "Your score: {0} of 30": "Sua pontuação: {0} de 30", "Your skin temperature last night compared with your usual. A rise of half a degree or more can come with illness, a hard training load, alcohol or the menstrual cycle.": "Sua temperatura da pele na noite passada comparada com o seu habitual. Um aumento de meio grau ou mais pode acompanhar doença, treino pesado, álcool ou o ciclo menstrual.", "Your sleep duration and stage balance were strong. Deep sleep looked supportive, which helped keep the overall score high.": "A duração do sono e o equilíbrio entre os estágios foram ótimos. O sono profundo ajudou, o que manteve a pontuação geral alta.", + "Your sleep trend and what moves it, in My Health": "Sua tendência de sono e o que a afeta, em Minha saúde", "Your sleep was in a workable range, with the score shaped mostly by duration and stage balance. Deep and light sleep were readable enough to give a useful recovery snapshot.": "Seu sono ficou numa faixa razoável, com a pontuação definida principalmente pela duração e pelo equilíbrio dos estágios. O sono profundo e o leve foram legíveis o bastante para dar um bom retrato da recuperação.", "Your usual {0}-day cycle would have ended {1} day{2} ago.": "Seu ciclo habitual de {0} dias teria terminado há {1} dia{2}.", "Your week at a glance": "Sua semana num relance", @@ -1883,6 +1898,7 @@ "{0} in · {1} out": "{0} entrada · {1} saída", "{0} inactive {1} since {2}:00": "{0} {1} sem se mexer desde as {2}:00", "{0} is retiring this model on {1}.": "{0} vai descontinuar este modelo em {1}.", + "{0} lab markers to review": "{0} marcadores de exame para revisar", "{0} left this week": "Restam {0} esta semana", "{0} markers": "{0} marcadores", "{0} markers found": "{0} marcadores encontrados", @@ -1927,6 +1943,7 @@ "{0} {1} in the last 7 days": "{0} {1} nos últimos 7 dias", "{0} · ring {1} · {2} {3}": "{0} · anel {1} · {2} {3}", "{0} · the lab's range is {1}": "{0} · a faixa do laboratório é {1}", + "{0} · {1}": "{0} · {1}", "{0} · {1} drink": "{0} · {1} bebida", "{0} · {1} readings · {2} on average": "{0} · {1} leituras · {2} em média", "{0} – {1} leaves tonight's totals and the hypnogram, and it won't come back on re-sync.": "{0} – {1} sai dos totais desta noite e do hipnograma, e não volta numa nova sincronização.", diff --git a/app/src/main/java/com/pulseloop/service/HealthHeadline.kt b/app/src/main/java/com/pulseloop/service/HealthHeadline.kt new file mode 100644 index 00000000..47f7b54b --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/HealthHeadline.kt @@ -0,0 +1,72 @@ +package com.pulseloop.service + +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** + * The one line under the greeting in every tab's header, which opens My Health. + * + * It says the most important thing first: lab markers outside their range, then a sign from the + * radar (What changed), then "still learning you", then how the health areas stand. It never + * names a condition: it points at what to look at, and the screen it opens says the rest. + */ +object HealthHeadline { + enum class Kind { LABS, RADAR, LEARNING, AREAS, NONE } + + /** [route] is the screen the line opens; [attention] paints the dot amber. */ + data class Headline(val kind: Kind, val text: String, val route: String, val attention: Boolean) + + fun pick(labsOutside: Int, radar: SymptomRadar.Result?, areas: List): Headline { + if (labsOutside > 0) { + val text = if (labsOutside == 1) tr("1 lab marker to review") else trf("{0} lab markers to review", labsOutside) + return Headline(Kind.LABS, text, "lab_reports", attention = true) + } + if (radar != null && radar.baselineNights >= SymptomRadar.MIN_BASELINE && radar.level != SymptomRadar.Level.NONE) { + val top = radar.flagged.maxByOrNull { it.z } + return Headline(Kind.RADAR, top?.let { signalText(it.metric) } ?: radar.level.label, "what_changed", attention = true) + } + if (radar != null && radar.baselineNights < SymptomRadar.MIN_BASELINE) { + return Headline( + Kind.LEARNING, + trf("Learning you · {0} of {1} nights", radar.baselineNights, SymptomRadar.MIN_BASELINE), + "my_health", attention = false, + ) + } + val worst = areas.maxByOrNull { it.rating.ordinal } + if (worst != null) { + return when (worst.rating) { + HealthArea.Rating.THRIVING, HealthArea.Rating.GOOD -> + Headline(Kind.AREAS, tr("All health areas steady"), "my_health", attention = false) + HealthArea.Rating.FAIR -> + Headline(Kind.AREAS, trf("{0} · {1}", worst.title, worst.rating.label), "my_health", attention = false) + HealthArea.Rating.NEEDS_CARE -> + Headline(Kind.AREAS, trf("{0} · {1}", worst.title, worst.rating.label), "my_health", attention = true) + } + } + return Headline(Kind.NONE, tr("My Health"), "my_health", attention = false) + } + + /** What moved, in the strain direction the radar measured. Never what it might mean. */ + fun signalText(metric: SymptomRadar.Metric): String = when (metric) { + SymptomRadar.Metric.TEMPERATURE, SymptomRadar.Metric.TEMPERATURE_TREND -> tr("Temperature above your usual") + SymptomRadar.Metric.RESTING_HR -> tr("Resting HR above your usual") + SymptomRadar.Metric.HRV -> tr("HRV below your usual") + SymptomRadar.Metric.RESPIRATORY_RATE -> tr("Breathing rate above your usual") + SymptomRadar.Metric.INACTIVE -> tr("Fewer steps than usual") + } + + /** Markers outside the lab's range in the latest report only: an older one was superseded. */ + fun labsOutside(reports: List, results: List): Int { + val latest = reports.maxWithOrNull(compareBy({ it.collectedDay }, { it.createdAt })) ?: return 0 + return results.count { it.reportId == latest.id && LabReports.isOutside(it.flag) } + } + + suspend fun load(db: PulseLoopDatabase): Headline = withContext(Dispatchers.Default) { + val labs = runCatching { labsOutside(db.labDao().reports(), db.labDao().results()) }.getOrDefault(0) + val snap = runCatching { HealthInsightsRepository.load(db) }.getOrNull() + pick(labs, snap?.radar, snap?.areas.orEmpty()) + } +} diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index bbfbc1b1..05a8c05a 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -15,6 +15,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch +import kotlinx.coroutines.flow.map import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.selected @@ -379,6 +380,26 @@ fun PulseLoopApp() { LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE val tabRoutes = remember(tabs) { tabs.map { it.route }.toSet() } + // The header's health line (HealthHeadline). Held here, not in the top bar, so it + // survives the coach screen swapping the header out; read off the main thread every + // few minutes and again when lab results change. The last line stays up while the + // next is read, so the header never blanks. + var headline by remember { mutableStateOf(null) } + val labsKey by remember(db) { + kotlinx.coroutines.flow.combine(db.labDao().reportsFlow(), db.labDao().resultsFlow()) { reports, results -> + com.pulseloop.service.HealthHeadline.labsOutside(reports, results) * 100_000 + reports.size + } + }.collectAsState(initial = -1) + LaunchedEffect(labsKey) { + while (true) { + runCatching { com.pulseloop.service.HealthHeadline.load(db) }.getOrNull()?.let { headline = it } + delay(5 * 60_000L) + } + } + val profileName by remember(db) { + db.userProfileDao().getFlow().map { it?.name } + }.collectAsState(initial = null) + // iOS-style frosted tab bar (.ultraThinMaterial parity): the scrollable tabs // render UNDER the bar (hazeSource on the NavHost) and the bar blurs whatever // is behind it. Real RenderEffect blur on Android 12+, scrim fallback below. @@ -490,6 +511,9 @@ fun PulseLoopApp() { onOpenSettings = { navController.navigate("settings") }, idle = ble.idleSince != null, sourceLabel = hcSource?.let { com.pulseloop.health.source.HealthConnectSource.label(context, it) + tr(" · Health Connect") }, + name = profileName, + headline = headline, + onOpenHeadline = { target -> navController.navigate(target) { launchSingleTop = true } }, ) // Thin sync-progress accent under the greeting while history streams in. // Its 2dp are always reserved: appearing and disappearing changed the diff --git a/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt b/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt index 9d863a85..a0433183 100644 --- a/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt +++ b/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt @@ -14,6 +14,8 @@ import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import com.pulseloop.service.HealthHeadline import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Settings import androidx.compose.material3.Icon @@ -36,9 +38,9 @@ import com.pulseloop.ui.theme.PulseColors import java.util.Calendar /** - * Fixed top header shared by every tab — ported from RootViews.swift `AppHeader`: - * small uppercase brand over a time-based greeting on the left; the connection-status - * pill plus a settings gear on the right. + * Fixed top header shared by every tab: the greeting as a small uppercase eyebrow over a + * one-line health status that opens My Health (or the screen the status is about); the + * connection-status pill plus a settings gear on the right. */ @Composable fun AppHeader( @@ -49,32 +51,67 @@ fun AppHeader( idle: Boolean = false, /** Set while Health Connect stands in for a ring ("Oura · Health Connect"); replaces the BLE state. */ sourceLabel: String? = null, + /** The profile's first name, added to the greeting. */ + name: String? = null, + /** The health line under the greeting (`HealthHeadline`); null while it is first read. */ + headline: HealthHeadline.Headline? = null, + onOpenHeadline: (String) -> Unit = {}, ) { Row( modifier = Modifier .fillMaxWidth() // No opaque background: the caller layers this header on the glass // top bar (hazeEffect in PulseLoopApp), which supplies the material. - .padding(start = 20.dp, end = 8.dp, top = 2.dp, bottom = 6.dp), + .padding(start = 12.dp, end = 8.dp, top = 2.dp, bottom = 6.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), ) { - Column(modifier = Modifier.weight(1f)) { + // The greeting is the eyebrow now; the line below it is the door to My Health. + // Both are one line, ellipsised, so a long translation or a new headline never + // changes the header's height. + val firstName = name?.trim()?.substringBefore(' ')?.takeIf { it.isNotEmpty() } + val greeting = (if (firstName != null) "${greetingForHour()}, $firstName" else greetingForHour()).uppercase() + val line = headline?.text ?: tr("My Health") + Column( + modifier = Modifier + .weight(1f) + .heightIn(min = 44.dp) + .clip(RoundedCornerShape(8.dp)) + .clickable( + onClickLabel = tr("Open My Health"), + role = Role.Button, + ) { onOpenHeadline(headline?.route ?: "my_health") } + .padding(horizontal = 8.dp, vertical = 2.dp), + verticalArrangement = Arrangement.Center, + ) { Text( - "PULSELOOP", + greeting, fontSize = 10.sp, fontWeight = FontWeight.Medium, letterSpacing = 1.2.sp, color = PulseColors.textMuted, - ) - Text( - greetingForHour(), - fontSize = 17.sp, - fontWeight = FontWeight.SemiBold, - color = PulseColors.textPrimary, maxLines = 1, overflow = TextOverflow.Ellipsis, ) + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + val dot = when { + headline == null -> PulseColors.textMuted + headline.attention -> PulseColors.warning + headline.kind == HealthHeadline.Kind.LEARNING || headline.kind == HealthHeadline.Kind.NONE -> PulseColors.textMuted + else -> PulseColors.accent + } + Box(Modifier.size(8.dp).clip(CircleShape).background(dot)) + Text( + line, + fontSize = 15.sp, + fontWeight = FontWeight.SemiBold, + color = PulseColors.textPrimary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f, fill = false), + ) + Text("›", fontSize = 18.sp, color = PulseColors.textMuted, maxLines = 1) + } } ConnectionStatusPill( state = state, diff --git a/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt index ce7e5d92..873341a4 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt @@ -250,6 +250,12 @@ fun ActivityScreen( if (state.dayOffset == 0) item { CardioLoadCard(state.workoutsLoaded to state.finishedWorkouts.size) } item { WeeklyGoalCard(state, days, onTap = { goalsOpen = true }) } + // In-context door to My Health: after the week's goal, how the month went. + if (navController != null) item { + MyHealthEntryCard(tr("How the month went"), tr("Your activity trend and habits, in My Health")) { + navController.navigate("my_health") { launchSingleTop = true } + } + } // The blocks behind today's total, each removable (issue #70). Under the summary rather // than beside it: it answers "why is that number wrong", which is a question you only ask // after reading the number. diff --git a/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt b/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt index 12f7f153..ee66183b 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt @@ -595,18 +595,21 @@ fun BreatheScreen(onBack: () -> Unit) { private const val BREATH_CYCLE_MS = 10_000L private const val INHALE_MS = 4_000L -/** The way into [MyHealthScreen] from Vitals: one row, with Rest Mode shown while it is on. */ +/** + * A tab's shortcut into [MyHealthScreen], worded for the question that tab raises + * ("See your last 90 days" on Sleep, "Trends & lab reports" on Vitals, "How the month went" + * on Activity). The header's health line is the main door; this is the in-context one. + */ @Composable -fun MyHealthEntryCard(onClick: () -> Unit) { - // Rest Mode has its own line on Today now, so this row only says what is behind it. +fun MyHealthEntryCard(title: String, subtitle: String, onClick: () -> Unit) { Row( Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) .clickable(onClick = onClick).padding(16.dp), verticalAlignment = Alignment.CenterVertically, ) { Column(Modifier.weight(1f)) { - Text(tr("My Health & Trends"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text(tr("How your last months went: health areas, trends and habits"), fontSize = 12.sp, color = PulseColors.textMuted) + Text(title, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(subtitle, fontSize = 12.sp, color = PulseColors.textMuted) } Text("›", fontSize = 22.sp, color = PulseColors.textMuted) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/Screens.kt b/app/src/main/java/com/pulseloop/ui/screens/Screens.kt index 8f2ae146..f4ca6e18 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/Screens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/Screens.kt @@ -525,6 +525,13 @@ fun VitalsScreen( item { HiddenMetricsTray(hiddenCards) { editState.setHidden(it, false) } } } + // In-context door to My Health: after today's readings, how they moved and the exams. + if (!editState.editing && navController != null) item { + MyHealthEntryCard(tr("Trends & lab reports"), tr("How your vitals moved, and your exams, in My Health")) { + navController.navigate("my_health") { launchSingleTop = true } + } + } + item { Spacer(Modifier.height(32.dp)) } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt index 9092b7a1..b6138fa9 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt @@ -116,6 +116,12 @@ fun SleepScreen( if (loaded) { if (state.range == SleepRangeKey.DAY) dayItems(state, navController, viewModel) else aggregateItems(state, navController) + // In-context door to My Health: after the night, the question is the longer run. + if (navController != null) item { + MyHealthEntryCard(tr("See your last 90 days"), tr("Your sleep trend and what moves it, in My Health")) { + navController.navigate("my_health") { launchSingleTop = true } + } + } } item { Spacer(Modifier.height(64.dp)) } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt index 9057aebf..b29b597f 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt @@ -406,10 +406,8 @@ fun TodayScreen( item { HiddenMetricsTray(hiddenCards) { editState.setHidden(it, false) } } } - // The long view ("how have I been this month?") starts from Today, not from inside Vitals. - if (!editState.editing && navController != null) { - item { MyHealthEntryCard { navController.navigate("my_health") } } - } + // The long view ("how have I been this month?") is the header's health line now, + // on every tab, so Today no longer ends with its own My Health card. item { Spacer(Modifier.height(64.dp)) } } diff --git a/app/src/test/java/com/pulseloop/service/HealthHeadlineTest.kt b/app/src/test/java/com/pulseloop/service/HealthHeadlineTest.kt new file mode 100644 index 00000000..4215fa75 --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/HealthHeadlineTest.kt @@ -0,0 +1,74 @@ +package com.pulseloop.service + +import com.pulseloop.data.entity.LabReportEntity +import com.pulseloop.data.entity.LabResultEntity +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** The header's health line: what wins when several things want to be said. */ +class HealthHeadlineTest { + + private val calm = SymptomRadar.Result(SymptomRadar.Level.NONE, emptyList(), 0.0, baselineNights = 20) + private val restingUp = SymptomRadar.Result( + SymptomRadar.Level.MINOR, + listOf( + SymptomRadar.Signal(SymptomRadar.Metric.HRV, 30.0, 42.0, 1.6), + SymptomRadar.Signal(SymptomRadar.Metric.RESTING_HR, 62.0, 56.0, 2.4), + ), + 2.0, baselineNights = 20, + ) + private fun area(rating: HealthArea.Rating, title: String = "Sleep health") = + HealthArea(title, rating, 50, emptyList(), "") + + @Test + fun labsOutsideTheirRangeComeFirst() { + val h = HealthHeadline.pick(2, restingUp, listOf(area(HealthArea.Rating.NEEDS_CARE))) + assertEquals(HealthHeadline.Kind.LABS, h.kind) + assertEquals("2 lab markers to review", h.text) + assertEquals("lab_reports", h.route) + assertEquals("1 lab marker to review", HealthHeadline.pick(1, null, emptyList()).text) + } + + @Test + fun aRadarSignNamesTheStrongestSignalAndOpensWhatChanged() { + val h = HealthHeadline.pick(0, restingUp, emptyList()) + assertEquals(HealthHeadline.Kind.RADAR, h.kind) + assertEquals("Resting HR above your usual", h.text) + assertEquals("what_changed", h.route) + assertTrue(h.attention) + } + + @Test + fun beforeTheBaselineItSaysItIsStillLearning() { + val early = SymptomRadar.Result(SymptomRadar.Level.NONE, emptyList(), 0.0, baselineNights = 4) + val h = HealthHeadline.pick(0, early, listOf(area(HealthArea.Rating.GOOD))) + assertEquals(HealthHeadline.Kind.LEARNING, h.kind) + assertEquals("Learning you · 4 of 14 nights", h.text) + assertFalse(h.attention) + } + + @Test + fun otherwiseTheWeakestAreaSpeaks() { + assertEquals("All health areas steady", HealthHeadline.pick(0, calm, listOf(area(HealthArea.Rating.GOOD), area(HealthArea.Rating.THRIVING))).text) + val fair = HealthHeadline.pick(0, calm, listOf(area(HealthArea.Rating.GOOD), area(HealthArea.Rating.FAIR, "Heart health"))) + assertEquals("Heart health · Fair", fair.text) + assertFalse(fair.attention) + assertTrue(HealthHeadline.pick(0, calm, listOf(area(HealthArea.Rating.NEEDS_CARE))).attention) + assertEquals(HealthHeadline.Kind.NONE, HealthHeadline.pick(0, null, emptyList()).kind) + } + + @Test + fun onlyTheLatestReportCounts() { + val reports = listOf( + LabReportEntity(id = "old", collectedDay = 1_000L, createdAt = 0), + LabReportEntity(id = "new", collectedDay = 2_000L, createdAt = 0), + ) + fun r(id: String, report: String, flag: String) = + LabResultEntity(id = id, reportId = report, panel = "", name = id, markerKey = id, flag = flag) + val results = listOf(r("a", "old", "HIGH"), r("b", "old", "LOW"), r("c", "new", "HIGH"), r("d", "new", "NORMAL")) + assertEquals(1, HealthHeadline.labsOutside(reports, results)) + assertEquals(0, HealthHeadline.labsOutside(emptyList(), results)) + } +}