From 5595b811d43e570515008a53e6a8fd76e0b8762d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 18:53:49 +0000 Subject: [PATCH 1/5] WIP: four-skill flow audit fixes in progress Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- .../pulseloop/coach/schema/CoachChartView.kt | 132 ----------------- .../coach/schema/CoachResponseView.kt | 134 ------------------ .../com/pulseloop/ui/screens/CoachScreen.kt | 53 +++++-- .../com/pulseloop/ui/screens/RecordScreen.kt | 46 +++--- 4 files changed, 66 insertions(+), 299 deletions(-) delete mode 100644 app/src/main/java/com/pulseloop/coach/schema/CoachChartView.kt delete mode 100644 app/src/main/java/com/pulseloop/coach/schema/CoachResponseView.kt diff --git a/app/src/main/java/com/pulseloop/coach/schema/CoachChartView.kt b/app/src/main/java/com/pulseloop/coach/schema/CoachChartView.kt deleted file mode 100644 index f785c758..00000000 --- a/app/src/main/java/com/pulseloop/coach/schema/CoachChartView.kt +++ /dev/null @@ -1,132 +0,0 @@ -package com.pulseloop.coach.schema - -import com.pulseloop.ui.theme.PulseColors -import androidx.compose.foundation.Canvas -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.* -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.geometry.Size -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.Path -import androidx.compose.ui.graphics.StrokeCap -import androidx.compose.ui.graphics.drawscope.Stroke -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.dp - -/** - * Ported from CoachChartView.swift. - * Renders a CoachChart (line, bar, scatter) using Compose Canvas. - * Data is already embedded by the prepare_chart tool. - */ -@Composable -fun CoachChartView( - chart: CoachChart, - modifier: Modifier = Modifier, - height: Int = 170, -) { - val color = when { - chart.title.contains("HR", ignoreCase = true) || chart.yLabel.contains("bpm", ignoreCase = true) -> PulseColors.heartRate - chart.title.contains("SpO2", ignoreCase = true) || chart.yLabel.contains("%", ignoreCase = true) -> PulseColors.spo2 - chart.title.contains("sleep", ignoreCase = true) -> PulseColors.sleep - chart.title.contains("step", ignoreCase = true) -> PulseColors.steps - else -> MaterialTheme.colorScheme.primary - } - - Column( - modifier = modifier - .fillMaxWidth() - .clip(RoundedCornerShape(8.dp)) - .background(PulseColors.card) - .padding(14.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Text( - chart.title.ifEmpty { "${chart.xLabel} vs ${chart.yLabel}" }, - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - - if (chart.points.isEmpty()) { - Box(Modifier.fillMaxWidth().height(60.dp), contentAlignment = Alignment.Center) { - Text("No data to plot for this range.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - } - } else { - when (chart.chartType.lowercase()) { - "line" -> LineChartPlot(chart, color, height) - "bar" -> BarChartPlot(chart, color, height) - "scatter" -> ScatterPlot(chart, color, height) - else -> LineChartPlot(chart, color, height) - } - } - } -} - -// ── Plot Composables ────────────────────────────────────────────────────── - -@Composable -private fun LineChartPlot(chart: CoachChart, color: Color, height: Int) { - val values = chart.points.map { it.yValue } - Canvas(modifier = Modifier.fillMaxWidth().height(height.dp)) { - if (values.isEmpty()) return@Canvas - val w = size.width; val h = size.height - val min = values.min(); val max = values.max() - val range = if (max - min < 0.01) 1.0 else max - min - val pad = 12f - val stepX = if (values.size > 1) (w - pad * 2) / (values.size - 1) else 0f - - val path = Path() - values.forEachIndexed { i, v -> - val x = if (values.size == 1) w / 2 else pad + i * stepX - val y = pad + (h - pad * 2) * (1f - ((v - min) / range).toFloat()) - if (i == 0) path.moveTo(x, y) else path.lineTo(x, y) - drawCircle(color, 3f, Offset(x, y)) - } - drawPath(path, color, style = Stroke(width = 2f, cap = StrokeCap.Round)) - } -} - -@Composable -private fun BarChartPlot(chart: CoachChart, color: Color, height: Int) { - val values = chart.points.map { it.yValue } - Canvas(modifier = Modifier.fillMaxWidth().height(height.dp)) { - if (values.isEmpty()) return@Canvas - val w = size.width; val h = size.height - val max = values.max() - if (max == 0.0) return@Canvas - val pad = 8f - val barWidth = (w - pad * 2) / values.size * 0.7f - val gap = (w - pad * 2) / values.size * 0.3f - - values.forEachIndexed { i, v -> - val x = pad + i * (barWidth + gap) - val barHeight = (h - pad * 2) * (v / max).toFloat() - drawRect(color.copy(alpha = 0.85f), Offset(x, h - pad - barHeight), Size(barWidth, barHeight)) - } - } -} - -@Composable -private fun ScatterPlot(chart: CoachChart, color: Color, height: Int) { - val values = chart.points.map { it.yValue } - Canvas(modifier = Modifier.fillMaxWidth().height(height.dp)) { - if (values.isEmpty()) return@Canvas - val w = size.width; val h = size.height - val min = values.min(); val max = values.max() - val range = if (max - min < 0.01) 1.0 else max - min - val pad = 12f - val stepX = if (values.size > 1) (w - pad * 2) / (values.size - 1) else 0f - - values.forEachIndexed { i, v -> - val x = if (values.size == 1) w / 2 else pad + i * stepX - val y = pad + (h - pad * 2) * (1f - ((v - min) / range).toFloat()) - drawCircle(color, 6f, Offset(x, y)) - } - } -} diff --git a/app/src/main/java/com/pulseloop/coach/schema/CoachResponseView.kt b/app/src/main/java/com/pulseloop/coach/schema/CoachResponseView.kt deleted file mode 100644 index 8fdee129..00000000 --- a/app/src/main/java/com/pulseloop/coach/schema/CoachResponseView.kt +++ /dev/null @@ -1,134 +0,0 @@ -package com.pulseloop.coach.schema - -import com.pulseloop.ui.theme.dither -import com.pulseloop.ui.theme.PulseColors -import androidx.compose.foundation.background -import androidx.compose.foundation.horizontalScroll -import androidx.compose.foundation.layout.* -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Info -import androidx.compose.material.icons.filled.Warning -import androidx.compose.material3.* -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.pulseloop.ui.components.SimpleLineChart - -/** - * Ported from CoachResponseView.swift. - * Renders a decoded CoachResponse as the assistant bubble's content: - * title, summary, bullets, embedded chart, safety notes, sources, follow-up chips. - */ -@Composable -fun CoachResponseView( - response: CoachResponse, - onChipTap: ((String) -> Unit)? = null, -) { - Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { - // Title - if (response.title.isNotEmpty()) { - Text( - text = response.title, - style = MaterialTheme.typography.titleSmall, - fontWeight = FontWeight.SemiBold, - color = MaterialTheme.colorScheme.onSurface, - ) - } - - // Summary - if (response.summary.isNotEmpty()) { - Text( - text = response.summary, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurface, - ) - } - - // Bullets - if (response.bullets.isNotEmpty()) { - Column(verticalArrangement = Arrangement.spacedBy(5.dp)) { - response.bullets.forEach { bullet -> - Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.Top) { - Text("•", color = MaterialTheme.colorScheme.primary) - Text(bullet, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - } - } - } - } - - // Chart (rendered in CoachChartView) - if (response.chart != null) { - CoachChartView(chart = response.chart!!) - } - - // Safety note - response.safetyNote?.takeIf { it.isNotEmpty() }?.let { note -> - NoteRow(icon = { Icon(Icons.Filled.Warning, null, tint = PulseColors.warning) }, text = note, tone = PulseColors.warning) - } - - // Data quality note - response.dataQualityNote?.takeIf { it.isNotEmpty() }?.let { note -> - NoteRow(icon = { Icon(Icons.Filled.Info, null, tint = MaterialTheme.colorScheme.onSurfaceVariant) }, text = note, tone = MaterialTheme.colorScheme.onSurfaceVariant) - } - - // Sources - if (response.sources.isNotEmpty()) { - Column(verticalArrangement = Arrangement.spacedBy(3.dp)) { - Text( - "SOURCES", - style = MaterialTheme.typography.labelSmall, - fontWeight = FontWeight.SemiBold, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - response.sources.forEach { source -> - Text( - "${source.title} — ${source.publisher}", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.primary, - ) - } - } - } - - // Follow-up chips - if (response.followUpChips.isNotEmpty()) { - Row( - modifier = Modifier.horizontalScroll(rememberScrollState()), - horizontalArrangement = Arrangement.spacedBy(6.dp), - ) { - response.followUpChips.forEach { chip -> - SuggestionChip( - onClick = { onChipTap?.invoke(chip) }, - label = { Text(chip, fontSize = 12.sp) }, - ) - } - } - } - } -} - -@Composable -private fun NoteRow( - icon: @Composable () -> Unit, - text: String, - tone: Color, -) { - Row( - modifier = Modifier - .fillMaxWidth() - .dither(tone, 0.1f, RoundedCornerShape(4.dp)) - .padding(10.dp), - horizontalArrangement = Arrangement.spacedBy(6.dp), - verticalAlignment = Alignment.Top, - ) { - icon() - Text(text, style = MaterialTheme.typography.bodySmall, color = tone) - } -} 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 e6c7e3cb..be9d72d5 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt @@ -26,6 +26,8 @@ import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.AddPhotoAlternate +import androidx.compose.material.icons.outlined.Flag import androidx.compose.material.icons.filled.ArrowUpward import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Info @@ -59,6 +61,7 @@ import kotlinx.coroutines.launch import com.pulseloop.coach.attachments.CoachAttachmentStore import com.pulseloop.ui.components.MarkdownLite import com.pulseloop.ui.theme.PulseColors +import com.pulseloop.ui.theme.PulseType import com.pulseloop.ui.viewmodels.CoachViewModel /** @@ -125,7 +128,7 @@ fun CoachScreen( start = 16.dp, end = 16.dp, top = topBarPadding + 8.dp, bottom = 8.dp, ), - verticalArrangement = Arrangement.spacedBy(10.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), ) { // The goal the coach plans around, or the prompt to set one. item { @@ -157,7 +160,7 @@ fun CoachScreen( Text( tr("Coach is thinking…"), fontSize = 12.sp, color = PulseColors.textMuted, - modifier = Modifier.padding(start = 8.dp), + modifier = Modifier.padding(start = 8.dp).semantics { liveRegion = LiveRegionMode.Polite }, ) } } @@ -222,7 +225,7 @@ fun CoachHeader(onNewChat: () -> Unit, onOpenUsage: (() -> Unit)? = null, onBack .padding(top = 9.dp, end = 9.dp) .size(6.dp) .clip(CircleShape) - .background(Color.White.copy(alpha = 0.9f)), + .background(PulseColors.onAccent.copy(alpha = 0.9f)), ) } Column(Modifier.weight(1f)) { @@ -277,7 +280,6 @@ private fun RoundIconTarget( @Composable private fun MessageBubble(msg: CoachViewModel.ChatMessage, viewModel: CoachViewModel?) { val isUser = msg.role == "user" - val ctx = LocalContext.current Column( Modifier.fillMaxWidth(), horizontalAlignment = if (isUser) Alignment.End else Alignment.Start, @@ -302,10 +304,10 @@ private fun MessageBubble(msg: CoachViewModel.ChatMessage, viewModel: CoachViewM if (msg.attachments.isNotEmpty()) { Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { msg.attachments.forEach { ref -> - val bmp = remember(ref.file) { CoachAttachmentStore.loadBitmap(ctx, ref) } + val bmp = rememberAttachmentBitmap(ref) bmp?.let { Image( - bitmap = it.asImageBitmap(), + bitmap = it, contentDescription = tr("Attached photo"), modifier = Modifier.size(96.dp).clip(RoundedCornerShape(4.dp)), contentScale = ContentScale.Crop, @@ -431,10 +433,10 @@ private fun Composer( ) { staged.forEach { ref -> Box { - val bmp = remember(ref.file) { CoachAttachmentStore.loadBitmap(ctx, ref) } + val bmp = rememberAttachmentBitmap(ref) bmp?.let { Image( - bitmap = it.asImageBitmap(), + bitmap = it, contentDescription = tr("Staged photo"), modifier = Modifier.size(56.dp).clip(RoundedCornerShape(4.dp)), contentScale = ContentScale.Crop, @@ -452,7 +454,12 @@ private fun Composer( }, contentAlignment = Alignment.TopEnd, ) { - Icon(Icons.Filled.Close, tr("Remove photo"), Modifier.padding(3.dp).size(14.dp), tint = Color.White) + // A scrim behind the glyph, so it reads on a bright photo too. + Icon( + Icons.Filled.Close, tr("Remove photo"), + Modifier.padding(4.dp).size(16.dp).clip(CircleShape).background(PulseColors.background.copy(alpha = 0.7f)), + tint = PulseColors.textPrimary, + ) } } } @@ -478,7 +485,8 @@ private fun Composer( enabled = !isThinking, onClick = { pickImage.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) }, ) { - Icon(Icons.Filled.Add, tr("Attach photo"), tint = PulseColors.textMuted, modifier = Modifier.size(20.dp)) + // Its own glyph: in landscape it sits beside New chat's "+". + Icon(Icons.Filled.AddPhotoAlternate, tr("Attach photo"), tint = PulseColors.textMuted, modifier = Modifier.size(20.dp)) } } // Pill text field (iOS composer): filled capsule, no outline. @@ -557,15 +565,15 @@ private fun GoalBanner( .clip(shape) .background(PulseColors.card) .border(1.dp, if (hasGoal) PulseColors.accent else PulseColors.borderSubtle, shape) - .clickable(enabled = enabled) { if (hasGoal) onCheckIn() else onSetGoal() } - .padding(horizontal = 14.dp, vertical = 12.dp), + .clickable(enabled = enabled, role = Role.Button) { if (hasGoal) onCheckIn() else onSetGoal() } + .padding(horizontal = 16.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(10.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), ) { - Text("◎", fontSize = 16.sp, color = PulseColors.accent) + Icon(Icons.Outlined.Flag, contentDescription = null, tint = PulseColors.accent, modifier = Modifier.size(20.dp)) Column(Modifier.weight(1f)) { if (hasGoal && plan != null) { - Text(tr("YOUR GOAL"), fontSize = 12.sp, letterSpacing = 1.4.sp, color = PulseColors.accent) + Text(tr("YOUR GOAL"), style = PulseType.eyebrow, color = PulseColors.textSecondary) Text(com.pulseloop.service.GoalPlan.headline(plan), fontSize = 14.sp, color = PulseColors.textPrimary, maxLines = 2) Text(com.pulseloop.service.GoalPlan.focusLine(plan) + tr(" · tap for this week's plan"), fontSize = 12.sp, color = PulseColors.textSecondary, maxLines = 2) } else { @@ -575,3 +583,18 @@ private fun GoalBanner( } } } + +/** + * A coach photo, decoded off the main thread: a full chat of photos decoded in composition + * dropped frames on every scroll (audit, v2.11.58, carried). + */ +@Composable +private fun rememberAttachmentBitmap(ref: CoachAttachmentRef): androidx.compose.ui.graphics.ImageBitmap? { + val ctx = LocalContext.current + val bmp by produceState(null, ref.file) { + value = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { + CoachAttachmentStore.loadBitmap(ctx, ref)?.asImageBitmap() + } + } + return bmp +} 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 f0509a94..f619c9de 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/RecordScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/RecordScreen.kt @@ -7,8 +7,8 @@ import com.pulseloop.ui.components.PulseButton import com.pulseloop.ui.theme.PulseColors import androidx.activity.compose.BackHandler import androidx.compose.foundation.layout.* -import androidx.compose.foundation.lazy.grid.GridCells -import androidx.compose.foundation.lazy.grid.LazyVerticalGrid +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* import androidx.compose.material3.* @@ -24,6 +24,7 @@ import com.pulseloop.service.HeartRateZones import com.pulseloop.settings.UnitConverter import com.pulseloop.settings.UnitSystem import com.pulseloop.ui.components.ActivityMeta +import com.pulseloop.ui.theme.PulseType import kotlinx.coroutines.delay /** @@ -82,6 +83,9 @@ fun RecordScreen( } Column(Modifier.fillMaxSize().padding(16.dp)) { + // Everything above the buttons scrolls, so landscape (or a large font) can still reach the + // stat tiles; Pause / Finish stay pinned at the bottom. + Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState())) { // Activity name + status Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { // Weighted (fill = false) so a long translated name wraps instead of pushing PAUSED off. @@ -99,7 +103,7 @@ fun RecordScreen( // Large elapsed + HR Card(Modifier.fillMaxWidth(), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)) { - Column(Modifier.padding(20.dp), horizontalAlignment = Alignment.CenterHorizontally) { + Column(Modifier.padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally) { Text(elapsed, fontSize = 40.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Spacer(Modifier.height(4.dp)) val hrText = heartRate?.let { "$it bpm" } ?: "-- bpm" @@ -120,24 +124,30 @@ fun RecordScreen( // Stat tiles — GPS tiles only for GPS sessions, matching iOS (`if session.useGps`); // iOS has no live calories tile, so the permanent "--" placeholder is dropped. - LazyVerticalGrid(columns = GridCells.Fixed(2), horizontalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + // A plain two-column grid (at most three tiles), not a LazyVerticalGrid: a lazy grid can't + // sit inside the scrolling column above. + val tiles = buildList { if (useGps && metricSet.showsDistance) { - item { - val distText = if (units == UnitSystem.METRIC && distanceMeters < 1000) { - "%.0f m".format(distanceMeters) - } else { - "%.2f %s".format(UnitConverter.distance(distanceMeters, units), UnitConverter.distanceUnit(units)) - } - StatTile(tr("Distance"), distText) + val distText = if (units == UnitSystem.METRIC && distanceMeters < 1000) { + "%.0f m".format(distanceMeters) + } else { + "%.2f %s".format(UnitConverter.distance(distanceMeters, units), UnitConverter.distanceUnit(units)) } + add(tr("Distance") to distText) } - if (useGps && (metricSet.showsPace || metricSet.showsSpeed)) { - item { StatTile(paceOrSpeedLabel, paceOrSpeedValue) } + if (useGps && (metricSet.showsPace || metricSet.showsSpeed)) add(paceOrSpeedLabel to paceOrSpeedValue) + add(tr("SpO₂") to (spO2?.let { "$it%" } ?: "--")) + } + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + tiles.chunked(2).forEach { row -> + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { + row.forEach { (label, value) -> Box(Modifier.weight(1f)) { StatTile(label, value) } } + if (row.size == 1) Spacer(Modifier.weight(1f)) + } } - item { StatTile(tr("SpO₂"), spO2?.let { "$it%" } ?: "--") } } - - Spacer(Modifier.weight(1f)) + Spacer(Modifier.height(16.dp)) + } // Action buttons Row(Modifier.fillMaxWidth().padding(bottom = 16.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) { @@ -166,8 +176,8 @@ fun RecordScreen( @Composable private fun StatTile(label: String, value: String) { Card(Modifier.fillMaxWidth()) { - Column(Modifier.padding(14.dp)) { - Text(label.uppercase(), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Column(Modifier.padding(16.dp)) { + Text(label.uppercase(), style = PulseType.eyebrow, color = PulseColors.textSecondary) Spacer(Modifier.height(4.dp)) Text(value, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.SemiBold) } From 0557bf87f860dcda7986823584ffda12ef83fe04 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 18:56:52 +0000 Subject: [PATCH 2/5] WIP: four-skill flow audit fixes (Today, header, My Health) Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- .../coach/schema/CoachToolTraceView.kt | 8 +- .../java/com/pulseloop/ui/PulseLoopApp.kt | 13 +- .../pulseloop/ui/components/ActivityMeta.kt | 33 ++++ .../com/pulseloop/ui/components/AppChrome.kt | 42 +---- .../pulseloop/ui/components/DeviceHeroCard.kt | 16 +- .../ui/components/DeviceHeroStatus.kt | 2 +- .../ui/components/PairingComponents.kt | 6 +- .../ui/components/SettingsComponents.kt | 20 +-- .../com/pulseloop/ui/components/TodayTiles.kt | 77 +------- .../pulseloop/ui/screens/ActivityScreen.kt | 36 ++-- .../ui/screens/BarcodeScannerScreen.kt | 44 ++--- .../java/com/pulseloop/ui/screens/DrinksUi.kt | 60 ++++--- .../java/com/pulseloop/ui/screens/FoodUi.kt | 13 +- .../com/pulseloop/ui/screens/GuidanceUi.kt | 38 ++-- .../java/com/pulseloop/ui/screens/LogSheet.kt | 12 +- .../pulseloop/ui/screens/MealAnalysisSheet.kt | 55 +++--- .../com/pulseloop/ui/screens/MyHealthUi.kt | 26 +-- .../pulseloop/ui/screens/NutritionScreen.kt | 55 ++++-- .../pulseloop/ui/screens/OnboardingScreen.kt | 113 ++++++------ .../com/pulseloop/ui/screens/PairingScreen.kt | 57 +++--- .../com/pulseloop/ui/screens/ReadinessUi.kt | 13 +- .../java/com/pulseloop/ui/screens/Screens.kt | 165 +++++++++++------- .../pulseloop/ui/screens/SettingsScreen.kt | 20 ++- .../ui/screens/SettingsSubScreens.kt | 74 ++++---- .../com/pulseloop/ui/screens/SleepScreen.kt | 104 +++++------ .../com/pulseloop/ui/screens/TodayGlance.kt | 52 +++--- .../com/pulseloop/ui/screens/TodayPrograms.kt | 10 +- .../com/pulseloop/ui/screens/TodayScreen.kt | 7 +- .../com/pulseloop/ui/screens/WhatChangedUi.kt | 6 +- .../java/com/pulseloop/update/UpdateUi.kt | 10 +- 30 files changed, 600 insertions(+), 587 deletions(-) diff --git a/app/src/main/java/com/pulseloop/coach/schema/CoachToolTraceView.kt b/app/src/main/java/com/pulseloop/coach/schema/CoachToolTraceView.kt index f38516de..0809c749 100644 --- a/app/src/main/java/com/pulseloop/coach/schema/CoachToolTraceView.kt +++ b/app/src/main/java/com/pulseloop/coach/schema/CoachToolTraceView.kt @@ -46,7 +46,7 @@ fun CoachToolTraceDisclosure(messageId: String, viewModel: CoachViewModel?) { horizontalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.heightIn(min = 48.dp).clickable(role = androidx.compose.ui.semantics.Role.Button) { expanded = !expanded }, ) { - Icon(Icons.Filled.Build, null, tint = PulseColors.textMuted, modifier = Modifier.size(11.dp)) + Icon(Icons.Filled.Build, null, tint = PulseColors.textMuted, modifier = Modifier.size(12.dp)) Text( collapsedLabel(calls), fontSize = 12.sp, color = PulseColors.textMuted, @@ -54,14 +54,14 @@ fun CoachToolTraceDisclosure(messageId: String, viewModel: CoachViewModel?) { ) Icon( if (expanded) Icons.Filled.KeyboardArrowUp else Icons.Filled.KeyboardArrowDown, - null, tint = PulseColors.textMuted, modifier = Modifier.size(14.dp), + null, tint = PulseColors.textMuted, modifier = Modifier.size(16.dp), ) } AnimatedVisibility( visible = expanded, - enter = expandVertically(tween(180)), - exit = shrinkVertically(tween(180)), + enter = expandVertically(tween(com.pulseloop.ui.theme.Motion.EMPHASIS_MS, easing = com.pulseloop.ui.theme.Motion.ease)), + exit = shrinkVertically(tween(com.pulseloop.ui.theme.Motion.STANDARD_MS, easing = com.pulseloop.ui.theme.Motion.ease)), ) { Column( verticalArrangement = Arrangement.spacedBy(6.dp), diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index b273f2ad..a2b89fe3 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -416,7 +416,7 @@ fun PulseLoopApp() { backgroundColor = com.pulseloop.ui.theme.PulseColors.background, tints = listOf( dev.chrisbanes.haze.HazeTint(com.pulseloop.ui.theme.PulseColors.background.copy(alpha = 0.42f)), - dev.chrisbanes.haze.HazeTint(Color.White.copy(alpha = 0.04f)), + dev.chrisbanes.haze.HazeTint(com.pulseloop.ui.theme.PulseColors.textPrimary.copy(alpha = 0.04f)), ), blurRadius = 24.dp, noiseFactor = 0.02f, @@ -433,8 +433,11 @@ fun PulseLoopApp() { // blinking with the screen change. androidx.compose.animation.AnimatedVisibility( visible = showLogFab, - enter = androidx.compose.animation.scaleIn() + androidx.compose.animation.fadeIn(), - exit = androidx.compose.animation.scaleOut() + androidx.compose.animation.fadeOut(), + // The system's durations and ease (theme/Motion.kt), not Compose's default springs. + enter = androidx.compose.animation.scaleIn(androidx.compose.animation.core.tween(com.pulseloop.ui.theme.Motion.EMPHASIS_MS, easing = com.pulseloop.ui.theme.Motion.ease)) + + androidx.compose.animation.fadeIn(androidx.compose.animation.core.tween(com.pulseloop.ui.theme.Motion.EMPHASIS_MS, easing = com.pulseloop.ui.theme.Motion.ease)), + exit = androidx.compose.animation.scaleOut(androidx.compose.animation.core.tween(com.pulseloop.ui.theme.Motion.STANDARD_MS, easing = com.pulseloop.ui.theme.Motion.ease)) + + androidx.compose.animation.fadeOut(androidx.compose.animation.core.tween(com.pulseloop.ui.theme.Motion.STANDARD_MS, easing = com.pulseloop.ui.theme.Motion.ease)), ) { ExtendedFloatingActionButton( onClick = { LaunchRequests.openLog.value = com.pulseloop.ui.screens.LogStep.MENU }, @@ -590,8 +593,8 @@ fun PulseLoopApp() { Icon( if (selected) tab.selectedIcon else tab.unselectedIcon, contentDescription = tab.label, - tint = if (selected) MaterialTheme.colorScheme.primary - else MaterialTheme.colorScheme.onSurfaceVariant, + tint = if (selected) com.pulseloop.ui.theme.PulseColors.accent + else com.pulseloop.ui.theme.PulseColors.textMuted, ) } } diff --git a/app/src/main/java/com/pulseloop/ui/components/ActivityMeta.kt b/app/src/main/java/com/pulseloop/ui/components/ActivityMeta.kt index 77f70bcf..5de3f1ca 100644 --- a/app/src/main/java/com/pulseloop/ui/components/ActivityMeta.kt +++ b/app/src/main/java/com/pulseloop/ui/components/ActivityMeta.kt @@ -34,6 +34,7 @@ object ActivityMeta { "yoga" -> tr("Yoga") "dance" -> tr("Dance") "hike" -> tr("Hiking") + "other" -> tr("Other") else -> type.replaceFirstChar { it.uppercase() } } @@ -127,3 +128,35 @@ object ActivityMeta { else "%.1f".format(mps * 3.6) to "KM/H" } } + +/** + * Times and dates in the phone's own format: the clock follows the system 12/24-hour setting and + * the dates follow the locale's own order and month names (a pattern like "MMM d" or "h:mm a" + * forced English order and a 12-hour clock on everyone). + */ +object PhoneFormat { + /** "07:42" or "7:42 AM", as the phone's clock setting says. */ + fun clock(context: android.content.Context, epochMillis: Long): String = + clock(android.text.format.DateFormat.is24HourFormat(context), epochMillis) + + /** The same, for code that read the 12/24-hour setting once already. Built the way the + * platform's own `DateFormat.getTimeFormat` builds it. */ + fun clock(is24Hour: Boolean, epochMillis: Long): String { + val locale = java.util.Locale.getDefault() + val pattern = android.text.format.DateFormat.getBestDateTimePattern(locale, if (is24Hour) "Hm" else "hm") + return java.text.SimpleDateFormat(pattern, locale).format(java.util.Date(epochMillis)) + } + + /** + * A date from a skeleton ("EEEMMMd", "yMMMd", "EEEE", "EEEEMMMMd"), arranged the locale's way: + * "Wed, Nov 4" in English, "qua., 4 de nov." in Portuguese. + */ + fun date(skeleton: String, date: java.time.temporal.TemporalAccessor): String { + val locale = java.util.Locale.getDefault() + val pattern = android.text.format.DateFormat.getBestDateTimePattern(locale, skeleton) + return java.time.format.DateTimeFormatter.ofPattern(pattern, locale).format(date) + } + + fun date(skeleton: String, epochMillis: Long): String = + date(skeleton, java.time.Instant.ofEpochMilli(epochMillis).atZone(java.time.ZoneId.systemDefault())) +} 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 a719d81f..d9134296 100644 --- a/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt +++ b/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt @@ -236,52 +236,14 @@ fun greetingForHour(): String = when (Calendar.getInstance().get(Calendar.HOUR_O else -> tr("Good night") } -/** - * The iOS card eyebrow: colored dot + letterspaced ALL-CAPS label, with an optional - * trailing slot (e.g. "Updated 5m ago", a legend, or a chip). Matches VitalCard's - * header so hand-built tiles read identically to the vitals cards. - */ -@Composable -fun CardEyebrow( - label: String, - dotColor: Color, - modifier: Modifier = Modifier, - trailing: (@Composable () -> Unit)? = null, -) { - Row( - modifier = modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - Box( - Modifier - .size(8.dp) - .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(), - style = PulseType.eyebrow, - color = PulseColors.textSecondary, - maxLines = 2, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), - ) - trailing?.let { Box(Modifier.widthIn(max = 180.dp)) { it() } } - } -} - /** Uppercase letterspaced section header used between card groups (RootViews `SectionHeader`). */ @Composable fun SectionHeaderCaps(title: String, modifier: Modifier = Modifier, action: (@Composable () -> Unit)? = null) { Row(modifier = modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { Text( title.uppercase(), - fontSize = 14.sp, - fontWeight = FontWeight.SemiBold, - letterSpacing = 1.sp, + // The one eyebrow style (12sp, 1sp tracking), not a hand-rolled 14sp variant. + style = PulseType.eyebrow, color = PulseColors.textSecondary, // Takes the free width (instead of a Spacer) so a long title wraps beside the action. modifier = Modifier.weight(1f), 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 9af9c9af..9e01c22f 100644 --- a/app/src/main/java/com/pulseloop/ui/components/DeviceHeroCard.kt +++ b/app/src/main/java/com/pulseloop/ui/components/DeviceHeroCard.kt @@ -18,7 +18,6 @@ import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight import androidx.compose.material.icons.filled.BatteryFull import androidx.compose.material3.Icon import androidx.compose.material3.Text @@ -76,8 +75,8 @@ fun DeviceHeroCard( .clip(RoundedCornerShape(8.dp)) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(8.dp)) - .padding(18.dp), - verticalArrangement = Arrangement.spacedBy(10.dp), + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), ) { Row( Modifier @@ -93,7 +92,7 @@ fun DeviceHeroCard( Column( Modifier.weight(1f), - verticalArrangement = Arrangement.spacedBy(5.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), ) { Text( status.title, @@ -123,7 +122,7 @@ fun DeviceHeroCard( Column( horizontalAlignment = Alignment.End, - verticalArrangement = Arrangement.spacedBy(14.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), ) { status.batteryText?.let { batteryText -> // Tinted by level: always green read "fine" at 5%. @@ -156,12 +155,7 @@ fun DeviceHeroCard( ) } } - Icon( - Icons.AutoMirrored.Filled.KeyboardArrowRight, - contentDescription = null, // the row's click label says it - modifier = Modifier.size(20.dp), - tint = PulseColors.textMuted, - ) + Chevron() // the row's click label says it } } diff --git a/app/src/main/java/com/pulseloop/ui/components/DeviceHeroStatus.kt b/app/src/main/java/com/pulseloop/ui/components/DeviceHeroStatus.kt index 774237b7..cbcefa9e 100644 --- a/app/src/main/java/com/pulseloop/ui/components/DeviceHeroStatus.kt +++ b/app/src/main/java/com/pulseloop/ui/components/DeviceHeroStatus.kt @@ -109,7 +109,7 @@ data class DeviceHeroStatus( fun relativeShort(fromMillis: Long, nowMillis: Long): String { val seconds = ((nowMillis - fromMillis) / 1000).coerceAtLeast(0) return when { - seconds < 60 -> "just now" + seconds < 60 -> tr("just now") seconds < 3_600 -> trf("{0}m ago", seconds / 60) seconds < 86_400 -> trf("{0}h ago", seconds / 3_600) else -> trf("{0}d ago", seconds / 86_400) 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 39217250..ed92d3a7 100644 --- a/app/src/main/java/com/pulseloop/ui/components/PairingComponents.kt +++ b/app/src/main/java/com/pulseloop/ui/components/PairingComponents.kt @@ -58,7 +58,7 @@ fun PrimaryButton( ), ) { if (icon != null) { - Icon(icon, contentDescription = null, Modifier.size(18.dp)) + Icon(icon, contentDescription = null, Modifier.size(20.dp)) Spacer(Modifier.width(8.dp)) } // Centered: a long translated title wraps to two lines inside the full-width button. @@ -89,7 +89,7 @@ fun SecondaryButton( ), ) { if (icon != null) { - Icon(icon, contentDescription = null, Modifier.size(18.dp), tint = PulseColors.textSecondary) + Icon(icon, contentDescription = null, Modifier.size(20.dp), tint = PulseColors.textSecondary) Spacer(Modifier.width(8.dp)) } // Centered: a long translated title wraps to two lines inside the full-width button. @@ -108,7 +108,7 @@ fun CapabilityChips(blurb: String, modifier: Modifier = Modifier) { modifier = modifier .fillMaxWidth() .horizontalScroll(rememberScrollState()), - horizontalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterHorizontally), + horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally), verticalAlignment = Alignment.CenterVertically, ) { chips.forEach { chip -> 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 e1ce45ac..f99b9a70 100644 --- a/app/src/main/java/com/pulseloop/ui/components/SettingsComponents.kt +++ b/app/src/main/java/com/pulseloop/ui/components/SettingsComponents.kt @@ -16,8 +16,6 @@ import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.Text @@ -56,11 +54,10 @@ data class SettingsRowItem( fun SettingsSection(title: String, rows: List) { if (rows.isEmpty()) return Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) { + // The design system's one tracked caps label (PulseType.eyebrow), not a hand-rolled one. Text( title.uppercase(), - fontSize = 14.sp, - fontWeight = FontWeight.SemiBold, - letterSpacing = 1.sp, + style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary, modifier = Modifier.padding(start = 16.dp), ) @@ -100,16 +97,16 @@ fun SettingsRow(item: SettingsRowItem) { .heightIn(min = 52.dp) .padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(14.dp), + horizontalArrangement = Arrangement.spacedBy(16.dp), ) { Box( Modifier - .size(34.dp) + .size(32.dp) .clip(RoundedCornerShape(4.dp)) .dither(item.tint, 0.14f), contentAlignment = Alignment.Center, ) { - Icon(item.icon, contentDescription = null, Modifier.size(18.dp), tint = item.tint) + Icon(item.icon, contentDescription = null, Modifier.size(20.dp), tint = item.tint) } // The title takes the free width (it used to be unweighted beside a weighted Spacer, so a @@ -132,11 +129,6 @@ fun SettingsRow(item: SettingsRowItem) { ) } - Icon( - Icons.AutoMirrored.Filled.KeyboardArrowRight, - contentDescription = null, - modifier = Modifier.size(18.dp), - tint = PulseColors.textMuted, - ) + Chevron() } } 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 78dc71f0..c70a6e32 100644 --- a/app/src/main/java/com/pulseloop/ui/components/TodayTiles.kt +++ b/app/src/main/java/com/pulseloop/ui/components/TodayTiles.kt @@ -121,7 +121,7 @@ fun TodayTile( .clip(shape) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, shape) - .then(if (onTap != null) Modifier.clickable(interactionSource = press, indication = androidx.compose.foundation.LocalIndication.current, onClick = onTap) else Modifier) + .then(if (onTap != null) Modifier.clickable(interactionSource = press, indication = androidx.compose.foundation.LocalIndication.current, role = Role.Button, onClick = onTap) else Modifier) .padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { @@ -379,7 +379,7 @@ fun SleepTile( tint = PulseColors.sleep.copy(alpha = 0.7f), modifier = Modifier.size(24.dp), ) - Spacer(Modifier.height(6.dp)) + Spacer(Modifier.height(8.dp)) Text( tr("No sleep recorded"), fontSize = 14.sp, @@ -391,81 +391,12 @@ fun SleepTile( } } -// ─────────────────── Hero insight + coach message cards ─────────────────── +// ─────────────────── Coach message card, and the brief's chips ─────────────────── enum class ChipTone { NEUTRAL, UP, DOWN, WARN } data class ToneChip(val label: String, val tone: ChipTone) -private fun ChipTone.foreground() = when (this) { - ChipTone.NEUTRAL -> PulseColors.textSecondary - ChipTone.UP -> PulseColors.success - ChipTone.DOWN -> PulseColors.danger - ChipTone.WARN -> PulseColors.warning -} - -/** The chip's wash: its tone colour dithered, never a translucent shade. */ -private fun ChipTone.ditherColor() = when (this) { - ChipTone.NEUTRAL -> PulseColors.textPrimary - ChipTone.UP -> PulseColors.success - ChipTone.DOWN -> PulseColors.danger - ChipTone.WARN -> PulseColors.warning -} - -private fun ChipTone.border() = when (this) { - ChipTone.NEUTRAL -> PulseColors.borderSubtle - else -> foreground().copy(alpha = 0.30f) -} - -/** 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) - Column( - modifier - .fillMaxWidth() - .clip(shape) - .background(PulseColors.card) - .ditherFade(PulseColors.accent, 0.18f, 0.06f) - .border(1.dp, PulseColors.borderSubtle, shape) - .padding(20.dp), - ) { - Text(title, fontSize = 28.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) - Text( - summary, - fontSize = 16.sp, - lineHeight = 21.sp, - color = PulseColors.textSecondary, - modifier = Modifier.padding(top = 8.dp), - ) - if (chips.isNotEmpty()) { - // Wraps: three translated chips ("Linha de base pendente", …) overflow one line. - FlowRow( - Modifier.padding(top = 16.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - chips.forEach { chip -> - Text( - chip.label, - fontSize = 12.sp, - 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) - .border(1.dp, chip.tone.border(), CircleShape) - .padding(horizontal = 12.dp, vertical = 4.dp), - ) - } - } - } - } -} - /** Full-width coach card (COACH eyebrow, headline, body, chips) — CoachMessageCard in Swift. */ @OptIn(ExperimentalLayoutApi::class) @Composable @@ -484,7 +415,7 @@ fun CoachMessageCard( .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, shape) .then(if (onTap != null) Modifier.clickable(role = Role.Button, onClick = onTap) else Modifier) - .padding(20.dp), + .padding(16.dp), ) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { Box( 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 abc1231a..98d72aa4 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt @@ -77,7 +77,10 @@ import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.Calendar -private val weekLabels = listOf("M", "T", "W", "T", "F", "S", "S") +/** Monday..Sunday initials in the phone's language ("M T W…" / "S T Q…"), not always English. */ +private fun weekLabels(): List = java.time.DayOfWeek.values().map { + it.getDisplayName(java.time.format.TextStyle.NARROW, java.util.Locale.getDefault()) +} /** * Activity dashboard — ported from ActivityView.swift: the daily summary card (colored stats + @@ -150,7 +153,7 @@ fun ActivityScreen( val todayIdx = ((Calendar.getInstance().get(Calendar.DAY_OF_WEEK) - 1) + 6) % 7 // recentDays is newest-first; index 0..6 = Monday..Sunday of this week's steps. val stepsByWeekday = weeklySteps(state, todayIdx) - val days = weekLabels.mapIndexed { i, label -> + val days = weekLabels().mapIndexed { i, label -> WeeklyDay(label, completed = (stepsByWeekday[i] ?: 0) >= state.stepGoal, isToday = i == todayIdx) } @@ -205,7 +208,7 @@ fun ActivityScreen( .clip(RoundedCornerShape(8.dp)) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(8.dp)) - .padding(vertical = 20.dp), + .padding(vertical = 24.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp), ) { @@ -372,9 +375,9 @@ private fun dayHeaderLabel(dayMillis: Long): String { return when { daysAgo <= 0 -> tr("Today") daysAgo == 1 -> tr("Yesterday") - daysAgo < 7 -> date.format(DateTimeFormatter.ofPattern("EEEE")) - date.year == java.time.Year.now().value -> date.format(DateTimeFormatter.ofPattern("EEE, MMM d")) - else -> date.format(DateTimeFormatter.ofPattern("MMM d, yyyy")) + daysAgo < 7 -> com.pulseloop.ui.components.PhoneFormat.date("EEEE", date) + date.year == java.time.Year.now().value -> com.pulseloop.ui.components.PhoneFormat.date("EEEMMMd", date) + else -> com.pulseloop.ui.components.PhoneFormat.date("yMMMd", date) } } @@ -480,7 +483,7 @@ fun ActivityWorkoutRow(session: ActivitySessionEntity, units: UnitSystem, onTap: maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f), ) - Text(SleepFormat.clockTime(session.startedAt), fontSize = 12.sp, color = PulseColors.textMuted) + Text(com.pulseloop.ui.components.PhoneFormat.clock(LocalContext.current, session.startedAt), fontSize = 12.sp, color = PulseColors.textMuted) } Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) { if (durationSec != null) { @@ -599,7 +602,8 @@ private fun WeeklyPillCalendar(days: List) { 1.dp, when { day.completed -> PulseColors.steps.copy(alpha = 0.5f) - day.isToday -> PulseColors.accent.copy(alpha = 0.6f) + // Today is a state, not a tap target: no mint. + day.isToday -> PulseColors.textSecondary else -> PulseColors.borderSubtle }, CircleShape, @@ -687,7 +691,6 @@ private fun WorkoutHistoryDialog( onSelect: (String) -> Unit, ) { val zone = remember { ZoneId.systemDefault() } - val headerFmt = remember { DateTimeFormatter.ofPattern("EEEE, MMM d") } val today = remember { LocalDate.now(zone) } val groups = remember(sessions) { sessions.groupBy { Instant.ofEpochMilli(it.startedAt).atZone(zone).toLocalDate() } @@ -698,7 +701,7 @@ private fun WorkoutHistoryDialog( 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) + else -> com.pulseloop.ui.components.PhoneFormat.date("EEEEMMMMd", day).uppercase(java.util.Locale.ROOT) } AlertDialog( @@ -803,9 +806,8 @@ private fun ActivityRecordsCard( if (expanded && buckets == null) buckets = viewModel?.bucketsForDay(dayStart) ?: emptyList() } - fun timeOf(startEpoch: Long): String = - DateTimeFormatter.ofPattern("h:mm a") - .format(Instant.ofEpochMilli(startEpoch).atZone(ZoneId.systemDefault())) + val context = LocalContext.current + fun timeOf(startEpoch: Long): String = com.pulseloop.ui.components.PhoneFormat.clock(context, startEpoch) Column( Modifier.fillMaxWidth().clip(shape).background(PulseColors.card).border(1.dp, PulseColors.borderSubtle, shape), @@ -868,7 +870,7 @@ private fun ActivityRecordsCard( ) if (bucket.distanceMeters > 0) { Text( - tr(" · %.2f %s").format(UnitConverter.distance(bucket.distanceMeters, units), UnitConverter.distanceUnit(units)), + " · " + "%.2f %s".format(UnitConverter.distance(bucket.distanceMeters, units), UnitConverter.distanceUnit(units)), fontSize = 12.sp, color = PulseColors.textMuted, ) } @@ -938,8 +940,6 @@ private fun DetectedActivityCard() { value = runCatching { com.pulseloop.service.ActivityDetection.load(context, db) }.getOrDefault(emptyList()) } if (proposals.isEmpty()) return - val fmt = remember { java.time.format.DateTimeFormatter.ofPattern("EEE HH:mm") } - val zone = remember { java.time.ZoneId.systemDefault() } Column( Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(8.dp)).padding(16.dp), @@ -952,11 +952,11 @@ private fun DetectedActivityCard() { val isNap = p.kind == com.pulseloop.service.ActivityDetection.Proposal.Kind.NAP Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Text( - (if (isNap) tr("Possible nap") else com.pulseloop.notifications.ActivityDetectionNotifier.phrase(type)) + " · ${p.minutes} min", + (if (isNap) tr("Possible nap") else com.pulseloop.notifications.ActivityDetectionNotifier.phrase(type)) + " · " + trf("{0} min", p.minutes), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, ) Text( - "${java.time.Instant.ofEpochMilli(p.startAt).atZone(zone).format(fmt)} · ${p.detail}", + "${com.pulseloop.ui.components.PhoneFormat.date("EEE", p.startAt)} ${com.pulseloop.ui.components.PhoneFormat.clock(context, p.startAt)} · ${p.detail}", fontSize = 12.sp, color = PulseColors.textMuted, ) if (!isNap) { 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 f156ad21..1015efaa 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/BarcodeScannerScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/BarcodeScannerScreen.kt @@ -224,27 +224,27 @@ fun BarcodeScannerScreen(onScan: (String) -> Unit, onDismiss: () -> Unit) { .systemBarsPadding(), ) { // iOS: navigationTitle "Scan barcode" (inline) + .cancellationAction Cancel (:41-45). - Row( - Modifier - .fillMaxWidth() - .padding(horizontal = 4.dp, vertical = 4.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - tr("Scan barcode"), - fontSize = 16.sp, - fontWeight = FontWeight.SemiBold, - color = PulseColors.textPrimary, - modifier = Modifier.weight(1f), - ) - PulseButton(PulseButtonStyle.Text, onClick = onDismiss) { Text(tr("Cancel")) } - } + // The app's one pushed-screen bar; its back arrow closes the scanner. + com.pulseloop.ui.components.PulseTopBar(title = tr("Scan barcode"), onBack = onDismiss) when (availability) { - ScanAvailability.Granted -> + ScanAvailability.Granted -> Box(Modifier.fillMaxSize()) { AndroidView( factory = { previewView }, modifier = Modifier.fillMaxSize(), ) + // The scanning state says what to do: the preview alone gave no hint. + Text( + tr("Point the camera at the barcode"), + fontSize = 14.sp, + color = PulseColors.textPrimary, + textAlign = TextAlign.Center, + modifier = Modifier + .align(Alignment.BottomCenter) + .padding(24.dp) + .background(PulseColors.background.copy(alpha = 0.7f), androidx.compose.foundation.shape.RoundedCornerShape(8.dp)) + .padding(horizontal = 16.dp, vertical = 8.dp), + ) + } ScanAvailability.Unavailable -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { // iOS fallback block, verbatim copy (BarcodeScannerSheet.swift:26-39). @@ -259,16 +259,16 @@ fun BarcodeScannerScreen(onScan: (String) -> Unit, onDismiss: () -> Unit) { Icons.Filled.QrCodeScanner, contentDescription = null, tint = PulseColors.textMuted, - modifier = Modifier.size(34.dp), + modifier = Modifier.size(32.dp), ) - Spacer(Modifier.height(10.dp)) + Spacer(Modifier.height(12.dp)) Text( tr("Scanning unavailable"), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, ) - Spacer(Modifier.height(6.dp)) + Spacer(Modifier.height(8.dp)) Text( tr("Barcode scanning needs a working device camera. Enter the food manually instead."), fontSize = 12.sp, @@ -287,16 +287,16 @@ fun BarcodeScannerScreen(onScan: (String) -> Unit, onDismiss: () -> Unit) { Icons.Filled.QrCodeScanner, contentDescription = null, tint = PulseColors.textMuted, - modifier = Modifier.size(34.dp), + modifier = Modifier.size(32.dp), ) - Spacer(Modifier.height(10.dp)) + Spacer(Modifier.height(12.dp)) Text( tr("Camera access needed"), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, ) - Spacer(Modifier.height(6.dp)) + Spacer(Modifier.height(8.dp)) Text( tr("Allow camera access in Settings to scan barcodes, or enter the food manually instead."), fontSize = 12.sp, 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 b3466496..e71ab7c1 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt @@ -46,6 +46,7 @@ import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.RadioButton import androidx.compose.material3.Text import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment @@ -58,6 +59,7 @@ import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.liveRegion import androidx.compose.ui.graphics.PathEffect import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.Stroke @@ -128,7 +130,7 @@ private fun DrinkCard(title: String? = null, action: (@Composable () -> Unit)? = ) { if (title != null || action != null) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { - Text(title.orEmpty().uppercase(), fontSize = 12.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted, modifier = Modifier.weight(1f)) + Text(title.orEmpty().uppercase(), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary, modifier = Modifier.weight(1f)) action?.invoke() } } @@ -163,7 +165,8 @@ private fun Pill(label: String, on: Boolean, color: Color = PulseColors.accent, fontWeight = if (on) FontWeight.Bold else FontWeight.Normal, color = if (on) PulseColors.onAccent else PulseColors.textSecondary, maxLines = 1, overflow = TextOverflow.Ellipsis, - modifier = Modifier.clip(shape) + // 48dp of layout for the touch target; the pill keeps its drawn size inside it. + modifier = Modifier.minimumInteractiveComponentSize().clip(shape) .background(if (on) color else PulseColors.cardSoft) .border(1.dp, if (on) color else PulseColors.borderSubtle, shape) .selectable(selected = on, role = Role.RadioButton, onClick = onClick) @@ -196,7 +199,10 @@ private fun Segments(options: List, selected: Int, onSelect: (Int) -> Un modifier = Modifier.weight(1f) .background(if (on) PulseColors.accent else PulseColors.cardSoft) .selectable(selected = on, role = Role.Tab) { onSelect(i) } - .padding(vertical = 9.dp), + // 48dp tall, label centred (was 9dp padding, about 36dp). + .heightIn(min = 48.dp) + .wrapContentHeight(Alignment.CenterVertically) + .padding(vertical = 8.dp), ) } } @@ -221,16 +227,10 @@ 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")) } - // Kept clear of the back and settings buttons whatever the voice calls this screen. - Text( - tr("Drinks"), fontSize = 16.sp, fontWeight = FontWeight.Bold, - maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center, - modifier = Modifier.align(Alignment.Center).padding(horizontal = 56.dp), - ) + // The app's one pushed-screen bar (was hand-rolled); it ellipsises a long voice title. + com.pulseloop.ui.components.PulseTopBar(title = tr("Drinks"), onBack = onBack) { if (enabled) { - IconButton(onClick = { settingsOpen = true }, modifier = Modifier.align(Alignment.CenterEnd)) { + IconButton(onClick = { settingsOpen = true }) { Icon(Icons.Filled.Settings, tr("Drinks settings"), tint = PulseColors.textSecondary) } } @@ -495,7 +495,7 @@ private fun LogCard(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChang Modifier.weight(1f).fillMaxHeight().clip(shape) .background(PulseColors.cardSoft) .border(1.dp, PulseColors.borderSubtle, shape) - .clickable { + .clickable(role = Role.Button, onClickLabel = tr("Log a drink")) { scope.launch { val rows = DrinksRepository.log(db, t) lastLogged = "+1 ${t.short.lowercase()}" to rows @@ -513,7 +513,7 @@ private fun LogCard(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChang } lastLogged?.let { (text, ids) -> Row(verticalAlignment = Alignment.CenterVertically) { - Text(trf("Logged {0}", text), fontSize = 14.sp, color = PulseColors.success, modifier = Modifier.weight(1f)) + Text(trf("Logged {0}", text), fontSize = 14.sp, color = PulseColors.success, modifier = Modifier.weight(1f).semantics { liveRegion = androidx.compose.ui.semantics.LiveRegionMode.Polite }) Text( tr("Undo"), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, @@ -606,9 +606,9 @@ private fun PlanChip(s: DrinksRepository.Snapshot, onClick: () -> Unit) { // 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) + modifier = Modifier.widthIn(max = 150.dp).minimumInteractiveComponentSize().clip(shape) .border(1.dp, if (planned == null) PulseColors.accent else PulseColors.borderSubtle, shape) - .clickable(onClick = onClick) + .clickable(role = Role.Button, onClick = onClick) .padding(horizontal = 12.dp, vertical = 8.dp), ) } @@ -619,7 +619,7 @@ private fun PlanSheet(s: DrinksRepository.Snapshot, onDone: () -> Unit) { Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(bottom = 32.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { Text(tr("Plan tonight"), fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(tr("Pick the number before the first drink. It's easier to keep a number you chose beforehand."), fontSize = 14.sp, color = PulseColors.textSecondary) - Stepper(tr("Drinks tonight"), if (plan == 0) "none" else "$plan", { plan = (plan - 1).coerceAtLeast(0) }, { plan = (plan + 1).coerceAtMost(12) }) + Stepper(tr("Drinks tonight"), if (plan == 0) tr("None") else "$plan", { plan = (plan - 1).coerceAtLeast(0) }, { plan = (plan + 1).coerceAtMost(12) }) PulseButton(onClick = { DrinkPrefs.setPlan(s.today, plan); onDone() }, modifier = Modifier.fillMaxWidth()) { Text(tr("Save plan")) } if (s.planToday != null) { PulseButton(PulseButtonStyle.Text, onClick = { DrinkPrefs.setPlan(s.today, null); onDone() }, modifier = Modifier.fillMaxWidth()) { Text(tr("Clear plan")) } @@ -630,8 +630,8 @@ private fun PlanSheet(s: DrinksRepository.Snapshot, onDone: () -> Unit) { @Composable private fun RecentDrinkRow(e: DrinkEntryEntity, gramsPerStd: Double, fmt: DateTimeFormatter, zone: ZoneId, onDelete: () -> Unit) { Row(verticalAlignment = Alignment.CenterVertically) { - Icon(DrinkType.of(e.type).icon, null, tint = PulseColors.textMuted, modifier = Modifier.size(18.dp)) - Spacer(Modifier.width(10.dp)) + Icon(DrinkType.of(e.type).icon, null, tint = PulseColors.textMuted, modifier = Modifier.size(20.dp)) + Spacer(Modifier.width(12.dp)) Column(Modifier.weight(1f)) { Text(DrinkType.of(e.type).label, fontSize = 14.sp, color = PulseColors.textPrimary) Text( @@ -809,15 +809,19 @@ private fun WeeksChart(s: DrinksRepository.Snapshot) { @Composable private fun SupportRow(icon: ImageVector, title: String, subtitle: String, onClick: (() -> Unit)?) { Row( - Modifier.fillMaxWidth().then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier).padding(vertical = 6.dp), + Modifier.fillMaxWidth().heightIn(min = 48.dp) + .then(if (onClick != null) Modifier.clickable(role = Role.Button, onClick = onClick) else Modifier) + .padding(vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { - Icon(icon, null, tint = PulseColors.accent, modifier = Modifier.size(22.dp)) + // Mint marks what can be tapped; an information-only row stays quiet. + Icon(icon, null, tint = if (onClick != null) PulseColors.accent else PulseColors.textSecondary, modifier = Modifier.size(24.dp)) Column(Modifier.weight(1f)) { Text(title, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) Text(subtitle, fontSize = 12.sp, color = PulseColors.textMuted) } + if (onClick != null) com.pulseloop.ui.components.Chevron() } } @@ -832,10 +836,20 @@ private fun SupportTab(s: DrinksRepository.Snapshot, onBreathe: () -> Unit, onCo } } AuditCard(s, onAuditDone) + val context = LocalContext.current + // A crisis line that only reads "188" makes the user dial it by hand; the row opens the dialer + // (ACTION_DIAL needs no permission and calls nothing until the user presses call). + fun open(uri: String, action: String) { + runCatching { context.startActivity(android.content.Intent(action, android.net.Uri.parse(uri))) } + } DrinkCard(tr("Support in Brazil")) { - SupportRow(Icons.Filled.Phone, tr("CVV · 188"), tr("Free emotional support, any time, by phone or chat."), null) + SupportRow(Icons.Filled.Phone, tr("CVV · 188"), tr("Free emotional support, any time, by phone or chat.")) { + open("tel:188", android.content.Intent.ACTION_DIAL) + } SupportRow(Icons.Filled.LocalHospital, tr("CAPS AD"), tr("Free public care for alcohol use. Ask at your local health unit."), null) - SupportRow(Icons.Filled.EventAvailable, tr("Alcoólicos Anônimos"), tr("Meetings across the country: aa.org.br"), null) + SupportRow(Icons.Filled.EventAvailable, tr("Alcoólicos Anônimos"), tr("Meetings across the country: aa.org.br")) { + open("https://www.aa.org.br", android.content.Intent.ACTION_VIEW) + } Text(tr("Anywhere: your doctor. If you drink most days, don't stop all at once; a doctor can help you cut down safely."), fontSize = 12.sp, color = PulseColors.textMuted) } } 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 a4aeff3e..a452cda5 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/FoodUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/FoodUi.kt @@ -88,14 +88,14 @@ fun FoodCard( .fillMaxWidth() .clip(RoundedCornerShape(8.dp)) .background(PulseColors.card) - .clickable(onClick = onOpen) + .clickable(role = Role.Button, onClick = onOpen) .padding(16.dp), - verticalArrangement = Arrangement.spacedBy(10.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), ) { Row(verticalAlignment = Alignment.CenterVertically) { Box(Modifier.size(8.dp).clip(RoundedCornerShape(4.dp)).background(PulseColors.calories)) Spacer(Modifier.width(8.dp)) - Text(tr("FOOD"), fontSize = 12.sp, letterSpacing = 1.8.sp, color = PulseColors.textSecondary, modifier = Modifier.weight(1f)) + Text(tr("FOOD"), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary, modifier = Modifier.weight(1f)) if (!f.enabled) { Text( tr("Hide"), fontSize = 12.sp, color = PulseColors.textMuted, @@ -144,16 +144,17 @@ private fun FoodAction(label: String, icon: ImageVector, modifier: Modifier, onC val shape = RoundedCornerShape(4.dp) Row( modifier + .heightIn(min = 48.dp) .clip(shape) .background(PulseColors.cardSoft) .border(1.dp, PulseColors.borderSubtle, shape) - .clickable(onClick = onClick) - .padding(horizontal = 4.dp, vertical = 10.dp), + .clickable(role = Role.Button, onClick = onClick) + .padding(horizontal = 4.dp, vertical = 12.dp), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, ) { Icon(icon, null, Modifier.size(16.dp), tint = PulseColors.accent) - Spacer(Modifier.width(6.dp)) + Spacer(Modifier.width(8.dp)) Text( label, fontSize = 14.sp, color = PulseColors.textPrimary, maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center, diff --git a/app/src/main/java/com/pulseloop/ui/screens/GuidanceUi.kt b/app/src/main/java/com/pulseloop/ui/screens/GuidanceUi.kt index ed4fb2e2..f9315250 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/GuidanceUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/GuidanceUi.kt @@ -46,26 +46,6 @@ fun rememberGuidance(db: PulseLoopDatabase, key: Any?): GuidanceState? { return state } -/** Shown only when two or more of last night's signals are outside the usual range. */ -@Composable -fun UnusualSignalsCard(signals: List) { - if (!VitalsCheck.shouldAlert(signals)) return - Column( - Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)) - .dither(PulseColors.warning, 0.12f).padding(16.dp), - verticalArrangement = Arrangement.spacedBy(6.dp), - ) { - Text(tr("Some signals look unusual"), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.warning) - signals.forEach { - Text("${it.title}: ${it.detail}", fontSize = 14.sp, color = PulseColors.textPrimary) - } - Text( - tr("Compared with your own recent nights. This can follow illness, stress, alcohol or a hard day. It isn't a diagnosis; consider an easier day."), - fontSize = 12.sp, color = PulseColors.textSecondary, - ) - } -} - /** Tonight: the suggested bedtime window and the caffeine cutoff that goes with it. */ @Composable fun TonightCard(g: BedtimeGuidance.Result, sleepGoalMinutes: Int) { @@ -74,20 +54,28 @@ fun TonightCard(g: BedtimeGuidance.Result, sleepGoalMinutes: Int) { horizontalArrangement = Arrangement.spacedBy(16.dp), ) { Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { - Text(tr("BEDTIME"), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.sleep) + Text(tr("BEDTIME"), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary) Text( - "${BedtimeGuidance.fmt(g.windowStart)}–${BedtimeGuidance.fmt(g.windowEnd)}", + "${clock(g.windowStart)}–${clock(g.windowEnd)}", fontSize = 20.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, ) Text( - trf("For {0}h asleep before your usual {1}", sleepGoalMinutes / 60, BedtimeGuidance.fmt(g.usualWake)), + trf("For {0}h asleep before your usual {1}", sleepGoalMinutes / 60, clock(g.usualWake)), fontSize = 12.sp, color = PulseColors.textMuted, ) } Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { - Text(tr("LAST CAFFEINE"), fontSize = 12.sp, fontWeight = FontWeight.Medium, color = PulseColors.calories) - Text(BedtimeGuidance.fmt(g.caffeineCutoff), fontSize = 20.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) + Text(tr("LAST CAFFEINE"), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary) + Text(clock(g.caffeineCutoff), fontSize = 20.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) Text(tr("8 hours before bed"), fontSize = 12.sp, color = PulseColors.textMuted) } } } + +/** A clock time in the phone's own 12/24-hour setting (BedtimeGuidance.fmt is always 24-hour). */ +@Composable +private fun clock(t: java.time.LocalTime): String { + val context = androidx.compose.ui.platform.LocalContext.current + val pattern = if (android.text.format.DateFormat.is24HourFormat(context)) "HH:mm" else "h:mm a" + return t.format(java.time.format.DateTimeFormatter.ofPattern(pattern)) +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/LogSheet.kt b/app/src/main/java/com/pulseloop/ui/screens/LogSheet.kt index 1d781b4e..b3867aa2 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/LogSheet.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/LogSheet.kt @@ -97,9 +97,13 @@ fun LogSheet( targetState = step, transitionSpec = { val forward = targetState != LogStep.MENU - (androidx.compose.animation.fadeIn(androidx.compose.animation.core.tween(220)) + - androidx.compose.animation.slideInHorizontally(androidx.compose.animation.core.tween(220)) { w -> if (forward) w / 6 else -w / 6 }) togetherWith - androidx.compose.animation.fadeOut(androidx.compose.animation.core.tween(150)) + // The system's own durations and ease (theme/Motion.kt), not one-off specs. + val emphasis = androidx.compose.animation.core.tween(com.pulseloop.ui.theme.Motion.EMPHASIS_MS, easing = com.pulseloop.ui.theme.Motion.ease) + val slide = androidx.compose.animation.core.tween(com.pulseloop.ui.theme.Motion.EMPHASIS_MS, easing = com.pulseloop.ui.theme.Motion.ease) + val standard = androidx.compose.animation.core.tween(com.pulseloop.ui.theme.Motion.STANDARD_MS, easing = com.pulseloop.ui.theme.Motion.ease) + (androidx.compose.animation.fadeIn(emphasis) + + androidx.compose.animation.slideInHorizontally(slide) { w -> if (forward) w / 6 else -w / 6 }) togetherWith + androidx.compose.animation.fadeOut(standard) }, label = "logStep", ) { shownStep -> @@ -154,7 +158,7 @@ private fun RowScope.IconAction(label: String, icon: androidx.compose.ui.graphic horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterVertically), ) { - Icon(icon, null, tint = tint, modifier = Modifier.size(26.dp)) + Icon(icon, null, tint = tint, modifier = Modifier.size(24.dp)) Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, textAlign = TextAlign.Center, maxLines = 1, overflow = TextOverflow.Ellipsis) } } 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 dab8a86e..c70e616a 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt @@ -39,6 +39,7 @@ import androidx.compose.foundation.layout.systemBarsPadding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons @@ -283,22 +284,9 @@ fun MealAnalysisDialog( .background(PulseColors.background) .systemBarsPadding(), ) { - // iOS: navigationTitle "AI meal log" (inline) + Cancel (MealAnalysisSheet.swift:70-74). - Row( - Modifier - .fillMaxWidth() - .padding(horizontal = 4.dp, vertical = 4.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - tr("AI meal log"), - fontSize = 16.sp, - fontWeight = FontWeight.SemiBold, - color = PulseColors.textPrimary, - modifier = Modifier.weight(1f), - ) - PulseButton(PulseButtonStyle.Text, onClick = onDismiss) { Text(tr("Cancel")) } - } + // The app's one pushed-screen bar: its back arrow is the way out (was a hand-rolled + // title row with a Cancel button). + com.pulseloop.ui.components.PulseTopBar(title = tr("AI meal log"), onBack = onDismiss) Column( Modifier .fillMaxSize() @@ -329,7 +317,7 @@ fun MealAnalysisDialog( Box(Modifier.fillMaxWidth()) { Image( bitmap = picked.asImageBitmap(), - contentDescription = null, + contentDescription = tr("Meal photo"), modifier = Modifier .fillMaxWidth() .height(220.dp) @@ -339,7 +327,12 @@ fun MealAnalysisDialog( onClick = { image = null }, modifier = Modifier.align(Alignment.TopEnd), ) { - Icon(Icons.Filled.Close, tr("Remove photo"), tint = Color.White) + // A scrim behind the glyph, so it reads on a bright photo. + Icon( + Icons.Filled.Close, tr("Remove photo"), + tint = PulseColors.textPrimary, + modifier = Modifier.background(PulseColors.background.copy(alpha = 0.7f), CircleShape).padding(4.dp), + ) } } } else { @@ -347,7 +340,7 @@ fun MealAnalysisDialog( Row(Modifier.fillMaxWidth().height(IntrinsicSize.Min), horizontalArrangement = Arrangement.spacedBy(12.dp)) { PulseButton(PulseButtonStyle.Outlined, onClick = { launchCamera() }, modifier = Modifier.weight(1f).fillMaxHeight()) { Icon(Icons.Filled.PhotoCamera, null, Modifier.size(18.dp)) - Spacer(Modifier.width(6.dp)) + Spacer(Modifier.width(8.dp)) Text(tr("Camera"), maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center) } PulseButton(PulseButtonStyle.Outlined, @@ -359,7 +352,7 @@ fun MealAnalysisDialog( modifier = Modifier.weight(1f).fillMaxHeight(), ) { Icon(Icons.Filled.PhotoLibrary, null, Modifier.size(18.dp)) - Spacer(Modifier.width(6.dp)) + Spacer(Modifier.width(8.dp)) Text(tr("Library"), maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center) } } @@ -368,9 +361,8 @@ fun MealAnalysisDialog( Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Text( if (image == null) tr("OR DESCRIBE IT") else tr("ADD DETAIL (OPTIONAL)"), - fontSize = 12.sp, - letterSpacing = 1.4.sp, - color = PulseColors.textMuted, + style = com.pulseloop.ui.theme.PulseType.eyebrow, + color = PulseColors.textSecondary, ) OutlinedTextField( value = describeText, @@ -382,14 +374,14 @@ fun MealAnalysisDialog( ) } - PulseButton( + // Tonal: the app's one filled accent is the Actions button. + PulseButton(PulseButtonStyle.Tonal, onClick = { analyze() }, enabled = canAnalyze, modifier = Modifier.fillMaxWidth(), - colors = ButtonDefaults.buttonColors(containerColor = PulseColors.accent), ) { Icon(Icons.Filled.AutoAwesome, null, Modifier.size(18.dp)) - Spacer(Modifier.width(6.dp)) + Spacer(Modifier.width(8.dp)) Text(tr("Analyze")) } @@ -421,7 +413,7 @@ fun MealAnalysisDialog( // ProvenanceBadge(source: .llmEstimate) — "AI estimate", sparkles, // accent (NutritionComponents.swift:231-264). Surface( - modifier = Modifier.dither(PulseColors.accent, 0.14f, RoundedCornerShape(50)), + modifier = Modifier.dither(PulseColors.info, 0.14f, RoundedCornerShape(50)), shape = RoundedCornerShape(50), color = Color.Transparent, ) { @@ -429,13 +421,13 @@ fun MealAnalysisDialog( Modifier.padding(horizontal = 8.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically, ) { - Icon(Icons.Filled.AutoAwesome, null, tint = PulseColors.accent, modifier = Modifier.size(12.dp)) + Icon(Icons.Filled.AutoAwesome, null, tint = PulseColors.info, modifier = Modifier.size(12.dp)) Spacer(Modifier.width(4.dp)) Text( tr("AI estimate"), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, - color = PulseColors.accent, + color = PulseColors.info, ) } } @@ -485,14 +477,13 @@ fun MealAnalysisDialog( } } val canSave = MealAnalysisLogic.canSave(name, calories) - PulseButton( + PulseButton(PulseButtonStyle.Tonal, onClick = { save() }, enabled = canSave, modifier = Modifier.fillMaxWidth(), - colors = ButtonDefaults.buttonColors(containerColor = PulseColors.accent), ) { Icon(Icons.Filled.Check, null, Modifier.size(18.dp)) - Spacer(Modifier.width(6.dp)) + Spacer(Modifier.width(8.dp)) Text(tr("Log meal")) } PulseButton(PulseButtonStyle.Text, 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 20f1842a..5c738bc4 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt @@ -117,7 +117,11 @@ internal fun Section( Text(title, style = com.pulseloop.ui.theme.PulseType.title, color = PulseColors.textPrimary) if (!open) Text(summary!!, fontSize = 12.sp, color = PulseColors.textMuted, maxLines = 2, overflow = TextOverflow.Ellipsis) } - val turn by androidx.compose.animation.core.animateFloatAsState(if (open) 180f else 0f, label = "chevron") + val turn by androidx.compose.animation.core.animateFloatAsState( + if (open) 180f else 0f, + androidx.compose.animation.core.tween(com.pulseloop.ui.theme.Motion.EMPHASIS_MS, easing = com.pulseloop.ui.theme.Motion.ease), + label = "chevron", + ) Icon( Icons.Filled.ExpandMore, contentDescription = null, tint = PulseColors.textMuted, modifier = Modifier.size(24.dp).graphicsLayer { rotationZ = turn }, @@ -125,8 +129,11 @@ internal fun Section( } androidx.compose.animation.AnimatedVisibility( visible = open, - enter = androidx.compose.animation.expandVertically() + androidx.compose.animation.fadeIn(), - exit = androidx.compose.animation.shrinkVertically() + androidx.compose.animation.fadeOut(), + // The system's durations and ease (theme/Motion.kt), not Compose's default springs. + enter = androidx.compose.animation.expandVertically(androidx.compose.animation.core.tween(com.pulseloop.ui.theme.Motion.EMPHASIS_MS, easing = com.pulseloop.ui.theme.Motion.ease)) + + androidx.compose.animation.fadeIn(androidx.compose.animation.core.tween(com.pulseloop.ui.theme.Motion.EMPHASIS_MS, easing = com.pulseloop.ui.theme.Motion.ease)), + exit = androidx.compose.animation.shrinkVertically(androidx.compose.animation.core.tween(com.pulseloop.ui.theme.Motion.STANDARD_MS, easing = com.pulseloop.ui.theme.Motion.ease)) + + androidx.compose.animation.fadeOut(androidx.compose.animation.core.tween(com.pulseloop.ui.theme.Motion.STANDARD_MS, easing = com.pulseloop.ui.theme.Motion.ease)), ) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { content() } } @@ -196,9 +203,9 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () Column(Modifier.fillMaxSize().background(PulseColors.background)) { val shareScope = rememberCoroutineScope() - androidx.compose.material3.CenterAlignedTopAppBar( - title = { Text(tr("My Health"), style = com.pulseloop.ui.theme.PulseType.title) }, - navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) } }, + com.pulseloop.ui.components.PulseTopBar( + title = tr("My Health"), + onBack = onBack, actions = { IconButton( onClick = { @@ -217,8 +224,6 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () }, ) { Icon(androidx.compose.material.icons.Icons.Filled.Share, tr("Share my week"), tint = PulseColors.textSecondary) } }, - windowInsets = androidx.compose.foundation.layout.WindowInsets(0, 0, 0, 0), - colors = androidx.compose.material3.TopAppBarDefaults.topAppBarColors(containerColor = PulseColors.background), ) // Lazy: each section composes as it scrolls in, instead of every chart and DB read at once. androidx.compose.foundation.lazy.LazyColumn( @@ -319,7 +324,8 @@ private fun RadarSection(r: SymptomRadar.Result?, restUntil: java.time.LocalDate Column(Modifier.weight(1f)) { Text(tr("Rest Mode"), fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text( - restUntil?.let { trf("On until {0}/{1}: activity nudges paused, the coach eases off.", it.dayOfMonth, it.monthValue) } + // A localised date ("Thu 6 Nov"), not a day/month pair that reads backwards in the US. + restUntil?.let { trf("On until {0}: activity nudges paused, the coach eases off.", it.format(java.time.format.DateTimeFormatter.ofPattern("EEE d MMM"))) } ?: tr("Feeling unwell? Pause activity nudges for 3 days."), fontSize = 12.sp, color = PulseColors.textMuted, ) @@ -559,7 +565,7 @@ fun BreatheScreen(onBack: () -> Unit) { ) animated } - Box(Modifier.size(220.dp).scale(s).clip(CircleShape).dither(PulseColors.accent, 0.35f, CircleShape).border(2.dp, PulseColors.accent, CircleShape)) + Box(Modifier.size(220.dp).scale(s).clip(CircleShape).dither(PulseColors.info, 0.35f, CircleShape).border(2.dp, PulseColors.info, CircleShape)) Spacer(Modifier.height(24.dp)) Text( if (inhaling) tr("Breathe in") else tr("Breathe out"), fontSize = 20.sp, color = PulseColors.textPrimary, 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 9a095973..3f92d442 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt @@ -78,7 +78,7 @@ fun NutritionScreen( } } val dateLabel = remember(todayStart) { - java.text.SimpleDateFormat("EEE, MMM d", java.util.Locale.US).format(java.util.Date(todayStart)) + java.text.SimpleDateFormat("EEE, MMM d", java.util.Locale.getDefault()).format(java.util.Date(todayStart)) } var meals by remember { mutableStateOf>(emptyList()) } @@ -128,16 +128,7 @@ fun NutritionScreen( // Insets are already applied by the route wrapper (see SettingsSubScreen). contentWindowInsets = WindowInsets(0, 0, 0, 0), topBar = { - if (!asTab) TopAppBar( - title = { Text(tr("Nutrition")) }, - navigationIcon = { - IconButton(onClick = onBack) { - Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) - } - }, - windowInsets = WindowInsets(0, 0, 0, 0), - colors = TopAppBarDefaults.topAppBarColors(containerColor = PulseColors.background), - ) + if (!asTab) com.pulseloop.ui.components.PulseTopBar(title = tr("Nutrition"), onBack = onBack) }, ) { padding -> LazyColumn( @@ -162,16 +153,24 @@ fun NutritionScreen( // Calorie gauge item { val totalCal = totals.sumOf { it.totalCal } + // Without a goal the 2000 is a stand-in, and the line says so rather than + // reading as a target the user set (audit, v2.11.58, carried). + val hasCalorieGoal = goal?.intakeCalories != null 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)) { // 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)), + Modifier.padding(16.dp).then(if (dayLoaded && goalLoaded) Modifier else Modifier.alpha(0f)), horizontalAlignment = Alignment.CenterHorizontally, ) { Text("${totalCal.roundToInt()} kcal", fontSize = 32.sp, fontWeight = FontWeight.Bold) - Text(trf("of {0}", goalCal.roundToInt()), color = PulseColors.textMuted) + Text( + if (hasCalorieGoal) trf("of {0}", goalCal.roundToInt()) + else trf("No goal set · {0} is a typical day", goalCal.roundToInt()), + color = PulseColors.textMuted, + textAlign = TextAlign.Center, + ) Spacer(Modifier.height(8.dp)) LinearProgressIndicator( progress = { pct.toFloat() }, @@ -255,6 +254,18 @@ fun NutritionScreen( } } + // An empty day says so, instead of ending at the logging row. + if (dayLoaded && meals.isEmpty()) { + item { + Text( + if (dayOffset == 0) tr("Nothing logged today yet.") else tr("Nothing logged on this day."), + fontSize = 14.sp, color = PulseColors.textMuted, + modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), + textAlign = TextAlign.Center, + ) + } + } + // Meals grouped by type val mealTypes = listOf("breakfast", "lunch", "dinner", "snack") for (type in mealTypes) { @@ -307,8 +318,15 @@ fun NutritionScreen( onDismiss = { showAddDialog = false; startScanner = false }, onSave = { save -> scope.launch { + // A past day's meal is stamped at that day's noon, not at this moment, by the + // rule the photo flow already uses (NutritionTools.resolveTimestamp). + val stamp = NutritionTools.resolveTimestamp( + date = java.time.Instant.ofEpochMilli(todayStart) + .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toString(), + time = null, + ) val entry = MealEntryEntity( - date = todayStart, timestamp = System.currentTimeMillis(), + date = todayStart, timestamp = stamp, name = save.name, mealTypeRaw = save.type, calories = save.calories, proteinG = save.proteinG, carbsG = save.carbsG, fatG = save.fatG, @@ -578,7 +596,7 @@ fun MealLogDialog( ) { if (estimating) CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp) else Icon(Icons.Filled.AutoAwesome, null, Modifier.size(18.dp)) - Spacer(Modifier.width(6.dp)) + Spacer(Modifier.width(8.dp)) Text( if (estimating) tr("Estimating…") else tr("Estimate calories with AI"), maxLines = 2, overflow = TextOverflow.Ellipsis, @@ -721,10 +739,11 @@ private fun NextMealCard( Modifier.fillMaxWidth(), shape = RoundedCornerShape(8.dp), colors = CardDefaults.cardColors(containerColor = PulseColors.card), - border = androidx.compose.foundation.BorderStroke(1.dp, PulseColors.accent), + // Mint is for what's tapped: the card itself isn't, so its frame is the quiet one. + border = androidx.compose.foundation.BorderStroke(1.dp, PulseColors.borderSubtle), ) { Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { - Text(trf("NEXT MEAL IDEA · {0}", idea.slot.uppercase()), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.accent) + Text(trf("NEXT MEAL IDEA · {0}", idea.slot.uppercase()), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary) if (idea.items.isEmpty()) { Text(idea.note ?: "", fontSize = 14.sp, color = PulseColors.textPrimary) } else { @@ -742,7 +761,7 @@ private fun NextMealCard( fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, ) if (idea.fromPreferences.isNotEmpty()) { - Text(tr("Your preference: ") + idea.fromPreferences.joinToString("; "), fontSize = 12.sp, color = PulseColors.accent) + Text(tr("Your preference: ") + idea.fromPreferences.joinToString("; "), fontSize = 12.sp, color = PulseColors.textSecondary) } idea.note?.let { Text(it, fontSize = 12.sp, color = PulseColors.textSecondary) } // Same treatment as the Photo/Describe pair: two lines allowed, equal heights. 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 f7d1f679..b5522ae3 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/OnboardingScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/OnboardingScreen.kt @@ -191,8 +191,9 @@ fun OnboardingScreen( AnimatedContent( targetState = step, transitionSpec = { - (fadeIn(tween(300)) + slideInHorizontally(tween(300)) { it / 4 }) - .togetherWith(fadeOut(tween(200))) + val enter = tween(com.pulseloop.ui.theme.Motion.EMPHASIS_MS, easing = com.pulseloop.ui.theme.Motion.ease) + (fadeIn(enter) + slideInHorizontally(tween(com.pulseloop.ui.theme.Motion.EMPHASIS_MS, easing = com.pulseloop.ui.theme.Motion.ease)) { it / 4 }) + .togetherWith(fadeOut(tween(com.pulseloop.ui.theme.Motion.STANDARD_MS))) }, label = "onboardingStep", modifier = Modifier.weight(1f), @@ -235,7 +236,14 @@ fun OnboardingScreen( coordinator = coordinator, next = { push(OnboardingStep.BASELINE) }, ) - OnboardingStep.BASELINE -> BaselineStep(finish = ::finish) + OnboardingStep.BASELINE -> BaselineStep( + source = when { + useHealthConnect -> BaselineSource.HEALTH_CONNECT + bleClient.hasLastKnownRing -> BaselineSource.RING + else -> BaselineSource.NONE + }, + finish = ::finish, + ) } } } @@ -253,11 +261,11 @@ private fun OnboardingTopBar( ) { val total = OnboardingStep.entries.size Column( - Modifier.padding(horizontal = 18.dp).padding(bottom = 8.dp), - verticalArrangement = Arrangement.spacedBy(10.dp), + Modifier.padding(horizontal = 16.dp).padding(bottom = 8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), ) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { - Box(Modifier.size(width = 60.dp, height = 44.dp), contentAlignment = Alignment.CenterStart) { + Box(Modifier.widthIn(min = 64.dp).heightIn(min = 48.dp), contentAlignment = Alignment.CenterStart) { if (canGoBack) { IconButton(onClick = onBack) { Icon( @@ -278,8 +286,8 @@ private fun OnboardingTopBar( modifier = Modifier.weight(1f), ) // 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) { + // wrapping inside it. 48dp tall: the design system's minimum target. + Box(Modifier.widthIn(min = 64.dp).heightIn(min = 48.dp), contentAlignment = Alignment.CenterEnd) { if (showsSkip) { Text( tr("Skip"), @@ -288,14 +296,16 @@ private fun OnboardingTopBar( color = PulseColors.textSecondary, maxLines = 1, modifier = Modifier + .heightIn(min = 48.dp) .clip(RoundedCornerShape(4.dp)) - .clickable(onClick = onSkip) - .padding(horizontal = 10.dp, vertical = 12.dp), + .clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onSkip) + .wrapContentHeight() + .padding(horizontal = 12.dp), ) } } } - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(7.dp)) { + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { OnboardingStep.entries.forEach { item -> Box( Modifier @@ -329,7 +339,7 @@ private fun WelcomeStep( val features = listOf( WelcomeFeature(Icons.Filled.Paid, tr("No subscription"), tr("Own your ring data"), PulseColors.success), WelcomeFeature(Icons.Filled.Lock, tr("Privacy first"), tr("Data stays on device"), PulseColors.info), - WelcomeFeature(Icons.Filled.AutoAwesome, tr("AI health coach"), tr("Learns your baseline"), PulseColors.accent), + WelcomeFeature(Icons.Filled.AutoAwesome, tr("AI health coach"), tr("Learns your baseline"), PulseColors.hrv), WelcomeFeature(Icons.Filled.MonitorHeart, tr("See your vitals"), tr("HR, SpO₂, HRV & stress"), PulseColors.heartRate), WelcomeFeature(Icons.Filled.Bedtime, tr("Sleep tracking"), tr("Stages and trends"), PulseColors.sleep), WelcomeFeature(Icons.Filled.DirectionsRun, tr("Activity recording"), tr("Live workout tracking"), PulseColors.steps), @@ -337,7 +347,7 @@ private fun WelcomeStep( StepScaffold( footer = { - Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { if (permissionDenied) { Text( tr("PulseLoop needs Bluetooth permission to find and connect to your ring. " + @@ -386,18 +396,18 @@ private fun WelcomeStep( .clip(RoundedCornerShape(8.dp)) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(8.dp)) - .padding(horizontal = 13.dp, vertical = 10.dp), + .padding(horizontal = 12.dp, vertical = 12.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterVertically), ) { Box( Modifier - .size(38.dp) + .size(40.dp) .clip(RoundedCornerShape(4.dp)) .dither(feature.tint, 0.14f), contentAlignment = Alignment.Center, ) { - Icon(feature.icon, contentDescription = null, Modifier.size(18.dp), tint = feature.tint) + Icon(feature.icon, contentDescription = null, Modifier.size(20.dp), tint = feature.tint) } Text( feature.title, @@ -480,6 +490,7 @@ private fun GoalsStep( next: () -> Unit, ) { val scope = rememberCoroutineScope() + val context = LocalContext.current val units = remember { apiKeyStore.resolvedUnitSystem } var draft by remember { mutableStateOf(null) } @@ -495,10 +506,11 @@ private fun GoalsStep( val current = draft ?: return@PrimaryButton scope.launch { val existing = db.userGoalDao().get() - db.userGoalDao().upsert( - current.applyTo(existing ?: UserGoalEntity(), units, includeWeeklyWorkouts = false), - ) - coordinator?.setGoal(current.steps.toInt()) + val saved = current.applyTo(existing ?: UserGoalEntity(), units, includeWeeklyWorkouts = false) + db.userGoalDao().upsert(saved) + // The one path every manual goal save takes: stops the field following the + // coach, sends the step goal to the ring and republishes the widget. + com.pulseloop.service.GoalSync.afterManualSave(context, saved, coordinator) next() } } @@ -528,14 +540,26 @@ private data class BaselineMilestone( val tint: Color, ) +/** Where the user's data will come from, so the finale doesn't promise a ring they skipped. */ +private enum class BaselineSource { RING, HEALTH_CONNECT, NONE } + @Composable -private fun BaselineStep(finish: () -> Unit) { - // iOS #75 finale copy: Today / First sync / Days 3–7. +private fun BaselineStep(source: BaselineSource, finish: () -> Unit) { + // The baseline needs 14 nights (My Health's "Learning you"), not the 3–7 days iOS #75 said. val milestones = listOf( BaselineMilestone(null, tr("Today"), tr("Activity and live vitals, right away"), PulseColors.info), BaselineMilestone(Icons.Filled.Bedtime, tr("First sync"), tr("Sleep stages and nightly trends"), PulseColors.sleep), - BaselineMilestone(Icons.AutoMirrored.Filled.TrendingUp, tr("Days 3–7"), tr("Your personalized baseline unlocks"), PulseColors.success), + BaselineMilestone(Icons.AutoMirrored.Filled.TrendingUp, tr("After 14 nights"), tr("Your personalized baseline unlocks"), PulseColors.success), ) + val subtitle = when (source) { + BaselineSource.RING -> tr("Wear your ring today. Your baseline builds from here.") + BaselineSource.HEALTH_CONNECT -> tr("Your device's data comes in through Health Connect. Your baseline builds from here.") + BaselineSource.NONE -> tr("Pair a ring from Settings whenever you're ready. Your baseline builds once it's on.") + } + val howItWorks = when (source) { + BaselineSource.HEALTH_CONNECT -> tr("Keep wearing your device and let its app sync. Trends become personal after 14 nights of sleep.") + else -> tr("Wear your ring during the day and sync after sleep. Trends become personal after 14 nights of sleep.") + } // Celebratory finale (iOS #75): the medallion scales in on appear. reduceMotion-equivalent // isn't gated here — the spring settles quickly and Compose respects the system animator scale. @@ -553,10 +577,9 @@ private fun BaselineStep(finish: () -> Unit) { }, ) { SuccessMedallion(scale = medallionScale) - SetupCompleteEyebrow() StepHeader( title = tr("You're all set"), - subtitle = tr("Wear your ring today. Your baseline builds from here."), + subtitle = subtitle, ) Column( @@ -564,10 +587,10 @@ private fun BaselineStep(finish: () -> Unit) { .fillMaxWidth() .clip(RoundedCornerShape(8.dp)) .background(PulseColors.card) - .ditherFade(PulseColors.accent, 0.14f, 0f) + .ditherFade(PulseColors.success, 0.14f, 0f) .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(8.dp)) - .padding(20.dp), - verticalArrangement = Arrangement.spacedBy(18.dp), + .padding(24.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), ) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Text( @@ -577,7 +600,7 @@ private fun BaselineStep(finish: () -> Unit) { color = PulseColors.textPrimary, ) Text( - tr("Wear your ring during the day and sync after sleep. Trends become more personal after a few days."), + howItWorks, fontSize = 14.sp, color = PulseColors.textSecondary, lineHeight = 20.sp, @@ -588,13 +611,13 @@ private fun BaselineStep(finish: () -> Unit) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { Box( Modifier - .size(34.dp) + .size(32.dp) .clip(RoundedCornerShape(4.dp)) .dither(milestone.tint, 0.14f), contentAlignment = Alignment.Center, ) { if (milestone.icon != null) { - Icon(milestone.icon, contentDescription = null, Modifier.size(15.dp), tint = milestone.tint) + Icon(milestone.icon, contentDescription = null, Modifier.size(16.dp), tint = milestone.tint) } else { Text("1", fontSize = 14.sp, fontWeight = FontWeight.Bold, color = milestone.tint) } @@ -618,49 +641,33 @@ private fun BaselineStep(finish: () -> Unit) { } } -/** Animated success medallion: two concentric accent rings around a check-seal badge, scaled in +/** Animated success medallion: two concentric success rings around a check-seal badge, scaled in * on appear (iOS #75 finale "Tier 1" medallion). */ @Composable private fun SuccessMedallion(scale: Float) { Box(contentAlignment = Alignment.Center, modifier = Modifier.size(140.dp).scale(scale)) { Box( Modifier.size(140.dp).clip(CircleShape) - .border(2.dp, PulseColors.accent.copy(alpha = 0.12f), CircleShape), + .border(2.dp, PulseColors.success.copy(alpha = 0.12f), CircleShape), ) Box( Modifier.size(104.dp).clip(CircleShape) - .border(2.dp, PulseColors.accent.copy(alpha = 0.25f), CircleShape), + .border(2.dp, PulseColors.success.copy(alpha = 0.25f), CircleShape), ) Box( - Modifier.size(96.dp).clip(CircleShape).dither(PulseColors.accent, 0.14f), + Modifier.size(96.dp).clip(CircleShape).dither(PulseColors.success, 0.14f), contentAlignment = Alignment.Center, ) { Icon( Icons.Filled.Verified, contentDescription = tr("Setup complete"), - tint = PulseColors.accent, + tint = PulseColors.success, modifier = Modifier.size(56.dp), ) } } } -/** "Setup complete" accent pill above the finale title (iOS #75 eyebrow). */ -@Composable -private fun SetupCompleteEyebrow() { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp), - modifier = Modifier - .clip(CircleShape) - .dither(PulseColors.accent, 0.16f) - .padding(horizontal = 12.dp, vertical = 6.dp), - ) { - Icon(Icons.Filled.Verified, contentDescription = null, Modifier.size(14.dp), tint = PulseColors.accent) - Text(tr("Setup complete"), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent) - } -} - // MARK: - Shared step chrome /** Scrolling step content above a pinned action footer (iOS `OnboardingActionFooter`). */ @@ -693,7 +700,7 @@ private fun StepScaffold( .verticalScroll(rememberScrollState()) .padding(horizontal = 24.dp, vertical = 16.dp), horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(18.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), content = content, ) androidx.compose.material3.HorizontalDivider(thickness = 1.dp, color = PulseColors.borderSubtle) diff --git a/app/src/main/java/com/pulseloop/ui/screens/PairingScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/PairingScreen.kt index 5c5c491e..4ea28f29 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/PairingScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/PairingScreen.kt @@ -298,7 +298,7 @@ fun PairingScreen( .heightIn(min = 88.dp) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle) - .padding(horizontal = 16.dp, vertical = 10.dp), + .padding(horizontal = 16.dp, vertical = 12.dp), contentAlignment = Alignment.CenterStart, ) { Text( @@ -317,7 +317,7 @@ fun PairingScreen( .fillMaxWidth() .background(PulseColors.secondaryBackground) .padding(horizontal = 24.dp, vertical = 12.dp), - verticalArrangement = Arrangement.spacedBy(10.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { if (!isLooking && btReady) { @@ -406,7 +406,7 @@ private fun BrandTabs( contentAlignment = Alignment.Center, ) { Text( - brand, + if (brand == ALL_BRANDS_TAB) tr("All") else brand, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = if (isSelected) PulseColors.onAccent else PulseColors.textSecondary, @@ -414,7 +414,7 @@ private fun BrandTabs( .clip(CircleShape) .background(if (isSelected) PulseColors.accent else PulseColors.card) .border(1.dp, if (isSelected) Color.Transparent else PulseColors.borderSubtle, CircleShape) - .padding(horizontal = 14.dp, vertical = 8.dp), + .padding(horizontal = 16.dp, vertical = 8.dp), ) } } @@ -438,15 +438,17 @@ private fun ModelCarousel( } Column(horizontalAlignment = Alignment.CenterHorizontally) { + // A minimum, not a fixed height: at large font scale the name and chips wrap, and a + // fixed 300dp clipped them. HorizontalPager( state = pagerState, modifier = Modifier .fillMaxWidth() - .height(300.dp), + .heightIn(min = 300.dp), ) { page -> val model = models[page] Column( - Modifier.fillMaxSize(), + Modifier.fillMaxWidth().heightIn(min = 300.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically), ) { @@ -456,6 +458,7 @@ private fun ModelCarousel( fontSize = 20.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, + textAlign = TextAlign.Center, ) CapabilityChips(model.blurb) } @@ -466,15 +469,22 @@ private fun ModelCarousel( Modifier.height(48.dp), verticalAlignment = Alignment.CenterVertically, ) { - if (models.size > 1) { + if (models.size > 8) { + // Twenty-odd dots overflow a phone's width; past eight, a count reads better. + Text( + trf("{0} of {1}", pagerState.currentPage + 1, models.size), + fontSize = 14.sp, + color = PulseColors.textSecondary, + ) + } else if (models.size > 1) { models.forEachIndexed { index, model -> val isSelected = pagerState.currentPage == index Box( Modifier .size(width = 32.dp, height = 48.dp) - .clickable { scope.launch { pagerState.animateScrollToPage(index) } } + .clickable(role = Role.Tab) { scope.launch { pagerState.animateScrollToPage(index) } } .semantics { - contentDescription = "${model.displayName}, ${index + 1} of ${models.size}" + contentDescription = model.displayName + ", " + trf("{0} of {1}", index + 1, models.size) selected = isSelected }, contentAlignment = Alignment.Center, @@ -557,9 +567,10 @@ private fun DiscoveredRingRow(ring: RingBLEClient.DiscoveredRing, onClick: () -> .clip(RoundedCornerShape(8.dp)) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(8.dp)) - .clickable(onClick = onClick), + .heightIn(min = 48.dp) + .clickable(role = Role.Button, onClick = onClick), ) { - // Accent left-stripe marks devices recognized as rings. matchParentSize resolves after + // Success left-stripe (recognised is a status, not a tap colour) marks devices recognized as rings. matchParentSize resolves after // the Row below is measured, so the stripe spans the full row height. if (ring.isLikelyRing) { Box(Modifier.matchParentSize()) { @@ -568,22 +579,22 @@ private fun DiscoveredRingRow(ring: RingBLEClient.DiscoveredRing, onClick: () -> .align(Alignment.CenterStart) .fillMaxHeight() .width(2.dp) - .background(PulseColors.accent), + .background(PulseColors.success), ) } } Row( Modifier .fillMaxWidth() - .padding(horizontal = 12.dp, vertical = 10.dp), + .padding(horizontal = 12.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(10.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), ) { Icon( if (ring.isLikelyRing) Icons.Filled.CheckCircle else Icons.Filled.BluetoothSearching, contentDescription = null, modifier = Modifier.size(20.dp), - tint = if (ring.isLikelyRing) PulseColors.accent else PulseColors.textMuted, + tint = if (ring.isLikelyRing) PulseColors.success else PulseColors.textMuted, ) Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { Text( @@ -598,7 +609,7 @@ private fun DiscoveredRingRow(ring: RingBLEClient.DiscoveredRing, onClick: () -> WearableModel.model(ring.wearableModelID)?.displayName ?: ringModelLabel(ring.name, type), fontSize = 12.sp, - color = PulseColors.accent, + color = PulseColors.textSecondary, ) } } @@ -659,7 +670,7 @@ private fun ConnectedCard( Icon( Icons.Filled.Check, contentDescription = null, - modifier = Modifier.size(22.dp).scale(checkScale), + modifier = Modifier.size(24.dp).scale(checkScale), tint = PulseColors.success, ) Text( @@ -683,14 +694,14 @@ private fun BluetoothOffCard() { .fillMaxWidth() .clip(RoundedCornerShape(8.dp)) .background(PulseColors.card) - .padding(horizontal = 20.dp, vertical = 32.dp), + .padding(horizontal = 24.dp, vertical = 32.dp), horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(14.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), ) { Icon( Icons.Filled.BluetoothDisabled, contentDescription = null, - modifier = Modifier.size(34.dp), + modifier = Modifier.size(32.dp), tint = PulseColors.textMuted, ) Text( @@ -724,14 +735,14 @@ private fun BluetoothPermissionCard(permanentlyDenied: Boolean, onRequest: () -> .fillMaxWidth() .clip(RoundedCornerShape(8.dp)) .background(PulseColors.card) - .padding(horizontal = 20.dp, vertical = 32.dp), + .padding(horizontal = 24.dp, vertical = 32.dp), horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(14.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), ) { Icon( Icons.Filled.BluetoothDisabled, contentDescription = null, - modifier = Modifier.size(34.dp), + modifier = Modifier.size(32.dp), tint = PulseColors.textMuted, ) Text( 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 fd73ae8d..c4571359 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt @@ -250,12 +250,7 @@ fun ReadinessScreen(db: PulseLoopDatabase, onBack: () -> Unit) { val result = load.value Column(Modifier.fillMaxSize()) { - androidx.compose.material3.CenterAlignedTopAppBar( - title = { Text(tr("Readiness"), style = com.pulseloop.ui.theme.PulseType.title) }, - navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) } }, - windowInsets = androidx.compose.foundation.layout.WindowInsets(0, 0, 0, 0), - colors = androidx.compose.material3.TopAppBarDefaults.topAppBarColors(containerColor = PulseColors.background), - ) + com.pulseloop.ui.components.PulseTopBar(tr("Readiness"), onBack) Column( Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), @@ -445,10 +440,12 @@ private fun DataBehindScore(db: PulseLoopDatabase, result: Readiness.Result?) { } Column( Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) - .clickable { open = !open }.padding(16.dp), + .clickable(role = Role.Button, onClickLabel = if (open) tr("Hide") else tr("Show")) { open = !open } + .semantics { stateDescription = if (open) tr("Expanded") else tr("Collapsed") } + .padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { - Row(verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.heightIn(min = 24.dp), verticalAlignment = Alignment.CenterVertically) { Text(tr("Data behind this score"), fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, modifier = Modifier.weight(1f)) Text(if (open) tr("Hide") else tr("Show"), fontSize = 14.sp, color = PulseColors.accent) } 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 8431e2d8..eb005f40 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/Screens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/Screens.kt @@ -94,6 +94,9 @@ fun VitalsScreen( // failure copy tells the user to put the ring on rather than the generic "hold still" (issue #29). var measureNotWornHint by remember { mutableStateOf(false) } var measureDisconnectedHint by remember { mutableStateOf(false) } + // Set when a run ends without a failed leg, so the end of a measurement is said too (the card + // updating silently gave TalkBack nothing, and sighted users a value change to spot). + var measureSucceeded by remember { mutableStateOf(false) } // Two measurement flavours: // • combined (56ff/Jring): one 0x23 packet → BP + SpO₂ + stress + fatigue + blood sugar // • spot (Colmi): sequential live HR + SpO₂ via the real-time command (0x69) @@ -322,6 +325,7 @@ fun VitalsScreen( measuring = true measuringLabel = label measureFailed = false + measureSucceeded = false measureNotWornHint = false measureDisconnectedHint = false remaining = seconds @@ -348,6 +352,8 @@ fun VitalsScreen( measureFailed = true measureNotWornHint = coordinator.measureNotWorn measureDisconnectedHint = coordinator.measureDisconnected + } else { + measureSucceeded = true } viewModel?.refreshNow() // show the new reading immediately } @@ -476,6 +482,9 @@ fun VitalsScreen( ((total - remaining).toFloat() / total).coerceIn(0f, 1f) }, modifier = Modifier.fillMaxWidth(), + // Progress is a state, not a tap target: no mint. + color = PulseColors.textPrimary, + trackColor = PulseColors.elevated, ) Text( measureCaption, @@ -502,6 +511,15 @@ fun VitalsScreen( modifier = Modifier.padding(top = 4.dp).semantics { liveRegion = LiveRegionMode.Polite }, ) } + if (measureSucceeded && !measuring) { + Spacer(Modifier.height(8.dp)) + Text( + tr("Done. The new reading is on its card below."), + style = MaterialTheme.typography.bodySmall, + color = PulseColors.textSecondary, + modifier = Modifier.padding(top = 4.dp).semantics { liveRegion = LiveRegionMode.Polite }, + ) + } Spacer(Modifier.height(8.dp)) } @@ -663,20 +681,11 @@ fun VitalDetailScreen( val title = metricDisplayName(metric) + // Read once here so every time on this screen follows the phone's 12/24-hour setting. + val is24h = android.text.format.DateFormat.is24HourFormat(context) + Column(Modifier.fillMaxSize()) { - // Inline nav bar (iOS .navigationBarTitleDisplayMode(.inline)): back on the leading - // edge, title centered. - Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { - IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { - Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) - } - Text( - title, - modifier = Modifier.align(Alignment.Center), - style = MaterialTheme.typography.titleMedium, - fontWeight = FontWeight.SemiBold, - ) - } + com.pulseloop.ui.components.PulseTopBar(title = title, onBack = onBack) if (state.loading) { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { @@ -697,6 +706,11 @@ fun VitalDetailScreen( PeriodSegmentedControl(selected = state.period, onSelect = { vm.setPeriod(it) }) } state.adjustedNote?.let { note -> item { AdjustedCaption(note) } } + // Derived stress says so before the chart, not after it (issue #67): the number + // is an inference, and the chart is the first thing read. + if (metric == "stress" && state.isDerived) { + metricDisclaimer(metric, true)?.let { disclaimer -> item { DisclaimerCard(disclaimer) } } + } // 2. Chart card: unit label + interactive trend chart (24dp continuous corners). item { @@ -770,7 +784,7 @@ fun VitalDetailScreen( // line up with the plotted line (iOS #43 §2/§3). thresholds = displayThresholds(state.thresholds, metric, units, gUnit), timestamps = state.timestamps, - tooltipTimeFormatter = { ts -> tooltipTime(ts, state.period) }, + tooltipTimeFormatter = { ts -> tooltipTime(ts, state.period, is24h) }, // The whole calendar period, gaps included (issue #102). timeDomain = state.windowStart to state.windowEnd, usualRange = state.usualRange, @@ -897,7 +911,7 @@ fun VitalDetailScreen( color = PulseColors.textSecondary, ) Text( - metricExplainer(metric), + metricExplainer(metric, state.isDerived), fontSize = 14.sp, lineHeight = 18.sp, color = PulseColors.textSecondary, @@ -908,38 +922,43 @@ fun VitalDetailScreen( // 7. Estimated-metric disclaimer (BP + glucose, iOS warning card; plus derived // stress, issue #67 — the card that opened this chart labels its number, and this // chart shows the same number, so it says the same thing here). - metricDisclaimer(metric, state.isDerived)?.let { disclaimer -> - item { - val cardShape = RoundedCornerShape(8.dp) - Row( - Modifier - .fillMaxWidth() - .clip(cardShape) - .dither(ZonePalette.ZoneAmber, 0.10f) - .border(1.dp, ZonePalette.ZoneAmber.copy(alpha = 0.30f), cardShape) - .padding(16.dp), - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - Icon( - Icons.Filled.Warning, null, - tint = ZonePalette.ZoneAmber, - modifier = Modifier.size(18.dp), - ) - Text( - disclaimer, - fontSize = 12.sp, - lineHeight = 17.sp, - color = PulseColors.textSecondary, - modifier = Modifier.weight(1f), - ) - } - } + // Derived stress shows its card above the chart instead (see the top of this list). + if (!(metric == "stress" && state.isDerived)) { + metricDisclaimer(metric, state.isDerived)?.let { disclaimer -> item { DisclaimerCard(disclaimer) } } } } } } } +/** The amber "this is an estimate" card (BP, glucose, derived stress). */ +@Composable +private fun DisclaimerCard(disclaimer: String) { + val cardShape = RoundedCornerShape(8.dp) + Row( + Modifier + .fillMaxWidth() + .clip(cardShape) + .dither(ZonePalette.ZoneAmber, 0.10f) + .border(1.dp, ZonePalette.ZoneAmber.copy(alpha = 0.30f), cardShape) + .padding(16.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Icon( + Icons.Filled.Warning, null, + tint = ZonePalette.ZoneAmber, + modifier = Modifier.size(20.dp), + ) + Text( + disclaimer, + fontSize = 12.sp, + lineHeight = 17.sp, + color = PulseColors.textSecondary, + modifier = Modifier.weight(1f), + ) + } +} + /** * The window's individual readings, with a delete affordance per row (issue #60). * @@ -964,6 +983,7 @@ private fun ReadingsCard( // PAGE_SIZE is what someone scanning for a bad measurement actually reads. var visibleCount by remember(readings.size) { mutableStateOf(READINGS_PAGE_SIZE) } val cardShape = RoundedCornerShape(8.dp) + val is24h = android.text.format.DateFormat.is24HourFormat(LocalContext.current) fun readingText(r: VitalDetailViewModel.Reading): String { val primary = formatStat(r.value, metric, gUnit) @@ -1018,7 +1038,7 @@ private fun ReadingsCard( verticalAlignment = Alignment.CenterVertically, ) { Text( - tooltipTime(reading.timestamp, period), + tooltipTime(reading.timestamp, period, is24h), fontSize = 14.sp, color = PulseColors.textSecondary, modifier = Modifier.weight(1f), @@ -1065,11 +1085,10 @@ private fun ReadingsCard( text = { Text( buildString { - append(readingText(reading)) - if (unitLabel.isNotEmpty()) append(" $unitLabel") - append(" at ") - append(tooltipTime(reading.timestamp, period)) - append(".\n\nThis can't be undone.") + val value = readingText(reading) + if (unitLabel.isNotEmpty()) " $unitLabel" else "" + append(trf("{0} at {1}.", value, tooltipTime(reading.timestamp, period, is24h))) + append("\n\n") + append(tr("This can't be undone.")) // Say so plainly rather than letting a user wonder why the reading // didn't come back after a re-sync — that is deliberate. if (reading.fromHistory) { @@ -1198,7 +1217,11 @@ private fun metricDisplayName(metric: String): String = when (metric) { } /** "WHAT THIS MEANS" copy, verbatim from iOS MetricDetailView `explainerText`. */ -private fun metricExplainer(metric: String): String = when (metric) { +private fun metricExplainer(metric: String, isDerived: Boolean = false): String = + // A derived score is not "based on heart-rate patterns" from the ring: say what it is. + if (metric == "stress" && isDerived) tr("A wellness score from 0–100 worked out from your HRV against your own usual range. " + + "Lower is calmer. It's an estimate, not a medical stress measure.") + else when (metric) { "hr" -> tr("Resting heart rate reflects how hard your heart works at rest. A typical adult range is 60–100 bpm; " + "fitness, medication, caffeine, and stress all shift it.") "spo2" -> tr("Blood oxygen (SpO₂) is the percentage of oxygen your blood carries. 95–100% is normal; " + @@ -1221,23 +1244,23 @@ private fun metricExplainer(metric: String): String = when (metric) { private fun dateLabel(anchor: Long, period: Period): String { val zone = java.time.ZoneId.systemDefault() val dt = java.time.Instant.ofEpochMilli(anchor).atZone(zone) + // The locale's own order and month names (was ISO "2026-11-04" and English "NOV"). + val fmt = com.pulseloop.ui.components.PhoneFormat return when (period) { - Period.DAY -> dt.toLocalDate().toString() - Period.WEEK -> { - val end = dt.plusDays(6) - "${dt.toLocalDate()} – ${end.toLocalDate()}" - } - Period.MONTH -> "${dt.month.name.take(3)} ${dt.year}" + Period.DAY -> fmt.date("EEEMMMd", dt) + Period.WEEK -> "${fmt.date("MMMd", dt)} – ${fmt.date("MMMd", dt.plusDays(6))}" + Period.MONTH -> fmt.date("yMMMM", dt) } } /** Precise time label for the chart scrub tooltip, formatted per aggregation period. */ -private fun tooltipTime(ts: Long, period: Period): String { +private fun tooltipTime(ts: Long, period: Period, is24h: Boolean): String { val z = java.time.Instant.ofEpochMilli(ts).atZone(java.time.ZoneId.systemDefault()) + val fmt = com.pulseloop.ui.components.PhoneFormat return when (period) { - Period.DAY -> z.format(java.time.format.DateTimeFormatter.ofPattern("h:mm a", java.util.Locale.getDefault())) - Period.WEEK -> "${z.dayOfWeek.name.take(3)} ${z.dayOfMonth}" - Period.MONTH -> "${z.month.name.take(3)} ${z.dayOfMonth}" + Period.DAY -> fmt.clock(is24h, ts) + Period.WEEK -> fmt.date("EEEd", z) + Period.MONTH -> fmt.date("MMMd", z) } } @@ -1286,9 +1309,8 @@ private fun MeasurePickerSheet(titles: List, onDismiss: () -> Unit, onPi ) { Text(tr("Measure"), fontSize = 20.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(tr("Keep the ring snug and your hand still until it finishes."), fontSize = 14.sp, color = PulseColors.textSecondary) - titles.forEachIndexed { i, t -> - SheetOption(t, tr("Tap to start"), Icons.Filled.MonitorHeart) { onPick(i) } - } + // Title only: "Tap to start" under every option said what a row always means. + titles.forEachIndexed { i, t -> MeasureOptionRow(t) { onPick(i) } } } } } @@ -1315,3 +1337,24 @@ private fun VitalsStatusLine() { overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, ) } + +/** One row of the Measure sheet: icon and title, a 48dp+ target. */ +@Composable +private fun MeasureOptionRow(title: String, onClick: () -> Unit) { + val shape = RoundedCornerShape(8.dp) + Row( + Modifier + .fillMaxWidth() + .heightIn(min = 56.dp) + .clip(shape) + .background(PulseColors.card) + .border(1.dp, PulseColors.borderSubtle, shape) + .clickable(role = Role.Button, onClick = onClick) + .padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Icon(Icons.Filled.MonitorHeart, null, Modifier.size(24.dp), tint = PulseColors.accent) + Text(title, fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + } +} 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 b840d721..89695561 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt @@ -94,22 +94,25 @@ fun SettingsScreen( navController?.navigate(route) } + // Settings is pushed from the header's gear, so it wears the shared pushed-screen bar + // (centred title + back) like its own sub-screens, instead of a bare headline. + Column(Modifier.fillMaxSize()) { + com.pulseloop.ui.components.PulseTopBar(title = tr("Settings"), onBack = { navController?.popBackStack() }) Column( Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), - verticalArrangement = Arrangement.spacedBy(20.dp), + verticalArrangement = Arrangement.spacedBy(24.dp), ) { - Text(tr("Settings"), style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold) 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) + // Same footprint as the hero card (16 dp padding, 72 dp art, 8 dp gap, 48 dp action) // so the rows below don't jump when the stored ring arrives. Box( Modifier .fillMaxWidth() - .height(166.dp) + .height(160.dp) .clip(RoundedCornerShape(8.dp)) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(8.dp)), @@ -133,11 +136,11 @@ fun SettingsScreen( SettingsSection( title = tr("My ring"), rows = buildList { - add(SettingsRowItem(Icons.Filled.Watch, PulseColors.accent, tr("Ring & sync")) { + add(SettingsRowItem(Icons.Filled.Watch, PulseColors.battery, tr("Ring & sync")) { navigate("settings/wearable") }) if (capabilities.contains(WearableCapability.MEASUREMENT_INTERVAL)) { - add(SettingsRowItem(Icons.Filled.Timer, PulseColors.spo2, tr("Measurement Frequency")) { + add(SettingsRowItem(Icons.Filled.Timer, PulseColors.spo2, tr("Measurement frequency")) { navigate("settings/measurement") }) } @@ -181,7 +184,7 @@ fun SettingsScreen( SettingsSection( title = tr("AI Coach"), rows = listOf( - SettingsRowItem(Icons.Filled.AutoAwesome, PulseColors.accent, tr("AI Coach"), coachTrailing) { + SettingsRowItem(Icons.Filled.AutoAwesome, PulseColors.sleep, tr("AI Coach"), coachTrailing) { navigate("settings/coach") }, ), @@ -205,7 +208,7 @@ fun SettingsScreen( SettingsSection( title = tr("Me"), rows = listOf( - SettingsRowItem(Icons.Filled.AccountCircle, PulseColors.accent, tr("User Profile")) { + SettingsRowItem(Icons.Filled.AccountCircle, PulseColors.textSecondary, tr("User profile")) { navigate("settings/profile") }, SettingsRowItem(Icons.Filled.MonitorHeart, PulseColors.hrv, tr("Physiology")) { @@ -237,4 +240,5 @@ fun SettingsScreen( Spacer(Modifier.height(32.dp)) } + } } 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 3bf89544..e71799dd 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt @@ -124,16 +124,9 @@ internal fun SettingsSubScreen( // is what produced the tall dead band above every settings title. contentWindowInsets = WindowInsets(0, 0, 0, 0), topBar = { - TopAppBar( - title = { Text(title) }, - navigationIcon = { - IconButton(onClick = onBack) { - Icon(Icons.AutoMirrored.Filled.ArrowBack, tr("Back")) - } - }, - windowInsets = WindowInsets(0, 0, 0, 0), - colors = TopAppBarDefaults.topAppBarColors(containerColor = PulseColors.background), - ) + // The shared pushed-screen bar (centred title, one back arrow), like every other + // pushed screen; it applies no insets of its own either. + com.pulseloop.ui.components.PulseTopBar(title = title, onBack = onBack) }, ) { padding -> Box(Modifier.fillMaxSize().padding(padding)) { @@ -573,7 +566,9 @@ fun CoachSettingsScreen(onBack: () -> Unit) { localProbeOk = false; localProbeResult = e.reason } catch (e: Exception) { localProbeOk = false - localProbeResult = e.message ?: tr("Couldn't reach the server.") + // The exception text names the HTTP stack; it goes to logcat. + android.util.Log.w("CoachSettings", "Local probe failed", e) + localProbeResult = tr("Couldn't reach the server.") } localProbeBusy = false } @@ -1222,7 +1217,7 @@ fun ProfileSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> Unit, ) } - SettingsSubScreen(title = tr("User Profile"), onBack = onBack) { + SettingsSubScreen(title = tr("User profile"), onBack = onBack) { Text( tr("Your age, sex, height and weight let the ring compute accurate calories (and, on " + "56ff/Jring rings, blood sugar). Blood pressure is measured directly by the sensor."), @@ -1694,7 +1689,7 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U } } - SettingsSubScreen(title = tr("Measurement Frequency"), onBack = onBack) { + SettingsSubScreen(title = tr("Measurement frequency"), onBack = onBack) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { Text(tr("Measurement"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) @@ -2038,7 +2033,7 @@ fun WearableSettingsScreen( Column(Modifier.padding(16.dp)) { Row(verticalAlignment = Alignment.CenterVertically) { Icon( - Icons.Filled.Bluetooth, null, Modifier.size(18.dp), + Icons.Filled.Bluetooth, null, Modifier.size(20.dp), tint = if (isConnected) PulseColors.success else MaterialTheme.colorScheme.onSurfaceVariant, ) Spacer(Modifier.width(8.dp)) @@ -2146,7 +2141,7 @@ fun WearableSettingsScreen( ) { Icon(Icons.Filled.DeleteForever, null, Modifier.size(16.dp)) Spacer(Modifier.width(4.dp)) - Text(tr("Forget Ring")) + Text(tr("Forget ring")) } // Factory reset — destructive, ring-side wipe. Only for connected rings that @@ -2168,7 +2163,7 @@ fun WearableSettingsScreen( ) { Icon(Icons.Filled.Refresh, null, Modifier.size(16.dp)) Spacer(Modifier.width(4.dp)) - Text(if (resetting) (resetStatus.ifEmpty { tr("Resetting…") }) else tr("Factory Reset Ring")) + Text(if (resetting) (resetStatus.ifEmpty { tr("Resetting…") }) else tr("Factory reset ring")) } } } @@ -2510,7 +2505,7 @@ fun PrivacyDataSettingsScreen( // Data Backup — export/import full app data as JSON. Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text(tr("Data Backup"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Data backup"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(8.dp)) Text( tr("Export all your data to a single JSON file for backup, device migration, or external analysis. Import restores everything — replacing all current data."), @@ -2526,7 +2521,7 @@ fun PrivacyDataSettingsScreen( ) Spacer(Modifier.height(12.dp)) Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - PulseButton( + PulseButton(PulseButtonStyle.Tonal, onClick = { exportInProgress = true scope.launch { @@ -2554,7 +2549,7 @@ fun PrivacyDataSettingsScreen( CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp) Spacer(Modifier.width(8.dp)) } - Text(if (exportInProgress) tr("Exporting…") else tr("Export All Data")) + Text(if (exportInProgress) tr("Exporting…") else tr("Export all data")) } PulseButton(PulseButtonStyle.Outlined, onClick = { @@ -2567,7 +2562,7 @@ fun PrivacyDataSettingsScreen( CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp) Spacer(Modifier.width(8.dp)) } - Text(if (importInProgress) tr("Importing…") else tr("Import Data")) + Text(if (importInProgress) tr("Importing…") else tr("Import data")) } } } @@ -2578,10 +2573,12 @@ fun PrivacyDataSettingsScreen( // App data — destructive reset/restore actions. Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text(tr("App Data"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("App data"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(8.dp)) + // Unpairing lives on Ring & sync only (one place for the ring); this card only + // erases the app's own data. Text( - tr("Destructive actions: reset app data, or unpair the ring and reset. To only forget the ring, use Ring & sync."), + tr("Erases everything stored in the app. To also unpair your ring, forget it in Ring & sync first."), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -2593,17 +2590,7 @@ fun PrivacyDataSettingsScreen( ) { Icon(Icons.Filled.DeleteForever, null, Modifier.size(16.dp)) Spacer(Modifier.width(4.dp)) - Text(tr("Reset App Data")) - } - Spacer(Modifier.height(8.dp)) - PulseButton(PulseButtonStyle.Outlined, - onClick = { pendingReset = ResetAction.UnpairAndReset }, - modifier = Modifier.fillMaxWidth(), - colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.error), - ) { - Icon(Icons.Filled.Warning, null, Modifier.size(16.dp)) - Spacer(Modifier.width(4.dp)) - Text(tr("Unpair & Reset")) + Text(tr("Reset app data")) } } } @@ -2611,7 +2598,7 @@ fun PrivacyDataSettingsScreen( // Demo data — Android-only (iOS seeds via the Simulator's SeedData). Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Text(tr("Demo Data"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(tr("Demo data"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(8.dp)) Text( tr("Explore the app without a ring. Seeds activity, HR, SpO2, sleep, and a coach conversation."), @@ -2619,12 +2606,12 @@ fun PrivacyDataSettingsScreen( color = MaterialTheme.colorScheme.onSurfaceVariant, ) Spacer(Modifier.height(12.dp)) - PulseButton(onClick = { showSeedDialog = true }, modifier = Modifier.fillMaxWidth()) { - Text(tr("Reseed Demo Data")) + PulseButton(PulseButtonStyle.Tonal, onClick = { showSeedDialog = true }, modifier = Modifier.fillMaxWidth()) { + Text(tr("Reseed demo data")) } Spacer(Modifier.height(8.dp)) PulseButton(PulseButtonStyle.Outlined, onClick = { showClearDialog = true }, modifier = Modifier.fillMaxWidth()) { - Text(tr("Clear Demo Data"), color = PulseColors.danger) + Text(tr("Clear demo data"), color = PulseColors.danger) } } } @@ -2660,7 +2647,7 @@ fun PrivacyDataSettingsScreen( Switch(checked = maskSensitive, onCheckedChange = null) } Spacer(Modifier.height(12.dp)) - PulseButton( + PulseButton(PulseButtonStyle.Tonal, onClick = { scope.launch { val db = PulseLoopDatabase.getInstance(context) @@ -2675,7 +2662,7 @@ fun PrivacyDataSettingsScreen( ) { Icon(Icons.Filled.Share, null) Spacer(Modifier.width(8.dp)) - Text(if (maskSensitive) tr("Export Diagnostics") else tr("Export Full (Unmasked)")) + Text(if (maskSensitive) tr("Export diagnostics") else tr("Export full (unmasked)")) } } } @@ -2697,7 +2684,7 @@ fun PrivacyDataSettingsScreen( showImportSuccess -> AlertDialog( onDismissRequest = { showImportSuccess = false }, - title = { Text(tr("Import Complete")) }, + title = { Text(tr("Import complete")) }, text = { Text(tr("Your data has been restored from the backup.")) }, confirmButton = { PulseButton(PulseButtonStyle.Text, onClick = { showImportSuccess = false }) { Text(tr("OK")) } @@ -2761,7 +2748,7 @@ fun PrivacyDataSettingsScreen( showSeedDialog -> AlertDialog( onDismissRequest = { showSeedDialog = false }, - title = { Text(tr("Reseed Demo Data?")) }, + title = { Text(tr("Reseed demo data?")) }, text = { Text(tr("This will replace all existing demo data. Your synced ring data — including sleep history — will not be affected.")) }, confirmButton = { PulseButton(PulseButtonStyle.Text, onClick = { @@ -2779,7 +2766,7 @@ fun PrivacyDataSettingsScreen( showClearDialog -> AlertDialog( onDismissRequest = { showClearDialog = false }, - title = { Text(tr("Clear Demo Data?")) }, + title = { Text(tr("Clear demo data?")) }, text = { Text( tr("Removes all demo measurements, activity, sleep, and the demo device. " + @@ -3136,7 +3123,8 @@ fun StravaSettingsScreen(onBack: () -> Unit) { else -> trf("Uploaded {0} workouts", count) } } catch (e: Exception) { - statusMessage = trf("Upload failed: {0}", e.message ?: tr("unknown error")) + android.util.Log.w("StravaSettings", "Upload failed", e) + statusMessage = tr("Upload failed. Check your connection and try again.") } isUploading = false } 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 037a580b..e60f67ca 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt @@ -54,6 +54,7 @@ import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.clearAndSetSemantics 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.TextOverflow @@ -96,6 +97,8 @@ fun SleepScreen( bottomBarPadding: androidx.compose.ui.unit.Dp = 0.dp, ) { LaunchedEffect(Unit) { onOpen() } + // Read once per composition so every time on this screen follows the phone's 12/24-hour setting. + sleepClock24h = android.text.format.DateFormat.is24HourFormat(androidx.compose.ui.platform.LocalContext.current) val state by (viewModel?.state?.collectAsState() ?: remember { mutableStateOf(SleepViewModel.SleepState()) }) LazyColumn( @@ -140,23 +143,9 @@ private fun androidx.compose.foundation.lazy.LazyListScope.dayItems( when { sessions.isEmpty() -> { val noData = SleepInsights.noDataState(SleepRangeKey.DAY) + // One empty state: the hero says there is no night and what to do. The empty hypnogram + // card and three "—" stage cards used to say the same thing twice more. item { SleepHeroCard(label = noData.label, value = noData.value, support = noData.support, score = null, scoreLabel = null, noData = true) } - item { - VisualizationCard(eyebrow = tr("Stages"), title = tr("Sleep architecture"), legend = false) { - Column( - Modifier.fillMaxWidth().height(180.dp), - verticalArrangement = Arrangement.Center, - horizontalAlignment = Alignment.CenterHorizontally, - ) { - Text(tr("No sleep recorded"), fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary) - Text( - tr("Wear your ring overnight to see your hypnogram here."), - fontSize = 12.sp, color = PulseColors.textMuted, - ) - } - } - } - item { SleepStageSummaryCards(deep = "—", light = "—", awake = "—") } } // Single session: render exactly as before, no carousel chrome. sessions.size == 1 -> sessionPageItems(sessions[0], state.dayBlocks[sessions[0].id] ?: emptyList(), viewModel, state.goalMinutes) @@ -287,7 +276,8 @@ private fun SleepCarousel( .size(7.dp) .clip(CircleShape) .background( - if (i == pagerState.currentPage) PulseColors.accent + // A position, not a tap target: no mint. + if (i == pagerState.currentPage) PulseColors.textPrimary else PulseColors.textSecondary.copy(alpha = 0.3f), ), ) @@ -332,7 +322,8 @@ private fun androidx.compose.foundation.lazy.LazyListScope.aggregateItems( ) } } - item { + // Without averages the three cards were three more "—": the hero already says there's no data. + if (state.stageAvg != null) item { SleepStageSummaryCards( prefix = tr("Avg "), deep = state.stageAvg?.let { SleepFormat.duration(it.first) } ?: "—", @@ -382,7 +373,7 @@ private fun SleepHeroCard( .background(PulseColors.card) .ditherFade(PulseColors.sleep, 0.16f, 0f) .border(1.dp, PulseColors.borderSubtle, shape) - .padding(20.dp), + .padding(24.dp), horizontalArrangement = Arrangement.spacedBy(12.dp), ) { Column(Modifier.weight(1f)) { @@ -401,7 +392,8 @@ private fun SleepHeroCard( Text(support, fontSize = 14.sp, color = PulseColors.textSecondary, modifier = Modifier.padding(top = 8.dp)) } } - Column(horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(4.dp)) { + // No night, no score: a big "—" beside "No sleep captured" was a third way of saying it. + if (!noData) Column(horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(4.dp)) { Text( score?.toString() ?: "—", fontSize = 40.sp, fontWeight = FontWeight.SemiBold, @@ -498,6 +490,13 @@ private fun SleepHypnogram( "AWAKE" -> PulseColors.stageAwake else -> PulseColors.stageLight } + fun stageName(stage: String): String = when (stage) { + "DEEP" -> tr("Deep") + "LIGHT" -> tr("Light") + "REM" -> tr("REM") + "AWAKE" -> tr("Awake") + else -> stage + } val sorted = remember(blocks) { blocks.filter { it.durationMinutes > 0 && it.stageRaw != "UNKNOWN" }.sortedBy { it.startMinute } } @@ -551,14 +550,14 @@ private fun SleepHypnogram( val summary = remember(sorted, startTs, safeTotal) { val perStage = sorted.groupBy { it.stageRaw }.mapValues { (_, b) -> b.sumOf { it.durationMinutes } } val parts = lanes.reversed().mapNotNull { stage -> - perStage[stage]?.let { "${if (stage == "REM") "REM" else stage.lowercase()} ${SleepFormat.duration(it)}" } + perStage[stage]?.let { "${stageName(stage)} ${SleepFormat.duration(it)}" } } trf("Sleep stages from {0} to {1}", clockTime(startTs), clockTime(startTs + safeTotal * 60_000L)) + - if (parts.isEmpty()) ": no stage data" else ": " + parts.joinToString(", ") + if (parts.isEmpty()) ": " + tr("no stage data") else ": " + parts.joinToString(", ") } fun readoutText(block: SleepStageBlockEntity): String { - val stage = block.stageRaw.replaceFirstChar { it.uppercase() } + val stage = stageName(block.stageRaw) val startTime = clockTime(startTs + block.startMinute * 60_000L) val endTime = clockTime(startTs + (block.startMinute + block.durationMinutes) * 60_000L) return "$stage · $startTime – $endTime" @@ -571,7 +570,7 @@ private fun SleepHypnogram( .height(height - 22.dp) .clip(RoundedCornerShape(8.dp)) .background(PulseColors.card) - .border(1.dp, Color.White.copy(alpha = 0.06f), RoundedCornerShape(8.dp)) + .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(8.dp)) .clearAndSetSemantics { contentDescription = summary }, ) { var plotWidthPx by remember { mutableFloatStateOf(0f) } @@ -667,7 +666,7 @@ private fun SleepHypnogram( if (isScrubbing && scrubBlockIndex in sorted.indices) { val sx = xForMinute(scrubMinute, size.width) drawLine( - color = Color.White.copy(alpha = 0.7f), + color = PulseColors.textPrimary.copy(alpha = 0.7f), start = Offset(sx, 0f), end = Offset(sx, size.height), strokeWidth = 2.dp.toPx(), @@ -684,7 +683,7 @@ private fun SleepHypnogram( val yFrac = laneFrac[stage] ?: 0.62f val labelY = yFrac * plotHeightPx Text( - stage, + stageName(stage).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, // Not the stage colour: DEEP's is 2.4:1 on the card. The bars and // legend swatches carry the colour. @@ -721,14 +720,14 @@ private fun SleepHypnogram( ) { androidx.compose.foundation.layout.Box( Modifier - .background(Color.Black.copy(alpha = 0.85f), RoundedCornerShape(4.dp)) + .background(PulseColors.elevated, RoundedCornerShape(4.dp)) .padding(horizontal = 12.dp, vertical = 8.dp), ) { Text( readoutText(block), fontSize = 12.sp, fontWeight = FontWeight.Medium, - color = Color.White, + color = PulseColors.textPrimary, ) } } @@ -877,7 +876,7 @@ private fun SleepDayNavHeader(state: SleepViewModel.SleepState, viewModel: Sleep Modifier .weight(1f) .clip(RoundedCornerShape(4.dp)) - .clickable(role = Role.Button) { showPicker = true } + .clickable(role = Role.Button, onClickLabel = tr("Pick a day")) { showPicker = true } .padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { @@ -981,9 +980,9 @@ private fun dayLabel(dayMillis: Long): String { return when { daysAgo <= 0 -> tr("Today") daysAgo == 1 -> tr("Yesterday") - daysAgo < 7 -> date.format(java.time.format.DateTimeFormatter.ofPattern("EEEE")) - date.year == java.time.Year.now().value -> date.format(java.time.format.DateTimeFormatter.ofPattern("EEE, MMM d")) - else -> date.format(java.time.format.DateTimeFormatter.ofPattern("MMM d, yyyy")) + daysAgo < 7 -> com.pulseloop.ui.components.PhoneFormat.date("EEEE", date) + date.year == java.time.Year.now().value -> com.pulseloop.ui.components.PhoneFormat.date("EEEMMMd", date) + else -> com.pulseloop.ui.components.PhoneFormat.date("yMMMd", date) } } @@ -993,12 +992,15 @@ private fun daySubLabel(dayMillis: Long): String { val daysAgo = ((today - dayMillis) / 86_400_000L).toInt() if (daysAgo >= 7) return "" val date = java.time.Instant.ofEpochMilli(dayMillis).atZone(java.time.ZoneId.systemDefault()) - return date.format(java.time.format.DateTimeFormatter.ofPattern("EEE, MMM d")).uppercase(java.util.Locale.ROOT) + return com.pulseloop.ui.components.PhoneFormat.date("EEEMMMd", date).uppercase(java.util.Locale.ROOT) } // ─────────────────────────── Helpers ─────────────────────────── -private fun clockTime(ts: Long): String = SleepFormat.clockTime(ts) +/** Set by [SleepScreen] on each composition from the phone's 12/24-hour setting. */ +@Volatile private var sleepClock24h: Boolean = false + +private fun clockTime(ts: Long): String = com.pulseloop.ui.components.PhoneFormat.clock(sleepClock24h, ts) private fun qualityText(label: SleepQualityLabel): String = when (label) { SleepQualityLabel.EXCELLENT -> tr("Excellent") @@ -1041,10 +1043,12 @@ private fun SleepRecordsCard( viewModel: SleepViewModel?, ) { val scope = androidx.compose.runtime.rememberCoroutineScope() - val context = androidx.compose.ui.platform.LocalContext.current // Two-step delete (the vitals/activity pattern): a row's trash icon arms the confirm dialog. var pendingRun by remember { mutableStateOf(null) } var editingRun by remember { mutableStateOf(null) } + // A failed edit or delete is said inline, under the records it concerns (was a Toast, which + // TalkBack can miss and which vanishes before it is read). + var failure by remember { mutableStateOf(null) } VisualizationCard( eyebrow = tr("Records"), // One run only happens on a carousel page, which may be a nap rather than a night. @@ -1063,7 +1067,7 @@ private fun SleepRecordsCard( ) Column(Modifier.weight(1f)) { Text( - "${SleepFormat.clockTime(run.startAt)} – ${SleepFormat.clockTime(run.endAt)}", + "${clockTime(run.startAt)} – ${clockTime(run.endAt)}", fontSize = 14.sp, color = PulseColors.textPrimary, ) @@ -1108,6 +1112,12 @@ private fun SleepRecordsCard( ) } } + failure?.let { + Text( + it, fontSize = 12.sp, color = PulseColors.danger, + modifier = Modifier.semantics { liveRegion = androidx.compose.ui.semantics.LiveRegionMode.Polite }, + ) + } } } @@ -1117,13 +1127,10 @@ private fun SleepRecordsCard( onDismiss = { editingRun = null }, onSave = { newStart, newEnd -> editingRun = null + failure = null scope.launch { val updated = viewModel?.editSleepRecord(session.id, run.recordStartAt, newStart, newEnd) ?: false - if (!updated) { - android.widget.Toast.makeText( - context, tr("Couldn't update this record"), android.widget.Toast.LENGTH_SHORT, - ).show() - } + if (!updated) failure = tr("Couldn't update this record") } }, ) @@ -1135,19 +1142,16 @@ private fun SleepRecordsCard( title = { Text(tr("Delete this record?")) }, text = { Text( - trf("{0} – {1} leaves tonight's totals and the hypnogram, and it won't come back on re-sync.", SleepFormat.clockTime(run.startAt), SleepFormat.clockTime(run.endAt)), + trf("{0} – {1} leaves tonight's totals and the hypnogram, and it won't come back on re-sync.", clockTime(run.startAt), clockTime(run.endAt)), ) }, confirmButton = { PulseButton(PulseButtonStyle.Text, onClick = { pendingRun = null + failure = null scope.launch { val removed = viewModel?.deleteSleepRecord(session.id, run.recordStartAt) ?: false - if (!removed) { - android.widget.Toast.makeText( - context, tr("Couldn't delete this record"), android.widget.Toast.LENGTH_SHORT, - ).show() - } + if (!removed) failure = tr("Couldn't delete this record") } }) { Text(tr("Delete"), color = PulseColors.danger) } }, @@ -1191,18 +1195,18 @@ private fun SleepRecordEditDialog( onClick = { pickingTime = "start" }, modifier = Modifier.weight(1f), ) { - Text(trf("Start: {0}", SleepFormat.clockTime(currentStart))) + Text(trf("Start: {0}", clockTime(currentStart))) } PulseButton(PulseButtonStyle.Outlined, onClick = { pickingTime = "end" }, modifier = Modifier.weight(1f), ) { - Text(trf("End: {0}", SleepFormat.clockTime(currentEnd))) + Text(trf("End: {0}", clockTime(currentEnd))) } } if (pickedOutside) { Text( - trf("This record runs {0} – {1}. You can only shorten it.", SleepFormat.clockTime(run.startAt), SleepFormat.clockTime(run.endAt)), + trf("This record runs {0} – {1}. You can only shorten it.", clockTime(run.startAt), clockTime(run.endAt)), color = PulseColors.danger, fontSize = 12.sp, ) 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 d44b1bd9..53d2400e 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt @@ -30,6 +30,8 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.semantics.Role +import com.pulseloop.ui.theme.PulseType import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp @@ -96,8 +98,9 @@ fun TodayGlance( .clip(shape) .dither(PulseColors.warning, 0.12f) .border(1.dp, PulseColors.warning, shape) - .clickable(onClick = onAlert) - .padding(horizontal = 12.dp, vertical = 10.dp), + .heightIn(min = 48.dp) + .clickable(role = Role.Button, onClick = onAlert) + .padding(horizontal = 12.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), ) { @@ -120,7 +123,7 @@ fun TodayGlance( overflow = TextOverflow.Ellipsis, modifier = Modifier .fillMaxWidth() - .then(if (onInsight != null) Modifier.clickable(onClick = onInsight) else Modifier) + .then(if (onInsight != null) Modifier.clickable(role = Role.Button, onClick = onInsight) else Modifier) .padding(horizontal = 4.dp), ) } else if (insightPending) { @@ -139,35 +142,44 @@ fun LastNightCard( /** The morning after drinks (docs/drinks-plan.md): what last night's drinks did to the night. */ drinksLine: String? = null, onDrinks: (() -> Unit)? = null, + /** + * The Sleep tile is on the grid and already shows the duration and score: the card then + * carries only what the tile can't, the drinks line (less-is-more, question 2). + */ + drinksOnly: Boolean = false, ) { Column( Modifier .fillMaxWidth() .clip(RoundedCornerShape(8.dp)) .background(PulseColors.card) - .clickable(onClick = onOpen) + .clickable(role = Role.Button, onClick = onOpen) .padding(16.dp), verticalArrangement = Arrangement.spacedBy(4.dp), ) { - Text(tr("LAST NIGHT"), fontSize = 12.sp, letterSpacing = 1.8.sp, color = PulseColors.sleep) - Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(12.dp)) { - Text(durationText, fontSize = 24.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - score?.let { - Text(trf("score {0}", it), fontSize = 14.sp, color = PulseColors.textSecondary, modifier = Modifier.padding(bottom = 4.dp)) + Text(tr("LAST NIGHT"), style = PulseType.eyebrow, color = PulseColors.textSecondary) + if (!drinksOnly || drinksLine == null) { + Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Text(durationText, fontSize = 24.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + score?.let { + Text(trf("score {0}", it), fontSize = 14.sp, color = PulseColors.textSecondary, modifier = Modifier.padding(bottom = 4.dp)) + } } + window?.let { Text(it, fontSize = 14.sp, color = PulseColors.textMuted) } } - window?.let { Text(it, fontSize = 14.sp, color = PulseColors.textMuted) } drinksLine?.let { line -> Text( line, fontSize = 14.sp, color = PulseColors.textPrimary, modifier = Modifier - .padding(top = 6.dp) + .padding(top = 8.dp) .fillMaxWidth() + .heightIn(min = 48.dp) .clip(RoundedCornerShape(4.dp)) .dither(PulseColors.drinks, 0.10f) - .then(if (onDrinks != null) Modifier.clickable(onClick = onDrinks) else Modifier) - .padding(horizontal = 10.dp, vertical = 8.dp), + .then(if (onDrinks != null) Modifier.clickable(role = Role.Button, onClick = onDrinks) else Modifier) + .wrapContentHeight(Alignment.CenterVertically) + .padding(horizontal = 12.dp, vertical = 8.dp), ) } } @@ -184,12 +196,12 @@ internal fun SheetOption(title: String, subtitle: String, icon: ImageVector, onC .clip(shape) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, shape) - .clickable(interactionSource = press, indication = androidx.compose.foundation.LocalIndication.current, onClick = onClick) + .clickable(interactionSource = press, indication = androidx.compose.foundation.LocalIndication.current, role = Role.Button, onClick = onClick) .padding(16.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { - Icon(icon, null, Modifier.size(22.dp), tint = PulseColors.accent) + Icon(icon, null, Modifier.size(24.dp), tint = PulseColors.accent) Column { Text(title, fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(subtitle, fontSize = 12.sp, color = PulseColors.textSecondary) @@ -217,19 +229,19 @@ fun CoachBriefSheet( Modifier .fillMaxWidth() .verticalScroll(androidx.compose.foundation.rememberScrollState()) - .padding(horizontal = 20.dp) + .padding(horizontal = 16.dp) .padding(bottom = 32.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) { - Text(tr("TODAY'S BRIEF"), fontSize = 12.sp, letterSpacing = 1.6.sp, color = PulseColors.accent) + Text(tr("TODAY'S BRIEF"), style = PulseType.eyebrow, color = PulseColors.textSecondary) Text(title, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(body, fontSize = 16.sp, lineHeight = 22.sp, color = PulseColors.textSecondary) if (chips.isNotEmpty()) { // Wraps rather than squeezing the third chip on a narrow phone or at a large font. FlowRow( Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(6.dp), - verticalArrangement = Arrangement.spacedBy(6.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), ) { chips.take(3).forEach { Text( @@ -239,7 +251,7 @@ fun CoachBriefSheet( .clip(RoundedCornerShape(16.dp)) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(16.dp)) - .padding(horizontal = 10.dp, vertical = 5.dp), + .padding(horizontal = 12.dp, vertical = 4.dp), ) } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/TodayPrograms.kt b/app/src/main/java/com/pulseloop/ui/screens/TodayPrograms.kt index 7b2abae2..d2279724 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayPrograms.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayPrograms.kt @@ -23,6 +23,7 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color 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.TextOverflow import androidx.compose.ui.unit.dp @@ -82,12 +83,12 @@ private fun ProgramChip(c: Chip) { .clip(shape) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, shape) - .clickable(onClick = c.onClick) + .clickable(role = Role.Button, onClick = c.onClick) .padding(horizontal = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), ) { - Icon(c.icon, null, Modifier.size(18.dp), tint = c.tint) + Icon(c.icon, null, Modifier.size(24.dp), tint = c.tint) Text(c.label, fontSize = 14.sp, color = PulseColors.textPrimary, maxLines = 1, overflow = TextOverflow.Ellipsis) } } @@ -107,7 +108,8 @@ fun RestModeLine(offerIt: Boolean) { Modifier.fillMaxWidth().clip(shape).background(PulseColors.card).padding(start = 12.dp), verticalAlignment = Alignment.CenterVertically, ) { - Icon(Icons.Filled.SelfImprovement, null, Modifier.size(18.dp), tint = PulseColors.readiness) + // Not mint: mint marks what to tap, and the tap is the action word on the right. + Icon(Icons.Filled.SelfImprovement, null, Modifier.size(24.dp), tint = PulseColors.textSecondary) Text( if (u != null) trf("Rest Mode on until {0}", u.format(DateTimeFormatter.ofPattern("EEE d MMM"))) else tr("Feeling unwell? Pause activity nudges for 3 days."), @@ -121,7 +123,7 @@ fun RestModeLine(offerIt: Boolean) { modifier = Modifier .widthIn(max = 140.dp) .heightIn(min = 48.dp) - .clickable { + .clickable(role = Role.Button) { RestMode.set(context, if (u != null) null else 3) until = RestMode.until(context) } 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 5db430df..347b351b 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt @@ -320,6 +320,7 @@ fun TodayScreen( onOpen = { navController?.navigate("sleep") }, drinksLine = drinks?.morningAfter?.let { com.pulseloop.service.DrinksRepository.morningAfterLine(it) }, onDrinks = { navController?.navigate("drinks") }, + drinksOnly = DashboardCard.SLEEP in visibleOrdered, ) } } @@ -747,9 +748,11 @@ private fun DetectedActivityLine(onOpen: () -> Unit) { }.getOrNull() } val p = newest ?: return - val time = remember(p.startAt) { + // Follows the phone's 12/24-hour setting, like the Last night card. + val is24 = android.text.format.DateFormat.is24HourFormat(context) + val time = remember(p.startAt, is24) { java.time.Instant.ofEpochMilli(p.startAt).atZone(java.time.ZoneId.systemDefault()) - .format(java.time.format.DateTimeFormatter.ofPattern("EEE HH:mm")) + .format(java.time.format.DateTimeFormatter.ofPattern(if (is24) "EEE HH:mm" else "EEE h:mm a")) } Row( Modifier.fillMaxWidth().heightIn(min = 48.dp).clip(androidx.compose.foundation.shape.RoundedCornerShape(8.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 5585af8e..be6f19e5 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/WhatChangedUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/WhatChangedUi.kt @@ -63,7 +63,7 @@ fun WhatChangedScreen(onBack: () -> Unit) { Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { - Text(tr("LAST 3 DAYS"), style = com.pulseloop.ui.theme.PulseType.eyebrow) + Text(tr("LAST 3 DAYS"), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary) if (rowsLoaded == null) { Spacer(Modifier.height(48.dp)) } else if (recent.isEmpty()) { @@ -75,7 +75,7 @@ fun WhatChangedScreen(onBack: () -> Unit) { } val older = rows.filter { it.day < recentKey }.groupBy { it.day } if (older.isNotEmpty()) { - Text(tr("EARLIER"), style = com.pulseloop.ui.theme.PulseType.eyebrow) + Text(tr("EARLIER"), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary) older.forEach { (day, list) -> Column( Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), @@ -104,7 +104,7 @@ private fun FindingRow(f: FindingEntity) { if (f.positive) androidx.compose.material.icons.Icons.Filled.CheckCircle else androidx.compose.material.icons.Icons.Filled.Info, contentDescription = if (f.positive) tr("Good sign") else tr("Worth a look"), tint = if (f.positive) PulseColors.success else PulseColors.warning, - modifier = Modifier.size(22.dp), + modifier = Modifier.size(24.dp), ) Column(Modifier.weight(1f)) { Text(f.title, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) diff --git a/app/src/main/java/com/pulseloop/update/UpdateUi.kt b/app/src/main/java/com/pulseloop/update/UpdateUi.kt index ccb57894..26d4caa8 100644 --- a/app/src/main/java/com/pulseloop/update/UpdateUi.kt +++ b/app/src/main/java/com/pulseloop/update/UpdateUi.kt @@ -141,7 +141,8 @@ fun CheckForUpdatesButton(modifier: Modifier = Modifier) { Column(modifier) { if (!UpdateChecker.isSupported()) { Text( - trf("Self-update works in the release build only ({0} / {1}).", BuildConfig.VERSION_NAME, BuildConfig.APPLICATION_ID), + // The package id is a developer detail; the version is enough to tell builds apart. + trf("Updates install in the release build only. This is version {0}.", BuildConfig.VERSION_NAME), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -155,8 +156,11 @@ fun CheckForUpdatesButton(modifier: Modifier = Modifier) { scope.launch { when (val result = UpdateChecker.check(context, force = true)) { is UpdateCheckResult.UpdateAvailable -> update = result.info - is UpdateCheckResult.Failed -> - status = trf("Couldn't check for updates ({0}). Try again.", result.reason) + is UpdateCheckResult.Failed -> { + // The reason names the engine (HTTP codes, parse errors): logcat, not the screen. + android.util.Log.w("UpdateUi", "Update check failed: ${result.reason}") + status = tr("Couldn't check for updates. Check your connection and try again.") + } else -> status = trf("You're on the latest version ({0}).", BuildConfig.VERSION_NAME) } checking = false From 8ac4ba749e06518ba0743d68931c00612d73ee7e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 18:59:56 +0000 Subject: [PATCH 3/5] WIP: four-skill flow audit fixes (onboarding, pairing, settings) Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- .../com/pulseloop/ui/components/Charts.kt | 106 ++-------------- .../com/pulseloop/ui/components/VitalCard.kt | 2 +- .../pulseloop/ui/components/VitalRingGauge.kt | 13 +- .../pulseloop/ui/components/WorkoutMapView.kt | 29 +++-- .../pulseloop/ui/components/ZoneLineChart.kt | 18 +-- .../pulseloop/ui/dashboard/DashboardEdit.kt | 2 +- .../com/pulseloop/ui/onboarding/Editors.kt | 14 +-- .../pulseloop/ui/screens/AccuracyCheckUi.kt | 18 ++- .../pulseloop/ui/screens/AccuracyReportUi.kt | 13 +- .../java/com/pulseloop/ui/screens/BodyUi.kt | 9 +- .../pulseloop/ui/screens/CoachModelPicker.kt | 14 ++- .../pulseloop/ui/screens/CoachUsageSheet.kt | 10 +- .../java/com/pulseloop/ui/screens/CycleUi.kt | 20 ++- .../java/com/pulseloop/ui/screens/DrinksUi.kt | 10 +- .../ui/screens/HealthConnectSourceUi.kt | 49 +++++--- .../com/pulseloop/ui/screens/JournalUi.kt | 39 +++--- .../com/pulseloop/ui/screens/LabReportsUi.kt | 63 ++++++---- .../ui/screens/LanguageSettingsScreen.kt | 14 ++- .../ui/screens/LogPastActivityScreen.kt | 41 +++--- .../java/com/pulseloop/ui/screens/MedsUi.kt | 54 ++++---- .../com/pulseloop/ui/screens/PostpartumUi.kt | 58 +++++---- .../ui/screens/WorkoutSummaryScreen.kt | 118 ++++++++---------- .../pulseloop/widgets/WidgetConfigActivity.kt | 35 +++--- 23 files changed, 375 insertions(+), 374 deletions(-) diff --git a/app/src/main/java/com/pulseloop/ui/components/Charts.kt b/app/src/main/java/com/pulseloop/ui/components/Charts.kt index 61170c95..1019f64e 100644 --- a/app/src/main/java/com/pulseloop/ui/components/Charts.kt +++ b/app/src/main/java/com/pulseloop/ui/components/Charts.kt @@ -101,91 +101,6 @@ fun zoneGradientStops(dataMin: Double, dataMax: Double, th: MetricThresholds): A return stops.toTypedArray() } -/** - * Simple line chart composable — draws a polyline from data points. - * No external charting library needed. - * - * When [thresholds] is provided, the line + dots are colored by each value's zone - * (matching the metric's threshold legend) instead of the flat [color]. - */ -@Composable -fun SimpleLineChart( - points: List, - modifier: Modifier = Modifier, - color: Color = MaterialTheme.colorScheme.primary, - lineWidth: Float = 2f, - showDots: Boolean = true, - thresholds: MetricThresholds? = null, -) { - if (points.isEmpty()) return - val min = points.min() - val max = points.max() - val range = if (max == min) 1.0 else max - min - - Canvas(modifier = modifier.fillMaxWidth().height(100.dp)) { - val w = size.width - val h = size.height - val pad = 8f - val stepX = (w - pad * 2) / maxOf(1, points.size - 1) - val top = pad - val bottom = h - pad - - val lineBrush = thresholds?.let { - Brush.verticalGradient( - colorStops = zoneGradientStops(min, max, it), - startY = top, - endY = bottom, - ) - } - - val path = Path() - points.forEachIndexed { i, value -> - val x = pad + i * stepX - val y = pad + (h - pad * 2) * (1f - ((value - min) / range).toFloat()) - if (i == 0) path.moveTo(x, y) else path.lineTo(x, y) - - if (showDots) { - val dotColor = thresholds?.zoneFor(value)?.color ?: color - drawCircle(dotColor, 3f, Offset(x, y)) - } - } - if (lineBrush != null) { - drawPath(path, brush = lineBrush, style = Stroke(width = lineWidth, cap = StrokeCap.Round)) - } else { - drawPath(path, color, style = Stroke(width = lineWidth, cap = StrokeCap.Round)) - } - } -} - -/** - * Metric card with embedded mini sparkline — ported from MiniSparkline in DesignSystem. - */ -@Composable -fun MetricWithSparkline( - label: String, - value: String, - unit: String, - sparkline: List, - modifier: Modifier = Modifier, - color: Color = MaterialTheme.colorScheme.primary, -) { - androidx.compose.material3.Card(modifier) { - Column(Modifier.padding(12.dp)) { - Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) - androidx.compose.foundation.layout.Spacer(Modifier.height(4.dp)) - androidx.compose.foundation.layout.Row(verticalAlignment = androidx.compose.ui.Alignment.Bottom) { - Text(value, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold) - androidx.compose.foundation.layout.Spacer(Modifier.width(4.dp)) - Text(unit, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(bottom = 2.dp)) - } - if (sparkline.isNotEmpty()) { - androidx.compose.foundation.layout.Spacer(Modifier.height(8.dp)) - SimpleLineChart(points = sparkline, modifier = Modifier.fillMaxWidth(), color = color, showDots = false) - } - } - } -} - /** Small color swatch + label, used as an inline chart legend (e.g. Systolic / Diastolic). */ @Composable fun LegendDot(label: String, color: Color) { @@ -207,17 +122,21 @@ private fun formatTick(value: Double): String { * midnight, and returns a label formatter whose granularity matches the step * (e.g. "2 PM" for hourly, "2:30 PM" sub-hour, "Jun 28" for multi-day). */ -private fun timeAxisTicks(visStart: Long, visEnd: Long, zone: ZoneId): Pair, (Long) -> String> { +private fun timeAxisTicks(visStart: Long, visEnd: Long, zone: ZoneId, is24h: Boolean): Pair, (Long) -> String> { val rangeMs = (visEnd - visStart).coerceAtLeast(1L) val stepsMin = longArrayOf(15, 30, 60, 120, 180, 360, 720, 1440, 2880, 10080) val stepMin = stepsMin.firstOrNull { rangeMs / (it * 60_000L) <= 5 } ?: stepsMin.last() val stepMs = stepMin * 60_000L - val pattern = when { - stepMin >= 1440 -> "MMM d" - stepMin < 60 -> "h:mm a" - else -> "h a" + // Skeletons, arranged the locale's way and on the phone's 12/24-hour clock (was "h a" and + // "MMM d" for everyone). + val skeleton = when { + stepMin >= 1440 -> "MMMd" + stepMin < 60 -> if (is24h) "Hm" else "hm" + else -> if (is24h) "Hm" else "ha" } - val fmt = DateTimeFormatter.ofPattern(pattern, Locale.getDefault()) + val locale = Locale.getDefault() + val fmt = java.text.SimpleDateFormat(android.text.format.DateFormat.getBestDateTimePattern(locale, skeleton), locale) + .apply { timeZone = java.util.TimeZone.getTimeZone(zone) } // Align ticks to local midnight so labels land on clean boundaries. val dayStart = Instant.ofEpochMilli(visStart).atZone(zone) .truncatedTo(ChronoUnit.DAYS).toInstant().toEpochMilli() @@ -226,7 +145,7 @@ private fun timeAxisTicks(visStart: Long, visEnd: Long, zone: ZoneId): Pair String = { ms -> Instant.ofEpochMilli(ms).atZone(zone).format(fmt) } + val formatter: (Long) -> String = { ms -> fmt.format(java.util.Date(ms)) } return ticks to formatter } @@ -293,6 +212,7 @@ fun TrendChart( val zone = ZoneId.systemDefault() val textMeasurer = rememberTextMeasurer() + val is24h = android.text.format.DateFormat.is24HourFormat(androidx.compose.ui.platform.LocalContext.current) val axisColor = MaterialTheme.colorScheme.onSurfaceVariant val surfaceColor = MaterialTheme.colorScheme.surface val onSurfaceColor = MaterialTheme.colorScheme.onSurface @@ -487,7 +407,7 @@ fun TrendChart( // X-axis time labels — real clock times at clean intervals across the visible window. if (useTime) { - val (ticks, fmt) = timeAxisTicks(visStart, visEnd, zone) + val (ticks, fmt) = timeAxisTicks(visStart, visEnd, zone, is24h) var lastRight = -Float.MAX_VALUE for (t in ticks) { val text = fmt(t) 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 5f9ec19f..ad55e587 100644 --- a/app/src/main/java/com/pulseloop/ui/components/VitalCard.kt +++ b/app/src/main/java/com/pulseloop/ui/components/VitalCard.kt @@ -68,7 +68,7 @@ fun VitalCard( horizontal = if (compact) 16.dp else 24.dp, vertical = 16.dp, ), - verticalArrangement = Arrangement.spacedBy(if (compact) 6.dp else 8.dp), + verticalArrangement = Arrangement.spacedBy(if (compact) 4.dp else 8.dp), ) { CardHeader(state, compact, footerText) if (showsValueRow && !compact) ValueRow(state) 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 a7bbad40..a2be4660 100644 --- a/app/src/main/java/com/pulseloop/ui/components/VitalRingGauge.kt +++ b/app/src/main/java/com/pulseloop/ui/components/VitalRingGauge.kt @@ -176,18 +176,21 @@ fun VitalRingGauge( ) } - // Center stack: value / unit / status / subtitle, scaled off the gauge size like iOS. + // Center stack: value / unit / status / subtitle, scaled off the gauge size like iOS, then + // snapped to the type scale (a 190dp gauge asked for 57sp and 15.2sp, both off it). + fun onScale(target: Float) = com.pulseloop.ui.theme.PulseType.SCALE + .minByOrNull { kotlin.math.abs(it - target) }!!.sp Column(horizontalAlignment = Alignment.CenterHorizontally) { Text( centerValue, - fontSize = (size.value * 0.30f).sp, + fontSize = onScale(size.value * 0.30f), fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onSurface, ) if (centerUnit != null) { Text( centerUnit, - fontSize = maxOf(12f, size.value * 0.08f).sp, + fontSize = onScale(size.value * 0.08f), fontWeight = FontWeight.Medium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -195,7 +198,7 @@ fun VitalRingGauge( if (centerStatus != null) { Text( centerStatus.uppercase(), - fontSize = maxOf(12f, size.value * 0.08f).sp, + fontSize = onScale(size.value * 0.08f), fontWeight = FontWeight.SemiBold, letterSpacing = 1.sp, color = valueColor, @@ -209,7 +212,7 @@ fun VitalRingGauge( if (subtitle != null) { Text( subtitle, - fontSize = maxOf(12f, size.value * 0.065f).sp, + fontSize = onScale(size.value * 0.065f), color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center, maxLines = 2, diff --git a/app/src/main/java/com/pulseloop/ui/components/WorkoutMapView.kt b/app/src/main/java/com/pulseloop/ui/components/WorkoutMapView.kt index 9f9e7712..2c8fd5fc 100644 --- a/app/src/main/java/com/pulseloop/ui/components/WorkoutMapView.kt +++ b/app/src/main/java/com/pulseloop/ui/components/WorkoutMapView.kt @@ -20,6 +20,8 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.dp import com.pulseloop.data.entity.ActivityGpsPointEntity @@ -56,7 +58,9 @@ fun WorkoutMapView( .fillMaxWidth() .height(height.dp) .clip(RoundedCornerShape(8.dp)) - .background(PulseColors.card), + .background(PulseColors.card) + // TalkBack can't see a drawn route: say what it is. + .semantics { contentDescription = trf("Route map: {0} GPS points", points.size) }, ) { Canvas(Modifier.fillMaxSize().padding(8.dp)) { val w = size.width; val h = size.height @@ -64,12 +68,19 @@ fun WorkoutMapView( val lons = points.map { it.longitude } val minLat = lats.min(); val maxLat = lats.max() val minLon = lons.min(); val maxLon = lons.max() + // One scale for both axes, with longitude shrunk by cos(latitude), so the route + // keeps its real shape instead of being stretched to fill the box. + val lonFactor = kotlin.math.cos(Math.toRadians((minLat + maxLat) / 2)).coerceAtLeast(0.01) val latR = if (maxLat == minLat) 0.001 else maxLat - minLat - val lonR = if (maxLon == minLon) 0.001 else maxLon - minLon + val lonR = (if (maxLon == minLon) 0.001 else maxLon - minLon) * lonFactor + val inset = 16f + val scale = minOf((w - 2 * inset) / lonR, (h - 2 * inset) / latR) + val offX = (w - lonR * scale) / 2 + val offY = (h - latR * scale) / 2 fun toScreen(lat: Double, lon: Double): Offset { - val x = kotlin.math.max(0f, ((lon - minLon) / lonR * (w - 32f) + 16f).toFloat()) - val y = kotlin.math.max(0f, (h - ((lat - minLat) / latR * (h - 32f) + 16f)).toFloat()) + val x = (offX + (lon - minLon) * lonFactor * scale).toFloat() + val y = (h - offY - (lat - minLat) * scale).toFloat() return androidx.compose.ui.geometry.Offset(x, y) } @@ -88,12 +99,12 @@ fun WorkoutMapView( // Start marker val start = toScreen(points.first().latitude, points.first().longitude) drawCircle(PulseColors.steps, 6f, start) - drawCircle(Color.White, 5f, start) + drawCircle(PulseColors.textPrimary, 5f, start) - // End marker (pulsing dot) + // End marker. Not mint: the map isn't a tap target. val end = toScreen(points.last().latitude, points.last().longitude) - drawCircle(PulseColors.accent, 8f, end) - drawCircle(PulseColors.accent, 12f, end, style = Stroke(width = 1.5f)) + drawCircle(PulseColors.textPrimary, 8f, end) + drawCircle(PulseColors.textPrimary, 12f, end, style = Stroke(width = 1.5f)) // Point count overlay } @@ -105,7 +116,7 @@ fun WorkoutMapView( infoText, modifier = Modifier.align(Alignment.BottomStart).padding(8.dp), style = MaterialTheme.typography.labelSmall, - color = Color.White.copy(alpha = 0.7f), + color = PulseColors.textSecondary, ) } } diff --git a/app/src/main/java/com/pulseloop/ui/components/ZoneLineChart.kt b/app/src/main/java/com/pulseloop/ui/components/ZoneLineChart.kt index 799c7439..249fac86 100644 --- a/app/src/main/java/com/pulseloop/ui/components/ZoneLineChart.kt +++ b/app/src/main/java/com/pulseloop/ui/components/ZoneLineChart.kt @@ -187,8 +187,9 @@ fun ZoneLineChart( Modifier.fillMaxWidth().padding(end = 34.dp, top = 2.dp), horizontalArrangement = Arrangement.SpaceBetween, ) { + val is24h = android.text.format.DateFormat.is24HourFormat(androidx.compose.ui.platform.LocalContext.current) listOf(minTs, (minTs + maxTs) / 2, maxTs).forEach { - Text(timeLabel(it, span), fontSize = 12.sp, color = PulseColors.textMuted) + Text(timeLabel(it, span, is24h), fontSize = 12.sp, color = PulseColors.textMuted) } } } @@ -196,12 +197,11 @@ fun ZoneLineChart( } /** Hour-of-day labels for day-scale spans, day/month for anything longer (iOS VitalsAxisFormat). */ -private fun timeLabel(ts: Long, spanMs: Long): String { - val t = Instant.ofEpochMilli(ts).atZone(ZoneId.systemDefault()) - if (spanMs > 48 * 3600_000L) { - return "${t.dayOfMonth} ${t.month.name.take(3).lowercase().replaceFirstChar { it.uppercase() }}" - } - val h = t.hour % 12 - val displayH = if (h == 0) 12 else h - return "$displayH ${if (t.hour < 12) "AM" else "PM"}" +private fun timeLabel(ts: Long, spanMs: Long, is24h: Boolean): String { + // The locale's month names and order, and the phone's 12/24-hour clock (was English "4 Nov" + // and "2 PM" for everyone). + if (spanMs > 48 * 3600_000L) return PhoneFormat.date("MMMd", ts) + val locale = java.util.Locale.getDefault() + val pattern = android.text.format.DateFormat.getBestDateTimePattern(locale, if (is24h) "Hm" else "ha") + return java.text.SimpleDateFormat(pattern, locale).format(java.util.Date(ts)) } diff --git a/app/src/main/java/com/pulseloop/ui/dashboard/DashboardEdit.kt b/app/src/main/java/com/pulseloop/ui/dashboard/DashboardEdit.kt index f66f53bd..f0f89559 100644 --- a/app/src/main/java/com/pulseloop/ui/dashboard/DashboardEdit.kt +++ b/app/src/main/java/com/pulseloop/ui/dashboard/DashboardEdit.kt @@ -205,7 +205,7 @@ private fun EditBadge( fun HiddenMetricsTray(hidden: List, onRestore: (DashboardCard) -> Unit) { if (hidden.isEmpty()) return Column(Modifier.fillMaxWidth().padding(vertical = 8.dp)) { - Text(com.pulseloop.ui.i18n.tr("HIDDEN"), style = com.pulseloop.ui.theme.PulseType.eyebrow) + Text(com.pulseloop.ui.i18n.tr("HIDDEN"), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = com.pulseloop.ui.theme.PulseColors.textSecondary) hidden.forEach { card -> Row( Modifier.fillMaxWidth().padding(vertical = 2.dp), 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 958ed083..c5fc16e5 100644 --- a/app/src/main/java/com/pulseloop/ui/onboarding/Editors.kt +++ b/app/src/main/java/com/pulseloop/ui/onboarding/Editors.kt @@ -244,7 +244,7 @@ private fun FormCard(content: @Composable () -> Unit) { .clip(RoundedCornerShape(8.dp)) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(8.dp)) - .padding(horizontal = 16.dp, vertical = 10.dp), + .padding(horizontal = 16.dp, vertical = 8.dp), ) { content() } @@ -270,6 +270,8 @@ private fun SegmentedRow( Box( Modifier .weight(1f) + // 48dp: each segment is a target (it was about 36dp). + .heightIn(min = 48.dp) .clip(RoundedCornerShape(4.dp)) .background(if (selected) PulseColors.accent else Color.Transparent) .selectable(selected = selected, role = Role.RadioButton) { onSelect(index) } @@ -296,7 +298,7 @@ private fun PickerRow(title: String, value: String?, onClick: () -> Unit) { Row( Modifier .fillMaxWidth() - .heightIn(min = 50.dp) + .heightIn(min = 48.dp) .clickable(role = Role.Button, onClick = onClick), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), @@ -316,12 +318,7 @@ private fun PickerRow(title: String, value: String?, onClick: () -> Unit) { maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 160.dp), ) - Icon( - Icons.AutoMirrored.Filled.KeyboardArrowRight, - contentDescription = null, - modifier = Modifier.size(16.dp), - tint = PulseColors.textMuted, - ) + com.pulseloop.ui.components.Chevron() } } @@ -379,6 +376,7 @@ private fun NumberPickerSheet( Box( Modifier .fillMaxWidth() + .heightIn(min = 48.dp) .selectable(selected = selected, role = Role.RadioButton) { selection = value } .then(if (selected) Modifier.dither(PulseColors.accent, 0.18f) else Modifier.background(Color.Transparent)) .padding(vertical = 12.dp), 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 52c0c83e..ed49f26e 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt @@ -28,6 +28,7 @@ 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.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn @@ -223,11 +224,14 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { Text(tr("Past checks"), fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) past.forEach { c -> Row( - Modifier.fillMaxWidth().clickable { viewing = c.id }.padding(vertical = 6.dp), + Modifier.fillMaxWidth() + .heightIn(min = 48.dp) + .clickable(role = androidx.compose.ui.semantics.Role.Button) { viewing = c.id } + .padding(vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, ) { Column(Modifier.weight(1f)) { - Text("${c.deviceLabel} vs ${c.referenceLabel}", fontSize = 14.sp, color = PulseColors.textPrimary) + Text(trf("{0} vs {1}", c.deviceLabel, c.referenceLabel), fontSize = 14.sp, color = PulseColors.textPrimary) Text(AccuracyUiText.span(c), fontSize = 12.sp, color = PulseColors.textMuted) } Text( @@ -361,7 +365,7 @@ private fun StartDialog( onDismissRequest = onDismiss, title = { Text(tr("Start an accuracy check")) }, text = { - Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { OutlinedTextField( value = label, onValueChange = { label = it }, singleLine = true, label = { Text(tr("Reference device")) }, @@ -371,7 +375,7 @@ private fun StartDialog( ) Text(tr("How long"), fontSize = 14.sp, fontWeight = FontWeight.SemiBold) // Four translated "N days" chips are wider than a dialog: let them wrap. - FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { AccuracyCheckController.DURATIONS_DAYS.forEach { d -> FilterChip(selected = days == d, onClick = { days = d }, label = { Text(trf("{0} days", d)) }) } @@ -411,7 +415,8 @@ private fun SourceCard(context: Context, s: ReferenceSourceSurvey, onUse: (() -> ) } s.metrics.forEach { MetricRow(it) } - if (onUse != null) PulseButton(onClick = onUse, modifier = Modifier.fillMaxWidth()) { Text(tr("Compare my ring with this")) } + // Tonal: one card per candidate app, so filled would put several mint buttons on one screen. + if (onUse != null) PulseButton(PulseButtonStyle.Tonal, onClick = onUse, modifier = Modifier.fillMaxWidth()) { Text(tr("Compare my ring with this")) } } } @@ -475,7 +480,8 @@ internal fun AccuracyCheckBanner(c: AccuracyCheckEntity, onOpen: () -> Unit) { trf("Accuracy check · day {0} of {1} · Health Connect export paused", day, total) } else tr("Accuracy report ready · choose what to do with the paused export") Row( - Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).clickable(onClick = onOpen).padding(12.dp), + Modifier.fillMaxWidth().heightIn(min = 48.dp).clip(RoundedCornerShape(8.dp)).background(PulseColors.card) + .clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onOpen).padding(12.dp), verticalAlignment = Alignment.CenterVertically, ) { Text(text, fontSize = 12.sp, color = PulseColors.warning, modifier = Modifier.weight(1f)) 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 a156d98c..4c016e1e 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.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn @@ -114,7 +115,7 @@ internal fun AccuracyReportSection( fontSize = 16.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) + if (scoring) CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) else PulseButton(PulseButtonStyle.Text, onClick = { rescore(force = true) }, modifier = Modifier.widthIn(max = 120.dp)) { Text(tr("Recompute"), maxLines = 1, overflow = TextOverflow.Ellipsis) } @@ -202,13 +203,17 @@ private fun MetricCard( ) { val m = summary.metric AccuracyCard { - Row(Modifier.fillMaxWidth().clickable(onClick = onToggle), verticalAlignment = Alignment.CenterVertically) { + Row( + Modifier.fillMaxWidth().heightIn(min = 48.dp) + .clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onToggle), + verticalAlignment = Alignment.CenterVertically, + ) { Column(Modifier.weight(1f)) { Text(m.label, fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) val headline = when { summary.verdict == Verdict.NOT_ENOUGH_DATA -> null - m.kind == ComparisonMetric.Kind.STAGES -> summary.stageAgreement?.let { "${(it * 100).roundToInt()} % same stage" } - else -> AccuracyReportText.signed(m, summary.bias) + " vs ${check.referenceLabel}" + m.kind == ComparisonMetric.Kind.STAGES -> summary.stageAgreement?.let { trf("{0} % same stage", (it * 100).roundToInt()) } + else -> trf("{0} vs {1}", AccuracyReportText.signed(m, summary.bias), check.referenceLabel) } headline?.let { Text(it, fontSize = 14.sp, color = PulseColors.textSecondary) } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/BodyUi.kt b/app/src/main/java/com/pulseloop/ui/screens/BodyUi.kt index e8d58662..62733eee 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/BodyUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/BodyUi.kt @@ -105,7 +105,7 @@ fun HealthConnectBodyCard(onUpdated: () -> Unit) { Column( Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), - verticalArrangement = Arrangement.spacedBy(10.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), ) { Row(Modifier.switchRow(checked = enabled, enabled = available && !busy, onCheckedChange = { on -> if (on) launcher.launch(HealthConnectBodyImport.permissions) @@ -129,9 +129,9 @@ fun HealthConnectBodyCard(onUpdated: () -> Unit) { val w = s.weight val whenText = Instant.ofEpochMilli(w.measuredAt).atZone(ZoneId.systemDefault()) .format(DateTimeFormatter.ofPattern("d MMM, HH:mm")) - Row(verticalAlignment = androidx.compose.ui.Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Row(verticalAlignment = androidx.compose.ui.Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(8.dp)) { Text("%.1f".format(UnitConverter.weight(w.value, units)), fontSize = 28.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text("$unit · $whenText", fontSize = 12.sp, color = PulseColors.textMuted, modifier = Modifier.padding(bottom = 5.dp)) + Text("$unit · $whenText", fontSize = 12.sp, color = PulseColors.textMuted, modifier = Modifier.padding(bottom = 4.dp)) } val facts = buildList { s.bodyFatPct?.let { add(trf("Body fat {0}%", "%.1f".format(it))) } @@ -168,7 +168,8 @@ private fun WeightLine(points: List, units: UnitSystem) { val o = Offset(x(p.measuredAt), y(p.value)) if (i == 0) path.moveTo(o.x, o.y) else path.lineTo(o.x, o.y) } - drawPath(path, PulseColors.accent, style = Stroke(width = 2.dp.toPx(), cap = StrokeCap.Round)) + // Mint is for what's tapped; a chart line takes a data hue. + drawPath(path, PulseColors.info, style = Stroke(width = 2.dp.toPx(), cap = StrokeCap.Round)) } Row(Modifier.fillMaxWidth()) { Text(shown(points.first().value), fontSize = 12.sp, color = PulseColors.textMuted, modifier = Modifier.weight(1f)) 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 9fd1ebd5..91fa8084 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CoachModelPicker.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CoachModelPicker.kt @@ -7,6 +7,9 @@ import com.pulseloop.ui.components.PulseButton import com.pulseloop.ui.i18n.tr import androidx.compose.foundation.layout.* +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowDropDown import androidx.compose.material3.* @@ -130,13 +133,14 @@ fun CoachModelPicker( val unlisted = success != null && CoachModelCatalog.isUnlisted(provider, success, selected) Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { val (status, color) = when { - savedKey.isBlank() -> "Save your key to see every model $providerName offers." to MaterialTheme.colorScheme.onSurfaceVariant - loading -> "Loading models from $providerName…" to MaterialTheme.colorScheme.onSurfaceVariant + savedKey.isBlank() -> trf("Save your key to see every model {0} offers.", providerName) to MaterialTheme.colorScheme.onSurfaceVariant + loading -> trf("Loading models from {0}…", providerName) to MaterialTheme.colorScheme.onSurfaceVariant listing is CoachModelCatalog.Result.Failure -> (listing as CoachModelCatalog.Result.Failure).message to PulseColors.danger - success != null -> "${success.entries.size} models available from $providerName" to MaterialTheme.colorScheme.onSurfaceVariant + success != null -> trf("{0} models available from {1}", success.entries.size, providerName) to MaterialTheme.colorScheme.onSurfaceVariant else -> "" to MaterialTheme.colorScheme.onSurfaceVariant } - Text(status, style = MaterialTheme.typography.bodySmall, color = color, modifier = Modifier.weight(1f)) + // Polite: the status changes as the listing loads, fails or arrives. + Text(status, style = MaterialTheme.typography.bodySmall, color = color, modifier = Modifier.weight(1f).semantics { liveRegion = LiveRegionMode.Polite }) if (savedKey.isNotBlank() && !loading) { // Bounded so a long translated label can't squeeze the weighted status text. PulseButton(PulseButtonStyle.Text, onClick = { load(force = true) }, modifier = Modifier.widthIn(max = 140.dp)) { @@ -169,7 +173,7 @@ private fun MenuHeader(text: String) { text, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), + modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp), ) } 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 07d4a1de..194e250c 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CoachUsageSheet.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CoachUsageSheet.kt @@ -116,9 +116,9 @@ private fun CostNote() { .clip(RoundedCornerShape(4.dp)) .dither(PulseColors.textMuted, 0.10f) .padding(12.dp), - horizontalArrangement = Arrangement.spacedBy(6.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), ) { - Icon(Icons.Filled.Info, null, tint = PulseColors.textMuted, modifier = Modifier.size(14.dp)) + Icon(Icons.Filled.Info, null, tint = PulseColors.textMuted, modifier = Modifier.size(16.dp)) Text( tr("Cost estimates aren't available for on-device or custom models."), fontSize = 12.sp, color = PulseColors.textMuted, @@ -137,7 +137,7 @@ private fun BreakdownCard(accounted: List) { .padding(16.dp), ) { Row( - Modifier.fillMaxWidth().clickable { expanded = !expanded }, + Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable(role = androidx.compose.ui.semantics.Role.Button) { expanded = !expanded }, horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, ) { @@ -148,7 +148,7 @@ private fun BreakdownCard(accounted: List) { Text(if (expanded) tr("Hide") else tr("Show"), fontSize = 12.sp, color = PulseColors.textSecondary) } if (expanded) { - Column(Modifier.padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Column(Modifier.padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { accounted.forEach { MessageBreakdownRow(it) } } } @@ -191,4 +191,4 @@ private fun Divider() { Box(Modifier.fillMaxWidth().height(1.dp).background(PulseColors.borderSubtle)) } -private fun formatTokens(value: Int): String = NumberFormat.getNumberInstance(Locale.US).format(value) +private fun formatTokens(value: Int): String = NumberFormat.getNumberInstance(Locale.getDefault()).format(value) 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 bc6f9fdc..ca3dddc0 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CycleUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CycleUi.kt @@ -64,21 +64,14 @@ fun CycleScreen(onBack: () -> Unit) { var pastStart by remember { mutableStateOf(null) } 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"), fontSize = 16.sp, fontWeight = FontWeight.Bold, - maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center, - modifier = Modifier.align(Alignment.Center).padding(horizontal = 56.dp), - ) - } + com.pulseloop.ui.components.PulseTopBar(title = tr("Cycle"), onBack = onBack) Column( Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) { Column( Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), - verticalArrangement = Arrangement.spacedBy(6.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), ) { if (!loaded) { // Holds roughly the card's height until the dates are read. @@ -111,18 +104,19 @@ fun CycleScreen(onBack: () -> Unit) { if (!loaded) { Spacer(Modifier.height(40.dp)) } else if (open != null) { - PulseButton(onClick = { scope.launch { db.periodDao().upsert(open.copy(endDay = today.toEpochDay())) } }, modifier = Modifier.fillMaxWidth()) { + // Tonal: the one filled accent is the Actions button. + PulseButton(PulseButtonStyle.Tonal, onClick = { scope.launch { db.periodDao().upsert(open.copy(endDay = today.toEpochDay())) } }, modifier = Modifier.fillMaxWidth()) { Text(tr("Period ended today")) } } else { - PulseButton(onClick = { scope.launch { db.periodDao().upsert(PeriodEntity(startDay = today.toEpochDay())) } }, modifier = Modifier.fillMaxWidth()) { + PulseButton(PulseButtonStyle.Tonal, onClick = { scope.launch { db.periodDao().upsert(PeriodEntity(startDay = today.toEpochDay())) } }, modifier = Modifier.fillMaxWidth()) { Text(tr("Period started today")) } } PulseButton(PulseButtonStyle.Outlined, onClick = { picking = "start" }, modifier = Modifier.fillMaxWidth()) { Text(tr("Log a past period")) } if (periods.isNotEmpty()) { - Text(tr("HISTORY"), fontSize = 12.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + Text(tr("HISTORY"), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary) val starts = periods.map { it.startDay }.sorted() periods.forEach { p -> val next = starts.firstOrNull { it > p.startDay } @@ -140,7 +134,7 @@ fun CycleScreen(onBack: () -> Unit) { } // Asks first: one tap used to delete a logged period with no way back. IconButton(onClick = { pendingDelete = p.id }) { - Icon(Icons.Filled.Delete, tr("Delete"), tint = PulseColors.textMuted, modifier = Modifier.size(18.dp)) + Icon(Icons.Filled.Delete, trf("Delete {0}", LocalDate.ofEpochDay(p.startDay).format(fmt)), tint = PulseColors.textMuted, modifier = Modifier.size(18.dp)) } } } 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 e71ab7c1..c3816f2a 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt @@ -364,7 +364,7 @@ private fun DrinksWelcome(onStart: () -> Unit) { } } } - PulseButton( + PulseButton(PulseButtonStyle.Tonal, onClick = { DrinkPrefs.baselinePerWeek = typical.toDouble() DrinkPrefs.weeklyLimit = limit.toDouble() @@ -620,7 +620,7 @@ private fun PlanSheet(s: DrinksRepository.Snapshot, onDone: () -> Unit) { Text(tr("Plan tonight"), fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(tr("Pick the number before the first drink. It's easier to keep a number you chose beforehand."), fontSize = 14.sp, color = PulseColors.textSecondary) Stepper(tr("Drinks tonight"), if (plan == 0) tr("None") else "$plan", { plan = (plan - 1).coerceAtLeast(0) }, { plan = (plan + 1).coerceAtMost(12) }) - PulseButton(onClick = { DrinkPrefs.setPlan(s.today, plan); onDone() }, modifier = Modifier.fillMaxWidth()) { Text(tr("Save plan")) } + PulseButton(PulseButtonStyle.Tonal, onClick = { DrinkPrefs.setPlan(s.today, plan); onDone() }, modifier = Modifier.fillMaxWidth()) { Text(tr("Save plan")) } if (s.planToday != null) { PulseButton(PulseButtonStyle.Text, onClick = { DrinkPrefs.setPlan(s.today, null); onDone() }, modifier = Modifier.fillMaxWidth()) { Text(tr("Clear plan")) } } @@ -653,12 +653,12 @@ private fun MoreDrinkSheet(onLog: (DrinkType, Int, Long, Double?) -> Unit) { var price by remember { mutableStateOf(DrinkPrefs.pricePerDrink.takeIf { it > 0 }?.let { "%.2f".format(it) } ?: "") } Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(bottom = 32.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { Text(tr("Log drinks"), fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - FlowRow(Modifier.selectableGroup(), horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + FlowRow(Modifier.selectableGroup(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { DrinkType.entries.forEach { t -> Pill(t.label, type == t, PulseColors.drinks) { type = t } } } Text(trf("{0} ml at {1}% · about {2} kcal", type.volumeMl.roundToInt(), type.abvPct, type.kcal.roundToInt()), fontSize = 12.sp, color = PulseColors.textMuted) Stepper(tr("How many"), "$count", { count = (count - 1).coerceAtLeast(1) }, { count = (count + 1).coerceAtMost(12) }) - FlowRow(Modifier.selectableGroup(), horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + FlowRow(Modifier.selectableGroup(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { listOf(0L to "Now", 1L to "1 h ago", 3L to "3 h ago", 12L to "Last night").forEach { (h, l) -> Pill(tr(l), hoursAgo == h, PulseColors.drinks) { hoursAgo = h } } @@ -669,7 +669,7 @@ private fun MoreDrinkSheet(onLog: (DrinkType, Int, Long, Double?) -> Unit) { keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal), singleLine = true, modifier = Modifier.fillMaxWidth(), ) - PulseButton( + PulseButton(PulseButtonStyle.Tonal, onClick = { onLog(type, count, hoursAgo, price.replace(',', '.').toDoubleOrNull()?.takeIf { it > 0 }) }, modifier = Modifier.fillMaxWidth(), ) { Text(trf("Log {0}", count)) } 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 0cd9200d..a434d876 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/HealthConnectSourceUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/HealthConnectSourceUi.kt @@ -8,6 +8,7 @@ import com.pulseloop.ui.i18n.tr import androidx.activity.compose.rememberLauncherForActivityResult import androidx.compose.foundation.background +import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape @@ -33,6 +34,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @@ -106,7 +108,11 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { scope.launch { note = when (val r = runCatching { HealthConnectSourceImporter.run(context) }.getOrNull()) { is HealthConnectSourceImporter.Outcome.Done -> trf("Imported {0} readings.", "%,d".format(r.stored)) - is HealthConnectSourceImporter.Outcome.Failed -> r.message + // The importer's message lists record types in English: logcat, not the screen. + is HealthConnectSourceImporter.Outcome.Failed -> { + android.util.Log.w("HcSource", r.message) + tr("Couldn't read most of your data from Health Connect. Try again in a moment.") + } HealthConnectSourceImporter.Outcome.NoPermission -> tr("PulseLoop isn't allowed to read Health Connect any more.") HealthConnectSourceImporter.Outcome.Unavailable -> tr("Health Connect isn't available on this phone.") else -> tr("The import failed. Try again in a moment.") @@ -155,7 +161,7 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { fontSize = 12.sp, color = PulseColors.warning, ) } else if (!canRead) { - PulseButton(onClick = { launcher.launch(HealthConnectSource.request) }) { Text(tr("Allow access")) } + PulseButton(PulseButtonStyle.Tonal, onClick = { launcher.launch(HealthConnectSource.request) }) { Text(tr("Allow access")) } } } @@ -167,7 +173,7 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { val count = remember(refresh) { HealthConnectSource.lastImportCount(context) } Text( last?.let { - trf("Last import {0}", DateTimeFormatter.ofPattern("EEE d MMM, HH:mm").format(Instant.ofEpochMilli(it).atZone(ZoneId.systemDefault()))) + + trf("Last import {0}", localDateTime(context, it)) + trf(" · {0} readings", "%,d".format(count)) } ?: tr("Not imported yet"), fontSize = 14.sp, color = PulseColors.textSecondary, @@ -185,7 +191,7 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp), ) { - PulseButton(onClick = { importNow() }, enabled = !importing && canRead) { Text(tr("Import now")) } + PulseButton(PulseButtonStyle.Tonal, onClick = { importNow() }, enabled = !importing && canRead) { Text(tr("Import now")) } if (missing.isNotEmpty()) { PulseButton(PulseButtonStyle.Outlined, onClick = { launcher.launch(HealthConnectSource.request) }) { Text(tr("Allow more")) } } @@ -243,17 +249,30 @@ fun HealthConnectSourceHeroCard(onOpen: () -> Unit) { val context = LocalContext.current val pkg = HealthConnectSource.sourcePackage(context) ?: return val last = HealthConnectSource.lastImportAt(context) - Column( - Modifier.fillMaxWidth().clip(RoundedCornerShape(12.dp)).background(PulseColors.card) - .clickable(onClick = onOpen).padding(16.dp), - verticalArrangement = Arrangement.spacedBy(4.dp), + // Same frame as the ring's hero card (8dp radius, hairline, chevron), so the hub reads the same + // whichever source feeds it. + Row( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) + .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(8.dp)) + .clickable(role = Role.Button, onClick = onOpen).padding(16.dp), + verticalAlignment = Alignment.CenterVertically, ) { - Text(tr("DATA SOURCE"), fontSize = 12.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) - Text(trf("{0} via Health Connect", HealthConnectSource.label(context, pkg)), fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text( - 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 = 14.sp, color = PulseColors.textSecondary, - ) + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text(tr("DATA SOURCE"), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary) + Text(trf("{0} via Health Connect", HealthConnectSource.label(context, pkg)), fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text( + last?.let { trf("Last import {0}", localDateTime(context, it)) } + ?: tr("Waiting for the first import"), + fontSize = 14.sp, color = PulseColors.textSecondary, + ) + } + com.pulseloop.ui.components.Chevron() } } + +/** Date and time in the phone's own format: its locale, and its 12/24-hour setting. */ +private fun localDateTime(context: android.content.Context, millis: Long): String { + val date = java.util.Date(millis) + return android.text.format.DateFormat.getMediumDateFormat(context).format(date) + ", " + + android.text.format.DateFormat.getTimeFormat(context).format(date) +} 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 93949172..994ae617 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt @@ -71,7 +71,7 @@ fun JournalTagsCard( Column( Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), - verticalArrangement = Arrangement.spacedBy(10.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), ) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { Text( @@ -175,15 +175,7 @@ fun JournalScreen(db: PulseLoopDatabase, onBack: () -> Unit, onOpenDrinks: (() - } Column(Modifier.fillMaxSize()) { - Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { - IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { - Icon(Icons.Filled.ArrowBack, tr("Back")) - } - Text( - tr("Journal"), modifier = Modifier.align(Alignment.Center), - style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, - ) - } + com.pulseloop.ui.components.PulseTopBar(title = tr("Journal"), onBack = onBack) Column( Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(16.dp), @@ -192,15 +184,28 @@ fun JournalScreen(db: PulseLoopDatabase, onBack: () -> Unit, onOpenDrinks: (() - JournalTagsCard(db, today.minusDays(1), tr("Yesterday")) // The Alcohol tag is a yes/no; Drinks counts them, sets a limit and shows the dose. if (onOpenDrinks != null) { - Text( - if (com.pulseloop.service.DrinkPrefs.enabled) tr("Open Drinks: this week, your plan and what drinking does to your nights") - else tr("Want to drink less? Track drinks, set a weekly limit and see what each drink does to your nights"), - fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.drinks, - modifier = Modifier.clickable(onClick = onOpenDrinks).padding(vertical = 4.dp), - ) + // A row with a button role, a 48dp target and a chevron (was bare clickable text). + Row( + Modifier + .fillMaxWidth() + .heightIn(min = 48.dp) + .clip(RoundedCornerShape(8.dp)) + .clickable(role = Role.Button, onClick = onOpenDrinks) + .padding(vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + if (com.pulseloop.service.DrinkPrefs.enabled) tr("Open Drinks: this week, your plan and what drinking does to your nights") + else tr("Want to drink less? Track drinks, set a weekly limit and see what each drink does to your nights"), + fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, + modifier = Modifier.weight(1f), + ) + com.pulseloop.ui.components.Chevron() + } } - Text(tr("What affects you"), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textMuted) + Text(tr("What affects you").uppercase(), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary) val list = effects when { list == null -> Unit diff --git a/app/src/main/java/com/pulseloop/ui/screens/LabReportsUi.kt b/app/src/main/java/com/pulseloop/ui/screens/LabReportsUi.kt index 7f061682..3e45a256 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/LabReportsUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/LabReportsUi.kt @@ -21,6 +21,7 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.AutoAwesome import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.PictureAsPdf import androidx.compose.material3.AlertDialog import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CircularProgressIndicator @@ -42,6 +43,7 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.liveRegion import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.drawText import androidx.compose.ui.text.font.FontWeight @@ -125,7 +127,7 @@ private fun openPdf(context: Context, report: LabReportEntity) { private fun LabNotice(text: String) { Row( Modifier.fillMaxWidth().clip(RoundedCornerShape(4.dp)).border(1.dp, PulseColors.warning, RoundedCornerShape(4.dp)) - .dither(PulseColors.warning, 0.12f).padding(horizontal = 12.dp, vertical = 10.dp), + .dither(PulseColors.warning, 0.12f).padding(horizontal = 12.dp, vertical = 12.dp), ) { Text(text, fontSize = 14.sp, color = PulseColors.textPrimary) } @@ -141,8 +143,8 @@ private fun LabCard(content: @Composable ColumnScope.() -> Unit) { } @Composable -private fun Overline(text: String, color: Color = PulseColors.textMuted) { - Text(text.uppercase(), fontSize = 12.sp, letterSpacing = 1.6.sp, color = color) +private fun Overline(text: String, color: Color = PulseColors.textSecondary) { + Text(text.uppercase(), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = color) } @Composable @@ -181,14 +183,16 @@ fun LabReportsScreen(onBack: () -> Unit, onMarker: (String) -> Unit, onAskCoach: draft?.let { LabReports.pdfFile(context, it.pdfFile).delete() } draft = null } + // A review can hold minutes of checking: Back or Discard asks before throwing it away. + var confirmDiscard by remember { mutableStateOf(false) } val current = draft if (current != null) { - BackHandler { discard() } + BackHandler { confirmDiscard = true } LabReviewScreen( draft = current, onChange = { draft = it }, - onDiscard = ::discard, + onDiscard = { confirmDiscard = true }, onSave = { scope.launch { LabReports.save(db, current) @@ -197,6 +201,17 @@ fun LabReportsScreen(onBack: () -> Unit, onMarker: (String) -> Unit, onAskCoach: } }, ) + if (confirmDiscard) { + AlertDialog( + onDismissRequest = { confirmDiscard = false }, + title = { Text(tr("Discard this report?")) }, + text = { Text(tr("The values read from it and your changes are lost. You'd need to add the PDF again.")) }, + confirmButton = { + PulseButton(PulseButtonStyle.Text, onClick = { confirmDiscard = false; discard() }) { Text(tr("Discard"), color = PulseColors.danger) } + }, + dismissButton = { PulseButton(PulseButtonStyle.Text, onClick = { confirmDiscard = false }) { Text(tr("Keep editing")) } }, + ) + } return } @@ -219,23 +234,26 @@ fun LabReportsScreen(onBack: () -> Unit, onMarker: (String) -> Unit, onAskCoach: .joinToString(" · "), fontSize = 12.sp, color = PulseColors.textMuted) } } - PulseButton( + // Tonal: the one filled accent is the Actions button. + PulseButton(PulseButtonStyle.Tonal, onClick = { picker.launch(arrayOf("application/pdf")) }, enabled = !reading, - modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), - colors = ButtonDefaults.buttonColors(containerColor = PulseColors.accent, contentColor = PulseColors.onAccent), + modifier = Modifier.fillMaxWidth(), ) { Icon(Icons.Filled.Add, null) Spacer(Modifier.width(8.dp)) Text(tr("Add a lab report (PDF)")) } if (reading) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Row( + Modifier.semantics { liveRegion = androidx.compose.ui.semantics.LiveRegionMode.Polite }, + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp, color = PulseColors.accent) Text(tr("The coach is reading the report. This can take a minute."), fontSize = 14.sp, color = PulseColors.textSecondary) } } - readError?.let { Text(it, fontSize = 14.sp, color = PulseColors.danger) } + readError?.let { Text(it, fontSize = 14.sp, color = PulseColors.danger, modifier = Modifier.semantics { liveRegion = androidx.compose.ui.semantics.LiveRegionMode.Polite }) } } if (latest != null) { @@ -257,7 +275,7 @@ fun LabReportsScreen(onBack: () -> Unit, onMarker: (String) -> Unit, onAskCoach: Text(tr("Ask the coach for a plan"), fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(tr("From these results, with goals you approve"), fontSize = 12.sp, color = PulseColors.textMuted) } - Text("›", fontSize = 20.sp, color = PulseColors.textMuted) + com.pulseloop.ui.components.Chevron() } Row(verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { @@ -285,9 +303,13 @@ fun LabReportsScreen(onBack: () -> Unit, onMarker: (String) -> Unit, onAskCoach: if (i > 0) Box(Modifier.fillMaxWidth().height(1.dp).background(PulseColors.borderSubtle)) val count = results.orEmpty().count { it.reportId == r.id } Row( - Modifier.fillMaxWidth().clickable { openPdf(context, r) }.padding(start = 16.dp, top = 8.dp, bottom = 8.dp, end = 4.dp), + Modifier.fillMaxWidth().clickable(role = Role.Button, onClickLabel = tr("Open PDF")) { openPdf(context, r) } + .padding(start = 16.dp, top = 8.dp, bottom = 8.dp, end = 4.dp), verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), ) { + // The PDF glyph says what a tap opens (was a "Tap a report…" line under the list). + Icon(Icons.Filled.PictureAsPdf, null, tint = PulseColors.textSecondary) Column(Modifier.weight(1f)) { Text(listOfNotNull(dayLabel(r.collectedDay), r.lab).joinToString(" · "), fontSize = 14.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) @@ -302,7 +324,6 @@ fun LabReportsScreen(onBack: () -> Unit, onMarker: (String) -> Unit, onAskCoach: } } } - Text(tr("Tap a report to open its PDF."), fontSize = 12.sp, color = PulseColors.textMuted) } Text(tr("Values come from your reports as you checked them. PulseLoop doesn't diagnose; the ranges are the lab's own."), @@ -331,7 +352,7 @@ private fun MarkerRow(m: LabReports.Marker, onClick: () -> Unit) { Row( Modifier.fillMaxWidth().clickable(role = Role.Button, onClick = onClick).padding(horizontal = 16.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(10.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), ) { Column(Modifier.weight(1f)) { Text(m.name, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary, maxLines = 2, overflow = TextOverflow.Ellipsis) @@ -352,7 +373,7 @@ private fun MarkerRow(m: LabReports.Marker, onClick: () -> Unit) { } } Text(flagLabel(l.flag), fontSize = 12.sp, fontWeight = FontWeight.Bold, color = flagColor(l.flag)) - Text("›", fontSize = 20.sp, color = PulseColors.textMuted) + com.pulseloop.ui.components.Chevron() } } @@ -375,7 +396,7 @@ fun LabMarkerScreen(markerKey: String, onBack: () -> Unit, onAskCoach: (markerNa Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(8.dp)) { Text(LabReports.valueLabel(l.valueNum, l.valueText), fontSize = 40.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(listOfNotNull(l.unit, dayLabel(l.day)).joinToString(" · "), fontSize = 14.sp, color = PulseColors.textMuted, - modifier = Modifier.padding(bottom = 6.dp)) + modifier = Modifier.padding(bottom = 8.dp)) } val ref = LabReports.referenceLabel(l.refLow, l.refHigh, l.refText, l.unit) Text( @@ -514,7 +535,7 @@ private fun LabReviewScreen( draft.results.forEachIndexed { i, r -> if (i > 0) Box(Modifier.fillMaxWidth().height(1.dp).background(PulseColors.borderSubtle)) Row( - Modifier.fillMaxWidth().clickable(role = Role.Button) { editing = i }.padding(vertical = 8.dp), + Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable(role = Role.Button, onClickLabel = tr("Edit marker")) { editing = i }.padding(vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), ) { @@ -527,17 +548,17 @@ private fun LabReviewScreen( Text(LabReports.valueLabel(r.valueNum, r.valueText) + (r.unit.takeIf { it.isNotBlank() }?.let { " $it" } ?: ""), fontSize = 14.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) if (LabReports.isOutside(r.flag)) Text(flagLabel(r.flag), fontSize = 12.sp, color = PulseColors.warning) + // The chevron says a row opens (was a mint "Tap a row…" hint under the list). + com.pulseloop.ui.components.Chevron() } } - Text(tr("Tap a row to fix or remove it."), fontSize = 12.sp, color = PulseColors.accent) } Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { PulseButton(PulseButtonStyle.Outlined, onClick = onDiscard, modifier = Modifier.weight(1f)) { Text(tr("Discard")) } - PulseButton( + PulseButton(PulseButtonStyle.Tonal, onClick = onSave, enabled = draft.results.isNotEmpty(), - modifier = Modifier.weight(1f).heightIn(min = 48.dp), - colors = ButtonDefaults.buttonColors(containerColor = PulseColors.accent, contentColor = PulseColors.onAccent), + modifier = Modifier.weight(1f), ) { Text(trf("Save {0} markers", draft.results.size)) } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/LanguageSettingsScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/LanguageSettingsScreen.kt index d324e242..8c315299 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/LanguageSettingsScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/LanguageSettingsScreen.kt @@ -9,6 +9,9 @@ import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AlertDialog @@ -23,6 +26,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.semantics.Role import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.pulseloop.ui.i18n.AppLanguage @@ -44,11 +48,15 @@ fun LanguageSettingsScreen(onBack: () -> Unit) { SettingsSubScreen(title = tr("Language"), onBack = onBack) { Column( - Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card), + // A radio group: TalkBack reads "selected, 1 of 5" and each row is one 48dp target. + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).selectableGroup(), ) { AppLanguage.entries.forEach { lang -> Row( - Modifier.fillMaxWidth().clickable { + Modifier.fillMaxWidth().heightIn(min = 48.dp).selectable( + selected = L10n.language == lang, + role = Role.RadioButton, + ) { when { lang == L10n.language -> Unit lang.voice == Voice.FUNNY -> confirming = lang @@ -58,7 +66,7 @@ fun LanguageSettingsScreen(onBack: () -> Unit) { verticalAlignment = Alignment.CenterVertically, ) { RadioButton(selected = L10n.language == lang, onClick = null) - Column(Modifier.padding(start = 12.dp, top = 6.dp, bottom = 6.dp)) { + Column(Modifier.padding(start = 12.dp, top = 8.dp, bottom = 8.dp)) { Text( if (lang == AppLanguage.SYSTEM) tr("System default") else lang.label, fontSize = 16.sp, color = PulseColors.textPrimary, diff --git a/app/src/main/java/com/pulseloop/ui/screens/LogPastActivityScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/LogPastActivityScreen.kt index 459fba23..4324b67e 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/LogPastActivityScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/LogPastActivityScreen.kt @@ -65,28 +65,17 @@ fun LogPastActivityScreen(onBack: () -> Unit, onSaved: (String) -> Unit) { val endedAt = startedAt + durationMinutes * 60_000L val isValid = durationMinutes > 0 && endedAt <= maximumDate + val is24h = android.text.format.DateFormat.is24HourFormat(context) + + Column(Modifier.fillMaxSize().background(PulseColors.background)) { + // The shared pushed-screen bar. The second 20sp title ("What did you do?") and its how-to + // line are gone: the three section labels below already say what to choose. + com.pulseloop.ui.components.PulseTopBar(title = tr("Log Past Activity"), onBack = onBack) LazyColumn( - modifier = Modifier.fillMaxSize().background(PulseColors.background), - contentPadding = PaddingValues(16.dp), - verticalArrangement = Arrangement.spacedBy(20.dp), + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 16.dp), + verticalArrangement = Arrangement.spacedBy(24.dp), ) { - item { - Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { - CircleIconButton(Icons.AutoMirrored.Filled.ArrowBack, tr("Back"), tint = PulseColors.textSecondary, onTap = onBack) - Spacer(Modifier.width(12.dp)) - Text(tr("Log Past Activity"), fontSize = 20.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - } - } - item { - Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { - Text(tr("What did you do?"), fontSize = 20.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text( - tr("Choose an activity, when it started, and how long it lasted."), - fontSize = 14.sp, color = PulseColors.textMuted, - ) - } - } - item { SectionLabel(tr("Activity type")) } item { ActivityTypeGrid(selectedType) { type -> @@ -104,7 +93,7 @@ fun LogPastActivityScreen(onBack: () -> Unit, onSaved: (String) -> Unit) { item { EditFieldRow(tr("Ends")) { Text( - formatDateTime(endedAt), + formatDateTime(endedAt, is24h), fontSize = 14.sp, color = if (isValid) PulseColors.textSecondary else PulseColors.warning, ) @@ -159,14 +148,14 @@ fun LogPastActivityScreen(onBack: () -> Unit, onSaved: (String) -> Unit) { } item { Spacer(Modifier.height(24.dp)) } } + } } @Composable private fun SectionLabel(text: String) { Text( text.uppercase(), - fontSize = 12.sp, fontWeight = FontWeight.SemiBold, - letterSpacing = 1.2.sp, color = PulseColors.textMuted, + style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary, ) } @@ -195,11 +184,11 @@ private fun ActivityTypeButton(type: String, isSelected: Boolean, onSelect: (Str .selectable(selected = isSelected, role = Role.RadioButton) { onSelect(type) } .padding(12.dp), verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(10.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), ) { Box( Modifier - .size(38.dp) + .size(40.dp) .clip(CircleShape) .background(if (isSelected) PulseColors.accent else PulseColors.card), contentAlignment = Alignment.Center, @@ -238,7 +227,7 @@ private fun PastActivityDurationCard(minutes: Int, onChange: (Int) -> Unit) { DurationStepButton(Icons.Filled.Remove, tr("Decrease duration by 5 minutes"), enabled = !atFloor) { onChange(maxOf(5, minutes - 5)) } Column(Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally) { Text(durationText(minutes), fontSize = 28.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text(tr("DURATION"), style = com.pulseloop.ui.theme.PulseType.eyebrow) + Text(tr("DURATION"), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary) } DurationStepButton(Icons.Filled.Add, tr("Increase duration by 5 minutes"), enabled = true) { onChange(minutes + 5) } } 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 0807d2ec..df0cabfd 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MedsUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MedsUi.kt @@ -22,6 +22,9 @@ import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text +import androidx.compose.material3.minimumInteractiveComponentSize +import androidx.compose.foundation.selection.selectable +import androidx.compose.ui.semantics.Role import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -65,16 +68,10 @@ 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")) } - // Kept clear of the back button: the translated title is long. - Text( - tr("Medications & supplements"), fontSize = 16.sp, fontWeight = FontWeight.Bold, - maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center, - modifier = Modifier.align(Alignment.Center).padding(horizontal = 56.dp), - ) - // Adding is setup, not the daily job: it sits in the header so today's doses lead. - IconButton(onClick = { adding = true }, modifier = Modifier.align(Alignment.CenterEnd)) { + // The app's one pushed-screen bar (was hand-rolled). Adding is setup, not the daily job: + // it sits in the bar so today's doses lead. + com.pulseloop.ui.components.PulseTopBar(title = tr("Medications & supplements"), onBack = onBack) { + IconButton(onClick = { adding = true }) { Icon(Icons.Filled.Add, tr("Add medication or supplement"), tint = PulseColors.textSecondary) } } @@ -88,9 +85,9 @@ fun MedsScreen(onBack: () -> Unit) { if (doses.isNotEmpty()) { Column( Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), - verticalArrangement = Arrangement.spacedBy(10.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), ) { - Text(tr("TODAY"), fontSize = 12.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + Text(tr("TODAY"), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary) doses.forEach { d -> Row(verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { @@ -121,7 +118,7 @@ fun MedsScreen(onBack: () -> Unit) { meds.forEach { m -> Row( Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card) - .clickable { editing = m }.padding(16.dp), + .clickable(role = Role.Button, onClickLabel = tr("Edit")) { editing = m }.padding(16.dp), verticalAlignment = Alignment.CenterVertically, ) { Column(Modifier.weight(1f)) { @@ -132,7 +129,7 @@ fun MedsScreen(onBack: () -> Unit) { Text( tr("While breastfeeding: check in e-lactancia or LactMed, and ask your clinician"), fontSize = 12.sp, color = PulseColors.accent, - modifier = Modifier.clickable { + modifier = Modifier.heightIn(min = 48.dp).clickable(role = Role.Button) { runCatching { context.startActivity( android.content.Intent( @@ -150,11 +147,12 @@ fun MedsScreen(onBack: () -> Unit) { fontSize = 12.sp, color = PulseColors.textMuted, ) } + com.pulseloop.ui.components.Chevron() } } // With nothing added yet, adding is the only thing to do here: keep the big button. if (medsLoaded != null && meds.isEmpty()) { - PulseButton(onClick = { adding = true }, modifier = Modifier.fillMaxWidth()) { Text(tr("Add medication or supplement")) } + PulseButton(PulseButtonStyle.Tonal, onClick = { adding = true }, modifier = Modifier.fillMaxWidth()) { Text(tr("Add medication or supplement")) } } Text( tr("A record for you and your doctor. PulseLoop doesn't check interactions or doses; ask your pharmacist."), @@ -183,30 +181,33 @@ private fun MedDialog(initial: MedEntity?, onDismiss: () -> Unit, onSave: (MedEn var kind by remember { mutableStateOf(initial?.kind ?: "medication") } var times by remember { mutableStateOf(initial?.let { Meds.times(it).toSet() } ?: setOf("08:00")) } var active by remember { mutableStateOf(initial?.active ?: true) } + // Deleting a medication also deletes its dose record, so it asks first. + var confirmDelete by remember { mutableStateOf(false) } @Composable fun chip(label: String, on: Boolean, onClick: () -> Unit) { val shape = RoundedCornerShape(16.dp) Text( label, fontSize = 14.sp, color = if (on) PulseColors.onAccent else PulseColors.textSecondary, - modifier = Modifier.clip(shape).background(if (on) PulseColors.accent else PulseColors.cardSoft) + // 48dp of layout for the target; the drawn chip keeps its size. Announced as selected. + modifier = Modifier.minimumInteractiveComponentSize().clip(shape).background(if (on) PulseColors.accent else PulseColors.cardSoft) .border(1.dp, if (on) PulseColors.accent else PulseColors.borderSubtle, shape) - .clickable(onClick = onClick).padding(horizontal = 12.dp, vertical = 8.dp), + .selectable(selected = on, onClick = onClick).padding(horizontal = 12.dp, vertical = 8.dp), ) } AlertDialog( onDismissRequest = onDismiss, title = { Text(if (initial == null) tr("Add") else tr("Edit")) }, text = { - Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { OutlinedTextField(name, { name = it.take(60) }, label = { Text(tr("Name")) }, singleLine = true, modifier = Modifier.fillMaxWidth()) OutlinedTextField(dose, { dose = it.take(40) }, label = { Text(tr("Dose (optional)")) }, singleLine = true, modifier = Modifier.fillMaxWidth()) - FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { chip(tr("Medication"), kind == "medication") { kind = "medication" } chip(tr("Supplement"), kind == "supplement") { kind = "supplement" } } Text(tr("Times"), fontSize = 14.sp, color = PulseColors.textSecondary) - FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { (PRESET_TIMES + times).distinct().sorted().forEach { t -> chip(t, t in times) { times = if (t in times) times - t else times + t } } @@ -216,7 +217,7 @@ private fun MedDialog(initial: MedEntity?, onDismiss: () -> Unit, onSave: (MedEn Text(tr("Active"), fontSize = 14.sp, modifier = Modifier.weight(1f)) androidx.compose.material3.Switch(checked = active, onCheckedChange = { active = it }) } - onDelete?.let { del -> PulseButton(PulseButtonStyle.Text, onClick = del) { + onDelete?.let { PulseButton(PulseButtonStyle.Text, onClick = { confirmDelete = true }) { Icon(Icons.Filled.Delete, null, tint = PulseColors.danger, modifier = Modifier.size(16.dp)) Text(tr(" Delete"), color = PulseColors.danger) } } @@ -233,4 +234,15 @@ private fun MedDialog(initial: MedEntity?, onDismiss: () -> Unit, onSave: (MedEn }, dismissButton = { PulseButton(PulseButtonStyle.Text, onClick = onDismiss) { Text(tr("Cancel")) } }, ) + if (confirmDelete && onDelete != null) { + AlertDialog( + onDismissRequest = { confirmDelete = false }, + title = { Text(trf("Delete {0}?", initial?.name.orEmpty())) }, + text = { Text(tr("Its dose record goes too. To stop the reminders but keep the record, switch off Active instead.")) }, + confirmButton = { + PulseButton(PulseButtonStyle.Text, onClick = { confirmDelete = false; onDelete() }) { Text(tr("Delete"), color = PulseColors.danger) } + }, + dismissButton = { PulseButton(PulseButtonStyle.Text, onClick = { confirmDelete = false }) { Text(tr("Cancel")) } }, + ) + } } 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 79383b04..50a19317 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/PostpartumUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/PostpartumUi.kt @@ -27,6 +27,7 @@ import androidx.compose.material3.IconButton import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.rememberDatePickerState +import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -75,9 +76,9 @@ fun PostpartumProfileCard(onOpen: () -> Unit) { Column( Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), - verticalArrangement = Arrangement.spacedBy(10.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), ) { - Text(tr("LIFE STAGE"), fontSize = 12.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + Text(tr("LIFE STAGE"), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary) Row(verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text(tr("Postpartum / breastfeeding"), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) @@ -98,7 +99,7 @@ fun PostpartumProfileCard(onOpen: () -> Unit) { PulseButton(PulseButtonStyle.Text, onClick = { picking = true }) { Text(birth?.format(fmt) ?: tr("Set")) } } Text(tr("Feeding"), fontSize = 14.sp, color = PulseColors.textSecondary) - FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + FlowRow(Modifier.selectableGroup(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { listOf( Postpartum.Feeding.EXCLUSIVE to tr("Breastfeeding only"), Postpartum.Feeding.MIXED to tr("Breastfeeding and formula"), @@ -152,9 +153,11 @@ private fun Chip(label: String, on: Boolean, onClick: () -> Unit) { Text( label, fontSize = 14.sp, color = if (on) PulseColors.onAccent else PulseColors.textSecondary, - modifier = Modifier.clip(shape).background(if (on) PulseColors.accent else PulseColors.cardSoft) + // 48dp of layout for the target, the drawn chip unchanged; one of a radio group. + modifier = Modifier.minimumInteractiveComponentSize().clip(shape).background(if (on) PulseColors.accent else PulseColors.cardSoft) .border(1.dp, if (on) PulseColors.accent else PulseColors.borderSubtle, shape) - .clickable(onClick = onClick).padding(horizontal = 12.dp, vertical = 8.dp), + .selectable(selected = on, role = androidx.compose.ui.semantics.Role.RadioButton, onClick = onClick) + .padding(horizontal = 12.dp, vertical = 8.dp), ) } @@ -230,11 +233,9 @@ fun PostpartumScreen(onBack: () -> Unit, onOpenProfile: () -> 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("Postpartum"), modifier = Modifier.align(Alignment.Center), fontSize = 16.sp, fontWeight = FontWeight.Bold) - // Birth date and feeding live in Profile → Life stage; one tap from here to change them. - IconButton(onClick = onOpenProfile, modifier = Modifier.align(Alignment.CenterEnd)) { + // Birth date and feeding live in Profile → Life stage; one tap from here to change them. + com.pulseloop.ui.components.PulseTopBar(title = tr("Postpartum"), onBack = onBack) { + IconButton(onClick = onOpenProfile) { Icon(Icons.Filled.Edit, tr("Edit life stage"), tint = PulseColors.textSecondary) } } @@ -245,7 +246,7 @@ fun PostpartumScreen(onBack: () -> Unit, onOpenProfile: () -> Unit) { if (birth == null) { Card { Text(tr("Set your baby's birth date in your profile to see this view."), fontSize = 14.sp, color = PulseColors.textSecondary) - PulseButton(onClick = onOpenProfile) { Text(tr("Open profile")) } + PulseButton(PulseButtonStyle.Tonal, onClick = onOpenProfile) { Text(tr("Open profile")) } } return@Column } @@ -286,7 +287,7 @@ fun PostpartumScreen(onBack: () -> Unit, onOpenProfile: () -> Unit) { // recovery is going, then reading for later. // Mood check-in: the EPDS, the validated questionnaire. Answers stay on this phone. val moodCard: @Composable () -> Unit = { Card { - Text(tr("MOOD CHECK-IN"), fontSize = 12.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + Text(tr("MOOD CHECK-IN"), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary) val last = history.lastOrNull() if (last != null) { Text(trf("Last check-in {0}: score {1} of 30", last.date, last.score), fontSize = 14.sp, color = PulseColors.textPrimary) @@ -306,7 +307,7 @@ fun PostpartumScreen(onBack: () -> Unit, onOpenProfile: () -> Unit) { if (moodUrgent) moodCard() d?.lastNight?.let { n -> Card { - Text(tr("LAST NIGHT"), fontSize = 12.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + Text(tr("LAST NIGHT"), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary) Text( trf("{0} asleep · woke {1} times · longest stretch {2}", fmtMin(n.asleepMin), n.wakings, fmtMin(n.longestSleepMin)), fontSize = 16.sp, color = PulseColors.textPrimary, @@ -322,7 +323,7 @@ fun PostpartumScreen(onBack: () -> Unit, onOpenProfile: () -> Unit) { ResourcesCard(context) if (d != null && (d.restingHr.isNotEmpty() || d.hrv.isNotEmpty())) { Card { - Text(tr("RECOVERY, WEEK BY WEEK"), fontSize = 12.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + Text(tr("RECOVERY, WEEK BY WEEK"), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary) val weeksShown = (d.restingHr.map { it.first } + d.hrv.map { it.first }).distinct().sorted().takeLast(4) weeksShown.forEach { w -> val rhr = d.restingHr.firstOrNull { it.first == w }?.second @@ -341,7 +342,7 @@ fun PostpartumScreen(onBack: () -> Unit, onOpenProfile: () -> Unit) { if (!moodUrgent) moodCard() Card { - Text(tr("NUTRITION"), fontSize = 12.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + Text(tr("NUTRITION"), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary) val bonus = Postpartum.calorieBonus(birth, today, Postpartum.feeding) if (bonus > 0) Text(trf("Breastfeeding uses about {0} kcal a day more; your intake goal includes it.", bonus), fontSize = 14.sp, color = PulseColors.textPrimary) Text( @@ -352,7 +353,7 @@ fun PostpartumScreen(onBack: () -> Unit, onOpenProfile: () -> Unit) { d?.lam?.let { lam -> Card { - Text(tr("BREASTFEEDING AS CONTRACEPTION (LAM)"), fontSize = 12.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + Text(tr("BREASTFEEDING AS CONTRACEPTION (LAM)"), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary) LamRow(tr("Baby under 6 months"), lam.babyUnderSixMonths, if (lam.babyUnderSixMonths) trf("{0} days to go", lam.daysToSixMonths) else null) LamRow(tr("No period since 8 weeks after birth"), lam.noPeriodSinceBirth, null) LamRow(tr("Breastfeeding only, day and night"), lam.fullBreastfeeding, null) @@ -428,7 +429,7 @@ private fun WarningSignsCard() { @Composable private fun ResourcesCard(context: Context) { Card { - Text(tr("HELP"), fontSize = 12.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) + Text(tr("HELP"), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary) ResourceRow(tr("SAMU (emergencies)"), "192") { dial(context, "192") } ResourceRow(tr("CVV (emotional support, 24 h)"), "188") { dial(context, "188") } ResourceRow(tr("Disque Saúde (find a human milk bank)"), "136") { dial(context, "136") } @@ -478,7 +479,7 @@ private fun EpdsGuidance(score: Int, selfHarm: Int) { if (selfHarm > 0) { Column( Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.danger.copy(alpha = 0.15f)).padding(12.dp), - verticalArrangement = Arrangement.spacedBy(6.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), ) { 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 = 14.sp, color = PulseColors.textPrimary) @@ -514,10 +515,23 @@ private fun EpdsCheckIn(onDone: (Postpartum.EpdsResult?) -> Unit) { val answers = remember { mutableStateListOf().apply { repeat(form.items.size) { add(null) } } } var result by remember { mutableStateOf(null) } + // Leaving half-way would throw the answers away without a word; ask first. A result already + // shown, or no answer yet, leaves at once. + var confirmLeave by remember { mutableStateOf(false) } + fun leave() { if (result == null && answers.any { it != null }) confirmLeave = true else onDone(result) } // System Back behaves like the arrow: it returns to Postpartum and keeps a result already shown. - androidx.activity.compose.BackHandler { onDone(result) } + androidx.activity.compose.BackHandler { leave() } + if (confirmLeave) { + androidx.compose.material3.AlertDialog( + onDismissRequest = { confirmLeave = false }, + title = { Text(tr("Leave the check-in?")) }, + text = { Text(tr("Your answers so far won't be saved.")) }, + confirmButton = { PulseButton(PulseButtonStyle.Text, onClick = { confirmLeave = false; onDone(null) }) { Text(tr("Leave")) } }, + dismissButton = { PulseButton(PulseButtonStyle.Text, onClick = { confirmLeave = false }) { Text(tr("Keep going")) } }, + ) + } Column(Modifier.fillMaxSize().background(PulseColors.background)) { - com.pulseloop.ui.components.PulseTopBar(tr("Mood check-in"), onBack = { onDone(result) }) + com.pulseloop.ui.components.PulseTopBar(tr("Mood check-in"), onBack = { leave() }) Column( Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(12.dp), @@ -528,7 +542,7 @@ private fun EpdsCheckIn(onDone: (Postpartum.EpdsResult?) -> Unit) { Text(trf("Your score: {0} of 30", r.score), fontSize = 20.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) EpdsGuidance(r.score, r.selfHarm) } - PulseButton(onClick = { onDone(r) }, modifier = Modifier.fillMaxWidth()) { Text(tr("Done")) } + PulseButton(PulseButtonStyle.Tonal, onClick = { onDone(r) }, modifier = Modifier.fillMaxWidth()) { Text(tr("Done")) } return@Column } Text(form.instruction, fontSize = 14.sp, color = PulseColors.textSecondary) @@ -552,7 +566,7 @@ private fun EpdsCheckIn(onDone: (Postpartum.EpdsResult?) -> Unit) { } } } - PulseButton( + PulseButton(PulseButtonStyle.Tonal, enabled = answers.all { it != null }, onClick = { val scores = form.items.mapIndexed { i, item -> item.options[answers[i]!!].score } 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 54970949..3b143165 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt @@ -30,6 +30,7 @@ import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.SelectableDates import androidx.compose.material3.Text @@ -119,17 +120,14 @@ fun WorkoutSummaryScreen( // caller) — an over-long pause total must never render a negative hero. val durationSec = s.endedAt?.let { maxOf(0, ((it - s.startedAt) / 1000.0 - s.totalPauseSeconds).toInt()) } - LazyColumn( - modifier = Modifier.fillMaxSize().background(PulseColors.background), - contentPadding = PaddingValues(16.dp), - verticalArrangement = Arrangement.spacedBy(16.dp), - ) { - item { - Row(Modifier.fillMaxWidth()) { - CircleIconButton(Icons.AutoMirrored.Filled.ArrowBack, tr("Back"), tint = PulseColors.textSecondary, onTap = onBack) - Spacer(Modifier.weight(1f)) + val is24h = android.text.format.DateFormat.is24HourFormat(context) + + Column(Modifier.fillMaxSize().background(PulseColors.background)) { + // The shared pushed-screen bar (was a hand-rolled row of circles): Back, then the screen's + // own actions on the trailing edge. + com.pulseloop.ui.components.PulseTopBar(title = tr("Workout"), onBack = onBack) { if (s.useGps && points.any { it.accepted }) { - CircleIconButton(Icons.Filled.Share, "Export route as GPX", tint = PulseColors.textSecondary, onTap = { + IconButton(onClick = { scope.launch { val hr = db.measurementDao().rangeReal( com.pulseloop.ring.MeasurementKind.HEART_RATE.name, s.startedAt, s.endedAt ?: System.currentTimeMillis(), @@ -143,24 +141,27 @@ fun WorkoutSummaryScreen( context.startActivity(android.content.Intent.createChooser(intent, tr("Export route (GPX)"))) } } - }) - Spacer(Modifier.width(10.dp)) + }) { Icon(Icons.Filled.Share, tr("Export route (GPX)"), tint = PulseColors.textSecondary) } } - CircleIconButton(Icons.Filled.Edit, tr("Edit workout"), tint = PulseColors.accent, onTap = { editing = true }) - Spacer(Modifier.width(10.dp)) - CircleIconButton(Icons.Filled.Delete, tr("Delete workout"), tint = PulseColors.danger, onTap = { confirmDelete = true }) - } - } + IconButton(onClick = { editing = true }) { Icon(Icons.Filled.Edit, tr("Edit workout"), tint = PulseColors.textSecondary) } + IconButton(onClick = { confirmDelete = true }) { Icon(Icons.Filled.Delete, tr("Delete workout"), tint = PulseColors.danger) } + } + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 16.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { item { Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) { Box( - Modifier.size(72.dp).clip(CircleShape).dither(PulseColors.accent, 0.18f), + // Decoration, not a tap target: no mint. + Modifier.size(72.dp).clip(CircleShape).dither(PulseColors.textSecondary, 0.18f), contentAlignment = Alignment.Center, ) { - Icon(ActivityMeta.icon(s.type), null, tint = PulseColors.accent, modifier = Modifier.size(34.dp)) + Icon(ActivityMeta.icon(s.type), null, tint = PulseColors.textPrimary, modifier = Modifier.size(32.dp)) } Text(ActivityMeta.label(s.type), fontSize = 24.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) - Text(dateRange(s), fontSize = 14.sp, color = PulseColors.textMuted) + Text(dateRange(s, is24h), fontSize = 14.sp, color = PulseColors.textMuted) } } item { SummaryHeroBand(s, durationSec, units) } @@ -174,6 +175,7 @@ fun WorkoutSummaryScreen( } item { Spacer(Modifier.height(48.dp)) } } + } if (confirmDelete) { AlertDialog( @@ -249,8 +251,8 @@ private fun EditWorkoutSheet( ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState, containerColor = PulseColors.background) { Column( - Modifier.fillMaxWidth().padding(horizontal = 20.dp).padding(bottom = 24.dp), - verticalArrangement = Arrangement.spacedBy(14.dp), + Modifier.fillMaxWidth().padding(horizontal = 24.dp).padding(bottom = 24.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), ) { Text(tr("Edit workout"), fontSize = 20.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) @@ -258,7 +260,7 @@ private fun EditWorkoutSheet( Box { PulseButton(PulseButtonStyle.Outlined, onClick = { typeExpanded = true }) { Icon(ActivityMeta.icon(type), null, tint = PulseColors.accent, modifier = Modifier.size(16.dp)) - Spacer(Modifier.width(6.dp)) + Spacer(Modifier.width(8.dp)) Text(ActivityMeta.label(type)) } DropdownMenu(expanded = typeExpanded, onDismissRequest = { typeExpanded = false }) { @@ -340,7 +342,7 @@ internal fun DateTimeButton(valueMillis: Long, onChange: (Long) -> Unit) { var pendingDayMillis by remember { mutableLongStateOf(valueMillis) } PulseButton(PulseButtonStyle.Text, onClick = { showDate = true }) { - Text(formatDateTime(valueMillis), color = PulseColors.accent, fontWeight = FontWeight.Medium) + Text(formatDateTime(valueMillis, android.text.format.DateFormat.is24HourFormat(LocalContext.current)), color = PulseColors.accent, fontWeight = FontWeight.Medium) } if (showDate) { @@ -404,8 +406,10 @@ internal fun DateTimeButton(valueMillis: Long, onChange: (Long) -> Unit) { } } -internal fun formatDateTime(millis: Long): String = - SimpleDateFormat("MMM d, h:mm a", Locale.getDefault()).format(Date(millis)) +/** "Nov 4, 6:05 PM" / "4 de nov., 18:05": the locale's date order and the phone's clock. */ +internal fun formatDateTime(millis: Long, is24h: Boolean): String = + com.pulseloop.ui.components.PhoneFormat.date("MMMd", millis) + ", " + + com.pulseloop.ui.components.PhoneFormat.clock(is24h, millis) /** The calendar date of a local-epoch millis value, expressed at UTC midnight (what DatePicker wants). */ internal fun localMillisToUtcMidnight(localMillis: Long): Long { @@ -419,28 +423,8 @@ internal fun utcMidnightToLocalDayStart(utcMillis: Long): Long { return date.atStartOfDay(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli() } -@Composable -internal fun CircleIconButton( - icon: androidx.compose.ui.graphics.vector.ImageVector, - contentDescription: String, - tint: Color, - onTap: () -> Unit, -) { - Box( - Modifier - .size(48.dp) - .clip(CircleShape) - .background(PulseColors.card) - .border(1.dp, PulseColors.borderSubtle, CircleShape) - .clickable(role = Role.Button, onClick = onTap), - contentAlignment = Alignment.Center, - ) { - Icon(icon, contentDescription, tint = tint, modifier = Modifier.size(20.dp)) - } -} - /** "Today · 6:05 – 6:43 PM" (WorkoutMetricsSections.dateRange). */ -private fun dateRange(s: ActivitySessionEntity): String { +private fun dateRange(s: ActivitySessionEntity, is24h: Boolean): String { val cal = Calendar.getInstance() val startCal = Calendar.getInstance().apply { timeInMillis = s.startedAt } val sameDay = cal.get(Calendar.YEAR) == startCal.get(Calendar.YEAR) && @@ -451,12 +435,11 @@ private fun dateRange(s: ActivitySessionEntity): String { val day = when { sameDay -> tr("Today") yesterday -> tr("Yesterday") - else -> SimpleDateFormat("MMM d", Locale.getDefault()).format(Date(s.startedAt)) + else -> com.pulseloop.ui.components.PhoneFormat.date("MMMd", s.startedAt) } val ended = s.endedAt ?: return day - val start = SimpleDateFormat("h:mm", Locale.getDefault()).format(Date(s.startedAt)) - val end = SimpleDateFormat("h:mm a", Locale.getDefault()).format(Date(ended)) - return "$day · $start – $end" + val fmt = com.pulseloop.ui.components.PhoneFormat + return "$day · ${fmt.clock(is24h, s.startedAt)} – ${fmt.clock(is24h, ended)}" } /** Three large headline stats: GPS → distance/duration/pace-or-speed (calories for sport); @@ -465,16 +448,17 @@ private fun dateRange(s: ActivitySessionEntity): String { @Composable private fun SummaryHeroBand(s: ActivitySessionEntity, durationSec: Int?, units: UnitSystem) { data class M(val value: String, val label: String, val tint: Color) + val corrections = rememberAccuracyCorrections() val dur = durationSec?.let { ActivityMeta.duration(it) } ?: "—" val metrics = if (s.useGps) { val metricSet = ActivityMeta.metricSet(s.type) val dist = s.distanceMeters?.let { "%.2f".format(UnitConverter.distance(it, units)) } val third = when { metricSet.showsPace -> - M(ActivityMeta.pace(s.distanceMeters, durationSec, units) ?: "—", "PACE ${ActivityMeta.paceUnit(units)}", PulseColors.accent) + M(ActivityMeta.pace(s.distanceMeters, durationSec, units) ?: "—", tr("Pace").uppercase() + " " + ActivityMeta.paceUnit(units), PulseColors.textPrimary) metricSet.showsSpeed -> { val parts = ActivityMeta.speedParts(s.distanceMeters, durationSec, units) - M(parts?.first ?: "—", parts?.second ?: "SPEED", PulseColors.accent) + M(parts?.first ?: "—", parts?.second ?: tr("Speed").uppercase(), PulseColors.textPrimary) } else -> M(s.calories?.let { "${it.toInt()}" } ?: "—", tr("CALORIES"), PulseColors.calories) } @@ -486,7 +470,9 @@ private fun SummaryHeroBand(s: ActivitySessionEntity, durationSec: Int?, units: } else { listOf( M(dur, tr("DURATION"), PulseColors.textPrimary), - M(durationSec?.let { "${it / 60}" } ?: "—", tr("ACTIVE MIN"), PulseColors.success), + // Was "ACTIVE MIN", which is the duration again in minutes. Average heart rate is the + // figure an indoor workout has instead of distance; the grid below then skips it. + M(s.avgHeartRate?.let { "${corrections.heartRate(it).toInt()}" } ?: "—", tr("Avg HR").uppercase(), PulseColors.heartRate), M(s.calories?.let { "${it.toInt()}" } ?: "—", tr("CALORIES"), PulseColors.calories), ) } @@ -497,13 +483,13 @@ private fun SummaryHeroBand(s: ActivitySessionEntity, durationSec: Int?, units: .clip(shape) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, shape) - .padding(vertical = 18.dp, horizontal = 8.dp), + .padding(vertical = 16.dp, horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically, ) { metrics.forEachIndexed { i, m -> - Column(Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(6.dp)) { + Column(Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp)) { Text(m.value, fontSize = 28.sp, fontWeight = FontWeight.SemiBold, color = m.tint, maxLines = 1) - Text(m.label, fontSize = 12.sp, fontWeight = FontWeight.Medium, letterSpacing = 0.8.sp, color = PulseColors.textMuted) + Text(m.label, style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textMuted, maxLines = 2, textAlign = TextAlign.Center) } if (i != metrics.lastIndex) { Box(Modifier.width(1.dp).height(40.dp).background(PulseColors.borderSubtle)) @@ -520,7 +506,8 @@ private fun StatsGrid(s: ActivitySessionEntity) { fun hr(v: Double?) = v?.let { "${corrections.heartRate(it).toInt()}" } ?: "—" val stats = buildList { if (s.useGps) add(tr("Calories") to (s.calories?.let { "${it.toInt()}" } ?: "—")) - add(tr("Avg HR") to hr(s.avgHeartRate)) + // Indoor workouts already lead with it in the band above. + if (s.useGps) add(tr("Avg HR") to hr(s.avgHeartRate)) add(tr("Max HR") to hr(s.maxHeartRate)) add(tr("Min HR") to hr(s.minHeartRate)) add("SpO₂" to (s.latestSpO2?.let { "${corrections.spo2(it).toInt()}%" } ?: "—")) @@ -540,12 +527,12 @@ private fun StatsGrid(s: ActivitySessionEntity) { .clip(shape) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, shape) - .padding(vertical = 14.dp), + .padding(vertical = 16.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp), ) { Text(value, fontSize = 20.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) - Text(label.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.Medium, letterSpacing = 0.8.sp, color = PulseColors.textMuted) + Text(label.uppercase(), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textMuted) } } repeat(3 - row.size) { Spacer(Modifier.weight(1f)) } @@ -574,9 +561,9 @@ private fun SplitsCard(points: List, units: UnitSystem, .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, shape) .padding(16.dp), - verticalArrangement = Arrangement.spacedBy(10.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), ) { - Text(tr("SPLITS"), style = com.pulseloop.ui.theme.PulseType.eyebrow) + Text(tr("SPLITS"), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary) splits.forEachIndexed { index, seconds -> val isFastest = seconds == fastest val frac = if (slowest > fastest) (seconds - fastest) / (slowest - fastest) else 0.0 @@ -594,13 +581,14 @@ private fun SplitsCard(points: List, units: UnitSystem, .fillMaxWidth((0.25f + 0.75f * (1f - frac.toFloat())).coerceIn(0.05f, 1f)) .fillMaxHeight() .clip(CircleShape) - .background(if (isFastest) PulseColors.accent else PulseColors.distance), + // Fastest is "good", not "tap here": success, not mint. + .background(if (isFastest) PulseColors.success else PulseColors.distance), ) } Text( paceLabel(seconds, paceUnit), fontSize = 12.sp, fontWeight = FontWeight.Medium, - color = if (isFastest) PulseColors.accent else PulseColors.textPrimary, + color = if (isFastest) PulseColors.success else PulseColors.textPrimary, modifier = Modifier.width(72.dp), textAlign = androidx.compose.ui.text.style.TextAlign.End, ) @@ -630,7 +618,7 @@ private fun MissingWorkout(onBack: () -> Unit) { Icon(Icons.AutoMirrored.Filled.DirectionsRun, null, tint = PulseColors.textMuted, modifier = Modifier.size(48.dp)) Spacer(Modifier.height(12.dp)) Text(tr("Workout not found"), fontSize = 20.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) - Spacer(Modifier.height(6.dp)) + Spacer(Modifier.height(8.dp)) Text( tr("This workout is no longer in local storage. It may have been deleted or replaced."), fontSize = 14.sp, color = PulseColors.textMuted, textAlign = TextAlign.Center, diff --git a/app/src/main/java/com/pulseloop/widgets/WidgetConfigActivity.kt b/app/src/main/java/com/pulseloop/widgets/WidgetConfigActivity.kt index 52546a5b..070f0ebc 100644 --- a/app/src/main/java/com/pulseloop/widgets/WidgetConfigActivity.kt +++ b/app/src/main/java/com/pulseloop/widgets/WidgetConfigActivity.kt @@ -17,6 +17,10 @@ import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.ui.semantics.Role import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState @@ -117,11 +121,11 @@ private fun ConfigScreen( // targetSdk 35 draws edge to edge: keep the title off the status bar and the button off the nav bar. .safeDrawingPadding() .verticalScroll(rememberScrollState()) - .padding(20.dp), + .padding(24.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { Text( - if (isDual) tr("Choose Metrics") else tr("Choose Metric"), + if (isDual) tr("Choose metrics") else tr("Choose metric"), fontSize = 24.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, @@ -135,30 +139,29 @@ private fun ConfigScreen( Spacer(Modifier.height(8.dp)) if (isDual) { - MetricPicker(tr("LEFT METRIC"), left) { left = it } + MetricPicker(tr("Left metric"), left) { left = it } Spacer(Modifier.height(12.dp)) - MetricPicker(tr("RIGHT METRIC"), right) { right = it } + MetricPicker(tr("Right metric"), right) { right = it } } else { MetricPicker(null, single) { single = it } } Spacer(Modifier.height(16.dp)) PulseButton(onClick = { onDone(single, left, right) }, modifier = Modifier.fillMaxWidth()) { - Text(tr("Add Widget")) + Text(tr("Add widget")) } } } @Composable private fun MetricPicker(title: String?, selected: WidgetMetric, onSelect: (WidgetMetric) -> Unit) { - Column { + // One radio group per picker: the row is the target (48dp) and carries the radio role. + Column(Modifier.selectableGroup()) { if (title != null) { Text( - title, - fontSize = 12.sp, - fontWeight = FontWeight.Medium, - letterSpacing = 1.sp, - color = PulseColors.textMuted, + title.uppercase(), + style = com.pulseloop.ui.theme.PulseType.eyebrow, + color = PulseColors.textSecondary, modifier = Modifier.padding(bottom = 4.dp), ) } @@ -166,13 +169,13 @@ private fun MetricPicker(title: String?, selected: WidgetMetric, onSelect: (Widg Row( Modifier .fillMaxWidth() - .clickable { onSelect(metric) } - .padding(vertical = 2.dp), + .heightIn(min = 48.dp) + .selectable(selected = metric == selected, role = Role.RadioButton) { onSelect(metric) }, verticalAlignment = Alignment.CenterVertically, ) { - RadioButton(selected = metric == selected, onClick = { onSelect(metric) }) - Spacer(Modifier.width(4.dp)) - Text(metric.displayName, fontSize = 16.sp, color = PulseColors.textPrimary) + RadioButton(selected = metric == selected, onClick = null) + Spacer(Modifier.width(8.dp)) + Text(tr(metric.displayName), fontSize = 16.sp, color = PulseColors.textPrimary) } } } From 1884944dc3b541f31e67be4a29b0ea1c9f3055f5 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 19:01:46 +0000 Subject: [PATCH 4/5] pt-BR entries for the flow-audit strings Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- app/src/main/assets/i18n/pt-BR.json | 63 +++++++++++++++++++ .../com/pulseloop/ui/components/Charts.kt | 6 +- .../com/pulseloop/ui/screens/SleepScreen.kt | 2 +- 3 files changed, 67 insertions(+), 4 deletions(-) diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index 7eaf5296..3ed1e20e 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -95,6 +95,7 @@ "A typical skin-temperature range from the ring.": "Uma faixa típica de temperatura da pele medida pelo anel.", "A typical week now": "Uma semana típica agora", "A weekly limit and dry days you choose": "Um limite semanal e dias sem álcool que você escolhe", + "A wellness score from 0–100 worked out from your HRV against your own usual range. Lower is calmer. It's an estimate, not a medical stress measure.": "Uma pontuação de bem-estar de 0 a 100 calculada a partir da sua VFC em relação à sua faixa habitual. Quanto menor, mais calmo. É uma estimativa, não uma medida médica de estresse.", "ACTIVE MIN": "MIN ATIVOS", "ADD DETAIL (OPTIONAL)": "ADICIONAR DETALHES (OPCIONAL)", "AI Coach": "Coach de IA", @@ -145,6 +146,7 @@ "Add medication or supplement": "Adicionar medicamento ou suplemento", "Add stravaClientId and stravaClientSecret to local.properties to enable Strava integration.": "Adicione stravaClientId e stravaClientSecret ao local.properties para ativar a integração com o Strava.", "Add what you take on a schedule. PulseLoop asks once per dose and keeps a week's record, and the coach can see it.": "Adicione o que você toma com horário. O PulseLoop pergunta uma vez por dose e guarda o registro de uma semana, e o coach pode vê-lo.", + "Add widget": "Adicionar widget", "Add workout": "Adicionar treino", "Add your age in Settings → User Profile for cardio capacity.": "Adicione sua idade em Configurações → Perfil do usuário para a capacidade cardiorrespiratória.", "Add your ring": "Adicione seu anel", @@ -154,6 +156,7 @@ "Adjust start time": "Ajustar horário de início", "Adjusted by your accuracy check: {0}. Settings → Accuracy check to change.": "Ajustado pela sua verificação de precisão: {0}. Configurações → Verificação de precisão para alterar.", "Adjusting your ring": "Ajustando seu anel", + "After 14 nights": "Depois de 14 noites", "After 1–2 drinks": "Depois de 1–2 doses", "After 1–2 drinks, your HRV runs {0}% {1} than on dry nights.": "Depois de 1–2 bebidas, sua HRV fica {0}% {1} do que nas noites sem álcool.", "After 3 or more": "Depois de 3 ou mais", @@ -172,6 +175,7 @@ "Alcohol: estimated clear for feeding around {0}": "Álcool: estimativa de liberação para amamentar por volta de {0}", "Alcoólicos Anônimos": "Alcoólicos Anônimos", "Alerts when your ring's battery runs low": "Alerta quando a bateria do anel estiver baixa", + "All": "Todos", "All health areas steady": "Todas as áreas estáveis", "All models from {0} ({1})": "Todos os modelos de {0} ({1})", "All three hold. LAM is about 98% effective only while all three do.": "As três condições valem. A LAM tem cerca de 98% de eficácia somente enquanto as três valerem.", @@ -194,6 +198,7 @@ "Anywhere: your doctor. If you drink most days, don't stop all at once; a doctor can help you cut down safely.": "Em qualquer lugar: seu médico. Se você bebe na maioria dos dias, não pare de uma vez; um médico pode ajudar você a reduzir com segurança.", "App Data": "Dados do app", "App Info": "Informações do app", + "App data": "Dados do app", "Applied to what PulseLoop shows, never to stored readings or Health Connect.": "Aplicado ao que o PulseLoop mostra, nunca às leituras armazenadas nem ao Health Connect.", "Apply": "Aplicar", "Apply correction ({0})": "Aplicar correção ({0})", @@ -266,7 +271,9 @@ "Beta-blockers": "Betabloqueadores", "Beta-blockers lower heart rate; this is expected on that medication.": "Betabloqueadores reduzem a frequência cardíaca; isso é esperado com esse medicamento.", "Blood": "Sangue", + "Blood Oxygen": "Oxigênio no sangue", "Blood Pressure": "Pressão arterial", + "Blood Sugar": "Glicemia", "Blood glucose": "Glicose no sangue", "Blood oxygen": "Oxigênio no sangue", "Blood oxygen (SpO₂)": "Oxigênio no sangue (SpO₂)", @@ -351,11 +358,15 @@ "Choose a model": "Escolha um modelo", "Choose a valid activity type.": "Escolha um tipo de atividade válido.", "Choose an activity, when it started, and how long it lasted.": "Escolha uma atividade, quando ela começou e quanto tempo durou.", + "Choose metric": "Escolher métrica", + "Choose metrics": "Escolher métricas", "Chopp": "Chopp", "Cider / other": "Sidra / outros", "Clear": "Limpar", "Clear Demo Data": "Apagar dados de demonstração", "Clear Demo Data?": "Apagar dados de demonstração?", + "Clear demo data": "Limpar dados de demonstração", + "Clear demo data?": "Limpar dados de demonstração?", "Clear plan": "Limpar plano", "Coach": "Coach", "Coach Check-Ins": "Check-ins do coach", @@ -405,6 +416,7 @@ "Could not open browser": "Não foi possível abrir o navegador", "Couldn't analyse the meal. Check your connection and try again, or enter it by hand.": "Não foi possível analisar a refeição. Verifique a conexão e tente de novo, ou digite à mão.", "Couldn't check for updates ({0}). Try again.": "Não foi possível procurar atualizações ({0}). Tente de novo.", + "Couldn't check for updates. Check your connection and try again.": "Não foi possível procurar atualizações. Verifique sua conexão e tente de novo.", "Couldn't connect. Keep the ring close and try again.": "Não foi possível conectar. Deixe o anel por perto e tente de novo.", "Couldn't copy that file.": "Não foi possível copiar esse arquivo.", "Couldn't delete this record": "Não foi possível excluir este registro", @@ -419,6 +431,7 @@ "Couldn't reach the coach. Try again.": "Não foi possível falar com o coach. Tente de novo.", "Couldn't reach the server.": "Não foi possível acessar o servidor.", "Couldn't read Health Connect. Try again in a moment.": "Não foi possível ler o Health Connect. Tente de novo em instantes.", + "Couldn't read most of your data from Health Connect. Try again in a moment.": "Não foi possível ler a maior parte dos seus dados do Health Connect. Tente de novo em instantes.", "Couldn't read the report. Check your connection and try again.": "Não foi possível ler o exame. Verifique a conexão e tente de novo.", "Couldn't read {0} from Health Connect just now.": "Não foi possível ler {0} do Health Connect agora.", "Couldn't read: ": "Não foi possível ler: ", @@ -455,6 +468,7 @@ "Data & privacy": "Dados e privacidade", "Data Backup": "Backup de dados", "Data Types": "Tipos de dados", + "Data backup": "Backup de dados", "Data behind this score": "Dados por trás desta pontuação", "Data stays on device": "Os dados ficam no dispositivo", "Database": "Banco de dados", @@ -494,9 +508,11 @@ "Delete workout?": "Excluir treino?", "Delete your {0} session from {1}? This can't be undone.": "Apagar sua sessão de {0} de {1}? Não dá para desfazer.", "Delete {0}": "Excluir {0}", + "Delete {0}?": "Apagar {0}?", "Deleted the {0} session.": "Sessão de {0} apagada.", "Deleting needs write permission, and PulseLoop has none right now — re-grant above, or delete the data in the Health Connect app.": "A exclusão precisa de permissão de gravação, e o PulseLoop não tem nenhuma agora — conceda de novo acima ou exclua os dados no app Health Connect.", "Demo Data": "Dados de demonstração", + "Demo data": "Dados de demonstração", "Describe": "Descrever", "Describe your meal": "Descreva sua refeição", "Destructive actions: reset app data, or unpair the ring and reset. To only forget the ring, use Ring & sync.": "Ações destrutivas: redefinir os dados do app, ou desparear o anel e redefinir. Para apenas esquecer o anel, use Anel e sincronização.", @@ -516,6 +532,7 @@ "Dinner": "Jantar", "Disabled": "Desativado", "Discard": "Descartar", + "Discard this report?": "Descartar este exame?", "Disconnect": "Desconectar", "Disconnect Strava?": "Desconectar o Strava?", "Disconnected": "Desconectado", @@ -526,6 +543,7 @@ "Distance, calories, and heart-rate stats are recalculated for the new window.": "Distância, calorias e estatísticas de frequência cardíaca são recalculadas para o novo período.", "Dizziness or fainting": "Tontura ou desmaio", "Done": "Concluído", + "Done. The new reading is on its card below.": "Pronto. A nova leitura está no cartão abaixo.", "Dose (optional)": "Dose (opcional)", "Download failed. Try again.": "O download falhou. Tente de novo.", "Downloading…": "Baixando…", @@ -580,6 +598,7 @@ "Enter a weight between {0} and {1} {2}.": "Informe um peso entre {0} e {1} {2}.", "Enter your weight in {0}": "Informe seu peso em {0}", "Environment": "Ambiente", + "Erases everything stored in the app. To also unpair your ring, forget it in Ring & sync first.": "Apaga tudo o que está salvo no app. Para desparear o anel também, esqueça-o antes em Anel e sincronização.", "Error": "Erro", "Error: {0}": "Erro: {0}", "Estimate calories with AI": "Estimar calorias com IA", @@ -614,10 +633,13 @@ "Export Full (Unmasked)": "Exportar completo (sem máscara)", "Export PulseLoop Data": "Exportar dados do PulseLoop", "Export PulseLoop data": "Exportar dados do PulseLoop", + "Export all data": "Exportar todos os dados", "Export all your data to a single JSON file for backup, device migration, or external analysis. Import restores everything — replacing all current data.": "Exporte todos os seus dados para um único arquivo JSON para backup, migração de dispositivo ou análise externa. A importação restaura tudo — substituindo todos os dados atuais.", "Export app, device, and wearable logs as JSON for bug reports.": "Exporte logs do app, do dispositivo e do wearable em JSON para relatórios de bugs.", "Export app, device, and wearable logs as JSON.": "Exporte logs do app, do dispositivo e do wearable em JSON.", + "Export diagnostics": "Exportar diagnóstico", "Export failed": "Falha na exportação", + "Export full (unmasked)": "Exportar completo (sem máscara)", "Export reset — re-grant permissions to sync again.": "Exportação redefinida — conceda as permissões novamente para voltar a sincronizar.", "Export ring data to Health Connect so other apps and dashboards can show it. Exporting only writes. PulseLoop reads Health Connect only for features you turn on: body data in your profile, Use without a ring, and the accuracy check.": "Exporte os dados do anel para o Health Connect para que outros apps e painéis possam exibi-los. A exportação só grava. O PulseLoop lê o Health Connect apenas para recursos que você ativa: dados corporais no seu perfil, Usar sem anel e a verificação de precisão.", "Export route (GPX)": "Exportar trajeto (GPX)", @@ -630,6 +652,7 @@ "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", "Factory reset ring?": "Restaurar anel de fábrica?", "Fair": "Razoável", "Fallback schedule (used when no Bedtime/DND mode was active):": "Horário alternativo (usado quando nenhum modo Hora de dormir/Não perturbe estava ativo):", @@ -668,6 +691,7 @@ "For {0}h asleep before your usual {1}": "Para {0}h de sono antes do seu horário habitual {1}", "Forget": "Esquecer", "Forget Ring": "Esquecer anel", + "Forget ring": "Esquecer anel", "Forget ring?": "Esquecer anel?", "Forget unbinds the ring and removes it from the app so it can be paired elsewhere. The app stays connected automatically the rest of the time.": "Esquecer desvincula o anel e o remove do app para que possa ser pareado em outro lugar. No restante do tempo, o app permanece conectado automaticamente.", "Formula version": "Versão da fórmula", @@ -799,6 +823,8 @@ "Imperial (mi, lbs, °F)": "Imperial (mi, lbs, °F)", "Import Complete": "Importação concluída", "Import Data": "Importar dados", + "Import complete": "Importação concluída", + "Import data": "Importar dados", "Import failed — the file may be corrupt or from a newer version.": "Falha na importação — o arquivo pode estar corrompido ou ser de uma versão mais recente.", "Import now": "Importar agora", "Imported {0} readings.": "{0} leituras importadas.", @@ -820,9 +846,11 @@ "It changes what PulseLoop shows and what it works out from it (zones, resting baseline, calorie estimate). Your ring's stored readings and what goes to Health Connect stay as measured.": "Isso muda o que o PulseLoop mostra e o que ele calcula a partir disso (zonas, linha de base em repouso, estimativa de calorias). As leituras guardadas do anel e o que vai para o Health Connect ficam como foram medidos.", "It reads the values you saved, never the PDF again.": "Ele lê os valores que você salvou, nunca mais o PDF.", "It's at {0}%. A short charge now keeps tonight's sleep tracked.": "Está em {0}%. Uma carga rápida agora garante o registro do sono desta noite.", + "Its dose record goes too. To stop the reminders but keep the record, switch off Active instead.": "O registro de doses também será apagado. Para parar os lembretes e manter o registro, desative Ativo.", "Its markers and its PDF are removed from this phone.": "Os marcadores e o PDF dele são removidos deste celular.", "Journal": "Diário", "Keep": "Manter", + "Keep editing": "Continuar editando", "Keep going": "Continue", "Keep recording": "Continuar gravando", "Keep still — measuring blood oxygen…": "Fique parado — medindo o oxigênio no sangue…", @@ -831,6 +859,7 @@ "Keep still — measuring heart rate…": "Fique parado — medindo frequência cardíaca…", "Keep still — measuring {0}…": "Fique parado — medindo {0}…", "Keep the ring snug and your hand still until it finishes.": "Mantenha o anel justo e a mão parada até terminar.", + "Keep wearing your device and let its app sync. Trends become personal after 14 nights of sleep.": "Continue usando seu dispositivo e deixe o app dele sincronizar. As tendências ficam pessoais após 14 noites de sono.", "Known lung condition": "Doença pulmonar conhecida", "LAST 3 DAYS": "ÚLTIMOS 3 DIAS", "LAST CAFFEINE": "ÚLTIMA CAFEÍNA", @@ -872,7 +901,10 @@ "Learning your dry nights: {0} of {1}. Then PulseLoop shows what each drink does to your sleep.": "Aprendendo suas noites sem álcool: {0} de {1}. Depois o PulseLoop mostra o que cada bebida faz com seu sono.", "Learning your normal: {0} of {1} nights.": "Aprendendo seu normal: {0} de {1} noites.", "Learns your baseline": "Aprende sua linha de base", + "Leave": "Sair", "Leave max tokens blank to let the server decide. Raise the timeout for a large model on CPU — a slow reply is not retried.": "Deixe o máximo de tokens em branco para o servidor decidir. Aumente o tempo limite para um modelo grande em CPU — uma resposta lenta não é repetida.", + "Leave the check-in?": "Sair do check-in?", + "Left metric": "Métrica da esquerda", "Legumes cozidos": "Legumes cozidos", "Less": "Menos", "Less than monthly": "Menos de uma vez por mês", @@ -887,6 +919,7 @@ "Live Measurements": "Medições ao vivo", "Live measurements and trends": "Medições ao vivo e tendências", "Live workout tracking": "Acompanhamento de treino ao vivo", + "Loading models from {0}…": "Carregando modelos de {0}…", "Loading…": "Carregando…", "Local": "Local", "Location": "Localização", @@ -956,11 +989,13 @@ "Meal": "Refeição", "Meal details": "Detalhes da refeição", "Meal name": "Nome da refeição", + "Meal photo": "Foto da refeição", "Meal reminder": "Lembrete de refeição", "Measure": "Medir", "Measured by your ring": "Medido pelo seu anel", "Measurement": "Medição", "Measurement Frequency": "Frequência de medição", + "Measurement frequency": "Frequência de medição", "Measurement units": "Unidades de medida", "Measuring… updates when complete": "Medindo… atualiza ao concluir", "Measuring… {0}s": "Medindo… {0}s", @@ -1057,6 +1092,7 @@ "No events yet. Sync the ring or trigger a measurement to see data.": "Nenhum evento ainda. Sincronize o anel ou inicie uma medição para ver os dados.", "No export has run yet. With the master switch on and a backfill choice made, PulseLoop exports automatically.": "Nenhuma exportação foi feita ainda. Com a chave principal ativada e uma opção de histórico escolhida, o PulseLoop exporta automaticamente.", "No fatigue data yet — take a measurement.": "Ainda não há dados de fadiga — faça uma medição.", + "No goal set · {0} is a typical day": "Sem meta definida · {0} é um dia típico", "No meals logged this week": "Nenhuma refeição registrada nesta semana", "No nights tracked in this range yet.": "Nenhuma noite registrada neste período ainda.", "No obvious signs in your biometrics of something straining your body.": "Nenhum sinal claro nos seus dados biométricos de algo sobrecarregando seu corpo.", @@ -1114,6 +1150,8 @@ "Not this": "Não é isso", "Not yet": "Ainda não", "Notably below your typical HRV — often linked to stress, poor sleep, or strain.": "Bem abaixo da sua HRV habitual — muitas vezes ligado a estresse, sono ruim ou sobrecarga.", + "Nothing logged on this day.": "Nada registrado neste dia.", + "Nothing logged today yet.": "Nada registrado hoje ainda.", "Nothing logged yet": "Nada registrado ainda", "Nothing new to upload": "Nada novo para enviar", "Nothing stood out": "Nada se destacou", @@ -1134,6 +1172,7 @@ "On": "Ativado", "On track": "No caminho certo", "On until {0}/{1}: activity nudges paused, the coach eases off.": "Ativo até {0}/{1}: lembretes de atividade pausados, o Coach pega mais leve.", + "On until {0}: activity nudges paused, the coach eases off.": "Ativo até {0}: lembretes de atividade pausados, o coach pega mais leve.", "On. PulseLoop syncs your ring about every 30 minutes, even while the phone is idle.": "Ativado. O PulseLoop sincroniza seu anel a cada 30 minutos, mesmo com o celular ocioso.", "Once per dose, at its time, for what you add with + Log → Medication or supplement.": "Uma vez por dose, no horário, para o que você adicionar em + Registrar → Medicamento ou suplemento.", "One tap for the usual ones": "Um toque para as de sempre", @@ -1148,6 +1187,7 @@ "Open Health Connect": "Abrir Health Connect", "Open My Health": "Abrir Minha saúde", "Open Nutrition Log": "Abrir registro de nutrição", + "Open PDF": "Abrir PDF", "Open PulseLoop to sync": "Abra o PulseLoop para sincronizar", "Open Settings": "Abrir Configurações", "Open postpartum view": "Abrir visão do pós-parto", @@ -1182,6 +1222,7 @@ "P {0} · C {1} · F {2} g": "P {0} · C {1} · G {2} g", "PAUSED": "PAUSADO", "Pace": "Ritmo", + "Pair a ring from Settings whenever you're ready. Your baseline builds once it's on.": "Pareie um anel em Configurações quando quiser. Sua linha de base começa quando ele estiver no dedo.", "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.", "Pair your ring first: a check compares it against the other device.": "Pareie seu anel primeiro: a verificação o compara com o outro dispositivo.", @@ -1206,6 +1247,7 @@ "Photo": "Foto", "Photo, barcode or by hand": "Foto, código de barras ou à mão", "Physiology": "Fisiologia", + "Pick a day": "Escolher um dia", "Pick the left and right PulseLoop metrics.": "Escolha as métricas do PulseLoop da esquerda e da direita.", "Pick the number before the first drink. It's easier to keep a number you chose beforehand.": "Escolha o número antes da primeira dose. É mais fácil cumprir um número que você definiu antes.", "Pick which PulseLoop metric this widget shows.": "Escolha qual métrica do PulseLoop este widget mostra.", @@ -1213,6 +1255,7 @@ "Plan tonight": "Planejar esta noite", "Plan: dry night": "Plano: noite sem álcool", "Plan: {0}": "Plano: {0}", + "Point the camera at the barcode": "Aponte a câmera para o código de barras", "Port from iOS · Open Source": "Portado do iOS · Código aberto", "Possible nap": "Possível cochilo", "Possible {0}": "Possível {0}", @@ -1307,6 +1350,8 @@ "Reseed": "Recriar", "Reseed Demo Data": "Recriar dados de demonstração", "Reseed Demo Data?": "Recriar dados de demonstração?", + "Reseed demo data": "Recriar dados de demonstração", + "Reseed demo data?": "Recriar dados de demonstração?", "Reset": "Redefinir", "Reset App Data": "Redefinir dados do app", "Reset app data": "Redefinir dados do app", @@ -1349,6 +1394,7 @@ "Ride it out": "Aguentar firme", "Right at your limit": "Exatamente no seu limite", "Right at your usual {0} bpm": "Exatamente no seu habitual de {0} bpm", + "Right metric": "Métrica da direita", "Ring & sync": "Anel e sincronização", "Ring Events": "Eventos do anel", "Ring battery alerts": "Alertas de bateria do anel", @@ -1359,6 +1405,7 @@ "Ring steps vs your phone": "Passos do anel vs. do seu celular", "Road, trail, or stationary": "Rua, trilha ou estacionária", "Route by": "Rotear por", + "Route map: {0} GPS points": "Mapa do percurso: {0} pontos de GPS", "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)", @@ -1375,6 +1422,7 @@ "Save measurement settings": "Salvar configurações de medição", "Save plan": "Salvar plano", "Save profile": "Salvar perfil", + "Save your key to see every model {0} offers.": "Salve sua chave para ver todos os modelos que {0} oferece.", "Save {0} markers": "Salvar {0} marcadores", "Saved": "Salvo", "Saved & sent to ring ✓": "Salvo e enviado ao anel ✓", @@ -1445,6 +1493,7 @@ "Show recent packets": "Mostrar pacotes recentes", "Show {0}": "Mostrar {0}", "Show {0} more": "Mostrar mais {0}", + "Skin Temperature": "Temperatura da pele", "Skin temperature": "Temperatura da pele", "Skin temperature from the ring runs cooler than core body temperature. Trends over time matter more than any single reading.": "A temperatura da pele medida pelo anel é mais baixa que a temperatura central do corpo. A tendência ao longo do tempo importa mais que qualquer leitura isolada.", "Skin temperature up": "Temperatura da pele em alta", @@ -1626,11 +1675,13 @@ "The target date has passed; agree a new one.": "A data-alvo já passou; defina uma nova.", "The tile and the morning-after line disappear. Your logged drinks stay on this phone until you delete them or clear your data.": "O bloco e a linha da manhã seguinte desaparecem. Suas bebidas registradas ficam neste celular até você excluí-las ou apagar seus dados.", "The two weeks before a period: skin temperature and resting heart rate often run a little higher.": "As duas semanas antes da menstruação: a temperatura da pele e a frequência cardíaca em repouso costumam ficar um pouco mais altas.", + "The values read from it and your changes are lost. You'd need to add the PDF again.": "Os valores lidos e suas alterações serão perdidos. Você precisará adicionar o PDF de novo.", "The window must be longer than the {0} min of pauses in this workout.": "A janela precisa ser maior que os {0} min de pausas deste treino.", "The workout must finish before now.": "O treino deve terminar antes de agora.", "There's room to move more today.": "Ainda dá para se mexer mais hoje.", "There's room to move more. Start with your {0}.": "Ainda dá para se mexer mais. Comece pelo seu {0}.", "These are patterns in your own data, not proof of cause and effect. Every tag is checked against your sleep, HRV and resting heart rate together, so a difference that could easily be chance isn't shown. They get more reliable the more days you tag.": "Estes são padrões nos seus próprios dados, não prova de causa e efeito. Cada marcação é verificada em conjunto com seu sono, HRV e frequência cardíaca em repouso, então uma diferença que poderia facilmente ser acaso não é exibida. Eles ficam mais confiáveis quanto mais dias você marcar.", + "This can't be undone.": "Não dá para desfazer.", "This check was run on {0}. Pair that ring to apply a correction from it.": "Esta verificação foi feita com {0}. Pareie esse anel para aplicar uma correção a partir dela.", "This deletes every record PulseLoop wrote to Health Connect and resets the export. It cannot be undone, and your ring data in PulseLoop is not affected.": "Isso exclui todos os registros que o PulseLoop gravou no Health Connect e redefine a exportação. Não é possível desfazer, e os dados do seu anel no PulseLoop não são afetados.", "This erases all data stored on the ring and resets it to factory state. We'll sync its latest data into the app first, but this can't be undone. The ring will need to be re-paired afterward.": "Isso apaga todos os dados armazenados no anel e o restaura para o estado de fábrica. Primeiro vamos sincronizar os dados mais recentes com o app, mas isso não pode ser desfeito. O anel precisará ser pareado novamente depois.", @@ -1727,6 +1778,8 @@ "Update your {0} session from {1}?": "Atualizar sua sessão de {0} de {1}?", "Update · {0}": "Atualizar · {0}", "Updated the {0} session.": "Sessão de {0} atualizada.", + "Updates install in the release build only. This is version {0}.": "Atualizações só são instaladas na versão de lançamento. Esta é a versão {0}.", + "Upload failed. Check your connection and try again.": "O envio falhou. Verifique sua conexão e tente de novo.", "Upload failed: {0}": "Falha no envio: {0}", "Uploaded 1 workout": "1 treino enviado", "Uploaded {0} workouts": "{0} treinos enviados", @@ -1742,6 +1795,7 @@ "Used to tune calories, activity goals, and summaries.": "Usado para ajustar calorias, metas de atividade e resumos.", "Used {0} tools": "Usou {0} ferramentas", "User Profile": "Perfil do usuário", + "User profile": "Perfil do usuário", "User profile is incomplete — insights may be less personalized.": "O perfil do usuário está incompleto — os insights podem ser menos personalizados.", "Uses additional tokens": "Usa tokens adicionais", "Using your latest ring sync": "Usando a sincronização mais recente do anel", @@ -1776,6 +1830,7 @@ "Wear both devices as you normally would, including at night.": "Use os dois dispositivos normalmente, inclusive à noite.", "Wear the ring and a watch or band you trust for a few days. PulseLoop reads that device's data from Health Connect and shows where the ring agrees and where it falls short.": "Use o anel e um relógio ou pulseira em que você confia por alguns dias. O PulseLoop lê os dados desse aparelho no Health Connect e mostra onde o anel concorda e onde fica devendo.", "Wear your ring during the day and sync after sleep. Trends become more personal after a few days.": "Use o anel durante o dia e sincronize depois de dormir. As tendências ficam mais personalizadas após alguns dias.", + "Wear your ring during the day and sync after sleep. Trends become personal after 14 nights of sleep.": "Use o anel durante o dia e sincronize depois de dormir. As tendências ficam pessoais após 14 noites de sono.", "Wear your ring overnight for a few nights to build a weekly view.": "Use o anel durante a noite por algumas noites para montar uma visão semanal.", "Wear your ring overnight so PulseLoop can track your next night.": "Use o anel durante a noite para que o PulseLoop acompanhe sua próxima noite.", "Wear your ring overnight to see your hypnogram here.": "Use o anel durante a noite para ver seu hipnograma aqui.", @@ -1858,6 +1913,7 @@ "Your HRV dipped this week. Lighter days and consistent sleep help it recover.": "Sua HRV caiu esta semana. Dias mais leves e sono regular ajudam a recuperá-la.", "Your activity trend and habits, in My Health": "Sua tendência de atividade e hábitos, em Minha saúde", "Your age, sex, height and weight let the ring compute accurate calories (and, on 56ff/Jring rings, blood sugar). Blood pressure is measured directly by the sensor.": "Sua idade, sexo, altura e peso permitem que o anel calcule as calorias com precisão (e, nos anéis 56ff/Jring, a glicose). A pressão arterial é medida diretamente pelo sensor.", + "Your answers so far won't be saved.": "Suas respostas até agora não serão salvas.", "Your answers stay on this phone. They aren't in backups, diagnostics or Health Connect.": "Suas respostas ficam neste celular. Não entram em backups, diagnósticos nem no Health Connect.", "Your answers suggest drinking at a level that is likely affecting your health. Please talk to a doctor. If you drink most days, don't stop all at once: stopping suddenly can be dangerous, and a doctor can help you cut down safely.": "Suas respostas sugerem um consumo de álcool que provavelmente está afetando sua saúde. Converse com um médico. Se você bebe na maioria dos dias, não pare de uma vez: parar de repente pode ser perigoso, e um médico pode ajudar você a reduzir com segurança.", "Your answers suggest drinking at a level that raises health risks. Cutting down gradually, with a weekly limit and dry days, is the usual first step.": "Suas respostas sugerem um consumo de álcool que aumenta os riscos à saúde. Reduzir aos poucos, com um limite semanal e dias sem álcool, é o primeiro passo habitual.", @@ -1870,6 +1926,7 @@ "Your body is still recovering. Go a little easier today.": "Seu corpo ainda está se recuperando. Pegue um pouco mais leve hoje.", "Your cycle predictions are worked out again without it.": "As previsões do seu ciclo são recalculadas sem ele.", "Your data has been restored from the backup.": "Seus dados foram restaurados a partir do backup.", + "Your device's data comes in through Health Connect. Your baseline builds from here.": "Os dados do seu dispositivo chegam pelo Health Connect. Sua linha de base começa aqui.", "Your drinks stay on this phone. They aren't sent to Health Connect or included in diagnostics.": "Suas bebidas ficam neste celular. Elas não são enviadas ao Health Connect nem incluídas nos diagnósticos.", "Your goal doesn't set any of these.": "Sua meta não define nenhum destes.", "Your goal, until 5 recovered nights teach the app yours": "Sua meta, até que 5 noites de recuperação ensinem ao app a sua", @@ -1927,6 +1984,7 @@ "higher": "maior", "hour": "hora", "hours": "horas", + "just now": "agora mesmo", "kcal": "kcal", "kcal eaten": "kcal ingeridas", "kcal not drunk": "kcal não bebidas", @@ -1941,6 +1999,7 @@ "nights": "noites", "no overlap": "sem sobreposição", "no sleep recorded": "nenhum sono registrado", + "no stage data": "sem dados de estágios", "not chosen": "não escolhido", "not counted": "não contado", "not measured": "não medido", @@ -1971,8 +2030,10 @@ "workouts a week": "treinos por semana", "your limit of {0}": "seu limite de {0}", "{0} % of {1} min on the same stage": "{0} % de {1} min no mesmo estágio", + "{0} % same stage": "{0} % no mesmo estágio", "{0} / week": "{0} / semana", "{0} asleep · woke {1} times · longest stretch {2}": "{0} dormindo · acordou {1} vezes · maior trecho {2}", + "{0} at {1}.": "{0} às {1}.", "{0} awake during the night": "{0} acordado durante a noite", "{0} bpm above your usual {1}": "{0} bpm acima do seu habitual de {1}", "{0} bpm avg": "{0} bpm média", @@ -2011,6 +2072,7 @@ "{0} min at {1}. Tap to add it, or say it wasn't.": "{0} min às {1}. Toque para adicionar, ou diga que não foi.", "{0} min {1} sleep": "{0} min de sono {1}", "{0} ml at {1}% · about {2} kcal": "{0} ml a {1}% · cerca de {2} kcal", + "{0} models available from {1}": "{0} modelos disponíveis de {1}", "{0} more dry day{1} to reach {2}": "Mais {0} dia{1} sem álcool para chegar a {2}", "{0} more — type to narrow": "Mais {0} — digite para filtrar", "{0} ms over the last 3 nights against your usual {1} ({2}%). Your body may be under extra load.": "{0} ms nas últimas 3 noites contra seu habitual de {1} ({2}%). Seu corpo pode estar sob carga extra.", @@ -2042,6 +2104,7 @@ "{0} to {1}": "{0} a {1}", "{0} unavailable": "{0} indisponível", "{0} via Health Connect": "{0} via Health Connect", + "{0} vs {1}": "{0} vs. {1}", "{0} vs {1}, until {2}.": "{0} vs {1}, até {2}.", "{0} was off from {1}, too long to compare": "{0} ficou desligado a partir das {1}, tempo demais para comparar", "{0} workouts a week": "{0} treinos por semana", diff --git a/app/src/main/java/com/pulseloop/ui/components/Charts.kt b/app/src/main/java/com/pulseloop/ui/components/Charts.kt index 1019f64e..76e84411 100644 --- a/app/src/main/java/com/pulseloop/ui/components/Charts.kt +++ b/app/src/main/java/com/pulseloop/ui/components/Charts.kt @@ -400,7 +400,7 @@ fun TrendChart( // Current-value marker at the last primary point primaryOffsets.lastOrNull()?.let { o -> val c = if (zoneColoring) thresholds?.zoneFor(points.last())?.color ?: color else color - drawCircle(Color.White, 7f, o) + drawCircle(PulseColors.textPrimary, 7f, o) drawCircle(c, 5f, o) } } @@ -443,12 +443,12 @@ fun TrendChart( // Vertical guide drawLine(outlineColor.copy(alpha = 0.6f), Offset(px, plotTop), Offset(px, plotBottom), 1.5f) // Highlighted point(s) - drawCircle(Color.White, 7f, Offset(px, py)) + drawCircle(PulseColors.textPrimary, 7f, Offset(px, py)) drawCircle(if (zoneColoring) thresholds?.zoneFor(points[idx])?.color ?: color else color, 5f, Offset(px, py)) val secVal = secondary.getOrNull(idx) if (secVal != null) { val py2 = yForValue(secVal) - drawCircle(Color.White, 6f, Offset(px, py2)) + drawCircle(PulseColors.textPrimary, 6f, Offset(px, py2)) drawCircle(colorSecondary, 4f, Offset(px, py2)) } 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 e60f67ca..3972994e 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt @@ -432,7 +432,7 @@ private fun VisualizationCard( verticalArrangement = Arrangement.spacedBy(16.dp), ) { Row(verticalAlignment = Alignment.Top) { - Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { Text( eyebrow.uppercase(), style = com.pulseloop.ui.theme.PulseType.eyebrow, color = PulseColors.textSecondary, From e63e0d2fa13ced748b3257a0239876ab3426b345 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 19:06:46 +0000 Subject: [PATCH 5/5] Audit: every flow and screen with the four skills (v2.11.59) Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- audits/2026-11-04-v2.11.59-flows.md | 165 ++++++++++++++++++++++++++++ 1 file changed, 165 insertions(+) create mode 100644 audits/2026-11-04-v2.11.59-flows.md diff --git a/audits/2026-11-04-v2.11.59-flows.md b/audits/2026-11-04-v2.11.59-flows.md new file mode 100644 index 00000000..873b11c2 --- /dev/null +++ b/audits/2026-11-04-v2.11.59-flows.md @@ -0,0 +1,165 @@ +# Audit: every user flow and screen, four skills (v2.11.59) + +Date: 2026-11-04 · PR: #64 · Auditor: Claude, in four parallel passes, one per journey. Each pass +mapped its flows, ran the four skills in order and fixed its findings in its own files; the results +were then merged and checked, and CI ran. + +## Scope + +Design system 0.31.0 adds **ux-user-flows** as the first of four skills. This is the first audit to +run all four, in the order AGENTS.md sets: ux-user-flows → impeccable → graphic-design-fundamentals → +less-is-more. Every skill was read from `.claude/skills/`, and none had to be applied by hand. + +The journeys: +- **Today and chrome:** launch, Today, header → My Health, Actions sheet, tiles, Readiness and + Activity score, What changed, Breathe, Customize cards. +- **Vitals, Sleep, Activity:** measure, Sleep and its records, Record → live → summary, detected + workout, Log past activity, Journal. +- **Nutrition, programs, coach:** meal by typing, photo and barcode; past-day back-fill; Drinks; + Meds; Body; Cycle; Postpartum and EPDS; Lab reports; Coach and its confirm card, usage sheet and + model picker. +- **First run, ring, Settings:** onboarding, pairing and every one of its states, first sync, the + Settings groups, Ring & sync, Backup & data, Accuracy check, Health Connect source, Language, + update, widget config. + +Known divergences were not reported: D-2, D-3, D-4, D-5, D-6, D-9 and P3-2. + +## ux-user-flows (flow map and §13 flow review) + +| Flow | States covered | §13 failures found | Fixed | +|---|---|---|---| +| Launch → Today | loading (space held), empty, partial, success | detected time forced to 24 h; last night repeated beside the Sleep tile | ✅ | +| Header → My Health | loading, error + Try again, success | hand-rolled bar; Rest Mode date written day/month | ✅ | +| Actions → meal / drink / dose / period / tags / workout | menu, steps, Logged + Undo | one-off 220 ms motion | ✅ | +| Readiness / Activity score | loading, learning, withheld, no sleep, score | "Data behind this score" had no role or expanded state | ✅ | +| Vitals → detail → measure | loading, empty, partial, picker, measuring, failure, not worn, disconnected | **no success state**; hand-rolled bar; English/24 h dates | ✅ success line, read out | +| Sleep → night → record → delete | loading, empty, one or several sessions, confirm | Toast errors; the empty state shown three ways; untranslated lanes | ✅ | +| Record → live → finish → summary | permission denied, leave dialog, edit validation, delete confirm | **didn't scroll in landscape**; summary bar hand-rolled | ✅ scrolls, buttons pinned | +| Detected workout → add / not this | hidden when empty, ranked chips | no feedback after Add, and a failure is silent | ⬜ carried | +| Log past activity | validation, save error, saving | two 20sp titles | ✅ | +| Nutrition: type / photo / barcode → save | input, analysing, review, failure | no empty-day state; **past-day meals stamped with the current time**; scanning gave no hint | ✅ (stamped at noon, as the photo flow does) | +| Drinks → log → undo | all | CVV row didn't dial; targets under 48dp; "Logged" not announced | ✅ | +| Meds → dose / delete | empty, loaded | **deleting a medicine erased its dose record without asking** | ✅ confirm | +| Postpartum → EPDS → result → crisis | all | **Back mid-check-in lost the answers silently** | ✅ confirm; EPDS wording untouched | +| Lab reports → add → read → review → save | all | review lost on Back or Discard | ✅ confirm; reading and failure announced | +| Coach → ask → reply → confirm card | all | photo decode on the main thread; attach and new chat shared an icon | ✅ | +| Onboarding → pairing → first sync | permission denied, Bluetooth off, nothing found, found, connecting, failed, connected, skip | **finale promised a baseline at days 3–7 (it is 14 nights) and a ring to people who skipped**; goal save skipped GoalSync; pager dots overflowed; pager clipped at large font | ✅ | +| Settings → groups; Backup & data | loading, every group | no top bar; unpairing offered off Ring & sync | ✅ | +| Accuracy, HC source, Language, Update, Widget config | all | raw failure reasons; radio rows without radio semantics; app id on screen | ✅ | + +## impeccable (audit, native / Android) + +Merged across the four journeys: + +| # | Dimension | Before | After | +|---|---|---|---| +| 1 | Accessibility | 2–3 | 3–4 | +| 2 | Performance | 3 | 3–4 (coach photo decode moved off the main thread) | +| 3 | Appearance & theming | 2–3 | 3–4 | +| 4 | Platform conformance | 2–3 | 3–4 | +| 5 | Adaptivity | 2–3 | 3 | +| | **Total** | **15/20** | **17/20** | + +**Fixed**, by area: +- **Back and destructive steps:** the EPDS, a lab review and a medicine delete each ask first; + "Unpair & Reset" left Backup & data. +- **States:** a measure success line; inline, read-out errors in Sleep; plain messages for update, + backup, Health Connect, the coach server check and Strava; "thinking" is announced. +- **Dates and times:** a shared `PhoneFormat` (ActivityMeta.kt) follows the 12/24-hour setting and + the locale. Charts, Sleep, Vitals, Activity, workout summary, Today, Guidance, Nutrition and + Health Connect all use it, and week initials come from the locale. +- **Adaptivity:** Record scrolls; the pairing pager is `heightIn`; with more than 8 models the dots + become "n of N"; the workout map keeps its aspect ratio. +- **Accessibility:** + - radio groups for Language and widget config; + - roles and expanded states on Today tiles, the glance alert, programs, Readiness and the coach banner; + - 48dp targets on Skip and Back in onboarding, editor segments, Drinks pills, Meds chips, + Accuracy rows and pairing rows; + - a spoken route summary on the workout map. +- **Consistency:** + - `PulseTopBar` on My Health, Readiness, vital detail, workout summary, Log past activity, + Journal, Nutrition, meal analysis, barcode, Drinks, Meds, Cycle, Postpartum and every Settings + sub-screen; + - `PulseType.eyebrow` across all four journeys; + - `Chevron()` replaces glyphs and `KeyboardArrowRight`; + - gauge text snaps to the type scale; + - `Motion` constants replace the one-off durations. +- **Colour:** decorative or status mint removed from: + - the brief, Rest Mode, Breathe and the AI badge; + - the pairing stripe and Settings icons; + - progress bars, page dots, the Activity today pill, the route and the Body chart; + - onboarding's medallion and tile. + `success` now marks the recognised ring and the fastest split. + +**Carried:** +- **P2 — detected workout "Add":** no confirmation, and a failure is silent. What it should say is + the owner's call: a snackbar, or opening the saved workout. +- **P2 — pairing pushed from Settings has no top bar.** Its `onBack` must come from + `PulseLoopApp`; system Back works. +- **P2 — trend charts zoom only by pinch** (WCAG 2.5.7). The spoken summary covers the data. +- **P2 — "Customize cards" shows on every Today and Vitals visit.** Moving it is the owner's call. +- **P3:** + - " min" / "bpm" templates still need split keys; + - `BedtimeGuidance.fmt` and `SleepFormat.clockTime` are still 24-hour for other callers; + - date patterns are still forced in the Accuracy text helpers; + - some `Card`/`titleMedium` remain inside `SettingsSubScreens`; + - the onboarding progress bar and the update changelog bullet are still mint; + - "Log Meal" is still title case, because renaming it would orphan its translation; + - Record and Log past activity each keep two filled buttons (they are pushed screens). +- **Rule text:** AGENTS.md says the readiness ring wears the brand colour, but the code colours it + by band. The rule should follow the code. + +## graphic-design-fundamentals (§13 checklist) + +| # | Question | Result | +|---|---|---| +| 1 | Brief | Pass | +| 2 | Concept | Pass | +| 3 | Hierarchy | Pass. Log past activity lost its second title; the onboarding finale no longer says "done" three times | +| 4 | Contrast | **Was failing, fixed.** Decorative mint is gone | +| 5 | Alignment and grid | Pass | +| 6 | Spacing | Pass where it was edited; a few 2dp gaps inside text stacks are carried (P3) | +| 7 | Typography | **Was failing, fixed.** Eyebrows are one style, and the gauge sizes are on the scale | +| 8 | Colour | **Was failing, fixed.** Mint is now only for tapping | +| 9 | Consistency | **Was failing, fixed.** One top bar, one eyebrow, one chevron | +| 10 | Simplicity | Pass. See the less-is-more cuts | +| 11 | Real-size test | **Was failing, fixed.** Landscape Record, the pairing pager and the dots | +| 12 | Accessibility and ergonomics | **Was failing, mostly fixed.** Pinch-only zoom is carried | +| 13 | Production | Pass. Every `tr()` key has a pt-BR entry (64 added, script-checked); no off-scale sizes; no direct Material buttons; every icon imported | + +## less-is-more + +| Element | Question | Action | +|---|---|---| +| Last night duration and score beside the Sleep tile | 2 | Removed when the tile is shown; the drinks line stays | +| Sleep's empty hypnogram card, "—" stage cards and "—" score | 2 | Removed; one empty state | +| "ACTIVE MIN" (= duration) | 2 | Replaced with Avg HR | +| "Tap to start" on each Measure option | 3 | Removed | +| Log past activity: "What did you do?" heading and its how-to line | 2, 3 | Removed | +| Lab "Tap a report…" / "Tap a row…" | 3 | Removed; a PDF icon and chevrons say it | +| Cancel beside Back on meal analysis and barcode | 2 | Removed; Back closes | +| Onboarding "Setup complete" pill | 2 | Removed | +| "Unpair & Reset" on Backup & data | 2, placement | Removed; Forget stays on Ring & sync | +| 22 pager dots | 1 | "n of N" | +| Raw error reasons, app id on screen | 1 | To logcat | +| Dead UI code (8 composables and files) | — | Deleted after a repo-wide grep | + +| Dimension | 0–4 | +|---|---| +| Elements per screen, compared with before | 4 | +| Duplicates left | 3 (Customize cards row carried) | +| Text to read when tired | 4 | +| Taps on the common actions (must not rise) | 4 (none rose; three destructive paths gained a confirm) | + +## Evidence + +- CI on #64 is green: unit tests, including `PulseTypeScaleTest`, `PulseTypographyTest` and + `PulseButtonTest`, plus lint and assemble. +- Script checks: every `tr()` key has a pt-BR entry; every `Icons.*` reference has its import; no + off-scale `fontSize`; no direct Material button. +- `drift.py --pulseloop`: 0 differences (no token changed). + +## Verdict + +Merge: there are no P0 or P1 findings, and the flow failures that lose data or mislead are fixed. +The carried P2/P3 items are listed above.