diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index c1d72a6a..e0dd93fc 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -23,6 +23,8 @@ "%,d steps": "%,d passos", "%,d steps a day": "%,d passos por dia", "%,d steps yesterday vs your usual %,d": "%,d passos ontem vs. seus habituais %,d", + "+ Log meal": "+ Registrar refeição", + "+ Record Activity": "+ Registrar atividade", "+%.1f °C from your usual": "+%.1f °C acima do seu habitual", "+%.1f °C last night against your usual. Can come with illness, a late workout, alcohol or the menstrual cycle.": "+%.1f °C na noite passada em relação ao seu habitual. Pode acompanhar doença, treino tarde, álcool ou o ciclo menstrual.", ", about {0} kcal. Can we look at alternatives?": ", cerca de {0} kcal. Podemos ver alternativas?", @@ -273,6 +275,7 @@ "CAPS AD": "CAPS AD", "CDC suggests waiting at least 2 hours per standard drink before breastfeeding. It's an estimate: bodies differ, and pumping and dumping doesn't make it faster. Not drinking is the safest choice.": "O CDC sugere esperar pelo menos 2 horas por dose padrão antes de amamentar. É uma estimativa: cada corpo é diferente, e tirar o leite e descartar não acelera nada. Não beber é a escolha mais segura.", "CDC suggests waiting at least 2 hours per standard drink before feeding. It's an estimate: bodies differ, and pumping and dumping doesn't make it faster. Not drinking is the safest choice.": "O CDC sugere esperar pelo menos 2 horas por dose padrão antes de amamentar. É uma estimativa: cada corpo é diferente, e tirar o leite e descartar não acelera nada. Não beber é a escolha mais segura.", + "COACH": "COACH", "CVV (emotional support, 24 h)": "CVV (apoio emocional, 24 h)", "CVV listens 24 hours a day, free and anonymous. In danger now, call SAMU.": "O CVV escuta 24 horas por dia, de graça e com sigilo. Se houver perigo agora, ligue para o SAMU.", "CVV · 188": "CVV · 188", @@ -384,6 +387,7 @@ "Cycling": "Ciclismo", "DATA SOURCE": "FONTE DE DADOS", "DETECTED · REVIEW": "DETECTADO · REVISAR", + "Daily": "Diário", "Daily AI-generated health insights based on your ring data": "Insights de saúde diários gerados por IA com base nos dados do seu anel", "Daily Check-in Notifications": "Notificações de check-in diário", "Daily Goals": "Metas diárias", @@ -472,6 +476,8 @@ "Duration held the score back": "A duração limitou a pontuação", "Duration must be greater than zero.": "A duração deve ser maior que zero.", "During the check, {0} wrote the same types to Health Connect. Exporting the ring's copy of those days now would count them twice.": "Durante a verificação, {0} gravou os mesmos tipos no Health Connect. Exportar agora a cópia do anel desses dias contaria tudo duas vezes.", + "EARLIER": "ANTERIORES", + "ESTIMATED": "ESTIMADO", "Each night is compared with your own previous four weeks once there are two weeks to compare with. ": "Cada noite é comparada com suas próprias quatro semanas anteriores assim que houver duas semanas para comparar. ", "Early bird": "Matutino", "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.", @@ -545,6 +551,7 @@ "Exporting all history can take a while on the first run.": "Exportar todo o histórico pode demorar um pouco na primeira vez.", "Exporting…": "Exportando…", "Extreme swelling of your hands or face": "Inchaço intenso nas mãos ou no rosto", + "FOOD": "ALIMENTAÇÃO", "Factory Reset Ring": "Restaurar anel de fábrica", "Factory reset erases all data stored on the ring itself and resets it to factory state. Your synced data in the app is kept.": "A restauração de fábrica apaga todos os dados armazenados no próprio anel e o retorna ao estado de fábrica. Seus dados sincronizados no app são mantidos.", "Factory reset ring?": "Restaurar anel de fábrica?", @@ -619,6 +626,7 @@ "Grounds suggestions in your city's current weather": "Baseia as sugestões no clima atual da sua cidade", "Gym": "Academia", "HELP": "AJUDA", + "HISTORY": "HISTÓRICO", "HR collected": "HR coletada", "HR pending": "HR pendente", "HR, SpO₂, HRV & stress": "HR, SpO₂, HRV e estresse", @@ -744,6 +752,7 @@ "Last 8 weeks": "Últimas 8 semanas", "Last Sleep": "Último sono", "Last check-in {0}: score {1} of 30": "Último check-in {0}: pontuação {1} de 30", + "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: {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ê.", @@ -1029,6 +1038,7 @@ "Overwhelming tiredness": "Cansaço extremo", "Ovos mexidos": "Ovos mexidos", "Own your ring data": "Seus dados do anel são seus", + "PAUSED": "PAUSADO", "Pace": "Ritmo", "Pair a ring to configure its all-day measurements.": "Pareie um anel para configurar as medições contínuas.", "Pair your ring first.": "Pareie seu anel primeiro.", @@ -1103,6 +1113,7 @@ "Quiet from": "Silêncio a partir de", "Quiet hours schedule:": "Horário de silêncio:", "Quiet until": "Silêncio até", + "READINGS": "LEITURAS", "RECOVERY, WEEK BY WEEK": "RECUPERAÇÃO, SEMANA A SEMANA", "REFERENCE ZONES": "ZONAS DE REFERÊNCIA", "REM sleep": "Sono REM", @@ -1195,6 +1206,7 @@ "Row counts include demo and real rows. Tap a table to see its newest rows. Stored health rows are never included in a diagnostics export.": "As contagens incluem linhas de demonstração e reais. Toque numa tabela para ver as linhas mais recentes. Dados de saúde armazenados nunca entram numa exportação de diagnóstico.", "Running": "Corrida", "SAMU (emergencies)": "SAMU (emergências)", + "SCORE": "PONTUAÇÃO", "Salada verde com tomate": "Salada verde com tomate", "Same as heart rate": "Igual à frequência cardíaca", "Save": "Salvar", @@ -1388,6 +1400,7 @@ "System default": "Padrão do sistema", "Systolic": "Sistólica", "TAP TO EDIT GOALS": "TOQUE PARA EDITAR AS METAS", + "TODAY": "HOJE", "TODAY'S BRIEF": "RESUMO DE HOJE", "Tag day": "Marcar dia", "Tag yesterday": "Marcar ontem", @@ -1475,6 +1488,7 @@ "Total sleep": "Sono total", "Total workout time this week. Health guidelines suggest at least 150 minutes of moderate activity a week.": "Tempo total de treino nesta semana. As diretrizes de saúde sugerem pelo menos 150 minutos de atividade moderada por semana.", "Track Bedtime / DND mode": "Monitorar modo Hora de dormir / Não perturbe", + "Track GPS route": "Rastrear rota por GPS", "Track more nights this month to see a monthly average.": "Registre mais noites este mês para ver uma média mensal.", "Tracked {0} {1} this year": "Este ano você registrou {0} {1}", "Trails and elevation": "Trilhas e elevação", @@ -1609,6 +1623,7 @@ "Workouts": "Treinos", "Workouts / week": "Treinos / semana", "Write Actions": "Ações de escrita", + "YESTERDAY": "ONTEM", "YOUR GOAL": "SUA META", "Year": "Ano", "Yearly Sleep": "Sono anual", @@ -1691,6 +1706,7 @@ "higher": "maior", "hour": "hora", "hours": "horas", + "kcal eaten": "kcal ingeridas", "kg": "kg", "lb": "lb", "less": "menos", @@ -1700,6 +1716,8 @@ "nights": "noites", "no overlap": "sem sobreposição", "not chosen": "não escolhido", + "nothing logged yet": "nada registrado ainda", + "of {0}": "de {0}", "of {0} this week": "de {0} esta semana", "resting HR {0}{1}": "HR em repouso {0}{1}", "resting heart rate {0} bpm {1}": "frequência cardíaca em repouso {0} bpm {1}", @@ -1798,4 +1816,4 @@ "±{0}m · {1} pts": "±{0}m · {1} pts", "−%.1f °C from your usual": "−%.1f °C em relação ao seu habitual", "≈ {0} kcal · {1} g protein · leaves {2} kcal": "≈ {0} kcal · {1} g de proteína · sobram {2} kcal" -} \ No newline at end of file +} diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index b00d86d1..38308e84 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -23,7 +23,9 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.ViewModel @@ -529,7 +531,18 @@ fun PulseLoopApp() { contentDescription = null, ) }, - label = { Text(tab.label) }, + // One line, a touch smaller than labelMedium: "Sinais vitais" wrapped to two + // lines and pushed its icon up out of line with the others. Items already + // share the width equally (NavigationBarItem weights itself 1f). + label = { + Text( + tab.label, + fontSize = 11.sp, + maxLines = 1, + softWrap = false, + overflow = TextOverflow.Ellipsis, + ) + }, selected = selected, onClick = { onTab(tab) }, colors = NavigationBarItemDefaults.colors( 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 20a952e9..9d863a85 100644 --- a/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt +++ b/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt @@ -81,7 +81,9 @@ fun AppHeader( batteryPercent = batteryPercent, idle = idle, sourceLabel = sourceLabel, - modifier = Modifier.clickable( + // Bounded: the pill is measured before the weighted greeting, so an unbounded + // "Falha na sincronização" or "Oura · Health Connect" squeezed the greeting to nothing. + modifier = Modifier.widthIn(max = 168.dp).clickable( onClickLabel = tr("Open ring settings"), role = Role.Button, onClick = onOpenSettings, @@ -157,6 +159,7 @@ fun ConnectionStatusPill( fontWeight = FontWeight.Medium, color = PulseColors.textSecondary, maxLines = 1, + overflow = TextOverflow.Ellipsis, ) } } @@ -192,15 +195,19 @@ fun CardEyebrow( .clip(CircleShape) .background(dotColor), ) + // The label takes the free width (instead of a Spacer) so a long translated label wraps + // rather than pushing the trailing slot off the card; the slot is bounded for the same reason. Text( label.uppercase(), fontSize = 11.sp, fontWeight = FontWeight.Medium, letterSpacing = 1.sp, color = PulseColors.textSecondary, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), ) - Spacer(Modifier.weight(1f)) - trailing?.invoke() + trailing?.let { Box(Modifier.widthIn(max = 180.dp)) { it() } } } } @@ -214,8 +221,9 @@ fun SectionHeaderCaps(title: String, modifier: Modifier = Modifier, action: (@Co fontWeight = FontWeight.SemiBold, letterSpacing = 0.8.sp, color = PulseColors.textSecondary, + // Takes the free width (instead of a Spacer) so a long title wraps beside the action. + modifier = Modifier.weight(1f), ) - Spacer(Modifier.weight(1f)) action?.invoke() } } diff --git a/app/src/main/java/com/pulseloop/ui/components/DeviceHeroCard.kt b/app/src/main/java/com/pulseloop/ui/components/DeviceHeroCard.kt index c46b4930..aad1c672 100644 --- a/app/src/main/java/com/pulseloop/ui/components/DeviceHeroCard.kt +++ b/app/src/main/java/com/pulseloop/ui/components/DeviceHeroCard.kt @@ -108,6 +108,7 @@ fun DeviceHeroCard( fontSize = 13.sp, color = status.statusTint, maxLines = 1, + overflow = TextOverflow.Ellipsis, ) status.syncText?.let { syncText -> Text( @@ -115,6 +116,7 @@ fun DeviceHeroCard( fontSize = 12.sp, color = PulseColors.textSecondary, maxLines = 1, + overflow = TextOverflow.Ellipsis, ) } } diff --git a/app/src/main/java/com/pulseloop/ui/components/FairyTransform.kt b/app/src/main/java/com/pulseloop/ui/components/FairyTransform.kt index 1abc4e08..fd3b5cf4 100644 --- a/app/src/main/java/com/pulseloop/ui/components/FairyTransform.kt +++ b/app/src/main/java/com/pulseloop/ui/components/FairyTransform.kt @@ -9,6 +9,7 @@ import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect @@ -26,6 +27,7 @@ import androidx.compose.ui.graphics.drawscope.rotate import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.pulseloop.ui.theme.FairyMode import kotlin.math.PI @@ -87,7 +89,8 @@ fun FairyTransformOverlay() { } val textIn = ((p - 0.42f) / 0.18f).coerceIn(0f, 1f) Column( - Modifier.alpha(textIn * veil).scale(0.7f + 0.3f * textIn), + // Side margin so a longer translation wraps short of the screen edge. + Modifier.padding(horizontal = 24.dp).alpha(textIn * veil).scale(0.7f + 0.3f * textIn), horizontalAlignment = Alignment.CenterHorizontally, ) { Text( diff --git a/app/src/main/java/com/pulseloop/ui/components/PairingComponents.kt b/app/src/main/java/com/pulseloop/ui/components/PairingComponents.kt index 2a105d75..716268a7 100644 --- a/app/src/main/java/com/pulseloop/ui/components/PairingComponents.kt +++ b/app/src/main/java/com/pulseloop/ui/components/PairingComponents.kt @@ -62,7 +62,8 @@ fun PrimaryButton( Icon(icon, contentDescription = null, Modifier.size(18.dp)) Spacer(Modifier.width(8.dp)) } - Text(title, fontSize = 16.sp, fontWeight = FontWeight.SemiBold) + // Centered: a long translated title wraps to two lines inside the full-width button. + Text(title, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, textAlign = TextAlign.Center) } } @@ -92,7 +93,8 @@ fun SecondaryButton( Icon(icon, contentDescription = null, Modifier.size(18.dp), tint = PulseColors.textSecondary) Spacer(Modifier.width(8.dp)) } - Text(title, fontSize = 16.sp, fontWeight = FontWeight.SemiBold) + // Centered: a long translated title wraps to two lines inside the full-width button. + Text(title, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, textAlign = TextAlign.Center) } } diff --git a/app/src/main/java/com/pulseloop/ui/components/SettingsComponents.kt b/app/src/main/java/com/pulseloop/ui/components/SettingsComponents.kt index f9562fe9..25243b3b 100644 --- a/app/src/main/java/com/pulseloop/ui/components/SettingsComponents.kt +++ b/app/src/main/java/com/pulseloop/ui/components/SettingsComponents.kt @@ -10,9 +10,9 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape @@ -112,14 +112,15 @@ fun SettingsRow(item: SettingsRowItem) { Icon(item.icon, contentDescription = null, Modifier.size(18.dp), tint = item.tint) } + // The title takes the free width (it used to be unweighted beside a weighted Spacer, so a + // long translated title and a long trailing value — a model slug — fought for the row). Text( item.title, fontSize = 16.sp, color = PulseColors.textPrimary, + modifier = Modifier.weight(1f), ) - Spacer(Modifier.weight(1f)) - item.trailingValue?.let { trailing -> Text( trailing, @@ -127,6 +128,7 @@ fun SettingsRow(item: SettingsRowItem) { color = PulseColors.textSecondary, maxLines = 1, overflow = TextOverflow.Ellipsis, + modifier = Modifier.widthIn(max = 140.dp), ) } diff --git a/app/src/main/java/com/pulseloop/ui/components/TodayTiles.kt b/app/src/main/java/com/pulseloop/ui/components/TodayTiles.kt index c4633a87..b510ef78 100644 --- a/app/src/main/java/com/pulseloop/ui/components/TodayTiles.kt +++ b/app/src/main/java/com/pulseloop/ui/components/TodayTiles.kt @@ -364,7 +364,7 @@ fun SleepTile( color = PulseColors.textPrimary, ) Text( - "SCORE", + tr("SCORE"), fontSize = 10.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.sp, @@ -424,6 +424,7 @@ private fun ChipTone.border() = when (this) { } /** Full-width gradient hero card at the top of Today (HeroInsightCardView in Swift). */ +@OptIn(ExperimentalLayoutApi::class) @Composable fun HeroInsightCard(title: String, summary: String, chips: List, modifier: Modifier = Modifier) { val shape = RoundedCornerShape(8.dp) @@ -445,7 +446,12 @@ fun HeroInsightCard(title: String, summary: String, chips: List, modif modifier = Modifier.padding(top = 8.dp), ) if (chips.isNotEmpty()) { - Row(Modifier.padding(top = 16.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) { + // Wraps: three translated chips ("Linha de base pendente", …) overflow one line. + FlowRow( + Modifier.padding(top = 16.dp), + horizontalArrangement = Arrangement.spacedBy(6.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { chips.forEach { chip -> Text( chip.label, @@ -453,6 +459,7 @@ fun HeroInsightCard(title: String, summary: String, chips: List, modif fontWeight = FontWeight.Medium, color = chip.tone.foreground(), maxLines = 1, + overflow = TextOverflow.Ellipsis, modifier = Modifier .clip(CircleShape) .dither(chip.tone.ditherColor(), if (chip.tone == ChipTone.NEUTRAL) 0.10f else 0.15f) @@ -466,6 +473,7 @@ fun HeroInsightCard(title: String, summary: String, chips: List, modif } /** Full-width coach card (COACH eyebrow, headline, body, chips) — CoachMessageCard in Swift. */ +@OptIn(ExperimentalLayoutApi::class) @Composable fun CoachMessageCard( headline: String, @@ -493,7 +501,7 @@ fun CoachMessageCard( .background(PulseColors.accent), ) Text( - "COACH", + tr("COACH"), fontSize = 10.sp, fontWeight = FontWeight.Medium, letterSpacing = 1.8.sp, @@ -515,7 +523,12 @@ fun CoachMessageCard( modifier = Modifier.padding(top = 6.dp), ) if (chips.isNotEmpty()) { - Row(Modifier.padding(top = 10.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + // Wraps rather than ellipsising the third chip to nothing on a narrow phone. + FlowRow( + Modifier.padding(top = 10.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { chips.take(3).forEach { chip -> Text( chip, diff --git a/app/src/main/java/com/pulseloop/ui/components/VitalCard.kt b/app/src/main/java/com/pulseloop/ui/components/VitalCard.kt index aba164b9..135c2800 100644 --- a/app/src/main/java/com/pulseloop/ui/components/VitalCard.kt +++ b/app/src/main/java/com/pulseloop/ui/components/VitalCard.kt @@ -1,5 +1,6 @@ package com.pulseloop.ui.components +import com.pulseloop.ui.i18n.tr import com.pulseloop.ui.theme.dither import androidx.compose.foundation.background import androidx.compose.foundation.border @@ -8,10 +9,10 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme @@ -93,14 +94,18 @@ private fun CardHeader(state: VitalCardState, compact: Boolean, footerText: Stri .clip(CircleShape) .background(accent), ) + // The title takes the free width (instead of a Spacer) and the footer is bounded: both + // used to be unweighted, so a long translated title could squeeze the footer to nothing. Text( state.title.uppercase(), fontSize = 11.sp, fontWeight = FontWeight.Medium, letterSpacing = 1.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), ) - Spacer(Modifier.weight(1f)) // "Updated …" lives top-right so it doesn't add a footer row and grow the card height. // Suppressed when the ESTIMATED chip is present so the two don't crowd the header. if (footerText != null && !compact && !state.isEstimated) { @@ -110,6 +115,7 @@ private fun CardHeader(state: VitalCardState, compact: Boolean, footerText: Stri color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, + modifier = Modifier.widthIn(max = 160.dp), ) } if (state.isEstimated) EstimatedChip() @@ -119,7 +125,7 @@ private fun CardHeader(state: VitalCardState, compact: Boolean, footerText: Stri @Composable private fun EstimatedChip() { Text( - "ESTIMATED", + tr("ESTIMATED"), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.8.sp, @@ -161,6 +167,8 @@ private fun ValueRow(state: VitalCardState) { fontWeight = FontWeight.SemiBold, letterSpacing = 0.8.sp, color = state.statusToken.toColor(), + // Wraps beside the trend instead of pushing it off the card. + modifier = Modifier.weight(1f, fill = false), ) if (state.trend.deltaText != null) { Row(horizontalArrangement = Arrangement.spacedBy(3.dp)) { diff --git a/app/src/main/java/com/pulseloop/ui/components/VitalRingGauge.kt b/app/src/main/java/com/pulseloop/ui/components/VitalRingGauge.kt index e5033abe..75f25ddc 100644 --- a/app/src/main/java/com/pulseloop/ui/components/VitalRingGauge.kt +++ b/app/src/main/java/com/pulseloop/ui/components/VitalRingGauge.kt @@ -22,6 +22,8 @@ import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.progressBarRangeInfo import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @@ -195,6 +197,11 @@ fun VitalRingGauge( fontWeight = FontWeight.SemiBold, letterSpacing = 1.sp, color = valueColor, + // A translated zone label can outgrow the ring's hole: wrap it centred, never + // more than two lines, instead of spilling over the arc. + textAlign = TextAlign.Center, + maxLines = 2, + overflow = TextOverflow.Ellipsis, ) } if (subtitle != null) { @@ -202,6 +209,9 @@ fun VitalRingGauge( subtitle, fontSize = (size.value * 0.065f).sp, color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + maxLines = 2, + overflow = TextOverflow.Ellipsis, ) } } diff --git a/app/src/main/java/com/pulseloop/ui/onboarding/Editors.kt b/app/src/main/java/com/pulseloop/ui/onboarding/Editors.kt index ed0308ac..217f9315 100644 --- a/app/src/main/java/com/pulseloop/ui/onboarding/Editors.kt +++ b/app/src/main/java/com/pulseloop/ui/onboarding/Editors.kt @@ -49,6 +49,7 @@ import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.pulseloop.settings.UnitSystem @@ -280,6 +281,9 @@ private fun SegmentedRow( fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium, color = if (selected) PulseColors.onAccent else PulseColors.textSecondary, maxLines = 1, + // Four translated options share the width; ellipsize rather than clip mid-glyph. + overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(horizontal = 2.dp), ) } } @@ -296,17 +300,20 @@ private fun PickerRow(title: String, value: String?, onClick: () -> Unit) { verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { + // The title takes the weight (not a Spacer) so it wraps instead of being squeezed by the value. Text( title, fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, + modifier = Modifier.weight(1f), ) - Spacer(Modifier.weight(1f)) Text( value ?: tr("Not set"), fontSize = 14.sp, color = if (value == null) PulseColors.textMuted else PulseColors.textSecondary, + maxLines = 1, overflow = TextOverflow.Ellipsis, + modifier = Modifier.widthIn(max = 160.dp), ) Icon( Icons.AutoMirrored.Filled.KeyboardArrowRight, @@ -633,13 +640,14 @@ private fun GoalSliderCard( ) { Icon(icon, contentDescription = null, Modifier.size(16.dp), tint = tint) } + // Weighted title (not a Spacer): a long translated title wraps beside the value. Text( title, fontSize = 15.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, + modifier = Modifier.weight(1f), ) - Spacer(Modifier.weight(1f)) Text( label, fontSize = 16.sp, 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 ce51295e..404ae4f9 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt @@ -22,10 +22,13 @@ import com.pulseloop.health.accuracy.ExportUnit import com.pulseloop.health.accuracy.RingIdentity import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator @@ -43,6 +46,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.health.connect.client.PermissionController @@ -56,6 +60,7 @@ import com.pulseloop.health.accuracy.ReferenceSourceScanner import com.pulseloop.health.accuracy.ReferenceSourceSurvey import com.pulseloop.health.accuracy.ReferenceSurveyText import com.pulseloop.ui.theme.PulseColors +import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import java.time.Instant import java.time.ZoneId @@ -66,21 +71,28 @@ import java.time.format.DateTimeFormatter * scan Health Connect for which apps write what, how often and how late, and start a check * against one of them. With one open: its progress or the resume choice, and the report. */ +@OptIn(ExperimentalLayoutApi::class) @Composable fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { val context = LocalContext.current val scope = rememberCoroutineScope() val db = remember { PulseLoopDatabase.getInstance(context) } val available = remember { HealthConnectSdk.availability(context) == HealthConnectAvailability.AVAILABLE } - var granted by remember { mutableStateOf>(emptySet()) } + // null until Health Connect has answered, so "Allow access" doesn't flash for someone who granted it. + var granted by remember { mutableStateOf?>(null) } var scanning by remember { mutableStateOf(false) } var result by remember { mutableStateOf(null) } var note by remember { mutableStateOf(null) } var starting by remember { mutableStateOf(null) } var viewing by remember { mutableStateOf(null) } - val open by db.accuracyDao().openFlow().collectAsState(initial = null) - val history by db.accuracyDao().allFlow().collectAsState(initial = emptyList()) - val ring by db.deviceDao().currentFlow().collectAsState(initial = null) + // Optional-wrapped so "not loaded yet" (null) differs from "no open check" / "no ring" (empty): + // reading null as "none" flashed the start-a-check card over a running check, and + // "Pair your ring first" over a paired one, until Room's first emission. + val openLoad by remember(db) { db.accuracyDao().openFlow().map { java.util.Optional.ofNullable(it) } }.collectAsState(initial = null) + val open: AccuracyCheckEntity? = openLoad?.orElse(null) + val history by remember(db) { db.accuracyDao().allFlow() }.collectAsState(initial = emptyList()) + val ringLoad by remember(db) { db.deviceDao().currentFlow().map { java.util.Optional.ofNullable(it) } }.collectAsState(initial = null) + val ring: com.pulseloop.data.entity.DeviceEntity? = ringLoad?.orElse(null) val hasRing = ring?.let { it.id != RingIdentity.DEMO_DEVICE_ID } == true fun scan() { @@ -103,7 +115,7 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { runCatching { AccuracyCheckController.endIfDue(context) } runCatching { AccuracyCheckController.refreshPauseSet(context) } } - val readable = AccuracyCheckPermissions.readable(granted) + val readable = AccuracyCheckPermissions.readable(granted.orEmpty()) val launcher = rememberLauncherForActivityResult(PermissionController.createRequestPermissionResultContract()) { got -> granted = got @@ -129,7 +141,7 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { } if (current != null) AccuracyReportSection(current) - if (current == null) { + if (openLoad != null && current == null) { AccuracyCard { Text(tr("Compare your ring with another device"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text( @@ -144,8 +156,12 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { ) if (!available) { Text(tr("Health Connect isn't available on this phone."), fontSize = 12.sp, color = PulseColors.danger) - } else { - Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { + } else if (granted != null) { + // FlowRow: "Allow more" + "Scan last N days" don't fit one line once translated. + FlowRow( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { if (readable.size < ReferenceMetric.entries.size) { Button(onClick = { launcher.launch(AccuracyCheckPermissions.request) }, enabled = !scanning) { Text(if (readable.isEmpty()) tr("Allow access") else tr("Allow more")) @@ -154,10 +170,10 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { if (readable.isNotEmpty()) { OutlinedButton(onClick = { scan() }, enabled = !scanning) { Text(trf("Scan last {0} days", ReferenceSourceScanner.LOOKBACK_DAYS)) } } - if (scanning) CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) + if (scanning) CircularProgressIndicator(Modifier.size(20.dp).align(Alignment.CenterVertically), strokeWidth = 2.dp) } } - if (!hasRing) Text(tr("Pair your ring first: a check compares it against the other device."), fontSize = 12.sp, color = PulseColors.textMuted) + if (ringLoad != null && !hasRing) Text(tr("Pair your ring first: a check compares it against the other device."), fontSize = 12.sp, color = PulseColors.textMuted) note?.let { Text(it, fontSize = 12.sp, color = PulseColors.warning) } } @@ -209,7 +225,11 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { Text("${c.deviceLabel} vs ${c.referenceLabel}", fontSize = 13.sp, color = PulseColors.textPrimary) Text(AccuracyUiText.span(c), fontSize = 12.sp, color = PulseColors.textMuted) } - Text(tr("View"), fontSize = 13.sp, color = PulseColors.accent) + Text( + tr("View"), fontSize = 13.sp, color = PulseColors.accent, + maxLines = 1, overflow = TextOverflow.Ellipsis, + modifier = Modifier.widthIn(max = 96.dp), + ) } } } @@ -264,7 +284,7 @@ internal object AccuracyUiText { private fun RunningCard(check: AccuracyCheckEntity, scope: kotlinx.coroutines.CoroutineScope) { val context = LocalContext.current val db = remember { PulseLoopDatabase.getInstance(context) } - val paused by db.accuracyDao().allPausedUnitsFlow().collectAsState(initial = emptyList()) + val paused by remember(db) { db.accuracyDao().allPausedUnitsFlow() }.collectAsState(initial = emptyList()) val units = paused.filter { it.checkId == check.id }.mapNotNull { ExportUnit.byName(it.unit) } var confirmEnd by remember { mutableStateOf(false) } val (day, total) = AccuracyUiText.dayOf(check) @@ -316,6 +336,7 @@ private fun ResumeCard(check: AccuracyCheckEntity, scope: kotlinx.coroutines.Cor } } +@OptIn(ExperimentalLayoutApi::class) @Composable private fun StartDialog( context: Context, @@ -344,7 +365,8 @@ private fun StartDialog( } else null, ) Text(tr("How long"), fontSize = 13.sp, fontWeight = FontWeight.SemiBold) - Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + // Four translated "N days" chips are wider than a dialog: let them wrap. + FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) { AccuracyCheckController.DURATIONS_DAYS.forEach { d -> FilterChip(selected = days == d, onClick = { days = d }, label = { Text(trf("{0} days", d)) }) } @@ -432,7 +454,8 @@ internal fun AdjustedCaption(note: String) { internal fun rememberAccuracyCorrections(): com.pulseloop.health.accuracy.Corrections { val context = LocalContext.current val db = remember { PulseLoopDatabase.getInstance(context) } - val tick by com.pulseloop.health.accuracy.AccuracyCorrections.flow(db).collectAsState(initial = com.pulseloop.health.accuracy.Corrections.NONE) + val tick by remember(db) { com.pulseloop.health.accuracy.AccuracyCorrections.flow(db) } + .collectAsState(initial = com.pulseloop.health.accuracy.Corrections.NONE) val loaded by androidx.compose.runtime.produceState(com.pulseloop.health.accuracy.Corrections.NONE, tick) { value = com.pulseloop.health.accuracy.AccuracyCorrections.load(db) } @@ -451,6 +474,10 @@ internal fun AccuracyCheckBanner(c: AccuracyCheckEntity, onOpen: () -> Unit) { verticalAlignment = Alignment.CenterVertically, ) { Text(text, fontSize = 12.sp, color = PulseColors.warning, modifier = Modifier.weight(1f)) - Text(tr("Open"), fontSize = 12.sp, color = PulseColors.accent) + Text( + tr("Open"), fontSize = 12.sp, color = PulseColors.accent, + maxLines = 1, overflow = TextOverflow.Ellipsis, + modifier = Modifier.widthIn(max = 96.dp), + ) } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt b/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt index 03296beb..a073fda5 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt @@ -12,6 +12,7 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button @@ -34,6 +35,7 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.pulseloop.data.PulseLoopDatabase @@ -49,6 +51,7 @@ import com.pulseloop.health.accuracy.ComparisonMetric import com.pulseloop.health.accuracy.EchoCheck import com.pulseloop.health.accuracy.Stage import com.pulseloop.ui.theme.PulseColors +import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import java.time.LocalDate import java.time.format.DateTimeFormatter @@ -68,7 +71,9 @@ internal fun AccuracyReportSection( val context = LocalContext.current val scope = rememberCoroutineScope() val db = remember { PulseLoopDatabase.getInstance(context) } - val days by db.accuracyDao().daysFlow(check.id).collectAsState(initial = emptyList()) + // null until Room answers, so "Nothing to compare yet" only shows when there really is nothing. + val daysLoad by remember(db, check.id) { db.accuracyDao().daysFlow(check.id) }.collectAsState(initial = null) + val days = daysLoad.orEmpty() var scoring by remember { mutableStateOf(false) } var status by remember { mutableStateOf(null) } var expanded by remember { mutableStateOf(null) } @@ -106,9 +111,12 @@ internal fun AccuracyReportSection( if (check.state == AccuracyCheckEntity.STATE_RUNNING) tr("So far (preliminary)") else tr("Report"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary, modifier = Modifier.weight(1f), ) + // Both actions are width-bounded so translated labels can't squeeze the weighted title. if (scoring) CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp) - else TextButton(onClick = { rescore(force = true) }) { Text(tr("Recompute")) } - if (summaries.isNotEmpty()) TextButton(onClick = { + else TextButton(onClick = { rescore(force = true) }, modifier = Modifier.widthIn(max = 120.dp)) { + Text(tr("Recompute"), maxLines = 1, overflow = TextOverflow.Ellipsis) + } + if (summaries.isNotEmpty()) TextButton(modifier = Modifier.widthIn(max = 120.dp), onClick = { scope.launch { val ring = db.deviceDao().currentReal()?.takeIf { RingIdentity.keyOf(it) == check.deviceKey } val text = AccuracyReportText.share( @@ -121,7 +129,7 @@ internal fun AccuracyReportSection( } context.startActivity(android.content.Intent.createChooser(send, tr("Share accuracy report"))) } - }) { Text(tr("Share")) } + }) { Text(tr("Share"), maxLines = 1, overflow = TextOverflow.Ellipsis) } } Text( trf("How your ring compares with {0}, the device you chose to trust. This is agreement between two consumer devices, not a lab measurement.", check.referenceLabel), @@ -142,7 +150,7 @@ internal fun AccuracyReportSection( ) } status?.let { Text(it, fontSize = 12.sp, color = PulseColors.warning) } - if (days.isEmpty() && !scoring) { + if (daysLoad != null && days.isEmpty() && !scoring) { Text(tr("Nothing to compare yet. Check back after the first full day and night."), fontSize = 13.sp, color = PulseColors.textSecondary) } val worst = AccuracyReportText.worstFirst(summaries) @@ -202,10 +210,14 @@ private fun MetricCard( } headline?.let { Text(it, fontSize = 13.sp, color = PulseColors.textSecondary) } } + // Bounded chip: unbounded, a long translated verdict took the row and squeezed the + // weighted metric name to a character per line (the DrinksUi bug). Text( AccuracyReportText.verdictLabel(summary.verdict), fontSize = 12.sp, color = verdictColor(summary.verdict), - modifier = Modifier.clip(RoundedCornerShape(10.dp)).background(PulseColors.cardSoft).padding(horizontal = 8.dp, vertical = 3.dp), + maxLines = 2, overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(start = 8.dp).widthIn(max = 140.dp) + .clip(RoundedCornerShape(10.dp)).background(PulseColors.cardSoft).padding(horizontal = 8.dp, vertical = 3.dp), ) } Text(AccuracyReportText.reading(summary, check.referenceLabel), fontSize = 12.sp, color = PulseColors.textSecondary) @@ -299,10 +311,14 @@ internal fun AccuracyCorrectionControl(check: AccuracyCheckEntity, summary: Accu val context = LocalContext.current val scope = rememberCoroutineScope() val db = remember { PulseLoopDatabase.getInstance(context) } - val all by db.accuracyDao().allCorrectionsFlow().collectAsState(initial = emptyList()) - val ring by db.deviceDao().currentFlow().collectAsState(initial = null) - val existing = all.firstOrNull { it.deviceKey == check.deviceKey && it.metric == metric.name } + // Both null until Room answers: read as "none", they flashed "Pair that ring" and the + // "Apply correction" button before the real state (correction on/off) replaced them. + val allLoad by remember(db) { db.accuracyDao().allCorrectionsFlow() }.collectAsState(initial = null) + val ringLoad by remember(db) { db.deviceDao().currentFlow().map { java.util.Optional.ofNullable(it) } }.collectAsState(initial = null) var editing by remember { mutableStateOf(false) } + val all = allLoad ?: return + val ring: com.pulseloop.data.entity.DeviceEntity? = (ringLoad ?: return).orElse(null) + val existing = all.firstOrNull { it.deviceKey == check.deviceKey && it.metric == metric.name } val paired = ring?.let { it.id != RingIdentity.DEMO_DEVICE_ID && RingIdentity.keyOf(it) == check.deviceKey } == true if (!paired) { @@ -313,13 +329,19 @@ internal fun AccuracyCorrectionControl(check: AccuracyCheckEntity, summary: Accu existing != null && existing.enabled -> Row(verticalAlignment = Alignment.CenterVertically) { Text(trf("Correction on: {0}", AccuracyCorrections.formatValue(metric, existing.value)), fontSize = 12.sp, color = PulseColors.success, modifier = Modifier.weight(1f)) - TextButton(onClick = { editing = true }) { Text(tr("Change")) } - TextButton(onClick = { scope.launch { AccuracyCorrections.setEnabled(db, existing, false) } }) { Text(tr("Turn off")) } + TextButton(onClick = { editing = true }, modifier = Modifier.widthIn(max = 110.dp)) { + Text(tr("Change"), maxLines = 1, overflow = TextOverflow.Ellipsis) + } + TextButton(onClick = { scope.launch { AccuracyCorrections.setEnabled(db, existing, false) } }, modifier = Modifier.widthIn(max = 110.dp)) { + Text(tr("Turn off"), maxLines = 1, overflow = TextOverflow.Ellipsis) + } } existing != null -> Row(verticalAlignment = Alignment.CenterVertically) { Text(trf("Correction off ({0})", AccuracyCorrections.formatValue(metric, existing.value)), fontSize = 12.sp, color = PulseColors.textMuted, modifier = Modifier.weight(1f)) - TextButton(onClick = { scope.launch { AccuracyCorrections.setEnabled(db, existing, true) } }) { Text(tr("Turn on")) } + TextButton(onClick = { scope.launch { AccuracyCorrections.setEnabled(db, existing, true) } }, modifier = Modifier.widthIn(max = 120.dp)) { + Text(tr("Turn on"), maxLines = 1, overflow = TextOverflow.Ellipsis) + } } else -> Button(onClick = { editing = true }, modifier = Modifier.fillMaxWidth()) { Text(trf("Apply correction ({0})", AccuracyCorrections.formatValue(metric, fitted))) @@ -389,8 +411,11 @@ internal fun AccuracyCorrectionsCard() { val context = LocalContext.current val scope = rememberCoroutineScope() val db = remember { PulseLoopDatabase.getInstance(context) } - val all by db.accuracyDao().allCorrectionsFlow().collectAsState(initial = emptyList()) - val ring by db.deviceDao().currentFlow().collectAsState(initial = null) + // null until loaded: an empty list flashed "None. A finished check offers one…" before the + // ring's corrections arrived. + val allLoad by remember(db) { db.accuracyDao().allCorrectionsFlow() }.collectAsState(initial = null) + val ring by remember(db) { db.deviceDao().currentFlow() }.collectAsState(initial = null) + val all = allLoad ?: return val r = ring?.takeIf { it.id != RingIdentity.DEMO_DEVICE_ID } ?: return val key = RingIdentity.keyOf(r) val mine = all.filter { it.deviceKey == key }.sortedBy { ComparisonMetric.byName(it.metric)?.ordinal ?: 99 } @@ -415,7 +440,9 @@ internal fun AccuracyCorrectionsCard() { } } Switch(checked = c.enabled, onCheckedChange = { on -> scope.launch { AccuracyCorrections.setEnabled(db, c, on) } }) - TextButton(onClick = { scope.launch { AccuracyCorrections.remove(db, c) } }) { Text(tr("Remove")) } + TextButton(onClick = { scope.launch { AccuracyCorrections.remove(db, c) } }, modifier = Modifier.widthIn(max = 110.dp)) { + Text(tr("Remove"), maxLines = 1, overflow = TextOverflow.Ellipsis) + } } } Text(tr("Applied to what PulseLoop shows, never to stored readings or Health Connect."), fontSize = 11.sp, color = PulseColors.textMuted) 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 67803143..106fa274 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt @@ -44,6 +44,7 @@ import androidx.compose.material3.TextButton import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext @@ -169,7 +170,7 @@ fun ActivityScreen( item { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { Text( - "+ Record Activity", + tr("+ Record Activity"), fontSize = 17.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.onAccent, @@ -227,7 +228,7 @@ fun ActivityScreen( item { Text( - "TODAY", + tr("TODAY"), fontSize = 11.sp, fontWeight = FontWeight.Medium, letterSpacing = 1.4.sp, color = PulseColors.textMuted, ) @@ -244,8 +245,11 @@ fun ActivityScreen( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp), ) { - Text(tr("No workouts recorded today"), fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary) - Text(tr("Start one manually when your ring misses an activity."), fontSize = 12.sp, color = PulseColors.textMuted) + // Until the sessions have loaded the card keeps its size but says nothing, so + // "no workouts" never flashes for a day that has them. + val shown = Modifier.alpha(if (state.workoutsLoaded) 1f else 0f) + Text(tr("No workouts recorded today"), fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, modifier = shown) + Text(tr("Start one manually when your ring misses an activity."), fontSize = 12.sp, color = PulseColors.textMuted, modifier = shown) } } } else { @@ -448,9 +452,11 @@ private fun SummaryMetric(label: String, value: String, unit: String?, color: Co letterSpacing = 0.6.sp, color = color, maxLines = 1, ) Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + // weight(fill = false): bounded so the unit beside it is never squeezed off. Text( value, fontSize = 32.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, maxLines = 1, overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f, fill = false), ) if (unit != null) { Text(unit, fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textMuted, modifier = Modifier.padding(bottom = 5.dp)) @@ -489,11 +495,14 @@ fun ActivityWorkoutRow(session: ActivitySessionEntity, units: UnitSystem, onTap: } Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) { Row(verticalAlignment = Alignment.CenterVertically) { + // The label takes the weight (not a Spacer) so a long translated type name + // ellipsizes instead of squeezing the start time. Text( ActivityMeta.label(session.type), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, + maxLines = 1, overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), ) - Spacer(Modifier.weight(1f)) Text(SleepFormat.clockTime(session.startedAt), fontSize = 11.sp, color = PulseColors.textMuted) } Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) { @@ -683,7 +692,7 @@ private fun RecordTypePickerDialog(onDismiss: () -> Unit, onStart: (String, Bool .switchRow(checked = useGps, onCheckedChange = { useGps = it }), verticalAlignment = Alignment.CenterVertically, ) { - Text("Track GPS route", fontSize = 14.sp, modifier = Modifier.weight(1f)) + Text(tr("Track GPS route"), fontSize = 14.sp, modifier = Modifier.weight(1f)) Switch(checked = useGps, onCheckedChange = null) } } @@ -714,8 +723,8 @@ private fun WorkoutHistoryDialog( .toList().sortedByDescending { it.first } } fun header(day: LocalDate): String = when (day) { - today -> "TODAY" - today.minusDays(1) -> "YESTERDAY" + today -> tr("TODAY") + today.minusDays(1) -> tr("YESTERDAY") // Locale.ROOT: iOS's uppercased() is locale-insensitive; a Turkish locale would turn // month-name i's into dotted İ otherwise. else -> headerFmt.format(day).uppercase(java.util.Locale.ROOT) @@ -999,7 +1008,8 @@ private fun DetectedActivityCard() { } } } - Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { + // FlowRow: the two translated actions wrap rather than overflow the card. + FlowRow(horizontalArrangement = Arrangement.spacedBy(16.dp)) { Text( if (isNap) tr("Yes, a nap") else tr("Add workout"), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, modifier = Modifier.clickable { diff --git a/app/src/main/java/com/pulseloop/ui/screens/BarcodeScannerScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/BarcodeScannerScreen.kt index 31d29fc1..4c200534 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/BarcodeScannerScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/BarcodeScannerScreen.kt @@ -107,7 +107,18 @@ fun BarcodeScannerScreen(onScan: (String) -> Unit, onDismiss: () -> Unit) { val hasCameraHardware = remember { context.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY) } - var availability by remember { mutableStateOf(ScanAvailability.Checking) } + // Settled up front when it can be, so an already-granted camera doesn't flash the + // "Checking" spinner for a frame before the preview; only a permission prompt starts there. + var availability by remember { + mutableStateOf( + when { + !hasCameraHardware -> ScanAvailability.Unavailable + ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == + PackageManager.PERMISSION_GRANTED -> ScanAvailability.Granted + else -> ScanAvailability.Checking + }, + ) + } val permissionLauncher = rememberLauncherForActivityResult( ActivityResultContracts.RequestPermission(), ) { granted -> diff --git a/app/src/main/java/com/pulseloop/ui/screens/CoachModelPicker.kt b/app/src/main/java/com/pulseloop/ui/screens/CoachModelPicker.kt index d8aa3ba4..b03d7c5f 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CoachModelPicker.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CoachModelPicker.kt @@ -136,8 +136,12 @@ fun CoachModelPicker( } Text(status, style = MaterialTheme.typography.bodySmall, color = color, modifier = Modifier.weight(1f)) if (savedKey.isNotBlank() && !loading) { - TextButton(onClick = { load(force = true) }) { - Text(if (listing is CoachModelCatalog.Result.Failure) tr("Retry") else tr("Refresh")) + // Bounded so a long translated label can't squeeze the weighted status text. + TextButton(onClick = { load(force = true) }, modifier = Modifier.widthIn(max = 140.dp)) { + Text( + if (listing is CoachModelCatalog.Result.Failure) tr("Retry") else tr("Refresh"), + maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, + ) } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt index 956eab2d..93a2acb7 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt @@ -53,6 +53,7 @@ import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.pulseloop.coach.attachments.CoachAttachmentRef +import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import com.pulseloop.coach.attachments.CoachAttachmentStore import com.pulseloop.ui.components.MarkdownLite @@ -98,10 +99,20 @@ fun CoachScreen( if (state.messages.isNotEmpty()) listState.animateScrollToItem(state.messages.size) } val goalDb = remember { com.pulseloop.data.PulseLoopDatabase.getInstance(ctx) } - val activeGoal by remember { goalDb.coachGoalDao().activeFlow() }.collectAsState(initial = null) - val goalPlan by produceState(null, activeGoal, state.messages.size) { - value = runCatching { com.pulseloop.service.GoalPlan.load(goalDb) }.getOrNull() + // `initial = null` is also "no goal", so track the first emission separately: otherwise the + // banner flashes "What's your goal?" for a frame before an existing goal arrives. + var goalLoaded by remember { mutableStateOf(false) } + val activeGoal by remember { + goalDb.coachGoalDao().activeFlow().onEach { goalLoaded = true } + }.collectAsState(initial = null) + // Paired with the goal it was loaded for, so a plan still loading for a just-arrived goal reads + // as loading rather than as "no plan". A reload on a new message keeps the previous plan shown. + val goalPlanFor by produceState?>(null, activeGoal, state.messages.size) { + val goal = activeGoal + value = goal to runCatching { com.pulseloop.service.GoalPlan.load(goalDb) }.getOrNull() } + val goalPlan = goalPlanFor?.second + val goalBannerLoading = !goalLoaded || (activeGoal != null && goalPlanFor?.first != activeGoal) Column(Modifier.fillMaxSize().background(PulseColors.background)) { LazyColumn( @@ -120,6 +131,7 @@ fun CoachScreen( GoalBanner( plan = goalPlan, hasGoal = activeGoal != null, + loading = goalBannerLoading, enabled = !state.isThinking, onSetGoal = { viewModel?.sendMessage(tr("I'd like to set a goal. Ask me what I want and help me make it realistic for my data."), emptyList()) }, onCheckIn = { viewModel?.sendMessage(tr("How am I doing on my goal? What should I focus on this week?"), emptyList()) }, @@ -303,7 +315,8 @@ private fun MessageBubble(msg: CoachViewModel.ChatMessage, viewModel: CoachViewM // ─────────────────────────── Composer ─────────────────────────── -private val SUGGESTIONS = listOf( +/** A getter, so the chips follow a language change without a restart. */ +private val SUGGESTIONS: List get() = listOf( tr("How am I doing today?"), tr("Explain my heart rate trend"), tr("Summarize my week"), @@ -503,11 +516,24 @@ private fun Composer( private fun GoalBanner( plan: com.pulseloop.service.GoalPlan.Plan?, hasGoal: Boolean, + loading: Boolean, enabled: Boolean, onSetGoal: () -> Unit, onCheckIn: () -> Unit, ) { val shape = RoundedCornerShape(8.dp) + if (loading) { + // Same card, empty, while the goal loads — keeps the chat below from jumping. + Box( + Modifier + .fillMaxWidth() + .heightIn(min = 64.dp) + .clip(shape) + .background(PulseColors.card) + .border(1.dp, PulseColors.borderSubtle, shape), + ) + return + } Row( Modifier .fillMaxWidth() diff --git a/app/src/main/java/com/pulseloop/ui/screens/CoachUsageSheet.kt b/app/src/main/java/com/pulseloop/ui/screens/CoachUsageSheet.kt index e44dadaa..f322bb74 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CoachUsageSheet.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CoachUsageSheet.kt @@ -21,6 +21,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.pulseloop.coach.config.CoachProviderMode @@ -142,7 +143,7 @@ private fun BreakdownCard(accounted: List) { ) { Text( tr("Per-message breakdown"), fontSize = 13.sp, fontWeight = FontWeight.Medium, - color = PulseColors.textPrimary, + color = PulseColors.textPrimary, modifier = Modifier.weight(1f), ) Text(if (expanded) tr("Hide") else tr("Show"), fontSize = 12.sp, color = PulseColors.textSecondary) } @@ -176,7 +177,12 @@ private fun UsageRow(label: String, value: String, mono: Boolean = false) { verticalAlignment = Alignment.CenterVertically, ) { Text(label, fontSize = 14.sp, color = PulseColors.textSecondary) - Text(value, fontSize = 14.sp, color = PulseColors.textPrimary) + // The value can be a list of model slugs: let it wrap in the space the label leaves + // instead of pushing the label off the row. + Text( + value, fontSize = 14.sp, color = PulseColors.textPrimary, textAlign = TextAlign.End, + modifier = Modifier.padding(start = 12.dp).weight(1f, fill = false), + ) } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/CycleUi.kt b/app/src/main/java/com/pulseloop/ui/screens/CycleUi.kt index ae105c96..5a4d79e1 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CycleUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CycleUi.kt @@ -29,6 +29,8 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.pulseloop.data.PulseLoopDatabase @@ -50,7 +52,11 @@ fun CycleScreen(onBack: () -> Unit) { val context = LocalContext.current val db = remember { PulseLoopDatabase.getInstance(context) } val scope = rememberCoroutineScope() - val periods by remember { db.periodDao().allFlow() }.collectAsState(initial = emptyList()) + // null until Room answers: read as empty, the card said "log your period to start" and the + // button offered "period started today" to someone mid-period, then both changed a frame later. + val periodsLoaded by remember { db.periodDao().allFlow() }.collectAsState(initial = null) + val loaded = periodsLoaded != null + val periods = periodsLoaded.orEmpty() val today = remember { LocalDate.now() } val status = Cycle.status(periods.map { it.toPeriod() }, today) val fmt = remember { DateTimeFormatter.ofPattern("EEE d MMM") } @@ -60,7 +66,11 @@ fun CycleScreen(onBack: () -> Unit) { Column(Modifier.fillMaxSize().background(PulseColors.background)) { Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) } - Text(tr("Cycle"), modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) + Text( + tr("Cycle"), fontSize = 17.sp, fontWeight = FontWeight.Bold, + maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center, + modifier = Modifier.align(Alignment.Center).padding(horizontal = 56.dp), + ) } Column( Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), @@ -70,7 +80,10 @@ fun CycleScreen(onBack: () -> Unit) { Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp), ) { - if (status == null) { + if (!loaded) { + // Holds roughly the card's height until the dates are read. + Spacer(Modifier.height(72.dp)) + } else if (status == null) { Text(tr("Log your period to start"), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(tr("PulseLoop shows the day of your cycle and its phase from the dates you log, next to your sleep and recovery."), fontSize = 13.sp, color = PulseColors.textSecondary) } else { @@ -95,7 +108,9 @@ fun CycleScreen(onBack: () -> Unit) { } } val open = periods.firstOrNull()?.takeIf { it.endDay == null && status?.inPeriod == true } - if (open != null) { + if (!loaded) { + Spacer(Modifier.height(40.dp)) + } else if (open != null) { Button(onClick = { scope.launch { db.periodDao().upsert(open.copy(endDay = today.toEpochDay())) } }, modifier = Modifier.fillMaxWidth()) { Text(tr("Period ended today")) } @@ -107,7 +122,7 @@ fun CycleScreen(onBack: () -> Unit) { OutlinedButton(onClick = { picking = "start" }, modifier = Modifier.fillMaxWidth()) { Text(tr("Log a past period")) } if (periods.isNotEmpty()) { - Text("HISTORY", fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + Text(tr("HISTORY"), fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) val starts = periods.map { it.startDay }.sorted() periods.forEach { p -> val next = starts.firstOrNull { it > p.startDay } diff --git a/app/src/main/java/com/pulseloop/ui/screens/DebugScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/DebugScreen.kt index 6f8ff294..1d18ed7d 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/DebugScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/DebugScreen.kt @@ -37,7 +37,7 @@ import java.util.* * the application-scoped `DiagnosticsSubscriber`, so leaving this screen loses nothing, and its * actions drive the app's own ring connection rather than a second client. */ -@OptIn(ExperimentalMaterial3Api::class) +@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) @Composable fun DebugScreen(viewModel: DiagnosticsViewModel, onBack: () -> Unit = {}) { val context = LocalContext.current @@ -78,7 +78,8 @@ fun DebugScreen(viewModel: DiagnosticsViewModel, onBack: () -> Unit = {}) { color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(bottom = 4.dp), ) - Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(bottom = 8.dp)) { + // FlowRow: the two translated labels don't fit side by side on a phone. + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(bottom = 8.dp)) { OutlinedButton( enabled = !busy, onClick = { viewModel.sync(connect = false) }, @@ -231,7 +232,7 @@ private fun DebugCard( Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, modifier = Modifier.weight(1f)) trailing?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt b/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt index 3b556cf3..985b47f7 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt @@ -65,6 +65,7 @@ import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp @@ -78,6 +79,7 @@ import com.pulseloop.service.DrinkType import com.pulseloop.service.DrinksRepository import com.pulseloop.ui.theme.PulseColors import com.pulseloop.ui.theme.dither +import kotlinx.coroutines.delay import kotlinx.coroutines.launch import java.time.Instant import java.time.LocalDate @@ -161,7 +163,7 @@ private fun Pill(label: String, on: Boolean, color: Color = PulseColors.accent, fontSize = 13.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.Normal, color = if (on) PulseColors.onAccent else PulseColors.textSecondary, - maxLines = 1, + maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.clip(shape) .background(if (on) color else PulseColors.cardSoft) .border(1.dp, if (on) color else PulseColors.borderSubtle, shape) @@ -191,7 +193,7 @@ private fun Segments(options: List, selected: Int, onSelect: (Int) -> Un fontWeight = if (on) FontWeight.Bold else FontWeight.Normal, color = if (on) PulseColors.onAccent else PulseColors.textSecondary, textAlign = TextAlign.Center, - maxLines = 1, + maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f) .background(if (on) PulseColors.accent else PulseColors.cardSoft) .selectable(selected = on, role = Role.Tab) { onSelect(i) } @@ -222,7 +224,12 @@ fun DrinksScreen(onBack: () -> Unit, onBreathe: () -> Unit, onCoach: ((String) - Column(Modifier.fillMaxSize().background(PulseColors.background)) { Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) } - Text(tr("Drinks"), modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) + // Kept clear of the back and settings buttons whatever the voice calls this screen. + Text( + tr("Drinks"), fontSize = 17.sp, fontWeight = FontWeight.Bold, + maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center, + modifier = Modifier.align(Alignment.Center).padding(horizontal = 56.dp), + ) if (enabled) { IconButton(onClick = { settingsOpen = true }, modifier = Modifier.align(Alignment.CenterEnd)) { Icon(Icons.Filled.Settings, tr("Drinks settings"), tint = PulseColors.textSecondary) @@ -239,7 +246,7 @@ fun DrinksScreen(onBack: () -> Unit, onBreathe: () -> Unit, onCoach: ((String) - Segments(listOf(tr("This week"), tr("Trends"), tr("Support")), tab) { tab = it } val s = snap if (s == null) { - Text(tr("Reading your drinks…"), color = PulseColors.textMuted, fontSize = 13.sp) + DrinksLoading() } else when (tab) { 0 -> { WeekHero(s) @@ -269,6 +276,23 @@ fun DrinksScreen(onBack: () -> Unit, onBreathe: () -> Unit, onCoach: ((String) - } } +/** + * First load: a card the hero's size, so the content lands where the placeholder was instead of + * pushing a line of text away. The text only appears if the read is actually slow; on a quick + * read it would just flash. + */ +@Composable +private fun DrinksLoading() { + var slow by remember { mutableStateOf(false) } + LaunchedEffect(Unit) { delay(400); slow = true } + Box( + Modifier.fillMaxWidth().height(200.dp).clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), + contentAlignment = Alignment.Center, + ) { + if (slow) Text(tr("Reading your drinks…"), color = PulseColors.textMuted, fontSize = 13.sp) + } +} + // ── Welcome ───────────────────────────────────────────────────────────────────────────────── /** @@ -384,7 +408,7 @@ private fun WeekHero(s: DrinksRepository.Snapshot) { } Column(horizontalAlignment = Alignment.CenterHorizontally) { Text(std(total), fontSize = 26.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text("of ${std(s.weeklyLimit)}", fontSize = 11.sp, color = PulseColors.textMuted) + Text(trf("of {0}", std(s.weeklyLimit)), fontSize = 11.sp, color = PulseColors.textMuted) } } Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { @@ -417,7 +441,7 @@ private fun WeekStrip(s: DrinksRepository.Snapshot) { Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp)) { Text( day.dayOfWeek.getDisplayName(TextStyle.NARROW, Locale.getDefault()), - fontSize = 11.sp, color = if (isToday) PulseColors.textPrimary else PulseColors.textMuted, + fontSize = 11.sp, maxLines = 1, color = if (isToday) PulseColors.textPrimary else PulseColors.textMuted, fontWeight = if (isToday) FontWeight.Bold else FontWeight.Normal, ) Box( @@ -436,7 +460,7 @@ private fun WeekStrip(s: DrinksRepository.Snapshot) { contentAlignment = Alignment.Center, ) { when { - drank -> Text(std(DrinkInsights.standardDrinks(grams, s.gramsPerStandard)), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = PulseColors.onAccent) + drank -> Text(std(DrinkInsights.standardDrinks(grams, s.gramsPerStandard)), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = PulseColors.onAccent, maxLines = 1, softWrap = false) !future && known && !isToday -> Icon(Icons.Filled.Check, tr("Dry"), tint = PulseColors.accent, modifier = Modifier.size(16.dp)) } } @@ -463,11 +487,13 @@ private fun LogCard(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChang modifier = Modifier.clickable { more = true }.padding(4.dp), ) }) { - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + // Equal-height buttons whose labels may take two lines: a translated or voice name + // ("Caipirinha", "Coquetel") doesn't fit a quarter of the card at one line. + Row(Modifier.fillMaxWidth().height(IntrinsicSize.Min), horizontalArrangement = Arrangement.spacedBy(8.dp)) { s.topTypes.forEach { t -> val shape = RoundedCornerShape(8.dp) Column( - Modifier.weight(1f).clip(shape) + Modifier.weight(1f).fillMaxHeight().clip(shape) .background(PulseColors.cardSoft) .border(1.dp, PulseColors.borderSubtle, shape) .clickable { @@ -477,12 +503,12 @@ private fun LogCard(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChang onChange() } } - .padding(vertical = 12.dp), + .padding(horizontal = 4.dp, vertical = 12.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(6.dp), ) { Icon(t.icon, null, tint = PulseColors.drinks, modifier = Modifier.size(24.dp)) - Text(t.short, fontSize = 11.sp, color = PulseColors.textPrimary, maxLines = 1, softWrap = false) + Text(t.short, fontSize = 11.sp, color = PulseColors.textPrimary, textAlign = TextAlign.Center, maxLines = 2, overflow = TextOverflow.Ellipsis) } } } @@ -492,7 +518,8 @@ private fun LogCard(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChang Text( tr("Undo"), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, - modifier = Modifier.clickable { + maxLines = 1, overflow = TextOverflow.Ellipsis, + modifier = Modifier.widthIn(max = 120.dp).clickable { scope.launch { ids.forEach { DrinksRepository.delete(db, it) }; lastLogged = null; onChange() } }.padding(4.dp), ) @@ -577,7 +604,10 @@ private fun PlanChip(s: DrinksRepository.Snapshot, onClick: () -> Unit) { label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = if (planned == null) PulseColors.accent else PulseColors.textPrimary, - modifier = Modifier.clip(shape) + // Bounded, so a long translation or voice line wraps inside the chip instead of + // starving the "tonight" text beside it down to one letter per line. + maxLines = 2, overflow = TextOverflow.Ellipsis, + modifier = Modifier.widthIn(max = 150.dp).clip(shape) .border(1.dp, if (planned == null) PulseColors.accent else PulseColors.borderSubtle, shape) .clickable(onClick = onClick) .padding(horizontal = 12.dp, vertical = 8.dp), @@ -703,8 +733,8 @@ private fun Stat(value: String, label: String, modifier: Modifier) { modifier.clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(12.dp), verticalArrangement = Arrangement.spacedBy(2.dp), ) { - Text(value, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary, maxLines = 1) - Text(label, fontSize = 11.sp, color = PulseColors.textMuted, maxLines = 2) + Text(value, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary, maxLines = 1, softWrap = false) + Text(label, fontSize = 11.sp, color = PulseColors.textMuted, maxLines = 2, overflow = TextOverflow.Ellipsis) } } @@ -816,10 +846,18 @@ private fun AuditCard(s: DrinksRepository.Snapshot, onDone: () -> Unit) { var taking by remember { mutableStateOf(false) } val context = LocalContext.current var sex by remember { mutableStateOf(null) } - LaunchedEffect(Unit) { sex = runCatching { PulseLoopDatabase.getInstance(context).userProfileDao().get()?.sex }.getOrNull() } + // The level's threshold depends on sex, so a level drawn before the profile is read can flash + // "increasing" (warning colour) and then settle on "low". Hold it until the read is done. + var sexLoaded by remember { mutableStateOf(false) } + LaunchedEffect(Unit) { + sex = runCatching { PulseLoopDatabase.getInstance(context).userProfileDao().get()?.sex }.getOrNull() + sexLoaded = true + } val score = DrinkPrefs.auditScore DrinkCard(tr("3-question check")) { - if (score != null) { + if (score != null && !sexLoaded) { + Spacer(Modifier.height(64.dp)) + } else if (score != null) { val level = AuditC.level(score, sex) Text(level.label, fontSize = 17.sp, fontWeight = FontWeight.Bold, color = if (level == AuditC.Level.LOW) PulseColors.accent else PulseColors.warning) Text(AuditC.advice(level), fontSize = 13.sp, color = PulseColors.textSecondary) @@ -934,14 +972,14 @@ fun ColumnScope.DrinksTileContent(week: DrinkInsights.Week?, limit: Double, dryT val total = week?.standardDrinks ?: 0.0 Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(4.dp)) { Text(std(total), fontSize = 22.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, maxLines = 1) - Text(trf("of {0} this week", std(limit)), fontSize = 11.sp, color = PulseColors.textMuted, modifier = Modifier.padding(bottom = 4.dp), maxLines = 1) + Text(trf("of {0} this week", std(limit)), fontSize = 11.sp, color = PulseColors.textMuted, modifier = Modifier.padding(bottom = 4.dp), maxLines = 1, overflow = TextOverflow.Ellipsis) } Bar(if (limit > 0) (total / limit).toFloat() else 0f, if (limit > 0 && total > limit) PulseColors.warning else PulseColors.drinks) - Text(trf("{0} of {1} dry days", week?.dryDays ?: 0, dryTarget), fontSize = 11.sp, color = PulseColors.textSecondary, maxLines = 1) + Text(trf("{0} of {1} dry days", week?.dryDays ?: 0, dryTarget), fontSize = 11.sp, color = PulseColors.textSecondary, maxLines = 1, overflow = TextOverflow.Ellipsis) Spacer(Modifier.weight(1f)) Text( "+ ${DrinkPrefs.lastType.label}", - fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, maxLines = 1, + fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.clickable(role = Role.Button, onClick = onAdd).padding(vertical = 2.dp), ) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/FoodUi.kt b/app/src/main/java/com/pulseloop/ui/screens/FoodUi.kt index c15f6af3..a1d3a953 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/FoodUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/FoodUi.kt @@ -24,6 +24,8 @@ import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.pulseloop.data.PulseLoopDatabase @@ -72,7 +74,12 @@ fun FoodCard( ) }.getOrNull() } - val f = food ?: return + val f = food ?: run { + // Still reading. Unless the user hid the invitation the card will show either way, so + // hold its place on Today instead of popping it in and pushing everything below down. + if (!hidden) Box(Modifier.fillMaxWidth().height(180.dp).clip(RoundedCornerShape(8.dp)).background(PulseColors.card)) + return + } if (!f.enabled && hidden) return val fmt = remember { NumberFormat.getIntegerInstance() } @@ -88,11 +95,12 @@ fun FoodCard( Row(verticalAlignment = Alignment.CenterVertically) { Box(Modifier.size(8.dp).clip(RoundedCornerShape(4.dp)).background(PulseColors.calories)) Spacer(Modifier.width(8.dp)) - Text("FOOD", fontSize = 12.sp, letterSpacing = 1.8.sp, color = PulseColors.textSecondary, modifier = Modifier.weight(1f)) + Text(tr("FOOD"), fontSize = 12.sp, letterSpacing = 1.8.sp, color = PulseColors.textSecondary, modifier = Modifier.weight(1f)) if (!f.enabled) { Text( tr("Hide"), fontSize = 12.sp, color = PulseColors.textMuted, - modifier = Modifier.clickable(role = Role.Button) { + maxLines = 1, overflow = TextOverflow.Ellipsis, + modifier = Modifier.widthIn(max = 120.dp).clickable(role = Role.Button) { hidden = true hiddenPrefs(context).edit().putBoolean("hidden", true).apply() }.heightIn(min = 48.dp).wrapContentHeight().padding(horizontal = 12.dp), @@ -103,13 +111,13 @@ fun FoodCard( if (f.enabled) { Row(verticalAlignment = Alignment.Bottom) { Text(fmt.format(f.eaten.roundToInt()), fontSize = 30.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text(" kcal eaten", fontSize = 13.sp, color = PulseColors.textSecondary, modifier = Modifier.padding(bottom = 4.dp)) + Text(" " + tr("kcal eaten"), fontSize = 13.sp, color = PulseColors.textSecondary, modifier = Modifier.padding(bottom = 4.dp)) } val parts = buildList { burned?.takeIf { it > 0 }?.let { add(trf("{0} burned", fmt.format(it.roundToInt()))) } f.calorieGoal?.takeIf { it > 0 }?.let { add(trf("goal {0}", fmt.format(it.roundToInt()))) } if (f.proteinG > 0) add(trf("{0} g protein", f.proteinG.roundToInt())) - if (f.meals == 0) add("nothing logged yet") + if (f.meals == 0) add(tr("nothing logged yet")) } if (parts.isNotEmpty()) { Text(parts.joinToString(" · "), fontSize = 13.sp, color = PulseColors.textSecondary) @@ -121,10 +129,12 @@ fun FoodCard( ) } - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - FoodAction(tr("Photo"), Icons.Filled.CameraAlt, Modifier.weight(1f)) { onLog("photo") } - FoodAction(tr("Barcode"), Icons.Filled.QrCodeScanner, Modifier.weight(1f)) { onLog("barcode") } - FoodAction(tr("Add"), Icons.Filled.Add, Modifier.weight(1f)) { onLog("add") } + // Thirds of the card: a label like "Código de barras" needs two lines, and the three + // buttons keep one height when it takes them. + Row(Modifier.fillMaxWidth().height(IntrinsicSize.Min), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + FoodAction(tr("Photo"), Icons.Filled.CameraAlt, Modifier.weight(1f).fillMaxHeight()) { onLog("photo") } + FoodAction(tr("Barcode"), Icons.Filled.QrCodeScanner, Modifier.weight(1f).fillMaxHeight()) { onLog("barcode") } + FoodAction(tr("Add"), Icons.Filled.Add, Modifier.weight(1f).fillMaxHeight()) { onLog("add") } } } } @@ -138,12 +148,16 @@ private fun FoodAction(label: String, icon: ImageVector, modifier: Modifier, onC .background(PulseColors.cardSoft) .border(1.dp, PulseColors.borderSubtle, shape) .clickable(onClick = onClick) - .padding(vertical = 10.dp), + .padding(horizontal = 4.dp, vertical = 10.dp), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, ) { Icon(icon, null, Modifier.size(16.dp), tint = PulseColors.accent) Spacer(Modifier.width(6.dp)) - Text(label, fontSize = 13.sp, color = PulseColors.textPrimary, maxLines = 1) + Text( + label, fontSize = 13.sp, color = PulseColors.textPrimary, + maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center, + modifier = Modifier.weight(1f, fill = false), + ) } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/HealthConnectSourceUi.kt b/app/src/main/java/com/pulseloop/ui/screens/HealthConnectSourceUi.kt index 94f4f100..34860bb4 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/HealthConnectSourceUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/HealthConnectSourceUi.kt @@ -12,6 +12,8 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.ui.draw.clip import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size @@ -44,6 +46,7 @@ import com.pulseloop.health.accuracy.RingIdentity import com.pulseloop.health.source.HealthConnectSource import com.pulseloop.health.source.HealthConnectSourceImporter import com.pulseloop.ui.theme.PulseColors +import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import java.time.Instant import java.time.ZoneId @@ -61,17 +64,24 @@ fun HealthConnectSourceScreen(onBack: () -> Unit) { * Pick the app whose data PulseLoop should use — Oura, Samsung Health, Fitbit — then import. Also * the onboarding step for people who don't have a PulseLoop ring ([onEnabled] moves it on). */ +@OptIn(ExperimentalLayoutApi::class) @Composable fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { val context = LocalContext.current val scope = rememberCoroutineScope() val services = remember { AppServices.get(context) } val available = remember { HealthConnectSdk.availability(context) == HealthConnectAvailability.AVAILABLE } - val ring by services.db.deviceDao().currentFlow().collectAsState(initial = null) + // null until Room answers, so a paired ring isn't briefly read as "no ring" (which flashed the + // Allow-access / app-picker path before the "a ring is paired" warning replaced it). + val ringLoad by remember(services.db) { services.db.deviceDao().currentFlow().map { java.util.Optional.ofNullable(it) } } + .collectAsState(initial = null) + val ring: com.pulseloop.data.entity.DeviceEntity? = ringLoad?.orElse(null) val hasRing = ring?.let { it.id != RingIdentity.DEMO_DEVICE_ID } == true || services.bleClient.hasLastKnownRing var enabled by remember { mutableStateOf(HealthConnectSource.isEnabled(context)) } var source by remember { mutableStateOf(HealthConnectSource.sourcePackage(context)) } - var granted by remember { mutableStateOf>(emptySet()) } + // null until Health Connect has answered: an empty set would show "Allow access" for a moment + // to someone who already granted it. + var granted by remember { mutableStateOf?>(null) } var scanning by remember { mutableStateOf(false) } var importing by remember { mutableStateOf(false) } var scan by remember { mutableStateOf(null) } @@ -108,8 +118,9 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { } LaunchedEffect(Unit) { - granted = ReferenceSourceScanner.grantedPermissions(context) - if (granted.any { it in HealthConnectSource.readPermissions } && !enabled) doScan() + val got = ReferenceSourceScanner.grantedPermissions(context) + granted = got + if (got.any { it in HealthConnectSource.readPermissions } && !enabled) doScan() } val launcher = rememberLauncherForActivityResult(PermissionController.createRequestPermissionResultContract()) { got -> @@ -118,8 +129,9 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { note = tr("No access granted. You can allow it in Health Connect's settings.") } else if (!enabled) doScan() } - val canRead = granted.any { it in HealthConnectSource.readPermissions } - val missing = HealthConnectSource.request - granted + val loaded = granted != null && ringLoad != null + val canRead = granted.orEmpty().any { it in HealthConnectSource.readPermissions } + val missing = HealthConnectSource.request - granted.orEmpty() Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { AccuracyCard { @@ -136,6 +148,8 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { ) if (!available) { Text(tr("Health Connect isn't available on this phone."), fontSize = 12.sp, color = PulseColors.danger) + } else if (!loaded) { + // Still reading the ring row and the grants: show neither the warning nor the button yet. } else if (hasRing && !enabled) { Text( tr("A ring is paired. Forget it in Settings → Wearable first: the two would count the same steps and nights."), @@ -154,7 +168,7 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { val count = remember(refresh) { HealthConnectSource.lastImportCount(context) } Text( last?.let { - "Last import " + DateTimeFormatter.ofPattern("EEE d MMM, HH:mm").format(Instant.ofEpochMilli(it).atZone(ZoneId.systemDefault())) + + trf("Last import {0}", DateTimeFormatter.ofPattern("EEE d MMM, HH:mm").format(Instant.ofEpochMilli(it).atZone(ZoneId.systemDefault()))) + trf(" · {0} readings", "%,d".format(count)) } ?: tr("Not imported yet"), fontSize = 13.sp, color = PulseColors.textSecondary, @@ -164,15 +178,19 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { trf("{0} has synced it in the morning.", HealthConnectSource.label(context, pkg)), fontSize = 12.sp, color = PulseColors.textMuted, ) - if (canRead && !HealthConnectSource.canReadInBackground(granted)) { + if (canRead && !HealthConnectSource.canReadInBackground(granted.orEmpty())) { Text(tr("Allow background access so imports also run while PulseLoop is closed."), fontSize = 12.sp, color = PulseColors.warning) } - Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { + // FlowRow: the two translated button labels plus the spinner overflow a phone's card width. + FlowRow( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { Button(onClick = { importNow() }, enabled = !importing && canRead) { Text(tr("Import now")) } if (missing.isNotEmpty()) { OutlinedButton(onClick = { launcher.launch(HealthConnectSource.request) }) { Text(tr("Allow more")) } } - if (importing) CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) + if (importing) CircularProgressIndicator(Modifier.size(20.dp).align(Alignment.CenterVertically), strokeWidth = 2.dp) } TextButton(onClick = { HealthConnectSource.disable(context) @@ -180,7 +198,7 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { doScan() }) { Text(tr("Stop using Health Connect"), color = PulseColors.danger) } } - } else if (canRead && !hasRing) { + } else if (loaded && canRead && !hasRing) { val r = scan if (scanning) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { @@ -233,7 +251,7 @@ fun HealthConnectSourceHeroCard(onOpen: () -> Unit) { Text(tr("DATA SOURCE"), fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) Text(trf("{0} via Health Connect", HealthConnectSource.label(context, pkg)), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text( - last?.let { "Last import " + DateTimeFormatter.ofPattern("EEE HH:mm").format(Instant.ofEpochMilli(it).atZone(ZoneId.systemDefault())) } + last?.let { trf("Last import {0}", DateTimeFormatter.ofPattern("EEE HH:mm").format(Instant.ofEpochMilli(it).atZone(ZoneId.systemDefault()))) } ?: tr("Waiting for the first import"), fontSize = 13.sp, color = PulseColors.textSecondary, ) diff --git a/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt b/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt index d3dae050..59b0979b 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt @@ -23,9 +23,11 @@ import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.pulseloop.data.PulseLoopDatabase @@ -61,8 +63,10 @@ fun JournalTagsCard( var onYesterday by remember(date) { mutableStateOf(false) } val shown = if (allowYesterday && onYesterday) date.minusDays(1) else date val day = remember(shown) { dayKey(shown) } - val entries by remember(day) { db.journalDao().forDayFlow(day) }.collectAsState(initial = emptyList()) - val selected = entries.map { it.tag }.toSet() + // null until Room's first answer: with emptyList() every chip drew unselected and the day's + // tags then flipped on a frame later. A day switch keeps the previous list until the new one lands. + val entries by remember(day) { db.journalDao().forDayFlow(day) }.collectAsState(initial = null) + val selected = entries.orEmpty().map { it.tag }.toSet() val scope = rememberCoroutineScope() Column( @@ -83,7 +87,8 @@ fun JournalTagsCard( // broke the longer labels over two lines in a monospace face. // Each chip sits in a 48dp-tall touch target, so the rows need no extra vertical gap. FlowRow( - Modifier.fillMaxWidth(), + // Laid out but invisible while loading, so the card keeps its height. + Modifier.fillMaxWidth().alpha(if (entries == null) 0f else 1f), horizontalArrangement = Arrangement.spacedBy(8.dp), ) { tags.forEach { tag -> @@ -125,15 +130,18 @@ fun JournalTagsCard( @Composable private fun DaySwitch(yesterday: Boolean, onChange: (Boolean) -> Unit) { val shape = RoundedCornerShape(16.dp) - Box(Modifier.heightIn(min = 48.dp), contentAlignment = Alignment.Center) { + // Bounded: it sits beside the weighted title and is measured first. + Box(Modifier.heightIn(min = 48.dp).widthIn(max = 200.dp), contentAlignment = Alignment.Center) { Row(Modifier.clip(shape).border(1.dp, PulseColors.borderSubtle, shape).selectableGroup()) { listOf(false to "Today", true to "Yesterday").forEach { (isYesterday, label) -> val on = yesterday == isYesterday Text( - label, + tr(label), fontSize = 12.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.Normal, color = if (on) PulseColors.onAccent else PulseColors.textSecondary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, modifier = Modifier .background(if (on) PulseColors.accent else PulseColors.cardSoft) .selectable(selected = on, role = Role.RadioButton) { onChange(isYesterday) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt b/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt index 49fffeec..d5a55897 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt @@ -21,6 +21,10 @@ import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize @@ -71,6 +75,7 @@ import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.window.Dialog @@ -116,6 +121,7 @@ import java.util.UUID */ private enum class AnalysisPhase { Input, Analyzing, Review, Failed } +@OptIn(ExperimentalLayoutApi::class) @Composable fun MealAnalysisDialog( /** Start-of-day millis of the selected nutrition day (iOS MealAnalysisSheet.day). */ @@ -304,8 +310,9 @@ fun MealAnalysisDialog( verticalArrangement = Arrangement.spacedBy(16.dp), ) { // Meal-type picker — iOS segmented Picker (:51-54); Android uses the same - // FilterChip row MealLogDialog uses. - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + // FilterChip row MealLogDialog uses. A FlowRow, as there: four chips overflow a + // narrow phone once the labels are translated. + FlowRow(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { listOf("breakfast", "lunch", "dinner", "snack").forEach { t -> FilterChip( selected = mealType == t, @@ -337,11 +344,12 @@ fun MealAnalysisDialog( } } } else { - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { - OutlinedButton(onClick = { launchCamera() }, modifier = Modifier.weight(1f)) { + // Equal heights if a translated label wraps to a second line. + Row(Modifier.fillMaxWidth().height(IntrinsicSize.Min), horizontalArrangement = Arrangement.spacedBy(12.dp)) { + OutlinedButton(onClick = { launchCamera() }, modifier = Modifier.weight(1f).fillMaxHeight()) { Icon(Icons.Filled.PhotoCamera, null, Modifier.size(18.dp)) Spacer(Modifier.width(6.dp)) - Text(tr("Camera")) + Text(tr("Camera"), maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center) } OutlinedButton( onClick = { @@ -349,11 +357,11 @@ fun MealAnalysisDialog( PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly) ) }, - modifier = Modifier.weight(1f), + modifier = Modifier.weight(1f).fillMaxHeight(), ) { Icon(Icons.Filled.PhotoLibrary, null, Modifier.size(18.dp)) Spacer(Modifier.width(6.dp)) - Text(tr("Library")) + Text(tr("Library"), maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center) } } } @@ -540,7 +548,7 @@ private fun NumberField(label: String, unit: String, value: String, modifier: Mo val cleaned = raw.replace(',', '.').filter { it.isDigit() || it == '.' } if (cleaned.count { it == '.' } <= 1) onChange(cleaned) }, - label = { Text(label, maxLines = 1) }, + label = { Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis) }, suffix = { Text(unit, color = PulseColors.textMuted) }, modifier = modifier, singleLine = true, 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 a0ed6469..def38a62 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MedsUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MedsUi.kt @@ -27,6 +27,8 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.pulseloop.data.PulseLoopDatabase @@ -48,7 +50,9 @@ fun MedsScreen(onBack: () -> Unit) { val db = remember { PulseLoopDatabase.getInstance(context) } val scope = rememberCoroutineScope() val today = remember { LocalDate.now() } - val meds by remember { db.medDao().allFlow() }.collectAsState(initial = emptyList()) + // null until Room answers, so the "add what you take" intro doesn't flash for someone who has meds. + val medsLoaded by remember { db.medDao().allFlow() }.collectAsState(initial = null) + val meds = medsLoaded.orEmpty() val answers by remember { db.medDao().dosesSinceFlow(today.minusDays(8).toEpochDay()) }.collectAsState(initial = emptyList()) var editing by remember { mutableStateOf(null) } var adding by remember { mutableStateOf(false) } @@ -62,13 +66,18 @@ fun MedsScreen(onBack: () -> Unit) { Column(Modifier.fillMaxSize().background(PulseColors.background)) { Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) } - Text(tr("Medications & supplements"), modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) + // Kept clear of the back button: the translated title is long. + Text( + tr("Medications & supplements"), fontSize = 17.sp, fontWeight = FontWeight.Bold, + maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center, + modifier = Modifier.align(Alignment.Center).padding(horizontal = 56.dp), + ) } Column( Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) { - if (meds.isEmpty()) { + if (medsLoaded != null && meds.isEmpty()) { Text(tr("Add what you take on a schedule. PulseLoop asks once per dose and keeps a week's record, and the coach can see it."), fontSize = 14.sp, color = PulseColors.textSecondary) } if (doses.isNotEmpty()) { @@ -76,7 +85,7 @@ fun MedsScreen(onBack: () -> Unit) { Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp), ) { - Text("TODAY", fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + Text(tr("TODAY"), fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) doses.forEach { d -> Row(verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { @@ -92,11 +101,12 @@ fun MedsScreen(onBack: () -> Unit) { ) } when (d.state) { + // Bounded so long translations can't squeeze the dose name beside them. Meds.State.TAKEN, Meds.State.SKIPPED -> - TextButton(onClick = { answer(d, null) }) { Text(tr("Undo")) } + TextButton(onClick = { answer(d, null) }, modifier = Modifier.widthIn(max = 104.dp)) { Text(tr("Undo"), maxLines = 1, overflow = TextOverflow.Ellipsis) } else -> { - TextButton(onClick = { answer(d, "skipped") }) { Text(tr("Skip"), color = PulseColors.textMuted) } - TextButton(onClick = { answer(d, "taken") }) { Text(tr("Taken")) } + TextButton(onClick = { answer(d, "skipped") }, modifier = Modifier.widthIn(max = 96.dp)) { Text(tr("Skip"), color = PulseColors.textMuted, maxLines = 1, overflow = TextOverflow.Ellipsis) } + TextButton(onClick = { answer(d, "taken") }, modifier = Modifier.widthIn(max = 96.dp)) { Text(tr("Taken"), maxLines = 1, overflow = TextOverflow.Ellipsis) } } } } 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 0aadab99..caa41986 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt @@ -54,6 +54,8 @@ import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.liveRegion import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.pulseloop.data.PulseLoopDatabase @@ -104,7 +106,8 @@ private fun Fact(label: String, value: String, note: String? = null, color: Colo Text(label, fontSize = 14.sp, color = PulseColors.textSecondary) note?.let { Text(it, fontSize = 12.sp, color = PulseColors.textMuted) } } - Text(value, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = color) + // Bounded: a translated value ("Moderada · 3h 20m") must not squeeze the label column. + Text(value, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = color, textAlign = TextAlign.End, modifier = Modifier.widthIn(max = 160.dp)) } } @@ -143,6 +146,9 @@ 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)) { @@ -173,10 +179,14 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () ) { val s = snap if (s == null) { - Text( - if (loadFailed) tr("Couldn't load your health history.") else tr("Reading your history…"), - color = if (loadFailed) PulseColors.warning else PulseColors.textMuted, fontSize = 13.sp, - ) + if (loadFailed) { + Text(tr("Couldn't load your health history."), color = PulseColors.warning, fontSize = 13.sp) + } else { + // Only after a moment: on a quick read the line would just flash before the cards. + var slow by remember { mutableStateOf(false) } + LaunchedEffect(Unit) { delay(400); slow = true } + if (slow) Text(tr("Reading your history…"), color = PulseColors.textMuted, fontSize = 13.sp) + } } else { Row( Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) @@ -203,8 +213,7 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () Text("›", fontSize = 22.sp, color = PulseColors.textMuted) } } - val periods by remember { db.periodDao().allFlow() }.collectAsState(initial = emptyList()) - val cycle = Cycle.status(periods.map { it.toPeriod() }, java.time.LocalDate.now()) + 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), @@ -212,7 +221,7 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () ) { 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 ?: tr("Log your period to see its phase beside your sleep and recovery"), fontSize = 12.sp, color = PulseColors.textMuted) + 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) } @@ -238,7 +247,7 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () Text(a.title, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(a.detail, fontSize = 12.sp, color = PulseColors.textMuted) } - Text(a.rating.label, fontSize = 13.sp, fontWeight = FontWeight.Bold, color = ratingColor(a.rating)) + Text(a.rating.label, fontSize = 13.sp, fontWeight = FontWeight.Bold, color = ratingColor(a.rating), textAlign = TextAlign.End, maxLines = 2, modifier = Modifier.widthIn(max = 120.dp)) } Sparkline(a.trend, ratingColor(a.rating)) } @@ -349,13 +358,14 @@ 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) - Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + 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")) } } @@ -429,12 +439,12 @@ private fun HabitsSection(h: HealthInsightsRepository.Habits) { private fun TrendsSection(db: PulseLoopDatabase) { var metric by remember { mutableStateOf(TrendMetric.SLEEP) } var period by remember { mutableStateOf(Trends.Period.WEEK) } - var trendFailed by remember { mutableStateOf(false) } - val points by produceState?>(null, metric, period) { - value = null - trendFailed = false - value = runCatching { Trends.aggregate(HealthInsightsRepository.daily(db, metric, period.days), period) } - .onFailure { trendFailed = true }.getOrNull() + // Each load remembers what it was for, so switching metric or period keeps the last chart up + // (drawn as its own metric) until the new one is in, instead of collapsing to "Loading…". + val load by produceState(null, metric, period) { + val m = metric + val p = period + value = TrendLoad(m, p, runCatching { Trends.aggregate(HealthInsightsRepository.daily(db, m, p.days), p) }.getOrNull()) } Section(tr("Trends")) { Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).selectableGroup(), horizontalArrangement = Arrangement.spacedBy(6.dp)) { @@ -450,7 +460,7 @@ private fun TrendsSection(db: PulseLoopDatabase) { Trends.Period.entries.forEach { p -> val on = p == period Text(p.label, fontSize = 12.sp, color = if (on) PulseColors.textPrimary else PulseColors.textMuted, - fontWeight = if (on) FontWeight.Bold else FontWeight.Normal, + fontWeight = if (on) FontWeight.Bold else FontWeight.Normal, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f).minimumInteractiveComponentSize().clip(RoundedCornerShape(4.dp)) .then(if (on) Modifier.dither(PulseColors.accent, 0.18f) else Modifier) .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(4.dp)) @@ -458,12 +468,15 @@ private fun TrendsSection(db: PulseLoopDatabase) { textAlign = androidx.compose.ui.text.style.TextAlign.Center) } } - val pts = points + val l = load + val pts = l?.points when { - pts == null && trendFailed -> Text(trf("Couldn't load {0} trends.", metric.label.lowercase()), fontSize = 12.sp, color = PulseColors.warning) - pts == null -> Text(tr("Loading…"), fontSize = 12.sp, color = PulseColors.textMuted) - pts.size < 2 -> Text(trf("Not enough {0} data for this view yet.", metric.label.lowercase()), fontSize = 12.sp, color = PulseColors.textMuted) + l == null -> Text(tr("Loading…"), fontSize = 12.sp, color = PulseColors.textMuted) + pts == null -> Text(trf("Couldn't load {0} trends.", l.metric.label.lowercase()), fontSize = 12.sp, color = PulseColors.warning) + pts.size < 2 -> Text(trf("Not enough {0} data for this view yet.", l.metric.label.lowercase()), fontSize = 12.sp, color = PulseColors.textMuted) else -> { + val metric = l.metric + val period = l.period val shown = pts.takeLast(if (period == Trends.Period.DAY) 30 else 26) val fmt = if (metric == TrendMetric.TEMPERATURE || metric == TrendMetric.SLEEP || metric == TrendMetric.WEIGHT) "%.1f" else "%.0f" val summary = trf("{0} by {1}: latest {2} {3}, range {4}–{5} {6}, {7} points", metric.label, period.label.lowercase(), fmt.format(shown.last().value), metric.unit, fmt.format(shown.minOf { it.value }), fmt.format(shown.maxOf { it.value }), metric.unit, shown.size) @@ -486,6 +499,9 @@ private fun TrendsSection(db: PulseLoopDatabase) { } } +/** One trend load and the metric and period it was made for. Null points: the load failed. */ +private data class TrendLoad(val metric: TrendMetric, val period: Trends.Period, val points: List?) + // ── Breathing session ───────────────────────────────────────────────────────────────────────── /** @@ -632,12 +648,15 @@ private fun StepCalibrationCard(db: PulseLoopDatabase) { granted = ok if (ok) scope.launch { com.pulseloop.service.StepCalibration.sample(context) } } + // "Collecting: needs N days…" is the answer for a null result, so it must wait for the read. + var resultLoaded by remember { mutableStateOf(false) } val result by produceState(null, granted) { value = runCatching { val zone = java.time.ZoneId.systemDefault() val ring = db.activityDailyDao().recentReal(60).associate { java.time.Instant.ofEpochMilli(it.date).atZone(zone).toLocalDate() to it.steps } com.pulseloop.service.StepCalibration.factor(com.pulseloop.service.StepCalibration.phoneDays(context), ring, java.time.LocalDate.now()) }.getOrNull() + resultLoaded = true } Section(tr("Ring steps vs your phone")) { when { @@ -647,6 +666,7 @@ private fun StepCalibrationCard(db: PulseLoopDatabase) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) launcher.launch(android.Manifest.permission.ACTIVITY_RECOGNITION) }, modifier = Modifier.fillMaxWidth()) { Text(tr("Compare with my phone")) } } + !resultLoaded -> Spacer(Modifier.height(36.dp)) result == null -> Text( trf("Collecting: needs {0} days with at least {1} steps on both. Carry your phone as usual.", com.pulseloop.service.StepCalibration.MIN_DAYS, com.pulseloop.service.StepCalibration.MIN_STEPS), fontSize = 13.sp, color = PulseColors.textMuted, 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 dd183c6c..eb092200 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt @@ -23,8 +23,11 @@ import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.pulseloop.coach.tools.NutritionTools @@ -73,14 +76,19 @@ fun NutritionScreen( var suggestion by remember { mutableStateOf(null) } + // Until the day and the goal are read, the gauge would show "0 kcal of 2000" and then jump. + // The previous day's values stay up while a new day loads (reload never clears them). + var dayLoaded by remember { mutableStateOf(false) } + var goalLoaded by remember { mutableStateOf(false) } fun reload() { scope.launch { meals = db.mealEntryDao().byDay(todayStart) totals = db.mealEntryDao().dayTotals(todayStart) suggestion = runCatching { com.pulseloop.service.MealSuggester.load(db) }.getOrNull() + dayLoaded = true } } - LaunchedEffect(Unit) { goal = db.userGoalDao().get() } + LaunchedEffect(Unit) { goal = db.userGoalDao().get(); goalLoaded = true } LaunchedEffect(dayOffset) { reload() } var showAddDialog by remember { mutableStateOf(false) } @@ -92,8 +100,8 @@ fun NutritionScreen( // photo-analysis pref, so both pills gate on the coach master toggle alone (reported // divergence in ios-sync.md). val keyStore = remember(context) { ApiKeyStore(context) } - var coachEnabled by remember { mutableStateOf(false) } - LaunchedEffect(Unit) { coachEnabled = keyStore.coachEnabled } + // Read up front, not in an effect: starting false popped the Photo/Describe row in a frame later. + var coachEnabled by remember { mutableStateOf(keyStore.coachEnabled) } var startScanner by remember { mutableStateOf(false) } LaunchedEffect(start) { when (start) { @@ -141,9 +149,13 @@ fun NutritionScreen( val goalCal = goal?.intakeCalories ?: 2000.0 val pct = if (goalCal > 0) (totalCal / goalCal).coerceAtMost(1.0) else 0.0 Card(Modifier.fillMaxWidth(), shape = RoundedCornerShape(8.dp), colors = CardDefaults.cardColors(containerColor = PulseColors.card)) { - Column(Modifier.padding(20.dp), horizontalAlignment = Alignment.CenterHorizontally) { + // Invisible rather than absent while loading, so the card keeps its height. + Column( + Modifier.padding(20.dp).then(if (dayLoaded && goalLoaded) Modifier else Modifier.alpha(0f)), + horizontalAlignment = Alignment.CenterHorizontally, + ) { Text("${totalCal.roundToInt()} kcal", fontSize = 32.sp, fontWeight = FontWeight.Bold) - Text("of ${goalCal.roundToInt()}", color = PulseColors.textMuted) + Text(trf("of {0}", goalCal.roundToInt()), color = PulseColors.textMuted) Spacer(Modifier.height(8.dp)) LinearProgressIndicator( progress = { pct.toFloat() }, @@ -152,10 +164,10 @@ fun NutritionScreen( trackColor = PulseColors.cardSoft, ) Spacer(Modifier.height(8.dp)) - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) { - MacroBar(tr("Protein"), totals.sumOf { it.totalP }, goal?.intakeProteinG ?: 150.0, PulseColors.heartRate) - MacroBar(tr("Carbs"), totals.sumOf { it.totalC }, goal?.intakeCarbsG ?: 250.0, PulseColors.calories) - MacroBar(tr("Fat"), totals.sumOf { it.totalF }, goal?.intakeFatG ?: 65.0, PulseColors.warning) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + MacroBar(tr("Protein"), totals.sumOf { it.totalP }, goal?.intakeProteinG ?: 150.0, PulseColors.heartRate, Modifier.weight(1f)) + MacroBar(tr("Carbs"), totals.sumOf { it.totalC }, goal?.intakeCarbsG ?: 250.0, PulseColors.calories, Modifier.weight(1f)) + MacroBar(tr("Fat"), totals.sumOf { it.totalF }, goal?.intakeFatG ?: 65.0, PulseColors.warning, Modifier.weight(1f)) } } } @@ -228,22 +240,26 @@ fun NutritionScreen( // analysis sheet in camera mode, Describe in describe mode. if (coachEnabled) { item { - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + // 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), + 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")) + Text(tr("Photo"), maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center) } OutlinedButton( onClick = { analysisRequest = AnalysisRequest(startWithCamera = false) }, - modifier = Modifier.weight(1f), + 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")) + Text(tr("Describe"), maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center) } } } @@ -350,10 +366,11 @@ data class MealLogSave( ) @Composable -private fun MacroBar(label: String, value: Double, goal: Double, color: Color) { +private fun MacroBar(label: String, value: Double, goal: Double, color: Color, modifier: Modifier = Modifier) { val pct = if (goal > 0) (value / goal).coerceAtMost(1.0) else 0.0 - Column(horizontalAlignment = Alignment.CenterHorizontally) { - Text(label, fontSize = 12.sp, color = PulseColors.textMuted) + // Equal thirds, so a long translated macro name ellipsizes instead of crowding its neighbours. + Column(modifier, horizontalAlignment = Alignment.CenterHorizontally) { + Text(label, fontSize = 12.sp, color = PulseColors.textMuted, maxLines = 1, overflow = TextOverflow.Ellipsis) Text("${value.roundToInt()}g", fontSize = 13.sp, fontWeight = FontWeight.SemiBold) LinearProgressIndicator( progress = { pct.toFloat() }, @@ -476,12 +493,12 @@ fun MealLogDialog( } } Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - OutlinedTextField(value = cal, onValueChange = { cal = decimalInput(it) ?: cal }, label = { Text("kcal", maxLines = 1) }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) - OutlinedTextField(value = protein, onValueChange = { protein = decimalInput(it) ?: protein }, label = { Text(tr("Protein (g)"), maxLines = 1) }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) + OutlinedTextField(value = cal, onValueChange = { cal = decimalInput(it) ?: cal }, label = { Text("kcal", maxLines = 1, overflow = TextOverflow.Ellipsis) }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) + OutlinedTextField(value = protein, onValueChange = { protein = decimalInput(it) ?: protein }, label = { Text(tr("Protein (g)"), maxLines = 1, overflow = TextOverflow.Ellipsis) }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) } Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - OutlinedTextField(value = carbs, onValueChange = { carbs = decimalInput(it) ?: carbs }, label = { Text(tr("Carbs (g)"), maxLines = 1) }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) - OutlinedTextField(value = fat, onValueChange = { fat = decimalInput(it) ?: fat }, label = { Text(tr("Fat (g)"), maxLines = 1) }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) + OutlinedTextField(value = carbs, onValueChange = { carbs = decimalInput(it) ?: carbs }, label = { Text(tr("Carbs (g)"), maxLines = 1, overflow = TextOverflow.Ellipsis) }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) + OutlinedTextField(value = fat, onValueChange = { fat = decimalInput(it) ?: fat }, label = { Text(tr("Fat (g)"), maxLines = 1, overflow = TextOverflow.Ellipsis) }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) } } }, @@ -590,10 +607,15 @@ private fun NextMealCard( Text(tr("Your preference: ") + idea.fromPreferences.joinToString("; "), fontSize = 12.sp, color = PulseColors.accent) } idea.note?.let { Text(it, fontSize = 12.sp, color = PulseColors.textSecondary) } - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Button(onClick = onLog, modifier = Modifier.weight(1f)) { Text(tr("Log this")) } + // Same treatment as the Photo/Describe pair: two lines allowed, equal heights. + Row(Modifier.fillMaxWidth().height(IntrinsicSize.Min), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Button(onClick = onLog, modifier = Modifier.weight(1f).fillMaxHeight(), contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp)) { + Text(tr("Log this"), maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center) + } if (onDiscuss != null) { - OutlinedButton(onClick = onDiscuss, modifier = Modifier.weight(1f)) { Text(tr("Other ideas")) } + OutlinedButton(onClick = onDiscuss, modifier = Modifier.weight(1f).fillMaxHeight(), contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp)) { + Text(tr("Other ideas"), maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center) + } } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/OnboardingScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/OnboardingScreen.kt index fb46e6a9..cee32d92 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/OnboardingScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/OnboardingScreen.kt @@ -278,13 +278,16 @@ private fun OnboardingTopBar( textAlign = TextAlign.Center, modifier = Modifier.weight(1f), ) - Box(Modifier.size(width = 60.dp, height = 44.dp), contentAlignment = Alignment.CenterEnd) { + // widthIn, not a fixed 60dp: a longer translated "Skip" grows the slot instead of + // wrapping inside it and clipping at 44dp tall. + Box(Modifier.widthIn(min = 60.dp).height(44.dp), contentAlignment = Alignment.CenterEnd) { if (showsSkip) { Text( tr("Skip"), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textSecondary, + maxLines = 1, modifier = Modifier .clip(RoundedCornerShape(4.dp)) .clickable(onClick = onSkip) @@ -378,16 +381,19 @@ private fun WelcomeStep( // Two-column feature grid (rows of two, since we're inside a scroll column). features.chunked(2).forEach { pair -> - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { + // Min height, not a fixed 118dp: two-line translated titles and subtitles overflowed it. + // IntrinsicSize.Min + fillMaxHeight keeps both tiles in a row the same height. + Row(Modifier.fillMaxWidth().height(IntrinsicSize.Min), horizontalArrangement = Arrangement.spacedBy(12.dp)) { pair.forEach { feature -> Column( Modifier .weight(1f) - .height(118.dp) + .fillMaxHeight() + .heightIn(min = 118.dp) .clip(RoundedCornerShape(8.dp)) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(8.dp)) - .padding(horizontal = 13.dp), + .padding(horizontal = 13.dp, vertical = 10.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterVertically), ) { 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 98b3b8ce..e50b9488 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/PostpartumUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/PostpartumUi.kt @@ -29,6 +29,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.pulseloop.data.PulseLoopDatabase @@ -198,9 +199,23 @@ fun PostpartumScreen(onBack: () -> Unit, onOpenProfile: () -> Unit) { val today = remember { LocalDate.now() } val birth = Postpartum.birthDate?.takeIf { Postpartum.active(today) } var data by remember { mutableStateOf(null) } + var loaded by remember { mutableStateOf(false) } var checkIn by remember { mutableStateOf(false) } var history by remember { mutableStateOf(Postpartum.epdsHistory()) } - LaunchedEffect(birth) { if (birth != null) data = loadPostpartum(db, birth, System.currentTimeMillis(), zone) } + LaunchedEffect(birth) { + if (birth != null) { + data = try { + loadPostpartum(db, birth, System.currentTimeMillis(), zone) + } catch (e: kotlinx.coroutines.CancellationException) { + throw e + } catch (e: Exception) { + null + } + } + // Set even on a failed read: the cards below are gated on it, and the warning signs + // among them must never stay hidden. + loaded = true + } if (checkIn) { EpdsCheckIn(onDone = { result -> @@ -243,6 +258,9 @@ fun PostpartumScreen(onBack: () -> Unit, onOpenProfile: () -> Unit) { ) } + // The data cards land between the hero and the mood check-in; drawn before the read + // finished, everything below jumped down as they arrived. Hold the rest until then. + if (!loaded) return@Column val d = data d?.alcoholClearAt?.let { clear -> val time = DateTimeFormatter.ofPattern("HH:mm").format(Instant.ofEpochMilli(clear).atZone(zone)) @@ -357,7 +375,8 @@ private fun LamRow(label: String, holds: Boolean, detail: String?) { Row(verticalAlignment = Alignment.CenterVertically) { Text(if (holds) "✓" else "✗", fontSize = 15.sp, color = if (holds) PulseColors.accent else PulseColors.warning, modifier = Modifier.width(24.dp)) Text(label, fontSize = 13.sp, color = PulseColors.textPrimary, modifier = Modifier.weight(1f)) - detail?.let { Text(it, fontSize = 12.sp, color = PulseColors.textMuted) } + // Bounded so a translated "days to go" can't squeeze the condition beside it. + detail?.let { Text(it, fontSize = 12.sp, color = PulseColors.textMuted, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 120.dp)) } } } @@ -430,6 +449,7 @@ private data class EpdsAsset(val en: EpdsForm, val pt: EpdsForm, val citation_en private val epdsJson = Json { ignoreUnknownKeys = true } /** What a score means, and item 10 first: any thought of self-harm gets the crisis lines, whatever the total. */ +@OptIn(ExperimentalLayoutApi::class) @Composable private fun EpdsGuidance(score: Int, selfHarm: Int) { val context = LocalContext.current @@ -440,7 +460,9 @@ private fun EpdsGuidance(score: Int, selfHarm: Int) { ) { Text(tr("You said thoughts of harming yourself have come up. Please talk to someone today."), fontSize = 14.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(tr("CVV listens 24 hours a day, free and anonymous. In danger now, call SAMU."), fontSize = 13.sp, color = PulseColors.textPrimary) - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + // FlowRow: the two translated labels don't fit side by side, and a crisis button + // pushed off the edge of the screen is the worst place for an overflow. + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { Button(onClick = { dial(context, "188") }) { Text(tr("Call CVV 188")) } OutlinedButton(onClick = { dial(context, "192") }) { Text(tr("Call SAMU 192")) } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt b/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt index ded8a428..bc103462 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt @@ -36,6 +36,7 @@ import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @@ -62,15 +63,26 @@ fun bandColor(band: Readiness.Band): Color = when (band) { Readiness.Band.PAY_ATTENTION -> PulseColors.danger } +/** + * A score loaded off the composition path. [loaded] tells "still loading" apart from "no score", + * so a screen can hold its space instead of flashing an empty state before the first load ends. + * A reload keeps the previous value (produceState doesn't reset on a key change). + */ +data class ScoreLoad(val loaded: Boolean, val value: T?) + /** Loads today's readiness, recomputing whenever [key] changes (new data, a new day). */ @Composable -fun rememberReadiness(db: PulseLoopDatabase, key: Any?): Readiness.Result? { - val result by produceState(initialValue = null, db, key) { - value = runCatching { ReadinessRepository.compute(db) }.getOrNull() +fun rememberReadinessLoad(db: PulseLoopDatabase, key: Any?): ScoreLoad { + val result by produceState(initialValue = ScoreLoad(false, null), db, key) { + value = ScoreLoad(true, runCatching { ReadinessRepository.compute(db) }.getOrNull()) } return result } +/** Loads today's readiness, recomputing whenever [key] changes (new data, a new day). */ +@Composable +fun rememberReadiness(db: PulseLoopDatabase, key: Any?): Readiness.Result? = rememberReadinessLoad(db, key).value + /** A score arc: track, coloured progress, the number centred. [value] null draws an empty ring. */ @Composable fun ScoreRing( @@ -128,8 +140,10 @@ private fun HeaderRing( verticalArrangement = Arrangement.spacedBy(6.dp), ) { ScoreRing(value = value, color = color, size = 84.dp, stroke = 7.dp, centerText = centerText) - Text(label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) - Text(caption, fontSize = 11.sp, color = PulseColors.textMuted, maxLines = 1) + // One line each, ellipsised: three rings share the row, and a voice's caption + // ("Ainda sem sono. Óbvio.") is wider than a third of a phone. + Text(label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(caption, fontSize = 11.sp, color = PulseColors.textMuted, maxLines = 1, overflow = TextOverflow.Ellipsis) } } @@ -144,6 +158,9 @@ fun ScoreHeader( onReadiness: () -> Unit, onSleep: () -> Unit, onActivity: () -> Unit, + /** False until the sleep / activity score has loaded: a blank caption, not "No data", until then. */ + sleepLoaded: Boolean = true, + activityLoaded: Boolean = true, ) { val score = readiness as? Readiness.Result.Score Column( @@ -164,22 +181,26 @@ fun ScoreHeader( color = score?.let { bandColor(it.band) } ?: PulseColors.readiness, onTap = onReadiness, modifier = Modifier.weight(1f), + // null is still loading (as the blank caption above): no "no score" dash yet. + centerText = score?.value?.toString() ?: if (readiness == null) "" else "—", ) HeaderRing( label = tr("Sleep"), value = sleepScore, - caption = sleepScore?.let { Readiness.Band.of(it).label } ?: tr("No data"), + caption = sleepScore?.let { Readiness.Band.of(it).label } ?: if (sleepLoaded) tr("No data") else " ", color = PulseColors.sleep, onTap = onSleep, modifier = Modifier.weight(1f), + centerText = sleepScore?.toString() ?: if (sleepLoaded) "—" else "", ) HeaderRing( label = tr("Activity"), value = activity?.value, - caption = activity?.band?.label ?: tr("No data"), + caption = activity?.band?.label ?: if (activityLoaded) tr("No data") else " ", color = PulseColors.steps, onTap = onActivity, modifier = Modifier.weight(1f), + centerText = activity?.value?.toString() ?: if (activityLoaded) "—" else "", ) } if (readiness != null) { @@ -196,6 +217,10 @@ fun ScoreHeader( modifier = Modifier.padding(horizontal = 24.dp), ) } + } else { + // Still loading (null is otherwise only a failed compute): keep the headline's line + // so the sentence arriving doesn't push the rest of Today down. + Text(" ", fontSize = 14.sp, modifier = Modifier.fillMaxWidth()) } } } @@ -210,7 +235,8 @@ private fun ProgressBar(fraction: Float, color: Color, modifier: Modifier = Modi /** Readiness detail: score, sentence, coverage caution, contributors, and what's missing. */ @Composable fun ReadinessScreen(db: PulseLoopDatabase, onBack: () -> Unit) { - val result = rememberReadiness(db, Unit) + val load = rememberReadinessLoad(db, Unit) + val result = load.value Column(Modifier.fillMaxSize()) { Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { @@ -233,6 +259,8 @@ fun ReadinessScreen(db: PulseLoopDatabase, onBack: () -> Unit) { value = score?.value, color = score?.let { bandColor(it.band) } ?: PulseColors.readiness, size = 168.dp, stroke = 12.dp, centerSize = 48, + // An empty ring while loading, not the "no score" dash. + centerText = score?.value?.toString() ?: if (load.loaded) "—" else "", ) score?.let { Text(it.band.label, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = bandColor(it.band)) @@ -329,19 +357,25 @@ private fun ContributorRow(c: ScoreContributor, expanded: Boolean, onTap: () -> } } -/** Loads today's activity score, recomputing whenever [key] changes. */ +/** Loads today's activity score, recomputing whenever [key] changes; see [ScoreLoad]. */ @Composable -fun rememberActivityScore(db: PulseLoopDatabase, key: Any?): com.pulseloop.service.ActivityScore.Result? { - val result by produceState(initialValue = null, db, key) { - value = runCatching { com.pulseloop.service.ActivityScore.load(db) }.getOrNull() +fun rememberActivityScoreLoad(db: PulseLoopDatabase, key: Any?): ScoreLoad { + val result by produceState(initialValue = ScoreLoad(false, null), db, key) { + value = ScoreLoad(true, runCatching { com.pulseloop.service.ActivityScore.load(db) }.getOrNull()) } return result } +/** Loads today's activity score, recomputing whenever [key] changes. */ +@Composable +fun rememberActivityScore(db: PulseLoopDatabase, key: Any?): com.pulseloop.service.ActivityScore.Result? = + rememberActivityScoreLoad(db, key).value + /** Activity score detail: score, band, contributors, and the estimate footer. */ @Composable fun ActivityScoreScreen(db: PulseLoopDatabase, onBack: () -> Unit, onOpenActivity: () -> Unit) { - val result = rememberActivityScore(db, Unit) + val load = rememberActivityScoreLoad(db, Unit) + val result = load.value Column(Modifier.fillMaxSize()) { Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { @@ -361,12 +395,16 @@ fun ActivityScoreScreen(db: PulseLoopDatabase, onBack: () -> Unit, onOpenActivit value = result?.value, color = result?.let { bandColor(it.band) } ?: PulseColors.steps, size = 168.dp, stroke = 12.dp, centerSize = 48, + centerText = result?.value?.toString() ?: if (load.loaded) "—" else "", ) result?.let { Text(it.band.label, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = bandColor(it.band)) } Text( - activityHeadline(result), fontSize = 15.sp, color = PulseColors.textSecondary, + // Blank while loading: activityHeadline(null) is the "no activity yet" copy, + // which flashed before every real score. + if (load.loaded) activityHeadline(result) else " ", + fontSize = 15.sp, color = PulseColors.textSecondary, textAlign = TextAlign.Center, ) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/RecordScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/RecordScreen.kt index 9cfad8c0..e6048886 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/RecordScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/RecordScreen.kt @@ -15,6 +15,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.pulseloop.service.HeartRateZones import com.pulseloop.settings.UnitConverter @@ -80,10 +81,14 @@ fun RecordScreen( Column(Modifier.fillMaxSize().padding(16.dp)) { // Activity name + status Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text(ActivityMeta.label(activityName), style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold) + // Weighted (fill = false) so a long translated name wraps instead of pushing PAUSED off. + Text( + ActivityMeta.label(activityName), style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold, + modifier = Modifier.weight(1f, fill = false).padding(end = 8.dp), + ) if (isPaused) { Surface(color = MaterialTheme.colorScheme.errorContainer, shape = MaterialTheme.shapes.small) { - Text("PAUSED", Modifier.padding(horizontal = 12.dp, vertical = 4.dp), style = MaterialTheme.typography.labelMedium, fontWeight = FontWeight.Bold) + Text(tr("PAUSED"), Modifier.padding(horizontal = 12.dp, vertical = 4.dp), style = MaterialTheme.typography.labelMedium, fontWeight = FontWeight.Bold) } } } @@ -137,19 +142,19 @@ fun RecordScreen( Button(onClick = onResume, Modifier.weight(1f).height(52.dp)) { Icon(Icons.Filled.PlayArrow, null) Spacer(Modifier.width(8.dp)) - Text(tr("Resume")) + Text(tr("Resume"), maxLines = 1, overflow = TextOverflow.Ellipsis) } } else { OutlinedButton(onClick = onPause, Modifier.weight(1f).height(52.dp)) { Icon(Icons.Filled.Pause, null) Spacer(Modifier.width(8.dp)) - Text(tr("Pause")) + Text(tr("Pause"), maxLines = 1, overflow = TextOverflow.Ellipsis) } } Button(onClick = onFinish, Modifier.weight(1f).height(52.dp), colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error)) { Icon(Icons.Filled.Stop, null) Spacer(Modifier.width(8.dp)) - Text(tr("Finish")) + Text(tr("Finish"), maxLines = 1, overflow = TextOverflow.Ellipsis) } } } 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 2b9e90c4..dc9fe0be 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/Screens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/Screens.kt @@ -31,6 +31,8 @@ import androidx.compose.ui.semantics.liveRegion import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.pulseloop.ring.RingDeviceType @@ -62,6 +64,7 @@ import kotlinx.coroutines.launch * Vitals dashboard — ported from VitalsView.swift. * Shows historical trends: HR, SpO2, HRV, stress, temperature with real data from Room. */ +@OptIn(ExperimentalLayoutApi::class) @Composable fun VitalsScreen( navController: androidx.navigation.NavController? = null, @@ -371,11 +374,18 @@ fun VitalsScreen( 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), ) { - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + FlowRow( + horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { Button( enabled = !measuring, onClick = { @@ -430,7 +440,10 @@ fun VitalsScreen( } } if (spotVitals.isNotEmpty()) { - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + FlowRow( + horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { for (vital in spotVitals) { val label = vital.label Button( @@ -457,6 +470,8 @@ fun VitalsScreen( } else { Button( enabled = !measuring, + // Same reason as the bound above: the title is weighted, this isn't. + modifier = Modifier.widthIn(max = 208.dp), onClick = { runMeasurement( measureSeconds, "all", @@ -535,7 +550,9 @@ fun VitalsScreen( } } - items(visibleOrdered, key = { it.key }) { card -> + // Not before the first load: until then every series is empty and every supports* flag + // false, so the list showed "No HR samples yet" cards and then grew as the rest arrived. + items(if (viewModel == null || state.loaded) visibleOrdered else emptyList(), key = { it.key }) { card -> EditableCard(editState, card, Modifier.fillMaxWidth()) { vitalsCardFor(card) } @@ -804,14 +821,17 @@ fun VitalDetailScreen( .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, cardShape) .padding(horizontal = 10.dp, vertical = 14.dp), - verticalAlignment = Alignment.CenterVertically, + // Bottom, so the values stay on one line when a translated title + // ("MAIS RECENTE") wraps to two; the dividers stay centred. + verticalAlignment = Alignment.Bottom, ) { + val divider = Modifier.align(Alignment.CenterVertically) DetailStat(tr("Latest"), state.latest?.let { formatStat(it, metric, gUnit) } ?: "--", Modifier.weight(1f)) - DetailStatDivider() + DetailStatDivider(divider) DetailStat(tr("Average"), state.avg?.let { formatStat(it, metric, gUnit) } ?: "--", Modifier.weight(1f)) - DetailStatDivider() + DetailStatDivider(divider) DetailStat(tr("Min"), state.min?.let { formatStat(it, metric, gUnit) } ?: "--", Modifier.weight(1f)) - DetailStatDivider() + DetailStatDivider(divider) DetailStat(tr("Max"), state.max?.let { formatStat(it, metric, gUnit) } ?: "--", Modifier.weight(1f)) } } @@ -862,13 +882,15 @@ fun VitalDetailScreen( .size(8.dp) .background(zone.colorToken.toColor(), CircleShape), ) + // Takes the free width (instead of a Spacer) so a long + // translated zone label wraps beside its range. Text( tr(zone.label), fontSize = 13.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, + modifier = Modifier.weight(1f), ) - Spacer(Modifier.weight(1f)) Text( zoneRangeText(zone, metric, units, gUnit), fontSize = 12.sp, @@ -933,6 +955,7 @@ fun VitalDetailScreen( fontSize = 12.sp, lineHeight = 17.sp, color = PulseColors.textSecondary, + modifier = Modifier.weight(1f), ) } } @@ -991,7 +1014,7 @@ private fun ReadingsCard( verticalAlignment = Alignment.CenterVertically, ) { Text( - "READINGS", + tr("READINGS"), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.sp, @@ -1125,6 +1148,9 @@ private fun PeriodSegmentedControl(selected: Period, onSelect: (Period) -> Unit) fontSize = 13.sp, fontWeight = if (isSelected) FontWeight.SemiBold else FontWeight.Medium, color = if (isSelected) PulseColors.textPrimary else PulseColors.textSecondary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(horizontal = 4.dp), ) } } @@ -1145,7 +1171,10 @@ private fun DetailStat(title: String, value: String, modifier: Modifier = Modifi fontWeight = FontWeight.Medium, letterSpacing = 0.6.sp, color = PulseColors.textMuted, - maxLines = 1, + // A quarter of the card: "MAIS RECENTE" doesn't fit one line, so it wraps centred. + maxLines = 2, + overflow = TextOverflow.Ellipsis, + textAlign = TextAlign.Center, ) Text( value, @@ -1158,9 +1187,9 @@ private fun DetailStat(title: String, value: String, modifier: Modifier = Modifi } @Composable -private fun DetailStatDivider() { +private fun DetailStatDivider(modifier: Modifier = Modifier) { Box( - Modifier + modifier .width(1.dp) .height(34.dp) .background(PulseColors.borderSubtle), diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt index e8416c17..2d88d703 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt @@ -4,7 +4,10 @@ import com.pulseloop.ui.i18n.trf import com.pulseloop.ui.i18n.tr +import androidx.compose.foundation.background +import androidx.compose.foundation.border import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons @@ -12,6 +15,7 @@ import androidx.compose.material.icons.filled.* import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp @@ -24,6 +28,7 @@ import com.pulseloop.ui.components.DeviceHeroCard import com.pulseloop.ui.components.SettingsRowItem import com.pulseloop.ui.components.SettingsSection import com.pulseloop.ui.theme.PulseColors +import kotlinx.coroutines.flow.map /** * Ported from SettingsView.swift (iOS #49 rehaul). @@ -44,7 +49,12 @@ fun SettingsScreen( val bleState = bleClient?.state?.collectAsState()?.value ?: com.pulseloop.ring.RingBLEClient.BLEState() - val storedDevice by db.deviceDao().currentFlow().collectAsState(initial = null) + // Wrapped so "not loaded yet" (null) differs from "no ring stored" (empty Optional): before + // Room's first emission the hero card used to read "No ring paired · Set up a ring" for a + // moment and then flip to the stored ring. + val storedDeviceLoad by remember(db) { db.deviceDao().currentFlow().map { java.util.Optional.ofNullable(it) } } + .collectAsState(initial = null) + val storedDevice: com.pulseloop.data.entity.DeviceEntity? = storedDeviceLoad?.orElse(null) // Capabilities of the live device (preferred) or the last stored device, used to decide // whether device-specific rows appear (iOS MetricsService.activeCapabilities). @@ -70,7 +80,7 @@ fun SettingsScreen( else -> keyStore.model } val notificationsTrailing = if (keyStore.notificationsEnabled) tr("On") else tr("Off") - val openCheck by db.accuracyDao().openFlow().collectAsState(initial = null) + val openCheck by remember(db) { db.accuracyDao().openFlow() }.collectAsState(initial = null) val accuracyTrailing = openCheck?.let { c -> if (c.state == com.pulseloop.data.entity.AccuracyCheckEntity.STATE_RUNNING) { val (day, total) = AccuracyUiText.dayOf(c) @@ -91,6 +101,17 @@ fun SettingsScreen( val hcSource by remember { com.pulseloop.health.source.HealthConnectSource.activeSource(context) }.collectAsState() if (hcSource != null) { HealthConnectSourceHeroCard(onOpen = { navigate("settings/hc-source") }) + } else if (storedDeviceLoad == null && bleState.connectionState != com.pulseloop.ring.RingConnectionState.CONNECTED) { + // Same footprint as the hero card (18 dp padding, 72 dp art, 10 dp gap, 48 dp action) + // so the rows below don't jump when the stored ring arrives. + Box( + Modifier + .fillMaxWidth() + .height(166.dp) + .clip(RoundedCornerShape(8.dp)) + .background(PulseColors.card) + .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(8.dp)), + ) } else DeviceHeroCard( bleState = bleState, storedDevice = storedDevice, 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 324e1765..fa7f5791 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt @@ -48,6 +48,7 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.pulseloop.coach.config.CoachProviderMode @@ -93,6 +94,7 @@ import com.pulseloop.ui.theme.PulseColors import com.pulseloop.wearables.WearableModel import kotlin.math.roundToInt import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch /** @@ -256,7 +258,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { askEnableCheckIns = true } }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text(tr("Enable AI Coach")) + Text(tr("Enable AI Coach"), Modifier.weight(1f)) Switch(checked = coachEnabled, onCheckedChange = null) } @@ -823,7 +825,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text(tr("Coach Memory"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Coach Memory"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, modifier = Modifier.weight(1f)) TextButton(onClick = { showMemory = !showMemory }) { Text(if (showMemory) tr("Hide") else trf("Show ({0})", memories.size)) } @@ -977,7 +979,7 @@ fun CheckInsSettingsScreen(onBack: () -> Unit) { Row(Modifier.fillMaxWidth() .switchRow(checked = notificationEnabled, enabled = coachEnabled, onCheckedChange = { setNotifications(it) }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text(tr("Daily Check-in Notifications")) + Text(tr("Daily Check-in Notifications"), Modifier.weight(1f)) Switch(checked = notificationEnabled, enabled = coachEnabled, onCheckedChange = null) } @@ -994,7 +996,7 @@ fun CheckInsSettingsScreen(onBack: () -> Unit) { // Morning time picker var morningHour by remember { mutableStateOf(keyStore.morningHour) } Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text(tr("Morning")) + Text(tr("Morning"), Modifier.weight(1f)) var amExpanded by remember { mutableStateOf(false) } Box { OutlinedButton(enabled = coachEnabled, onClick = { amExpanded = true }) { @@ -1014,7 +1016,7 @@ fun CheckInsSettingsScreen(onBack: () -> Unit) { // Evening time picker var eveningHour by remember { mutableStateOf(keyStore.eveningHour) } Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text(tr("Evening")) + Text(tr("Evening"), Modifier.weight(1f)) var pmExpanded by remember { mutableStateOf(false) } Box { OutlinedButton(enabled = coachEnabled, onClick = { pmExpanded = true }) { @@ -1065,7 +1067,7 @@ fun CheckInsSettingsScreen(onBack: () -> Unit) { Spacer(Modifier.height(12.dp)) Row(Modifier.fillMaxWidth() .switchRow(checked = batteryAlertsEnabled, onCheckedChange = { setBatteryAlerts(it) }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text(tr("Low Battery Notifications")) + Text(tr("Low Battery Notifications"), Modifier.weight(1f)) Switch(checked = batteryAlertsEnabled, onCheckedChange = null) } if (batteryPermDenied) { @@ -1268,23 +1270,21 @@ fun PhysiologySettingsScreen(onBack: () -> Unit) { val keyStore = remember { ApiKeyStore(context) } val imperial = keyStore.resolvedUnitSystem == UnitSystem.IMPERIAL - var athleteMode by remember { mutableStateOf(false) } - var altitudeText by remember { mutableStateOf("") } - var betaBlockers by remember { mutableStateOf(null) } - var lungCondition by remember { mutableStateOf(null) } - var glucoseUnit by remember { mutableStateOf(GlucoseUnit.MGDL) } - var savedMsg by remember { mutableStateOf(null) } - - LaunchedEffect(Unit) { - athleteMode = keyStore.athleteMode - betaBlockers = keyStore.usesBetaBlockers - lungCondition = keyStore.hasKnownLungCondition - glucoseUnit = keyStore.preferredGlucoseUnit - keyStore.altitudeMeters?.let { m -> - // Stored canonical metres; show in the display unit (iOS enters ft, stores m). - altitudeText = (if (imperial) (m / 0.3048).roundToInt() else m.roundToInt()).toString() - } + // Initialised straight from the (synchronous) prefs: loading them in a LaunchedEffect showed + // the defaults for a frame and then flipped every control to the stored value. + var athleteMode by remember { mutableStateOf(keyStore.athleteMode) } + var altitudeText by remember { + mutableStateOf( + keyStore.altitudeMeters?.let { m -> + // Stored canonical metres; show in the display unit (iOS enters ft, stores m). + (if (imperial) (m / 0.3048).roundToInt() else m.roundToInt()).toString() + } ?: "", + ) } + var betaBlockers by remember { mutableStateOf(keyStore.usesBetaBlockers) } + var lungCondition by remember { mutableStateOf(keyStore.hasKnownLungCondition) } + var glucoseUnit by remember { mutableStateOf(keyStore.preferredGlucoseUnit) } + var savedMsg by remember { mutableStateOf(null) } SettingsSubScreen(title = tr("Physiology"), onBack = onBack) { Text( @@ -1384,15 +1384,18 @@ private fun PhysiologyCard(title: String, footer: String?, content: @Composable @Composable private fun TriStateRow(title: String, value: Boolean?, onChange: (Boolean?) -> Unit) { val options = listOf>("Not set" to null, "No" to false, "Yes" to true) - Row(verticalAlignment = Alignment.CenterVertically) { - Text(title, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f)) - SingleChoiceSegmentedButtonRow { + // Stacked rather than side by side: three translated segments ("Não definido" …) left the + // weighted title a few dp and broke it a character per line. + Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text(title, style = MaterialTheme.typography.bodyMedium) + SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) { options.forEachIndexed { i, (label, v) -> SegmentedButton( selected = value == v, onClick = { onChange(v) }, shape = SegmentedButtonDefaults.itemShape(i, options.size), - ) { Text(label) } + modifier = Modifier.weight(1f), + ) { Text(tr(label), maxLines = 1, overflow = TextOverflow.Ellipsis) } } } } @@ -1413,20 +1416,14 @@ fun CalibrationSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U val db = remember { PulseLoopDatabase.getInstance(context) } val scope = rememberCoroutineScope() - var bpSys by remember { mutableStateOf("") } - var bpDia by remember { mutableStateOf("") } - var glucoseRef by remember { mutableStateOf("") } - var glucoseOffset by remember { mutableStateOf(0.0) } + // Initialised from the prefs directly, so the fields don't flash empty / "No calibration set". + var bpSys by remember { mutableStateOf(keyStore.bpAdjustSystolic.takeIf { it > 0 }?.toString() ?: "") } + var bpDia by remember { mutableStateOf(keyStore.bpAdjustDiastolic.takeIf { it > 0 }?.toString() ?: "") } + var glucoseRef by remember { mutableStateOf(keyStore.glucoseRefMgdl.takeIf { it > 0 }?.let { "%.0f".format(it) } ?: "") } + var glucoseOffset by remember { mutableStateOf(keyStore.glucoseOffsetMgdl) } var glucoseMsg by remember { mutableStateOf(null) } var savedMsg by remember { mutableStateOf(null) } - LaunchedEffect(Unit) { - bpSys = keyStore.bpAdjustSystolic.takeIf { it > 0 }?.toString() ?: "" - bpDia = keyStore.bpAdjustDiastolic.takeIf { it > 0 }?.toString() ?: "" - glucoseOffset = keyStore.glucoseOffsetMgdl - glucoseRef = keyStore.glucoseRefMgdl.takeIf { it > 0 }?.let { "%.0f".format(it) } ?: "" - } - SettingsSubScreen(title = tr("Calibration"), onBack = onBack) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { @@ -1528,7 +1525,7 @@ fun CalibrationSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U glucoseOffset = 0.0 glucoseRef = "" glucoseMsg = tr("Calibration cleared") - }) { Text(tr("Reset")) } + }, modifier = Modifier.widthIn(max = 120.dp)) { Text(tr("Reset"), maxLines = 1, overflow = TextOverflow.Ellipsis) } } } glucoseMsg?.let { @@ -1610,7 +1607,11 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U val context = LocalContext.current val db = remember { PulseLoopDatabase.getInstance(context) } val scope = rememberCoroutineScope() - val device = db.deviceDao().currentFlow().collectAsState(initial = null).value + // Optional-wrapped: null = still loading, empty = no ring. Reading null as "no ring" flashed + // "Pair a ring to configure…" before the toggles appeared. + val deviceLoad = remember(db) { db.deviceDao().currentFlow().map { java.util.Optional.ofNullable(it) } } + .collectAsState(initial = null).value + val device: com.pulseloop.data.entity.DeviceEntity? = deviceLoad?.orElse(null) val capabilities = device?.capabilities.orEmpty() val minimumInterval = if (device?.deviceType == RingDeviceType.YCBT) 30 else 5 val intervalSteps = ((60 - minimumInterval) / 5 - 1).coerceAtLeast(0) @@ -1656,7 +1657,7 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U fun VitalToggle(label: String, checked: Boolean, onChange: (Boolean) -> Unit) { Row(Modifier.fillMaxWidth() .switchRow(checked = checked, enabled = cfgLoaded, onCheckedChange = { onChange(it); cfgSavedMsg = null }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text(label) + Text(label, Modifier.weight(1f)) Switch(checked = checked, enabled = cfgLoaded, onCheckedChange = null) } } @@ -1673,7 +1674,9 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U ) Spacer(Modifier.height(12.dp)) - if (device == null) { + if (deviceLoad == null) { + // Loading: the header above is enough until the ring row arrives. + } else if (device == null) { Text( tr("Pair a ring to configure its all-day measurements."), style = MaterialTheme.typography.bodySmall, @@ -1815,7 +1818,7 @@ private fun QuietHoursCard() { horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, ) { - Text(tr("Sleep quiet hours"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Sleep quiet hours"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, modifier = Modifier.weight(1f)) Switch(checked = enabled, onCheckedChange = null) } Text( @@ -1971,7 +1974,12 @@ fun WearableSettingsScreen( val bleState = bleClient?.state?.collectAsState()?.value ?: RingBLEClient.BLEState() // Observe the device row reactively so the connection status reflects live BLE state // changes (connect / disconnect / reconnect) in real time. - val device by db.deviceDao().currentFlow().collectAsState(initial = null) + // Optional-wrapped: null = still loading, empty = no ring. Reading null as "no ring" flashed + // "No ring paired" + "Add a ring" before the stored ring's details. + val deviceLoad by remember(db) { db.deviceDao().currentFlow().map { java.util.Optional.ofNullable(it) } } + .collectAsState(initial = null) + val deviceLoaded = deviceLoad != null + val device: com.pulseloop.data.entity.DeviceEntity? = deviceLoad?.orElse(null) val isConnected = bleState.connectionState == RingConnectionState.CONNECTED val supportsFactoryReset = bleState.activeCapabilities .contains(com.pulseloop.ring.WearableCapability.FACTORY_RESET) @@ -2003,6 +2011,7 @@ fun WearableSettingsScreen( Spacer(Modifier.width(8.dp)) Text( if (isConnected) trf("Connected — {0} · {1}%", wearableDisplayName, battery ?: 0) + else if (!deviceLoaded) "" // keeps the line's height while loading else device?.let { trf("Last seen: {0}", wearableDisplayName) } ?: tr("No ring paired"), style = MaterialTheme.typography.bodyMedium, ) @@ -2020,7 +2029,7 @@ fun WearableSettingsScreen( Text(trf("Last synced: {0}", lastSyncedLabel), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp)) } - if (device == null) { + if (deviceLoaded && device == null) { // No ring yet — route into the redesigned pairing screen (iOS #48). Spacer(Modifier.height(12.dp)) Button(onClick = onAddRing, modifier = Modifier.fillMaxWidth()) { @@ -2280,14 +2289,15 @@ private fun BackgroundSyncCard() { /** 24h/7d windows for the battery drainage chart (iOS #61b — only these two ranges). */ private enum class BatteryHistoryRange(val label: String, val spanMs: Long) { - DAY(tr("24h"), 24 * 3600_000L), - WEEK(tr("7d"), 7 * 24 * 3600_000L), + DAY("24h", 24 * 3600_000L), + WEEK("7d", 7 * 24 * 3600_000L), } /** Fixed 0–100 zone coloring for the battery line — mirrors iOS `colorForValue` * (≤20 danger, ≤50 warning, else success). Zone boundaries use an exclusive upper bound * (`ZoneLineChart` matches `lower <= value < upper`), so 21/51 sit just above each cut. */ -private val batteryZones = listOf( +/** A getter, so the zone names follow a language change without a restart. */ +private val batteryZones: List get() = listOf( MetricZone("critical", tr("Critical"), null, 21.0, ZoneSeverity.CRITICAL, VitalColorToken.Red, tr("Battery critically low")), MetricZone("low", tr("Low"), 21.0, 51.0, ZoneSeverity.WATCH, VitalColorToken.Amber, tr("Battery low")), MetricZone("good", tr("Good"), 51.0, null, ZoneSeverity.OPTIMAL, VitalColorToken.Mint, tr("Battery healthy")), @@ -2302,8 +2312,10 @@ private val batteryZones = listOf( private fun BatteryHistorySection(db: PulseLoopDatabase) { var range by remember { mutableStateOf(BatteryHistoryRange.DAY) } // Reactive on the device row so a fresh battery reading refetches the window without a manual pull. - val device by db.deviceDao().currentFlow().collectAsState(initial = null) - var samples by remember { mutableStateOf>(emptyList()) } + val device by remember(db) { db.deviceDao().currentFlow() }.collectAsState(initial = null) + // null until the first read: "Not enough data yet" then only shows when it is true. A range + // switch keeps the previous series on screen while the new one loads. + var samples by remember { mutableStateOf?>(null) } LaunchedEffect(range, device?.batteryPercent, device?.updatedAt) { val end = System.currentTimeMillis() @@ -2315,7 +2327,7 @@ private fun BatteryHistorySection(db: PulseLoopDatabase) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text(tr("Battery history"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Battery history"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, modifier = Modifier.weight(1f)) SingleChoiceSegmentedButtonRow { BatteryHistoryRange.entries.forEachIndexed { i, r -> SegmentedButton( @@ -2327,7 +2339,11 @@ private fun BatteryHistorySection(db: PulseLoopDatabase) { } } Spacer(Modifier.height(8.dp)) - if (samples.size < 2) { + val loaded = samples + if (loaded == null) { + // Chart-height placeholder so the card doesn't grow when the samples land. + Spacer(Modifier.height(160.dp)) + } else if (loaded.size < 2) { Text( tr("Not enough data yet — battery history builds up as the ring reports its level."), style = MaterialTheme.typography.bodySmall, @@ -2335,19 +2351,19 @@ private fun BatteryHistorySection(db: PulseLoopDatabase) { ) } else { ZoneLineChart( - samples = samples, + samples = loaded, zones = batteryZones, yDomain = 0.0..100.0, accent = PulseColors.success, height = 160.dp, // Day boundaries on the 7 d view, six-hour marks on 24 h (issue #65). verticalGridlines = com.pulseloop.service.BatteryProjection.gridlines( - startMs = samples.first().timestampMs, - endMs = samples.last().timestampMs, + startMs = loaded.first().timestampMs, + endMs = loaded.last().timestampMs, ), ) Spacer(Modifier.height(10.dp)) - BatteryRuntimeEstimate(samples) + BatteryRuntimeEstimate(loaded) } } } @@ -3558,7 +3574,9 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { verticalAlignment = Alignment.CenterVertically, ) { Text(msg, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f)) - TextButton(onClick = { store.update { it.copy(removalStatus = null) } }) { Text(tr("Dismiss")) } + TextButton(onClick = { store.update { it.copy(removalStatus = null) } }, modifier = Modifier.widthIn(max = 120.dp)) { + Text(tr("Dismiss"), maxLines = 1, overflow = TextOverflow.Ellipsis) + } } } } @@ -3800,14 +3818,16 @@ private fun AutoBackupCard() { trf("Folder: {0}", folderName ?: tr("not chosen")), style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f), ) - TextButton(onClick = { picker.launch(null) }) { Text(if (folderName == null) tr("Choose") else tr("Change")) } + TextButton(onClick = { picker.launch(null) }, modifier = Modifier.widthIn(max = 120.dp)) { + Text(if (folderName == null) tr("Choose") else tr("Change"), maxLines = 1, overflow = TextOverflow.Ellipsis) + } } Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { listOf(1 to "Daily", 7 to "Weekly").forEach { (d, label) -> FilterChip( selected = interval == d, onClick = { interval = d; com.pulseloop.data.AutoBackup.setIntervalDays(context, d) }, - label = { Text(label) }, + label = { Text(tr(label)) }, ) } } 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 2ff79833..5fd30839 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt @@ -110,8 +110,13 @@ fun SleepScreen( SleepRangeSelector(state.range) { viewModel?.setRange(it) } } state.adjustedNote?.let { note -> item { AdjustedCaption(note) } } - if (state.range == SleepRangeKey.DAY) dayItems(state, navController, viewModel) - else aggregateItems(state, navController) + // Every rebuild stamps shownDayMillis, so 0 means the first one hasn't landed yet: render + // nothing rather than flash "No sleep recorded" (and a 1970 date header) for a frame. + val loaded = viewModel == null || state.shownDayMillis != 0L + if (loaded) { + if (state.range == SleepRangeKey.DAY) dayItems(state, navController, viewModel) + else aggregateItems(state, navController) + } item { Spacer(Modifier.height(64.dp)) } } } @@ -367,6 +372,7 @@ private fun SleepRangeSelector(selection: SleepRangeKey, onSelect: (SleepRangeKe fontWeight = FontWeight.SemiBold, color = if (active) PulseColors.textPrimary else PulseColors.textMuted, textAlign = androidx.compose.ui.text.style.TextAlign.Center, + maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier .weight(1f) .heightIn(min = 48.dp) @@ -426,13 +432,20 @@ private fun SleepHeroCard( color = PulseColors.sleep, ) if (scoreLabel != null && score != null) { - Text(scoreLabel, fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary) + // Bounded: a long translated rating word must not squeeze the duration column. + Text( + scoreLabel, fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, + textAlign = androidx.compose.ui.text.style.TextAlign.End, + maxLines = 2, overflow = TextOverflow.Ellipsis, + modifier = Modifier.widthIn(max = 120.dp), + ) } } } } /** Card wrapper for sleep visualizations: eyebrow + title + optional stage legend. */ +@OptIn(ExperimentalLayoutApi::class) @Composable private fun VisualizationCard( eyebrow: String, @@ -460,7 +473,13 @@ private fun VisualizationCard( Text(title, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) } if (legend) { - Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { + // A wrapping legend capped at half the row (weight, fill = false): four translated + // stage names in one unbounded Row squeezed the title to a word per line. + FlowRow( + Modifier.weight(1f, fill = false), + horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { LegendItem(tr("Deep"), PulseColors.stageDeep) LegendItem(tr("Light"), PulseColors.stageLight) LegendItem("REM", PulseColors.stageRem) diff --git a/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt b/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt index 259e604c..e5d03b23 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt @@ -83,6 +83,11 @@ fun TodayGlance( insight: String?, onAlert: () -> Unit, onInsight: (() -> Unit)?, + /** + * The insight is still loading: hold two lines of space for it instead of showing nothing + * (or a "sync your ring" fallback) and then pushing everything below it down. + */ + insightPending: Boolean = false, ) { Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) { if (!alert.isNullOrEmpty()) { @@ -103,12 +108,13 @@ fun TodayGlance( tr("Unusual last night: ") + alert.joinToString(", ") { it.title.lowercase() }, fontSize = 13.sp, color = PulseColors.textPrimary, maxLines = 2, overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), ) } } - insight?.let { + if (insight != null) { Text( - it, + insight, fontSize = 15.sp, lineHeight = 21.sp, color = PulseColors.textSecondary, @@ -119,6 +125,8 @@ fun TodayGlance( .then(if (onInsight != null) Modifier.clickable(onClick = onInsight) else Modifier) .padding(horizontal = 4.dp), ) + } else if (insightPending) { + Text("", fontSize = 15.sp, lineHeight = 21.sp, minLines = 2, modifier = Modifier.fillMaxWidth()) } } } @@ -148,7 +156,13 @@ private fun QuickChip(label: String, icon: ImageVector, tint: Color, modifier: M verticalArrangement = Arrangement.spacedBy(4.dp), ) { Icon(icon, null, Modifier.size(20.dp), tint = tint) - Text(label, fontSize = 12.sp, color = PulseColors.textPrimary, maxLines = 1) + Text( + label, fontSize = 12.sp, color = PulseColors.textPrimary, + // Four equal chips: a long translated label ("Refeição", a voice's rewrite) ellipsises + // inside its quarter rather than clipping mid-letter. + maxLines = 1, overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(horizontal = 4.dp), + ) } } @@ -289,6 +303,7 @@ fun CoachBriefSheet( chips.take(3).forEach { Text( it, fontSize = 12.sp, color = PulseColors.textPrimary, maxLines = 1, + overflow = TextOverflow.Ellipsis, modifier = Modifier .clip(RoundedCornerShape(16.dp)) .background(PulseColors.card) 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 ed856011..9742d441 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt @@ -100,13 +100,20 @@ fun TodayScreen( val hero = remember(state, sleep) { deriveHero(state, sleep) } // Readiness recomputes whenever Today's data or last night's session changes. val db = remember { com.pulseloop.data.PulseLoopDatabase.getInstance(context) } - val readiness = rememberReadiness(db, listOf(state.lastUpdated, sleep.lastNight?.id, sleep.lastNight?.updatedAt)) - val activityScore = rememberActivityScore(db, listOf(state.lastUpdated, state.steps)) + val readinessLoad = rememberReadinessLoad(db, listOf(state.lastUpdated, sleep.lastNight?.id, sleep.lastNight?.updatedAt)) + val readiness = readinessLoad.value + val activityLoad = rememberActivityScoreLoad(db, listOf(state.lastUpdated, state.steps)) + val activityScore = activityLoad.value + // Standalone (no view models, e.g. a preview) there is nothing to wait for. + val sleepLoaded = sleepViewModel == null || sleep.loaded + val vitalsLoaded = vitalsViewModel == null || vitals.loaded val guidance = rememberGuidance(db, listOf(state.lastUpdated, sleep.lastNight?.id, sleep.lastNight?.updatedAt)) var mealSheet by remember { mutableStateOf(false) } var briefSheet by remember { mutableStateOf(false) } var tagSheet by remember { mutableStateOf(false) } - // Today's food log, for the Nutrition tile and the midday food moment. + // Today's food log, for the Nutrition tile and the midday food moment. [foodLoaded] tells the + // first load apart from "nothing logged", so the tile doesn't flash 0 kcal before it. + var foodLoaded by remember { mutableStateOf(false) } val food by produceState(null, state.lastUpdated, mealSheet) { value = runCatching { val meals = db.mealEntryDao().byDay(java.time.LocalDate.now().atStartOfDay(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli()) @@ -120,6 +127,7 @@ fun TodayScreen( goalKcal = goal?.intakeCalories, ) }.getOrNull() + foodLoaded = true } val mealsToday = food?.meals // Ring steps calibrated against the phone, only when the user applied it in My Health. @@ -135,9 +143,11 @@ fun TodayScreen( } // Drinks, when the user tracks them: the tile and the morning-after line on Last night. var drinkTick by remember { mutableIntStateOf(0) } - val accuracyOpen by db.accuracyDao().openFlow().collectAsState(initial = null) + var drinksLoaded by remember { mutableStateOf(false) } + val accuracyOpen by remember(db) { db.accuracyDao().openFlow() }.collectAsState(initial = null) val drinks by produceState(null, state.lastUpdated, sleep.lastNight?.id, drinkTick) { value = if (com.pulseloop.service.DrinkPrefs.enabled) runCatching { com.pulseloop.service.DrinksRepository.load(db) }.getOrNull() else null + drinksLoaded = true } // Per-metric visibility + user order (iOS #64), read reactively so a hide/show/reorder @@ -178,9 +188,10 @@ fun TodayScreen( when (card) { DashboardCard.ACTIVITY -> ActivityTileFor(state, units, m, onTap = { navController?.navigate("activity") }, stepFactor = stepFactor) DashboardCard.SLEEP -> SleepTileFor(sleep, m) { navController?.navigate("sleep") } - DashboardCard.NUTRITION -> NutritionTile(food, m, onLog = { mealSheet = true }) { navController?.navigate("nutrition") } - DashboardCard.DRINKS -> TodayTile(label = "Drinks", color = PulseColors.drinks, modifier = m, onTap = { navController?.navigate("drinks") }) { - DrinksTileContent( + DashboardCard.NUTRITION -> NutritionTile(food, foodLoaded, m, onLog = { mealSheet = true }) { navController?.navigate("nutrition") } + DashboardCard.DRINKS -> TodayTile(label = tr("Drinks"), color = PulseColors.drinks, modifier = m, onTap = { navController?.navigate("drinks") }) { + // The empty tile until the first load, not "0 of 14 this week". + if (drinksLoaded) DrinksTileContent( week = drinks?.week, limit = drinks?.weeklyLimit ?: com.pulseloop.service.DrinkPrefs.weeklyLimit, dryTarget = drinks?.dryDaysTarget ?: com.pulseloop.service.DrinkPrefs.dryDaysTarget, @@ -218,6 +229,8 @@ fun TodayScreen( readiness = readiness, sleepScore = sleep.score?.score ?: sleep.lastNight?.score, activity = activityScore, + sleepLoaded = sleepLoaded, + activityLoaded = activityLoad.loaded, onReadiness = { navController?.navigate("readiness") }, onSleep = { navController?.navigate("sleep") }, onActivity = { navController?.navigate("activity_score") }, @@ -232,14 +245,19 @@ fun TodayScreen( item { val alert = guidance?.offSignals?.takeIf { com.pulseloop.service.VitalsCheck.shouldAlert(it) } val summary = state.coachSummary + // Until readiness has loaded, the fallback would be the hero's "sync your ring" copy, + // which flashed on every launch before the real sentence replaced it. + val pending = !(coachEnabled && summary != null) && !readinessLoad.loaded val insight = when { coachEnabled && summary != null -> listOf(summary.title, summary.body).filter { it.isNotBlank() }.joinToString(". ") readiness != null -> com.pulseloop.service.ReadinessCopy.headline(readiness) + pending -> null else -> hero.summary } TodayGlance( alert = alert, insight = insight, + insightPending = pending, onAlert = { navController?.navigate("readiness") }, // The line is cut at three lines; tapping opens the whole brief. onInsight = { briefSheet = true }, @@ -325,7 +343,10 @@ fun TodayScreen( // Three across from 600dp (tablets, unfolded foldables) instead of two stretched tiles. val columns = if (screenWidthDp >= 600) 3 else 2 - val rows = visibleOrdered.chunked(columns) + // No tiles until vitals and sleep have loaded: before that every supports* flag is + // false (the HRV/temperature tiles appear later and reflow the grid) and the tiles + // say "No sleep recorded" / "No data" for data that is merely still being read. + val rows = if (vitalsLoaded && sleepLoaded) visibleOrdered.chunked(columns) else emptyList() // Keyed by the cards in the row so a reorder in edit mode moves rows rather than // recomposing every row in place. items(rows.size, key = { rows[it].joinToString("|") { card -> card.name } }) { rowIndex -> @@ -644,36 +665,42 @@ internal data class FoodTotals( /** Half-width Nutrition tile: calories eaten against the goal, macros, and a one-tap log. */ @Composable -private fun NutritionTile(food: FoodTotals?, modifier: Modifier, onLog: () -> Unit, onTap: () -> Unit) { +private fun NutritionTile(food: FoodTotals?, loaded: Boolean, modifier: Modifier, onLog: () -> Unit, onTap: () -> Unit) { TodayTile(label = tr("Nutrition"), color = PulseColors.calories, modifier = modifier, onTap = onTap) { - val kcal = food?.kcal ?: 0.0 - Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(4.dp)) { - Text(Formats.count(kcal.toInt()), fontSize = 22.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, maxLines = 1) - Text("kcal", fontSize = 11.sp, color = PulseColors.textMuted, modifier = Modifier.padding(bottom = 4.dp)) - } - val goal = food?.goalKcal?.takeIf { it > 0 } - if (goal != null) { - val shape = androidx.compose.foundation.shape.RoundedCornerShape(2.dp) - Box(Modifier.fillMaxWidth().height(6.dp).clip(shape).dither(PulseColors.calories, 0.25f)) { - Box(Modifier.fillMaxWidth((kcal / goal).toFloat().coerceIn(0f, 1f)).fillMaxHeight().background(PulseColors.calories)) - } - Text("of ${Formats.count(goal.toInt())}", fontSize = 11.sp, color = PulseColors.textMuted) - } - Spacer(Modifier.weight(1f)) - if (food != null && food.meals > 0) { - Text( - "P ${food.proteinG.toInt()} · C ${food.carbsG.toInt()} · F ${food.fatG.toInt()} g", - fontSize = 11.sp, color = PulseColors.textSecondary, maxLines = 1, - ) - } else { - Text(tr("Nothing logged yet"), fontSize = 11.sp, color = PulseColors.textMuted, maxLines = 1) + // Before the first load: the bare tile, not "0 kcal · Nothing logged yet". + if (loaded) NutritionTileBody(food, onLog) + } +} + +@Composable +private fun ColumnScope.NutritionTileBody(food: FoodTotals?, onLog: () -> Unit) { + val kcal = food?.kcal ?: 0.0 + Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + Text(Formats.count(kcal.toInt()), fontSize = 22.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, maxLines = 1) + Text("kcal", fontSize = 11.sp, color = PulseColors.textMuted, modifier = Modifier.padding(bottom = 4.dp)) + } + val goal = food?.goalKcal?.takeIf { it > 0 } + if (goal != null) { + val shape = androidx.compose.foundation.shape.RoundedCornerShape(2.dp) + Box(Modifier.fillMaxWidth().height(6.dp).clip(shape).dither(PulseColors.calories, 0.25f)) { + Box(Modifier.fillMaxWidth((kcal / goal).toFloat().coerceIn(0f, 1f)).fillMaxHeight().background(PulseColors.calories)) } + Text(trf("of {0}", Formats.count(goal.toInt())), fontSize = 11.sp, color = PulseColors.textMuted) + } + Spacer(Modifier.weight(1f)) + if (food != null && food.meals > 0) { Text( - "+ Log meal", - fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, - // No min height here: it would stretch the tile and its row. Compose already widens a - // small clickable's hit area towards 48dp. - modifier = Modifier.clickable(role = Role.Button, onClick = onLog).padding(vertical = 2.dp), + "P ${food.proteinG.toInt()} · C ${food.carbsG.toInt()} · F ${food.fatG.toInt()} g", + fontSize = 11.sp, color = PulseColors.textSecondary, maxLines = 1, ) + } else { + Text(tr("Nothing logged yet"), fontSize = 11.sp, color = PulseColors.textMuted, maxLines = 1) } + Text( + tr("+ Log meal"), + fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, + // No min height here: it would stretch the tile and its row. Compose already widens a + // small clickable's hit area towards 48dp. + modifier = Modifier.clickable(role = Role.Button, onClick = onLog).padding(vertical = 2.dp), + ) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/WhatChangedUi.kt b/app/src/main/java/com/pulseloop/ui/screens/WhatChangedUi.kt index 394a7c69..900c4371 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/WhatChangedUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/WhatChangedUi.kt @@ -44,7 +44,9 @@ fun WhatChangedScreen(onBack: () -> Unit) { val today = remember { LocalDate.now() } val from = remember { FindingsRepository.dayKey(today.minusDays(90), zone) } LaunchedEffect(Unit) { runCatching { FindingsRepository.refresh(db) } } - val rows by remember { db.findingDao().sinceFlow(from) }.collectAsState(initial = emptyList()) + // null until Room answers: read as empty, the card claimed "Nothing stood out" for a frame. + val rowsLoaded by remember { db.findingDao().sinceFlow(from) }.collectAsState(initial = null) + val rows = rowsLoaded.orEmpty() val fmt = remember { DateTimeFormatter.ofPattern("EEE d MMM") } Column(Modifier.fillMaxSize().background(PulseColors.background)) { @@ -63,7 +65,9 @@ fun WhatChangedScreen(onBack: () -> Unit) { verticalArrangement = Arrangement.spacedBy(6.dp), ) { Text(tr("LAST 3 DAYS"), fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) - if (recent.isEmpty()) { + if (rowsLoaded == null) { + Spacer(Modifier.height(48.dp)) + } else if (recent.isEmpty()) { Text(tr("Nothing stood out"), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(tr("Your nights look like your usual. That's an answer too."), fontSize = 13.sp, color = PulseColors.textSecondary) } else { @@ -72,7 +76,7 @@ fun WhatChangedScreen(onBack: () -> Unit) { } val older = rows.filter { it.day < recentKey }.groupBy { it.day } if (older.isNotEmpty()) { - Text("EARLIER", fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + Text(tr("EARLIER"), fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) older.forEach { (day, list) -> Column( Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), diff --git a/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt index 250e0e84..ac1a1874 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt @@ -322,9 +322,13 @@ internal fun EditFieldRow(title: String, content: @Composable () -> Unit) { .padding(horizontal = 16.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, ) { - Text(title, fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary) - Spacer(Modifier.weight(1f)) - content() + // The title takes the weight and the control is capped, so neither a long translated + // title nor a long activity/date label can squeeze the other to a sliver. + Text( + title, fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, + modifier = Modifier.weight(1f).padding(end = 8.dp), + ) + Box(Modifier.widthIn(max = 200.dp)) { content() } } } diff --git a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt index f98c9be6..e3485342 100644 --- a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt +++ b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt @@ -253,6 +253,11 @@ class SleepViewModel( val rangeSummary: CoachSummaryEntity? = null, /** Accuracy corrections applied to the time-asleep figures; null = none. */ val adjustedNote: String? = null, + /** + * The first rebuild has finished. Until then `lastNight == null` means "not read yet", not + * "no sleep", so Today shows no "No sleep recorded" / "No data" before the night arrives. + */ + val loaded: Boolean = false, ) private val _state = MutableStateFlow(SleepState()) @@ -274,6 +279,8 @@ class SleepViewModel( db.sleepSessionDao().recentFlow(7).combine(AccuracyCorrections.flow(db)) { sessions, c -> sessions to c }.collect { (sessions, c) -> _state.update { it.copy(recentSessions = sessions.map(c::sleep)) } try { rebuild(_state.value.range) } catch (_: Exception) {} + // Also after a failed rebuild, so the screen falls back to its empty state. + if (!_state.value.loaded) _state.update { it.copy(loaded = true) } } } } @@ -382,6 +389,7 @@ class SleepViewModel( daySummary = daySummary, rangeSummary = rangeSummary, adjustedNote = corrections.describe(setOf(com.pulseloop.health.accuracy.ComparisonMetric.SLEEP_ASLEEP)), + loaded = true, ) } } @@ -455,6 +463,8 @@ class ActivityViewModel(db: PulseLoopDatabase) : ViewModel() { val recentDays: List = emptyList(), /** All finished sessions, newest first (drives Today + the history sheet). */ val finishedWorkouts: List = emptyList(), + /** True once the sessions table has answered, so "no workouts" is only said when it's so. */ + val workoutsLoaded: Boolean = false, val today: ActivityDailyEntity? = null, // ── Day navigation (issue #76 — mirrors SleepViewModel's, iOS #84) ── /** How many days back the shown day is: 0 = today, clamped to [0, maxDayOffset]. */ @@ -530,7 +540,7 @@ class ActivityViewModel(db: PulseLoopDatabase) : ViewModel() { } viewModelScope.launch { db.activitySessionDao().recentFlow(200).collect { sessions -> - _state.update { it.copy(finishedWorkouts = sessions.filter { s -> s.statusRaw == "finished" }) } + _state.update { it.copy(finishedWorkouts = sessions.filter { s -> s.statusRaw == "finished" }, workoutsLoaded = true) } } } viewModelScope.launch { refreshMaxDayOffset() } @@ -687,6 +697,11 @@ class VitalsViewModel(private val db: PulseLoopDatabase, private val apiKeyStore val supportsManualSpo2: Boolean = false, /** Accuracy corrections applied to heart rate and SpO₂ here; null = none. */ val adjustedNote: String? = null, + /** + * The first [buildState] has landed. Until then every series is empty and every supports* + * flag false, which would render "No HR samples yet" and a short card list that then grows. + */ + val loaded: Boolean = false, ) private val _state = MutableStateFlow(VitalsState()) @@ -704,7 +719,8 @@ class VitalsViewModel(private val db: PulseLoopDatabase, private val apiKeyStore // Poll every 5 seconds so data appears as the ring syncs history viewModelScope.launch { while (true) { - try { refresh(db) } catch (_: Exception) {} + // A failed build still ends "loading", so the screen falls back to its empty cards. + try { refresh(db) } catch (_: Exception) { if (!_state.value.loaded) _state.update { it.copy(loaded = true) } } kotlinx.coroutines.delay(5000) } } @@ -717,7 +733,7 @@ class VitalsViewModel(private val db: PulseLoopDatabase, private val apiKeyStore } private suspend fun refresh(db: PulseLoopDatabase) { - _state.value = buildState(db, apiKeyStore) + _state.value = buildState(db, apiKeyStore).copy(loaded = true) } companion object {