Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
17 changes: 17 additions & 0 deletions app/src/main/assets/i18n/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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}.",
Expand Down Expand Up @@ -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.",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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.",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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.",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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.",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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.",
Expand Down
72 changes: 72 additions & 0 deletions app/src/main/java/com/pulseloop/service/HealthHeadline.kt
Original file line number Diff line number Diff line change
@@ -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<HealthArea>): 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<com.pulseloop.data.entity.LabReportEntity>, results: List<com.pulseloop.data.entity.LabResultEntity>): 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())
}
}
24 changes: 24 additions & 0 deletions app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<com.pulseloop.service.HealthHeadline.Headline?>(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.
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading