From d40588211ac95e2a96428d47b783484ae7cc23bd Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 00:30:37 +0000 Subject: [PATCH] Release 2: My Health as the monthly view, sections moved to Sleep/Activity, Vitals status and Measure picker, Postpartum by urgency, Meds and Nutrition actions first Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- app/src/main/assets/i18n/pt-BR.json | 14 +- .../service/HealthInsightsRepository.kt | 24 +++ .../pulseloop/ui/screens/AccuracyCheckUi.kt | 3 + .../pulseloop/ui/screens/ActivityScreen.kt | 39 ++-- .../java/com/pulseloop/ui/screens/MedsUi.kt | 10 +- .../com/pulseloop/ui/screens/MyHealthUi.kt | 178 ++++++--------- .../pulseloop/ui/screens/NutritionScreen.kt | 85 ++++---- .../com/pulseloop/ui/screens/PostpartumUi.kt | 66 +++--- .../java/com/pulseloop/ui/screens/Screens.kt | 202 +++++++++--------- .../ui/screens/SettingsSubScreens.kt | 2 +- .../com/pulseloop/ui/screens/SleepScreen.kt | 3 + .../com/pulseloop/ui/screens/TodayScreen.kt | 5 + 12 files changed, 324 insertions(+), 307 deletions(-) diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index 48c5ad0f..2d38c098 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -259,6 +259,7 @@ "Body fat {0}%": "Gordura corporal {0}%", "Body metrics": "Medidas corporais", "Body temperature": "Temperatura corporal", + "Breakfast": "Café da manhã", "Breastfeeding and formula": "Amamentação e fórmula", "Breastfeeding only": "Só amamentação", "Breastfeeding only, day and night": "Só amamentação, de dia e de noite", @@ -300,6 +301,7 @@ "Cardio": "Cardio", "Cardio capacity (VO₂max)": "Capacidade cardio (VO₂max)", "Cardio capacity {0}, estimated from resting heart rate and age": "Capacidade cardio {0}, estimada a partir da frequência cardíaca em repouso e da idade", + "Cardio load": "Carga cardio", "Cardio load today": "Carga cardio hoje", "Castanhas": "Castanhas", "Casual or brisk walking": "Caminhada leve ou rápida", @@ -452,6 +454,7 @@ "Device: not recorded": "Dispositivo: não registrado", "Diagnostics": "Diagnósticos", "Diastolic": "Diastólica", + "Dinner": "Jantar", "Disabled": "Desativado", "Disconnect": "Desconectar", "Disconnect Strava?": "Desconectar o Strava?", @@ -486,6 +489,7 @@ "Early evening, when you're under 70% of your step goal. Off in Rest Mode.": "No início da noite, quando você estiver abaixo de 70% da sua meta de passos. Desativado no Modo Descanso.", "Edit": "Editar", "Edit goals": "Editar metas", + "Edit life stage": "Editar fase da vida", "Edit sleep record": "Editar registro de sono", "Edit this record's times": "Editar os horários deste registro", "Edit workout": "Editar treino", @@ -696,6 +700,7 @@ "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 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.", "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.", @@ -741,6 +746,7 @@ "Keep still — measuring heart rate & SpO₂…": "Fique parado — medindo frequência cardíaca e SpO₂…", "Keep still — measuring heart rate…": "Fique parado — medindo frequência cardíaca…", "Keep still — measuring {0}…": "Fique parado — medindo {0}…", + "Keep the ring snug and your hand still until it finishes.": "Mantenha o anel justo e a mão parada até terminar.", "Known lung condition": "Doença pulmonar conhecida", "LAST 3 DAYS": "ÚLTIMOS 3 DIAS", "LAST CAFFEINE": "ÚLTIMA CAFEÍNA", @@ -758,6 +764,7 @@ "Last import {0}": "Última importação {0}", "Last night": "Ontem à noite", "Last night's heart rate and HRV readings weren't enough to score recovery": "As leituras de frequência cardíaca e HRV da noite passada não foram suficientes para calcular a recuperação", + "Last night: all within your usual range": "Noite passada: tudo dentro do seu normal", "Last night: {0}. A few dry nights will show what it does to you.": "Noite passada: {0}. Algumas noites sem álcool vão mostrar o efeito em você.", "Last night: {0}. Your night looked close to your dry ones.": "Noite passada: {0}. Sua noite ficou parecida com as noites sem álcool.", "Last night: {0}. {1}.": "Noite passada: {0}. {1}.", @@ -830,6 +837,7 @@ "Lower risk": "Risco menor", "Lowest heart rate {0} before waking": "Frequência cardíaca mais baixa {0} antes de acordar", "Lowest {0} · {1} readings": "Mínimo {0} · {1} leituras", + "Lunch": "Almoço", "Luteal": "Lútea", "MOOD CHECK-IN": "CHECK-IN DE HUMOR", "MY WEEK": "MINHA SEMANA", @@ -1011,7 +1019,7 @@ "On track": "No caminho certo", "On until {0}/{1}: activity nudges paused, the coach eases off.": "Ativo até {0}/{1}: lembretes de atividade pausados, o Coach pega mais leve.", "On. PulseLoop syncs your ring about every 30 minutes, even while the phone is idle.": "Ativado. O PulseLoop sincroniza seu anel a cada 30 minutos, mesmo com o celular ocioso.", - "Once per dose, at its time, for what you add in My Health → Medications & supplements.": "Uma vez por dose, no horário dela, para o que você adicionar em Minha saúde → Medicamentos e suplementos.", + "Once per dose, at its time, for what you add with + Log → Medication or supplement.": "Uma vez por dose, no horário, para o que você adicionar em + Registrar → Medicamento ou suplemento.", "One tap for the usual ones": "Um toque para as de sempre", "Only needed if you started the server with --api-key. Leave blank otherwise.": "Só é necessário se você iniciou o servidor com --api-key. Caso contrário, deixe em branco.", "Only new data from now on": "Apenas dados novos daqui em diante", @@ -1046,6 +1054,7 @@ "Out of sync": "Fora de sincronia", "Outdoor or treadmill runs": "Corridas ao ar livre ou na esteira", "Output tokens": "Tokens de saída", + "Outside your usual last night: {0}": "Fora do seu normal na noite passada: {0}", "Overwhelming tiredness": "Cansaço extremo", "Ovos mexidos": "Ovos mexidos", "Own your ring data": "Seus dados do anel são seus", @@ -1327,6 +1336,7 @@ "Slightly off": "Um pouco fora", "Slow breathing: in for 4 seconds, out for 6.": "Respiração lenta: inspire por 4 segundos, expire por 6.", "Small signs in your biometrics of something straining your body.": "Sinais leves nos seus dados biométricos de algo sobrecarregando seu corpo.", + "Snack": "Lanche", "Snap your plate; the AI estimates it": "Fotografe seu prato; a IA faz a estimativa", "So far (preliminary)": "Até agora (preliminar)", "Solid": "Boa", @@ -1383,6 +1393,7 @@ "Strava Not Configured": "Strava não configurado", "Strength or circuit training": "Musculação ou treino em circuito", "Stress": "Estresse", + "Stress & breathing": "Estresse e respiração", "Stress management": "Gestão do estresse", "Stressful": "Estressante", "Stressful day": "Dia estressante", @@ -1427,6 +1438,7 @@ "Take the check": "Fazer o teste", "Taken": "Tomado", "Talk it through": "Conversar sobre isso", + "Tap to start": "Toque para começar", "Tapioca com ovo": "Tapioca com ovo", "Tatá, te amo!": "Tatá, te amo!", "Team or racket sports": "Esportes coletivos ou de raquete", diff --git a/app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt b/app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt index fc28ee72..83026579 100644 --- a/app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt +++ b/app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt @@ -256,6 +256,30 @@ object HealthInsightsRepository { return Snapshot(nights, need, debt, radar, todayStress, resilience, bodyClock, cardio, areas, habits, hrToday, sleepWindows, workoutWindows, cardioLoad) } + /** Sleep need, debt and body clock: what the Sleep tab shows under last night. */ + data class SleepBalance(val need: SleepNeed, val debt: SleepDebt?, val bodyClock: BodyClock?) + + suspend fun sleepBalance(db: PulseLoopDatabase, now: Long = System.currentTimeMillis(), zone: ZoneId = ZoneId.systemDefault()): SleepBalance { + val inputs = ReadinessRepository.loadInputs(db, now, zone) + val nights = (inputs.history + listOfNotNull(inputs.lastNight)).sortedBy { it.day } + val today = Instant.ofEpochMilli(now).atZone(zone).toLocalDate() + val need = SleepNeed.estimate(nights, db.userGoalDao().get()?.sleepMinutes ?: 480, today) + return SleepBalance(need, SleepDebt.from(nights, need, today), BodyClock.compute(nights, zone)) + } + + /** Today's cardio load, for the Activity tab; null until there are enough days of heart rate. */ + suspend fun cardioLoadToday(db: PulseLoopDatabase, now: Long = System.currentTimeMillis(), zone: ZoneId = ZoneId.systemDefault()): CardioLoad.Result? { + val inputs = ReadinessRepository.loadInputs(db, now, zone) + val nights = inputs.history + listOfNotNull(inputs.lastNight) + val today = Instant.ofEpochMilli(now).atZone(zone).toLocalDate() + val hr29 = db.measurementDao().rangeReal(MeasurementKind.HEART_RATE.name, today.minusDays(29).atStartOfDay(zone).toInstant().toEpochMilli(), now) + .map { it.timestamp to it.value } + val nightRanges = nights.map { it.startAt..it.endAt } + return runCatching { + CardioLoad.compute(hr29, { t -> nightRanges.any { t in it } }, today, zone, db.userProfileDao().get()?.age) + }.getOrNull() + } + // ── Trends ─────────────────────────────────────────────────────────────── enum class TrendMetric(private val labelEn: String, val unit: String) { diff --git a/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt b/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt index 404ae4f9..b4c707ab 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt @@ -211,6 +211,9 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { } if (hasRing) AccuracyCorrectionsCard() + // The phone-steps comparison is the same question ("is my ring counting right?"), so it + // lives here rather than in My Health. + if (hasRing) StepCalibrationCard(db) val past = history.filter { it.state == AccuracyCheckEntity.STATE_DONE } if (past.isNotEmpty()) { 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 f2fb45ff..521f9fb9 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt @@ -194,38 +194,24 @@ fun ActivityScreen( ) { Icon(Icons.Filled.CalendarMonth, tr("Workout history"), tint = PulseColors.textSecondary) } - } - } - - item { DetectedActivityCard() } - - item { - Row( - Modifier - .fillMaxWidth() - .heightIn(min = 68.dp) - .clip(RoundedCornerShape(8.dp)) - .background(PulseColors.card) - .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(8.dp)) - .clickable { navController?.navigate("log_past_activity") } - .padding(horizontal = 16.dp), - verticalAlignment = Alignment.CenterVertically, - ) { + // Logging a forgotten workout used to be its own full-width card between the + // summary and the day's workouts; it is the same job as recording one. Box( - Modifier.size(40.dp).clip(CircleShape).dither(PulseColors.accent, 0.18f), + Modifier + .size(60.dp) + .clip(CircleShape) + .background(PulseColors.card) + .border(1.dp, PulseColors.borderSubtle, CircleShape) + .clickable(role = Role.Button) { navController?.navigate("log_past_activity") }, contentAlignment = Alignment.Center, ) { - Icon(Icons.Filled.History, null, tint = PulseColors.accent, modifier = Modifier.size(20.dp)) + Icon(Icons.Filled.History, tr("Log Past Activity"), tint = PulseColors.textSecondary) } - Spacer(Modifier.width(12.dp)) - Column(Modifier.weight(1f)) { - Text(tr("Log Past Activity"), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) - Text(tr("Add a workout you forgot to record"), fontSize = 12.sp, color = PulseColors.textMuted) - } - Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, null, tint = PulseColors.textMuted) } } + item { DetectedActivityCard() } + item { Text( tr("TODAY"), @@ -260,6 +246,9 @@ fun ActivityScreen( } } + // Moved from My Health: today's load belongs beside today's activity. + if (state.dayOffset == 0) item { CardioLoadCard(state.workoutsLoaded to state.finishedWorkouts.size) } + item { WeeklyGoalCard(state, days, onTap = { goalsOpen = 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 diff --git a/app/src/main/java/com/pulseloop/ui/screens/MedsUi.kt b/app/src/main/java/com/pulseloop/ui/screens/MedsUi.kt index def38a62..138e3b01 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MedsUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MedsUi.kt @@ -13,6 +13,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Delete import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button @@ -72,6 +73,10 @@ fun MedsScreen(onBack: () -> Unit) { maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center, modifier = Modifier.align(Alignment.Center).padding(horizontal = 56.dp), ) + // Adding is setup, not the daily job: it sits in the header so today's doses lead. + IconButton(onClick = { adding = true }, modifier = Modifier.align(Alignment.CenterEnd)) { + Icon(Icons.Filled.Add, tr("Add medication or supplement"), tint = PulseColors.textSecondary) + } } Column( Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), @@ -147,7 +152,10 @@ fun MedsScreen(onBack: () -> Unit) { } } } - Button(onClick = { adding = true }, modifier = Modifier.fillMaxWidth()) { Text(tr("Add medication or supplement")) } + // With nothing added yet, adding is the only thing to do here: keep the big button. + if (medsLoaded != null && meds.isEmpty()) { + Button(onClick = { adding = true }, modifier = Modifier.fillMaxWidth()) { Text(tr("Add medication or supplement")) } + } Text( tr("A record for you and your doctor. PulseLoop doesn't check interactions or doses; ask your pharmacist."), fontSize = 11.sp, color = PulseColors.textMuted, 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 caa41986..7571bd11 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt @@ -88,7 +88,7 @@ import kotlin.math.roundToInt */ @Composable -private fun Section(title: String, content: @Composable ColumnScope.() -> Unit) { +internal fun Section(title: String, content: @Composable ColumnScope.() -> Unit) { Column( Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp), @@ -100,7 +100,7 @@ private fun Section(title: String, content: @Composable ColumnScope.() -> Unit) } @Composable -private fun Fact(label: String, value: String, note: String? = null, color: Color = PulseColors.textPrimary) { +internal fun Fact(label: String, value: String, note: String? = null, color: Color = PulseColors.textPrimary) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.Top) { Column(Modifier.weight(1f)) { Text(label, fontSize = 14.sp, color = PulseColors.textSecondary) @@ -146,9 +146,6 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () value = runCatching { HealthInsightsRepository.load(db) }.onFailure { loadFailed = true }.getOrNull() } var restUntil by remember { mutableStateOf(RestMode.until(context)) } - // Collected here, not under the loaded branch, so it is in by the time the snapshot is; null - // until then, so the Cycle row never shows "log your period" to someone who has. - val periods by remember { db.periodDao().allFlow() }.collectAsState(initial = null) Column(Modifier.fillMaxSize().background(PulseColors.background)) { Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { @@ -188,54 +185,9 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () if (slow) Text(tr("Reading your history…"), color = PulseColors.textMuted, fontSize = 13.sp) } } else { - Row( - Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) - .clickable(onClick = onWhatChanged).padding(16.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Column(Modifier.weight(1f)) { - Text(tr("What changed"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text(tr("Your nights against your own normal, kept as a log"), fontSize = 12.sp, color = PulseColors.textMuted) - } - Text("›", fontSize = 22.sp, color = PulseColors.textMuted) - } - if (com.pulseloop.service.Postpartum.active()) { - Row( - Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) - .clickable(onClick = onPostpartum).padding(16.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Column(Modifier.weight(1f)) { - val birth = com.pulseloop.service.Postpartum.birthDate!! - Text(trf("Postpartum · week {0}", com.pulseloop.service.Postpartum.weeksSince(birth, java.time.LocalDate.now())), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text(tr("Recovery, nights, mood check-in and warning signs"), fontSize = 12.sp, color = PulseColors.textMuted) - } - Text("›", fontSize = 22.sp, color = PulseColors.textMuted) - } - } - val cycle = periods?.let { list -> Cycle.status(list.map { it.toPeriod() }, java.time.LocalDate.now()) } - Row( - Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) - .clickable(onClick = onCycle).padding(16.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Column(Modifier.weight(1f)) { - Text(cycle?.let { trf("Cycle · day {0} · {1}", it.cycleDay, it.phase.label) } ?: tr("Cycle"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text(cycle?.phase?.note ?: if (periods == null) "" else tr("Log your period to see its phase beside your sleep and recovery"), fontSize = 12.sp, color = PulseColors.textMuted) - } - Text("›", fontSize = 22.sp, color = PulseColors.textMuted) - } - Row( - Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) - .clickable(onClick = onMeds).padding(16.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Column(Modifier.weight(1f)) { - Text(tr("Medications & supplements"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text(tr("Your schedule, today's doses and a week's record"), fontSize = 12.sp, color = PulseColors.textMuted) - } - Text("›", fontSize = 22.sp, color = PulseColors.textMuted) - } + // Overview first: is anything off, then the long view, then the tools to dig in. + // Programs (cycle, meds, postpartum) live on Today and in "+ Log" now, and the + // day's sleep, heart and stress detail on their own tabs. RadarSection(s.radar, restUntil) { days -> RestMode.set(context, days); restUntil = RestMode.until(context) } @@ -253,12 +205,20 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () } } } - SleepSection(s) - StressSection(s, onBreathe) - HeartSection(s) - HabitsSection(s.habits) - StepCalibrationCard(db) TrendsSection(db) + HabitsSection(s.habits, s.cardio) + StressSection(s, onBreathe) + Row( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) + .clickable(onClick = onWhatChanged).padding(16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text(tr("What changed"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("Your nights against your own normal, kept as a log"), fontSize = 12.sp, color = PulseColors.textMuted) + } + Text("›", fontSize = 22.sp, color = PulseColors.textMuted) + } Text( tr("Estimates from your ring compared with your own recent normal, not medical measurements."), fontSize = 11.sp, color = PulseColors.textMuted, @@ -282,7 +242,8 @@ private fun RadarSection(r: SymptomRadar.Result?, restUntil: java.time.LocalDate } Text(r.level.label, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = color) Text(r.level.summary, fontSize = 13.sp, color = PulseColors.textSecondary) - r.signals.forEach { sig -> + // When nothing is flagged the headline says so; five "Normal" rows under it were noise. + if (r.level != SymptomRadar.Level.NONE) r.signals.forEach { sig -> Fact(sig.metric.title, if (sig.flagged) tr("Elevated") else tr("Normal"), sig.detail, if (sig.flagged) PulseColors.warning else PulseColors.textSecondary) } @@ -305,8 +266,8 @@ private fun RadarSection(r: SymptomRadar.Result?, restUntil: java.time.LocalDate } @Composable -private fun SleepSection(s: HealthInsightsRepository.Snapshot) { - Section(tr("Sleep")) { +internal fun SleepBalanceSection(s: HealthInsightsRepository.SleepBalance) { + Section(tr("Sleep balance")) { Fact(tr("Sleep need"), SleepFormat.duration(s.need.minutes), if (s.need.isLearned) tr("Learned from nights you woke recovered") else tr("Your goal, until 5 recovered nights teach the app yours")) s.debt?.let { d -> @@ -326,22 +287,7 @@ private fun SleepSection(s: HealthInsightsRepository.Snapshot) { @Composable private fun StressSection(s: HealthInsightsRepository.Snapshot, onBreathe: () -> Unit) { val context = LocalContext.current - Section(tr("Stress")) { - val z = s.todayStress - if (z == null) { - Text(tr("No daytime stress readings today yet."), fontSize = 13.sp, color = PulseColors.textMuted) - } else { - Text(trf("Today: {0}", z.summary.label), fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - val total = z.totalMin.coerceAtLeast(1).toFloat() - Row(Modifier.fillMaxWidth().height(10.dp).clip(RoundedCornerShape(2.dp))) { - listOf(z.restoredMin to PulseColors.success, z.relaxedMin to PulseColors.info, - z.engagedMin to PulseColors.warning, z.stressedMin to PulseColors.danger).forEach { (m, c) -> - if (m > 0) Box(Modifier.weight(m / total).fillMaxHeight().background(c)) - } - } - Text(trf("Restored {0} · relaxed {1} · engaged {2} · stressed {3}", SleepFormat.duration(z.restoredMin), SleepFormat.duration(z.relaxedMin), SleepFormat.duration(z.engagedMin), SleepFormat.duration(z.stressedMin)), - fontSize = 12.sp, color = PulseColors.textMuted) - } + Section(tr("Stress & breathing")) { s.resilience?.let { Fact(tr("Resilience"), it.level.label, trf("Daytime recovery against stress, and how well nights restore you ({0} days)", it.daysUsed)) } val sessions = remember { MindfulSessions.all(context) } val week = sessions.filter { it.startAt >= System.currentTimeMillis() - 7 * 86_400_000L } @@ -358,34 +304,6 @@ private fun StressSection(s: HealthInsightsRepository.Snapshot, onBreathe: () -> } } -@OptIn(ExperimentalLayoutApi::class) -@Composable -private fun HeartSection(s: HealthInsightsRepository.Snapshot) { - Section(tr("Heart")) { - if (s.hrToday.size >= 2) { - Text(tr("Heart rate since last night"), fontSize = 13.sp, color = PulseColors.textSecondary) - HeartRateContextChart(s.hrToday, s.sleepWindows, s.workoutWindows) - FlowRow(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { - Legend(PulseColors.sleep, tr("Sleep")); Legend(PulseColors.steps, tr("Workout")); Legend(PulseColors.heartRate, tr("Day")) - } - } - s.cardioLoad?.let { l -> - Fact( - tr("Cardio load today"), "${l.load}" + (l.band?.let { " · ${it.label}" } ?: ""), - trf("Heart rate above your quiet waking {0} bpm, {1} min well above it", l.quietHr, l.elevatedMinutes) + - (l.usual?.let { trf(". Your usual day: {0}", it) } ?: ""), - ) - } - s.cardio?.let { c -> - Fact(tr("Cardio capacity (VO₂max)"), "%.0f · %s".format(c.vo2max, c.level.label), - if (c.fromRing) tr("Measured by your ring") else tr("Estimated from resting heart rate and age")) - // No "cardiovascular age": from a ring it would only restate resting heart rate and age - // as a number of years, which reads as far more than it is (OpenStrap Edge dropped its - // own for the same reason). - } ?: Text(tr("Add your age in Settings → User Profile for cardio capacity."), fontSize = 12.sp, color = PulseColors.textMuted) - } -} - @Composable private fun Legend(color: Color, label: String) { Row(verticalAlignment = Alignment.CenterVertically) { @@ -421,7 +339,7 @@ fun HeartRateContextChart(samples: List, sleep: List, wo } @Composable -private fun HabitsSection(h: HealthInsightsRepository.Habits) { +private fun HabitsSection(h: HealthInsightsRepository.Habits, cardio: com.pulseloop.service.CardioCapacity?) { Section(tr("Habits & routines · 30-day averages")) { h.bedtime?.let { Fact(tr("Bedtime"), it) } h.wake?.let { Fact(tr("Wake-up"), it) } @@ -429,6 +347,13 @@ private fun HabitsSection(h: HealthInsightsRepository.Habits) { h.steps?.let { Fact(tr("Steps"), "%,d".format(it)) } h.activeMin?.let { Fact(tr("Active minutes"), "$it min") } h.restingHr?.let { Fact(tr("Resting heart rate"), "${it.roundToInt()} bpm") } + cardio?.let { c -> + Fact(tr("Cardio capacity (VO₂max)"), "%.0f · %s".format(c.vo2max, c.level.label), + if (c.fromRing) tr("Measured by your ring") else tr("Estimated from resting heart rate and age")) + // No "cardiovascular age": from a ring it would only restate resting heart rate and age + // as a number of years, which reads as far more than it is (OpenStrap Edge dropped its + // own for the same reason). + } if (listOf(h.bedtime, h.steps, h.restingHr).all { it == null }) { Text(tr("A few more days of data and your routines show up here."), fontSize = 12.sp, color = PulseColors.textMuted) } @@ -615,8 +540,7 @@ private const val INHALE_MS = 4_000L /** The way into [MyHealthScreen] from Vitals: one row, with Rest Mode shown while it is on. */ @Composable fun MyHealthEntryCard(onClick: () -> Unit) { - val context = LocalContext.current - val restUntil = remember { RestMode.until(context) } + // Rest Mode has its own line on Today now, so this row only says what is behind it. Row( Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) .clickable(onClick = onClick).padding(16.dp), @@ -624,11 +548,7 @@ fun MyHealthEntryCard(onClick: () -> Unit) { ) { Column(Modifier.weight(1f)) { Text(tr("My Health & Trends"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text( - if (restUntil != null) trf("Rest Mode on until {0}", restUntil.dayOfWeek.getDisplayName(java.time.format.TextStyle.SHORT, java.util.Locale.getDefault())) - else tr("Symptom radar, sleep debt, stress, body clock, cardio capacity"), - fontSize = 12.sp, color = if (restUntil != null) PulseColors.accent else PulseColors.textMuted, - ) + Text(tr("How your last months went: health areas, trends and habits"), fontSize = 12.sp, color = PulseColors.textMuted) } Text("›", fontSize = 22.sp, color = PulseColors.textMuted) } @@ -637,7 +557,7 @@ fun MyHealthEntryCard(onClick: () -> Unit) { /** Ring steps against the phone's own counter, with the option to show calibrated steps on Today. */ @Composable -private fun StepCalibrationCard(db: PulseLoopDatabase) { +internal fun StepCalibrationCard(db: PulseLoopDatabase) { val context = LocalContext.current var granted by remember { mutableStateOf(com.pulseloop.service.StepCalibration.hasPermission(context)) } var applied by remember { mutableStateOf(com.pulseloop.service.StepCalibration.isApplied(context)) } @@ -691,3 +611,33 @@ private fun StepCalibrationCard(db: PulseLoopDatabase) { } } } + +/** Sleep need, debt and body clock, under last night on the Sleep tab. Nothing until loaded. */ +@Composable +fun SleepBalanceCard() { + val context = LocalContext.current + val db = remember { PulseLoopDatabase.getInstance(context) } + val balance by produceState(null) { + value = runCatching { HealthInsightsRepository.sleepBalance(db) }.getOrNull() + } + balance?.let { SleepBalanceSection(it) } +} + +/** Today's cardio load on the Activity tab; nothing until there are enough days of heart rate. */ +@Composable +fun CardioLoadCard(refreshKey: Any?) { + val context = LocalContext.current + val db = remember { PulseLoopDatabase.getInstance(context) } + val load by produceState(null, refreshKey) { + value = runCatching { HealthInsightsRepository.cardioLoadToday(db) }.getOrNull() ?: value + } + load?.let { l -> + Section(tr("Cardio load today")) { + Fact( + tr("Cardio load"), "${l.load}" + (l.band?.let { " · ${it.label}" } ?: ""), + trf("Heart rate above your quiet waking {0} bpm, {1} min well above it", l.quietHr, l.elevatedMinutes) + + (l.usual?.let { trf(". Your usual day: {0}", it) } ?: ""), + ) + } + } +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt index eb092200..136e92ad 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt @@ -173,6 +173,49 @@ fun NutritionScreen( } } + // Logging is why people open this screen, so its buttons sit under the day's total, + // not below every meal of the day. + // AI log actions (iOS logActions, NutritionView.swift:114-125): Photo opens the + // analysis sheet in camera mode, Describe in describe mode. + if (coachEnabled) { + item { + // Half-width buttons: tighter padding and up to two lines for a long translation, + // equal heights so a wrapped label doesn't leave the pair misaligned. + Row(Modifier.fillMaxWidth().height(IntrinsicSize.Min), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedButton( + onClick = { analysisRequest = AnalysisRequest(startWithCamera = true) }, + modifier = Modifier.weight(1f).fillMaxHeight(), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + ) { + Icon(Icons.Filled.PhotoCamera, null, Modifier.size(18.dp)) + Spacer(Modifier.width(6.dp)) + Text(tr("Photo"), maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center) + } + OutlinedButton( + onClick = { analysisRequest = AnalysisRequest(startWithCamera = false) }, + modifier = Modifier.weight(1f).fillMaxHeight(), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + ) { + Icon(Icons.Filled.AutoAwesome, null, Modifier.size(18.dp)) + Spacer(Modifier.width(6.dp)) + Text(tr("Describe"), maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center) + } + } + } + } + + // Add button + item { + OutlinedButton( + onClick = { showAddDialog = true }, + modifier = Modifier.fillMaxWidth(), + ) { + Icon(Icons.Filled.Add, null, Modifier.size(18.dp)) + Spacer(Modifier.width(6.dp)) + Text(tr("Log Meal")) + } + } + // Next-meal idea, once a third of the day's target is eaten (today only). val eatenToday = totals.sumOf { it.totalCal } val targetToday = goal?.intakeCalories ?: 2000.0 @@ -218,7 +261,7 @@ fun NutritionScreen( val typeMeals = meals.filter { it.mealTypeRaw == type } if (typeMeals.isNotEmpty()) { item { - Text(type.replaceFirstChar { it.uppercase() }, fontWeight = FontWeight.SemiBold, fontSize = 14.sp, color = PulseColors.textSecondary) + Text(tr(type.replaceFirstChar { it.uppercase() }), fontWeight = FontWeight.SemiBold, fontSize = 14.sp, color = PulseColors.textSecondary) } items(typeMeals, key = { it.id }) { meal -> Card(Modifier.fillMaxWidth(), shape = RoundedCornerShape(8.dp), colors = CardDefaults.cardColors(containerColor = PulseColors.card)) { @@ -236,46 +279,6 @@ fun NutritionScreen( } } - // AI log actions (iOS logActions, NutritionView.swift:114-125): Photo opens the - // analysis sheet in camera mode, Describe in describe mode. - if (coachEnabled) { - item { - // Half-width buttons: tighter padding and up to two lines for a long translation, - // equal heights so a wrapped label doesn't leave the pair misaligned. - Row(Modifier.fillMaxWidth().height(IntrinsicSize.Min), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - OutlinedButton( - onClick = { analysisRequest = AnalysisRequest(startWithCamera = true) }, - modifier = Modifier.weight(1f).fillMaxHeight(), - contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), - ) { - Icon(Icons.Filled.PhotoCamera, null, Modifier.size(18.dp)) - Spacer(Modifier.width(6.dp)) - Text(tr("Photo"), maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center) - } - OutlinedButton( - onClick = { analysisRequest = AnalysisRequest(startWithCamera = false) }, - modifier = Modifier.weight(1f).fillMaxHeight(), - contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), - ) { - Icon(Icons.Filled.AutoAwesome, null, Modifier.size(18.dp)) - Spacer(Modifier.width(6.dp)) - Text(tr("Describe"), maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center) - } - } - } - } - - // Add button - item { - OutlinedButton( - onClick = { showAddDialog = true }, - modifier = Modifier.fillMaxWidth(), - ) { - Icon(Icons.Filled.Add, null, Modifier.size(18.dp)) - Spacer(Modifier.width(6.dp)) - Text(tr("Log Meal")) - } - } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/PostpartumUi.kt b/app/src/main/java/com/pulseloop/ui/screens/PostpartumUi.kt index e50b9488..2cbbae7f 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/PostpartumUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/PostpartumUi.kt @@ -12,6 +12,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Edit import androidx.compose.material3.Button import androidx.compose.material3.DatePicker import androidx.compose.material3.DatePickerDialog @@ -229,6 +230,10 @@ fun PostpartumScreen(onBack: () -> Unit, onOpenProfile: () -> Unit) { Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) } Text(tr("Postpartum"), modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) + // Birth date and feeding live in Profile → Life stage; one tap from here to change them. + IconButton(onClick = onOpenProfile, modifier = Modifier.align(Alignment.CenterEnd)) { + Icon(Icons.Filled.Edit, tr("Edit life stage"), tint = PulseColors.textSecondary) + } } Column( Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), @@ -273,6 +278,29 @@ fun PostpartumScreen(onBack: () -> Unit, onOpenProfile: () -> Unit) { } } + // Ordered by urgency, not by topic: what she may need right now first (alcohol, a + // check-in that is due or a worrying last score, warning signs and help), then how + // recovery is going, then reading for later. + // Mood check-in: the EPDS, the validated questionnaire. Answers stay on this phone. + val moodCard: @Composable () -> Unit = { Card { + Text(tr("MOOD CHECK-IN"), fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + val last = history.lastOrNull() + if (last != null) { + Text(trf("Last check-in {0}: score {1} of 30", last.date, last.score), fontSize = 14.sp, color = PulseColors.textPrimary) + EpdsGuidance(last.score, last.selfHarm) + } else { + Text(tr("Ten quick questions about the last 7 days, used by health services worldwide to spot postpartum depression early."), fontSize = 13.sp, color = PulseColors.textSecondary) + } + Postpartum.nextCheckIn(birth, today, history)?.let { next -> + Text(trf("Suggested next check-in: {0}", next.format(DateTimeFormatter.ofPattern("d MMM"))), fontSize = 12.sp, color = PulseColors.textMuted) + } + Button(onClick = { checkIn = true }) { Text(tr("Start check-in")) } + Text(tr("Your answers stay on this phone. They aren't in backups, diagnostics or Health Connect."), fontSize = 11.sp, color = PulseColors.textMuted) + } } + val lastEpds = history.lastOrNull() + val moodUrgent = Postpartum.nextCheckIn(birth, today, history)?.let { !it.minusDays(7).isAfter(today) } == true || + (lastEpds != null && (lastEpds.score >= 10 || lastEpds.selfHarm > 0)) + if (moodUrgent) moodCard() d?.lastNight?.let { n -> Card { Text(tr("LAST NIGHT"), fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) @@ -287,10 +315,12 @@ fun PostpartumScreen(onBack: () -> Unit, onOpenProfile: () -> Unit) { } } + WarningSignsCard() + ResourcesCard(context) if (d != null && (d.restingHr.isNotEmpty() || d.hrv.isNotEmpty())) { Card { Text(tr("RECOVERY, WEEK BY WEEK"), fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) - val weeksShown = (d.restingHr.map { it.first } + d.hrv.map { it.first }).distinct().sorted().takeLast(8) + val weeksShown = (d.restingHr.map { it.first } + d.hrv.map { it.first }).distinct().sorted().takeLast(4) weeksShown.forEach { w -> val rhr = d.restingHr.firstOrNull { it.first == w }?.second val hrv = d.hrv.firstOrNull { it.first == w }?.second @@ -306,21 +336,15 @@ fun PostpartumScreen(onBack: () -> Unit, onOpenProfile: () -> Unit) { } } - // Mood check-in: the EPDS, the validated questionnaire. Answers stay on this phone. + if (!moodUrgent) moodCard() Card { - Text(tr("MOOD CHECK-IN"), fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) - val last = history.lastOrNull() - if (last != null) { - Text(trf("Last check-in {0}: score {1} of 30", last.date, last.score), fontSize = 14.sp, color = PulseColors.textPrimary) - EpdsGuidance(last.score, last.selfHarm) - } else { - Text(tr("Ten quick questions about the last 7 days, used by health services worldwide to spot postpartum depression early."), fontSize = 13.sp, color = PulseColors.textSecondary) - } - Postpartum.nextCheckIn(birth, today, history)?.let { next -> - Text(trf("Suggested next check-in: {0}", next.format(DateTimeFormatter.ofPattern("d MMM"))), fontSize = 12.sp, color = PulseColors.textMuted) - } - Button(onClick = { checkIn = true }) { Text(tr("Start check-in")) } - Text(tr("Your answers stay on this phone. They aren't in backups, diagnostics or Health Connect."), fontSize = 11.sp, color = PulseColors.textMuted) + Text(tr("NUTRITION"), fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + val bonus = Postpartum.calorieBonus(birth, today, Postpartum.feeding) + if (bonus > 0) Text(trf("Breastfeeding uses about {0} kcal a day more; your intake goal includes it.", bonus), fontSize = 13.sp, color = PulseColors.textPrimary) + Text( + tr("Drink to thirst and keep water where you feed. Ask your clinician about iodine, DHA and your baby's vitamin D. This is no time for a diet."), + fontSize = 12.sp, color = PulseColors.textSecondary, + ) } d?.lam?.let { lam -> @@ -338,18 +362,6 @@ fun PostpartumScreen(onBack: () -> Unit, onOpenProfile: () -> Unit) { } } - Card { - Text(tr("NUTRITION"), fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) - val bonus = Postpartum.calorieBonus(birth, today, Postpartum.feeding) - if (bonus > 0) Text(trf("Breastfeeding uses about {0} kcal a day more; your intake goal includes it.", bonus), fontSize = 13.sp, color = PulseColors.textPrimary) - Text( - tr("Drink to thirst and keep water where you feed. Ask your clinician about iodine, DHA and your baby's vitamin D. This is no time for a diet."), - fontSize = 12.sp, color = PulseColors.textSecondary, - ) - } - - WarningSignsCard() - ResourcesCard(context) Text( tr("PulseLoop doesn't detect mastitis, fever, depression, preeclampsia, milk supply or returning fertility. The ring's numbers are context, not a diagnosis."), fontSize = 11.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 dc9fe0be..8f2ae146 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/Screens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/Screens.kt @@ -293,7 +293,9 @@ fun VitalsScreen( Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text(tr("Vitals"), style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold) - Text(tr("Live measurements and trends"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + // The answer first: is anything outside this person's usual range? The + // cards below are the detail. + VitalsStatusLine() state.adjustedNote?.let { AdjustedCaption(it) } } // Measure button: combined (0x23) for 56ff/Jring, or sequential live @@ -372,100 +374,64 @@ fun VitalsScreen( // On-demand HRV / stress / temperature, one control each (issue #66's rule). val spotVitals = coordinator.measurableSpotVitals if (separateLegs) { - // Stacked, not side by side: this sits in the header Row beside the title, - // so a second Row here would be laid out horizontally and crush the title. - // Bounded, with each group wrapping: the buttons are measured before the - // weighted title, so three or four unbounded buttons ("PA e HRV", a running - // "SpO₂ 45s") squeezed "Sinais vitais" to a letter or two per line. - Column( - Modifier.widthIn(max = 208.dp), - horizontalAlignment = Alignment.End, - verticalArrangement = Arrangement.spacedBy(8.dp), + // One "Measure" button opening a list, instead of up to six buttons beside the + // title: they were measured before the weighted title and crushed it. + data class Option(val label: String, val title: String, val run: () -> Unit) + val options = buildList { + add(Option("HR", tr("Heart rate")) { + runMeasurement( + coordinator.heartRateMeasureSeconds, "HR", + caption = tr("Keep still — measuring heart rate…"), + failed = { coordinator.hrState == failedState }, + ) { coordinator.measureHeartRateOnly() } + }) + add(Option(tr("SpO₂"), tr("Blood oxygen")) { + runMeasurement( + coordinator.spo2OnlyMeasureSeconds, tr("SpO₂"), + caption = tr("Keep still — measuring blood oxygen…"), + failed = { coordinator.spo2State == failedState }, + ) { coordinator.measureSpO2Only() } + }) + if (remainingLegsLabel != null) add(Option(remainingLegsLabel, remainingLegsLabel) { + runMeasurement( + coordinator.remainingLegsMeasureSeconds, remainingLegsLabel, + caption = trf("Keep still — measuring {0}…", remainingLegsLabel), + failed = { + (coordinator.canMeasureBloodPressure && + coordinator.bloodPressureState == failedState) || + (coordinator.canMeasureHrv && coordinator.hrvState == failedState) + }, + ) { coordinator.measureRemainingLegs() } + }) + spotVitals.forEach { vital -> + add(Option(vital.label, tr(vital.description.replaceFirstChar { it.uppercase() })) { + runMeasurement( + coordinator.spotVitalMeasureSeconds, vital.label, + caption = trf("Keep still — measuring {0}…", vital.description), + failed = { coordinator.vitalState(vital) == failedState }, + ) { coordinator.measureVitalOnly(vital) } + }) + } + } + var pickOpen by remember { mutableStateOf(false) } + Button( + enabled = !measuring, + modifier = Modifier.widthIn(max = 160.dp), + onClick = { pickOpen = true }, ) { - FlowRow( - horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Button( - enabled = !measuring, - onClick = { - runMeasurement( - coordinator.heartRateMeasureSeconds, "HR", - caption = tr("Keep still — measuring heart rate…"), - failed = { coordinator.hrState == failedState }, - ) { coordinator.measureHeartRateOnly() } - }, - ) { - Text( - if (measuring && measuringLabel == "HR") "HR ${remaining}s" else "HR", - color = androidx.compose.ui.graphics.Color.Unspecified, - ) - } - Button( - enabled = !measuring, - onClick = { - runMeasurement( - coordinator.spo2OnlyMeasureSeconds, tr("SpO₂"), - caption = tr("Keep still — measuring blood oxygen…"), - failed = { coordinator.spo2State == failedState }, - ) { coordinator.measureSpO2Only() } - }, - ) { - Text( - if (measuring && measuringLabel == "SpO₂") "SpO₂ ${remaining}s" else tr("SpO₂"), - color = androidx.compose.ui.graphics.Color.Unspecified, - ) - } - if (remainingLegsLabel != null) { - Button( - enabled = !measuring, - onClick = { - runMeasurement( - coordinator.remainingLegsMeasureSeconds, remainingLegsLabel, - caption = trf("Keep still — measuring {0}…", remainingLegsLabel), - failed = { - (coordinator.canMeasureBloodPressure && - coordinator.bloodPressureState == failedState) || - (coordinator.canMeasureHrv && coordinator.hrvState == failedState) - }, - ) { coordinator.measureRemainingLegs() } - }, - ) { - Text( - if (measuring && measuringLabel == remainingLegsLabel) - "$remainingLegsLabel ${remaining}s" else remainingLegsLabel, - color = androidx.compose.ui.graphics.Color.Unspecified, - ) - } - } - } - if (spotVitals.isNotEmpty()) { - FlowRow( - horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - for (vital in spotVitals) { - val label = vital.label - Button( - enabled = !measuring, - // Three to a row beside the title: tighter than the default 24 dp. - contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), - onClick = { - runMeasurement( - coordinator.spotVitalMeasureSeconds, label, - caption = trf("Keep still — measuring {0}…", vital.description), - failed = { coordinator.vitalState(vital) == failedState }, - ) { coordinator.measureVitalOnly(vital) } - }, - ) { - Text( - if (measuring && measuringLabel == label) "$label ${remaining}s" else label, - color = androidx.compose.ui.graphics.Color.Unspecified, - ) - } - } - } - } + Text( + if (measuring) "$measuringLabel ${remaining}s" else tr("Measure"), + color = androidx.compose.ui.graphics.Color.Unspecified, + maxLines = 1, + overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, + ) + } + if (pickOpen) MeasurePickerSheet( + titles = options.map { it.title }, + onDismiss = { pickOpen = false }, + ) { index -> + pickOpen = false + options[index].run() } } else { Button( @@ -536,9 +502,6 @@ fun VitalsScreen( Spacer(Modifier.height(8.dp)) } - if (navController != null) { - item { MyHealthEntryCard { navController.navigate("my_health") } } - } // Card order mirrors VitalsView.swift (HR, SpO₂, BP, HRV, Stress, Fatigue, Glucose, Temp) // by default, but honors the user's per-metric visibility + order (iOS #64). Long-press a @@ -1329,3 +1292,48 @@ private fun displayThresholds( ) } + +/** What to measure, one row each; the measurement runs once a row is picked. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun MeasurePickerSheet(titles: List, onDismiss: () -> Unit, onPick: (Int) -> Unit) { + ModalBottomSheet( + onDismissRequest = onDismiss, + sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), + containerColor = PulseColors.secondaryBackground, + ) { + Column( + Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(bottom = 32.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text(tr("Measure"), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(tr("Keep the ring snug and your hand still until it finishes."), fontSize = 13.sp, color = PulseColors.textSecondary) + titles.forEachIndexed { i, t -> + SheetOption(t, tr("Tap to start"), Icons.Filled.MonitorHeart) { onPick(i) } + } + } + } +} + +/** + * One line under the Vitals title: last night against this person's usual range. Holds its line + * while loading so the cards below don't shift when it lands. + */ +@Composable +private fun VitalsStatusLine() { + val context = androidx.compose.ui.platform.LocalContext.current + val db = remember { com.pulseloop.data.PulseLoopDatabase.getInstance(context) } + val guidance = rememberGuidance(db, Unit) + val off = guidance?.offSignals + Text( + when { + off == null -> " " + off.isEmpty() -> tr("Last night: all within your usual range") + else -> trf("Outside your usual last night: {0}", off.joinToString(", ") { it.title.lowercase() }) + }, + style = MaterialTheme.typography.bodySmall, + color = if (off.isNullOrEmpty()) MaterialTheme.colorScheme.onSurfaceVariant else PulseColors.warning, + maxLines = 2, + overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, + ) +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt index b92cfa82..4d4dfe36 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt @@ -1143,7 +1143,7 @@ private fun DailyGuidanceSettingsCard() { ) { progress = it; prefs.activityProgress = it } GuidanceSwitch( tr("Medication reminders"), - tr("Once per dose, at its time, for what you add in My Health → Medications & supplements."), + tr("Once per dose, at its time, for what you add with + Log → Medication or supplement."), medsOn, ) { medsOn = it; prefs.medReminders = it } } 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 5fd30839..9092b7a1 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt @@ -159,6 +159,9 @@ private fun androidx.compose.foundation.lazy.LazyListScope.dayItems( else -> item { SleepCarousel(sessions, state.dayBlocks, viewModel, state.goalMinutes) } } + // Need, debt and body clock describe now, not the night being browsed, so only on today. + if (state.dayOffset == 0) item { SleepBalanceCard() } + item { val summary = state.daySummary val fallback = state.coach 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 3e42df93..2cc2e3ac 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt @@ -395,6 +395,11 @@ 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") } } + } + item { Spacer(Modifier.height(64.dp)) } }