From a551fb158487ab128ffeac0a54d5e6ad62f143ee Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 00:16:15 +0000 Subject: [PATCH 1/3] Notifications always reachable, one goal save path, honest Health Connect copy (WIP) Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- app/src/main/assets/i18n/en-FH.json | 4 +- app/src/main/assets/i18n/pt-BR-FH.json | 4 +- app/src/main/assets/i18n/pt-BR.json | 4 +- .../java/com/pulseloop/service/GoalSync.kt | 11 +++ .../pulseloop/ui/screens/ActivityScreen.kt | 7 +- .../pulseloop/ui/screens/SettingsScreen.kt | 20 +++-- .../ui/screens/SettingsSubScreens.kt | 78 +++++++++---------- .../com/pulseloop/ui/viewmodels/ViewModels.kt | 19 ++--- 8 files changed, 78 insertions(+), 69 deletions(-) diff --git a/app/src/main/assets/i18n/en-FH.json b/app/src/main/assets/i18n/en-FH.json index 99bd5a34..ffa81ba9 100644 --- a/app/src/main/assets/i18n/en-FH.json +++ b/app/src/main/assets/i18n/en-FH.json @@ -98,7 +98,7 @@ "First sync": "First sync. Let's see the damage.", "Flow, stretch, or breathwork": "Flow, stretch, or just f*cking breathe", "For drinks, money and calories saved": "For drinks, money and calories you didn't waste", - "Get a daily check-in from your coach. You can change this anytime in Coach Check-Ins.": "Get a daily check-in from your coach. Change your mind anytime in Coach Check-Ins.", + "Get a daily check-in from your coach. You can change this anytime in Settings → Notifications.": "Get a daily check-in from your coach. Change your mind anytime in Settings → Notifications.", "Get notified when your ring drops below 20% and 10%, so tracking doesn't stop mid-day.": "Get yelled at when your ring drops below 20% and 10%, so tracking doesn't die mid-day.", "Get started": "Fine, let's start", "Goal met on {0} of the last {1} days": "Goal met on {0} of the last {1} days. And the rest, huh?", @@ -456,4 +456,4 @@ "{0} steps to your goal.": "{0} steps to your goal. Move it.", "{0} steps today. {1} Time to start winding down.": "{0} steps today. {1} Now put the damn phone down and wind down.", "{0}% of the night asleep": "{0}% of the night actually asleep" -} \ No newline at end of file +} diff --git a/app/src/main/assets/i18n/pt-BR-FH.json b/app/src/main/assets/i18n/pt-BR-FH.json index 20e6de6b..5db611e8 100644 --- a/app/src/main/assets/i18n/pt-BR-FH.json +++ b/app/src/main/assets/i18n/pt-BR-FH.json @@ -98,7 +98,7 @@ "First sync": "Primeira sincronização. Bora ver o estrago.", "Flow, stretch, or breathwork": "Flow, alongamento ou só respira, p*rra", "For drinks, money and calories saved": "Para bebidas, dinheiro e calorias que você não torrou", - "Get a daily check-in from your coach. You can change this anytime in Coach Check-Ins.": "Receba um check-in diário do seu coach. Mudou de ideia? Altera quando quiser em Check-ins do Coach.", + "Get a daily check-in from your coach. You can change this anytime in Settings → Notifications.": "Receba um check-in diário do seu coach. Mudou de ideia? Altera quando quiser em Configurações → Notificações.", "Get notified when your ring drops below 20% and 10%, so tracking doesn't stop mid-day.": "Leve um grito quando a bateria do anel ficar abaixo de 20% e 10%, pro monitoramento não morrer no meio do dia.", "Get started": "Tá, bora começar", "Goal met on {0} of the last {1} days": "Meta atingida em {0} dos últimos {1} dias. E o resto, hein?", @@ -456,4 +456,4 @@ "{0} steps to your goal.": "Faltam {0} passos para sua meta. Bora.", "{0} steps today. {1} Time to start winding down.": "{0} passos hoje. {1} Agora larga a p*rra do celular e vai relaxar.", "{0}% of the night asleep": "{0}% da noite dormindo de verdade" -} \ No newline at end of file +} diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index e0dd93fc..84323591 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -544,7 +544,7 @@ "Export app, device, and wearable logs as JSON.": "Exporte logs do app, do dispositivo e do wearable em JSON.", "Export failed": "Falha na exportação", "Export reset — re-grant permissions to sync again.": "Exportação redefinida — conceda as permissões novamente para voltar a sincronizar.", - "Export ring data to Health Connect so other apps and dashboards can show it. Write-only: PulseLoop never reads data back.": "Exporte os dados do anel para o Health Connect para que outros apps e painéis possam exibi-los. Somente gravação: o PulseLoop nunca lê dados de volta.", + "Export ring data to Health Connect so other apps and dashboards can show it. Exporting only writes. PulseLoop reads Health Connect only for features you turn on: body data in your profile, Use without a ring, and the accuracy check.": "Exporte os dados do anel para o Health Connect para que outros apps e painéis possam exibi-los. A exportação só grava. O PulseLoop lê o Health Connect apenas para recursos que você ativa: dados corporais no seu perfil, Usar sem anel e a verificação de precisão.", "Export them too": "Exportar também", "Export them too if you're taking the other device off and want the ring's full history in Health Connect.": "Exporte também se você vai deixar de usar o outro dispositivo e quer o histórico completo do anel no Health Connect.", "Exported only when switched on. A row stays dim until its permission is granted.": "Exportado somente quando ativado. Uma linha fica esmaecida até que sua permissão seja concedida.", @@ -604,7 +604,7 @@ "Gemini": "Gemini", "Gemini API Key": "Chave de API do Gemini", "General": "Geral", - "Get a daily check-in from your coach. You can change this anytime in Coach Check-Ins.": "Receba um check-in diário do seu coach. Você pode alterar isso a qualquer momento em Check-ins do Coach.", + "Get a daily check-in from your coach. You can change this anytime in Settings → Notifications.": "Receba um check-in diário do seu coach. Você pode alterar isso a qualquer momento em Configurações → Notificações.", "Get care now if you notice": "Procure atendimento agora se notar", "Get notified when your ring drops below 20% and 10%, so tracking doesn't stop mid-day.": "Seja avisado quando a bateria do anel ficar abaixo de 20% e 10%, para o monitoramento não parar no meio do dia.", "Get started": "Começar", diff --git a/app/src/main/java/com/pulseloop/service/GoalSync.kt b/app/src/main/java/com/pulseloop/service/GoalSync.kt index 77e002c7..75e60594 100644 --- a/app/src/main/java/com/pulseloop/service/GoalSync.kt +++ b/app/src/main/java/com/pulseloop/service/GoalSync.kt @@ -156,6 +156,17 @@ object GoalSync { if (edited.isNotEmpty()) setFollowing(context, edited, false) } + /** + * Everything a hand-saved goal must do besides the database write, whichever screen saved it: + * stop the edited fields following the coach, send the step goal to the ring, and republish + * the widget's rings. Activity's goal dialog used to skip all three. + */ + fun afterManualSave(context: Context, saved: UserGoalEntity, coordinator: RingSyncCoordinator?) { + noteEdits(context, saved) + coordinator?.setGoal(saved.steps) + com.pulseloop.widgets.WidgetSnapshotPublisher.publish(context) + } + private fun lastApplied(context: Context): Map { val p = prefs(context) return Field.entries.mapNotNull { f -> 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 106fa274..f2fb45ff 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt @@ -314,7 +314,12 @@ fun ActivityScreen( onDismiss = { goalsOpen = false }, onSave = { steps, active, sleepMin, workouts -> goalsOpen = false - scope.launch { viewModel.saveGoals(steps, active, sleepMin, workouts) } + scope.launch { + val saved = viewModel.saveGoals(steps, active, sleepMin, workouts) + com.pulseloop.service.GoalSync.afterManualSave( + context, saved, com.pulseloop.AppServices.get(context).coordinator, + ) + } }, ) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt index 2d88d703..c1cf132e 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt @@ -79,7 +79,6 @@ fun SettingsScreen( CoachProviderMode.BACKEND_PROXY -> tr("Backend proxy") else -> keyStore.model } - val notificationsTrailing = if (keyStore.notificationsEnabled) tr("On") else tr("Off") val openCheck by remember(db) { db.accuracyDao().openFlow() }.collectAsState(initial = null) val accuracyTrailing = openCheck?.let { c -> if (c.state == com.pulseloop.data.entity.AccuracyCheckEntity.STATE_RUNNING) { @@ -126,19 +125,15 @@ fun SettingsScreen( onSetUp = { navigate("pairing") }, ) - // AI COACH — check-ins are a coach sub-feature, only shown once the coach is on. + // AI COACH. Notifications sit under General, not here: most of them (daily guidance, + // battery alerts) work without the coach and were unreachable while it was off. SettingsSection( title = tr("AI Coach"), - rows = buildList { - add(SettingsRowItem(Icons.Filled.AutoAwesome, PulseColors.accent, tr("AI Coach"), coachTrailing) { + rows = listOf( + SettingsRowItem(Icons.Filled.AutoAwesome, PulseColors.accent, tr("AI Coach"), coachTrailing) { navigate("settings/coach") - }) - if (coachEnabled) { - add(SettingsRowItem(Icons.Filled.NotificationsActive, PulseColors.warning, tr("Coach Check-Ins"), notificationsTrailing) { - navigate("settings/checkins") - }) - } - }, + }, + ), ) // GENERAL — Physiology sits under User Profile (iOS SettingsView General group), feeding the @@ -155,6 +150,9 @@ fun SettingsScreen( add(SettingsRowItem(Icons.Filled.MonitorHeart, PulseColors.hrv, tr("Physiology")) { navigate("settings/physiology") }) + add(SettingsRowItem(Icons.Filled.NotificationsActive, PulseColors.warning, tr("Notifications")) { + navigate("settings/checkins") + }) add(SettingsRowItem(Icons.Filled.Language, PulseColors.info, tr("Language"), com.pulseloop.ui.i18n.L10n.language.let { if (it == com.pulseloop.ui.i18n.AppLanguage.SYSTEM) tr("System default") else it.label }) { navigate("settings/language") }) 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 fa7f5791..b92cfa82 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt @@ -875,7 +875,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { AlertDialog( onDismissRequest = { askEnableCheckIns = false }, title = { Text(tr("Enable Coach Check-Ins?")) }, - text = { Text(tr("Get a daily check-in from your coach. You can change this anytime in Coach Check-Ins.")) }, + text = { Text(tr("Get a daily check-in from your coach. You can change this anytime in Settings → Notifications.")) }, confirmButton = { TextButton(onClick = { askEnableCheckIns = false; enableCheckIns() }) { Text(tr("Enable")) } }, @@ -957,16 +957,33 @@ fun CheckInsSettingsScreen(onBack: () -> Unit) { } } - SettingsSubScreen(title = tr("Coach Check-Ins"), onBack = onBack) { - if (!coachEnabled) { - Card(Modifier.fillMaxWidth()) { - Column(Modifier.padding(16.dp)) { - Text(tr("AI Coach is off"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) - Spacer(Modifier.height(4.dp)) + SettingsSubScreen(title = tr("Notifications"), onBack = onBack) { + // Guidance and battery alerts work without the coach, so they lead; the coach's own + // check-ins come last and explain themselves when the coach is off. + DailyGuidanceSettingsCard() + + // Ring battery alerts — independent of the coach toggle (iOS #61a puts this in its own + // NotificationsSettingsView section): a local notification at <20% / <10%, once per day. + Card(Modifier.fillMaxWidth()) { + Column(Modifier.padding(16.dp)) { + Text(tr("Ring battery alerts"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Spacer(Modifier.height(4.dp)) + Text( + tr("Get notified when your ring drops below 20% and 10%, so tracking doesn't stop mid-day."), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(12.dp)) + Row(Modifier.fillMaxWidth() + .switchRow(checked = batteryAlertsEnabled, onCheckedChange = { setBatteryAlerts(it) }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { + Text(tr("Low Battery Notifications"), Modifier.weight(1f)) + Switch(checked = batteryAlertsEnabled, onCheckedChange = null) + } + if (batteryPermDenied) { Text( - tr("Enable the AI Coach to change these — daily check-ins are written by the coach from your recent trends."), + tr("Notifications are disabled for PulseLoop in Android Settings."), style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, + color = PulseColors.danger, ) } } @@ -975,6 +992,14 @@ fun CheckInsSettingsScreen(onBack: () -> Unit) { Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(16.dp)) { Text(tr("Daily check-ins"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + if (!coachEnabled) { + Spacer(Modifier.height(4.dp)) + Text( + tr("Enable the AI Coach to change these — daily check-ins are written by the coach from your recent trends."), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } Spacer(Modifier.height(12.dp)) Row(Modifier.fillMaxWidth() @@ -1053,34 +1078,6 @@ fun CheckInsSettingsScreen(onBack: () -> Unit) { } } - // Ring battery alerts — independent of the coach toggle (iOS #61a puts this in its own - // NotificationsSettingsView section): a local notification at <20% / <10%, once per day. - Card(Modifier.fillMaxWidth()) { - Column(Modifier.padding(16.dp)) { - Text(tr("Ring battery alerts"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) - Spacer(Modifier.height(4.dp)) - Text( - tr("Get notified when your ring drops below 20% and 10%, so tracking doesn't stop mid-day."), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Spacer(Modifier.height(12.dp)) - Row(Modifier.fillMaxWidth() - .switchRow(checked = batteryAlertsEnabled, onCheckedChange = { setBatteryAlerts(it) }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text(tr("Low Battery Notifications"), Modifier.weight(1f)) - Switch(checked = batteryAlertsEnabled, onCheckedChange = null) - } - if (batteryPermDenied) { - Text( - tr("Notifications are disabled for PulseLoop in Android Settings."), - style = MaterialTheme.typography.bodySmall, - color = PulseColors.danger, - ) - } - } - } - - DailyGuidanceSettingsCard() } } @@ -1579,10 +1576,7 @@ fun GoalsSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> Unit) { includeWeeklyWorkouts = true, ) db.userGoalDao().upsert(saved) - com.pulseloop.service.GoalSync.noteEdits(context, saved) - coordinator?.setGoal(draft.steps.toInt()) - // Ring goals drive the widget's activity rings — republish. - com.pulseloop.widgets.WidgetSnapshotPublisher.publish(context) + com.pulseloop.service.GoalSync.afterManualSave(context, saved, coordinator) goalSavedMsg = if (coordinator?.isConnected == true) tr("Saved & sent to ring ✓") else tr("Saved") } @@ -3334,7 +3328,7 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { Text(tr("Health Connect"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(4.dp)) Text( - tr("Export ring data to Health Connect so other apps and dashboards can show it. Write-only: PulseLoop never reads data back."), + tr("Export ring data to Health Connect so other apps and dashboards can show it. Exporting only writes. PulseLoop reads Health Connect only for features you turn on: body data in your profile, Use without a ring, and the accuracy check."), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) diff --git a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt index e3485342..2606655a 100644 --- a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt +++ b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt @@ -622,18 +622,19 @@ class ActivityViewModel(db: PulseLoopDatabase) : ViewModel() { } catch (_: Exception) {} } - suspend fun saveGoals(steps: Int, activeMinutes: Int, sleepMinutes: Int, workoutsPerWeek: Int) { + /** Writes the goals and returns the saved row, for [com.pulseloop.service.GoalSync.afterManualSave]. */ + suspend fun saveGoals(steps: Int, activeMinutes: Int, sleepMinutes: Int, workoutsPerWeek: Int): UserGoalEntity { val existing = try { db.userGoalDao().get() } catch (_: Exception) { null } - db.userGoalDao().upsert( - (existing ?: UserGoalEntity()).copy( - steps = steps, - activeMinutes = activeMinutes, - sleepMinutes = sleepMinutes, - workoutsPerWeek = workoutsPerWeek, - updatedAt = System.currentTimeMillis(), - ), + val saved = (existing ?: UserGoalEntity()).copy( + steps = steps, + activeMinutes = activeMinutes, + sleepMinutes = sleepMinutes, + workoutsPerWeek = workoutsPerWeek, + updatedAt = System.currentTimeMillis(), ) + db.userGoalDao().upsert(saved) reloadGoals() + return saved } } From 978a1a1d89256a6ff9150dd02c17ca4e4ff3ebd6 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 00:20:09 +0000 Subject: [PATCH 2/3] Today: + Log sheet, active programs, Rest Mode; stop repeating sleep and readiness (WIP) Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- .../java/com/pulseloop/ui/LaunchRequests.kt | 3 + .../java/com/pulseloop/ui/PulseLoopApp.kt | 48 +++++- .../java/com/pulseloop/ui/screens/DrinksUi.kt | 4 +- .../java/com/pulseloop/ui/screens/LogSheet.kt | 163 ++++++++++++++++++ .../com/pulseloop/ui/screens/TodayGlance.kt | 48 +----- .../com/pulseloop/ui/screens/TodayPrograms.kt | 132 ++++++++++++++ .../com/pulseloop/ui/screens/TodayScreen.kt | 59 ++++--- 7 files changed, 384 insertions(+), 73 deletions(-) create mode 100644 app/src/main/java/com/pulseloop/ui/screens/LogSheet.kt create mode 100644 app/src/main/java/com/pulseloop/ui/screens/TodayPrograms.kt diff --git a/app/src/main/java/com/pulseloop/ui/LaunchRequests.kt b/app/src/main/java/com/pulseloop/ui/LaunchRequests.kt index 0491dd8b..2a7bcf66 100644 --- a/app/src/main/java/com/pulseloop/ui/LaunchRequests.kt +++ b/app/src/main/java/com/pulseloop/ui/LaunchRequests.kt @@ -16,4 +16,7 @@ object LaunchRequests { /** Today's Workout chip: open the Activity tab with the workout-type picker up. */ val openWorkoutPicker = MutableStateFlow(false) + + /** The app-wide "+ Log" sheet: open at this step, or closed when null. */ + val openLog = MutableStateFlow(null) } diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index 38308e84..f4394585 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -381,8 +381,23 @@ fun PulseLoopApp() { noiseFactor = 0.02f, ) + // "+ Log" on every tab but Coach: recording something is the most frequent job in the + // app, so it sits in the same place whichever tab is open. + val fabEntry by navController.currentBackStackEntryAsState() + val showLogFab = fabEntry?.destination?.route.let { it in tabRoutes && it != "coach" } Scaffold( containerColor = com.pulseloop.ui.theme.PulseColors.background, + floatingActionButton = { + if (showLogFab) { + ExtendedFloatingActionButton( + onClick = { LaunchRequests.openLog.value = com.pulseloop.ui.screens.LogStep.MENU }, + icon = { Icon(Icons.Filled.Add, contentDescription = null) }, + text = { Text(tr("Log"), maxLines = 1) }, + containerColor = com.pulseloop.ui.theme.PulseColors.accent, + contentColor = com.pulseloop.ui.theme.PulseColors.onAccent, + ) + } + }, topBar = { // Shared iOS-style header (PULSELOOP eyebrow + greeting + status pill) on tab // routes only; pushed screens (settings, details, pairing) bring their own bars. @@ -564,6 +579,8 @@ fun PulseLoopApp() { // bars as an opaque floor/ceiling via this per-route padding wrapper. val topPad = padding.calculateTopPadding() val barPad = padding.calculateBottomPadding() + // The four tabs with the "+ Log" button scroll their last card clear of it. + val tabPad = barPad + 72.dp fun androidx.navigation.NavGraphBuilder.paddedComposable( route: String, content: @Composable (androidx.navigation.NavBackStackEntry) -> Unit, @@ -575,10 +592,10 @@ fun PulseLoopApp() { startDestination = "today", modifier = Modifier.hazeSource(hazeState), ) { - composable("today") { TodayScreen(navController, todayVM, coordinator, vitalsVM, sleepVM, topBarPadding = topPad, bottomBarPadding = barPad) } - composable("vitals") { VitalsScreen(navController = navController, viewModel = vitalsVM, coordinator = coordinator, topBarPadding = topPad, bottomBarPadding = barPad) } - composable("sleep") { SleepScreen(navController = navController, viewModel = sleepVM, onOpen = { coordinator.syncSleepNow() }, topBarPadding = topPad, bottomBarPadding = barPad) } - composable("activity") { ActivityScreen(navController = navController, viewModel = activityVM, liveWorkout = liveWorkout, topBarPadding = topPad, bottomBarPadding = barPad) } + composable("today") { TodayScreen(navController, todayVM, coordinator, vitalsVM, sleepVM, topBarPadding = topPad, bottomBarPadding = tabPad) } + composable("vitals") { VitalsScreen(navController = navController, viewModel = vitalsVM, coordinator = coordinator, topBarPadding = topPad, bottomBarPadding = tabPad) } + composable("sleep") { SleepScreen(navController = navController, viewModel = sleepVM, onOpen = { coordinator.syncSleepNow() }, topBarPadding = topPad, bottomBarPadding = tabPad) } + composable("activity") { ActivityScreen(navController = navController, viewModel = activityVM, liveWorkout = liveWorkout, topBarPadding = topPad, bottomBarPadding = tabPad) } paddedComposable("activity_detail/{id}") { backStackEntry -> val id = backStackEntry.arguments?.getString("id") ?: return@paddedComposable WorkoutSummaryScreen(sessionId = id, onBack = { navController.popBackStack() }) @@ -820,6 +837,29 @@ fun PulseLoopApp() { } } + val logStep by LaunchRequests.openLog.collectAsState() + logStep?.let { step -> + fun close() { LaunchRequests.openLog.value = null } + com.pulseloop.ui.screens.LogSheet( + db = db, + start = step, + onDismiss = ::close, + onMeal = { start -> close(); navController.navigate("nutrition/$start") }, + onMoreDrinks = { close(); navController.navigate("drinks") }, + onMeds = { close(); navController.navigate("meds") }, + onPeriod = { close(); navController.navigate("cycle") }, + onWorkout = { + close() + LaunchRequests.openWorkoutPicker.value = true + navController.navigate("activity") { + popUpTo(navController.graph.startDestinationId) + launchSingleTop = true + } + }, + onSeeEffects = { close(); navController.navigate("journal") }, + ) + } + pendingUpdate?.let { info -> com.pulseloop.update.UpdateDialog(info) { // Remember what was dismissed: foreground checks now run every ON_START, and 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 985b47f7..9a8da54d 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt @@ -98,7 +98,7 @@ import kotlin.math.roundToInt private fun std(v: Double) = DrinkInsights.fmt(v) /** Short names for the one-tap buttons; the full label is on the "More" sheet. */ -private val DrinkType.short: String +internal val DrinkType.short: String get() = when (this) { DrinkType.BEER -> tr("Beer") DrinkType.BEER_600 -> tr("600 ml") @@ -110,7 +110,7 @@ private val DrinkType.short: String DrinkType.OTHER -> tr("Other") } -private val DrinkType.icon: ImageVector +internal val DrinkType.icon: ImageVector get() = when (this) { DrinkType.BEER, DrinkType.BEER_600, DrinkType.DRAFT -> Icons.Filled.SportsBar DrinkType.WINE -> Icons.Filled.WineBar diff --git a/app/src/main/java/com/pulseloop/ui/screens/LogSheet.kt b/app/src/main/java/com/pulseloop/ui/screens/LogSheet.kt new file mode 100644 index 00000000..59d5301c --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/screens/LogSheet.kt @@ -0,0 +1,163 @@ +package com.pulseloop.ui.screens + +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +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.CameraAlt +import androidx.compose.material.icons.filled.DirectionsRun +import androidx.compose.material.icons.filled.LocalBar +import androidx.compose.material.icons.filled.LocalOffer +import androidx.compose.material.icons.filled.Medication +import androidx.compose.material.icons.filled.QrCodeScanner +import androidx.compose.material.icons.filled.Restaurant +import androidx.compose.material.icons.filled.WaterDrop +import androidx.compose.material.icons.filled.Add +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Text +import androidx.compose.material3.rememberModalBottomSheetState +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.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.data.entity.DrinkEntryEntity +import com.pulseloop.service.DrinkPrefs +import com.pulseloop.service.DrinksRepository +import com.pulseloop.ui.theme.PulseColors +import kotlinx.coroutines.launch + +/** + * Where a "+ Log" sheet opens. [MENU] lists everything; the others jump straight to one step, for + * the shortcuts on Today. + */ +enum class LogStep { MENU, MEAL, DRINK, TAGS } + +/** + * One place to record anything, reached the same way from every tab: logging is the most frequent + * thing people do in the app, and it used to live on six different screens. + * + * Meals, drinks and day tags are logged inside the sheet. Medications, periods and workouts open + * their own screens, whose first block is the action, because they need more than one tap. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun LogSheet( + db: PulseLoopDatabase, + start: LogStep, + onDismiss: () -> Unit, + onMeal: (start: String) -> Unit, + onMoreDrinks: () -> Unit, + onMeds: () -> Unit, + onPeriod: () -> Unit, + onWorkout: () -> Unit, + onSeeEffects: () -> Unit, +) { + var step by remember(start) { mutableStateOf(start) } + ModalBottomSheet( + onDismissRequest = onDismiss, + sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), + containerColor = PulseColors.secondaryBackground, + ) { + Column( + Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp).padding(bottom = 32.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + when (step) { + LogStep.MENU -> { + Text(tr("Log"), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + SheetOption(tr("Meal"), tr("Photo, barcode or by hand"), Icons.Filled.Restaurant) { step = LogStep.MEAL } + SheetOption(tr("Drink"), tr("One tap for the usual ones"), Icons.Filled.LocalBar) { step = LogStep.DRINK } + SheetOption(tr("Medication or supplement"), tr("Mark today's doses"), Icons.Filled.Medication, onMeds) + SheetOption(tr("Period"), tr("Started or ended today, or a past one"), Icons.Filled.WaterDrop, onPeriod) + SheetOption(tr("Tag your day"), tr("Caffeine, stress, a late meal…"), Icons.Filled.LocalOffer) { step = LogStep.TAGS } + SheetOption(tr("Workout"), tr("Start one now"), Icons.Filled.DirectionsRun, onWorkout) + } + LogStep.MEAL -> { + Text(tr("Log a meal"), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + SheetOption(tr("Photo"), tr("Snap your plate; the AI estimates it"), Icons.Filled.CameraAlt) { onMeal("photo") } + SheetOption(tr("Barcode"), tr("Scan a packaged food"), Icons.Filled.QrCodeScanner) { onMeal("barcode") } + SheetOption(tr("Add by hand"), tr("Type the name and calories"), Icons.Filled.Add) { onMeal("add") } + } + LogStep.DRINK -> QuickDrinks(db, onMoreDrinks) + LogStep.TAGS -> JournalTagsCard(db, java.time.LocalDate.now(), tr("Tag your day"), allowYesterday = true) { + Text( + tr("See what affects you"), + fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, + modifier = Modifier + .heightIn(min = 48.dp) + .clickable(role = Role.Button, onClick = onSeeEffects) + .wrapContentHeight(Alignment.CenterVertically), + ) + } + } + } + } +} + +/** The four usual drinks, one tap each, with an undo; everything else is on the Drinks screen. */ +@Composable +private fun QuickDrinks(db: PulseLoopDatabase, onMore: () -> Unit) { + val scope = rememberCoroutineScope() + // Most-logged first, read once: re-ranking under the user's thumb would move the button they + // are about to tap again. + val types = remember { + DrinksRepository.topTypes(listOf(DrinkPrefs.lastType)) + } + var logged by remember { mutableStateOf>?>(null) } + + Text(tr("Log a drink"), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Row(Modifier.fillMaxWidth().height(IntrinsicSize.Min), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + types.forEach { t -> + val shape = RoundedCornerShape(8.dp) + Column( + Modifier.weight(1f).fillMaxHeight().clip(shape) + .background(PulseColors.card) + .border(1.dp, PulseColors.borderSubtle, shape) + .clickable { + scope.launch { logged = t.short to DrinksRepository.log(db, t) } + } + .padding(horizontal = 4.dp, vertical = 12.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + Icon(t.icon, null, tint = PulseColors.drinks, modifier = Modifier.size(24.dp)) + Text(t.short, fontSize = 11.sp, color = PulseColors.textPrimary, textAlign = TextAlign.Center, maxLines = 2, overflow = TextOverflow.Ellipsis) + } + } + } + // Same height whether or not something was just logged, so the buttons above don't jump. + Row(Modifier.fillMaxWidth().heightIn(min = 48.dp), verticalAlignment = Alignment.CenterVertically) { + val last = logged + Text( + if (last != null) trf("Logged {0}", last.first.lowercase()) else "", + fontSize = 13.sp, color = PulseColors.accent, modifier = Modifier.weight(1f), + maxLines = 1, overflow = TextOverflow.Ellipsis, + ) + if (last != null) { + Text( + tr("Undo"), + fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, + maxLines = 1, + modifier = Modifier.clickable { + scope.launch { last.second.forEach { DrinksRepository.delete(db, it) }; logged = null } + }.padding(12.dp), + ) + } + } + SheetOption(tr("More drinks"), tr("Other types, several at once, or earlier tonight"), Icons.Filled.LocalBar, onMore) +} 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 e5d03b23..eb75f6da 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt @@ -12,11 +12,9 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add -import androidx.compose.material.icons.filled.CameraAlt import androidx.compose.material.icons.filled.DirectionsRun import androidx.compose.material.icons.filled.FavoriteBorder -import androidx.compose.material.icons.filled.LocalOffer -import androidx.compose.material.icons.filled.QrCodeScanner +import androidx.compose.material.icons.filled.LocalBar import androidx.compose.material.icons.filled.Restaurant import androidx.compose.material.icons.filled.Warning import androidx.compose.material3.ExperimentalMaterial3Api @@ -27,7 +25,6 @@ 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 @@ -35,7 +32,6 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp -import com.pulseloop.data.PulseLoopDatabase import com.pulseloop.service.OffSignal import com.pulseloop.ui.theme.PulseColors import com.pulseloop.ui.theme.dither @@ -131,12 +127,12 @@ fun TodayGlance( } } -/** Meal · Tag day · Measure · Workout — the things a user does on Today, one tap each. */ +/** Meal · Drink · Measure · Workout — Today's shortcuts; the "+ Log" button holds the rest. */ @Composable -fun QuickLogRow(onMeal: () -> Unit, onTag: () -> Unit, onMeasure: () -> Unit, onWorkout: () -> Unit) { +fun QuickLogRow(onMeal: () -> Unit, onDrink: () -> Unit, onMeasure: () -> Unit, onWorkout: () -> Unit) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { QuickChip(tr("Meal"), Icons.Filled.Restaurant, PulseColors.calories, Modifier.weight(1f), onMeal) - QuickChip(tr("Tag day"), Icons.Filled.LocalOffer, PulseColors.accent, Modifier.weight(1f), onTag) + QuickChip(tr("Drink"), Icons.Filled.LocalBar, PulseColors.drinks, Modifier.weight(1f), onDrink) QuickChip(tr("Measure"), Icons.Filled.FavoriteBorder, PulseColors.heartRate, Modifier.weight(1f), onMeasure) QuickChip(tr("Workout"), Icons.Filled.DirectionsRun, PulseColors.steps, Modifier.weight(1f), onWorkout) } @@ -210,42 +206,8 @@ fun LastNightCard( } } -/** Meal chip: photo, barcode or a manual entry. */ -@OptIn(ExperimentalMaterial3Api::class) @Composable -fun MealSheet(onDismiss: () -> Unit, onPick: (start: String) -> Unit) { - ModalBottomSheet(onDismissRequest = onDismiss, sheetState = rememberModalBottomSheetState(), containerColor = PulseColors.secondaryBackground) { - Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(bottom = 32.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { - Text(tr("Log a meal"), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - SheetOption(tr("Photo"), tr("Snap your plate; the AI estimates it"), Icons.Filled.CameraAlt) { onPick("photo") } - SheetOption(tr("Barcode"), tr("Scan a packaged food"), Icons.Filled.QrCodeScanner) { onPick("barcode") } - SheetOption(tr("Add by hand"), tr("Type the name and calories"), Icons.Filled.Add) { onPick("add") } - } - } -} - -/** Tag-day chip: every journal tag for today, and the way to the effects. */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun TagDaySheet(db: PulseLoopDatabase, onDismiss: () -> Unit, onSeeEffects: () -> Unit) { - ModalBottomSheet(onDismissRequest = onDismiss, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), containerColor = PulseColors.secondaryBackground) { - Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(bottom = 32.dp)) { - JournalTagsCard(db, java.time.LocalDate.now(), tr("Tag your day"), allowYesterday = true) { - Text( - tr("See what affects you"), - fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, - modifier = Modifier - .heightIn(min = 48.dp) - .clickable(role = Role.Button, onClick = onSeeEffects) - .wrapContentHeight(Alignment.CenterVertically), - ) - } - } - } -} - -@Composable -private fun SheetOption(title: String, subtitle: String, icon: ImageVector, onClick: () -> Unit) { +internal fun SheetOption(title: String, subtitle: String, icon: ImageVector, onClick: () -> Unit) { val shape = RoundedCornerShape(8.dp) Row( Modifier diff --git a/app/src/main/java/com/pulseloop/ui/screens/TodayPrograms.kt b/app/src/main/java/com/pulseloop/ui/screens/TodayPrograms.kt new file mode 100644 index 00000000..7ad95c7d --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayPrograms.kt @@ -0,0 +1,132 @@ +package com.pulseloop.ui.screens + +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf +import androidx.compose.foundation.ExperimentalLayoutApi +import androidx.compose.foundation.FlowRow +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ChildCare +import androidx.compose.material.icons.filled.Medication +import androidx.compose.material.icons.filled.SelfImprovement +import androidx.compose.material.icons.filled.WaterDrop +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +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.vector.ImageVector +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.service.Cycle +import com.pulseloop.service.Meds +import com.pulseloop.service.Postpartum +import com.pulseloop.service.RestMode +import com.pulseloop.ui.theme.PulseColors +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.format.DateTimeFormatter + +/** + * What the user has switched on and uses day to day — cycle, medications, postpartum — one tap + * from Today instead of two levels down under Vitals → My Health. Nothing shows for a program + * that isn't in use, and nothing shows until Room has answered, so a chip never flashes in and + * out on launch. + */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +fun ProgramsRow(db: PulseLoopDatabase, onCycle: () -> Unit, onMeds: () -> Unit, onPostpartum: () -> Unit) { + val today = remember { LocalDate.now() } + val periods by remember(db) { db.periodDao().allFlow() }.collectAsState(initial = null) + val meds by remember(db) { db.medDao().allFlow() }.collectAsState(initial = null) + val answers by remember(db) { db.medDao().dosesSinceFlow(today.toEpochDay()) }.collectAsState(initial = null) + if (periods == null || meds == null || answers == null) return + + val chips = buildList { + if (Postpartum.active()) Postpartum.birthDate?.let { birth -> + add(Chip(Icons.Filled.ChildCare, PulseColors.accent, trf("Postpartum · week {0}", Postpartum.weeksSince(birth, today)), onPostpartum)) + } + Cycle.status(periods!!.map { it.toPeriod() }, today)?.let { s -> + add(Chip(Icons.Filled.WaterDrop, PulseColors.danger, trf("Cycle · day {0}", s.cycleDay), onCycle)) + } + val doses = Meds.dosesOn(today, meds!!.filter { it.active }, answers!!, LocalDateTime.now()) + if (doses.isNotEmpty()) { + val taken = doses.count { it.state == Meds.State.TAKEN } + add(Chip(Icons.Filled.Medication, PulseColors.info, trf("Meds · {0} of {1}", taken, doses.size), onMeds)) + } + } + if (chips.isEmpty()) return + FlowRow(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + chips.forEach { ProgramChip(it) } + } +} + +private data class Chip(val icon: ImageVector, val tint: Color, val label: String, val onClick: () -> Unit) + +@Composable +private fun ProgramChip(c: Chip) { + val shape = RoundedCornerShape(8.dp) + Row( + Modifier + .heightIn(min = 48.dp) + .clip(shape) + .background(PulseColors.card) + .border(1.dp, PulseColors.borderSubtle, shape) + .clickable(onClick = c.onClick) + .padding(horizontal = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Icon(c.icon, null, Modifier.size(18.dp), tint = c.tint) + Text(c.label, fontSize = 13.sp, color = PulseColors.textPrimary, maxLines = 1, overflow = TextOverflow.Ellipsis) + } +} + +/** + * Rest Mode, where the "I'm not well" moment happens. On: say so and offer to end it. Off, and + * last night looked unusual: offer it. Otherwise nothing. + */ +@Composable +fun RestModeLine(offerIt: Boolean) { + val context = LocalContext.current + var until by remember { mutableStateOf(RestMode.until(context)) } + val u = until + if (u == null && !offerIt) return + val shape = RoundedCornerShape(8.dp) + Row( + Modifier.fillMaxWidth().clip(shape).background(PulseColors.card).padding(start = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon(Icons.Filled.SelfImprovement, null, Modifier.size(18.dp), tint = PulseColors.readiness) + Text( + if (u != null) trf("Rest Mode on until {0}", u.format(DateTimeFormatter.ofPattern("EEE d MMM"))) + else tr("Feeling unwell? Pause activity nudges for 3 days."), + fontSize = 13.sp, color = PulseColors.textPrimary, + modifier = Modifier.weight(1f).padding(horizontal = 8.dp, vertical = 12.dp), + ) + Text( + if (u != null) tr("Turn off") else tr("Rest Mode"), + fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.readiness, + maxLines = 1, + modifier = Modifier + .widthIn(max = 140.dp) + .heightIn(min = 48.dp) + .clickable { + RestMode.set(context, if (u != null) null else 3) + until = RestMode.until(context) + } + .wrapContentHeight(Alignment.CenterVertically) + .padding(horizontal = 12.dp), + ) + } +} 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 9742d441..3e42df93 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt @@ -108,13 +108,15 @@ fun TodayScreen( val sleepLoaded = sleepViewModel == null || sleep.loaded val vitalsLoaded = vitalsViewModel == null || vitals.loaded val guidance = rememberGuidance(db, listOf(state.lastUpdated, sleep.lastNight?.id, sleep.lastNight?.updatedAt)) - var mealSheet by remember { mutableStateOf(false) } var briefSheet by remember { mutableStateOf(false) } - var tagSheet by remember { mutableStateOf(false) } + // The "+ Log" sheet is app-wide (PulseLoopApp); Today's shortcuts open it at a step, and + // its closing is what refreshes the food and drinks numbers here. + val logOpen by com.pulseloop.ui.LaunchRequests.openLog.collectAsState() + fun openLog(step: LogStep) { com.pulseloop.ui.LaunchRequests.openLog.value = step } // Today's food log, for the Nutrition tile and the midday food moment. [foodLoaded] tells the // first load apart from "nothing logged", so the tile doesn't flash 0 kcal before it. var foodLoaded by remember { mutableStateOf(false) } - val food by produceState(null, state.lastUpdated, mealSheet) { + val food by produceState(null, state.lastUpdated, logOpen) { value = runCatching { val meals = db.mealEntryDao().byDay(java.time.LocalDate.now().atStartOfDay(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli()) val goal = db.userGoalDao().get() @@ -145,7 +147,7 @@ fun TodayScreen( var drinkTick by remember { mutableIntStateOf(0) } var drinksLoaded by remember { mutableStateOf(false) } val accuracyOpen by remember(db) { db.accuracyDao().openFlow() }.collectAsState(initial = null) - val drinks by produceState(null, state.lastUpdated, sleep.lastNight?.id, drinkTick) { + val drinks by produceState(null, state.lastUpdated, sleep.lastNight?.id, drinkTick, logOpen) { value = if (com.pulseloop.service.DrinkPrefs.enabled) runCatching { com.pulseloop.service.DrinksRepository.load(db) }.getOrNull() else null drinksLoaded = true } @@ -188,7 +190,7 @@ fun TodayScreen( when (card) { DashboardCard.ACTIVITY -> ActivityTileFor(state, units, m, onTap = { navController?.navigate("activity") }, stepFactor = stepFactor) DashboardCard.SLEEP -> SleepTileFor(sleep, m) { navController?.navigate("sleep") } - DashboardCard.NUTRITION -> NutritionTile(food, foodLoaded, m, onLog = { mealSheet = true }) { navController?.navigate("nutrition") } + DashboardCard.NUTRITION -> NutritionTile(food, foodLoaded, m, onLog = { openLog(LogStep.MEAL) }) { navController?.navigate("nutrition") } DashboardCard.DRINKS -> TodayTile(label = tr("Drinks"), color = PulseColors.drinks, modifier = m, onTap = { navController?.navigate("drinks") }) { // The empty tile until the first load, not "0 of 14 this week". if (drinksLoaded) DrinksTileContent( @@ -246,12 +248,17 @@ fun TodayScreen( val alert = guidance?.offSignals?.takeIf { com.pulseloop.service.VitalsCheck.shouldAlert(it) } val summary = state.coachSummary // Until readiness has loaded, the fallback would be the hero's "sync your ring" copy, - // which flashed on every launch before the real sentence replaced it. - val pending = !(coachEnabled && summary != null) && !readinessLoad.loaded + // which flashed on every launch before the real sentence replaced it. Space is held + // only when a coach brief is likely to fill it; without the coach the line is + // usually empty once loaded, and holding it would collapse on every launch. + val pending = coachEnabled && summary == null && !readinessLoad.loaded + // The readiness sentence is already the line under the score rings, so it isn't + // repeated here: this line is for the coach's brief, or the hero copy when there + // is no readiness at all. val insight = when { coachEnabled && summary != null -> listOf(summary.title, summary.body).filter { it.isNotBlank() }.joinToString(". ") - readiness != null -> com.pulseloop.service.ReadinessCopy.headline(readiness) - pending -> null + !readinessLoad.loaded -> null + readiness != null -> null else -> hero.summary } TodayGlance( @@ -267,8 +274,8 @@ fun TodayScreen( // Act: one tap to log, then at most two cards chosen by the time of day. item { QuickLogRow( - onMeal = { mealSheet = true }, - onTag = { tagSheet = true }, + onMeal = { openLog(LogStep.MEAL) }, + onDrink = { openLog(LogStep.DRINK) }, onMeasure = { navController?.navigate("vitals") }, onWorkout = { com.pulseloop.ui.LaunchRequests.openWorkoutPicker.value = true @@ -276,9 +283,25 @@ fun TodayScreen( }, ) } + item { + ProgramsRow( + db = db, + onCycle = { navController?.navigate("cycle") }, + onMeds = { navController?.navigate("meds") }, + onPostpartum = { navController?.navigate("postpartum") }, + ) + } + item { + val unusual = guidance?.offSignals?.let { com.pulseloop.service.VitalsCheck.shouldAlert(it) } == true + RestModeLine(offerIt = unusual) + } val moments = TodayMoments.at( hour = java.time.LocalTime.now().hour, - hasSleep = sleep.lastNight != null, + // The Sleep tile already shows last night, so the morning card only adds itself + // when the tile is hidden or when it carries what the tile can't: what last + // night's drinks did to the night. + hasSleep = sleep.lastNight != null && + (DashboardCard.SLEEP !in visibleOrdered || drinks?.morningAfter != null), // The tile already invites a meal when it is on the grid; the card is for when it isn't. mealsToday = if (DashboardCard.NUTRITION in visibleOrdered) -1 else mealsToday ?: -1, hasBedtime = guidance?.bedtime != null, @@ -375,12 +398,6 @@ fun TodayScreen( item { Spacer(Modifier.height(64.dp)) } } - if (mealSheet) { - MealSheet(onDismiss = { mealSheet = false }) { start -> - mealSheet = false - navController?.navigate("nutrition/$start") - } - } if (briefSheet) { val summary = state.coachSummary val fromCoach = coachEnabled && summary != null @@ -397,12 +414,6 @@ fun TodayScreen( }, ) } - if (tagSheet) { - TagDaySheet(db, onDismiss = { tagSheet = false }) { - tagSheet = false - navController?.navigate("journal") - } - } PullRefreshIndicator( refreshing = isRefreshing, From f10ea36c05d0945003fb30ac094883832a13e8e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 00:20:55 +0000 Subject: [PATCH 3/3] Release 1: + Log sheet, programs and Rest Mode on Today, translations, AGENTS.md IA rules Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- AGENTS.md | 22 +++++++++++++++++++ app/src/main/assets/i18n/pt-BR.json | 14 ++++++++++++ .../java/com/pulseloop/ui/screens/LogSheet.kt | 2 +- .../com/pulseloop/ui/screens/TodayPrograms.kt | 4 ++-- 4 files changed, 39 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e5234d85..a08083e9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1096,3 +1096,25 @@ sources: `docs/postpartum-breastfeeding-research.md`. by the difference between what the stage calls for and what was added before, so weaning or switching off takes exactly that back. - **No F*cking Health jokes here**: postpartum text is on the voice's safety list. + +## Where things live: intent first, then overview → detail + +**Read this before adding a card, a row or a screen.** The app is organised in two layers, and most +clutter came from ignoring one of them: + +- **Where a thing lives follows what the user came to do.** Logging (meal, drink, dose, period, + tags, workout) is one job, so it has one door: the "+ Log" button on every tab but Coach + (`LogSheet`, opened through `LaunchRequests.openLog`). Today's Meal/Drink chips open the same + sheet at a step; don't grow a second logging path on a new screen. Programs the user switched on + (cycle, meds, postpartum) surface on Today (`ProgramsRow`), and Rest Mode is offered where + "I'm unwell" happens (`RestModeLine`), not only in a menu. +- **Inside a screen, summary first, detail on tap.** A screen leads with one summary and its + primary action; everything else is a row that opens. A new section added inline at full weight + is how My Health became a wall. +- **Repeat a figure only when the question differs.** Last night's sleep on Today (am I okay?) and + on Sleep (why?) is fine; the same sleep three times on Today is not. The alcohol-clearance card + on Postpartum stays even though Drinks has one: "can I feed now?" is asked on that screen. +- **Notifications are reachable whether or not the coach is on.** Most of them (daily guidance, + battery alerts) never needed it, and gating the row on the coach hid them all. +- **A goal saved anywhere goes through `GoalSync.afterManualSave`** — it is what stops the field + following the coach, sends the step goal to the ring and republishes the widget. diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index 84323591..48c5ad0f 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -154,6 +154,7 @@ "Aim for an earlier bedtime: you averaged {0} against a {1} goal.": "Tente dormir mais cedo: sua média foi {0} contra uma meta de {1}.", "Aim to be in bed by {0} to get your {1} hours before your usual {2} wake-up.": "Tente estar na cama até {0} para ter suas {1} horas antes do seu despertar habitual às {2}.", "Alcohol": "Álcool", + "Alcohol, stress, a late meal…": "Álcool, estresse, refeição tarde…", "Alcohol: estimated clear for feeding around {0}": "Álcool: estimativa de liberação para amamentar por volta de {0}", "Alcoólicos Anônimos": "Alcoólicos Anônimos", "Alerts when your ring's battery runs low": "Alerta quando a bateria do anel estiver baixa", @@ -383,6 +384,7 @@ "Customize": "Personalizar", "Cycle": "Ciclo", "Cycle of {0} days": "Ciclo de {0} dias", + "Cycle · day {0}": "Ciclo · dia {0}", "Cycle · day {0} · {1}": "Ciclo · dia {0} · {1}", "Cycling": "Ciclismo", "DATA SOURCE": "FONTE DE DADOS", @@ -462,6 +464,7 @@ "Dizziness or fainting": "Tontura ou desmaio", "Done": "Concluído", "Dose (optional)": "Dose (opcional)", + "Drink": "Bebida", "Drink less, sleep better": "Beba menos, durma melhor", "Drink to thirst and keep water where you feed. Ask your clinician about iodine, DHA and your baby's vitamin D. This is no time for a diet.": "Beba conforme a sede e deixe água por perto onde você amamenta. Pergunte ao seu profissional de saúde sobre iodo, DHA e a vitamina D do bebê. Não é hora de fazer dieta.", "Drinks": "Bebidas", @@ -790,6 +793,7 @@ "Loading…": "Carregando…", "Local": "Local", "Location": "Localização", + "Log": "Registrar", "Log Activity": "Registrar atividade", "Log Meal": "Registrar refeição", "Log Past Activity": "Registrar atividade anterior", @@ -835,6 +839,7 @@ "Manage in Android settings": "Gerenciar nas configurações do Android", "Manage or re-grant permissions, and review or delete PulseLoop's data, in the Health Connect app.": "Gerencie ou conceda novamente as permissões e revise ou exclua os dados do PulseLoop no app Health Connect.", "Mandioca cozida": "Mandioca cozida", + "Mark today's doses": "Marque as doses de hoje", "Mask sensitive data": "Mascarar dados sensíveis", "Max": "Máx.", "Max tokens": "Máximo de tokens", @@ -851,10 +856,12 @@ "Measuring… updates when complete": "Medindo… atualiza ao concluir", "Measuring… {0}s": "Medindo… {0}s", "Medication": "Medicamento", + "Medication or supplement": "Medicamento ou suplemento", "Medication reminders": "Lembretes de medicamentos", "Medications & supplements": "Medicamentos e suplementos", "Medicines while breastfeeding": "Medicamentos na amamentação", "Meditation or relaxing": "Meditação ou relaxamento", + "Meds · {0} of {1}": "Remédios · {0} de {1}", "Meet daily goals": "Cumprir metas diárias", "Meetings across the country: aa.org.br": "Reuniões em todo o país: aa.org.br", "Melancia": "Melancia", @@ -881,6 +888,7 @@ "Monthly or less": "Uma vez por mês ou menos", "Mood check-in": "Check-in de humor", "More": "Mais", + "More drinks": "Mais bebidas", "Morning": "Manhã", "Morning type": "Matutino", "Move every hour": "Mexa-se a cada hora", @@ -989,6 +997,7 @@ "Nothing stood out": "Nada se destacou", "Nothing to compare yet. Check back after the first full day and night.": "Nada para comparar ainda. Volte depois do primeiro dia e noite completos.", "Nothing tonight": "Nada esta noite", + "Notifications": "Notificações", "Notifications are disabled for PulseLoop in Android Settings.": "As notificações estão desativadas para o PulseLoop nas Configurações do Android.", "Notifications are off for PulseLoop. Turn them on in Android Settings to get check-ins.": "As notificações estão desativadas para o PulseLoop. Ative-as nas Configurações do Android para receber check-ins.", "Nutrition": "Nutrição", @@ -1003,6 +1012,7 @@ "On until {0}/{1}: activity nudges paused, the coach eases off.": "Ativo até {0}/{1}: lembretes de atividade pausados, o Coach pega mais leve.", "On. PulseLoop syncs your ring about every 30 minutes, even while the phone is idle.": "Ativado. O PulseLoop sincroniza seu anel a cada 30 minutos, mesmo com o celular ocioso.", "Once per dose, at its time, for what you add in My Health → Medications & supplements.": "Uma vez por dose, no horário dela, para o que você adicionar em Minha saúde → Medicamentos e suplementos.", + "One tap for the usual ones": "Um toque para as de sempre", "Only needed if you started the server with --api-key. Leave blank otherwise.": "Só é necessário se você iniciou o servidor com --api-key. Caso contrário, deixe em branco.", "Only new data from now on": "Apenas dados novos daqui em diante", "Only providers that don't retain data": "Apenas provedores que não retêm dados", @@ -1032,6 +1042,7 @@ "Optional. The ring estimates glucose from your profile, not a real sensor. Enter a recent lab/meter reading (mg/dL) to offset the displayed value to match.": "Opcional. O anel estima a glicose a partir do seu perfil, não de um sensor de verdade. Informe uma leitura recente de laboratório/glicosímetro (mg/dL) para ajustar o valor exibido.", "Other": "Outro", "Other ideas": "Outras ideias", + "Other types, several at once, or earlier tonight": "Outros tipos, várias de uma vez ou mais cedo hoje à noite", "Out of sync": "Fora de sincronia", "Outdoor or treadmill runs": "Corridas ao ar livre ou na esteira", "Output tokens": "Tokens de saída", @@ -1062,6 +1073,7 @@ "Permission required": "Permissão obrigatória", "Phases come only from the dates you log. PulseLoop doesn't predict fertile days, and this isn't contraception or a medical tool.": "As fases vêm só das datas que você registra. O PulseLoop não prevê dias férteis, e isto não é um método contraceptivo nem uma ferramenta médica.", "Photo": "Foto", + "Photo, barcode or by hand": "Foto, código de barras ou à mão", "Physiology": "Fisiologia", "Pick the left and right PulseLoop metrics.": "Escolha as métricas do PulseLoop da esquerda e da direita.", "Pick the number before the first drink. It's easier to keep a number you chose beforehand.": "Escolha o número antes da primeira dose. É mais fácil cumprir um número que você definiu antes.", @@ -1347,12 +1359,14 @@ "Start an accuracy check": "Iniciar uma verificação de precisão", "Start check-in": "Começar check-in", "Start one manually when your ring misses an activity.": "Inicie um manualmente quando o anel não registrar uma atividade.", + "Start one now": "Comece um agora", "Start time must be before end time.": "O horário de início deve ser anterior ao de término.", "Start tracking": "Começar a monitorar", "Start using PulseLoop": "Começar a usar o PulseLoop", "Start with recommended targets. You can change these anytime.": "Comece com as metas recomendadas. Você pode alterá-las a qualquer momento.", "Start: {0}": "Início: {0}", "Started": "Iniciado", + "Started or ended today, or a past one": "Começou ou terminou hoje, ou uma anterior", "Starts": "Início", "Steady build": "Evolução constante", "Step progress": "Progresso de passos", diff --git a/app/src/main/java/com/pulseloop/ui/screens/LogSheet.kt b/app/src/main/java/com/pulseloop/ui/screens/LogSheet.kt index 59d5301c..80cd871e 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/LogSheet.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/LogSheet.kt @@ -84,7 +84,7 @@ fun LogSheet( SheetOption(tr("Drink"), tr("One tap for the usual ones"), Icons.Filled.LocalBar) { step = LogStep.DRINK } SheetOption(tr("Medication or supplement"), tr("Mark today's doses"), Icons.Filled.Medication, onMeds) SheetOption(tr("Period"), tr("Started or ended today, or a past one"), Icons.Filled.WaterDrop, onPeriod) - SheetOption(tr("Tag your day"), tr("Caffeine, stress, a late meal…"), Icons.Filled.LocalOffer) { step = LogStep.TAGS } + SheetOption(tr("Tag your day"), tr("Alcohol, stress, a late meal…"), Icons.Filled.LocalOffer) { step = LogStep.TAGS } SheetOption(tr("Workout"), tr("Start one now"), Icons.Filled.DirectionsRun, onWorkout) } LogStep.MEAL -> { diff --git a/app/src/main/java/com/pulseloop/ui/screens/TodayPrograms.kt b/app/src/main/java/com/pulseloop/ui/screens/TodayPrograms.kt index 7ad95c7d..5af711ef 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayPrograms.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayPrograms.kt @@ -2,8 +2,8 @@ package com.pulseloop.ui.screens import com.pulseloop.ui.i18n.tr import com.pulseloop.ui.i18n.trf -import androidx.compose.foundation.ExperimentalLayoutApi -import androidx.compose.foundation.FlowRow +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable