diff --git a/.gitignore b/.gitignore index 5e4da497..f70ee99c 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,4 @@ dist/ app/.DS_Store gradle/.DS_Store .DS_Store +.kotlin/ diff --git a/app/src/main/java/com/pulseloop/MainActivity.kt b/app/src/main/java/com/pulseloop/MainActivity.kt index 92b2c6c0..c309395a 100644 --- a/app/src/main/java/com/pulseloop/MainActivity.kt +++ b/app/src/main/java/com/pulseloop/MainActivity.kt @@ -73,7 +73,9 @@ class MainActivity : ComponentActivity() { CoachNotifications.createChannel(this) com.pulseloop.notifications.BatteryNotifications.createChannel(this) - requestAllPermissions() + // Ask once per launch, not on every resume: a dismissed dialog resumes the activity, and + // re-asking from onResume reopened the same prompt straight away. + if (savedInstanceState == null) requestAllPermissions() setContent { // GMind brand frame: a 4dp mint border round the app, drawn inside the system bars @@ -100,8 +102,7 @@ class MainActivity : ComponentActivity() { override fun onResume() { super.onResume() - // Re-request on resume in case user granted in Settings - requestAllPermissions() + // Only re-check here, in case the user granted from system Settings while away. if (hasAllBlePermissions() && hasNotificationPermission()) { CoachNotifications.schedule(this) } @@ -221,7 +222,11 @@ class MainActivity : ComponentActivity() { val missing = mutableListOf() // BLE / Location — GPS tracking needs location on all API levels - if (!hasFineLocation()) missing.add(Manifest.permission.ACCESS_FINE_LOCATION) + // Android 12+ ignores a fine-only request; coarse has to be asked for alongside it. + if (!hasFineLocation()) { + missing.add(Manifest.permission.ACCESS_FINE_LOCATION) + missing.add(Manifest.permission.ACCESS_COARSE_LOCATION) + } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { if (!hasBleScan()) missing.add(Manifest.permission.BLUETOOTH_SCAN) diff --git a/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt b/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt index 9b5cdb7a..db2b5976 100644 --- a/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt +++ b/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt @@ -141,6 +141,24 @@ class LiveWorkoutManager( refreshNotification() } + // UI entry points for the record screen's buttons. They run on this manager's own scope, which + // outlives the screen: finishing pops the record route, and a screen-scoped launch was cancelled + // mid Strava upload. A tap landing while the previous one is still writing is dropped, so a + // double tap on Finish can't credit the workout twice. Main-confined, so the flag needs no lock. + private var uiActionInFlight = false + + fun pauseFromUi(session: ActivitySessionEntity) = launchUiAction { pause(session) } + fun resumeFromUi(session: ActivitySessionEntity) = launchUiAction { resume(session) } + fun finishFromUi(session: ActivitySessionEntity) = launchUiAction { finish(session) } + + private fun launchUiAction(action: suspend () -> Unit) { + if (uiActionInFlight) return + uiActionInFlight = true + scope.launch { + try { action() } finally { uiActionInFlight = false } + } + } + suspend fun finish(session: ActivitySessionEntity) { gps.stop() polling.stop() diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index afa7ba66..0fc9acdb 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -12,6 +12,10 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color @@ -375,19 +379,6 @@ fun PulseLoopApp() { val navBackStackEntry by navController.currentBackStackEntryAsState() val route = navBackStackEntry?.destination?.route val onTabRoute = route in tabRoutes - if (onTabRoute && isLandscape) { - // Edge-to-edge draws content under the transparent status bar. In landscape the - // tabs render no full header, so without a backdrop scrolled content (chat - // bubbles, charts) bleeds through the status bar. Keep a status-bar-height glass - // strip so the status bar stays legible on every tab — matching the landscape - // bottom bar's glass — while content still scrolls under it. - Box( - Modifier - .fillMaxWidth() - .hazeEffect(state = hazeState, style = glassStyle) - .windowInsetsPadding(WindowInsets.statusBars), - ) - } if (onTabRoute && !isLandscape) { Column( Modifier @@ -430,7 +421,9 @@ fun PulseLoopApp() { } } else { val ble by bleClient.state.collectAsState() - val storedDevice by db.deviceDao().currentFlow() + // remember the Flow: this lambda recomposes on every BLE state change, and a + // fresh Flow resubscribes from `null`, blinking the pill. + val storedDevice by remember(db) { db.deviceDao().currentFlow() } .collectAsState(initial = null) // Prefer live BLE state; fall back to the stored device so demo data // shows its ring instead of a permanently blank pill (RootViews.swift). @@ -491,7 +484,13 @@ fun PulseLoopApp() { ) { tabs.forEach { tab -> val selected = isSelected(tab) - IconButton(onClick = { onTab(tab) }) { + IconButton( + onClick = { onTab(tab) }, + modifier = Modifier.semantics { + this.selected = selected + role = Role.Tab + }, + ) { Icon( if (selected) tab.selectedIcon else tab.unselectedIcon, contentDescription = tab.label, @@ -515,7 +514,8 @@ fun PulseLoopApp() { icon = { Icon( if (selected) tab.selectedIcon else tab.unselectedIcon, - contentDescription = tab.label, + // The item's label already names the tab. + contentDescription = null, ) }, label = { Text(tab.label) }, @@ -744,19 +744,17 @@ fun PulseLoopApp() { hrZone = workoutState.hrZone, units = apiKeyStore.resolvedUnitSystem, onPause = { - workoutState.activeSession?.let { kotlinx.coroutines.runBlocking { liveWorkout.pause(it) } } + workoutState.activeSession?.let { liveWorkout.pauseFromUi(it) } }, onResume = { - workoutState.activeSession?.let { kotlinx.coroutines.runBlocking { liveWorkout.resume(it) } } + workoutState.activeSession?.let { liveWorkout.resumeFromUi(it) } }, onFinish = { - workoutState.activeSession?.let { - kotlinx.coroutines.runBlocking { liveWorkout.finish(it) } - // Land on the summary (iOS RecordSummaryView), replacing the live screen. - navController.navigate("activity_detail/${it.id}") { - popUpTo("record") { inclusive = true } - } - } + // No runBlocking on the main thread. The finishedSessionId effect above lands + // on the summary (iOS RecordSummaryView) once the finish is written; with no + // session there is nothing to finish, so just leave. + workoutState.activeSession?.let { liveWorkout.finishFromUi(it) } + ?: navController.popBackStack() }, ) } diff --git a/app/src/main/java/com/pulseloop/ui/components/A11y.kt b/app/src/main/java/com/pulseloop/ui/components/A11y.kt new file mode 100644 index 00000000..65eb25ab --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/components/A11y.kt @@ -0,0 +1,39 @@ +package com.pulseloop.ui.components + +import android.provider.Settings +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.selection.toggleable +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.unit.dp + +/** + * Makes a label + [androidx.compose.material3.Switch] row one control: the whole row toggles, and + * TalkBack reads the label with the state ("Athlete mode, off, switch") instead of a bare + * "off, switch". Give the row's Switch `onCheckedChange = null` so it is only the indicator. + */ +fun Modifier.switchRow( + checked: Boolean, + enabled: Boolean = true, + onCheckedChange: (Boolean) -> Unit, +): Modifier = heightIn(min = 48.dp).toggleable( + value = checked, + enabled = enabled, + role = Role.Switch, + onValueChange = onCheckedChange, +) + +/** + * True when the user turned animations off (Settings › Accessibility › Remove animations, which + * sets the animator duration scale to 0). Looping decoration should hold still then. + */ +@Composable +fun rememberReduceMotion(): Boolean { + val resolver = LocalContext.current.contentResolver + return remember(resolver) { + Settings.Global.getFloat(resolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f) == 0f + } +} diff --git a/app/src/main/java/com/pulseloop/ui/components/ActivityRings.kt b/app/src/main/java/com/pulseloop/ui/components/ActivityRings.kt index 647aefdd..d9257be2 100644 --- a/app/src/main/java/com/pulseloop/ui/components/ActivityRings.kt +++ b/app/src/main/java/com/pulseloop/ui/components/ActivityRings.kt @@ -11,6 +11,8 @@ import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp @@ -48,8 +50,15 @@ fun ActivityRings( /** Gap between concentric rings. */ ringSpacing: Dp = 5.dp, trackColor: Color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.10f), + /** Spoken name per ring, in [rings] order (e.g. "steps"); unnamed rings read as "ring N". */ + labels: List = emptyList(), ) { - Canvas(modifier.size(size)) { + // Drawn arcs say nothing to TalkBack; speak each ring's share of its goal instead. + val description = "Goal progress: " + rings.mapIndexed { i, ring -> + val name = labels.getOrNull(i) ?: "ring ${i + 1}" + if (ring.value == null) "$name unavailable" else "$name ${(ring.progress * 100).toInt()}%" + }.joinToString(", ") + Canvas(modifier.size(size).clearAndSetSemantics { contentDescription = description }) { val strokePx = strokeWidth.toPx() val spacingPx = ringSpacing.toPx() val stroke = Stroke(width = strokePx, cap = StrokeCap.Round) 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 5c4e8fd4..d80c92ea 100644 --- a/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt +++ b/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt @@ -22,6 +22,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color +import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp @@ -73,7 +74,11 @@ fun AppHeader( state = state, batteryPercent = batteryPercent, idle = idle, - modifier = Modifier.clickable(onClick = onOpenSettings), + modifier = Modifier.clickable( + onClickLabel = "Open ring settings", + role = Role.Button, + onClick = onOpenSettings, + ), ) IconButton(onClick = onOpenSettings) { Icon(Icons.Outlined.Settings, "Settings", tint = PulseColors.textSecondary) @@ -95,7 +100,9 @@ fun ConnectionStatusPill( idle: Boolean = false, ) { val idleNow = idle && state == RingConnectionState.DISCONNECTED - val isPulsing = state == RingConnectionState.CONNECTING || state == RingConnectionState.RECONNECTING + // Holds still under "Remove animations"; the label already says "Connecting…". + val isPulsing = (state == RingConnectionState.CONNECTING || state == RingConnectionState.RECONNECTING) && + !rememberReduceMotion() val dotColor = when (state) { RingConnectionState.CONNECTED -> PulseColors.success RingConnectionState.CONNECTING, RingConnectionState.RECONNECTING -> PulseColors.accent @@ -110,12 +117,15 @@ fun ConnectionStatusPill( if (batteryPercent != null && batteryPercent > 0) "Idle · $batteryPercent%" else "Idle" } else "Disconnected" } - val pulse by rememberInfiniteTransition(label = "pill").animateFloat( - initialValue = 1f, - targetValue = if (isPulsing) 0.35f else 1f, - animationSpec = infiniteRepeatable(tween(800), RepeatMode.Reverse), - label = "pillDot", - ) + // Only run the transition while pulsing: an infinite 1f→1f animation still ticks every frame. + val pulse = if (isPulsing) { + rememberInfiniteTransition(label = "pill").animateFloat( + initialValue = 1f, + targetValue = 0.35f, + animationSpec = infiniteRepeatable(tween(800), RepeatMode.Reverse), + label = "pillDot", + ).value + } else 1f Row( modifier = modifier 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 0752406a..f2d11167 100644 --- a/app/src/main/java/com/pulseloop/ui/components/Charts.kt +++ b/app/src/main/java/com/pulseloop/ui/components/Charts.kt @@ -38,6 +38,8 @@ import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.drawscope.clipRect import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.drawText import androidx.compose.ui.text.font.FontWeight @@ -261,6 +263,8 @@ fun TrendChart( /** The user's own usual range, shaded behind the line (service/UsualRange). */ usualRange: ClosedFloatingPointRange? = null, usualColor: Color = color, + /** Spoken name for the chart's TalkBack summary (e.g. "Heart Rate"). */ + title: String? = null, ) { if (points.isEmpty()) return @@ -302,6 +306,12 @@ fun TrendChart( var scrubX by remember(points) { mutableStateOf(null) } var plotLeftPx by remember { mutableStateOf(0f) } var plotRightPx by remember { mutableStateOf(0f) } + // TalkBack can't scrub; give it the shape of the data in one sentence instead. + val summary = remember(points, secondary, title) { + fun v(i: Int) = valueFormatter(points[i]) + (secondary.getOrNull(i)?.let { "/" + valueFormatter(it) } ?: "") + "${title ?: "Chart"}: latest ${v(points.lastIndex)}, " + + "range ${valueFormatter(points.min())}–${valueFormatter(points.max())}, ${points.size} readings" + } Column(modifier = modifier) { // Legend row (for dual-series) @@ -315,7 +325,7 @@ fun TrendChart( } } - val canvasModifier = Modifier.fillMaxWidth().height(220.dp).let { base -> + val canvasModifier = Modifier.fillMaxWidth().height(220.dp).semantics { contentDescription = summary }.let { base -> if (!interactive) base else base.pointerInput(points) { awaitEachGesture { val first = awaitFirstDown(requireUnconsumed = false) @@ -420,7 +430,7 @@ fun TrendChart( return best } - val labelStyle = TextStyle(fontSize = 10.sp, color = axisColor) + val labelStyle = TextStyle(fontSize = 11.sp, color = axisColor) // No zone-band background: the iOS detail chart plots on a clean card, with the // zone-split line + the REFERENCE ZONES card carrying the range context. 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 fe95a34a..2bfbdecc 100644 --- a/app/src/main/java/com/pulseloop/ui/components/DeviceHeroCard.kt +++ b/app/src/main/java/com/pulseloop/ui/components/DeviceHeroCard.kt @@ -23,6 +23,7 @@ import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.Role import androidx.compose.ui.draw.clip import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow @@ -79,7 +80,7 @@ fun DeviceHeroCard( Row( Modifier .fillMaxWidth() - .clickable(onClick = onOpenWearable), + .clickable(onClickLabel = "Open ring settings", role = Role.Button, onClick = onOpenWearable), horizontalArrangement = Arrangement.spacedBy(16.dp), ) { RingArtView( @@ -145,7 +146,7 @@ fun DeviceHeroCard( } Icon( Icons.AutoMirrored.Filled.KeyboardArrowRight, - contentDescription = "Opens ring settings", + contentDescription = null, // the row's click label says it modifier = Modifier.size(20.dp), tint = PulseColors.textMuted, ) @@ -162,10 +163,10 @@ fun DeviceHeroCard( fontWeight = FontWeight.SemiBold, color = if (status.actionEnabled) PulseColors.accent else PulseColors.textMuted, modifier = Modifier - .heightIn(min = 44.dp) + .heightIn(min = 48.dp) .clip(CircleShape) .then(if (status.actionEnabled) Modifier.dither(PulseColors.accent, 0.18f) else Modifier.background(PulseColors.elevated)) - .clickable(enabled = status.actionEnabled) { + .clickable(enabled = status.actionEnabled, role = Role.Button) { when (status.action) { DeviceHeroStatus.Action.CONNECT -> onConnect() DeviceHeroStatus.Action.SET_UP -> onSetUp() 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 e6cd3507..2a105d75 100644 --- a/app/src/main/java/com/pulseloop/ui/components/PairingComponents.kt +++ b/app/src/main/java/com/pulseloop/ui/components/PairingComponents.kt @@ -23,6 +23,7 @@ import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.foundation.layout.heightIn import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector @@ -50,7 +51,7 @@ fun PrimaryButton( Button( onClick = onClick, enabled = enabled, - modifier = modifier.fillMaxWidth().height(52.dp), + modifier = modifier.fillMaxWidth().heightIn(min = 52.dp), shape = RoundedCornerShape(8.dp), colors = ButtonDefaults.buttonColors( containerColor = PulseColors.accent, @@ -79,7 +80,7 @@ fun SecondaryButton( enabled = enabled, modifier = modifier .fillMaxWidth() - .height(52.dp) + .heightIn(min = 52.dp) .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(8.dp)), shape = RoundedCornerShape(8.dp), colors = ButtonDefaults.buttonColors( 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 c1fba33f..f9562fe9 100644 --- a/app/src/main/java/com/pulseloop/ui/components/SettingsComponents.kt +++ b/app/src/main/java/com/pulseloop/ui/components/SettingsComponents.kt @@ -29,6 +29,7 @@ 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 androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp @@ -95,7 +96,7 @@ fun SettingsRow(item: SettingsRowItem) { Modifier .fillMaxWidth() .background(if (pressed) PulseColors.elevated else Color.Transparent) - .clickable(interactionSource = interactionSource, indication = null, onClick = item.action) + .clickable(interactionSource = interactionSource, indication = null, role = Role.Button, onClick = item.action) .heightIn(min = 52.dp) .padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically, 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 1412d729..11881ee8 100644 --- a/app/src/main/java/com/pulseloop/ui/components/TodayTiles.kt +++ b/app/src/main/java/com/pulseloop/ui/components/TodayTiles.kt @@ -27,6 +27,8 @@ import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.unit.Constraints import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.text.PlatformTextStyle import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight @@ -37,6 +39,7 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.pulseloop.ui.theme.PulseColors import com.pulseloop.ui.theme.ditherFade +import kotlin.math.roundToInt // Today-page tiles, ported from Views/TodayTiles.swift. Every tile is half-width (2-column grid) // and shares one fixed height so the grid never jumps. Each wraps the shared [TodayTile] chrome @@ -163,6 +166,7 @@ fun ActivityTile( size = 76.dp, strokeWidth = 8.dp, ringSpacing = 4.dp, + labels = values.map { it.label.lowercase() }, ) // Three metrics (steps/distance/calories) share one tile. At 22.sp the third value // overflowed and clipped the calories row (issue #24), so each pair is compact — @@ -265,7 +269,7 @@ fun SleepStageBar(segments: List, modifier: Modifier = Modifi val total = segments.sumOf { it.minutes }.coerceAtLeast(1.0) val measurer = rememberTextMeasurer() val labelStyle = TextStyle( - fontSize = 9.sp, + fontSize = 10.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, ) @@ -273,8 +277,14 @@ fun SleepStageBar(segments: List, modifier: Modifier = Modifi // directly, but it is a SubcomposeLayout and the Today grid measures these tiles with // IntrinsicSize.Min, which subcomposition can't answer. onSizeChanged keeps intrinsics intact. var barWidthPx by remember { mutableIntStateOf(0) } + // Labels drop out when a segment is too narrow, and the bar itself says nothing to TalkBack, + // so the whole bar speaks one summary instead. + val spoken = segments.joinToString(", ") { "${stageName(it.label)} ${it.minutes.roundToInt()} min" } Column( - modifier = modifier.fillMaxWidth().onSizeChanged { barWidthPx = it.width }, + modifier = modifier + .fillMaxWidth() + .onSizeChanged { barWidthPx = it.width } + .clearAndSetSemantics { contentDescription = "Sleep stages: $spoken" }, verticalArrangement = Arrangement.spacedBy(3.dp), ) { Row(Modifier.fillMaxWidth().height(12.dp), horizontalArrangement = Arrangement.spacedBy(2.dp)) { @@ -303,7 +313,8 @@ fun SleepStageBar(segments: List, modifier: Modifier = Modifi Text( seg.label, style = labelStyle, - color = seg.color, + // Deep's indigo is ~2.4:1 on the card: legible as a bar, not as text. + color = if (seg.color == PulseColors.stageDeep) PulseColors.textSecondary else seg.color, maxLines = 1, overflow = TextOverflow.Clip, ) @@ -314,6 +325,12 @@ fun SleepStageBar(segments: List, modifier: Modifier = Modifi } } +private fun stageName(label: String) = when (label) { + "AWK" -> "awake" + "REM" -> "REM" + else -> label.lowercase() +} + /** Sleep tile: duration on top, stage distribution bar, score below (SleepTileView in Swift). */ @Composable fun SleepTile( 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 6708c72b..aba164b9 100644 --- a/app/src/main/java/com/pulseloop/ui/components/VitalCard.kt +++ b/app/src/main/java/com/pulseloop/ui/components/VitalCard.kt @@ -120,7 +120,7 @@ private fun CardHeader(state: VitalCardState, compact: Boolean, footerText: Stri private fun EstimatedChip() { Text( "ESTIMATED", - fontSize = 9.sp, + fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.8.sp, color = ZonePalette.ZoneAmber, 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 6b786d3b..e5033abe 100644 --- a/app/src/main/java/com/pulseloop/ui/components/VitalRingGauge.kt +++ b/app/src/main/java/com/pulseloop/ui/components/VitalRingGauge.kt @@ -17,6 +17,10 @@ import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Fill import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.semantics.ProgressBarRangeInfo +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.progressBarRangeInfo import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp @@ -71,7 +75,20 @@ fun VitalRingGauge( return ((v - domain.start) / span).coerceIn(0.0, 1.0) } - Box(modifier.size(size), contentAlignment = Alignment.Center) { + // One spoken summary for the whole gauge (value, unit, status), plus its position on the scale. + val description = listOfNotNull(centerValue, centerUnit, centerStatus, subtitle).joinToString(" ") + Box( + modifier.size(size).clearAndSetSemantics { + contentDescription = description + if (domain.endInclusive > domain.start) { + progressBarRangeInfo = ProgressBarRangeInfo( + value.coerceIn(domain.start, domain.endInclusive).toFloat(), + domain.start.toFloat()..domain.endInclusive.toFloat(), + ) + } + }, + contentAlignment = Alignment.Center, + ) { Canvas(Modifier.matchParentSize()) { val strokePx = lineWidth.toPx() // Inset the arc radius by half the stroke so the stroke fits inside the frame (no 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 bf81b649..02a8bd76 100644 --- a/app/src/main/java/com/pulseloop/ui/components/ZoneLineChart.kt +++ b/app/src/main/java/com/pulseloop/ui/components/ZoneLineChart.kt @@ -11,6 +11,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset @@ -18,6 +19,8 @@ import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathEffect import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @@ -61,6 +64,8 @@ fun ZoneLineChart( * which is why this is opt-in rather than a default. */ verticalGridlines: List = emptyList(), + /** Spoken name for the chart's TalkBack summary, e.g. the card's metric title. */ + label: String? = null, ) { if (samples.size < 2) return val minTs = samples.first().timestampMs @@ -76,8 +81,16 @@ fun ZoneLineChart( val thresholds = zones.flatMap { listOfNotNull(it.lower, it.upper) } .filter { it > yDomain.start && it < yDomain.endInclusive } .distinct().sorted() + // Computed once per data set rather than on every draw pass. + val runs = remember(samples, maxGapMs) { ZoneLineSplitter.segmentsByGap(samples.map { it.timestampMs }, maxGapMs) } + val summary = remember(samples, label) { + val values = samples.map { it.value } + val fmt = if (values.all { it % 1.0 == 0.0 }) "%.0f" else "%.1f" + "${label ?: "Trend"}: latest ${fmt.format(values.last())}, " + + "range ${fmt.format(values.min())}–${fmt.format(values.max())}, ${values.size} readings" + } - Column(modifier.fillMaxWidth()) { + Column(modifier.fillMaxWidth().semantics { contentDescription = summary }) { Row(Modifier.fillMaxWidth().height(if (showAxes) height - 16.dp else height)) { Canvas(Modifier.weight(1f).fillMaxHeight()) { fun x(ts: Long) = (ts - minTs).toFloat() / span * size.width @@ -114,7 +127,6 @@ fun ZoneLineChart( ) } // Zone-colored line, broken across data gaps. - val runs = ZoneLineSplitter.segmentsByGap(samples.map { it.timestampMs }, maxGapMs) runs.forEach { run -> // A gap-isolated single sample would otherwise draw nothing — sparse series // (daily HRV/temp, fatigue) must still show their readings. @@ -163,7 +175,7 @@ fun ZoneLineChart( horizontalAlignment = Alignment.End, ) { listOf(yDomain.endInclusive, (yDomain.start + yDomain.endInclusive) / 2, yDomain.start).forEach { - Text("${it.toInt()}", fontSize = 9.sp, color = PulseColors.textMuted) + Text("${it.toInt()}", fontSize = 11.sp, color = PulseColors.textMuted) } } } @@ -174,7 +186,7 @@ fun ZoneLineChart( horizontalArrangement = Arrangement.SpaceBetween, ) { listOf(minTs, (minTs + maxTs) / 2, maxTs).forEach { - Text(timeLabel(it, span), fontSize = 9.sp, color = PulseColors.textMuted) + Text(timeLabel(it, span), fontSize = 11.sp, color = PulseColors.textMuted) } } } 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 566a63d9..2b38c53c 100644 --- a/app/src/main/java/com/pulseloop/ui/dashboard/DashboardEdit.kt +++ b/app/src/main/java/com/pulseloop/ui/dashboard/DashboardEdit.kt @@ -29,6 +29,14 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.input.pointer.pointerInput +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.unit.dp /** @@ -133,44 +141,57 @@ fun EditableCard( content: @Composable () -> Unit, ) { Box(modifier) { - content() + // While editing, TalkBack hears the card's name only, not its navigate action. + Box(if (editState.editing) Modifier.clearAndSetSemantics { contentDescription = card.displayName } else Modifier) { + content() + } if (editState.editing) { // Consume taps on the card body so navigation doesn't fire while editing (no ripple). - Box( - Modifier.matchParentSize().clickable( - interactionSource = remember { MutableInteractionSource() }, - indication = null, - ) {}, - ) - Surface( - shape = RoundedCornerShape(50), - color = MaterialTheme.colorScheme.errorContainer, - modifier = Modifier.align(Alignment.TopStart).padding(6.dp).size(28.dp), - ) { - IconButton(onClick = { editState.setHidden(card, true) }) { - Icon(Icons.Filled.Remove, contentDescription = "Hide ${card.displayName}", tint = MaterialTheme.colorScheme.onErrorContainer) - } - } - Row(Modifier.align(Alignment.TopEnd).padding(6.dp)) { + // pointerInput rather than clickable: a clickable scrim was a TalkBack stop that did nothing. + Box(Modifier.matchParentSize().pointerInput(Unit) { detectTapGestures { } }) + EditBadge( + Icons.Filled.Remove, "Hide ${card.displayName}", + container = MaterialTheme.colorScheme.errorContainer, + content = MaterialTheme.colorScheme.onErrorContainer, + modifier = Modifier.align(Alignment.TopStart), + ) { editState.setHidden(card, true) } + Row(Modifier.align(Alignment.TopEnd)) { if (editState.canMoveUp(card)) { - Surface(shape = RoundedCornerShape(50), color = MaterialTheme.colorScheme.secondaryContainer, modifier = Modifier.size(28.dp)) { - IconButton(onClick = { editState.moveUp(card) }) { - Icon(Icons.Filled.KeyboardArrowUp, contentDescription = "Move ${card.displayName} up") - } - } + EditBadge(Icons.Filled.KeyboardArrowUp, "Move ${card.displayName} up") { editState.moveUp(card) } } if (editState.canMoveDown(card)) { - Surface(shape = RoundedCornerShape(50), color = MaterialTheme.colorScheme.secondaryContainer, modifier = Modifier.padding(start = 4.dp).size(28.dp)) { - IconButton(onClick = { editState.moveDown(card) }) { - Icon(Icons.Filled.KeyboardArrowDown, contentDescription = "Move ${card.displayName} down") - } - } + EditBadge(Icons.Filled.KeyboardArrowDown, "Move ${card.displayName} down") { editState.moveDown(card) } } } } } } +/** A 28dp badge drawn inside a 48dp touch target, so the up/down pair isn't a 4dp-apart miss. */ +@Composable +private fun EditBadge( + icon: ImageVector, + description: String, + modifier: Modifier = Modifier, + container: Color = MaterialTheme.colorScheme.secondaryContainer, + content: Color = MaterialTheme.colorScheme.onSecondaryContainer, + onClick: () -> Unit, +) { + Box( + modifier + .size(48.dp) + .clickable(role = Role.Button, onClick = onClick) + .semantics { contentDescription = description }, + contentAlignment = Alignment.Center, + ) { + Surface(shape = RoundedCornerShape(50), color = container, modifier = Modifier.size(28.dp)) { + Box(contentAlignment = Alignment.Center) { + Icon(icon, contentDescription = null, tint = content, modifier = Modifier.size(20.dp)) + } + } + } +} + /** * The tray of currently-hidden cards shown while editing, each with a "+" to restore it to its * saved position (iOS `HiddenMetricsTray`). Renders nothing when nothing is hidden. 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 a5cbeca9..34feaf0d 100644 --- a/app/src/main/java/com/pulseloop/ui/onboarding/Editors.kt +++ b/app/src/main/java/com/pulseloop/ui/onboarding/Editors.kt @@ -8,6 +8,8 @@ import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.material.icons.Icons @@ -35,6 +37,10 @@ import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight @@ -112,7 +118,8 @@ fun ProfileEditor( textAlign = TextAlign.End, ), cursorBrush = SolidColor(PulseColors.accent), - modifier = Modifier.fillMaxWidth(), + // The "Name" label is a sibling Text, so the field names itself. + modifier = Modifier.fillMaxWidth().semantics { contentDescription = "Name" }, ) } } @@ -248,7 +255,8 @@ private fun SegmentedRow( .fillMaxWidth() .clip(RoundedCornerShape(4.dp)) .background(PulseColors.cardSoft) - .padding(3.dp), + .padding(3.dp) + .selectableGroup(), horizontalArrangement = Arrangement.spacedBy(3.dp), ) { options.forEachIndexed { index, option -> @@ -258,7 +266,7 @@ private fun SegmentedRow( .weight(1f) .clip(RoundedCornerShape(4.dp)) .background(if (selected) PulseColors.accent else Color.Transparent) - .clickable { onSelect(index) } + .selectable(selected = selected, role = Role.RadioButton) { onSelect(index) } .padding(vertical = 8.dp), contentAlignment = Alignment.Center, ) { @@ -280,7 +288,7 @@ private fun PickerRow(title: String, value: String?, onClick: () -> Unit) { Modifier .fillMaxWidth() .heightIn(min = 50.dp) - .clickable(onClick = onClick), + .clickable(role = Role.Button, onClick = onClick), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { @@ -352,14 +360,14 @@ private fun NumberPickerSheet( } LazyColumn( state = listState, - modifier = Modifier.fillMaxWidth().height(300.dp), + modifier = Modifier.fillMaxWidth().height(300.dp).selectableGroup(), ) { itemsIndexed(values) { _, value -> val selected = value == selection Box( Modifier .fillMaxWidth() - .clickable { selection = value } + .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), contentAlignment = Alignment.Center, @@ -472,11 +480,20 @@ private fun DecimalValueSheet( ), keyboardOptions = androidx.compose.foundation.text.KeyboardOptions( keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal, + imeAction = androidx.compose.ui.text.input.ImeAction.Done, ), + // Done on the keyboard saves, as the sheet's Done does, once the value is valid. + keyboardActions = androidx.compose.foundation.text.KeyboardActions(onDone = { + if (parsedValue != null) { + onSave(parsedValue) + onDismiss() + } + }), cursorBrush = SolidColor(PulseColors.accent), modifier = Modifier .fillMaxWidth() - .focusRequester(focusRequester), + .focusRequester(focusRequester) + .semantics { contentDescription = "Weight in $unit" }, ) } @@ -636,6 +653,10 @@ private fun GoalSliderCard( onValueChange(snapped.toDouble()) }, valueRange = range, + modifier = Modifier.semantics { + contentDescription = title + stateDescription = label + }, colors = SliderDefaults.colors( thumbColor = tint, activeTrackColor = tint, 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 31ae3f0f..8e1fb93c 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.components.switchRow + import com.pulseloop.ui.theme.dither import android.Manifest import android.content.pm.PackageManager @@ -10,6 +12,11 @@ import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons @@ -36,6 +43,9 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp @@ -97,11 +107,14 @@ fun ActivityScreen( // ACTIVITY_RECOGNITION or startForeground() throws — request it right before starting rather // than at app launch, since it's only needed for this one action. var pendingStart by remember { mutableStateOf?>(null) } + // A denial used to do nothing at all; say why the workout didn't start. + var permissionDenied by remember { mutableStateOf(false) } val activityRecognitionLauncher = rememberLauncherForActivityResult( ActivityResultContracts.RequestPermission(), ) { granted -> val pending = pendingStart pendingStart = null + if (!granted) permissionDenied = true if (granted && pending != null) { val (type, useGps) = pending scope.launch { @@ -125,7 +138,7 @@ fun ActivityScreen( } val todayStart = com.pulseloop.util.TimeUtil.startOfTodayLocal() - val todayWorkouts = state.finishedWorkouts.filter { it.startedAt >= todayStart } + val todayWorkouts = remember(state.finishedWorkouts, todayStart) { state.finishedWorkouts.filter { it.startedAt >= todayStart } } 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) @@ -160,7 +173,7 @@ fun ActivityScreen( .height(60.dp) .clip(CircleShape) .background(PulseColors.accent) - .clickable { pickerOpen = true } + .clickable(role = Role.Button) { pickerOpen = true } .wrapContentHeight(), ) Box( @@ -169,7 +182,7 @@ fun ActivityScreen( .clip(CircleShape) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, CircleShape) - .clickable { historyOpen = true }, + .clickable(role = Role.Button) { historyOpen = true }, contentAlignment = Alignment.Center, ) { Icon(Icons.Filled.CalendarMonth, "Workout history", tint = PulseColors.textSecondary) @@ -181,7 +194,7 @@ fun ActivityScreen( Row( Modifier .fillMaxWidth() - .height(68.dp) + .heightIn(min = 68.dp) .clip(RoundedCornerShape(8.dp)) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(8.dp)) @@ -228,9 +241,9 @@ fun ActivityScreen( } } } else { - items(todayWorkouts.size) { i -> - ActivityWorkoutRow(todayWorkouts[i], units) { - navController?.navigate("activity_detail/${todayWorkouts[i].id}") + items(todayWorkouts, key = { it.id }) { workout -> + ActivityWorkoutRow(workout, units) { + navController?.navigate("activity_detail/${workout.id}") } } } @@ -250,6 +263,19 @@ fun ActivityScreen( item { Spacer(Modifier.height(64.dp)) } } + if (permissionDenied) { + AlertDialog( + onDismissRequest = { permissionDenied = false }, + title = { Text("Permission needed") }, + text = { + Text( + "Recording a workout needs the Physical activity permission. " + + "You can allow it in Android Settings › Apps › PulseLoop › Permissions.", + ) + }, + confirmButton = { TextButton(onClick = { permissionDenied = false }) { Text("OK") } }, + ) + } if (pickerOpen) { RecordTypePickerDialog( onDismiss = { pickerOpen = false }, @@ -336,9 +362,9 @@ private fun ActivityNavChevron( ) { Box( Modifier - .size(44.dp) + .size(48.dp) .clip(CircleShape) - .then(if (enabled) Modifier.clickable(onClick = onClick) else Modifier), + .clickable(enabled = enabled, role = Role.Button, onClick = onClick), contentAlignment = Alignment.Center, ) { Icon( @@ -400,6 +426,7 @@ private fun DailyActivitySummaryCard(state: ActivityViewModel.ActivityState, uni size = 112.dp, strokeWidth = 11.dp, ringSpacing = 5.dp, + labels = listOf("steps", "distance", "calories"), ) } } @@ -511,7 +538,7 @@ private fun WeeklyGoalCard(state: ActivityViewModel.ActivityState, days: List) { } Text( day.label, - fontSize = 10.sp, fontWeight = FontWeight.Medium, letterSpacing = 0.5.sp, + fontSize = 11.sp, fontWeight = FontWeight.Medium, letterSpacing = 0.5.sp, color = if (day.isToday) PulseColors.textPrimary else PulseColors.textMuted, ) } @@ -617,33 +644,38 @@ private fun RecordTypePickerDialog(onDismiss: () -> Unit, onStart: (String, Bool onDismissRequest = onDismiss, title = { Text("Record activity") }, text = { - Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { - ActivityMeta.ORDER.forEach { type -> - val active = type == selected - Row( - Modifier - .fillMaxWidth() - .clip(RoundedCornerShape(4.dp)) - .then(if (active) Modifier.dither(PulseColors.accent, 0.18f) else Modifier.background(Color.Transparent)) - .clickable { selected = type } - .padding(horizontal = 10.dp, vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(10.dp), - ) { - Icon(ActivityMeta.icon(type), null, tint = PulseColors.accent, modifier = Modifier.size(18.dp)) - Column { - Text(ActivityMeta.label(type), fontSize = 14.sp, fontWeight = FontWeight.Medium) - Text(ActivityMeta.helper(type), fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) + // Scrolls: eight types plus the GPS row overflow a landscape or large-font dialog. + Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Column(Modifier.selectableGroup(), verticalArrangement = Arrangement.spacedBy(4.dp)) { + ActivityMeta.ORDER.forEach { type -> + val active = type == selected + Row( + Modifier + .fillMaxWidth() + .heightIn(min = 48.dp) + .clip(RoundedCornerShape(4.dp)) + .then(if (active) Modifier.dither(PulseColors.accent, 0.18f) else Modifier.background(Color.Transparent)) + .selectable(selected = active, role = Role.RadioButton) { selected = type } + .padding(horizontal = 10.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + Icon(ActivityMeta.icon(type), null, tint = PulseColors.accent, modifier = Modifier.size(18.dp)) + Column { + Text(ActivityMeta.label(type), fontSize = 14.sp, fontWeight = FontWeight.Medium) + Text(ActivityMeta.helper(type), fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) + } } } } if (ActivityMeta.gpsCapable(selected)) { Row( - Modifier.fillMaxWidth().padding(top = 8.dp), + Modifier.fillMaxWidth().padding(top = 8.dp) + .switchRow(checked = useGps, onCheckedChange = { useGps = it }), verticalAlignment = Alignment.CenterVertically, ) { Text("Track GPS route", fontSize = 14.sp, modifier = Modifier.weight(1f)) - Switch(checked = useGps, onCheckedChange = { useGps = it }) + Switch(checked = useGps, onCheckedChange = null) } } } @@ -792,7 +824,13 @@ private fun ActivityRecordsCard( Modifier.fillMaxWidth().clip(shape).background(PulseColors.card).border(1.dp, PulseColors.borderSubtle, shape), ) { Row( - Modifier.fillMaxWidth().clickable { expanded = !expanded }.padding(16.dp), + Modifier.fillMaxWidth() + .clickable( + role = Role.Button, + onClickLabel = if (expanded) "Hide activity records" else "Show activity records", + ) { expanded = !expanded } + .semantics { stateDescription = if (expanded) "Expanded" else "Collapsed" } + .padding(16.dp), verticalAlignment = Alignment.CenterVertically, ) { Text( @@ -806,7 +844,7 @@ private fun ActivityRecordsCard( } Icon( if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, - contentDescription = if (expanded) "Hide activity records" else "Show activity records", + contentDescription = null, tint = PulseColors.textMuted, modifier = Modifier.size(20.dp), ) @@ -847,7 +885,7 @@ private fun ActivityRecordsCard( fontSize = 11.sp, color = PulseColors.textMuted, ) } - IconButton(onClick = { pending = bucket }, modifier = Modifier.size(36.dp)) { + IconButton(onClick = { pending = bucket }) { Icon( Icons.Filled.DeleteOutline, contentDescription = "Delete this activity record", 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 55a67410..c34961ac 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/BarcodeScannerScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/BarcodeScannerScreen.kt @@ -2,7 +2,10 @@ package com.pulseloop.ui.screens import android.Manifest import android.content.Context +import android.content.Intent import android.content.pm.PackageManager +import android.net.Uri +import android.provider.Settings import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.camera.core.CameraSelector @@ -25,6 +28,7 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.QrCodeScanner import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Icon +import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable @@ -105,7 +109,7 @@ fun BarcodeScannerScreen(onScan: (String) -> Unit, onDismiss: () -> Unit) { val permissionLauncher = rememberLauncherForActivityResult( ActivityResultContracts.RequestPermission(), ) { granted -> - availability = if (granted) ScanAvailability.Granted else ScanAvailability.Unavailable + availability = if (granted) ScanAvailability.Granted else ScanAvailability.Denied } LaunchedEffect(Unit) { when { @@ -116,6 +120,16 @@ fun BarcodeScannerScreen(onScan: (String) -> Unit, onDismiss: () -> Unit) { } } + // A grant made in system Settings while this sheet is open picks the camera up on return. + LaunchedEffect(availability) { + while (availability == ScanAvailability.Denied) { + kotlinx.coroutines.delay(1_000) + if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == + PackageManager.PERMISSION_GRANTED + ) availability = ScanAvailability.Granted + } + } + val previewView = remember { PreviewView(context).apply { implementationMode = PreviewView.ImplementationMode.COMPATIBLE @@ -243,7 +257,7 @@ fun BarcodeScannerScreen(onScan: (String) -> Unit, onDismiss: () -> Unit) { ) Spacer(Modifier.height(6.dp)) Text( - "Barcode scanning needs a device camera and camera access. Search by name instead.", + "Barcode scanning needs a working device camera. Enter the food manually instead.", fontSize = 12.sp, color = PulseColors.textMuted, textAlign = TextAlign.Center, @@ -251,6 +265,43 @@ fun BarcodeScannerScreen(onScan: (String) -> Unit, onDismiss: () -> Unit) { } } + ScanAvailability.Denied -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Column( + Modifier.fillMaxWidth().padding(horizontal = 32.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Icon( + Icons.Filled.QrCodeScanner, + contentDescription = null, + tint = PulseColors.textMuted, + modifier = Modifier.size(34.dp), + ) + Spacer(Modifier.height(10.dp)) + Text( + "Camera access needed", + fontSize = 17.sp, + fontWeight = FontWeight.SemiBold, + color = PulseColors.textPrimary, + ) + Spacer(Modifier.height(6.dp)) + Text( + "Allow camera access in Settings to scan barcodes, or enter the food manually instead.", + fontSize = 12.sp, + color = PulseColors.textMuted, + textAlign = TextAlign.Center, + ) + Spacer(Modifier.height(16.dp)) + OutlinedButton(onClick = { + runCatching { + context.startActivity( + Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) + .setData(Uri.fromParts("package", context.packageName, null)), + ) + } + }) { Text("Open settings") } + } + } + ScanAvailability.Checking -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator(color = PulseColors.accent) } @@ -270,7 +321,7 @@ fun BarcodeScannerDialog(onScan: (String) -> Unit, onDismiss: () -> Unit) { } } -private enum class ScanAvailability { Checking, Granted, Unavailable } +private enum class ScanAvailability { Checking, Granted, Denied, Unavailable } /** Bridges a Guava [ListenableFuture] (CameraX's provider future) to a suspend call without * the kotlinx-coroutines-jdk8 artifact — the listener resumes on the main executor. */ 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 205f0e31..faaba08e 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/BodyUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/BodyUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.components.switchRow + import androidx.activity.compose.rememberLauncherForActivityResult import androidx.compose.foundation.Canvas import androidx.compose.foundation.background @@ -16,6 +18,8 @@ import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @@ -25,6 +29,9 @@ import com.pulseloop.data.entity.BodyMeasurementEntity import com.pulseloop.health.HealthConnectAvailability import com.pulseloop.health.HealthConnectBodyImport import com.pulseloop.health.HealthConnectSdk +import com.pulseloop.settings.ApiKeyStore +import com.pulseloop.settings.UnitConverter +import com.pulseloop.settings.UnitSystem import com.pulseloop.ui.theme.PulseColors import kotlinx.coroutines.launch import java.time.Instant @@ -55,6 +62,9 @@ fun HealthConnectBodyCard(onUpdated: () -> Unit) { var busy by remember { mutableStateOf(false) } var note by remember { mutableStateOf(null) } var refresh by remember { mutableIntStateOf(0) } + // Stored in kg; shown in the user's unit setting (BMI still computes from kg). + val units = remember { ApiKeyStore(context) }.resolvedUnitSystem + val unit = UnitConverter.weightUnit(units) val snapshot by produceState(null, refresh) { value = runCatching { @@ -92,7 +102,10 @@ fun HealthConnectBodyCard(onUpdated: () -> Unit) { Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp), ) { - Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) { + Row(Modifier.switchRow(checked = enabled, enabled = available && !busy, onCheckedChange = { on -> + if (on) launcher.launch(HealthConnectBodyImport.permissions) + else { enabled = false; HealthConnectBodyImport.setEnabled(context, false) } + }), verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text("Sync from your scale", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text( @@ -100,14 +113,7 @@ fun HealthConnectBodyCard(onUpdated: () -> Unit) { fontSize = 12.sp, color = PulseColors.textSecondary, ) } - Switch( - checked = enabled, - enabled = available && !busy, - onCheckedChange = { on -> - if (on) launcher.launch(HealthConnectBodyImport.permissions) - else { enabled = false; HealthConnectBodyImport.setEnabled(context, false) } - }, - ) + Switch(checked = enabled, enabled = available && !busy, onCheckedChange = null) } if (!available) { Text("Health Connect isn't available on this phone.", fontSize = 12.sp, color = PulseColors.textMuted) @@ -119,16 +125,16 @@ fun HealthConnectBodyCard(onUpdated: () -> Unit) { 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)) { - Text("%.1f".format(w.value), fontSize = 28.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text("kg · $whenText", fontSize = 12.sp, color = PulseColors.textMuted, modifier = Modifier.padding(bottom = 5.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)) } val facts = buildList { s.bodyFatPct?.let { add("Body fat ${"%.1f".format(it)}%") } - s.leanMassKg?.let { add("Lean ${"%.1f".format(it)} kg") } + s.leanMassKg?.let { add("Lean ${"%.1f".format(UnitConverter.weight(it, units))} $unit") } s.heightCm?.takeIf { it > 0 }?.let { h -> add("BMI ${"%.1f".format(w.value / ((h / 100) * (h / 100)))}") } } if (facts.isNotEmpty()) Text(facts.joinToString(" · "), fontSize = 13.sp, color = PulseColors.textSecondary) - if (s.trend.size >= 2) WeightLine(s.trend) + if (s.trend.size >= 2) WeightLine(s.trend, units) Text("From ${w.source}", fontSize = 11.sp, color = PulseColors.textMuted) } note?.let { Text(it, fontSize = 12.sp, color = PulseColors.textMuted) } @@ -140,12 +146,16 @@ fun HealthConnectBodyCard(onUpdated: () -> Unit) { /** A plain 90-day weight line. */ @Composable -private fun WeightLine(points: List) { +private fun WeightLine(points: List, units: UnitSystem) { val min = points.minOf { it.value } val max = points.maxOf { it.value } val t0 = points.first().measuredAt val t1 = points.last().measuredAt - Canvas(Modifier.fillMaxWidth().height(56.dp)) { + val unit = UnitConverter.weightUnit(units) + fun shown(kg: Double) = "%.1f".format(UnitConverter.weight(kg, units)) + val summary = "Weight, last 90 days: latest ${shown(points.last().value)} $unit, " + + "range ${shown(min)}–${shown(max)} $unit, ${points.size} weigh-ins" + Canvas(Modifier.fillMaxWidth().height(56.dp).semantics { contentDescription = summary }) { val range = (max - min).takeIf { it > 0.2 } ?: 0.2 fun x(t: Long) = if (t1 == t0) size.width else (t - t0).toFloat() / (t1 - t0) * size.width fun y(v: Double) = size.height - ((v - min) / range * size.height * 0.85 + size.height * 0.075).toFloat() @@ -157,10 +167,10 @@ private fun WeightLine(points: List) { drawPath(path, PulseColors.accent, style = Stroke(width = 2.dp.toPx(), cap = StrokeCap.Round)) } Row(Modifier.fillMaxWidth()) { - Text("%.1f".format(points.first().value), fontSize = 11.sp, color = PulseColors.textMuted, modifier = Modifier.weight(1f)) - val delta = points.last().value - points.first().value + Text(shown(points.first().value), fontSize = 11.sp, color = PulseColors.textMuted, modifier = Modifier.weight(1f)) + val delta = UnitConverter.weight(points.last().value - points.first().value, units) Text( - "${if (delta >= 0) "+" else ""}${(delta * 10).roundToInt() / 10.0} kg in 90 days", + "${if (delta >= 0) "+" else ""}${(delta * 10).roundToInt() / 10.0} $unit in 90 days", fontSize = 11.sp, color = PulseColors.textMuted, ) } 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 636519f4..e7a54f58 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CoachModelPicker.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CoachModelPicker.kt @@ -95,6 +95,7 @@ fun CoachModelPicker( OutlinedTextField( value = filter, onValueChange = { filter = it }, + label = { Text("Filter models") }, placeholder = { Text("Filter, e.g. claude") }, singleLine = true, modifier = Modifier.padding(horizontal = 12.dp).fillMaxWidth(), 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 ed973f6f..8cb1181f 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt @@ -17,13 +17,14 @@ import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.ArrowUpward import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Info import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment @@ -36,7 +37,14 @@ import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.Role +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.input.ImeAction +import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @@ -113,7 +121,8 @@ fun CoachScreen( onCheckIn = { viewModel?.sendMessage("How am I doing on my goal? What should I focus on this week?", emptyList()) }, ) } - items(state.messages.size) { idx -> + // Persisted rows key by id; the greeting and this session's unsaved turns have none. + items(state.messages.size, key = { idx -> state.messages[idx].id ?: "local-$idx" }) { idx -> MessageBubble(state.messages[idx], viewModel) } if (state.isThinking) { @@ -127,7 +136,10 @@ fun CoachScreen( } if (state.error != null) { item { - Text("Error: ${state.error}", fontSize = 12.sp, color = PulseColors.danger, modifier = Modifier.padding(start = 8.dp)) + Text( + "Error: ${state.error}", fontSize = 12.sp, color = PulseColors.danger, + modifier = Modifier.padding(start = 8.dp).semantics { liveRegion = LiveRegionMode.Polite }, + ) } } } @@ -185,29 +197,45 @@ fun CoachHeader(onNewChat: () -> Unit, onOpenUsage: (() -> Unit)? = null) { Text("Using your latest ring sync", fontSize = 12.sp, color = PulseColors.textMuted) } if (onOpenUsage != null) { - Box( - Modifier - .size(36.dp) - .clip(CircleShape) - .background(PulseColors.card) - .border(1.dp, PulseColors.borderSubtle, CircleShape) - .clickable(onClick = onOpenUsage), - contentAlignment = Alignment.Center, - ) { + RoundIconTarget(visualSize = 36.dp, onClick = onOpenUsage) { Icon(Icons.Filled.Info, "Usage & cost", tint = PulseColors.textSecondary, modifier = Modifier.size(16.dp)) } } + RoundIconTarget(visualSize = 36.dp, onClick = onNewChat) { + Icon(Icons.Filled.Add, "New chat", tint = PulseColors.textSecondary, modifier = Modifier.size(18.dp)) + } + } +} + +/** + * A round icon button drawn at [visualSize] inside a 48dp touch target, so the small circles + * keep their look while meeting the minimum target size. + */ +@Composable +private fun RoundIconTarget( + visualSize: Dp, + background: Color = PulseColors.card, + bordered: Boolean = true, + enabled: Boolean = true, + onClick: () -> Unit, + content: @Composable BoxScope.() -> Unit, +) { + Box( + Modifier + .size(48.dp) + .clip(CircleShape) + .clickable(enabled = enabled, role = Role.Button, onClick = onClick), + contentAlignment = Alignment.Center, + ) { Box( Modifier - .size(36.dp) + .size(visualSize) .clip(CircleShape) - .background(PulseColors.card) - .border(1.dp, PulseColors.borderSubtle, CircleShape) - .clickable(onClick = onNewChat), + .background(background) + .then(if (bordered) Modifier.border(1.dp, PulseColors.borderSubtle, CircleShape) else Modifier), contentAlignment = Alignment.Center, - ) { - Icon(Icons.Filled.Add, "New chat", tint = PulseColors.textSecondary, modifier = Modifier.size(18.dp)) - } + content = content, + ) } } @@ -308,6 +336,11 @@ private fun Composer( } } val canSend = (inputText.isNotBlank() || staged.isNotEmpty()) && !isThinking + fun send() { + if (!canSend) return + onSend(inputText.trim(), staged) + staged = emptyList() + } // Coach draws full-bleed under the bottom nav bar, so the composer must lift itself: above the // keyboard while it's open, above the nav bar otherwise. max() (not sum) of the two insets @@ -326,26 +359,34 @@ private fun Composer( .padding(bottom = composerBottom + 8.dp), ) { if (showChips) { + // Each chip sits in a 48dp-tall touch target, which stands in for the row's old + // vertical padding. Row( Modifier .fillMaxWidth() .horizontalScroll(rememberScrollState()) - .padding(horizontal = 12.dp, vertical = 8.dp), + .padding(horizontal = 12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), ) { SUGGESTIONS.forEach { chip -> - Text( - chip, - fontSize = 12.sp, fontWeight = FontWeight.Medium, - color = PulseColors.textSecondary, - maxLines = 1, - modifier = Modifier - .clip(CircleShape) - .background(PulseColors.card) - .border(1.dp, PulseColors.borderSubtle, CircleShape) - .clickable(enabled = !isThinking) { onSend(chip, emptyList()) } - .padding(horizontal = 12.dp, vertical = 7.dp), - ) + Box( + Modifier + .heightIn(min = 48.dp) + .clickable(enabled = !isThinking, role = Role.Button) { onSend(chip, emptyList()) }, + contentAlignment = Alignment.Center, + ) { + Text( + chip, + fontSize = 12.sp, fontWeight = FontWeight.Medium, + color = PulseColors.textSecondary, + maxLines = 1, + modifier = Modifier + .clip(CircleShape) + .background(PulseColors.card) + .border(1.dp, PulseColors.borderSubtle, CircleShape) + .padding(horizontal = 12.dp, vertical = 7.dp), + ) + } } } } @@ -365,13 +406,20 @@ private fun Composer( contentScale = ContentScale.Crop, ) } - IconButton( - onClick = { - CoachAttachmentStore.delete(ctx, ref) - staged = staged - ref - }, - modifier = Modifier.size(20.dp).align(Alignment.TopEnd), - ) { Icon(Icons.Filled.Close, "Remove photo", Modifier.size(14.dp), tint = Color.White) } + // 48dp touch target over the thumbnail's corner; the glyph stays small + // in that corner, where it always sat. + Box( + Modifier + .size(48.dp) + .align(Alignment.TopEnd) + .clickable(role = Role.Button) { + CoachAttachmentStore.delete(ctx, ref) + staged = staged - ref + }, + contentAlignment = Alignment.TopEnd, + ) { + Icon(Icons.Filled.Close, "Remove photo", Modifier.padding(3.dp).size(14.dp), tint = Color.White) + } } } } @@ -385,28 +433,16 @@ private fun Composer( // Landscape has no Coach header — bring its new-chat button down in line with the // input. Bordered circle + "+" glyph mirrors the header's affordance exactly so the // control reads the same in both orientations. - Box( - Modifier - .size(40.dp) - .clip(CircleShape) - .background(PulseColors.card) - .border(1.dp, PulseColors.borderSubtle, CircleShape) - .clickable(onClick = onNewChat), - contentAlignment = Alignment.Center, - ) { + RoundIconTarget(visualSize = 40.dp, onClick = onNewChat) { Icon(Icons.Filled.Add, "New chat", tint = PulseColors.textSecondary, modifier = Modifier.size(18.dp)) } } if (imageInputEnabled) { - Box( - Modifier - .size(40.dp) - .clip(CircleShape) - .background(PulseColors.card) - .clickable(enabled = !isThinking) { - pickImage.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) - }, - contentAlignment = Alignment.Center, + RoundIconTarget( + visualSize = 40.dp, + bordered = false, + enabled = !isThinking, + onClick = { pickImage.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) }, ) { Icon(Icons.Filled.Add, "Attach photo", tint = PulseColors.textMuted, modifier = Modifier.size(20.dp)) } @@ -431,19 +467,22 @@ private fun Composer( fontSize = 14.sp, color = PulseColors.textPrimary, ), cursorBrush = SolidColor(PulseColors.accent), - modifier = Modifier.fillMaxWidth(), + keyboardOptions = KeyboardOptions( + capitalization = KeyboardCapitalization.Sentences, + imeAction = ImeAction.Send, + ), + keyboardActions = KeyboardActions(onSend = { send() }), + // The placeholder is a sibling Text that disappears once typing starts, so + // the field carries its own label. + modifier = Modifier.fillMaxWidth().semantics { contentDescription = "Message the coach" }, ) } - Box( - Modifier - .size(40.dp) - .clip(CircleShape) - .background(if (canSend) PulseColors.accent else PulseColors.card) - .clickable(enabled = canSend) { - onSend(inputText.trim(), staged) - staged = emptyList() - }, - contentAlignment = Alignment.Center, + RoundIconTarget( + visualSize = 40.dp, + background = if (canSend) PulseColors.accent else PulseColors.card, + bordered = false, + enabled = canSend, + onClick = ::send, ) { Icon( Icons.Filled.ArrowUpward, "Send", 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 b8b6281c..c1bac44a 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CoachUsageSheet.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CoachUsageSheet.kt @@ -158,8 +158,8 @@ private fun MessageBreakdownRow(message: CoachMessageEntity) { Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { Text(preview.ifEmpty { "(no text)" }, fontSize = 12.sp, color = PulseColors.textPrimary, maxLines = 1) Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { - Text(tokens, fontSize = 11.sp, color = PulseColors.textMuted) - Text(cost, fontSize = 11.sp, color = PulseColors.textMuted) + Text(tokens, fontSize = 12.sp, color = PulseColors.textMuted) + Text(cost, fontSize = 12.sp, color = PulseColors.textMuted) } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/DebugScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/DebugScreen.kt index 3aae30e9..c6b44e98 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/DebugScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/DebugScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.components.switchRow + import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.icons.Icons @@ -166,7 +168,7 @@ fun DebugScreen(viewModel: DiagnosticsViewModel, onBack: () -> Unit = {}) { DebugCard("Diagnostics") { Text("Export app, device, and wearable logs as JSON.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - Row(verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.switchRow(checked = maskSensitive, onCheckedChange = { maskSensitive = it }), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text("Mask sensitive data", style = MaterialTheme.typography.bodyMedium) Text( @@ -179,7 +181,7 @@ fun DebugScreen(viewModel: DiagnosticsViewModel, onBack: () -> Unit = {}) { else MaterialTheme.colorScheme.error, ) } - Switch(checked = maskSensitive, onCheckedChange = { maskSensitive = it }) + Switch(checked = maskSensitive, onCheckedChange = null) } Button( onClick = { 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 ec518cc5..00ed1860 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt @@ -4,6 +4,8 @@ import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape @@ -49,6 +51,10 @@ 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.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.graphics.PathEffect import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.Stroke @@ -117,7 +123,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 = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted, modifier = Modifier.weight(1f)) + Text(title.orEmpty().uppercase(), fontSize = 12.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted, modifier = Modifier.weight(1f)) action?.invoke() } } @@ -130,14 +136,19 @@ private fun Stepper(label: String, value: String, onMinus: () -> Unit, onPlus: ( Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text(label, fontSize = 14.sp, color = PulseColors.textPrimary) - note?.let { Text(it, fontSize = 11.sp, color = PulseColors.textMuted) } + note?.let { Text(it, fontSize = 12.sp, color = PulseColors.textMuted) } + } + TextButton(onClick = onMinus, modifier = Modifier.semantics { contentDescription = "Decrease $label" }) { + Text("−", fontSize = 18.sp, modifier = Modifier.clearAndSetSemantics {}) } - TextButton(onClick = onMinus) { Text("−", fontSize = 18.sp) } Text(value, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary, textAlign = TextAlign.Center, modifier = Modifier.widthIn(min = 36.dp)) - TextButton(onClick = onPlus) { Text("+", fontSize = 18.sp) } + TextButton(onClick = onPlus, modifier = Modifier.semantics { contentDescription = "Increase $label" }) { + Text("+", fontSize = 18.sp, modifier = Modifier.clearAndSetSemantics {}) + } } } +/** One option of a single-choice group: put the group under `Modifier.selectableGroup()`. */ @Composable private fun Pill(label: String, on: Boolean, color: Color = PulseColors.accent, onClick: () -> Unit) { val shape = RoundedCornerShape(16.dp) @@ -150,7 +161,7 @@ private fun Pill(label: String, on: Boolean, color: Color = PulseColors.accent, modifier = Modifier.clip(shape) .background(if (on) color else PulseColors.cardSoft) .border(1.dp, if (on) color else PulseColors.borderSubtle, shape) - .clickable(onClick = onClick) + .selectable(selected = on, role = Role.RadioButton, onClick = onClick) .padding(horizontal = 12.dp, vertical = 8.dp), ) } @@ -167,7 +178,7 @@ private fun Bar(fraction: Float, color: Color) { @Composable private fun Segments(options: List, selected: Int, onSelect: (Int) -> Unit) { val shape = RoundedCornerShape(16.dp) - Row(Modifier.fillMaxWidth().clip(shape).border(1.dp, PulseColors.borderSubtle, shape)) { + Row(Modifier.fillMaxWidth().clip(shape).border(1.dp, PulseColors.borderSubtle, shape).selectableGroup()) { options.forEachIndexed { i, label -> val on = i == selected Text( @@ -179,7 +190,7 @@ private fun Segments(options: List, selected: Int, onSelect: (Int) -> Un maxLines = 1, modifier = Modifier.weight(1f) .background(if (on) PulseColors.accent else PulseColors.cardSoft) - .clickable { onSelect(i) } + .selectable(selected = on, role = Role.Tab) { onSelect(i) } .padding(vertical = 9.dp), ) } @@ -298,7 +309,7 @@ private fun DrinksWelcome(onStart: () -> Unit) { Icon(if (showSize) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, null, tint = PulseColors.textMuted) } if (showSize) { - FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + FlowRow(Modifier.selectableGroup(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { listOf(10.0 to "10 g (WHO)", 8.0 to "8 g (UK)", 14.0 to "14 g (US)").forEach { (g, l) -> Pill(l, grams == g, PulseColors.drinks) { grams = g } } @@ -418,6 +429,7 @@ private fun LogCard(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChang var planOpen by remember { mutableStateOf(false) } var showTonight by remember { mutableStateOf(false) } var lastLogged by remember { mutableStateOf>?>(null) } + var toDelete by remember { mutableStateOf(null) } DrinkCard("Log a drink", action = { Text( @@ -482,9 +494,23 @@ private fun LogCard(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChang if (showTonight) { val zone = ZoneId.systemDefault() val fmt = DateTimeFormatter.ofPattern("EEE HH:mm") - s.recent.forEach { e -> RecentDrinkRow(e, s.gramsPerStandard, fmt, zone) { scope.launch { db.drinkDao().delete(e.id); onChange() } } } + s.recent.forEach { e -> RecentDrinkRow(e, s.gramsPerStandard, fmt, zone) { toDelete = e } } } } + toDelete?.let { e -> + AlertDialog( + onDismissRequest = { toDelete = null }, + title = { Text("Delete drink?") }, + text = { Text("This ${DrinkType.of(e.type).label.lowercase()} will be removed from your log.") }, + confirmButton = { + TextButton(onClick = { + toDelete = null + scope.launch { db.drinkDao().delete(e.id); onChange() } + }) { Text("Delete", color = PulseColors.danger) } + }, + dismissButton = { TextButton(onClick = { toDelete = null }) { Text("Cancel") } }, + ) + } if (more) { ModalBottomSheet( @@ -557,10 +583,10 @@ private fun RecentDrinkRow(e: DrinkEntryEntity, gramsPerStd: Double, fmt: DateTi Text( "${Instant.ofEpochMilli(e.timestamp).atZone(zone).format(fmt)} · ${std(DrinkInsights.standardDrinks(e.grams, gramsPerStd))} drink" + if (e.mealId != null) " · from food log" else "", - fontSize = 11.sp, color = PulseColors.textMuted, + fontSize = 12.sp, color = PulseColors.textMuted, ) } - IconButton(onClick = onDelete) { Icon(Icons.Filled.Delete, "Delete", tint = PulseColors.textMuted, modifier = Modifier.size(18.dp)) } + IconButton(onClick = onDelete) { Icon(Icons.Filled.Delete, "Delete ${DrinkType.of(e.type).label}", tint = PulseColors.textMuted, modifier = Modifier.size(18.dp)) } } } @@ -573,12 +599,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("Log drinks", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + FlowRow(Modifier.selectableGroup(), horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { DrinkType.entries.forEach { t -> Pill(t.label, type == t, PulseColors.drinks) { type = t } } } Text("${type.volumeMl.roundToInt()} ml at ${type.abvPct}% · about ${type.kcal.roundToInt()} kcal", fontSize = 12.sp, color = PulseColors.textMuted) Stepper("How many", "$count", { count = (count - 1).coerceAtLeast(1) }, { count = (count + 1).coerceAtMost(12) }) - FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + FlowRow(Modifier.selectableGroup(), horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { listOf(0L to "Now", 1L to "1 h ago", 3L to "3 h ago", 12L to "Last night").forEach { (h, l) -> Pill(l, hoursAgo == h, PulseColors.drinks) { hoursAgo = h } } @@ -791,13 +817,17 @@ private fun AuditCard(s: DrinksRepository.Snapshot, onDone: () -> Unit) { Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(12.dp)) { AuditC.QUESTIONS.forEachIndexed { qi, (q, options) -> Text(q, fontSize = 14.sp, fontWeight = FontWeight.Medium) - options.forEachIndexed { oi, o -> - Row( - Modifier.fillMaxWidth().clickable { answers[qi] = oi }.padding(vertical = 2.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - RadioButton(selected = answers[qi] == oi, onClick = { answers[qi] = oi }) - Text(o, fontSize = 13.sp) + Column(Modifier.selectableGroup()) { + options.forEachIndexed { oi, o -> + Row( + Modifier.fillMaxWidth() + .selectable(selected = answers[qi] == oi, role = Role.RadioButton) { answers[qi] = oi } + .heightIn(min = 48.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + RadioButton(selected = answers[qi] == oi, onClick = null) + Text(o, fontSize = 13.sp) + } } } } @@ -839,7 +869,7 @@ private fun DrinkSettings(onChange: () -> Unit, onTurnedOff: () -> Unit) { { typical = (typical + 1).coerceAtMost(80); DrinkPrefs.baselinePerWeek = typical.toDouble(); onChange() }, note = "For drinks, money and calories saved") Text("Standard drink", fontSize = 14.sp, color = PulseColors.textPrimary) - FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + FlowRow(Modifier.selectableGroup(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { listOf(10.0 to "10 g (WHO)", 8.0 to "8 g (UK)", 14.0 to "14 g (US)").forEach { (g, l) -> Pill(l, grams == g, PulseColors.drinks) { grams = g; DrinkPrefs.gramsPerStandard = g; onChange() } } @@ -887,6 +917,6 @@ fun ColumnScope.DrinksTileContent(week: DrinkInsights.Week?, limit: Double, dryT Text( "+ ${DrinkPrefs.lastType.label}", fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, maxLines = 1, - modifier = Modifier.clickable(onClick = onAdd).padding(vertical = 2.dp), + modifier = Modifier.clickable(role = Role.Button, onClick = onAdd).padding(vertical = 2.dp), ) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/FoodUi.kt b/app/src/main/java/com/pulseloop/ui/screens/FoodUi.kt index 0237698a..14804354 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/FoodUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/FoodUi.kt @@ -18,6 +18,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip 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.unit.dp import androidx.compose.ui.unit.sp @@ -87,10 +88,10 @@ fun FoodCard( if (!f.enabled) { Text( "Hide", fontSize = 12.sp, color = PulseColors.textMuted, - modifier = Modifier.clickable { + modifier = Modifier.clickable(role = Role.Button) { hidden = true hiddenPrefs(context).edit().putBoolean("hidden", true).apply() - }.padding(4.dp), + }.heightIn(min = 48.dp).wrapContentHeight().padding(horizontal = 12.dp), ) } } 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 118a62e3..64401726 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt @@ -5,6 +5,9 @@ import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.foundation.selection.toggleable import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons @@ -17,6 +20,7 @@ import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +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 @@ -73,57 +77,65 @@ fun JournalTagsCard( } // Chips size to their label and wrap as a row, one line each: a fixed two-column grid // broke the longer labels over two lines in a monospace face. + // Each chip sits in a 48dp-tall touch target, so the rows need no extra vertical gap. FlowRow( Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), ) { tags.forEach { tag -> val on = tag.key in selected val chip = RoundedCornerShape(16.dp) // GMind pill: filter chips keep the 16dp radius - Text( - tag.label, - fontSize = 13.sp, - fontWeight = if (on) FontWeight.Bold else FontWeight.Normal, - color = if (on) PulseColors.onAccent else PulseColors.textSecondary, - maxLines = 1, - softWrap = false, - modifier = Modifier - .clip(chip) - .background(if (on) PulseColors.accent else PulseColors.cardSoft) - .border(1.dp, if (on) PulseColors.accent else PulseColors.borderSubtle, chip) - .clickable { + Box( + Modifier + .heightIn(min = 48.dp) + .toggleable(value = on, role = Role.Checkbox) { scope.launch { val id = JournalEntryEntity.idFor(day, tag.key) if (on) db.journalDao().delete(id) else db.journalDao().upsert(JournalEntryEntity(id = id, day = day, tag = tag.key)) } - } - .padding(horizontal = 12.dp, vertical = 8.dp), - ) + }, + contentAlignment = Alignment.Center, + ) { + Text( + tag.label, + fontSize = 13.sp, + fontWeight = if (on) FontWeight.Bold else FontWeight.Normal, + color = if (on) PulseColors.onAccent else PulseColors.textSecondary, + maxLines = 1, + softWrap = false, + modifier = Modifier + .clip(chip) + .background(if (on) PulseColors.accent else PulseColors.cardSoft) + .border(1.dp, if (on) PulseColors.accent else PulseColors.borderSubtle, chip) + .padding(horizontal = 12.dp, vertical = 8.dp), + ) + } } } footer?.invoke() } } -/** Today / Yesterday, as two small segments. */ +/** Today / Yesterday, as two small segments, each with a 48dp-tall touch target. */ @Composable private fun DaySwitch(yesterday: Boolean, onChange: (Boolean) -> Unit) { val shape = RoundedCornerShape(16.dp) - Row(Modifier.clip(shape).border(1.dp, PulseColors.borderSubtle, shape)) { - listOf(false to "Today", true to "Yesterday").forEach { (isYesterday, label) -> - val on = yesterday == isYesterday - Text( - label, - fontSize = 12.sp, - fontWeight = if (on) FontWeight.Bold else FontWeight.Normal, - color = if (on) PulseColors.onAccent else PulseColors.textSecondary, - modifier = Modifier - .background(if (on) PulseColors.accent else PulseColors.cardSoft) - .clickable { onChange(isYesterday) } - .padding(horizontal = 10.dp, vertical = 6.dp), - ) + Box(Modifier.heightIn(min = 48.dp), contentAlignment = Alignment.Center) { + Row(Modifier.clip(shape).border(1.dp, PulseColors.borderSubtle, shape).selectableGroup()) { + listOf(false to "Today", true to "Yesterday").forEach { (isYesterday, label) -> + val on = yesterday == isYesterday + Text( + label, + fontSize = 12.sp, + fontWeight = if (on) FontWeight.Bold else FontWeight.Normal, + color = if (on) PulseColors.onAccent else PulseColors.textSecondary, + modifier = Modifier + .background(if (on) PulseColors.accent else PulseColors.cardSoft) + .selectable(selected = on, role = Role.RadioButton) { onChange(isYesterday) } + .padding(horizontal = 10.dp, vertical = 6.dp), + ) + } } } } 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 ee506d85..60bc9740 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/LogPastActivityScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/LogPastActivityScreen.kt @@ -5,6 +5,8 @@ import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape @@ -18,12 +20,14 @@ import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.Text +import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.* 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.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 @@ -65,7 +69,7 @@ fun LogPastActivityScreen(onBack: () -> Unit, onSaved: (String) -> Unit) { ) { item { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { - CircleIconButton(Icons.AutoMirrored.Filled.ArrowBack, tint = PulseColors.textSecondary, onTap = onBack) + CircleIconButton(Icons.AutoMirrored.Filled.ArrowBack, "Back", tint = PulseColors.textSecondary, onTap = onBack) Spacer(Modifier.width(12.dp)) Text("Log Past Activity", fontSize = 20.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) } @@ -165,7 +169,7 @@ private fun SectionLabel(text: String) { @Composable private fun ActivityTypeGrid(selectedType: String, onSelect: (String) -> Unit) { - Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + Column(Modifier.selectableGroup(), verticalArrangement = Arrangement.spacedBy(12.dp)) { ActivityMeta.ORDER.chunked(2).forEach { row -> Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { row.forEach { type -> @@ -185,7 +189,7 @@ private fun ActivityTypeButton(type: String, isSelected: Boolean, onSelect: (Str .clip(shape) .then(if (isSelected) Modifier.dither(PulseColors.accent, 0.18f) else Modifier.background(PulseColors.cardSoft)) .border(1.5.dp, if (isSelected) PulseColors.accent.copy(alpha = 0.9f) else Color.Transparent, shape) - .clickable { onSelect(type) } + .selectable(selected = isSelected, role = Role.RadioButton) { onSelect(type) } .padding(12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), @@ -228,14 +232,14 @@ private fun PastActivityDurationCard(minutes: Int, onChange: (Int) -> Unit) { verticalArrangement = Arrangement.spacedBy(16.dp), ) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { - DurationStepButton(Icons.Filled.Remove, enabled = !atFloor) { onChange(maxOf(5, minutes - 5)) } + DurationStepButton(Icons.Filled.Remove, "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("DURATION", fontSize = 10.sp, letterSpacing = 1.1.sp, color = PulseColors.textMuted) + Text("DURATION", fontSize = 11.sp, letterSpacing = 1.1.sp, color = PulseColors.textMuted) } - DurationStepButton(Icons.Filled.Add, enabled = true) { onChange(minutes + 5) } + DurationStepButton(Icons.Filled.Add, "Increase duration by 5 minutes", enabled = true) { onChange(minutes + 5) } } - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Row(Modifier.fillMaxWidth().selectableGroup(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { listOf(15, 30, 45, 60, 90).forEach { value -> val selected = minutes == value Text( @@ -244,11 +248,13 @@ private fun PastActivityDurationCard(minutes: Int, onChange: (Int) -> Unit) { color = if (selected) PulseColors.accent else PulseColors.textSecondary, modifier = Modifier .weight(1f) + // 34dp pill, 48dp touch target. + .minimumInteractiveComponentSize() .height(34.dp) .clip(CircleShape) .then(if (selected) Modifier.dither(PulseColors.accent, 0.18f) else Modifier.background(PulseColors.card)) .border(1.dp, if (selected) PulseColors.accent.copy(alpha = 0.9f) else Color.Transparent, CircleShape) - .clickable { onChange(value) } + .selectable(selected = selected, role = Role.RadioButton) { onChange(value) } .wrapContentHeight(), textAlign = androidx.compose.ui.text.style.TextAlign.Center, ) @@ -258,16 +264,21 @@ private fun PastActivityDurationCard(minutes: Int, onChange: (Int) -> Unit) { } @Composable -private fun DurationStepButton(icon: androidx.compose.ui.graphics.vector.ImageVector, enabled: Boolean, onTap: () -> Unit) { +private fun DurationStepButton( + icon: androidx.compose.ui.graphics.vector.ImageVector, + contentDescription: String, + enabled: Boolean, + onTap: () -> Unit, +) { Box( Modifier - .size(44.dp) + .size(48.dp) .clip(CircleShape) .background(PulseColors.card) - .then(if (enabled) Modifier.clickable(onClick = onTap) else Modifier), + .clickable(enabled = enabled, role = Role.Button, onClick = onTap), contentAlignment = Alignment.Center, ) { - Icon(icon, null, tint = if (enabled) PulseColors.textPrimary else PulseColors.textMuted) + Icon(icon, contentDescription, tint = if (enabled) PulseColors.textPrimary else PulseColors.textMuted) } } 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 0407e5c2..c57ce407 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt @@ -357,13 +357,14 @@ fun MealAnalysisDialog( Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Text( if (image == null) "OR DESCRIBE IT" else "ADD DETAIL (OPTIONAL)", - fontSize = 11.sp, + fontSize = 12.sp, letterSpacing = 1.4.sp, color = PulseColors.textMuted, ) OutlinedTextField( value = describeText, onValueChange = { describeText = it }, + label = { Text(if (image == null) "Describe your meal" else "Meal details") }, placeholder = { Text("e.g. two eggs, toast with butter, black coffee") }, modifier = Modifier.fillMaxWidth(), minLines = 2, diff --git a/app/src/main/java/com/pulseloop/ui/screens/MeasurementModal.kt b/app/src/main/java/com/pulseloop/ui/screens/MeasurementModal.kt deleted file mode 100644 index 8797e4b4..00000000 --- a/app/src/main/java/com/pulseloop/ui/screens/MeasurementModal.kt +++ /dev/null @@ -1,200 +0,0 @@ -package com.pulseloop.ui.screens - -import com.pulseloop.ui.theme.dither -import com.pulseloop.ui.theme.PulseColors -import androidx.compose.animation.core.* -import androidx.compose.foundation.Canvas -import androidx.compose.foundation.layout.* -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.* -import androidx.compose.runtime.* -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.graphics.drawscope.Stroke -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import com.pulseloop.data.PulseLoopDatabase -import com.pulseloop.data.entity.MeasurementEntity -import com.pulseloop.ring.MeasurementKind -import com.pulseloop.service.RingSyncCoordinator -import kotlinx.coroutines.delay - -private enum class MeasurePhase { PREPARING, MEASURING, RESULT, ERROR } - -/** - * Ported from MeasurementSheet / MeasurementModal.swift. - * Live measurement overlay for spot HR or SpO2 readings with ring animation. - */ -@Composable -fun MeasurementModal( - kind: MeasurementKind, - db: PulseLoopDatabase, - coordinator: RingSyncCoordinator?, - onDismiss: () -> Unit, -) { - val color = when (kind) { - MeasurementKind.HEART_RATE -> PulseColors.heartRate - MeasurementKind.SPO2 -> PulseColors.spo2 - else -> MaterialTheme.colorScheme.primary - } - val name = when (kind) { - MeasurementKind.HEART_RATE -> "Heart Rate" - MeasurementKind.SPO2 -> "Blood Oxygen" - else -> "Measurement" - } - val unit = when (kind) { - MeasurementKind.HEART_RATE -> "bpm" - MeasurementKind.SPO2 -> "%" - else -> "" - } - val instruction = when (kind) { - MeasurementKind.HEART_RATE -> "Keep your hand still and rest your wrist on a flat surface." - MeasurementKind.SPO2 -> "Breathe normally. Keep the sensor pressed firmly to your skin." - else -> "Stay still during the measurement." - } - - var phase by remember { mutableStateOf(MeasurePhase.PREPARING) } - var value by remember { mutableStateOf(null) } - - val infiniteTransition = rememberInfiniteTransition() - val scale by infiniteTransition.animateFloat( - initialValue = 0.85f, targetValue = 1.15f, - animationSpec = infiniteRepeatable( - animation = tween(1600, easing = LinearEasing), - repeatMode = RepeatMode.Restart, - ), - ) - - // Run measurement - LaunchedEffect(Unit) { - delay(1200) - phase = MeasurePhase.MEASURING - - val result: Int? = if (coordinator != null) { - try { - when (kind) { - MeasurementKind.HEART_RATE -> coordinator.measureHR() - MeasurementKind.SPO2 -> coordinator.measureSpO2() - else -> null - } - } catch (_: Exception) { null } - } else { - delay(if (kind == MeasurementKind.HEART_RATE) 2200 else 3000) - val mockValue = when (kind) { - MeasurementKind.HEART_RATE -> (62..86).random() - MeasurementKind.SPO2 -> (96..99).random() - else -> 0 - } - db.measurementDao().insert(MeasurementEntity( - kindRaw = kind.name, - value = mockValue.toDouble(), - unit = unit, - timestamp = System.currentTimeMillis(), - sourceRaw = "mock", - confidenceRaw = "known", - )) - mockValue - } - - if (result != null && result > 0) { - value = result - phase = MeasurePhase.RESULT - delay(1300) - onDismiss() - } else { - phase = MeasurePhase.ERROR - } - } - - Column( - modifier = Modifier.fillMaxSize().padding(24.dp), - horizontalAlignment = Alignment.CenterHorizontally, - ) { - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.Top) { - Column { - Text("MEASURING", style = MaterialTheme.typography.labelSmall, fontWeight = FontWeight.Medium, color = MaterialTheme.colorScheme.onSurfaceVariant) - Text(name, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) - } - TextButton(onClick = onDismiss) { - Text(if (phase == MeasurePhase.MEASURING) "Finish" else "Cancel") - } - } - - Spacer(Modifier.weight(1f)) - - if (phase == MeasurePhase.ERROR) { - Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(16.dp)) { - Surface(Modifier.size(80.dp).dither(PulseColors.heartRate, 0.1f, CircleShape), shape = CircleShape, color = Color.Transparent) { - Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { - Text("!", style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold, color = PulseColors.heartRate) - } - } - Text( - "Couldn't get a reading. Make sure the ring is snug and worn on your finger, then try again.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Button(onClick = onDismiss) { Text("Close") } - } - } else { - Box(contentAlignment = Alignment.Center, modifier = Modifier.size(240.dp)) { - repeat(3) { i -> - Canvas(Modifier.fillMaxSize()) { - val r = size.minDimension / 2 * 0.8f - drawCircle( - color = color.copy(alpha = 0.3f * (1f - i * 0.25f)), - radius = r, - style = Stroke(width = 2f), - ) - } - } - Surface(Modifier.size(220.dp).dither(color, 0.12f, CircleShape), shape = CircleShape, color = Color.Transparent) { - Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { - Column(horizontalAlignment = Alignment.CenterHorizontally) { - if (value != null && phase != MeasurePhase.PREPARING) { - Text("$value", style = MaterialTheme.typography.displaySmall, fontWeight = FontWeight.SemiBold) - Text(unit.uppercase(), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - } else { - Text( - if (phase == MeasurePhase.PREPARING) "READY" else "MEASURING", - style = MaterialTheme.typography.labelMedium, - fontWeight = FontWeight.Medium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - } - } - } - - Spacer(Modifier.height(24.dp)) - Text( - when (phase) { - MeasurePhase.PREPARING -> instruction - MeasurePhase.MEASURING -> if (kind == MeasurementKind.SPO2) "Measuring SpO₂… keep your hand still." else "Measuring… stay still." - MeasurePhase.RESULT -> "Reading saved." - MeasurePhase.ERROR -> "" - }, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - - Spacer(Modifier.weight(1f)) - - if (phase == MeasurePhase.RESULT) { - Surface( - Modifier.fillMaxWidth().padding(bottom = 28.dp).clip(RoundedCornerShape(8.dp)).dither(PulseColors.success, 0.1f), - color = Color.Transparent, - ) { - Text("Saved", Modifier.fillMaxWidth().padding(vertical = 14.dp), - style = MaterialTheme.typography.labelMedium, fontWeight = FontWeight.Medium, - color = PulseColors.success, textAlign = TextAlign.Center) - } - } - } -} 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 bc6f12a5..d79a4868 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt @@ -1,5 +1,9 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.components.rememberReduceMotion +import com.pulseloop.ui.components.switchRow +import androidx.activity.compose.BackHandler + import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.animateFloat @@ -13,6 +17,8 @@ import androidx.compose.foundation.clickable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll @@ -24,6 +30,7 @@ import androidx.compose.material3.IconButton import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Switch import androidx.compose.material3.Text +import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -36,6 +43,11 @@ import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.Role +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.unit.dp import androidx.compose.ui.unit.sp @@ -53,8 +65,11 @@ import com.pulseloop.service.Trends import com.pulseloop.service.VitalSample import com.pulseloop.ui.theme.PulseColors import com.pulseloop.ui.theme.dither +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.delay import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import kotlin.math.roundToInt /* @@ -115,8 +130,11 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit) { val context = LocalContext.current val db = remember { PulseLoopDatabase.getInstance(context) } var refresh by remember { mutableIntStateOf(0) } + // A failed load used to leave "Reading your history…" up forever. + var loadFailed by remember { mutableStateOf(false) } val snap by produceState(null, refresh) { - value = runCatching { HealthInsightsRepository.load(db) }.getOrNull() + loadFailed = false + value = runCatching { HealthInsightsRepository.load(db) }.onFailure { loadFailed = true }.getOrNull() } var restUntil by remember { mutableStateOf(RestMode.until(context)) } @@ -131,7 +149,10 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit) { ) { val s = snap if (s == null) { - Text("Reading your history…", color = PulseColors.textMuted, fontSize = 13.sp) + Text( + if (loadFailed) "Couldn't load your health history." else "Reading your history…", + color = if (loadFailed) PulseColors.warning else PulseColors.textMuted, fontSize = 13.sp, + ) } else { RadarSection(s.radar, restUntil) { days -> RestMode.set(context, days); restUntil = RestMode.until(context) @@ -186,7 +207,7 @@ private fun RadarSection(r: SymptomRadar.Result?, restUntil: java.time.LocalDate Text("Not a diagnosis. Rest, fluids and an easier day help; see a doctor if you feel unwell.", fontSize = 12.sp, color = PulseColors.textMuted) } } - Row(verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.switchRow(checked = restUntil != null, onCheckedChange = { on -> onRest(if (on) 3 else null) }), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text("Rest Mode", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text( @@ -195,7 +216,7 @@ private fun RadarSection(r: SymptomRadar.Result?, restUntil: java.time.LocalDate fontSize = 12.sp, color = PulseColors.textMuted, ) } - Switch(checked = restUntil != null, onCheckedChange = { on -> onRest(if (on) 3 else null) }) + Switch(checked = restUntil != null, onCheckedChange = null) } } } @@ -277,7 +298,11 @@ private fun Legend(color: Color, label: String) { @Composable fun HeartRateContextChart(samples: List, sleep: List, workouts: List) { val sorted = remember(samples) { samples.sortedBy { it.timestampMs } } - Canvas(Modifier.fillMaxWidth().height(90.dp)) { + val summary = remember(sorted) { + "Heart rate since last night: latest ${sorted.last().value.roundToInt()} bpm, " + + "range ${sorted.minOf { it.value }.roundToInt()}–${sorted.maxOf { it.value }.roundToInt()} bpm, ${sorted.size} readings" + } + Canvas(Modifier.fillMaxWidth().height(90.dp).semantics { contentDescription = summary }) { val t0 = sorted.first().timestampMs; val t1 = sorted.last().timestampMs.coerceAtLeast(t0 + 1) val lo = sorted.minOf { it.value } - 5; val hi = sorted.maxOf { it.value } + 5 fun x(t: Long) = (t - t0).toFloat() / (t1 - t0) * size.width @@ -314,39 +339,46 @@ private fun HabitsSection(h: HealthInsightsRepository.Habits) { private fun TrendsSection(db: PulseLoopDatabase) { var metric by remember { mutableStateOf(TrendMetric.SLEEP) } var period by remember { mutableStateOf(Trends.Period.WEEK) } + var trendFailed by remember { mutableStateOf(false) } val points by produceState?>(null, metric, period) { value = null - value = runCatching { Trends.aggregate(HealthInsightsRepository.daily(db, metric, period.days), period) }.getOrNull() + trendFailed = false + value = runCatching { Trends.aggregate(HealthInsightsRepository.daily(db, metric, period.days), period) } + .onFailure { trendFailed = true }.getOrNull() } Section("Trends") { - Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).selectableGroup(), horizontalArrangement = Arrangement.spacedBy(6.dp)) { TrendMetric.entries.forEach { m -> val on = m == metric Text(m.label, fontSize = 12.sp, color = if (on) PulseColors.onAccent else PulseColors.textSecondary, - modifier = Modifier.clip(RoundedCornerShape(16.dp)) + modifier = Modifier.minimumInteractiveComponentSize().clip(RoundedCornerShape(16.dp)) .background(if (on) PulseColors.accent else PulseColors.cardSoft) - .clickable { metric = m }.padding(horizontal = 10.dp, vertical = 6.dp)) + .selectable(selected = on, role = Role.Tab) { metric = m }.padding(horizontal = 10.dp, vertical = 6.dp)) } } - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Row(Modifier.fillMaxWidth().selectableGroup(), horizontalArrangement = Arrangement.spacedBy(6.dp)) { Trends.Period.entries.forEach { p -> val on = p == period Text(p.label, fontSize = 12.sp, color = if (on) PulseColors.textPrimary else PulseColors.textMuted, fontWeight = if (on) FontWeight.Bold else FontWeight.Normal, - modifier = Modifier.weight(1f).clip(RoundedCornerShape(4.dp)) + modifier = Modifier.weight(1f).minimumInteractiveComponentSize().clip(RoundedCornerShape(4.dp)) .then(if (on) Modifier.dither(PulseColors.accent, 0.18f) else Modifier) .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(4.dp)) - .clickable { period = p }.padding(vertical = 6.dp), + .selectable(selected = on, role = Role.Tab) { period = p }.padding(vertical = 6.dp), textAlign = androidx.compose.ui.text.style.TextAlign.Center) } } val pts = points when { + pts == null && trendFailed -> Text("Couldn't load ${metric.label.lowercase()} trends.", fontSize = 12.sp, color = PulseColors.warning) pts == null -> Text("Loading…", fontSize = 12.sp, color = PulseColors.textMuted) pts.size < 2 -> Text("Not enough ${metric.label.lowercase()} data for this view yet.", fontSize = 12.sp, color = PulseColors.textMuted) else -> { val shown = pts.takeLast(if (period == Trends.Period.DAY) 30 else 26) - Canvas(Modifier.fillMaxWidth().height(120.dp)) { + val fmt = if (metric == TrendMetric.TEMPERATURE || metric == TrendMetric.SLEEP || metric == TrendMetric.WEIGHT) "%.1f" else "%.0f" + val summary = "${metric.label} by ${period.label.lowercase()}: latest ${fmt.format(shown.last().value)} ${metric.unit}, " + + "range ${fmt.format(shown.minOf { it.value })}–${fmt.format(shown.maxOf { it.value })} ${metric.unit}, ${shown.size} points" + Canvas(Modifier.fillMaxWidth().height(120.dp).semantics { contentDescription = summary }) { val max = shown.maxOf { it.value }; val min = minOf(0.0, shown.minOf { it.value }) val lo = if (metric in setOf(TrendMetric.RESTING_HR, TrendMetric.HRV, TrendMetric.SPO2, TrendMetric.TEMPERATURE, TrendMetric.WEIGHT)) shown.minOf { it.value } * 0.95 else min @@ -358,7 +390,6 @@ private fun TrendsSection(db: PulseLoopDatabase) { } } val last = shown.last() - val fmt = if (metric == TrendMetric.TEMPERATURE || metric == TrendMetric.SLEEP || metric == TrendMetric.WEIGHT) "%.1f" else "%.0f" Text("Latest ${period.label.lowercase()}: ${fmt.format(last.value)} ${metric.unit} · average ${fmt.format(shown.map { it.value }.average())} ${metric.unit}", fontSize = 12.sp, color = PulseColors.textSecondary) } @@ -380,20 +411,31 @@ fun BreatheScreen(onBack: () -> Unit) { var minutes by remember { mutableIntStateOf(5) } var startedAt by remember { mutableStateOf(null) } var remaining by remember { mutableIntStateOf(0) } + var elapsedMs by remember { mutableLongStateOf(0L) } var result by remember { mutableStateOf(null) } + val reduceMotion = rememberReduceMotion() fun finish() { val s = startedAt ?: return startedAt = null - scope.launch { result = MindfulSessions.finish(context, db, s, System.currentTimeMillis()) } + val end = System.currentTimeMillis() + // Leaving the screen right after finish() disposes `scope`; the save must outlive it. + // UNDISPATCHED enters the NonCancellable block before any dispose can cancel the launch. + scope.launch(start = CoroutineStart.UNDISPATCHED) { + val saved = withContext(NonCancellable) { MindfulSessions.finish(context, db, s, end) } + result = saved + } } + BackHandler(enabled = startedAt != null) { finish(); onBack() } + LaunchedEffect(startedAt) { val s = startedAt ?: return@LaunchedEffect while (true) { - remaining = (minutes * 60 - ((System.currentTimeMillis() - s) / 1000)).toInt() + elapsedMs = System.currentTimeMillis() - s + remaining = (minutes * 60 - (elapsedMs / 1000)).toInt() if (remaining <= 0) { finish(); break } - delay(500) + delay(200) } } @@ -408,15 +450,24 @@ fun BreatheScreen(onBack: () -> Unit) { val r = result when { startedAt != null -> { - val t = rememberInfiniteTransition(label = "breath") - val s by t.animateFloat( - 0.55f, 1f, - infiniteRepeatable(keyframes { durationMillis = 10_000; 1f at 4_000 using FastOutSlowInEasing; 0.55f at 10_000 }, RepeatMode.Restart), - label = "scale", - ) + // Same 10 s cycle as the circle (in for the first 4 s, out for 6), counted from the + // session start so the cue and the circle agree. + val inhaling = elapsedMs % BREATH_CYCLE_MS < INHALE_MS + val s = if (reduceMotion) 0.8f else { + val t = rememberInfiniteTransition(label = "breath") + val animated by t.animateFloat( + 0.55f, 1f, + infiniteRepeatable(keyframes { durationMillis = BREATH_CYCLE_MS.toInt(); 1f at INHALE_MS.toInt() using FastOutSlowInEasing; 0.55f at BREATH_CYCLE_MS.toInt() }, RepeatMode.Restart), + label = "scale", + ) + animated + } Box(Modifier.size(220.dp).scale(s).clip(CircleShape).dither(PulseColors.accent, 0.35f, CircleShape).border(2.dp, PulseColors.accent, CircleShape)) Spacer(Modifier.height(24.dp)) - Text(if (s > 0.98f || remaining % 10 < 4) "Breathe in" else "Breathe out", fontSize = 18.sp, color = PulseColors.textPrimary) + Text( + if (inhaling) "Breathe in" else "Breathe out", fontSize = 18.sp, color = PulseColors.textPrimary, + modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite }, + ) Text("%d:%02d".format(remaining / 60, remaining % 60), fontSize = 28.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Spacer(Modifier.height(16.dp)) OutlinedButton(onClick = { finish() }) { Text("End session") } @@ -436,23 +487,26 @@ fun BreatheScreen(onBack: () -> Unit) { else -> { Text("Slow breathing: in for 4 seconds, out for 6.", fontSize = 15.sp, color = PulseColors.textSecondary) Spacer(Modifier.height(16.dp)) - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Row(Modifier.selectableGroup(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { listOf(1, 3, 5, 10).forEach { m -> val on = m == minutes Text("$m min", fontSize = 14.sp, color = if (on) PulseColors.onAccent else PulseColors.textPrimary, - modifier = Modifier.clip(RoundedCornerShape(16.dp)) + modifier = Modifier.minimumInteractiveComponentSize().clip(RoundedCornerShape(16.dp)) .background(if (on) PulseColors.accent else PulseColors.card) - .clickable { minutes = m }.padding(horizontal = 14.dp, vertical = 8.dp)) + .selectable(selected = on, role = Role.RadioButton) { minutes = m }.padding(horizontal = 14.dp, vertical = 8.dp)) } } Spacer(Modifier.height(24.dp)) - Button(onClick = { result = null; startedAt = System.currentTimeMillis() }) { Text("Start") } + Button(onClick = { result = null; elapsedMs = 0L; startedAt = System.currentTimeMillis() }) { Text("Start") } } } Spacer(Modifier.weight(1f)) } } +private const val BREATH_CYCLE_MS = 10_000L +private const val INHALE_MS = 4_000L + /** The way into [MyHealthScreen] from Vitals: one row, with Rest Mode shown while it is on. */ @Composable fun MyHealthEntryCard(onClick: () -> Unit) { 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 fa8dede4..1cd0ed19 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt @@ -1,6 +1,8 @@ package com.pulseloop.ui.screens import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape @@ -78,6 +80,7 @@ fun NutritionScreen( LaunchedEffect(dayOffset) { reload() } var showAddDialog by remember { mutableStateOf(false) } + var mealToDelete by remember { mutableStateOf(null) } var analysisRequest by remember { mutableStateOf(null) } // iOS gates the Photo/Describe pills on coach + cloud provider + a photo-analysis @@ -122,9 +125,9 @@ fun NutritionScreen( // Day navigation — left goes to older dates (higher offset), right goes to today (offset 0). item { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) { - IconButton(onClick = { dayOffset++ }) { Icon(Icons.Filled.ChevronLeft, "Previous") } + IconButton(onClick = { dayOffset++ }) { Icon(Icons.Filled.ChevronLeft, "Previous day") } Text(dateLabel, fontWeight = FontWeight.SemiBold, fontSize = 16.sp) - IconButton(onClick = { if (dayOffset > 0) dayOffset-- }, enabled = dayOffset > 0) { Icon(Icons.Filled.ChevronRight, "Next") } + IconButton(onClick = { if (dayOffset > 0) dayOffset-- }, enabled = dayOffset > 0) { Icon(Icons.Filled.ChevronRight, "Next day") } } } @@ -208,14 +211,8 @@ fun NutritionScreen( Text(meal.name, fontWeight = FontWeight.Medium) Text("${meal.calories.roundToInt()} kcal · P${meal.proteinG.roundToInt()} C${meal.carbsG.roundToInt()} F${meal.fatG.roundToInt()}", fontSize = 12.sp, color = PulseColors.textMuted) } - IconButton(onClick = { - scope.launch { - db.mealEntryDao().deleteById(meal.id) - com.pulseloop.service.DrinksRepository.onMealDeleted(db, meal.id) - reload() - } - }) { - Icon(Icons.Filled.Delete, "Delete", tint = PulseColors.danger, modifier = Modifier.size(18.dp)) + IconButton(onClick = { mealToDelete = meal }) { + Icon(Icons.Filled.Delete, "Delete ${meal.name}", tint = PulseColors.danger, modifier = Modifier.size(18.dp)) } } } @@ -262,6 +259,25 @@ fun NutritionScreen( } } + mealToDelete?.let { meal -> + AlertDialog( + onDismissRequest = { mealToDelete = null }, + title = { Text("Delete meal?") }, + text = { Text("\"${meal.name}\" will be removed from this day's log.") }, + confirmButton = { + TextButton(onClick = { + mealToDelete = null + scope.launch { + db.mealEntryDao().deleteById(meal.id) + com.pulseloop.service.DrinksRepository.onMealDeleted(db, meal.id) + reload() + } + }) { Text("Delete", color = PulseColors.danger) } + }, + dismissButton = { TextButton(onClick = { mealToDelete = null }) { Text("Cancel") } }, + ) + } + if (showAddDialog) { MealLogDialog( startWithScanner = startScanner, @@ -333,7 +349,7 @@ data class MealLogSave( private fun MacroBar(label: String, value: Double, goal: Double, color: Color) { val pct = if (goal > 0) (value / goal).coerceAtMost(1.0) else 0.0 Column(horizontalAlignment = Alignment.CenterHorizontally) { - Text(label, fontSize = 10.sp, color = PulseColors.textMuted) + Text(label, fontSize = 12.sp, color = PulseColors.textMuted) Text("${value.roundToInt()}g", fontSize = 13.sp, fontWeight = FontWeight.SemiBold) LinearProgressIndicator( progress = { pct.toFloat() }, @@ -343,6 +359,7 @@ private fun MacroBar(label: String, value: Double, goal: Double, color: Color) { } } +@OptIn(ExperimentalLayoutApi::class) @Composable fun MealLogDialog( onDismiss: () -> Unit, @@ -427,7 +444,8 @@ fun MealLogDialog( onDismissRequest = onDismiss, title = { Text("Log Meal") }, text = { - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + // Scrolls so the fields stay reachable on short screens and with the keyboard up. + Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) { Row( Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End, @@ -448,18 +466,18 @@ fun MealLogDialog( Text(it, fontSize = 12.sp, color = PulseColors.warning) } OutlinedTextField(value = name, onValueChange = { name = it }, label = { Text("Name") }, modifier = Modifier.fillMaxWidth(), maxLines = 3, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(capitalization = androidx.compose.ui.text.input.KeyboardCapitalization.Sentences)) - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + FlowRow(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { listOf("breakfast", "lunch", "dinner", "snack").forEach { t -> FilterChip(selected = type == t, onClick = { type = t }, label = { Text(t.replaceFirstChar { it.uppercase() }) }) } } Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - OutlinedTextField(value = cal, onValueChange = { cal = it }, label = { Text("kcal") }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) - OutlinedTextField(value = protein, onValueChange = { protein = it }, label = { Text("P(g)") }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) + OutlinedTextField(value = cal, onValueChange = { cal = decimalInput(it) ?: cal }, label = { Text("kcal", maxLines = 1) }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) + OutlinedTextField(value = protein, onValueChange = { protein = decimalInput(it) ?: protein }, label = { Text("Protein (g)", maxLines = 1) }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) } Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - OutlinedTextField(value = carbs, onValueChange = { carbs = it }, label = { Text("C(g)") }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) - OutlinedTextField(value = fat, onValueChange = { fat = it }, label = { Text("F(g)") }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) + OutlinedTextField(value = carbs, onValueChange = { carbs = decimalInput(it) ?: carbs }, label = { Text("Carbs (g)", maxLines = 1) }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) + OutlinedTextField(value = fat, onValueChange = { fat = decimalInput(it) ?: fat }, label = { Text("Fat (g)", maxLines = 1) }, modifier = Modifier.weight(1f), singleLine = true, keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal)) } } }, @@ -512,6 +530,12 @@ fun MealLogDialog( } } +/** Keeps a numeric field to digits and one decimal point (comma accepted), as MealAnalysisSheet's NumberField does; null rejects the edit. */ +private fun decimalInput(raw: String): String? { + val cleaned = raw.replace(',', '.').filter { it.isDigit() || it == '.' } + return if (cleaned.count { it == '.' } <= 1) cleaned else null +} + /** * A scanned-and-resolved OFF product held until Save — carries the prefill snapshot so * post-prefill edits can flip userEdited, and the provenance fields the row records. 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 0d96372c..68a3be92 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/OnboardingScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/OnboardingScreen.kt @@ -3,8 +3,12 @@ package com.pulseloop.ui.screens import com.pulseloop.ui.theme.dither import android.Manifest import android.content.Context +import android.content.Intent import android.content.pm.PackageManager +import android.net.Uri import android.os.Build +import android.provider.Settings +import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedContent @@ -52,6 +56,9 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign @@ -112,6 +119,9 @@ fun OnboardingScreen( progressStore.savePath(path) } + // System back walks the step stack before it leaves the flow. + BackHandler(enabled = path.size > 1) { goBack() } + fun finish() { scope.launch { val profile = db.userProfileDao().get() ?: UserProfileEntity() @@ -129,6 +139,8 @@ fun OnboardingScreen( } // BLE permissions gate on "Get started" (preserved from the previous onboarding screen). + // A denial used to leave the button silently doing nothing; it now explains and offers a way out. + var blePermissionDenied by remember { mutableStateOf(false) } val blePermissions = remember { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT) @@ -139,7 +151,12 @@ fun OnboardingScreen( val permissionLauncher = rememberLauncherForActivityResult( ActivityResultContracts.RequestMultiplePermissions(), ) { results -> - if (blePermissions.all { results[it] == true }) push(OnboardingStep.RING) + if (blePermissions.all { results[it] == true }) { + blePermissionDenied = false + push(OnboardingStep.RING) + } else { + blePermissionDenied = true + } } fun getStarted() { @@ -178,6 +195,14 @@ fun OnboardingScreen( OnboardingStep.WELCOME -> WelcomeStep( getStarted = ::getStarted, exploreWithoutRing = { push(OnboardingStep.PROFILE) }, + permissionDenied = blePermissionDenied, + openAppSettings = { + context.startActivity( + Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) + .setData(Uri.fromParts("package", context.packageName, null)) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + ) + }, ) OnboardingStep.RING -> PairingScreen( bleClient = bleClient, @@ -282,7 +307,12 @@ private data class WelcomeFeature( ) @Composable -private fun WelcomeStep(getStarted: () -> Unit, exploreWithoutRing: () -> Unit) { +private fun WelcomeStep( + getStarted: () -> Unit, + exploreWithoutRing: () -> Unit, + permissionDenied: Boolean = false, + openAppSettings: () -> Unit = {}, +) { val features = listOf( WelcomeFeature(Icons.Filled.Paid, "No subscription", "Own your ring data", PulseColors.success), WelcomeFeature(Icons.Filled.Lock, "Privacy first", "Data stays on device", PulseColors.info), @@ -295,8 +325,24 @@ private fun WelcomeStep(getStarted: () -> Unit, exploreWithoutRing: () -> Unit) StepScaffold( footer = { Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { - PrimaryButton("Get started", icon = Icons.Filled.ArrowForward, onClick = getStarted) - SecondaryButton("Explore without ring", icon = Icons.Filled.GridView, onClick = exploreWithoutRing) + if (permissionDenied) { + Text( + "PulseLoop needs Bluetooth permission to find and connect to your ring. " + + "Allow it in Settings, or continue without a ring and pair one later.", + fontSize = 13.sp, + color = PulseColors.textSecondary, + textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth().semantics { liveRegion = LiveRegionMode.Polite }, + ) + // "Try again" re-checks the grant first, so it also carries on after the user + // allowed Bluetooth in Settings; without it a denial had no way back to pairing. + PrimaryButton("Try again", icon = Icons.Filled.ArrowForward, onClick = getStarted) + SecondaryButton("Open settings", onClick = openAppSettings) + SecondaryButton("Continue without ring", icon = Icons.Filled.GridView, onClick = exploreWithoutRing) + } else { + PrimaryButton("Get started", icon = Icons.Filled.ArrowForward, onClick = getStarted) + SecondaryButton("Explore without ring", icon = Icons.Filled.GridView, onClick = exploreWithoutRing) + } } }, ) { 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 2c4dc816..25b445e9 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/PairingScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/PairingScreen.kt @@ -1,6 +1,14 @@ package com.pulseloop.ui.screens +import android.Manifest +import android.app.Activity +import android.content.Context +import android.content.ContextWrapper import android.content.Intent +import android.net.Uri +import android.os.Build +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.core.Spring import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.spring @@ -10,6 +18,8 @@ import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.rememberPagerState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape @@ -37,10 +47,15 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.scale import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import androidx.core.app.ActivityCompat import com.pulseloop.ring.RingBLEClient import com.pulseloop.ring.RingConnectionState import com.pulseloop.ring.ringModelLabel @@ -79,13 +94,53 @@ fun PairingScreen( // The adapter flag isn't part of BLEState until a scan attempt, so poll it directly. var btReady by remember { mutableStateOf(bleClient.isBluetoothEnabled) } + // Polled with the adapter so a grant made in system Settings is picked up on return. + var hasBlePermissions by remember { mutableStateOf(bleClient.hasPermissions()) } LaunchedEffect(Unit) { while (true) { btReady = bleClient.isBluetoothEnabled + hasBlePermissions = bleClient.hasPermissions() delay(1000) } } + // Scanning needs the runtime BLE permissions; ask for them here rather than letting the + // scan fail with a raw "permissions not granted" error. Same per-SDK list as onboarding. + val blePermissions = remember { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT) + } else { + arrayOf(Manifest.permission.ACCESS_FINE_LOCATION) + } + } + var permissionDenied by remember { mutableStateOf(false) } + var permissionPermanentlyDenied by remember { mutableStateOf(false) } + val permissionLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.RequestMultiplePermissions(), + ) { results -> + if (blePermissions.all { results[it] == true }) { + hasBlePermissions = true + permissionDenied = false + isLooking = true + bleClient.startScanning() + } else { + permissionDenied = true + // No rationale after a denial means the system won't show the dialog again. + val activity = context.findActivity() + permissionPermanentlyDenied = activity != null && blePermissions.none { + ActivityCompat.shouldShowRequestPermissionRationale(activity, it) + } + } + } + fun startLooking() { + if (bleClient.hasPermissions()) { + isLooking = true + bleClient.startScanning() + } else { + permissionLauncher.launch(blePermissions) + } + } + val allModels = WearableModel.CATALOG // "All" first, then each distinct brand alphabetically (case-insensitive). val brands = remember(allModels) { @@ -164,6 +219,11 @@ fun PairingScreen( if (!btReady) { BluetoothOffCard() + } else if (!hasBlePermissions && permissionDenied && !connected) { + BluetoothPermissionCard( + permanentlyDenied = permissionPermanentlyDenied, + onRequest = { permissionLauncher.launch(blePermissions) }, + ) } else if (connected) { ConnectedCard( model = WearableModel.model(state.activeWearableModelID) ?: selectedModel, @@ -196,7 +256,8 @@ fun PairingScreen( } } - if (state.lastError != null && !connected) { + // The permission card explains a missing grant; don't also show the raw scan error. + if (state.lastError != null && !connected && hasBlePermissions) { Text( state.lastError ?: "", fontSize = 12.sp, @@ -211,7 +272,11 @@ fun PairingScreen( if (showDiagnostics) "Hide connection details" else "Show connection details", fontSize = 12.sp, color = PulseColors.textSecondary, - modifier = Modifier.clickable { showDiagnostics = !showDiagnostics }, + modifier = Modifier + .heightIn(min = 48.dp) + .clickable(role = Role.Button) { showDiagnostics = !showDiagnostics } + .wrapContentHeight() + .padding(horizontal = 8.dp), ) } } @@ -252,10 +317,7 @@ fun PairingScreen( horizontalAlignment = Alignment.CenterHorizontally, ) { if (!isLooking && btReady) { - PrimaryButton("Connect ring", icon = Icons.Filled.Sensors) { - isLooking = true - bleClient.startScanning() - } + PrimaryButton("Connect ring", icon = Icons.Filled.Sensors) { startLooking() } if (bleClient.hasLastKnownRing && state.connectionState != RingConnectionState.RECONNECTING ) { @@ -327,6 +389,7 @@ private fun BrandTabs( // fits the supported labels on narrow phones and naturally grows as models are added. brands.chunked(3).forEach { rowBrands -> Row( + Modifier.selectableGroup(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally), verticalAlignment = Alignment.CenterVertically, ) { @@ -334,8 +397,8 @@ private fun BrandTabs( val isSelected = brand == selectedBrand Box( Modifier - .heightIn(min = 44.dp) - .clickable { onSelect(brand) }, + .heightIn(min = 48.dp) + .selectable(selected = isSelected, role = Role.Tab) { onSelect(brand) }, contentAlignment = Alignment.Center, ) { Text( @@ -396,16 +459,20 @@ private fun ModelCarousel( // Fixed-height tappable dot row keeps layout stable across brand tabs. Row( - Modifier.height(44.dp), + Modifier.height(48.dp), verticalAlignment = Alignment.CenterVertically, ) { if (models.size > 1) { - models.forEachIndexed { index, _ -> + models.forEachIndexed { index, model -> val isSelected = pagerState.currentPage == index Box( Modifier - .size(width = 32.dp, height = 44.dp) - .clickable { scope.launch { pagerState.animateScrollToPage(index) } }, + .size(width = 32.dp, height = 48.dp) + .clickable { scope.launch { pagerState.animateScrollToPage(index) } } + .semantics { + contentDescription = "${model.displayName}, ${index + 1} of ${models.size}" + selected = isSelected + }, contentAlignment = Alignment.Center, ) { Box( @@ -631,7 +698,7 @@ private fun BluetoothOffCard() { Text( "Turn on Bluetooth to find and connect your ring.", fontSize = 14.sp, - color = PulseColors.textMuted, + color = PulseColors.textSecondary, textAlign = TextAlign.Center, ) SecondaryButton("Open Settings", icon = Icons.Filled.Settings) { @@ -643,3 +710,68 @@ private fun BluetoothOffCard() { } } } + +/** Shown after the BLE permission request is denied; styled like [BluetoothOffCard]. */ +@Composable +private fun BluetoothPermissionCard(permanentlyDenied: Boolean, onRequest: () -> Unit) { + val context = LocalContext.current + Column( + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(8.dp)) + .background(PulseColors.card) + .padding(horizontal = 20.dp, vertical = 32.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(14.dp), + ) { + Icon( + Icons.Filled.BluetoothDisabled, + contentDescription = null, + modifier = Modifier.size(34.dp), + tint = PulseColors.textMuted, + ) + Text( + "Bluetooth access needed", + fontSize = 17.sp, + fontWeight = FontWeight.SemiBold, + color = PulseColors.textPrimary, + ) + Text( + if (permanentlyDenied) { + "PulseLoop uses Bluetooth to find and connect your ring. " + + "Allow " + + (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) "\"Nearby devices\"" else "Location") + + " for PulseLoop in Settings." + } else { + "PulseLoop uses Bluetooth to find and connect your ring. " + + "Nothing is shared off your phone." + }, + fontSize = 14.sp, + color = PulseColors.textSecondary, + textAlign = TextAlign.Center, + ) + if (permanentlyDenied) { + SecondaryButton("Open Settings", icon = Icons.Filled.Settings) { + try { + context.startActivity( + Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS) + .setData(Uri.fromParts("package", context.packageName, null)), + ) + } catch (_: Exception) { + // No app-details settings activity on this device — nothing to open. + } + } + } else { + SecondaryButton("Allow Bluetooth access", icon = Icons.Filled.Bluetooth, onClick = onRequest) + } + } +} + +private fun Context.findActivity(): Activity? { + var current: Context? = this + while (current is ContextWrapper) { + if (current is Activity) return current + current = current.baseContext + } + return null +} 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 b78c1046..c5ae4502 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt @@ -9,7 +9,7 @@ import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.ArrowBack +import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme @@ -23,6 +23,13 @@ import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.semantics.ProgressBarRangeInfo +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.progressBarRangeInfo +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Dp @@ -69,7 +76,14 @@ fun ScoreRing( centerText: String = value?.toString() ?: "—", centerSize: Int = 22, ) { - Box(Modifier.size(size), contentAlignment = Alignment.Center) { + Box( + Modifier.size(size).clearAndSetSemantics { + // One spoken value instead of a bare number; an empty ring says so. + contentDescription = value?.let { "Score $it out of 100" } ?: "No score" + if (value != null) progressBarRangeInfo = ProgressBarRangeInfo(value.coerceIn(0, 100).toFloat(), 0f..100f) + }, + contentAlignment = Alignment.Center, + ) { Canvas(Modifier.fillMaxSize()) { val w = stroke.toPx() val inset = w / 2 @@ -195,7 +209,7 @@ fun ReadinessScreen(db: PulseLoopDatabase, onBack: () -> Unit) { Column(Modifier.fillMaxSize()) { Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { - Icon(Icons.Filled.ArrowBack, "Back") + Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } Text( "Readiness", modifier = Modifier.align(Alignment.Center), @@ -273,7 +287,10 @@ fun ContributorsCard(contributors: List, title: String = "Cont @Composable private fun ContributorRow(c: ScoreContributor, expanded: Boolean, onTap: () -> Unit) { Column( - Modifier.fillMaxWidth().clickable(onClick = onTap).padding(horizontal = 16.dp, vertical = 12.dp), + Modifier.fillMaxWidth() + .clickable(role = Role.Button, onClick = onTap) + .semantics { stateDescription = if (expanded) "Expanded" else "Collapsed" } + .padding(horizontal = 16.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(6.dp), ) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { @@ -304,7 +321,7 @@ fun ActivityScoreScreen(db: PulseLoopDatabase, onBack: () -> Unit, onOpenActivit Column(Modifier.fillMaxSize()) { Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { - Icon(Icons.Filled.ArrowBack, "Back") + Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } Text( "Activity", modifier = Modifier.align(Alignment.Center), diff --git a/app/src/main/java/com/pulseloop/ui/screens/RecordScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/RecordScreen.kt index e50a399d..6fd35540 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/RecordScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/RecordScreen.kt @@ -1,6 +1,7 @@ package com.pulseloop.ui.screens 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 @@ -54,6 +55,24 @@ fun RecordScreen( ?.let { it + ActivityMeta.paceUnit(units) } ?: "—" } + // System back used to pop this screen while the workout kept recording, with no way back to + // it. Ask instead: keep going, or finish (which lands on the summary). + var showLeaveDialog by remember { mutableStateOf(false) } + BackHandler { showLeaveDialog = true } + if (showLeaveDialog) { + AlertDialog( + onDismissRequest = { showLeaveDialog = false }, + title = { Text("Workout in progress") }, + text = { Text("Your workout is still recording. Finish it now, or keep recording?") }, + confirmButton = { + TextButton(onClick = { showLeaveDialog = false; onFinish() }) { Text("Finish") } + }, + dismissButton = { + TextButton(onClick = { showLeaveDialog = false }) { Text("Keep recording") } + }, + ) + } + Column(Modifier.fillMaxSize().padding(16.dp)) { // Activity name + status Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { @@ -109,19 +128,19 @@ fun RecordScreen( Row(Modifier.fillMaxWidth().padding(bottom = 16.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) { if (isPaused) { Button(onClick = onResume, Modifier.weight(1f).height(52.dp)) { - Icon(Icons.Filled.PlayArrow, "Resume") + Icon(Icons.Filled.PlayArrow, null) Spacer(Modifier.width(8.dp)) Text("Resume") } } else { OutlinedButton(onClick = onPause, Modifier.weight(1f).height(52.dp)) { - Icon(Icons.Filled.Pause, "Pause") + Icon(Icons.Filled.Pause, null) Spacer(Modifier.width(8.dp)) Text("Pause") } } Button(onClick = onFinish, Modifier.weight(1f).height(52.dp), colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error)) { - Icon(Icons.Filled.Stop, "Finish") + Icon(Icons.Filled.Stop, null) Spacer(Modifier.width(8.dp)) Text("Finish") } 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 137cd064..12ca5d04 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/Screens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/Screens.kt @@ -10,7 +10,10 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.* import androidx.compose.material3.* import androidx.compose.runtime.* @@ -18,6 +21,11 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @@ -148,6 +156,7 @@ fun VitalsScreen( ZoneLineChart( samples = c.samples, zones = c.zones, yDomain = c.yDomain, accent = ZonePalette.accent(MetricKind.HEART_RATE), + label = "Heart rate", referenceBands = c.referenceBands, dashedRules = c.dashedRules, ) } else { @@ -163,6 +172,7 @@ fun VitalsScreen( ZoneLineChart( samples = c.samples, zones = c.zones, yDomain = c.yDomain, accent = ZonePalette.accent(MetricKind.SPO2), + label = "Blood oxygen", referenceBands = c.referenceBands, dashedRules = c.dashedRules, showPoints = true, ) @@ -210,6 +220,7 @@ fun VitalsScreen( ZoneLineChart( samples = c.samples, zones = c.zones, yDomain = c.yDomain, accent = ZonePalette.accent(MetricKind.HRV), + label = "HRV", referenceBands = c.referenceBands, dashedRules = c.dashedRules, ) } else { @@ -252,6 +263,7 @@ fun VitalsScreen( ZoneLineChart( samples = c.samples, zones = c.zones, yDomain = c.yDomain, accent = ZonePalette.accent(MetricKind.TEMPERATURE), + label = "Temperature", referenceBands = c.referenceBands, dashedRules = c.dashedRules, ) } else { @@ -480,7 +492,7 @@ fun VitalsScreen( measureCaption, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(top = 4.dp), + modifier = Modifier.padding(top = 4.dp).semantics { liveRegion = LiveRegionMode.Polite }, ) } if (measureFailed && !measuring) { @@ -498,7 +510,7 @@ fun VitalsScreen( }, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error, - modifier = Modifier.padding(top = 4.dp), + modifier = Modifier.padding(top = 4.dp).semantics { liveRegion = LiveRegionMode.Polite }, ) } Spacer(Modifier.height(8.dp)) @@ -657,7 +669,7 @@ fun VitalDetailScreen( // edge, title centered. Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { - Icon(Icons.Filled.ArrowBack, "Back") + Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } Text( title, @@ -712,7 +724,7 @@ fun VitalDetailScreen( color = PulseColors.textMuted, ) Row(verticalAlignment = Alignment.CenterVertically) { - IconButton(onClick = { vm.prev() }, modifier = Modifier.size(28.dp)) { + IconButton(onClick = { vm.prev() }) { Icon(Icons.Filled.ChevronLeft, "Previous", tint = PulseColors.textMuted) } Text( @@ -724,7 +736,6 @@ fun VitalDetailScreen( IconButton( onClick = { vm.next() }, enabled = vm.canGoForward(), - modifier = Modifier.size(28.dp), ) { Icon( Icons.Filled.ChevronRight, "Next", @@ -763,6 +774,7 @@ fun VitalDetailScreen( // The whole calendar period, gaps included (issue #102). timeDomain = state.windowStart to state.windowEnd, usualRange = state.usualRange, + title = title, ) if (state.usualRange != null) { Text( @@ -964,7 +976,11 @@ private fun ReadingsCard( Row( Modifier .fillMaxWidth() - .clickable { expanded = !expanded } + .clickable( + role = Role.Button, + onClickLabel = if (expanded) "Hide readings" else "Show readings", + ) { expanded = !expanded } + .semantics { stateDescription = if (expanded) "Expanded" else "Collapsed" } .padding(16.dp), verticalAlignment = Alignment.CenterVertically, ) { @@ -984,7 +1000,7 @@ private fun ReadingsCard( ) Icon( if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, - contentDescription = if (expanded) "Hide readings" else "Show readings", + contentDescription = null, tint = PulseColors.textMuted, modifier = Modifier.size(20.dp), ) @@ -1017,10 +1033,7 @@ private fun ReadingsCard( color = PulseColors.textMuted, ) } - IconButton( - onClick = { pendingDelete = reading }, - modifier = Modifier.size(36.dp), - ) { + IconButton(onClick = { pendingDelete = reading }) { Icon( Icons.Filled.DeleteOutline, contentDescription = "Delete this reading", @@ -1086,16 +1099,18 @@ private fun PeriodSegmentedControl(selected: Period, onSelect: (Period) -> Unit) .fillMaxWidth() .clip(RoundedCornerShape(4.dp)) .background(PulseColors.cardSoft) - .padding(2.dp), + .padding(2.dp) + .selectableGroup(), ) { Period.entries.forEach { p -> val isSelected = selected == p Box( Modifier .weight(1f) + .heightIn(min = 48.dp) .clip(RoundedCornerShape(4.dp)) .then(if (isSelected) Modifier.dither(PulseColors.textPrimary, 0.16f) else Modifier) - .clickable { onSelect(p) } + .selectable(selected = isSelected, role = Role.Tab) { onSelect(p) } .padding(vertical = 7.dp), contentAlignment = Alignment.Center, ) { 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 7119d8e1..3dda8893 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.components.switchRow + import com.pulseloop.ui.theme.dither import android.Manifest import android.content.Context @@ -35,6 +37,9 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType @@ -125,7 +130,8 @@ private fun SettingsSubScreen( ) { padding -> Box(Modifier.fillMaxSize().padding(padding)) { Column( - Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), + // imePadding: the app is edge-to-edge, so without it the keyboard covers fields. + Modifier.fillMaxSize().imePadding().verticalScroll(rememberScrollState()).padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp), ) { content() @@ -161,6 +167,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { var liveMeasurements by remember { mutableStateOf(keyStore.liveMeasurementsEnabled) } var environmentContext by remember { mutableStateOf(keyStore.enableEnvironmentContext) } var showMemory by remember { mutableStateOf(false) } + var memoryToDelete by remember { mutableStateOf(null) } // Location & weather (iOS #65d) — opt-in, requests ACCESS_COARSE_LOCATION only when // the user turns it on, mirroring CoachEnvironmentContextService.requestPermissionIfNeeded(). @@ -232,9 +239,8 @@ fun CoachSettingsScreen(onBack: () -> Unit) { Spacer(Modifier.height(12.dp)) // Master toggle - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text("Enable AI Coach") - Switch(checked = coachEnabled, onCheckedChange = { enabled -> + Row(Modifier.fillMaxWidth() + .switchRow(checked = coachEnabled, onCheckedChange = { enabled -> coachEnabled = enabled; keyStore.coachEnabled = enabled if (!enabled) { CoachNotifications.cancel(context) @@ -245,7 +251,9 @@ fun CoachSettingsScreen(onBack: () -> Unit) { // on "Enable") — iOS #49. askEnableCheckIns = true } - }) + }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { + Text("Enable AI Coach") + Switch(checked = coachEnabled, onCheckedChange = null) } if (checkInPermissionDenied) { @@ -354,7 +362,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { IconButton(onClick = onVisibility) { Icon( if (visible) Icons.Filled.VisibilityOff else Icons.Filled.Visibility, - contentDescription = "Toggle visibility" + contentDescription = if (visible) "Hide key" else "Show key" ) } }, @@ -443,12 +451,13 @@ fun CoachSettingsScreen(onBack: () -> Unit) { onRemove = { orKey = ""; providerStore.openRouterApiKey = ""; keySaves++ }, ) Spacer(Modifier.height(8.dp)) - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.fillMaxWidth() + .switchRow(checked = orPrivacy, onCheckedChange = { orPrivacy = it; providerStore.orPrivacyRouting = it }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text("Privacy routing") Text("Only providers that don't retain data", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } - Switch(checked = orPrivacy, onCheckedChange = { orPrivacy = it; providerStore.orPrivacyRouting = it }) + Switch(checked = orPrivacy, onCheckedChange = null) } ModelDropdown( "Route by", orSort ?: "auto", @@ -625,7 +634,10 @@ fun CoachSettingsScreen(onBack: () -> Unit) { ) Spacer(Modifier.height(8.dp)) - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.fillMaxWidth() + .switchRow(checked = localToolCalling, onCheckedChange = { + localToolCalling = it; providerStore.localToolCalling = it + }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text("Tool calling") Text( @@ -635,9 +647,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { color = MaterialTheme.colorScheme.onSurfaceVariant, ) } - Switch(checked = localToolCalling, onCheckedChange = { - localToolCalling = it; providerStore.localToolCalling = it - }) + Switch(checked = localToolCalling, onCheckedChange = null) } Spacer(Modifier.height(8.dp)) @@ -745,12 +755,13 @@ fun CoachSettingsScreen(onBack: () -> Unit) { } // Image attachments (iOS #31): gates the attach button in the coach chat. - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.fillMaxWidth() + .switchRow(checked = imageInput, onCheckedChange = { imageInput = it; providerStore.imageInputEnabled = it }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text("Image attachments") Text("Attach photos to coach messages", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } - Switch(checked = imageInput, onCheckedChange = { imageInput = it; providerStore.imageInputEnabled = it }) + Switch(checked = imageInput, onCheckedChange = null) } HorizontalDivider() @@ -760,40 +771,44 @@ fun CoachSettingsScreen(onBack: () -> Unit) { // tool anyway — this is the UI half). if (providerMode != CoachProviderMode.USER_MINIMAX_KEY && providerMode != CoachProviderMode.LOCAL_OPENAI_COMPAT) { - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.fillMaxWidth() + .switchRow(checked = webSearch, onCheckedChange = { + webSearch = it; keyStore.webSearchEnabled = it + }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text("Web Search") Text("Uses additional tokens", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } - Switch(checked = webSearch, onCheckedChange = { - webSearch = it; keyStore.webSearchEnabled = it - }) + Switch(checked = webSearch, onCheckedChange = null) } } - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.fillMaxWidth() + .switchRow(checked = writeTools, onCheckedChange = { + writeTools = it; keyStore.writeToolsEnabled = it + }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text("Write Actions") Text("Set goals, log, edit data", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } - Switch(checked = writeTools, onCheckedChange = { - writeTools = it; keyStore.writeToolsEnabled = it - }) + Switch(checked = writeTools, onCheckedChange = null) } - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.fillMaxWidth() + .switchRow(checked = liveMeasurements, onCheckedChange = { + liveMeasurements = it; keyStore.liveMeasurementsEnabled = it + }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text("Live Measurements") Text("Trigger real-time ring readings", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } - Switch(checked = liveMeasurements, onCheckedChange = { - liveMeasurements = it; keyStore.liveMeasurementsEnabled = it - }) + Switch(checked = liveMeasurements, onCheckedChange = null) } - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.fillMaxWidth() + .switchRow(checked = environmentContext, onCheckedChange = { setEnvironmentContext(it) }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text("Use location & weather") Text("Grounds suggestions in your city's current weather", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } - Switch(checked = environmentContext, onCheckedChange = { setEnvironmentContext(it) }) + Switch(checked = environmentContext, onCheckedChange = null) } } } @@ -821,10 +836,8 @@ fun CoachSettingsScreen(onBack: () -> Unit) { Text(memory.key, style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Medium) Text(memory.value, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 2) } - IconButton(onClick = { - scope.launch { db.coachMemoryDao().deleteByKey(memory.key) } - }) { - Icon(Icons.Filled.Delete, "Delete", tint = MaterialTheme.colorScheme.error) + IconButton(onClick = { memoryToDelete = memory.key }) { + Icon(Icons.Filled.Delete, "Delete ${memory.key}", tint = MaterialTheme.colorScheme.error) } } } @@ -835,6 +848,23 @@ fun CoachSettingsScreen(onBack: () -> Unit) { } } + memoryToDelete?.let { key -> + AlertDialog( + onDismissRequest = { memoryToDelete = null }, + title = { Text("Delete memory?") }, + text = { Text("The coach will forget \"$key\". This can't be undone.") }, + confirmButton = { + TextButton(onClick = { + memoryToDelete = null + scope.launch { db.coachMemoryDao().deleteByKey(key) } + }) { Text("Delete", color = MaterialTheme.colorScheme.error) } + }, + dismissButton = { + TextButton(onClick = { memoryToDelete = null }) { Text("Cancel") } + }, + ) + } + if (askEnableCheckIns) { AlertDialog( onDismissRequest = { askEnableCheckIns = false }, @@ -941,13 +971,10 @@ fun CheckInsSettingsScreen(onBack: () -> Unit) { Text("Daily check-ins", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(12.dp)) - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.fillMaxWidth() + .switchRow(checked = notificationEnabled, enabled = coachEnabled, onCheckedChange = { setNotifications(it) }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Text("Daily Check-in Notifications") - Switch( - enabled = coachEnabled, - checked = notificationEnabled, - onCheckedChange = { setNotifications(it) }, - ) + Switch(checked = notificationEnabled, enabled = coachEnabled, onCheckedChange = null) } if (notifPermissionDenied) { @@ -1032,12 +1059,10 @@ fun CheckInsSettingsScreen(onBack: () -> Unit) { color = MaterialTheme.colorScheme.onSurfaceVariant, ) Spacer(Modifier.height(12.dp)) - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.fillMaxWidth() + .switchRow(checked = batteryAlertsEnabled, onCheckedChange = { setBatteryAlerts(it) }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Text("Low Battery Notifications") - Switch( - checked = batteryAlertsEnabled, - onCheckedChange = { setBatteryAlerts(it) }, - ) + Switch(checked = batteryAlertsEnabled, onCheckedChange = null) } if (batteryPermDenied) { Text( @@ -1118,13 +1143,13 @@ private fun DailyGuidanceSettingsCard() { @Composable private fun GuidanceSwitch(title: String, subtitle: String, checked: Boolean, onChange: (Boolean) -> Unit) { - Row(verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.switchRow(checked = checked, onCheckedChange = onChange), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text(title, style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Medium) Text(subtitle, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } Spacer(Modifier.width(12.dp)) - Switch(checked = checked, onCheckedChange = onChange) + Switch(checked = checked, onCheckedChange = null) } } @@ -1261,9 +1286,9 @@ fun PhysiologySettingsScreen(onBack: () -> Unit) { title = "Fitness", footer = "Treats a low resting heart rate as a sign of fitness rather than a concern, and relaxes the low-HR threshold.", ) { - Row(verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.switchRow(checked = athleteMode, onCheckedChange = { athleteMode = it; savedMsg = null }), verticalAlignment = Alignment.CenterVertically) { Text("Athlete mode", style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f)) - Switch(checked = athleteMode, onCheckedChange = { athleteMode = it; savedMsg = null }) + Switch(checked = athleteMode, onCheckedChange = null) } } @@ -1617,9 +1642,10 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U @Composable fun VitalToggle(label: String, checked: Boolean, onChange: (Boolean) -> Unit) { - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.fillMaxWidth() + .switchRow(checked = checked, enabled = cfgLoaded, onCheckedChange = { onChange(it); cfgSavedMsg = null }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Text(label) - Switch(enabled = cfgLoaded, checked = checked, onCheckedChange = { onChange(it); cfgSavedMsg = null }) + Switch(checked = checked, enabled = cfgLoaded, onCheckedChange = null) } } @@ -1772,12 +1798,13 @@ private fun QuietHoursCard() { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { Row( - Modifier.fillMaxWidth(), + Modifier.fillMaxWidth() + .switchRow(checked = enabled, onCheckedChange = { enabled = it; prefs.enabled = it }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, ) { Text("Sleep quiet hours", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) - Switch(checked = enabled, onCheckedChange = { enabled = it; prefs.enabled = it }) + Switch(checked = enabled, onCheckedChange = null) } Text( "When on, sleep the ring records outside the window is trimmed off on import — a " + @@ -1791,7 +1818,22 @@ private fun QuietHoursCard() { if (enabled) { Spacer(Modifier.height(12.dp)) Row( - Modifier.fillMaxWidth(), + Modifier.fillMaxWidth() + .switchRow(checked = gateByZenMode, onCheckedChange = { desired -> + if (desired) { + ZenModeListener.setEnabled(context, true) + if (ZenModeListener.isAccessGranted(context)) { + gateByZenMode = true + prefs.gateByZenMode = true + } else { + showPermissionDialog = true + } + } else { + gateByZenMode = false + prefs.gateByZenMode = false + ZenModeListener.setEnabled(context, false) + } + }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, ) { @@ -1807,24 +1849,7 @@ private fun QuietHoursCard() { color = MaterialTheme.colorScheme.onSurfaceVariant, ) } - Switch( - checked = gateByZenMode, - onCheckedChange = { desired -> - if (desired) { - ZenModeListener.setEnabled(context, true) - if (ZenModeListener.isAccessGranted(context)) { - gateByZenMode = true - prefs.gateByZenMode = true - } else { - showPermissionDialog = true - } - } else { - gateByZenMode = false - prefs.gateByZenMode = false - ZenModeListener.setEnabled(context, false) - } - }, - ) + Switch(checked = gateByZenMode, onCheckedChange = null) } Spacer(Modifier.height(8.dp)) @@ -1942,6 +1967,7 @@ fun WearableSettingsScreen( val supportsFindDevice = bleState.activeCapabilities .contains(com.pulseloop.ring.WearableCapability.FIND_DEVICE) var showFactoryReset by remember { mutableStateOf(false) } + var showForgetRing by remember { mutableStateOf(false) } var resetting by remember { mutableStateOf(false) } var resetStatus by remember { mutableStateOf("") } @@ -2064,25 +2090,7 @@ fun WearableSettingsScreen( ) Spacer(Modifier.height(12.dp)) OutlinedButton( - onClick = { - scope.launch { - // Cancel background sync before unpair - RingSyncWorker.cancel(context) - // Send ring-side unbind, then disconnect & clear DB - if (coordinator != null && isConnected) { - // Runs on the coordinator's long-lived scope, so the row is - // cleared even if the user leaves this screen meanwhile. - // Clearing it emits null through currentFlow(), which - // updates the UI reactively. - coordinator.forgetRing { - db.deviceDao().clear() - } - } else { - bleClient?.forget() - db.deviceDao().clear() - } - } - }, + onClick = { showForgetRing = true }, modifier = Modifier.fillMaxWidth(), colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.error), ) { @@ -2118,6 +2126,44 @@ fun WearableSettingsScreen( } } + if (showForgetRing) { + AlertDialog( + onDismissRequest = { showForgetRing = false }, + title = { Text("Forget ring?") }, + text = { + Text( + "This unbinds the ring and removes it from the app. Your synced data is " + + "kept, but you'll need to pair the ring again to keep syncing." + ) + }, + confirmButton = { + TextButton(onClick = { + showForgetRing = false + scope.launch { + // Cancel background sync before unpair + RingSyncWorker.cancel(context) + // Send ring-side unbind, then disconnect & clear DB + if (coordinator != null && isConnected) { + // Runs on the coordinator's long-lived scope, so the row is + // cleared even if the user leaves this screen meanwhile. + // Clearing it emits null through currentFlow(), which + // updates the UI reactively. + coordinator.forgetRing { + db.deviceDao().clear() + } + } else { + bleClient?.forget() + db.deviceDao().clear() + } + } + }) { Text("Forget", color = MaterialTheme.colorScheme.error) } + }, + dismissButton = { + TextButton(onClick = { showForgetRing = false }) { Text("Cancel") } + }, + ) + } + if (showFactoryReset) { AlertDialog( onDismissRequest = { showFactoryReset = false }, @@ -2539,7 +2585,7 @@ fun PrivacyDataSettingsScreen( color = MaterialTheme.colorScheme.onSurfaceVariant, ) Spacer(Modifier.height(12.dp)) - Row(verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.switchRow(checked = maskSensitive, onCheckedChange = { maskSensitive = it }), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text("Anonymize export", style = MaterialTheme.typography.bodyMedium) Text( @@ -2552,7 +2598,7 @@ fun PrivacyDataSettingsScreen( else MaterialTheme.colorScheme.error, ) } - Switch(checked = maskSensitive, onCheckedChange = { maskSensitive = it }) + Switch(checked = maskSensitive, onCheckedChange = null) } Spacer(Modifier.height(12.dp)) Button( @@ -2776,7 +2822,8 @@ fun AboutSettingsScreen(onOpenDebug: () -> Unit, onBack: () -> Unit) { .clip(CircleShape) .background(PulseColors.elevated) .border(1.dp, PulseColors.borderSubtle, CircleShape) - .padding(horizontal = 16.dp, vertical = 10.dp), + .padding(horizontal = 16.dp, vertical = 10.dp) + .semantics { liveRegion = LiveRegionMode.Polite }, ) } }, @@ -2878,21 +2925,18 @@ fun NutritionSettingsScreen(onBack: () -> Unit, onNavigateToNutrition: () -> Uni CoachManagedCard(com.pulseloop.service.GoalSync.NUTRITION_FIELDS) { goalReload++ } Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.fillMaxWidth() + .switchRow(checked = goal?.nutritionEnabled == true, enabled = goalLoaded, onCheckedChange = { enabled -> + val g = goal ?: return@switchRow + scope.launch { + goal = g.copy(nutritionEnabled = enabled).also { db.userGoalDao().upsert(it) } + } + }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text("Enable Nutrition Tracking", fontWeight = FontWeight.Medium) Text("Log meals and track calories & macros", fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) } - Switch( - checked = goal?.nutritionEnabled == true, - enabled = goalLoaded, - onCheckedChange = { enabled -> - val g = goal ?: return@Switch - scope.launch { - goal = g.copy(nutritionEnabled = enabled).also { db.userGoalDao().upsert(it) } - } - }, - ) + Switch(checked = goal?.nutritionEnabled == true, enabled = goalLoaded, onCheckedChange = null) } } } @@ -2966,6 +3010,7 @@ fun StravaSettingsScreen(onBack: () -> Unit) { var athleteName by remember { mutableStateOf(tokenStore.get()?.athleteName) } var isUploading by remember { mutableStateOf(false) } var statusMessage by remember { mutableStateOf(null) } + var confirmDisconnect by remember { mutableStateOf(false) } // The OAuth callback lands in MainActivity, which writes tokens (or a failure message) into // the store. Poll for either for 60 s after entering the screen, then stop. @@ -3043,20 +3088,7 @@ fun StravaSettingsScreen(onBack: () -> Unit) { Text(if (isUploading) "Syncing…" else "Sync Now") } OutlinedButton( - onClick = { - scope.launch { - // Revoke on Strava's side first, so PulseLoop also disappears - // from the athlete's "My Apps" list — clearing local tokens - // alone leaves the authorization live forever. - tokenStore.get()?.let { - runCatching { com.pulseloop.strava.StravaAuth.deauthorize(it) } - } - tokenStore.clear() - isConnected = false - athleteName = null - statusMessage = "Disconnected from Strava" - } - }, + onClick = { confirmDisconnect = true }, modifier = Modifier.weight(1f), colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.error), ) { @@ -3115,6 +3147,34 @@ fun StravaSettingsScreen(onBack: () -> Unit) { } } } + + if (confirmDisconnect) { + AlertDialog( + onDismissRequest = { confirmDisconnect = false }, + title = { Text("Disconnect Strava?") }, + text = { Text("PulseLoop will stop uploading workouts. Workouts already on Strava stay there.") }, + confirmButton = { + TextButton(onClick = { + confirmDisconnect = false + scope.launch { + // Revoke on Strava's side first, so PulseLoop also disappears + // from the athlete's "My Apps" list — clearing local tokens + // alone leaves the authorization live forever. + tokenStore.get()?.let { + runCatching { com.pulseloop.strava.StravaAuth.deauthorize(it) } + } + tokenStore.clear() + isConnected = false + athleteName = null + statusMessage = "Disconnected from Strava" + } + }) { Text("Disconnect", color = MaterialTheme.colorScheme.error) } + }, + dismissButton = { + TextButton(onClick = { confirmDisconnect = false }) { Text("Cancel") } + }, + ) + } } // MARK: - Health Connect @@ -3277,7 +3337,14 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { } HealthConnectAvailability.AVAILABLE -> { - Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.fillMaxWidth() + .switchRow(checked = prefs.enabled, onCheckedChange = { on -> + if (on) { + permissionLauncher.launch(HealthConnectPermissions.all) + } else { + store.update { it.copy(enabled = false) } + } + }), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text("Export PulseLoop data", style = MaterialTheme.typography.bodyLarge) Text( @@ -3286,16 +3353,7 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { color = MaterialTheme.colorScheme.onSurfaceVariant, ) } - Switch( - checked = prefs.enabled, - onCheckedChange = { on -> - if (on) { - permissionLauncher.launch(HealthConnectPermissions.all) - } else { - store.update { it.copy(enabled = false) } - } - }, - ) + Switch(checked = prefs.enabled, onCheckedChange = null) } // Always reachable (review pass 5). Two states have no other way out: // once every permission is revoked the app can no longer delete what it @@ -3350,23 +3408,8 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { val rowPerms = HealthConnectPermissions.permissionsForRow(row) val rowGranted = rowPerms.isEmpty() || rowPerms.any { it in granted } Row( - Modifier.fillMaxWidth().padding(vertical = 4.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Column(Modifier.weight(1f)) { - Text(label, style = MaterialTheme.typography.bodyMedium) - if (!rowGranted) { - Text( - "Awaiting permission", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - Switch( - checked = prefs.toggleFor(row), - enabled = rowGranted, - onCheckedChange = { on -> + Modifier.fillMaxWidth().padding(vertical = 4.dp) + .switchRow(checked = prefs.toggleFor(row), enabled = rowGranted, onCheckedChange = { on -> store.update { p -> p.withToggleFor(row, on) } // Re-enabling a VITALS kind must backfill the readings recorded while it // was off: the VITALS group watermark is driven by the *enabled* kinds @@ -3379,8 +3422,20 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { store.resetWatermarks(setOf(HealthConnectWatermarks.Key.VITALS)) HealthConnectExportWorker.enqueue(context) } - }, - ) + }), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text(label, style = MaterialTheme.typography.bodyMedium) + if (!rowGranted) { + Text( + "Awaiting permission", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + Switch(checked = prefs.toggleFor(row), enabled = rowGranted, onCheckedChange = null) } if (row == HealthConnectPermissions.DataTypeRow.HEART_RATE_VARIABILITY) { // Plan §7 open item: the rings' HRV metric is vendor-undocumented, and @@ -3650,7 +3705,14 @@ private fun CoachManagedCard(fields: Set, Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { - Row(verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.switchRow(checked = following.size == fields.size, onCheckedChange = { on -> + com.pulseloop.service.GoalSync.setFollowing(context, fields, on) + scope.launch { + if (on) com.pulseloop.service.GoalSync.sync(context, db, force = true) + refresh++ + onChanged() + } + }), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text("Coach goal: ${g.description}", fontWeight = FontWeight.Medium) Text( @@ -3659,17 +3721,7 @@ private fun CoachManagedCard(fields: Set, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, ) } - Switch( - checked = following.size == fields.size, - onCheckedChange = { on -> - com.pulseloop.service.GoalSync.setFollowing(context, fields, on) - scope.launch { - if (on) com.pulseloop.service.GoalSync.sync(context, db, force = true) - refresh++ - onChanged() - } - }, - ) + Switch(checked = following.size == fields.size, onCheckedChange = null) } Text("Let my goal manage these", fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) } 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 225ac39a..d54de1ea 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt @@ -8,6 +8,8 @@ import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.foundation.shape.CircleShape @@ -27,6 +29,7 @@ import androidx.compose.material3.OutlinedButton import androidx.compose.material3.SelectableDates import androidx.compose.material3.Text import androidx.compose.material3.TextButton +import androidx.compose.material3.TimeInput import androidx.compose.material3.TimePicker import androidx.compose.material3.rememberDatePickerState import androidx.compose.material3.rememberTimePickerState @@ -44,6 +47,10 @@ import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onSizeChanged 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.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.IntOffset @@ -176,7 +183,7 @@ private fun androidx.compose.foundation.lazy.LazyListScope.sessionPageItems( val runs = com.pulseloop.service.sleepRecordRuns(blocks) if (runs.size > 1) item { SleepRecordsCard(session, runs, viewModel) } item { - val byStage = blocks.groupBy { it.stageRaw }.mapValues { (_, b) -> b.sumOf { it.durationMinutes } } + val byStage = remember(blocks) { blocks.groupBy { it.stageRaw }.mapValues { (_, b) -> b.sumOf { it.durationMinutes } } } SleepStageSummaryCards( deep = SleepFormat.duration(byStage["DEEP"] ?: 0), light = SleepFormat.duration(byStage["LIGHT"] ?: 0), @@ -243,7 +250,7 @@ private fun SleepCarousel( // night) is its own page, and this card is the only place to delete it (#78). val runs = com.pulseloop.service.sleepRecordRuns(blocks) if (runs.isNotEmpty()) SleepRecordsCard(s, runs, viewModel) - val byStage = blocks.groupBy { it.stageRaw }.mapValues { (_, b) -> b.sumOf { it.durationMinutes } } + val byStage = remember(blocks) { blocks.groupBy { it.stageRaw }.mapValues { (_, b) -> b.sumOf { it.durationMinutes } } } SleepStageSummaryCards( deep = SleepFormat.duration(byStage["DEEP"] ?: 0), light = SleepFormat.duration(byStage["LIGHT"] ?: 0), @@ -343,7 +350,8 @@ private fun SleepRangeSelector(selection: SleepRangeKey, onSelect: (SleepRangeKe .clip(CircleShape) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, CircleShape) - .padding(4.dp), + .padding(4.dp) + .selectableGroup(), horizontalArrangement = Arrangement.spacedBy(4.dp), ) { options.forEach { (key, label) -> @@ -356,11 +364,13 @@ private fun SleepRangeSelector(selection: SleepRangeKey, onSelect: (SleepRangeKe textAlign = androidx.compose.ui.text.style.TextAlign.Center, modifier = Modifier .weight(1f) + .heightIn(min = 48.dp) .clip(CircleShape) .then(if (active) Modifier.dither(PulseColors.accent, 0.15f) else Modifier) .border(1.dp, if (active) PulseColors.accent.copy(alpha = 0.4f) else Color.Transparent, CircleShape) - .clickable { onSelect(key) } - .padding(vertical = 6.dp), + .selectable(selected = active, role = Role.Tab) { onSelect(key) } + .padding(vertical = 6.dp) + .wrapContentHeight(), ) } } @@ -461,7 +471,7 @@ private fun VisualizationCard( private fun LegendItem(label: String, color: Color) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp)) { Box(Modifier.size(6.dp).clip(CircleShape).background(color)) - Text(label, fontSize = 9.sp, color = PulseColors.textSecondary) + Text(label, fontSize = 11.sp, color = PulseColors.textSecondary) } } @@ -538,6 +548,16 @@ private fun SleepHypnogram( return best.coerceIn(0, sorted.lastIndex) } + // Spoken stand-in for the plot: the window, then minutes per stage in lane order. + 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)}" } + } + "Sleep stages from ${clockTime(startTs)} to ${clockTime(startTs + safeTotal * 60_000L)}" + + if (parts.isEmpty()) ": no stage data" else ": " + parts.joinToString(", ") + } + fun readoutText(block: SleepStageBlockEntity): String { val stage = block.stageRaw.replaceFirstChar { it.uppercase() } val startTime = clockTime(startTs + block.startMinute * 60_000L) @@ -552,7 +572,8 @@ 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, Color.White.copy(alpha = 0.06f), RoundedCornerShape(8.dp)) + .clearAndSetSemantics { contentDescription = summary }, ) { var plotWidthPx by remember { mutableFloatStateOf(0f) } var plotHeightPx by remember { mutableFloatStateOf(0f) } @@ -666,7 +687,9 @@ private fun SleepHypnogram( Text( stage, fontSize = 10.sp, fontWeight = FontWeight.SemiBold, - letterSpacing = 1.4.sp, color = stageColor(stage), + // Not the stage colour: DEEP's is 2.4:1 on the card. The bars and + // legend swatches carry the colour. + letterSpacing = 1.4.sp, color = PulseColors.textSecondary, modifier = Modifier.offset { IntOffset( x = -LABEL_GUTTER_DP.dp.roundToPx(), @@ -718,7 +741,7 @@ private fun SleepHypnogram( Modifier.fillMaxWidth().padding(start = plotInsets.x, end = plotTrailing), horizontalArrangement = Arrangement.SpaceBetween, ) { - ticks.forEach { Text(it, fontSize = 10.sp, color = PulseColors.textMuted) } + ticks.forEach { Text(it, fontSize = 11.sp, color = PulseColors.textMuted) } } } } @@ -747,7 +770,7 @@ private fun StageStat(label: String, value: String, color: Color, modifier: Modi Box(Modifier.size(8.dp).clip(CircleShape).background(color)) Text( label.uppercase(), - fontSize = 10.sp, fontWeight = FontWeight.Medium, + fontSize = 11.sp, fontWeight = FontWeight.Medium, letterSpacing = 0.6.sp, color = PulseColors.textMuted, maxLines = 1, overflow = TextOverflow.Ellipsis, ) @@ -781,9 +804,17 @@ private fun SleepDurationHistogram( val yMax = maxOf(bars.mapNotNull { it.durationMin }.maxOrNull() ?: 0, goalMin ?: 0) .let { if (it > 0) it * 1.15f else 600f } val labelInterval = if (bars.size > 14) maxOf(1, bars.size / 6) else 1 + val summary = remember(bars, goalMin) { + val tracked = bars.filter { it.present }.mapNotNull { it.durationMin } + if (tracked.isEmpty()) "Nightly sleep: no nights tracked in this range" + else "Nightly sleep: latest ${SleepFormat.duration(tracked.last())}, " + + "range ${SleepFormat.duration(tracked.min())}–${SleepFormat.duration(tracked.max())}, " + + "${tracked.size} of ${bars.size} nights tracked" + + (goalMin?.takeIf { it > 0 }?.let { ", goal ${SleepFormat.duration(it)}" } ?: "") + } Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { - Canvas(Modifier.fillMaxWidth().height(height - 24.dp)) { + Canvas(Modifier.fillMaxWidth().height(height - 24.dp).semantics { contentDescription = summary }) { val slotW = size.width / bars.size val barW = if (slim) 7.dp.toPx() else (slotW * 0.7f).coerceAtMost(30.dp.toPx()) val r = if (slim) 3.dp.toPx() else 6.dp.toPx() @@ -822,7 +853,7 @@ private fun SleepDurationHistogram( bars.forEachIndexed { i, bar -> Box(Modifier.weight(1f), contentAlignment = Alignment.Center) { if (i % labelInterval == 0) { - Text(bar.label, fontSize = 9.sp, color = PulseColors.textMuted, maxLines = 1) + Text(bar.label, fontSize = 11.sp, color = PulseColors.textMuted, maxLines = 1) } } } @@ -887,9 +918,9 @@ private fun NavChevron( ) { Box( Modifier - .size(44.dp) + .size(48.dp) .clip(CircleShape) - .then(if (enabled) Modifier.clickable(onClick = onClick) else Modifier), + .clickable(enabled = enabled, role = Role.Button, onClick = onClick), contentAlignment = Alignment.Center, ) { Icon( @@ -1206,6 +1237,8 @@ private fun SleepRecordEditDialog( ) pickingTime?.let { which -> + val landscape = androidx.compose.ui.platform.LocalConfiguration.current.orientation == + android.content.res.Configuration.ORIENTATION_LANDSCAPE val targetTs = if (which == "start") currentStart else currentEnd val zdt = java.time.Instant.ofEpochMilli(targetTs).atZone(zone) val timeState = rememberTimePickerState( @@ -1217,7 +1250,8 @@ private fun SleepRecordEditDialog( AlertDialog( onDismissRequest = { pickingTime = null }, title = { Text(if (which == "start") "Adjust start time" else "Adjust end time") }, - text = { TimePicker(state = timeState) }, + // The dial doesn't fit a landscape dialog; the keyboard entry form does. + text = { if (landscape) TimeInput(state = timeState) else TimePicker(state = timeState) }, confirmButton = { TextButton(onClick = { val picked = resolveAdjustedTime(targetTs, run.startAt, run.endAt, timeState.hour, timeState.minute, zone) 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 7cae966c..138654f6 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt @@ -23,6 +23,7 @@ import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.Role import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector @@ -215,7 +216,10 @@ fun TagDaySheet(db: PulseLoopDatabase, onDismiss: () -> Unit, onSeeEffects: () - Text( "See what affects you", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, - modifier = Modifier.clickable(onClick = onSeeEffects).padding(top = 4.dp), + modifier = Modifier + .heightIn(min = 48.dp) + .clickable(role = Role.Button, onClick = onSeeEffects) + .wrapContentHeight(Alignment.CenterVertically), ) } } @@ -245,7 +249,7 @@ private fun SheetOption(title: String, subtitle: String, icon: ImageVector, onCl } /** The whole coach brief (the Today line shows only its first lines), with a way into the chat. */ -@OptIn(ExperimentalMaterial3Api::class) +@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) @Composable fun CoachBriefSheet( title: String, @@ -272,7 +276,12 @@ fun CoachBriefSheet( Text(title, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(body, fontSize = 15.sp, lineHeight = 22.sp, color = PulseColors.textSecondary) if (chips.isNotEmpty()) { - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(6.dp)) { + // 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), + ) { chips.take(3).forEach { Text( it, fontSize = 12.sp, color = PulseColors.textPrimary, maxLines = 1, 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 a2282b4f..46557c55 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt @@ -13,7 +13,10 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment +import androidx.compose.ui.semantics.Role +import androidx.activity.compose.BackHandler import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp @@ -66,6 +69,7 @@ fun TodayScreen( val scope = rememberCoroutineScope() var isRefreshing by remember { mutableStateOf(false) } val context = LocalContext.current + val screenWidthDp = LocalConfiguration.current.screenWidthDp // remember{}: the ApiKeyStore constructor does Keystore + encrypted-prefs I/O — far // too expensive to repeat on every recomposition of this state-collecting screen. val keyStore = remember { ApiKeyStore(context) } @@ -125,6 +129,8 @@ fun TodayScreen( val prefsStore = remember { MetricPrefsStore.get(context) } val prefs by prefsStore.prefs.collectAsState() val editState = rememberDashboardEditState(MetricScope.TODAY, prefsStore) + // System Back finishes editing, the same as Done, instead of leaving the tab mid-edit. + BackHandler(enabled = editState.editing) { editState.exit() } val supported: (DashboardCard) -> Boolean = { card -> when (card) { @@ -243,7 +249,10 @@ fun TodayScreen( when (moment) { TodayMoments.Moment.LAST_NIGHT -> sleep.lastNight?.let { night -> item { - val fmt = java.time.format.DateTimeFormatter.ofPattern("HH:mm") + // Follow the phone's 12/24-hour setting rather than forcing 24-hour. + val fmt = java.time.format.DateTimeFormatter.ofPattern( + if (android.text.format.DateFormat.is24HourFormat(context)) "HH:mm" else "h:mm a", + ) val zone = java.time.ZoneId.systemDefault() fun t(ms: Long) = java.time.Instant.ofEpochMilli(ms).atZone(zone).format(fmt) LastNightCard( @@ -276,7 +285,10 @@ fun TodayScreen( Text( "See what affects you", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.readiness, - modifier = Modifier.clickable { navController?.navigate("journal") }.padding(top = 4.dp), + modifier = Modifier + .heightIn(min = 48.dp) + .clickable(role = Role.Button) { navController?.navigate("journal") } + .wrapContentHeight(Alignment.CenterVertically), ) } } @@ -291,8 +303,12 @@ fun TodayScreen( } } - val rows = visibleOrdered.chunked(2) - items(rows.size) { rowIndex -> + // Three across from 600dp (tablets, unfolded foldables) instead of two stretched tiles. + val columns = if (screenWidthDp >= 600) 3 else 2 + val rows = visibleOrdered.chunked(columns) + // Keyed by the cards in the row so a reorder in edit mode moves rows rather than + // recomposing every row in place. + items(rows.size, key = { rows[it].joinToString("|") { card -> card.name } }) { rowIndex -> val row = rows[rowIndex] // IntrinsicSize.Min + fillMaxHeight is what keeps the grid uniform now that tiles // size to their content: the row takes the height its tallest tile actually needs, @@ -307,7 +323,7 @@ fun TodayScreen( todayCardFor(card, Modifier.fillMaxWidth().fillMaxHeight()) } } - if (row.size == 1) Spacer(Modifier.weight(1f)) + repeat(columns - row.size) { Spacer(Modifier.weight(1f)) } } } @@ -423,6 +439,7 @@ private fun ChartTile(card: VitalCardState, values: List, modifier: Modi zones = card.zones, yDomain = card.yDomain, accent = ZonePalette.accent(card.metric), + label = card.title, referenceBands = card.referenceBands, dashedRules = card.dashedRules, showPoints = card.metric == MetricKind.SPO2, @@ -629,7 +646,9 @@ private fun NutritionTile(food: FoodTotals?, modifier: Modifier, onLog: () -> Un Text( "+ Log meal", fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, - modifier = Modifier.clickable(onClick = onLog).padding(vertical = 2.dp), + // No min height here: it would stretch the tile and its row. Compose already widens a + // small clickable's hit area towards 48dp. + modifier = Modifier.clickable(role = Role.Button, onClick = onLog).padding(vertical = 2.dp), ) } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt index 1628d36a..5adb087c 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/WorkoutSummaryScreen.kt @@ -1,5 +1,6 @@ package com.pulseloop.ui.screens +import android.content.res.Configuration import com.pulseloop.ui.theme.dither import androidx.compose.foundation.background import androidx.compose.foundation.border @@ -28,6 +29,7 @@ import androidx.compose.material3.OutlinedButton import androidx.compose.material3.SelectableDates import androidx.compose.material3.Text import androidx.compose.material3.TextButton +import androidx.compose.material3.TimeInput import androidx.compose.material3.TimePicker import androidx.compose.material3.rememberDatePickerState import androidx.compose.material3.rememberModalBottomSheetState @@ -37,7 +39,9 @@ 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.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp @@ -83,6 +87,8 @@ fun WorkoutSummaryScreen( var points by remember { mutableStateOf>(emptyList()) } var confirmDelete by remember { mutableStateOf(false) } var editing by remember { mutableStateOf(false) } + // Set when applyEdit refuses the save, so the sheet says so instead of silently staying open. + var editError by remember { mutableStateOf(null) } // Windowed to [startedAt, endedAt] so a post-finish edit excludes out-of-window route points // from the map/splits too (inert for unedited sessions — every point lies inside the recorded @@ -116,11 +122,11 @@ fun WorkoutSummaryScreen( ) { item { Row(Modifier.fillMaxWidth()) { - CircleIconButton(Icons.AutoMirrored.Filled.ArrowBack, tint = PulseColors.textSecondary, onTap = onBack) + CircleIconButton(Icons.AutoMirrored.Filled.ArrowBack, "Back", tint = PulseColors.textSecondary, onTap = onBack) Spacer(Modifier.weight(1f)) - CircleIconButton(Icons.Filled.Edit, tint = PulseColors.accent, onTap = { editing = true }) + CircleIconButton(Icons.Filled.Edit, "Edit workout", tint = PulseColors.accent, onTap = { editing = true }) Spacer(Modifier.width(10.dp)) - CircleIconButton(Icons.Filled.Delete, tint = PulseColors.danger, onTap = { confirmDelete = true }) + CircleIconButton(Icons.Filled.Delete, "Delete workout", tint = PulseColors.danger, onTap = { confirmDelete = true }) } } item { @@ -172,12 +178,16 @@ fun WorkoutSummaryScreen( if (editing) { EditWorkoutSheet( session = s, - onDismiss = { editing = false }, + saveError = editError, + onDismiss = { editing = false; editError = null }, onSave = { newType, newStart, newEnd -> + editError = null scope.launch { if (ActivityAggregates.applyEdit(db, s, newType, newStart, newEnd)) { reload() editing = false + } else { + editError = "Couldn't save these changes. Check the times and try again." } } }, @@ -195,6 +205,7 @@ fun WorkoutSummaryScreen( @Composable private fun EditWorkoutSheet( session: ActivitySessionEntity, + saveError: String?, onDismiss: () -> Unit, onSave: (type: String, startedAt: Long, endedAt: Long) -> Unit, ) { @@ -247,11 +258,12 @@ private fun EditWorkoutSheet( DateTimeButton(endedAt) { endedAt = it } } + val message = validationMessage ?: saveError Text( - validationMessage + message ?: "Distance, calories, and heart-rate stats are recalculated for the new window.", fontSize = 12.sp, - color = if (validationMessage != null) PulseColors.warning else PulseColors.textMuted, + color = if (message != null) PulseColors.warning else PulseColors.textMuted, textAlign = androidx.compose.ui.text.style.TextAlign.Center, modifier = Modifier.fillMaxWidth(), ) @@ -336,6 +348,7 @@ internal fun DateTimeButton(valueMillis: Long, onChange: (Long) -> Unit) { } if (showTime) { + val landscape = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE val cal = Calendar.getInstance().apply { timeInMillis = pendingDayMillis } val timeState = rememberTimePickerState( initialHour = cal.get(Calendar.HOUR_OF_DAY), @@ -346,7 +359,8 @@ internal fun DateTimeButton(valueMillis: Long, onChange: (Long) -> Unit) { AlertDialog( onDismissRequest = { showTime = false }, title = { Text("Time") }, - text = { TimePicker(state = timeState) }, + // The dial doesn't fit a landscape dialog; the keyboard entry form does. + text = { if (landscape) TimeInput(state = timeState) else TimePicker(state = timeState) }, confirmButton = { TextButton(onClick = { val result = Calendar.getInstance().apply { @@ -380,17 +394,22 @@ internal fun utcMidnightToLocalDayStart(utcMillis: Long): Long { } @Composable -internal fun CircleIconButton(icon: androidx.compose.ui.graphics.vector.ImageVector, tint: Color, onTap: () -> Unit) { +internal fun CircleIconButton( + icon: androidx.compose.ui.graphics.vector.ImageVector, + contentDescription: String, + tint: Color, + onTap: () -> Unit, +) { Box( Modifier - .size(44.dp) + .size(48.dp) .clip(CircleShape) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, CircleShape) - .clickable(onClick = onTap), + .clickable(role = Role.Button, onClick = onTap), contentAlignment = Alignment.Center, ) { - Icon(icon, null, tint = tint, modifier = Modifier.size(20.dp)) + Icon(icon, contentDescription, tint = tint, modifier = Modifier.size(20.dp)) } } @@ -458,7 +477,7 @@ private fun SummaryHeroBand(s: ActivitySessionEntity, durationSec: Int?, units: metrics.forEachIndexed { i, m -> Column(Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(6.dp)) { Text(m.value, fontSize = 30.sp, fontWeight = FontWeight.SemiBold, color = m.tint, maxLines = 1) - Text(m.label, fontSize = 10.sp, fontWeight = FontWeight.Medium, letterSpacing = 0.8.sp, color = PulseColors.textMuted) + Text(m.label, fontSize = 11.sp, fontWeight = FontWeight.Medium, letterSpacing = 0.8.sp, color = PulseColors.textMuted) } if (i != metrics.lastIndex) { Box(Modifier.width(1.dp).height(40.dp).background(PulseColors.borderSubtle)) @@ -493,7 +512,7 @@ private fun StatsGrid(s: ActivitySessionEntity) { verticalArrangement = Arrangement.spacedBy(4.dp), ) { Text(value, fontSize = 20.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) - Text(label.uppercase(), fontSize = 10.sp, fontWeight = FontWeight.Medium, letterSpacing = 0.8.sp, color = PulseColors.textMuted) + Text(label.uppercase(), fontSize = 11.sp, fontWeight = FontWeight.Medium, letterSpacing = 0.8.sp, color = PulseColors.textMuted) } } repeat(3 - row.size) { Spacer(Modifier.weight(1f)) } diff --git a/app/src/main/java/com/pulseloop/ui/theme/PulseColors.kt b/app/src/main/java/com/pulseloop/ui/theme/PulseColors.kt index dc67f726..59532037 100644 --- a/app/src/main/java/com/pulseloop/ui/theme/PulseColors.kt +++ b/app/src/main/java/com/pulseloop/ui/theme/PulseColors.kt @@ -18,7 +18,8 @@ object PulseColors { val elevated = Color(0xFF2C2B30) val textPrimary = Color(0xFFF2F2F2) val textSecondary = Color(0xFFA8A7AD) - val textMuted = Color(0xFF7C7B82) + /** Tertiary text. #8E8D94 so it still reads at 4.5:1 on [card] and [cardSoft] (#7C7B82 was 4.1 / 3.7). */ + val textMuted = Color(0xFF8E8D94) /** GMind mint: the primary action, the selected state, the screen frame. */ val accent = Color(0xFF43F3B7) val accentSoft = Color(0x2E43F3B7) // accent @ 18% diff --git a/docs/ui-audit-2026-10.md b/docs/ui-audit-2026-10.md new file mode 100644 index 00000000..42fe38b9 --- /dev/null +++ b/docs/ui-audit-2026-10.md @@ -0,0 +1,61 @@ +# UI audit — October 2026 + +A code-level audit of the Compose UI, run with two design skills: **impeccable** (`audit` for +native Android, scored against Material 3) and **ui-ux-pro-max** (its priority rules and the +Jetpack Compose stack guidance). Three parallel passes covered the whole `ui/` tree; every finding +was checked against the code before it was acted on. + +The GMind brand is treated as the brief, not as a finding: dark-only, Ubuntu Mono throughout, one +mint accent with ink-green on it, and the 4dp mint frame. + +## Score (before the fixes in this branch) + +| # | Dimension | Score | Key finding | +|---|-----------|-------|-------------| +| 1 | Accessibility | 1 | ~24 switch rows had no spoken label ("off, switch"); no `semantics`, `selectable` or `liveRegion` anywhere in `ui/`; icon-only Back/Edit/Delete read as "unlabeled button" | +| 2 | Performance | 3 | `runBlocking` on the UI thread for workout pause/resume/finish; a Room Flow rebuilt on every recomposition | +| 3 | Appearance & theming | 3 | Tokenised throughout (`PulseColors`), but `textMuted` failed 4.5:1 on every card surface (182 uses) | +| 4 | Platform conformance | 2 | No `BackHandler` in the app: Back abandoned onboarding, edit mode, a live workout and breathing sessions; permission prompts re-opened on every resume | +| 5 | Adaptivity | 2 | Landscape handled; no window-size awareness, so tablets get stretched phone tiles | +| | **Total** | **11/20** | **Acceptable — significant work needed** | + +## Systemic fixes + +- **`textMuted` #7C7B82 → #8E8D94.** One token change lifts all 182 uses to 5.2:1 on `card` and + 4.75:1 on `cardSoft`, while staying a visible step below `textSecondary`. +- **Switch rows are one control** (`Modifier.switchRow`, `ui/components/A11y.kt`): the whole row + toggles with `Role.Switch` and the Switch is only the indicator. TalkBack now reads + "Athlete mode, off, switch", and the label is tappable. +- **"Remove animations" is honoured** (`rememberReduceMotion()`): the connection pill and the + breathing circle hold still when the system animator scale is 0. + +## Fixed in this branch + +See the commit for the full list. In short: Back handling (onboarding steps, dashboard edit mode, +live workout, breathing session save), the permission loop and the missing coarse-location +request, confirmations for Forget Ring / meal / drink / Strava / memory deletes, IME insets on +settings sub-screens, 48dp touch targets on the dashboard edit badges, coach composer, period +chevrons, chips and segmented controls, selection semantics on chips and segmented controls, +spoken summaries for charts, gauges, rings and the hypnogram, the DEEP stage label's contrast, +9sp labels raised, bottom-nav labels no longer read twice, tile grid keys and a 3-column grid at +600dp+, and `runBlocking` removed from the record screen. + +Removed as dead code: the landscape "status-bar glass strip" in `PulseLoopApp`. `MainActivity` +pads and consumes the system-bar insets around the whole app, so `WindowInsets.statusBars` inside +resolved to zero and the strip had no height; content already stops below the status bar. + +Workout pause/resume/finish run on `LiveWorkoutManager`'s own scope (`*FromUi`), not the record +screen's: finishing pops that screen, and a screen-scoped launch would cancel the Strava upload. +A second tap while one is in flight is dropped, so Finish can't credit a workout twice. + +## Open (not done here) + +- **Location is still requested at launch.** Material guidance is to ask just before the first + GPS workout; that needs a rationale screen in the record flow. +- **Charts are summarised, not navigable.** TalkBack hears a one-line summary; per-point + exploration would need custom accessibility actions. +- **Window size classes.** Only the Today grid adapts; a navigation rail on expanded width and + wider content gutters are the next step. +- **Sleep times are always 12-hour** (`SleepFormat.clockTime`), while Today now follows the + phone's 12/24-hour setting. +- **Toasts** remain in `SleepScreen`; a `SnackbarHost` at the app scaffold would let them move.