From b4b451a245bf5123eaeb6cdb0f41a5642b02d04b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 11:29:02 +0000 Subject: [PATCH 1/6] Portuguese: translate strings with values and the insight/notification text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Template strings become trf("… {0} …", values) so a translation can move the value; plain literals in services, notifications and widgets go through tr(); enum labels (cycle phases, readiness bands, drink types, med states…) translate in a getter so a language change shows at once. Coach notifications follow the app language too. Catalog entries follow. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- .../accuracy/AccuracyCheckPermissions.kt | 7 +- .../health/accuracy/AccuracyComparison.kt | 5 +- .../notifications/BatteryNotifications.kt | 4 +- .../CoachNotificationDataTrigger.kt | 4 +- .../CoachNotificationSlotRunner.kt | 23 +- .../notifications/CoachNotifications.kt | 4 +- .../pulseloop/notifications/GuidanceWorker.kt | 25 ++- .../NotificationContextBuilder.kt | 8 +- .../notifications/NotificationModels.kt | 5 +- .../pulseloop/service/ActivityDetection.kt | 11 +- .../com/pulseloop/service/ActivityScore.kt | 39 ++-- .../java/com/pulseloop/service/BodyContext.kt | 4 +- .../java/com/pulseloop/service/CardioLoad.kt | 6 +- .../main/java/com/pulseloop/service/Cycle.kt | 8 +- .../com/pulseloop/service/DailyGuidance.kt | 33 +-- .../com/pulseloop/service/DrinkInsights.kt | 40 ++-- .../com/pulseloop/service/DrinksRepository.kt | 19 +- .../java/com/pulseloop/service/Findings.kt | 33 +-- .../java/com/pulseloop/service/GoalPlan.kt | 29 +-- .../java/com/pulseloop/service/GoalSync.kt | 17 +- .../com/pulseloop/service/HealthInsights.kt | 45 +++- .../service/HealthInsightsRepository.kt | 18 +- .../com/pulseloop/service/HeartRateZones.kt | 7 +- .../com/pulseloop/service/JournalInsights.kt | 12 +- .../pulseloop/service/LiveWorkoutManager.kt | 4 +- .../service/ManualActivityService.kt | 8 +- .../java/com/pulseloop/service/MealJournal.kt | 4 +- .../com/pulseloop/service/MealSuggester.kt | 63 +++--- .../main/java/com/pulseloop/service/Meds.kt | 6 +- .../java/com/pulseloop/service/Readiness.kt | 85 +++---- .../pulseloop/service/RingSyncCoordinator.kt | 6 +- .../com/pulseloop/service/ScoresContext.kt | 4 +- .../com/pulseloop/service/SleepInsights.kt | 117 +++++----- .../service/VitalsThresholdEngine.kt | 211 +++++++++--------- .../com/pulseloop/service/VitalsZoneModel.kt | 16 +- .../java/com/pulseloop/service/WeeklyRecap.kt | 14 +- .../service/WorkoutForegroundService.kt | 19 +- .../java/com/pulseloop/settings/UnitSystem.kt | 5 +- .../pulseloop/ui/components/ActivityRings.kt | 6 +- .../com/pulseloop/ui/components/AppChrome.kt | 6 +- .../com/pulseloop/ui/components/Charts.kt | 6 +- .../ui/components/DeviceHeroStatus.kt | 10 +- .../ui/components/MetricThresholds.kt | 86 +++---- .../com/pulseloop/ui/components/TodayTiles.kt | 4 +- .../pulseloop/ui/components/WorkoutMapView.kt | 4 +- .../pulseloop/ui/components/ZoneLineChart.kt | 7 +- .../pulseloop/ui/dashboard/DashboardEdit.kt | 10 +- .../main/java/com/pulseloop/ui/i18n/L10n.kt | 11 + .../com/pulseloop/ui/onboarding/Editors.kt | 18 +- .../pulseloop/ui/screens/AccuracyCheckUi.kt | 30 +-- .../pulseloop/ui/screens/AccuracyReportUi.kt | 44 ++-- .../pulseloop/ui/screens/ActivityScreen.kt | 22 +- .../java/com/pulseloop/ui/screens/BodyUi.kt | 16 +- .../pulseloop/ui/screens/CoachModelPicker.kt | 12 +- .../com/pulseloop/ui/screens/CoachScreen.kt | 4 +- .../pulseloop/ui/screens/CoachUsageSheet.kt | 6 +- .../java/com/pulseloop/ui/screens/CycleUi.kt | 10 +- .../com/pulseloop/ui/screens/DebugScreen.kt | 12 +- .../java/com/pulseloop/ui/screens/DrinksUi.kt | 52 ++--- .../java/com/pulseloop/ui/screens/FoodUi.kt | 8 +- .../com/pulseloop/ui/screens/GuidanceUi.kt | 4 +- .../ui/screens/HealthConnectSourceUi.kt | 18 +- .../com/pulseloop/ui/screens/JournalUi.kt | 6 +- .../pulseloop/ui/screens/MealAnalysisSheet.kt | 20 +- .../java/com/pulseloop/ui/screens/MedsUi.kt | 4 +- .../com/pulseloop/ui/screens/MyHealthUi.kt | 56 ++--- .../pulseloop/ui/screens/NutritionScreen.kt | 14 +- .../pulseloop/ui/screens/OnboardingScreen.kt | 6 +- .../com/pulseloop/ui/screens/PairingScreen.kt | 12 +- .../com/pulseloop/ui/screens/ReadinessUi.kt | 8 +- .../java/com/pulseloop/ui/screens/Screens.kt | 24 +- .../pulseloop/ui/screens/SettingsScreen.kt | 4 +- .../ui/screens/SettingsSubScreens.kt | 66 +++--- .../com/pulseloop/ui/screens/SleepScreen.kt | 30 +-- .../com/pulseloop/ui/screens/TodayGlance.kt | 4 +- .../com/pulseloop/ui/screens/TodayScreen.kt | 8 +- .../com/pulseloop/ui/screens/WhatChangedUi.kt | 4 +- .../ui/screens/WorkoutSummaryScreen.kt | 4 +- .../com/pulseloop/ui/viewmodels/ViewModels.kt | 4 +- .../pulseloop/ui/viewmodels/VitalCardState.kt | 12 +- .../pulseloop/widgets/WidgetConfigActivity.kt | 14 +- .../com/pulseloop/widgets/WidgetMetric.kt | 6 +- .../pulseloop/widgets/WidgetTileRenderer.kt | 16 +- .../ui/i18n/PortugueseCatalogTest.kt | 14 ++ 84 files changed, 978 insertions(+), 732 deletions(-) diff --git a/app/src/main/java/com/pulseloop/health/accuracy/AccuracyCheckPermissions.kt b/app/src/main/java/com/pulseloop/health/accuracy/AccuracyCheckPermissions.kt index bc1140e3..ea06d444 100644 --- a/app/src/main/java/com/pulseloop/health/accuracy/AccuracyCheckPermissions.kt +++ b/app/src/main/java/com/pulseloop/health/accuracy/AccuracyCheckPermissions.kt @@ -1,5 +1,7 @@ package com.pulseloop.health.accuracy +import com.pulseloop.ui.i18n.tr + import androidx.health.connect.client.permission.HealthPermission import androidx.health.connect.client.records.ActiveCaloriesBurnedRecord import androidx.health.connect.client.records.DistanceRecord @@ -16,7 +18,7 @@ import kotlin.reflect.KClass * What the accuracy check can compare, one entry per Health Connect record type it reads * (docs/accuracy-check-plan.md, "Per metric"). Display order. */ -enum class ReferenceMetric(val label: String, val recordType: KClass) { +enum class ReferenceMetric(private val labelEn: String, val recordType: KClass) { STEPS("Steps", StepsRecord::class), DISTANCE("Distance", DistanceRecord::class), ACTIVE_CALORIES("Active calories", ActiveCaloriesBurnedRecord::class), @@ -24,7 +26,8 @@ enum class ReferenceMetric(val label: String, val recordType: KClass RESTING_HEART_RATE("Resting heart rate", RestingHeartRateRecord::class), SLEEP("Sleep", SleepSessionRecord::class), OXYGEN_SATURATION("Blood oxygen", OxygenSaturationRecord::class), - HRV("HRV", HeartRateVariabilityRmssdRecord::class), + HRV("HRV", HeartRateVariabilityRmssdRecord::class); + val label: String get() = tr(labelEn) } /** diff --git a/app/src/main/java/com/pulseloop/health/accuracy/AccuracyComparison.kt b/app/src/main/java/com/pulseloop/health/accuracy/AccuracyComparison.kt index e8c4e376..e3d90038 100644 --- a/app/src/main/java/com/pulseloop/health/accuracy/AccuracyComparison.kt +++ b/app/src/main/java/com/pulseloop/health/accuracy/AccuracyComparison.kt @@ -1,5 +1,7 @@ package com.pulseloop.health.accuracy +import com.pulseloop.ui.i18n.tr + import com.pulseloop.data.entity.AccuracyCheckDayEntity import java.time.Instant import java.time.ZoneId @@ -14,7 +16,7 @@ import kotlin.math.sqrt * are computed differently by every vendor; sleep timing and stages are described, not adjusted). */ enum class ComparisonMetric( - val label: String, + private val labelEn: String, val unit: String, val kind: Kind, val source: ReferenceMetric, @@ -39,6 +41,7 @@ enum class ComparisonMetric( SPO2("Blood oxygen", "%", Kind.PAIRED, ReferenceMetric.OXYGEN_SATURATION, 2.0, false, CorrectionKind.OFFSET, 3, 30), HRV("HRV", "ms", Kind.DAILY, ReferenceMetric.HRV, 10.0, false, null, 3), ; + val label: String get() = tr(labelEn) enum class Kind { DAILY, PAIRED, STAGES } diff --git a/app/src/main/java/com/pulseloop/notifications/BatteryNotifications.kt b/app/src/main/java/com/pulseloop/notifications/BatteryNotifications.kt index 1c3ecc73..e235de66 100644 --- a/app/src/main/java/com/pulseloop/notifications/BatteryNotifications.kt +++ b/app/src/main/java/com/pulseloop/notifications/BatteryNotifications.kt @@ -1,5 +1,7 @@ package com.pulseloop.notifications +import com.pulseloop.ui.i18n.tr + import android.Manifest import android.app.NotificationChannel import android.app.NotificationManager @@ -31,7 +33,7 @@ object BatteryNotifications { val channel = NotificationChannel( CHANNEL_ID, "Ring Battery", NotificationManager.IMPORTANCE_DEFAULT ).apply { - description = "Alerts when your ring's battery runs low" + description = tr("Alerts when your ring's battery runs low") } val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager nm.createNotificationChannel(channel) diff --git a/app/src/main/java/com/pulseloop/notifications/CoachNotificationDataTrigger.kt b/app/src/main/java/com/pulseloop/notifications/CoachNotificationDataTrigger.kt index 522b19cf..7c33ba6f 100644 --- a/app/src/main/java/com/pulseloop/notifications/CoachNotificationDataTrigger.kt +++ b/app/src/main/java/com/pulseloop/notifications/CoachNotificationDataTrigger.kt @@ -1,5 +1,7 @@ package com.pulseloop.notifications +import com.pulseloop.ui.i18n.tr + import android.content.Context import com.pulseloop.ring.PulseEvent import com.pulseloop.ring.PulseEventBus @@ -40,7 +42,7 @@ class CoachNotificationDataTrigger( private val slotRun: suspend () -> CoachNotificationOutcome = runDueSlot ?: { val c = requireNotNull(context) { - "CoachNotificationDataTrigger needs a Context when the production runner is used" + tr("CoachNotificationDataTrigger needs a Context when the production runner is used") } CoachNotificationSlotRunner.forContext(c).runDueSlot() } diff --git a/app/src/main/java/com/pulseloop/notifications/CoachNotificationSlotRunner.kt b/app/src/main/java/com/pulseloop/notifications/CoachNotificationSlotRunner.kt index f7da76ae..1dd1f6d0 100644 --- a/app/src/main/java/com/pulseloop/notifications/CoachNotificationSlotRunner.kt +++ b/app/src/main/java/com/pulseloop/notifications/CoachNotificationSlotRunner.kt @@ -1,5 +1,8 @@ package com.pulseloop.notifications +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf + import android.content.Context import androidx.lifecycle.Lifecycle import androidx.lifecycle.ProcessLifecycleOwner @@ -525,7 +528,7 @@ private class CoachSlotProductionEngine( val input = JsonArray(listOf( JsonObject(mapOf( "role" to JsonPrimitive("system"), - "content" to JsonPrimitive(NotificationPromptBuilder.systemPrompt(slot)), + "content" to JsonPrimitive(NotificationPromptBuilder.systemPrompt(slot) + com.pulseloop.ui.i18n.L10n.coachInstruction()), )), JsonObject(mapOf( "role" to JsonPrimitive("developer"), @@ -574,13 +577,13 @@ private class CoachSlotProductionEngine( val h = sleep.totalMin / 60 val m = sleep.totalMin % 60 CoachNotificationContent( - title = "Good morning$name", - body = "You logged ${h}h ${m}m of sleep. Here's to a strong day — get moving when you can.", + title = trf("Good morning{0}", name), + body = trf("You logged {0}h {1}m of sleep. Here's to a strong day — get moving when you can.", h, m), ) } else { CoachNotificationContent( - title = "Good morning$name", - body = "Ready to start the day? Take a measurement and I'll help you plan it.", + title = trf("Good morning{0}", name), + body = tr("Ready to start the day? Take a measurement and I'll help you plan it."), ) } } @@ -588,15 +591,15 @@ private class CoachSlotProductionEngine( val steps = packet.today.steps if (steps != null) { val goal = packet.goals.stepsDaily - val hit = if (steps >= goal) "You hit your $goal step goal — nice work." else "${goal - steps} steps to your goal." + val hit = if (steps >= goal) trf("You hit your {0} step goal — nice work.", goal) else trf("{0} steps to your goal.", goal - steps) CoachNotificationContent( - title = "Evening check-in", - body = "$steps steps today. $hit Time to start winding down.", + title = tr("Evening check-in"), + body = trf("{0} steps today. {1} Time to start winding down.", steps, hit), ) } else { CoachNotificationContent( - title = "Evening check-in", - body = "How did today feel? Sync your ring and I'll recap your day.", + title = tr("Evening check-in"), + body = tr("How did today feel? Sync your ring and I'll recap your day."), ) } } diff --git a/app/src/main/java/com/pulseloop/notifications/CoachNotifications.kt b/app/src/main/java/com/pulseloop/notifications/CoachNotifications.kt index 85301c04..774acb68 100644 --- a/app/src/main/java/com/pulseloop/notifications/CoachNotifications.kt +++ b/app/src/main/java/com/pulseloop/notifications/CoachNotifications.kt @@ -1,5 +1,7 @@ package com.pulseloop.notifications +import com.pulseloop.ui.i18n.tr + import android.Manifest import android.app.NotificationChannel import android.app.NotificationManager @@ -33,7 +35,7 @@ object CoachNotifications { val channel = NotificationChannel( CHANNEL_ID, "Coach Check-ins", NotificationManager.IMPORTANCE_DEFAULT ).apply { - description = "Daily AI-generated health insights based on your ring data" + description = tr("Daily AI-generated health insights based on your ring data") } val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager nm.createNotificationChannel(channel) diff --git a/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt b/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt index 22155672..02b223c1 100644 --- a/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt +++ b/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt @@ -1,5 +1,8 @@ package com.pulseloop.notifications +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf + import android.Manifest import android.app.NotificationChannel import android.app.NotificationManager @@ -141,8 +144,8 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork // Drinks, for users who track them: the week that is ending, in one line. val drinks = if (com.pulseloop.service.DrinkPrefs.enabled) runCatching { val d = com.pulseloop.service.DrinksRepository.load(db, now, zone) - " Drinks: ${com.pulseloop.service.DrinkInsights.fmt(d.week.standardDrinks)} of ${com.pulseloop.service.DrinkInsights.fmt(d.weeklyLimit)}, " + - "${d.week.dryDays} dry day${if (d.week.dryDays == 1) "" else "s"}." + trf(" Drinks: {0} of {1}, ", com.pulseloop.service.DrinkInsights.fmt(d.week.standardDrinks), com.pulseloop.service.DrinkInsights.fmt(d.weeklyLimit)) + + trf("{0} dry day{1}.", d.week.dryDays, if (d.week.dryDays == 1) "" else "s") }.getOrNull().orEmpty() else "" val body = report + drinks notify(ctx, ID_WEEKLY, title, body) @@ -156,8 +159,8 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork val minsToBed = minutesUntil(local.toLocalTime(), g.bedtime) if (minsToBed in 15..45) { notify( - ctx, ID_BEDTIME, "Time to wind down", - "Aim to be in bed by ${BedtimeGuidance.fmt(g.bedtime)} to get your ${inputs.sleepGoalMinutes / 60} hours before your usual ${BedtimeGuidance.fmt(g.usualWake)} wake-up.", + ctx, ID_BEDTIME, tr("Time to wind down"), + trf("Aim to be in bed by {0} to get your {1} hours before your usual {2} wake-up.", BedtimeGuidance.fmt(g.bedtime), inputs.sleepGoalMinutes / 60, BedtimeGuidance.fmt(g.usualWake)), ) prefs.lastBedtimeReminderDay = today.toString() } @@ -169,7 +172,7 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork val battery = db.deviceDao().currentReal()?.batteryPercent val minsToBed = bedtime?.let { minutesUntil(local.toLocalTime(), it) } if (Nudges.chargeBeforeBed(battery, minsToBed)) { - notify(ctx, ID_BATTERY, "Charge your ring before bed", "It's at $battery%. A short charge now keeps tonight's sleep tracked.") + notify(ctx, ID_BATTERY, tr("Charge your ring before bed"), trf("It's at {0}%. A short charge now keeps tonight's sleep tracked.", battery)) prefs.lastBatteryReminderDay = today.toString() } } @@ -183,7 +186,7 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork val fresh = device?.lastSyncAt?.let { now - it <= 40 * 60_000L } == true && buckets.isNotEmpty() val lastHour = buckets.filter { it.startEpoch >= now - 3_600_000L }.sumOf { it.steps } if (Nudges.inactive(local.hour, lastHour, fresh)) { - notify(ctx, ID_INACTIVE, "Time to move", "Under 100 steps in the last hour. A few minutes on your feet helps your energy and your sleep.") + notify(ctx, ID_INACTIVE, tr("Time to move"), tr("Under 100 steps in the last hour. A few minutes on your feet helps your energy and your sleep.")) prefs.lastInactivityAt = now } } @@ -206,8 +209,8 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork val fresh = due.filter { it.id !in prefs.remindedDoses } if (fresh.isNotEmpty()) { val names = fresh.joinToString(", ") { it.med.name + (it.med.dose?.let { d -> " $d" } ?: "") } - notify(ctx, ID_MEDS, "Time for ${fresh.first().med.name}" + if (fresh.size > 1) " and more" else "", - "$names. Open PulseLoop to mark it taken or skipped.") + notify(ctx, ID_MEDS, trf("Time for {0}", fresh.first().med.name) + if (fresh.size > 1) " and more" else "", + trf("{0}. Open PulseLoop to mark it taken or skipped.", names)) prefs.remindedDoses = (prefs.remindedDoses + fresh.map { it.id }).toList().takeLast(50).toSet() } } @@ -256,7 +259,7 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork private fun createChannel(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel(CHANNEL_ID, "Daily guidance", NotificationManager.IMPORTANCE_DEFAULT).apply { - description = "Unusual-signal alerts, your weekly report and wind-down reminders" + description = tr("Unusual-signal alerts, your weekly report and wind-down reminders") } (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(channel) } @@ -266,7 +269,7 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED - @android.annotation.SuppressLint("MissingPermission") // checked by canNotify before every call + @android.annotation.SuppressLint(tr("MissingPermission")) // checked by canNotify before every call private fun notify(context: Context, id: Int, title: String, body: String, openMealLog: Boolean = false) { val intent = Intent(context, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK @@ -302,7 +305,7 @@ object Nudges { val left = goal - steps val minutes = (left / 100.0).let { kotlin.math.ceil(it).toInt() } return "${"%,d".format(left)} steps to your goal" to - "You're at ${"%,d".format(steps)} of ${"%,d".format(goal)}. About $minutes minutes of walking closes it." + trf("You're at {0} of {1}. About {2} minutes of walking closes it.", "%,d".format(steps), "%,d".format(goal), minutes) } } diff --git a/app/src/main/java/com/pulseloop/notifications/NotificationContextBuilder.kt b/app/src/main/java/com/pulseloop/notifications/NotificationContextBuilder.kt index 574111d7..e429f40f 100644 --- a/app/src/main/java/com/pulseloop/notifications/NotificationContextBuilder.kt +++ b/app/src/main/java/com/pulseloop/notifications/NotificationContextBuilder.kt @@ -1,5 +1,7 @@ package com.pulseloop.notifications +import com.pulseloop.ui.i18n.tr + import com.pulseloop.coach.context.EnvironmentContext import com.pulseloop.ring.MeasurementKind import com.pulseloop.data.PulseLoopDatabase @@ -71,16 +73,16 @@ object NotificationContextBuilder { val warnings = mutableListOf() val profileComplete = profile != null && profile.name != null && profile.age != null && profile.heightCm != null && profile.weightKg != null if (!profileComplete) { - warnings.add("User profile is incomplete — insights may be less personalized.") + warnings.add(tr("User profile is incomplete — insights may be less personalized.")) } // lastFullSyncAt (not lastSyncAt, which the ring re-stamps on every bare CONNECT before // any data streams) — iOS #61c's freshness-gate fix. val lastFullSync = device?.lastFullSyncAt if (lastFullSync != null && (now - lastFullSync) > 12 * 3600_000L) { - warnings.add("Ring hasn't synced in >12h — today's data may be stale.") + warnings.add(tr("Ring hasn't synced in >12h — today's data may be stale.")) } if (hrRows.size < 10) { - warnings.add("Limited HR data available for today.") + warnings.add(tr("Limited HR data available for today.")) } return NotificationContextPacket( diff --git a/app/src/main/java/com/pulseloop/notifications/NotificationModels.kt b/app/src/main/java/com/pulseloop/notifications/NotificationModels.kt index d1e8f87e..a6b71c68 100644 --- a/app/src/main/java/com/pulseloop/notifications/NotificationModels.kt +++ b/app/src/main/java/com/pulseloop/notifications/NotificationModels.kt @@ -1,5 +1,7 @@ package com.pulseloop.notifications +import com.pulseloop.ui.i18n.tr + import com.pulseloop.coach.context.EnvironmentContext /** @@ -10,9 +12,10 @@ import com.pulseloop.coach.context.EnvironmentContext /** * Notification slot types — ported from CoachNotificationSlot.swift. */ -enum class CoachNotificationSlot(val label: String) { +enum class CoachNotificationSlot(private val labelEn: String) { MORNING("Morning"), EVENING("Evening"); + val label: String get() = tr(labelEn) companion object { fun current( diff --git a/app/src/main/java/com/pulseloop/service/ActivityDetection.kt b/app/src/main/java/com/pulseloop/service/ActivityDetection.kt index 44dc566f..184e011b 100644 --- a/app/src/main/java/com/pulseloop/service/ActivityDetection.kt +++ b/app/src/main/java/com/pulseloop/service/ActivityDetection.kt @@ -1,5 +1,8 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf + import android.content.Context import com.pulseloop.data.PulseLoopDatabase import com.pulseloop.ring.MeasurementKind @@ -36,7 +39,7 @@ object ActivityDetection { val s = runStart ?: return if (count >= 2) { val kind = if (fast * 2 > count) Proposal.Kind.RUN else Proposal.Kind.WALK - out += Proposal(kind, s, last + WINDOW, "%,d steps".format(total)) + out += Proposal(kind, s, last + WINDOW, tr("%,d steps").format(total)) } runStart = null; total = 0; fast = 0; count = 0 } @@ -63,7 +66,7 @@ object ActivityDetection { var start: Long? = null; var last = 0L; var peak = 0.0 fun close() { val s = start ?: return - if (last - s >= 20 * 60_000L) out += Proposal(Proposal.Kind.CARDIO, s, last, "Heart rate up to ${peak.toInt()} bpm") + if (last - s >= 20 * 60_000L) out += Proposal(Proposal.Kind.CARDIO, s, last, trf("Heart rate up to {0} bpm", peak.toInt())) start = null; peak = 0.0 } for ((t, bpm) in hr.sortedBy { it.first }) { @@ -88,7 +91,7 @@ object ActivityDetection { fun close() { val s = start ?: return if (last - s >= 25 * 60_000L && n >= 4 && stepsBetween(s, last) < 60) { - out += Proposal(Proposal.Kind.NAP, s, last, "Heart rate stayed at your quiet level with no steps") + out += Proposal(Proposal.Kind.NAP, s, last, tr("Heart rate stayed at your quiet level with no steps")) } start = null; n = 0 } @@ -160,7 +163,7 @@ suspend fun ActivityDetection.accept(c: Context, db: PulseLoopDatabase, p: Activ val tag = JournalInsights.Tag.NAP.key db.journalDao().upsert(com.pulseloop.data.entity.JournalEntryEntity(com.pulseloop.data.entity.JournalEntryEntity.idFor(day, tag), day, tag)) } else { - ManualActivityService.create(db, type, p.startAt, p.minutes.toDouble(), notes = "Detected by PulseLoop and confirmed") + ManualActivityService.create(db, type, p.startAt, p.minutes.toDouble(), notes = tr("Detected by PulseLoop and confirmed")) } answer(c, p) } diff --git a/app/src/main/java/com/pulseloop/service/ActivityScore.kt b/app/src/main/java/com/pulseloop/service/ActivityScore.kt index e18d73c6..2ddc39d2 100644 --- a/app/src/main/java/com/pulseloop/service/ActivityScore.kt +++ b/app/src/main/java/com/pulseloop/service/ActivityScore.kt @@ -1,5 +1,8 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf + import com.pulseloop.data.PulseLoopDatabase import java.time.Instant import java.time.ZoneId @@ -61,10 +64,10 @@ object ActivityScore { if (i.stepGoal <= 0) return null val r = steps.toDouble() / i.stepGoal return ScoreContributor( - "Daily goal", + tr("Daily goal"), Readiness.curve(r, listOf(0.0 to 0.0, 0.5 to 50.0, 0.8 to 80.0, 1.0 to 100.0)), - "%,d of %,d steps".format(steps, i.stepGoal), - "Today's steps against your step goal. It fills up as the day goes on.", + tr("%,d of %,d steps").format(steps, i.stepGoal), + tr("Today's steps against your step goal. It fills up as the day goes on."), 0.25, ) } @@ -74,10 +77,10 @@ object ActivityScore { if (week.size < 3 || i.stepGoal <= 0) return null val met = week.count { it >= i.stepGoal } return ScoreContributor( - "Meet daily goals", + tr("Meet daily goals"), Readiness.curve(met.toDouble(), listOf(0.0 to 20.0, 1.0 to 40.0, 2.0 to 55.0, 3.0 to 70.0, 5.0 to 100.0)), - "Goal met on $met of the last ${week.size} days", - "How many recent days you reached your step goal. Aim for at least 3 days a week, ideally 5 or more.", + trf("Goal met on {0} of the last {1} days", met, week.size), + tr("How many recent days you reached your step goal. Aim for at least 3 days a week, ideally 5 or more."), 0.20, ) } @@ -92,10 +95,10 @@ object ActivityScore { .mapValues { (_, b) -> b.sumOf { it.second } } val inactive = hours.count { (byHour[it] ?: 0) < ACTIVE_HOUR_STEPS } return ScoreContributor( - "Move every hour", + tr("Move every hour"), Readiness.curve(inactive.toDouble(), listOf(0.0 to 100.0, 1.0 to 90.0, 3.0 to 70.0, 5.0 to 45.0, 8.0 to 10.0)), - if (inactive == 0) "Active every hour since ${DAY_START_HOUR}:00" else "$inactive inactive ${if (inactive == 1) "hour" else "hours"} since ${DAY_START_HOUR}:00", - "Long stretches without moving are linked to poorer health, even on days you exercise. A short walk every hour helps.", + if (inactive == 0) trf("Active every hour since {0}:00", DAY_START_HOUR) else trf("{0} inactive {1} since {2}:00", inactive, if (inactive == 1) tr("hour") else tr("hours"), DAY_START_HOUR), + tr("Long stretches without moving are linked to poorer health, even on days you exercise. A short walk every hour helps."), 0.15, ) } @@ -105,10 +108,10 @@ object ActivityScore { internal fun trainingFrequency(i: Inputs): ScoreContributor { val n = recentWorkouts(i).size return ScoreContributor( - "Training frequency", + tr("Training frequency"), Readiness.curve(n.toDouble(), listOf(0.0 to 30.0, 1.0 to 55.0, 2.0 to 75.0, 3.0 to 100.0)), - "$n ${if (n == 1) "workout" else "workouts"} in the last 7 days", - "How often you exercised this week. Three or more sessions a week is a good target.", + trf("{0} {1} in the last 7 days", n, if (n == 1) tr("workout") else tr("workouts")), + tr("How often you exercised this week. Three or more sessions a week is a good target."), 0.15, ) } @@ -116,10 +119,10 @@ object ActivityScore { internal fun trainingVolume(i: Inputs): ScoreContributor { val minutes = recentWorkouts(i).sumOf { it.minutes } return ScoreContributor( - "Training volume", + tr("Training volume"), Readiness.curve(minutes.toDouble(), listOf(0.0 to 30.0, 60.0 to 60.0, 150.0 to 100.0)), - "${SleepFormat.duration(minutes)} of exercise in the last 7 days", - "Total workout time this week. Health guidelines suggest at least 150 minutes of moderate activity a week.", + trf("{0} of exercise in the last 7 days", SleepFormat.duration(minutes)), + tr("Total workout time this week. Health guidelines suggest at least 150 minutes of moderate activity a week."), 0.15, ) } @@ -128,10 +131,10 @@ object ActivityScore { val days = recentWorkouts(i).map { Instant.ofEpochMilli(it.startAt).atZone(i.zone).toLocalDate() }.toSet().size val rest = 7 - days return ScoreContributor( - "Recovery time", + tr("Recovery time"), Readiness.curve(rest.toDouble(), listOf(0.0 to 50.0, 1.0 to 80.0, 2.0 to 100.0)), - "$rest rest ${if (rest == 1) "day" else "days"} in the last 7", - "Rest days let your body adapt to training. One or two easier days a week is enough for most people.", + trf("{0} rest {1} in the last 7", rest, if (rest == 1) tr("day") else tr("days")), + tr("Rest days let your body adapt to training. One or two easier days a week is enough for most people."), 0.10, ) } diff --git a/app/src/main/java/com/pulseloop/service/BodyContext.kt b/app/src/main/java/com/pulseloop/service/BodyContext.kt index 6c172062..b2a8cff9 100644 --- a/app/src/main/java/com/pulseloop/service/BodyContext.kt +++ b/app/src/main/java/com/pulseloop/service/BodyContext.kt @@ -1,5 +1,7 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr + import com.pulseloop.data.PulseLoopDatabase import com.pulseloop.data.entity.BodyMeasurementEntity import kotlinx.serialization.Serializable @@ -16,7 +18,7 @@ data class BodyContext( val weightChange30dKg: Double, val weighIns30d: Int, val bodyFatPct: Double? = null, - val note: String = "From the user's smart scale via Health Connect. Day-to-day weight swings are mostly water; talk about the trend only.", + val note: String = tr("From the user's smart scale via Health Connect. Day-to-day weight swings are mostly water; talk about the trend only."), ) { companion object { suspend fun build(db: PulseLoopDatabase, now: Long = System.currentTimeMillis()): BodyContext? = runCatching { diff --git a/app/src/main/java/com/pulseloop/service/CardioLoad.kt b/app/src/main/java/com/pulseloop/service/CardioLoad.kt index 7b145e3c..b84fa989 100644 --- a/app/src/main/java/com/pulseloop/service/CardioLoad.kt +++ b/app/src/main/java/com/pulseloop/service/CardioLoad.kt @@ -1,5 +1,7 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr + import java.time.Instant import java.time.LocalDate import java.time.ZoneId @@ -18,7 +20,9 @@ object CardioLoad { const val MIN_QUIET_DAYS = 3 private const val MAX_GAP_MIN = 30.0 - enum class Band(val label: String) { LIGHT("Light"), USUAL("Usual"), HIGH("High"), VERY_HIGH("Very high") } + enum class Band(private val labelEn: String) { LIGHT("Light"), USUAL("Usual"), HIGH("High"), VERY_HIGH("Very high"); + val label: String get() = tr(labelEn) + } data class Result(val load: Int, val quietHr: Int, val usual: Int?, val band: Band?, val elevatedMinutes: Int) diff --git a/app/src/main/java/com/pulseloop/service/Cycle.kt b/app/src/main/java/com/pulseloop/service/Cycle.kt index b11b3b5d..fccb4037 100644 --- a/app/src/main/java/com/pulseloop/service/Cycle.kt +++ b/app/src/main/java/com/pulseloop/service/Cycle.kt @@ -1,5 +1,7 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr + import java.time.LocalDate import java.time.temporal.ChronoUnit @@ -10,12 +12,14 @@ import java.time.temporal.ChronoUnit * screen would be read as a measurement. */ object Cycle { - enum class Phase(val label: String, val note: String) { + enum class Phase(private val labelEn: String, private val noteEn: String) { MENSTRUAL("Period", "Energy and sleep can dip; resting heart rate is often at its lowest."), FOLLICULAR("Follicular", "After the period, until about two weeks before the next one."), LUTEAL("Luteal", "The two weeks before a period: skin temperature and resting heart rate often run a little higher."), LATE("Period later than usual", "Later than your usual cycle length. Log it when it starts."), - UNKNOWN("Cycle", "Log two periods to see phases and an estimate of the next one."), + UNKNOWN("Cycle", "Log two periods to see phases and an estimate of the next one."); + val label: String get() = tr(labelEn) + val note: String get() = tr(noteEn) } data class Period(val start: LocalDate, val end: LocalDate?) diff --git a/app/src/main/java/com/pulseloop/service/DailyGuidance.kt b/app/src/main/java/com/pulseloop/service/DailyGuidance.kt index 9548c57c..35132585 100644 --- a/app/src/main/java/com/pulseloop/service/DailyGuidance.kt +++ b/app/src/main/java/com/pulseloop/service/DailyGuidance.kt @@ -1,5 +1,8 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf + import java.time.Instant import java.time.LocalTime import java.time.ZoneId @@ -40,15 +43,15 @@ object VitalsCheck { val usual = percentile(sorted, 0.5) val fmt = { v: Double -> if (unit == "h") SleepFormat.duration((v * 60).roundToInt()) else "${v.roundToInt()}$unit" } when { - value > hi && higherIsWorse -> out += OffSignal(title, "${fmt(value)}, higher than your usual ${fmt(usual)}") - value < lo && !higherIsWorse -> out += OffSignal(title, "${fmt(value)}, lower than your usual ${fmt(usual)}") + value > hi && higherIsWorse -> out += OffSignal(title, trf("{0}, higher than your usual {1}", fmt(value), fmt(usual))) + value < lo && !higherIsWorse -> out += OffSignal(title, trf("{0}, lower than your usual {1}", fmt(value), fmt(usual))) } } - check("Resting heart rate", lastNight.restingHr, history.mapNotNull { it.restingHr }, " bpm", higherIsWorse = true, minDelta = 2.0) + check(tr("Resting heart rate"), lastNight.restingHr, history.mapNotNull { it.restingHr }, " bpm", higherIsWorse = true, minDelta = 2.0) check("HRV", lastNight.hrv, history.mapNotNull { it.hrv }, " ms", higherIsWorse = false, minDelta = 3.0) - check("Blood oxygen", lastNight.spo2, history.mapNotNull { it.spo2 }, "%", higherIsWorse = false, minDelta = 1.0) + check(tr("Blood oxygen"), lastNight.spo2, history.mapNotNull { it.spo2 }, "%", higherIsWorse = false, minDelta = 1.0) check( - "Sleep", lastNight.asleepMinutes.takeIf { it > 0 }?.let { it / 60.0 }, + tr("Sleep"), lastNight.asleepMinutes.takeIf { it > 0 }?.let { it / 60.0 }, history.filter { it.asleepMinutes > 0 }.map { it.asleepMinutes / 60.0 }, "h", higherIsWorse = false, minDelta = 0.5, ) return out @@ -57,7 +60,7 @@ object VitalsCheck { fun shouldAlert(signals: List) = signals.size >= ALERT_THRESHOLD fun alertText(signals: List): Pair = - "Some of your signals look unusual" to + tr("Some of your signals look unusual") to signals.joinToString("; ") { "${it.title}: ${it.detail}" } + ". This can happen with illness, stress, alcohol or a hard day. Consider taking it easy." } @@ -134,36 +137,36 @@ object WeeklyReport { thisWeek.avgAsleepMinutes?.let { now -> val prev = lastWeek?.avgAsleepMinutes - lines += "Sleep ${SleepFormat.duration(now)} a night" + (prev?.let { " (${signed(now - it)} min vs last week)" } ?: "") + lines += trf("Sleep {0} a night", SleepFormat.duration(now)) + (prev?.let { trf(" ({0} min vs last week)", signed(now - it)) } ?: "") val short = (sleepGoalMinutes - now).toDouble() / sleepGoalMinutes - if (short > 0.1 && short > worst) { worst = short; focus = "Aim for an earlier bedtime: you averaged ${SleepFormat.duration(now)} against a ${SleepFormat.duration(sleepGoalMinutes)} goal." } + if (short > 0.1 && short > worst) { worst = short; focus = trf("Aim for an earlier bedtime: you averaged {0} against a {1} goal.", SleepFormat.duration(now), SleepFormat.duration(sleepGoalMinutes)) } } thisWeek.avgRestingHr?.let { now -> val prev = lastWeek?.avgRestingHr - lines += "Resting heart rate ${now.roundToInt()} bpm" + (prev?.let { " (${signed((now - it).roundToInt())} vs last week)" } ?: "") + lines += trf("Resting heart rate {0} bpm", now.roundToInt()) + (prev?.let { trf(" ({0} vs last week)", signed((now - it).roundToInt())) } ?: "") if (prev != null) { val rise = (now - prev) / prev - if (rise > 0.05 && rise > worst) { worst = rise; focus = "Your resting heart rate is up on last week. Prioritise recovery and sleep." } + if (rise > 0.05 && rise > worst) { worst = rise; focus = tr("Your resting heart rate is up on last week. Prioritise recovery and sleep.") } } } thisWeek.avgHrv?.let { now -> val prev = lastWeek?.avgHrv - lines += "HRV ${now.roundToInt()} ms" + (prev?.let { " (${signed((now - it).roundToInt())} vs last week)" } ?: "") + lines += "HRV ${now.roundToInt()} ms" + (prev?.let { trf(" ({0} vs last week)", signed((now - it).roundToInt())) } ?: "") if (prev != null && prev > 0) { val drop = (prev - now) / prev - if (drop > 0.1 && drop > worst) { worst = drop; focus = "Your HRV dipped this week. Lighter days and consistent sleep help it recover." } + if (drop > 0.1 && drop > worst) { worst = drop; focus = tr("Your HRV dipped this week. Lighter days and consistent sleep help it recover.") } } } thisWeek.avgSteps?.let { now -> val prev = lastWeek?.avgSteps - lines += "%,d steps a day".format(now) + (prev?.let { " (${signed(now - it)} vs last week)" } ?: "") + lines += tr("%,d steps a day").format(now) + (prev?.let { trf(" ({0} vs last week)", signed(now - it)) } ?: "") if (prev != null && prev > 0) { val drop = (prev - now).toDouble() / prev - if (drop > 0.15 && drop > worst) { worst = drop; focus = "You moved less than last week. A daily walk is an easy way back." } + if (drop > 0.15 && drop > worst) { worst = drop; focus = tr("You moved less than last week. A daily walk is an easy way back.") } } } if (lines.isEmpty()) return null - val body = lines.joinToString(". ") + ". " + (focus ?: "A steady week. Keep it up.") + val body = lines.joinToString(". ") + ". " + (focus ?: tr("A steady week. Keep it up.")) return "Your week in review" to body } diff --git a/app/src/main/java/com/pulseloop/service/DrinkInsights.kt b/app/src/main/java/com/pulseloop/service/DrinkInsights.kt index 976f80a1..8932c732 100644 --- a/app/src/main/java/com/pulseloop/service/DrinkInsights.kt +++ b/app/src/main/java/com/pulseloop/service/DrinkInsights.kt @@ -1,5 +1,8 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf + import java.time.DayOfWeek import java.time.LocalDate import kotlin.math.roundToInt @@ -12,7 +15,7 @@ import kotlin.math.roundToInt /** A drink as logged, with typical Brazilian and international sizes. */ /** [carbsG] per drink, rough label values, so a drink logged from the Drinks card fills the meal log's macros too. */ -enum class DrinkType(val key: String, val label: String, val volumeMl: Double, val abvPct: Double, val kcal: Double, val carbsG: Double = 0.0) { +enum class DrinkType(val key: String, private val labelEn: String, val volumeMl: Double, val abvPct: Double, val kcal: Double, val carbsG: Double = 0.0) { BEER("beer", "Beer (can)", 350.0, 5.0, 150.0, 12.0), BEER_600("beer_600", "Beer (600 ml)", 600.0, 5.0, 255.0, 21.0), DRAFT("draft", "Chopp", 300.0, 5.0, 130.0, 11.0), @@ -21,6 +24,7 @@ enum class DrinkType(val key: String, val label: String, val volumeMl: Double, v CAIPIRINHA("caipirinha", "Caipirinha", 50.0, 40.0, 240.0, 25.0), COCKTAIL("cocktail", "Cocktail", 50.0, 40.0, 200.0, 15.0), OTHER("other", "Cider / other", 330.0, 4.5, 140.0, 12.0); + val label: String get() = tr(labelEn) val grams: Double get() = DrinkInsights.grams(volumeMl, abvPct) @@ -116,21 +120,21 @@ object DrinkInsights { fun headline(week: Week, limit: Double, dryTarget: Int, today: LocalDate): Pair { val total = week.standardDrinks val title = when { - limit <= 0 -> if (total <= 0) "No drinks this week" else "${fmt(total)} drinks this week" - total > limit -> "${fmt(total - limit)} over your limit" - total <= 0 -> "No drinks yet this week" - limit - total < 0.05 -> "Right at your limit" - else -> "${fmt(limit - total)} left this week" + limit <= 0 -> if (total <= 0) tr("No drinks this week") else trf("{0} drinks this week", fmt(total)) + total > limit -> trf("{0} over your limit", fmt(total - limit)) + total <= 0 -> tr("No drinks yet this week") + limit - total < 0.05 -> tr("Right at your limit") + else -> trf("{0} left this week", fmt(limit - total)) } // Days still to come this week, today included, while today is still dry. val daysLeft = 7 - (today.dayOfWeek.value - 1) val canStillBeDry = if (week.drankToday) daysLeft - 1 else daysLeft val needed = (dryTarget - week.dryDays).coerceAtLeast(0) val sub = when { - dryTarget <= 0 -> "${week.dryDays} dry day${if (week.dryDays == 1) "" else "s"} so far" - needed == 0 -> "Dry-day goal reached: ${week.dryDays} of $dryTarget" - needed <= canStillBeDry -> "$needed more dry day${if (needed == 1) "" else "s"} to reach $dryTarget" - else -> "${week.dryDays} of $dryTarget dry days; a fresh week starts Monday" + dryTarget <= 0 -> trf("{0} dry day{1} so far", week.dryDays, if (week.dryDays == 1) "" else "s") + needed == 0 -> trf("Dry-day goal reached: {0} of {1}", week.dryDays, dryTarget) + needed <= canStillBeDry -> trf("{0} more dry day{1} to reach {2}", needed, if (needed == 1) "" else "s", dryTarget) + else -> trf("{0} of {1} dry days; a fresh week starts Monday", week.dryDays, dryTarget) } return title to sub } @@ -278,17 +282,19 @@ object DrinkInsights { object AuditC { val QUESTIONS = listOf( "How often do you have a drink containing alcohol?" to listOf( - "Never", "Monthly or less", "2–4 times a month", "2–3 times a week", "4 or more times a week", + tr("Never"), tr("Monthly or less"), tr("2–4 times a month"), tr("2–3 times a week"), tr("4 or more times a week"), ), "How many standard drinks do you have on a typical day when you are drinking?" to listOf( - "1 or 2", "3 or 4", "5 or 6", "7 to 9", "10 or more", + tr("1 or 2"), tr("3 or 4"), tr("5 or 6"), tr("7 to 9"), tr("10 or more"), ), "How often do you have six or more drinks on one occasion?" to listOf( - "Never", "Less than monthly", "Monthly", "Weekly", "Daily or almost daily", + tr("Never"), tr("Less than monthly"), tr("Monthly"), tr("Weekly"), tr("Daily or almost daily"), ), ) - enum class Level(val label: String) { LOW("Lower risk"), INCREASING("Increasing risk"), HIGHER("Higher risk") } + enum class Level(private val labelEn: String) { LOW("Lower risk"), INCREASING("Increasing risk"), HIGHER("Higher risk"); + val label: String get() = tr(labelEn) + } /** Retake after this many days. */ const val RETAKE_DAYS = 90L @@ -306,8 +312,8 @@ object AuditC { } fun advice(level: Level): String = when (level) { - Level.LOW -> "Your answers suggest lower-risk drinking. Keeping some dry days each week helps keep it that way." - Level.INCREASING -> "Your answers suggest drinking at a level that raises health risks. Cutting down gradually, with a weekly limit and dry days, is the usual first step." - Level.HIGHER -> "Your answers suggest drinking at a level that is likely affecting your health. Please talk to a doctor. If you drink most days, don't stop all at once: stopping suddenly can be dangerous, and a doctor can help you cut down safely." + Level.LOW -> tr("Your answers suggest lower-risk drinking. Keeping some dry days each week helps keep it that way.") + Level.INCREASING -> tr("Your answers suggest drinking at a level that raises health risks. Cutting down gradually, with a weekly limit and dry days, is the usual first step.") + Level.HIGHER -> tr("Your answers suggest drinking at a level that is likely affecting your health. Please talk to a doctor. If you drink most days, don't stop all at once: stopping suddenly can be dangerous, and a doctor can help you cut down safely.") } } diff --git a/app/src/main/java/com/pulseloop/service/DrinksRepository.kt b/app/src/main/java/com/pulseloop/service/DrinksRepository.kt index d4ef813e..d8add452 100644 --- a/app/src/main/java/com/pulseloop/service/DrinksRepository.kt +++ b/app/src/main/java/com/pulseloop/service/DrinksRepository.kt @@ -1,5 +1,8 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf + import android.content.Context import android.content.SharedPreferences import com.pulseloop.data.PulseLoopDatabase @@ -276,16 +279,16 @@ object DrinksRepository { /** One line for a morning-after card or notification, null when there's nothing honest to say. */ fun morningAfterLine(m: DrinkInsights.MorningAfter): String { - val drinks = "${DrinkInsights.fmt(m.standardDrinks)} drink${if (m.standardDrinks == 1.0) "" else "s"}" + val drinks = trf("{0} drink{1}", DrinkInsights.fmt(m.standardDrinks), if (m.standardDrinks == 1.0) "" else "s") val parts = buildList { - m.impact.hrvPct?.let { add("HRV ${kotlin.math.abs(it)}% ${if (it < 0) "below" else "above"} your dry nights") } - m.impact.restingHr?.let { if (it != 0) add("resting heart rate ${if (it > 0) "+" else ""}$it bpm") } - m.impact.asleepMinutes?.let { if (kotlin.math.abs(it) >= 10) add("${kotlin.math.abs(it)} min ${if (it < 0) "less" else "more"} sleep") } + m.impact.hrvPct?.let { add(trf("HRV {0}% {1} your dry nights", kotlin.math.abs(it), if (it < 0) tr("below") else tr("above"))) } + m.impact.restingHr?.let { if (it != 0) add(trf("resting heart rate {0}{1} bpm", if (it > 0) "+" else "", it)) } + m.impact.asleepMinutes?.let { if (kotlin.math.abs(it) >= 10) add(trf("{0} min {1} sleep", kotlin.math.abs(it), if (it < 0) tr("less") else tr("more"))) } } return if (parts.isEmpty()) { - if (m.dryNights < DrinkInsights.MIN_NIGHTS) "Last night: $drinks. A few dry nights will show what it does to you." - else "Last night: $drinks. Your night looked close to your dry ones." - } else "Last night: $drinks. ${parts.joinToString(", ").replaceFirstChar { it.uppercase() }}." + if (m.dryNights < DrinkInsights.MIN_NIGHTS) trf("Last night: {0}. A few dry nights will show what it does to you.", drinks) + else trf("Last night: {0}. Your night looked close to your dry ones.", drinks) + } else trf("Last night: {0}. {1}.", drinks, parts.joinToString(", ").replaceFirstChar { it.uppercase() }) } } @@ -302,7 +305,7 @@ data class DrinksContext( val lastNightStandardDrinks: Double? = null, val lastNightEffect: String? = null, val standardDrinkGrams: Double, - val note: String = "Drinks the user logged themselves, in standard drinks of the given grams. Effects compare the user's own nights after drinking with their dry nights; a pattern, not proof.", + val note: String = tr("Drinks the user logged themselves, in standard drinks of the given grams. Effects compare the user's own nights after drinking with their dry nights; a pattern, not proof."), ) { companion object { suspend fun build(db: PulseLoopDatabase, now: Long = System.currentTimeMillis()): DrinksContext? { diff --git a/app/src/main/java/com/pulseloop/service/Findings.kt b/app/src/main/java/com/pulseloop/service/Findings.kt index 0ca598c4..4fd9469f 100644 --- a/app/src/main/java/com/pulseloop/service/Findings.kt +++ b/app/src/main/java/com/pulseloop/service/Findings.kt @@ -1,5 +1,8 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf + import java.time.LocalDate import kotlin.math.abs import kotlin.math.roundToInt @@ -62,8 +65,8 @@ object Findings { val m = median(now)!!; val b = median(base)!! val delta = m - b if (delta >= 3 && delta >= 2 * mad(base, 1.0)) { - out += Finding(day, Finding.Kind.RESTING_HR_UP, "Resting heart rate up", - "${m.roundToInt()} bpm over the last 3 nights against your usual ${b.roundToInt()}. Illness, alcohol, stress, heat or hard training can all raise it.") + out += Finding(day, Finding.Kind.RESTING_HR_UP, tr("Resting heart rate up"), + trf("{0} bpm over the last 3 nights against your usual {1}. Illness, alcohol, stress, heat or hard training can all raise it.", m.roundToInt(), b.roundToInt())) } } // Resting heart rate trending down over two weeks: usually fitness or recovery. @@ -73,8 +76,8 @@ object Findings { if (now.size < 10 || base.size < MIN_BASELINE) return@run val delta = median(now)!! - median(base)!! if (delta <= -3) { - out += Finding(day, Finding.Kind.RESTING_HR_DOWN, "Resting heart rate trending down", - "${abs(delta).roundToInt()} bpm lower over two weeks than the four before. Often a sign of improving fitness or recovery.") + out += Finding(day, Finding.Kind.RESTING_HR_DOWN, tr("Resting heart rate trending down"), + trf("{0} bpm lower over two weeks than the four before. Often a sign of improving fitness or recovery.", abs(delta).roundToInt())) } } // HRV: the last 3 nights against the 28 before. @@ -85,8 +88,8 @@ object Findings { val m = median(now)!!; val b = median(base)!! if (b <= 0) return@run if (m <= b * 0.85 && b - m >= 2 * mad(base, 2.0)) { - out += Finding(day, Finding.Kind.HRV_DOWN, "HRV lower than usual", - "${m.roundToInt()} ms over the last 3 nights against your usual ${b.roundToInt()} (${((m - b) / b * 100).roundToInt()}%). Your body may be under extra load.") + out += Finding(day, Finding.Kind.HRV_DOWN, tr("HRV lower than usual"), + trf("{0} ms over the last 3 nights against your usual {1} ({2}%). Your body may be under extra load.", m.roundToInt(), b.roundToInt(), ((m - b) / b * 100).roundToInt())) } } run { @@ -95,8 +98,8 @@ object Findings { if (now.size < 10 || base.size < MIN_BASELINE) return@run val m = median(now)!!; val b = median(base)!! if (b > 0 && m >= b * 1.10) { - out += Finding(day, Finding.Kind.HRV_UP, "HRV trending up", - "${((m - b) / b * 100).roundToInt()}% higher over two weeks than the four before.") + out += Finding(day, Finding.Kind.HRV_UP, tr("HRV trending up"), + trf("{0}% higher over two weeks than the four before.", ((m - b) / b * 100).roundToInt())) } } // Skin temperature: last night against the 28 before. @@ -107,8 +110,8 @@ object Findings { val b = median(base)!! val delta = t - b if (delta >= 0.5 && delta >= 2 * mad(base, 0.1)) { - out += Finding(day, Finding.Kind.TEMPERATURE_UP, "Skin temperature up", - "+%.1f °C last night against your usual. Can come with illness, a late workout, alcohol or the menstrual cycle.".format(delta)) + out += Finding(day, Finding.Kind.TEMPERATURE_UP, tr("Skin temperature up"), + tr("+%.1f °C last night against your usual. Can come with illness, a late workout, alcohol or the menstrual cycle.").format(delta)) } } // Sleep: the last 7 nights against the 28 before. @@ -118,15 +121,15 @@ object Findings { if (now.size < 5 || base.size < MIN_BASELINE) return@run val delta = now.average() - median(base)!! if (delta <= -45) { - out += Finding(day, Finding.Kind.SLEEP_SHORT, "Sleeping less this week", - "${abs(delta).roundToInt()} min a night less than your usual over the last 7 nights.") + out += Finding(day, Finding.Kind.SLEEP_SHORT, tr("Sleeping less this week"), + trf("{0} min a night less than your usual over the last 7 nights.", abs(delta).roundToInt())) } else if (delta >= 45) { - out += Finding(day, Finding.Kind.SLEEP_LONGER, "Sleeping more this week", - "${delta.roundToInt()} min a night more than your usual over the last 7 nights.") + out += Finding(day, Finding.Kind.SLEEP_LONGER, tr("Sleeping more this week"), + trf("{0} min a night more than your usual over the last 7 nights.", delta.roundToInt())) } } if (radar != null && radar != SymptomRadar.Level.NONE) { - out += Finding(day, Finding.Kind.RADAR, "Symptom Radar: ${radar.label.lowercase()}", radar.summary) + out += Finding(day, Finding.Kind.RADAR, trf("Symptom Radar: {0}", radar.label.lowercase()), radar.summary) } return out } diff --git a/app/src/main/java/com/pulseloop/service/GoalPlan.kt b/app/src/main/java/com/pulseloop/service/GoalPlan.kt index ff40a379..bac4334b 100644 --- a/app/src/main/java/com/pulseloop/service/GoalPlan.kt +++ b/app/src/main/java/com/pulseloop/service/GoalPlan.kt @@ -1,5 +1,8 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf + import androidx.room.withTransaction import com.pulseloop.data.PulseLoopDatabase import com.pulseloop.data.entity.BodyMeasurementEntity @@ -153,7 +156,7 @@ object GoalPlan { var pct: Double? = null var pace: String? = null if (kgToGo != null && current != null && daysLeft != null) { - if (daysLeft <= 0) notes += "The target date has passed; agree a new one." + if (daysLeft <= 0) notes += tr("The target date has passed; agree a new one.") else { required = kgToGo / (daysLeft / 7.0) pct = abs(required) / current * 100 @@ -165,7 +168,7 @@ object GoalPlan { } if (pct > 1.0) { val safeDays = (abs(kgToGo) / (current * 0.01) * 7).roundToInt() - notes += "At 1% of body weight a week this takes about $safeDays days." + notes += trf("At 1% of body weight a week this takes about {0} days.", safeDays) } } } @@ -178,7 +181,7 @@ object GoalPlan { else -> actual >= required * 0.8 } } else null - if (actual == null && weightGoal) notes += "Not enough recent weigh-ins for a trend yet (needs 3 across a week)." + if (actual == null && weightGoal) notes += tr("Not enough recent weigh-ins for a trend yet (needs 3 across a week).") val floor = maxOf(i.bmrKcal ?: 0.0, if (i.sex?.lowercase() == "female") 1200.0 else 1500.0) var suggested: Double? = null @@ -193,11 +196,11 @@ object GoalPlan { } suggested = i.avgBurnKcal + dailyDelta if (suggested < floor) { - notes += "The date needs more of a deficit than is safe; the suggestion is held at the floor." + notes += tr("The date needs more of a deficit than is safe; the suggestion is held at the floor.") suggested = floor } } - if (i.loggedDays in 1..3) notes += "Only ${i.loggedDays} day(s) of food logged this week; intake may be incomplete." + if (i.loggedDays in 1..3) notes += trf("Only {0} day(s) of food logged this week; intake may be incomplete.", i.loggedDays) val protein = when { !weightGoal && g.kind != "eat_better" -> null @@ -259,24 +262,24 @@ object GoalPlan { val sleepTargetH = (if (g.kind == "sleep_better") g.targetValue else null) ?: (i.sleepGoalMin / 60.0) val sleep = higher("sleep", i.avgSleepMin?.div(60), sleepTargetH, "h/night") - val regularity = lower("bedtime_regularity", i.bedtimeSpreadMin, 30.0, "min spread", "Bedtimes within about 30 minutes help sleep quality") + val regularity = lower("bedtime_regularity", i.bedtimeSpreadMin, 30.0, "min spread", tr("Bedtimes within about 30 minutes help sleep quality")) val workoutsTarget = (if (g.kind in setOf("get_fitter", "build_muscle")) g.targetValue else null) ?: i.workoutsGoal.toDouble() val workouts = higher("workouts", i.workoutsPerWeek, workoutsTarget, "per week") val stepsTarget = (if (g.kind == "move_more") g.targetValue else null) ?: i.stepsGoal.toDouble() val steps = higher("steps", i.avgSteps, stepsTarget, "per day") val active = higher("active_minutes", i.avgActiveMin, i.activeMinGoal.toDouble(), "min/day") - val protein = higher("protein", i.avgProteinG, proteinTarget, "g/day", if (i.loggedDays == 0) "No meals logged this week" else null) + val protein = higher("protein", i.avgProteinG, proteinTarget, "g/day", if (i.loggedDays == 0) tr("No meals logged this week") else null) val eaten = i.avgIntakeKcal val intake = when { suggestedIntake == null || eaten == null -> Lever("calories_eaten", eaten?.let(::round1), suggestedIntake?.let(::round1), "kcal/day", "unknown", - if (i.loggedDays == 0) "Log meals to compare intake with the plan" else null) + if (i.loggedDays == 0) tr("Log meals to compare intake with the plan") else null) g.kind == "build_muscle" || g.kind == "gain_weight" -> higher("calories_eaten", eaten, suggestedIntake, "kcal/day", slack = 0.95) g.kind == "maintain_weight" -> Lever("calories_eaten", round1(eaten), round1(suggestedIntake), "kcal/day", if (abs(eaten - suggestedIntake) <= 200) "on_target" else "short") else -> lower("calories_eaten", eaten, suggestedIntake, "kcal/day") } - val rhr = trend("resting_hr", i.restingHr7, i.restingHrBase, "bpm", wantDown = true, note = "Last 7 nights against the 3 weeks before; falling means fitter or better recovered") - val hrv = trend("hrv", i.hrv7, i.hrvBase, "ms", wantDown = false, note = "Last 7 nights against the 3 weeks before; rising means better recovery") + val rhr = trend("resting_hr", i.restingHr7, i.restingHrBase, "bpm", wantDown = true, note = tr("Last 7 nights against the 3 weeks before; falling means fitter or better recovered")) + val hrv = trend("hrv", i.hrv7, i.hrvBase, "ms", wantDown = false, note = tr("Last 7 nights against the 3 weeks before; rising means better recovery")) val leanD = i.leanChange30d val fatD = i.fatPctChange30d val lean = Lever("lean_mass_change_30d", leanD?.let(::round1), null, "kg", @@ -332,8 +335,8 @@ object GoalPlan { /** Short line for the coach screen's banner and check-ins, e.g. "Lose 5 kg by 18 Dec · 2.1 kg down · 38 days left". */ fun headline(p: Plan): String = buildList { add(p.description.replaceFirstChar { it.uppercase() }) - p.kgDone?.takeIf { abs(it) >= 0.1 }?.let { add("${abs(it)} kg ${if (it < 0) "down" else "up"}") } - p.daysLeft?.takeIf { it >= 0 }?.let { add("$it days left") } + p.kgDone?.takeIf { abs(it) >= 0.1 }?.let { add("${abs(it)} kg ${if (it < 0) tr("down") else tr("up")}") } + p.daysLeft?.takeIf { it >= 0 }?.let { add(trf("{0} days left", it)) } }.joinToString(" · ") private val LEVER_LABELS = mapOf( @@ -353,7 +356,7 @@ object GoalPlan { val nums = if (short.value != null && short.target != null) " (${fmt(short.value)} of ${fmt(short.target)} ${short.unit})" else "" return "Focus: $label$nums" } - return if (p.levers.any { it.status == "on_target" }) "On track" else "Building a picture from your data" + return if (p.levers.any { it.status == "on_target" }) tr("On track") else tr("Building a picture from your data") } private fun fmt(v: Double) = if (v >= 100 || v == v.roundToInt().toDouble()) v.roundToInt().toString() else v.toString() diff --git a/app/src/main/java/com/pulseloop/service/GoalSync.kt b/app/src/main/java/com/pulseloop/service/GoalSync.kt index 50496714..77e002c7 100644 --- a/app/src/main/java/com/pulseloop/service/GoalSync.kt +++ b/app/src/main/java/com/pulseloop/service/GoalSync.kt @@ -1,5 +1,9 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr + +import com.pulseloop.ui.i18n.trf + import android.content.Context import com.pulseloop.data.PulseLoopDatabase import com.pulseloop.data.entity.UserGoalEntity @@ -16,14 +20,15 @@ import kotlin.math.roundToInt */ object GoalSync { - enum class Field(val key: String, val label: String) { + enum class Field(val key: String, private val labelEn: String) { CALORIES("intakeCalories", "daily calories"), PROTEIN("intakeProteinG", "protein"), CARBS("intakeCarbsG", "carbs"), FAT("intakeFatG", "fat"), SLEEP("sleepMinutes", "sleep"), STEPS("steps", "steps"), - WORKOUTS("workoutsPerWeek", "workouts a week"), + WORKOUTS("workoutsPerWeek", "workouts a week"); + val label: String get() = tr(labelEn) } val NUTRITION_FIELDS = setOf(Field.CALORIES, Field.PROTEIN, Field.CARBS, Field.FAT) @@ -184,11 +189,11 @@ object GoalSync { /** "daily calories 1,850 kcal, protein 132 g" — for the coach to tell the user. */ fun describe(changed: Map): String = changed.entries.joinToString(", ") { (f, v) -> when (f) { - Field.CALORIES -> "daily calories ${"%,d".format(v.roundToInt())} kcal" + Field.CALORIES -> trf("daily calories {0} kcal", "%,d".format(v.roundToInt())) Field.PROTEIN, Field.CARBS, Field.FAT -> "${f.label} ${v.roundToInt()} g" - Field.SLEEP -> "sleep ${"%.1f".format(v / 60)} h" - Field.STEPS -> "steps ${"%,d".format(v.roundToInt())} a day" - Field.WORKOUTS -> "${v.roundToInt()} workouts a week" + Field.SLEEP -> trf("sleep {0} h", "%.1f".format(v / 60)) + Field.STEPS -> trf("steps {0} a day", "%,d".format(v.roundToInt())) + Field.WORKOUTS -> trf("{0} workouts a week", v.roundToInt()) } } } diff --git a/app/src/main/java/com/pulseloop/service/HealthInsights.kt b/app/src/main/java/com/pulseloop/service/HealthInsights.kt index 154d47e3..d0b58be6 100644 --- a/app/src/main/java/com/pulseloop/service/HealthInsights.kt +++ b/app/src/main/java/com/pulseloop/service/HealthInsights.kt @@ -1,5 +1,7 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr + import java.time.LocalDate import java.time.ZoneId import kotlin.math.abs @@ -62,7 +64,9 @@ data class SleepNeed(val minutes: Int, val isLearned: Boolean) { * Needs five nights in the window, like Oura's. */ data class SleepDebt(val minutes: Int, val needMinutes: Int, val nights: Int) { - enum class Level(val label: String) { NONE("None"), LOW("Low"), MODERATE("Moderate"), HIGH("High") } + enum class Level(private val labelEn: String) { NONE("None"), LOW("Low"), MODERATE("Moderate"), HIGH("High"); + val label: String get() = tr(labelEn) + } val level: Level get() = when { minutes < 15 -> Level.NONE @@ -100,19 +104,22 @@ data class SleepDebt(val minutes: Int, val needMinutes: Int, val nights: Int) { * It is never a diagnosis, and the copy says so. */ object SymptomRadar { - enum class Level(val label: String, val summary: String) { + enum class Level(private val labelEn: String, private val summaryEn: String) { NONE("No signs", "No obvious signs in your biometrics of something straining your body."), MINOR("Minor signs", "Small signs in your biometrics of something straining your body."), - MAJOR("Major signs", "Stronger signs in your biometrics of something straining your body."), + MAJOR("Major signs", "Stronger signs in your biometrics of something straining your body."); + val label: String get() = tr(labelEn) + val summary: String get() = tr(summaryEn) } - enum class Metric(val title: String, val weight: Double, val strainUp: Boolean, val minSd: Double, val unit: String) { + enum class Metric(private val titleEn: String, val weight: Double, val strainUp: Boolean, val minSd: Double, val unit: String) { TEMPERATURE("Body temperature", 1.0, true, 0.15, "°C"), TEMPERATURE_TREND("Temperature trend", 1.0, true, 0.12, "°C"), RESTING_HR("Resting heart rate", 0.8, true, 1.5, "bpm"), HRV("Heart rate variability", 1.0, false, 3.0, "ms"), RESPIRATORY_RATE("Respiratory rate", 0.8, true, 0.5, "/min"), - INACTIVE("Inactivity", 0.5, false, 800.0, "steps"), + INACTIVE("Inactivity", 0.5, false, 800.0, "steps"); + val title: String get() = tr(titleEn) } data class Signal(val metric: Metric, val value: Double, val usual: Double, val z: Double) { @@ -196,7 +203,9 @@ object SymptomRadar { /** The day's stress readings in Oura's four zones (the ring logs 1–100). */ data class DaytimeStress(val restoredMin: Int, val relaxedMin: Int, val engagedMin: Int, val stressedMin: Int) { - enum class Summary(val label: String) { RESTORED("Restored"), NORMAL("Normal"), STRESSFUL("Stressful") } + enum class Summary(private val labelEn: String) { RESTORED("Restored"), NORMAL("Normal"), STRESSFUL("Stressful"); + val label: String get() = tr(labelEn) + } val totalMin: Int get() = restoredMin + relaxedMin + engagedMin + stressedMin val summary: Summary get() = when { @@ -222,7 +231,9 @@ data class DaytimeStress(val restoredMin: Int, val relaxedMin: Int, val engagedM * recovery and the nights' restoration (HRV relative to normal). Oura's five levels. */ data class Resilience(val level: Level, val daysUsed: Int) { - enum class Level(val label: String) { LIMITED("Limited"), ADEQUATE("Adequate"), SOLID("Solid"), STRONG("Strong"), EXCEPTIONAL("Exceptional") } + enum class Level(private val labelEn: String) { LIMITED("Limited"), ADEQUATE("Adequate"), SOLID("Solid"), STRONG("Strong"), EXCEPTIONAL("Exceptional"); + val label: String get() = tr(labelEn) + } data class Day(val stressedMin: Int, val restoredMin: Int, val hrvRatio: Double?) @@ -250,8 +261,12 @@ data class Resilience(val level: Level, val daysUsed: Int) { /** Chronotype from the usual sleep midpoint, and whether recent nights keep to it. */ data class BodyClock(val chronotype: Chronotype, val usualMidpointMin: Int, val recentShiftMin: Int, val alignment: Alignment) { - enum class Chronotype(val label: String) { EARLY("Early bird"), MORNING("Morning type"), INTERMEDIATE("In between"), EVENING("Evening type"), LATE("Night owl") } - enum class Alignment(val label: String) { ALIGNED("In sync"), SLIGHTLY_OFF("Slightly off"), MISALIGNED("Out of sync") } + enum class Chronotype(private val labelEn: String) { EARLY("Early bird"), MORNING("Morning type"), INTERMEDIATE("In between"), EVENING("Evening type"), LATE("Night owl"); + val label: String get() = tr(labelEn) + } + enum class Alignment(private val labelEn: String) { ALIGNED("In sync"), SLIGHTLY_OFF("Slightly off"), MISALIGNED("Out of sync"); + val label: String get() = tr(labelEn) + } /** "3:15" for a midpoint in minutes past midnight. */ fun midpointLabel(): String { @@ -293,7 +308,9 @@ data class BodyClock(val chronotype: Chronotype, val usualMidpointMin: Int, val * waveform this ring doesn't share — and are labelled so. A ring's own VO₂max wins when present. */ data class CardioCapacity(val vo2max: Double, val level: Level, val fromRing: Boolean, val cardioAge: Int?) { - enum class Level(val label: String) { LOW("Below average"), AVERAGE("Average"), GOOD("Good"), EXCELLENT("Excellent") } + enum class Level(private val labelEn: String) { LOW("Below average"), AVERAGE("Average"), GOOD("Good"), EXCELLENT("Excellent"); + val label: String get() = tr(labelEn) + } companion object { fun expectedVo2(age: Int, female: Boolean): Double = (if (female) 42.0 else 48.0) - 0.32 * (age - 25).coerceAtLeast(0) @@ -327,7 +344,9 @@ data class CardioCapacity(val vo2max: Double, val level: Level, val fromRing: Bo /** A long-term area rated on Oura's scale, from a 0–100 score over the last 90 days. */ data class HealthArea(val title: String, val rating: Rating, val score: Int, val trend: List, val detail: String) { - enum class Rating(val label: String) { THRIVING("Thriving"), GOOD("Good"), FAIR("Fair"), NEEDS_CARE("Needs care") } + enum class Rating(private val labelEn: String) { THRIVING("Thriving"), GOOD("Good"), FAIR("Fair"), NEEDS_CARE("Needs care"); + val label: String get() = tr(labelEn) + } companion object { fun rate(score: Int): Rating = when { @@ -346,7 +365,9 @@ data class HealthArea(val title: String, val rating: Rating, val score: Int, val /** Averages a daily series by week, month or year for the Trends view. */ object Trends { - enum class Period(val label: String, val days: Long) { DAY("Day", 30), WEEK("Week", 7 * 26), MONTH("Month", 365), YEAR("Year", 365 * 3) } + enum class Period(private val labelEn: String, val days: Long) { DAY("Day", 30), WEEK("Week", 7 * 26), MONTH("Month", 365), YEAR("Year", 365 * 3); + val label: String get() = tr(labelEn) + } data class Point(val start: LocalDate, val value: Double) diff --git a/app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt b/app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt index 0de90fda..fc28ee72 100644 --- a/app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt +++ b/app/src/main/java/com/pulseloop/service/HealthInsightsRepository.kt @@ -1,5 +1,8 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf + import android.content.Context import com.pulseloop.data.PulseLoopDatabase import com.pulseloop.data.entity.BodyMeasurementEntity @@ -193,9 +196,9 @@ object HealthInsightsRepository { val spread = kotlin.math.sqrt(mids.sumOf { (it - m) * (it - m) } / mids.size) val regularity = Readiness.curve(spread, listOf(30.0 to 100.0, 60.0 to 75.0, 120.0 to 25.0)) val score = (0.7 * HealthArea.scoreOf(ratio) + 0.3 * regularity).roundToInt() - add(HealthArea("Sleep health", HealthArea.rate(score), score, + add(HealthArea(tr("Sleep health"), HealthArea.rate(score), score, weekly { n -> n.asleepMinutes.takeIf { it > 0 }?.div(60.0) }, - "Averaging ${SleepFormat.duration(asleep.map { it.asleepMinutes }.average().roundToInt())} against a need of ${SleepFormat.duration(need.minutes)}")) + trf("Averaging {0} against a need of {1}", SleepFormat.duration(asleep.map { it.asleepMinutes }.average().roundToInt()), SleepFormat.duration(need.minutes)))) } resilience?.let { r -> val score = when (r.level) { @@ -204,13 +207,13 @@ object HealthInsightsRepository { } val trend = stressRows.groupBy { Instant.ofEpochMilli(it.timestamp).atZone(zone).toLocalDate() } .toSortedMap().values.map { d -> d.map { it.value }.average() } - add(HealthArea("Stress management", HealthArea.rate(score), score, trend, "Resilience ${r.level.label.lowercase()} over ${r.daysUsed} days")) + add(HealthArea(tr("Stress management"), HealthArea.rate(score), score, trend, trf("Resilience {0} over {1} days", r.level.label.lowercase(), r.daysUsed))) } cardio?.let { c -> val expected = profile?.age?.let { CardioCapacity.expectedVo2(it, profile?.sex?.lowercase() == "female") } val score = expected?.let { HealthArea.scoreOf(c.vo2max / it * 0.85) } ?: 60 - add(HealthArea("Heart health", HealthArea.rate(score), score, weekly { it.restingHr }, - "Cardio capacity ${c.level.label.lowercase()}, estimated from resting heart rate and age")) + add(HealthArea(tr("Heart health"), HealthArea.rate(score), score, weekly { it.restingHr }, + trf("Cardio capacity {0}, estimated from resting heart rate and age", c.level.label.lowercase()))) } } @@ -255,9 +258,10 @@ object HealthInsightsRepository { // ── Trends ─────────────────────────────────────────────────────────────── - enum class TrendMetric(val label: String, val unit: String) { + enum class TrendMetric(private val labelEn: String, val unit: String) { SLEEP("Sleep", "h"), STEPS("Steps", ""), ACTIVE("Active minutes", "min"), RESTING_HR("Resting HR", "bpm"), - HRV("HRV", "ms"), STRESS("Stress", ""), SPO2("Blood oxygen", "%"), TEMPERATURE("Temperature", "°C"), WEIGHT("Weight", "kg"), + HRV("HRV", "ms"), STRESS("Stress", ""), SPO2("Blood oxygen", "%"), TEMPERATURE("Temperature", "°C"), WEIGHT("Weight", "kg"); + val label: String get() = tr(labelEn) } /** One value per day for [metric] over the last [days]. */ diff --git a/app/src/main/java/com/pulseloop/service/HeartRateZones.kt b/app/src/main/java/com/pulseloop/service/HeartRateZones.kt index decac831..c1555d69 100644 --- a/app/src/main/java/com/pulseloop/service/HeartRateZones.kt +++ b/app/src/main/java/com/pulseloop/service/HeartRateZones.kt @@ -1,5 +1,7 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr + /** * Ported from the HR zone calculation logic in the iOS app. * Max HR estimated via 220 - age formula; zones are percentage-based. @@ -7,12 +9,13 @@ package com.pulseloop.service object HeartRateZones { fun maxHR(age: Int = 30): Int = 220 - age - enum class Zone(val label: String, val range: IntRange) { + enum class Zone(private val labelEn: String, val range: IntRange) { REST("Rest", 0..59), FAT_BURN("Fat Burn", 60..69), CARDIO("Cardio", 70..79), PEAK("Peak", 80..89), - MAX("Max", 90..220), + MAX("Max", 90..220); + val label: String get() = tr(labelEn) } fun zoneFor(bpm: Int, age: Int = 30): Zone { diff --git a/app/src/main/java/com/pulseloop/service/JournalInsights.kt b/app/src/main/java/com/pulseloop/service/JournalInsights.kt index 0dd5203d..ff1f29ef 100644 --- a/app/src/main/java/com/pulseloop/service/JournalInsights.kt +++ b/app/src/main/java/com/pulseloop/service/JournalInsights.kt @@ -1,5 +1,8 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf + import java.time.LocalDate import kotlin.math.abs import kotlin.math.roundToInt @@ -17,7 +20,7 @@ object JournalInsights { const val MIN_NIGHTS = 3 - enum class Tag(val key: String, val label: String) { + enum class Tag(val key: String, private val labelEn: String) { ALCOHOL("alcohol", "Alcohol"), LATE_CAFFEINE("late_caffeine", "Caffeine after 2 pm"), LATE_MEAL("late_meal", "Late meal"), @@ -28,6 +31,7 @@ object JournalInsights { TRAVEL("travel", "Travel"), RELAXATION("relaxation", "Meditation or relaxing"), NAP("nap", "Daytime nap"); + val label: String get() = tr(labelEn) companion object { fun of(key: String) = entries.firstOrNull { it.key == key } @@ -50,9 +54,9 @@ object JournalInsights { /** e.g. "HRV 18% lower, resting heart rate 4 bpm higher on the night after (5 nights)". */ fun summary(): String { val parts = buildList { - hrvPct?.let { add("HRV ${abs(it)}% ${if (it < 0) "lower" else "higher"}") } - restingHr?.let { add("resting heart rate ${abs(it)} bpm ${if (it > 0) "higher" else "lower"}") } - sleepMinutes?.let { add("${abs(it)} min ${if (it < 0) "less" else "more"} sleep") } + hrvPct?.let { add("HRV ${abs(it)}% ${if (it < 0) tr("lower") else tr("higher")}") } + restingHr?.let { add(trf("resting heart rate {0} bpm {1}", abs(it), if (it > 0) tr("higher") else tr("lower"))) } + sleepMinutes?.let { add(trf("{0} min {1} sleep", abs(it), if (it < 0) tr("less") else tr("more"))) } } val what = if (parts.isEmpty()) "no clear effect yet" else parts.joinToString(", ") return "$what on the night after ($nightsWith nights)" diff --git a/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt b/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt index 7a8db7b0..d9cadb32 100644 --- a/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt +++ b/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt @@ -1,5 +1,7 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr + import android.content.Context import android.content.Intent import androidx.work.WorkManager @@ -258,7 +260,7 @@ class LiveWorkoutManager( serviceIntent.apply { val s = _state.value val notification = Intent(context, WorkoutForegroundService::class.java).apply { - putExtra("activityName", s.activeSession?.let { ActivityMeta.label(it.type) } ?: "Workout") + putExtra("activityName", s.activeSession?.let { ActivityMeta.label(it.type) } ?: tr("Workout")) putExtra("status", if (s.isPaused) "paused" else "recording") putExtra("elapsedSeconds", s.elapsedSeconds) putExtra("distanceMeters", s.distanceMeters) diff --git a/app/src/main/java/com/pulseloop/service/ManualActivityService.kt b/app/src/main/java/com/pulseloop/service/ManualActivityService.kt index 313d9c84..4df041d1 100644 --- a/app/src/main/java/com/pulseloop/service/ManualActivityService.kt +++ b/app/src/main/java/com/pulseloop/service/ManualActivityService.kt @@ -1,14 +1,16 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr + import com.pulseloop.data.PulseLoopDatabase import com.pulseloop.data.entity.ActivitySessionEntity import com.pulseloop.ui.components.ActivityMeta /** Ported from `ManualActivityCreationError` in ManualActivityService.swift (iOS #57d). */ sealed class ManualActivityError(message: String) : Exception(message) { - object InvalidActivityType : ManualActivityError("Choose a valid activity type.") - object InvalidDuration : ManualActivityError("Duration must be greater than zero.") - object EndsInFuture : ManualActivityError("The activity must end in the past.") + object InvalidActivityType : ManualActivityError(tr("Choose a valid activity type.")) + object InvalidDuration : ManualActivityError(tr("Duration must be greater than zero.")) + object EndsInFuture : ManualActivityError(tr("The activity must end in the past.")) } /** diff --git a/app/src/main/java/com/pulseloop/service/MealJournal.kt b/app/src/main/java/com/pulseloop/service/MealJournal.kt index 156f38b9..ce5a5363 100644 --- a/app/src/main/java/com/pulseloop/service/MealJournal.kt +++ b/app/src/main/java/com/pulseloop/service/MealJournal.kt @@ -1,5 +1,7 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr + import com.pulseloop.data.PulseLoopDatabase import com.pulseloop.data.entity.JournalEntryEntity import com.pulseloop.data.entity.MealEntryEntity @@ -134,7 +136,7 @@ data class NutritionContext( /** Whether yesterday evening had a meal at or after 21:00. */ val lateMealLastNight: Boolean = false, val alcoholLastNight: Boolean = false, - val note: String = "Food the user logged themselves; totals are only as complete as the log.", + val note: String = tr("Food the user logged themselves; totals are only as complete as the log."), ) { companion object { suspend fun build(db: PulseLoopDatabase, now: Long = System.currentTimeMillis(), zone: ZoneId = ZoneId.systemDefault()): NutritionContext? = diff --git a/app/src/main/java/com/pulseloop/service/MealSuggester.kt b/app/src/main/java/com/pulseloop/service/MealSuggester.kt index 1256f605..66dfb11e 100644 --- a/app/src/main/java/com/pulseloop/service/MealSuggester.kt +++ b/app/src/main/java/com/pulseloop/service/MealSuggester.kt @@ -1,5 +1,8 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf + import com.pulseloop.data.PulseLoopDatabase import com.pulseloop.data.entity.FoodPreferenceEntity import kotlinx.serialization.Serializable @@ -40,32 +43,32 @@ object MealSuggester { /** Typical portions, TACO-style values, rounded. */ val CATALOG: List = listOf( // Fruit - Food("banana", "Banana", "banana", "1 medium", 105.0, 1.3, 27.0, 0.4, Role.FRUIT, setOf(B, S, D)), - Food("maca", "Maçã", "apple", "1 medium", 95.0, 0.5, 25.0, 0.3, Role.FRUIT, setOf(B, S, D)), - Food("mamao", "Mamão papaia", "papaya", "½ fruit", 60.0, 1.0, 15.0, 0.2, Role.FRUIT, setOf(B, S)), - Food("laranja", "Laranja", "orange", "1 medium", 62.0, 1.2, 15.0, 0.2, Role.FRUIT, setOf(B, S)), - Food("melancia", "Melancia", "watermelon", "2 slices", 60.0, 1.2, 15.0, 0.3, Role.FRUIT, setOf(S)), + Food("banana", tr("Banana"), "banana", tr("1 medium"), 105.0, 1.3, 27.0, 0.4, Role.FRUIT, setOf(B, S, D)), + Food("maca", tr("Maçã"), "apple", tr("1 medium"), 95.0, 0.5, 25.0, 0.3, Role.FRUIT, setOf(B, S, D)), + Food("mamao", tr("Mamão papaia"), "papaya", "½ fruit", 60.0, 1.0, 15.0, 0.2, Role.FRUIT, setOf(B, S)), + Food("laranja", tr("Laranja"), "orange", tr("1 medium"), 62.0, 1.2, 15.0, 0.2, Role.FRUIT, setOf(B, S)), + Food("melancia", tr("Melancia"), "watermelon", tr("2 slices"), 60.0, 1.2, 15.0, 0.3, Role.FRUIT, setOf(S)), // Breakfast and snacks - Food("pao_queijo_minas", "Pão francês com queijo minas", "bread roll with fresh cheese", "1 roll + 30 g", 220.0, 9.0, 30.0, 6.0, Role.CARB, setOf(B, S)), - Food("tapioca_ovo", "Tapioca com ovo", "tapioca with egg", "1 medium", 230.0, 8.0, 32.0, 6.0, Role.CARB, setOf(B, S, D)), - Food("cuscuz_ovo", "Cuscuz com ovo", "corn couscous with egg", "1 plate", 250.0, 9.0, 35.0, 7.0, Role.CARB, setOf(B, D)), - Food("ovos_mexidos", "Ovos mexidos", "scrambled eggs", "2 eggs", 180.0, 12.0, 2.0, 14.0, Role.PROTEIN, setOf(B, D)), - Food("iogurte", "Iogurte natural", "plain yogurt", "1 pot (170 g)", 100.0, 6.0, 8.0, 5.0, Role.DAIRY, setOf(B, S, D)), - Food("cafe_leite", "Café com leite", "coffee with milk", "1 cup", 90.0, 6.0, 9.0, 3.0, Role.DAIRY, setOf(B, S)), - Food("castanhas", "Castanhas", "brazil or cashew nuts", "30 g", 180.0, 4.0, 6.0, 16.0, Role.EXTRA, setOf(S)), - Food("pao_de_queijo", "Pão de queijo", "cheese bread", "2 small", 180.0, 3.0, 18.0, 10.0, Role.EXTRA, setOf(B, S)), + Food("pao_queijo_minas", tr("Pão francês com queijo minas"), "bread roll with fresh cheese", tr("1 roll + 30 g"), 220.0, 9.0, 30.0, 6.0, Role.CARB, setOf(B, S)), + Food("tapioca_ovo", tr("Tapioca com ovo"), "tapioca with egg", tr("1 medium"), 230.0, 8.0, 32.0, 6.0, Role.CARB, setOf(B, S, D)), + Food("cuscuz_ovo", tr("Cuscuz com ovo"), "corn couscous with egg", tr("1 plate"), 250.0, 9.0, 35.0, 7.0, Role.CARB, setOf(B, D)), + Food("ovos_mexidos", tr("Ovos mexidos"), "scrambled eggs", tr("2 eggs"), 180.0, 12.0, 2.0, 14.0, Role.PROTEIN, setOf(B, D)), + Food("iogurte", tr("Iogurte natural"), "plain yogurt", tr("1 pot (170 g)"), 100.0, 6.0, 8.0, 5.0, Role.DAIRY, setOf(B, S, D)), + Food("cafe_leite", tr("Café com leite"), "coffee with milk", tr("1 cup"), 90.0, 6.0, 9.0, 3.0, Role.DAIRY, setOf(B, S)), + Food("castanhas", tr("Castanhas"), "brazil or cashew nuts", tr("30 g"), 180.0, 4.0, 6.0, 16.0, Role.EXTRA, setOf(S)), + Food("pao_de_queijo", tr("Pão de queijo"), "cheese bread", tr("2 small"), 180.0, 3.0, 18.0, 10.0, Role.EXTRA, setOf(B, S)), // Lunch and dinner - Food("arroz", "Arroz branco", "white rice", "4 tbsp (100 g)", 130.0, 2.5, 28.0, 0.3, Role.CARB, setOf(L, D)), - Food("feijao", "Feijão", "beans", "1 ladle (100 g)", 76.0, 4.8, 14.0, 0.5, Role.LEGUME, setOf(L, D)), - Food("batata_doce", "Batata-doce", "sweet potato", "150 g", 130.0, 2.0, 30.0, 0.2, Role.CARB, setOf(L, D)), - Food("mandioca", "Mandioca cozida", "boiled cassava", "100 g", 125.0, 1.0, 30.0, 0.3, Role.CARB, setOf(L, D)), - Food("frango", "Frango grelhado", "grilled chicken", "120 g", 195.0, 37.0, 0.0, 4.0, Role.PROTEIN, setOf(L, D)), - Food("tilapia", "Tilápia grelhada", "grilled tilapia", "120 g", 155.0, 31.0, 0.0, 3.0, Role.PROTEIN, setOf(L, D)), - Food("patinho", "Patinho moído", "lean ground beef", "100 g", 220.0, 27.0, 0.0, 12.0, Role.PROTEIN, setOf(L, D)), - Food("omelete", "Omelete de 2 ovos com queijo", "2-egg cheese omelette", "1", 250.0, 17.0, 2.0, 19.0, Role.PROTEIN, setOf(D)), - Food("salada", "Salada verde com tomate", "green salad with tomato", "1 plate, 1 tsp olive oil", 60.0, 1.0, 5.0, 4.0, Role.VEG, setOf(L, D)), - Food("legumes", "Legumes cozidos", "steamed vegetables (zucchini, carrot, broccoli)", "150 g", 60.0, 3.0, 10.0, 0.5, Role.VEG, setOf(L, D)), - Food("sopa_legumes", "Sopa de legumes com frango", "vegetable and chicken soup", "1 bowl", 220.0, 18.0, 22.0, 6.0, Role.PROTEIN, setOf(D)), + Food("arroz", tr("Arroz branco"), "white rice", tr("4 tbsp (100 g)"), 130.0, 2.5, 28.0, 0.3, Role.CARB, setOf(L, D)), + Food("feijao", tr("Feijão"), "beans", tr("1 ladle (100 g)"), 76.0, 4.8, 14.0, 0.5, Role.LEGUME, setOf(L, D)), + Food("batata_doce", tr("Batata-doce"), "sweet potato", tr("150 g"), 130.0, 2.0, 30.0, 0.2, Role.CARB, setOf(L, D)), + Food("mandioca", tr("Mandioca cozida"), "boiled cassava", tr("100 g"), 125.0, 1.0, 30.0, 0.3, Role.CARB, setOf(L, D)), + Food("frango", tr("Frango grelhado"), "grilled chicken", tr("120 g"), 195.0, 37.0, 0.0, 4.0, Role.PROTEIN, setOf(L, D)), + Food("tilapia", tr("Tilápia grelhada"), "grilled tilapia", tr("120 g"), 155.0, 31.0, 0.0, 3.0, Role.PROTEIN, setOf(L, D)), + Food("patinho", tr("Patinho moído"), "lean ground beef", tr("100 g"), 220.0, 27.0, 0.0, 12.0, Role.PROTEIN, setOf(L, D)), + Food("omelete", tr("Omelete de 2 ovos com queijo"), tr("2-egg cheese omelette"), "1", 250.0, 17.0, 2.0, 19.0, Role.PROTEIN, setOf(D)), + Food("salada", tr("Salada verde com tomate"), "green salad with tomato", tr("1 plate, 1 tsp olive oil"), 60.0, 1.0, 5.0, 4.0, Role.VEG, setOf(L, D)), + Food("legumes", tr("Legumes cozidos"), "steamed vegetables (zucchini, carrot, broccoli)", tr("150 g"), 60.0, 3.0, 10.0, 0.5, Role.VEG, setOf(L, D)), + Food("sopa_legumes", tr("Sopa de legumes com frango"), "vegetable and chicken soup", tr("1 bowl"), 220.0, 18.0, 22.0, 6.0, Role.PROTEIN, setOf(D)), ) /** The meal slot for a local time of day. */ @@ -126,7 +129,7 @@ object MealSuggester { private fun foodFor(p: FoodPreferenceEntity): Food? = CATALOG.firstOrNull { matches(it, p.item) } ?: if (p.kcal != null) Food("pref:${p.item}", p.item.replaceFirstChar { it.uppercase() }, p.item, - p.portion ?: "1 portion", p.kcal, p.proteinG ?: 0.0, 0.0, 0.0, Role.EXTRA, setOf(B, L, S, D)) else null + p.portion ?: tr("1 portion"), p.kcal, p.proteinG ?: 0.0, 0.0, 0.0, Role.EXTRA, setOf(B, L, S, D)) else null fun suggest(i: Inputs): Suggestion { val remaining = i.targetKcal - i.eatenKcal @@ -144,9 +147,9 @@ object MealSuggester { val fruit = pool(Role.FRUIT).firstOrNull() return Suggestion( slot = slot, items = emptyList(), totalKcal = 0, totalProteinG = 0, leavesKcal = remaining.roundToInt(), - note = if (remaining <= 0) "You've reached today's target. Water or tea if you're hungry" + - (fruit?.let { ", or a ${it.english} if you need something (${it.kcal.roundToInt()} kcal)." } ?: ".") - else "Only ${remaining.roundToInt()} kcal left: " + (fruit?.let { "a ${it.english} fits." } ?: "keep it light."), + note = if (remaining <= 0) tr("You've reached today's target. Water or tea if you're hungry") + + (fruit?.let { trf(", or a {0} if you need something ({1} kcal).", it.english, it.kcal.roundToInt()) } ?: ".") + else trf("Only {0} kcal left: ", remaining.roundToInt()) + (fruit?.let { trf("a {0} fits.", it.english) } ?: "keep it light."), ) } @@ -171,7 +174,7 @@ object MealSuggester { replaces?.let { template.remove(it) } template.remove(food.role) plate += food - used += "${p.item} at ${if (p.slot == "any") "any meal" else p.slot}" + (p.insteadOf?.let { " instead of $it" } ?: "") + used += "${p.item} at ${if (p.slot == "any") tr("any meal") else p.slot}" + (p.insteadOf?.let { trf(" instead of {0}", it) } ?: "") } // Then fill the template, protein first when there's a gap, each within what's left. val order = if (proteinGap > 15) template.sortedBy { if (it == Role.PROTEIN || it == Role.DAIRY) 0 else 1 } else template @@ -190,7 +193,7 @@ object MealSuggester { totalProteinG = plate.sumOf { it.proteinG }.roundToInt(), leavesKcal = (remaining - total).roundToInt(), fromPreferences = used, - note = if (proteinGap > 30) "You're ${proteinGap.roundToInt()} g short of today's protein, so this leans on protein." else null, + note = if (proteinGap > 30) trf("You're {0} g short of today's protein, so this leans on protein.", proteinGap.roundToInt()) else null, ) } diff --git a/app/src/main/java/com/pulseloop/service/Meds.kt b/app/src/main/java/com/pulseloop/service/Meds.kt index 66744888..091efe37 100644 --- a/app/src/main/java/com/pulseloop/service/Meds.kt +++ b/app/src/main/java/com/pulseloop/service/Meds.kt @@ -1,5 +1,7 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr + import com.pulseloop.data.entity.MedDoseEntity import com.pulseloop.data.entity.MedEntity import java.time.LocalDate @@ -13,7 +15,9 @@ import java.time.LocalTime * belongs with a pharmacist, not an app that can't see the whole picture. */ object Meds { - enum class State(val label: String) { TAKEN("Taken"), SKIPPED("Skipped"), DUE("Due"), MISSED("Missed"), LATER("Later") } + enum class State(private val labelEn: String) { TAKEN("Taken"), SKIPPED("Skipped"), DUE("Due"), MISSED("Missed"), LATER("Later"); + val label: String get() = tr(labelEn) + } data class Dose(val med: MedEntity, val day: LocalDate, val time: String, val state: State) { val id: String get() = MedDoseEntity.idFor(med.id, day.toEpochDay(), time) diff --git a/app/src/main/java/com/pulseloop/service/Readiness.kt b/app/src/main/java/com/pulseloop/service/Readiness.kt index 3da6abc0..94dad430 100644 --- a/app/src/main/java/com/pulseloop/service/Readiness.kt +++ b/app/src/main/java/com/pulseloop/service/Readiness.kt @@ -1,5 +1,8 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf + import java.time.Instant import java.time.LocalDate import java.time.ZoneId @@ -194,8 +197,9 @@ object Readiness { const val MIN_REGULARITY_NIGHTS = 5 const val MIN_ACTIVITY_DAYS = 7 - enum class Band(val label: String) { + enum class Band(private val labelEn: String) { OPTIMAL("Optimal"), GOOD("Good"), FAIR("Fair"), PAY_ATTENTION("Pay attention"); + val label: String get() = tr(labelEn) companion object { /** Oura's published bands: 85+ optimal, 70–84 good, 60–69 fair, below 60 pay attention. */ @@ -213,7 +217,7 @@ object Readiness { * dense night heart rate; when a ring never provides them they are left out (not "missing") * and the rest are renormalised. */ - enum class ContributorKind(val title: String, val weight: Double, val optionalSensor: Boolean = false) { + enum class ContributorKind(private val titleEn: String, val weight: Double, val optionalSensor: Boolean = false) { // The original seven keep their proportions (×0.8), so a ring without the optional // sensors scores exactly as it did before they existed. RESTING_HR("Resting heart rate", 0.16), @@ -224,7 +228,8 @@ object Readiness { SLEEP_BALANCE("Sleep balance", 0.12), SLEEP_REGULARITY("Sleep regularity", 0.04), PREVIOUS_DAY_ACTIVITY("Previous day activity", 0.08), - ACTIVITY_BALANCE("Activity balance", 0.08), + ACTIVITY_BALANCE("Activity balance", 0.08); + val title: String get() = tr(titleEn) } data class Contributor( @@ -302,7 +307,7 @@ object Readiness { contributors.size < MIN_CONTRIBUTORS || weightSum < applicableWeight * MIN_WEIGHT_SHARE ) { val reasons = night.withheld.values.toList().ifEmpty { - listOf("Last night's heart rate and HRV readings weren't enough to score recovery") + listOf(tr("Last night's heart rate and HRV readings weren't enough to score recovery")) } return Result.Withheld(reasons, night.coverage) } @@ -341,9 +346,9 @@ object Readiness { val score = curve(delta, listOf(-15.0 to 60.0, -10.0 to 100.0, 1.0 to 100.0, 3.0 to 85.0, 5.0 to 65.0, 8.0 to 40.0, 12.0 to 15.0)) val d = delta.roundToInt() val detail = when { - d == 0 -> "Right at your usual ${base.roundToInt()} bpm" - d > 0 -> "$d bpm above your usual ${base.roundToInt()}" - else -> "${-d} bpm below your usual ${base.roundToInt()}" + d == 0 -> trf("Right at your usual {0} bpm", base.roundToInt()) + d > 0 -> trf("{0} bpm above your usual {1}", d, base.roundToInt()) + else -> trf("{0} bpm below your usual {1}", -d, base.roundToInt()) } return Contributor(ContributorKind.RESTING_HR, score, detail) } @@ -362,9 +367,9 @@ object Readiness { val score = curve(ratio, listOf(0.6 to 20.0, 0.75 to 50.0, 0.85 to 70.0, 0.95 to 90.0, 1.0 to 100.0)) val pct = ((ratio - 1) * 100).roundToInt() val detail = when { - abs(pct) < 3 -> "In line with your usual ${base.roundToInt()} ms" - pct > 0 -> "$pct% above your usual ${base.roundToInt()} ms" - else -> "${-pct}% below your usual ${base.roundToInt()} ms" + abs(pct) < 3 -> trf("In line with your usual {0} ms", base.roundToInt()) + pct > 0 -> trf("{0}% above your usual {1} ms", pct, base.roundToInt()) + else -> trf("{0}% below your usual {1} ms", -pct, base.roundToInt()) } return Contributor(ContributorKind.HRV_BALANCE, score, detail) } @@ -376,9 +381,9 @@ object Readiness { val delta = t - base val score = curve(abs(delta), listOf(0.3 to 100.0, 0.5 to 80.0, 1.0 to 45.0, 1.5 to 15.0)) val detail = when { - abs(delta) < 0.1 -> "At your usual" - delta > 0 -> "+%.1f °C from your usual".format(delta) - else -> "−%.1f °C from your usual".format(-delta) + abs(delta) < 0.1 -> tr("At your usual") + delta > 0 -> tr("+%.1f °C from your usual").format(delta) + else -> tr("−%.1f °C from your usual").format(-delta) } return Contributor(ContributorKind.BODY_TEMPERATURE, score, detail) } @@ -394,13 +399,13 @@ object Readiness { val fraction = ((at - night.startAt).toDouble() / span).coerceIn(0.0, 1.0) val score = curve(fraction, listOf(0.5 to 100.0, 0.7 to 75.0, 0.85 to 55.0, 1.0 to 35.0)) val beforeWake = ((night.endAt - at) / 60_000L).toInt() - return Contributor(ContributorKind.RECOVERY_INDEX, score, "Lowest heart rate ${SleepFormat.duration(beforeWake)} before waking") + return Contributor(ContributorKind.RECOVERY_INDEX, score, trf("Lowest heart rate {0} before waking", SleepFormat.duration(beforeWake))) } internal fun sleep(night: NightSummary, goalMinutes: Int): Contributor? { if (goalMinutes <= 0 || night.asleepMinutes <= 0) return null val score = sleepCurve(night.asleepMinutes.toDouble() / goalMinutes) - return Contributor(ContributorKind.SLEEP, score, "${SleepFormat.duration(night.asleepMinutes)} of ${SleepFormat.duration(goalMinutes)} goal") + return Contributor(ContributorKind.SLEEP, score, trf("{0} of {1} goal", SleepFormat.duration(night.asleepMinutes), SleepFormat.duration(goalMinutes))) } internal fun sleepBalance(night: NightSummary, history: List, goalMinutes: Int): Contributor? { @@ -409,7 +414,7 @@ object Readiness { if (nights.size < MIN_BASELINE_NIGHTS) return null val avg = nights.map { it.asleepMinutes }.average() val score = sleepCurve(avg / goalMinutes) - return Contributor(ContributorKind.SLEEP_BALANCE, score, "Averaging ${SleepFormat.duration(avg.roundToInt())} over ${nights.size} nights") + return Contributor(ContributorKind.SLEEP_BALANCE, score, trf("Averaging {0} over {1} nights", SleepFormat.duration(avg.roundToInt()), nights.size)) } internal fun sleepRegularity(night: NightSummary, history: List, zone: ZoneId): Contributor? { @@ -419,7 +424,7 @@ object Readiness { val mean = mids.average() val sd = sqrt(mids.sumOf { (it - mean) * (it - mean) } / mids.size) val score = curve(sd, listOf(30.0 to 100.0, 60.0 to 75.0, 90.0 to 50.0, 120.0 to 25.0, 180.0 to 0.0)) - return Contributor(ContributorKind.SLEEP_REGULARITY, score, "Sleep midpoint varies by about ${sd.roundToInt()} min") + return Contributor(ContributorKind.SLEEP_REGULARITY, score, trf("Sleep midpoint varies by about {0} min", sd.roundToInt())) } internal fun previousDayActivity(dailySteps: List): Contributor? { @@ -430,7 +435,7 @@ object Readiness { val ratio = yesterday / usual // Both ends cost points: a sedentary day, and a very heavy one that calls for recovery. val score = curve(ratio, listOf(0.0 to 30.0, 0.3 to 50.0, 0.7 to 100.0, 1.5 to 100.0, 2.5 to 60.0)) - return Contributor(ContributorKind.PREVIOUS_DAY_ACTIVITY, score, "%,d steps yesterday vs your usual %,d".format(yesterday, usual.roundToInt())) + return Contributor(ContributorKind.PREVIOUS_DAY_ACTIVITY, score, tr("%,d steps yesterday vs your usual %,d").format(yesterday, usual.roundToInt())) } internal fun activityBalance(dailySteps: List): Contributor? { @@ -442,9 +447,9 @@ object Readiness { val score = curve(ratio, listOf(0.3 to 30.0, 0.5 to 60.0, 0.8 to 100.0, 1.3 to 100.0, 2.0 to 60.0)) val pct = ((ratio - 1) * 100).roundToInt() val detail = when { - abs(pct) < 5 -> "This week matches your monthly rhythm" - pct > 0 -> "This week is $pct% more active than your monthly average" - else -> "This week is ${-pct}% less active than your monthly average" + abs(pct) < 5 -> tr("This week matches your monthly rhythm") + pct > 0 -> trf("This week is {0}% more active than your monthly average", pct) + else -> trf("This week is {0}% less active than your monthly average", -pct) } return Contributor(ContributorKind.ACTIVITY_BALANCE, score, detail) } @@ -483,21 +488,21 @@ object ReadinessCopy { val weakest = result.contributors.minByOrNull { it.score } ?.takeIf { it.score < 70 }?.kind?.title?.lowercase() when (result.band) { - Readiness.Band.OPTIMAL -> "You're well recovered. A good day to take on something demanding." - Readiness.Band.GOOD -> "You're in good shape today. Your usual plans should feel fine." + Readiness.Band.OPTIMAL -> tr("You're well recovered. A good day to take on something demanding.") + Readiness.Band.GOOD -> tr("You're in good shape today. Your usual plans should feel fine.") Readiness.Band.FAIR -> if (weakest != null) - "Your body is still recovering. Go a little easier today and watch your $weakest." - else "Your body is still recovering. Go a little easier today." + trf("Your body is still recovering. Go a little easier today and watch your {0}.", weakest) + else tr("Your body is still recovering. Go a little easier today.") Readiness.Band.PAY_ATTENTION -> if (weakest != null) - "Your body is asking for rest. Make recovery today's priority: your $weakest is furthest from your usual." - else "Your body is asking for rest. Make recovery today's priority." + trf("Your body is asking for rest. Make recovery today's priority: your {0} is furthest from your usual.", weakest) + else tr("Your body is asking for rest. Make recovery today's priority.") } } is Readiness.Result.Learning -> - "Learning your baseline: ${result.nightsCollected} of ${result.nightsNeeded} nights. Keep wearing your ring to bed." - Readiness.Result.NoSleep -> "No sleep recorded for last night yet. Sync your ring after you wake up." + trf("Learning your baseline: {0} of {1} nights. Keep wearing your ring to bed.", result.nightsCollected, result.nightsNeeded) + Readiness.Result.NoSleep -> tr("No sleep recorded for last night yet. Sync your ring after you wake up.") is Readiness.Result.Withheld -> - "No readiness today: ${result.reasons.first().replaceFirstChar { it.lowercase() }}. Wear the ring snugly tonight." + trf("No readiness today: {0}. Wear the ring snugly tonight.", result.reasons.first().replaceFirstChar { it.lowercase() }) } /** A visible caution when the ring missed much of the night, or null when coverage is fine. */ @@ -510,27 +515,27 @@ object ReadinessCopy { const val LOW_COVERAGE = 0.6 const val DERIVED_FOOTER = - "Readiness is estimated by PulseLoop from your ring's sleep, heart rate, HRV and activity, compared with your own recent nights. It is not a medical measurement." + tr("Readiness is estimated by PulseLoop from your ring's sleep, heart rate, HRV and activity, compared with your own recent nights. It is not a medical measurement.") /** What each contributor measures, for its detail sheet. */ fun explanation(kind: Readiness.ContributorKind): String = when (kind) { Readiness.ContributorKind.RESTING_HR -> - "Your lowest sustained heart rate last night, compared with your usual over recent nights. A resting heart rate a few beats above normal can mean your body is working on recovery, stress, or an oncoming illness." + tr("Your lowest sustained heart rate last night, compared with your usual over recent nights. A resting heart rate a few beats above normal can mean your body is working on recovery, stress, or an oncoming illness.") Readiness.ContributorKind.HRV_BALANCE -> - "Your heart rate variability over the last few nights, weighted toward last night, compared with your usual. Higher than usual generally means you're well recovered; a drop suggests strain." + tr("Your heart rate variability over the last few nights, weighted toward last night, compared with your usual. Higher than usual generally means you're well recovered; a drop suggests strain.") Readiness.ContributorKind.BODY_TEMPERATURE -> - "Your skin temperature last night compared with your usual. A rise of half a degree or more can come with illness, a hard training load, alcohol or the menstrual cycle." + tr("Your skin temperature last night compared with your usual. A rise of half a degree or more can come with illness, a hard training load, alcohol or the menstrual cycle.") Readiness.ContributorKind.RECOVERY_INDEX -> - "How early in the night your heart rate reached its lowest. An early low means your body had time to recover; a low just before waking means it was still working, often after a late meal, alcohol or an evening workout." + tr("How early in the night your heart rate reached its lowest. An early low means your body had time to recover; a low just before waking means it was still working, often after a late meal, alcohol or an evening workout.") Readiness.ContributorKind.SLEEP -> - "How much you slept last night compared with your sleep need, learned from the nights you woke up recovered (your sleep goal until then)." + tr("How much you slept last night compared with your sleep need, learned from the nights you woke up recovered (your sleep goal until then).") Readiness.ContributorKind.SLEEP_BALANCE -> - "Your average sleep over the last two weeks compared with your goal. It shows whether sleep debt is building up." + tr("Your average sleep over the last two weeks compared with your goal. It shows whether sleep debt is building up.") Readiness.ContributorKind.SLEEP_REGULARITY -> - "How consistent the timing of your sleep has been over the last two weeks. A steady rhythm helps recovery." + tr("How consistent the timing of your sleep has been over the last two weeks. A steady rhythm helps recovery.") Readiness.ContributorKind.PREVIOUS_DAY_ACTIVITY -> - "Yesterday's steps compared with your usual. Both a very inactive day and an unusually heavy one lower this." + tr("Yesterday's steps compared with your usual. Both a very inactive day and an unusually heavy one lower this.") Readiness.ContributorKind.ACTIVITY_BALANCE -> - "This week's activity compared with your monthly average. It flags both overdoing it and a drop in activity." + tr("This week's activity compared with your monthly average. It flags both overdoing it and a drop in activity.") } } diff --git a/app/src/main/java/com/pulseloop/service/RingSyncCoordinator.kt b/app/src/main/java/com/pulseloop/service/RingSyncCoordinator.kt index 988b1bdf..4bcddbee 100644 --- a/app/src/main/java/com/pulseloop/service/RingSyncCoordinator.kt +++ b/app/src/main/java/com/pulseloop/service/RingSyncCoordinator.kt @@ -1,5 +1,7 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr + import com.pulseloop.data.PulseLoopDatabase import com.pulseloop.data.entity.DeviceEntity import com.pulseloop.data.entity.MeasurementEntity @@ -499,7 +501,7 @@ class RingSyncCoordinator( fun factoryResetRing(onProgress: (String) -> Unit = {}, onCleared: suspend () -> Unit) { scope.launch { if (isConnected) { - onProgress("Syncing latest data…") + onProgress(tr("Syncing latest data…")) syncNow() // Wait for the history sync to drain (progress reaches 100 or clears), capped // so a stale link can never hang the reset. @@ -507,7 +509,7 @@ class RingSyncCoordinator( syncProgress.first { it == null || it >= 100 } } kotlinx.coroutines.delay(800) // let the final history writes flush - onProgress("Resetting ring…") + onProgress(tr("Resetting ring…")) engine?.factoryReset() // The reset frame is only ENQUEUED on the GATT op queue; wait until it has // actually been written and acked before forget() tears the queue down — diff --git a/app/src/main/java/com/pulseloop/service/ScoresContext.kt b/app/src/main/java/com/pulseloop/service/ScoresContext.kt index 7e485151..d82e1906 100644 --- a/app/src/main/java/com/pulseloop/service/ScoresContext.kt +++ b/app/src/main/java/com/pulseloop/service/ScoresContext.kt @@ -1,5 +1,7 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr + import com.pulseloop.data.PulseLoopDatabase import kotlinx.serialization.Serializable @@ -35,7 +37,7 @@ data class ScoresContext( val cardioLoadBand: String? = null, /** Today's scheduled medications and supplements with their state ("Vitamin D 08:00: taken"). */ val medsToday: List = emptyList(), - val note: String = "Scores are PulseLoop estimates from ring data compared with the user's own baseline, not medical measurements.", + val note: String = tr("Scores are PulseLoop estimates from ring data compared with the user's own baseline, not medical measurements."), ) { /** Short stable string for coach-summary regeneration signatures. */ fun signature(): String = listOf(readinessStatus, readiness, activityScore, baselineNightsCollected).joinToString("|") + diff --git a/app/src/main/java/com/pulseloop/service/SleepInsights.kt b/app/src/main/java/com/pulseloop/service/SleepInsights.kt index c6584b89..5b73034a 100644 --- a/app/src/main/java/com/pulseloop/service/SleepInsights.kt +++ b/app/src/main/java/com/pulseloop/service/SleepInsights.kt @@ -1,5 +1,8 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf + import com.pulseloop.data.DemoDataPolicy import com.pulseloop.data.entity.SleepSessionEntity import com.pulseloop.data.entity.SleepStageBlockEntity @@ -104,50 +107,50 @@ object SleepScore { if (asleep > 0 && goalMinutes > 0) { val r = asleep / goalMinutes out += ScoreContributor( - "Total sleep", + tr("Total sleep"), Readiness.curve(r, listOf(0.0 to 0.0, 0.5 to 30.0, 0.7 to 60.0, 0.85 to 80.0, 1.0 to 100.0)), - "${SleepFormat.duration(asleep.roundToInt())} of ${SleepFormat.duration(goalMinutes)} goal", - "How long you were asleep, compared with your sleep goal. Most adults need 7 to 9 hours.", + trf("{0} of {1} goal", SleepFormat.duration(asleep.roundToInt()), SleepFormat.duration(goalMinutes)), + tr("How long you were asleep, compared with your sleep goal. Most adults need 7 to 9 hours."), 0.35, ) } if (asleep > 0 && span > 0 && hasAwakeSignal) { val eff = (asleep / span).coerceAtMost(1.0) out += ScoreContributor( - "Efficiency", + tr("Efficiency"), Readiness.curve(eff, listOf(0.4 to 0.0, 0.6 to 40.0, 0.75 to 70.0, 0.85 to 90.0, 0.9 to 100.0)), - "${(eff * 100).roundToInt()}% of the night asleep", - "The share of your time in bed spent asleep. Around 85% or more is considered good.", + trf("{0}% of the night asleep", (eff * 100).roundToInt()), + tr("The share of your time in bed spent asleep. Around 85% or more is considered good."), 0.15, ) } if (blocks.isNotEmpty()) { val deepMin = minutes(SleepStage.DEEP) out += ScoreContributor( - "Deep sleep", + tr("Deep sleep"), Readiness.curve(deepMin.toDouble(), listOf(0.0 to 0.0, 30.0 to 50.0, 45.0 to 70.0, 60.0 to 85.0, 75.0 to 100.0)), SleepFormat.duration(deepMin), - "Deep sleep is when the body does most of its physical recovery. Around 1 to 1.5 hours is typical for younger adults, and it tends to shrink with age.", + tr("Deep sleep is when the body does most of its physical recovery. Around 1 to 1.5 hours is typical for younger adults, and it tends to shrink with age."), 0.20, ) } if (blocks.any { it.stageRaw == SleepStage.REM.name }) { val remMin = minutes(SleepStage.REM) out += ScoreContributor( - "REM sleep", + tr("REM sleep"), Readiness.curve(remMin.toDouble(), listOf(0.0 to 0.0, 30.0 to 50.0, 60.0 to 80.0, 90.0 to 100.0)), SleepFormat.duration(remMin), - "REM sleep supports memory and mood. It usually makes up 20 to 25% of a night, about 90 minutes or more.", + tr("REM sleep supports memory and mood. It usually makes up 20 to 25% of a night, about 90 minutes or more."), 0.10, ) } if (hasAwakeSignal && blocks.isNotEmpty()) { val awakeMin = awakeMinutes(blocks) out += ScoreContributor( - "Restfulness", + tr("Restfulness"), Readiness.curve(awakeMin.toDouble(), listOf(20.0 to 100.0, 40.0 to 80.0, 60.0 to 60.0, 120.0 to 20.0, 180.0 to 0.0)), - "${SleepFormat.duration(awakeMin)} awake during the night", - "How much you were awake once asleep. Some waking is normal; long or frequent wake-ups lower this.", + trf("{0} awake during the night", SleepFormat.duration(awakeMin)), + tr("How much you were awake once asleep. Some waking is normal; long or frequent wake-ups lower this."), 0.10, ) } @@ -157,10 +160,10 @@ object SleepScore { val minutes = mid.hour * 60 + mid.minute val m = (if (minutes >= 12 * 60) minutes - 24 * 60 else minutes).toDouble() out += ScoreContributor( - "Timing", + tr("Timing"), Readiness.curve(m, listOf(-240.0 to 40.0, -60.0 to 100.0, 210.0 to 100.0, 300.0 to 70.0, 420.0 to 40.0)), - "Midpoint of sleep at %02d:%02d".format(mid.hour, mid.minute), - "Whether your sleep lines up with your body clock. A midpoint between midnight and about 3:30 am is ideal for most people.", + tr("Midpoint of sleep at %02d:%02d").format(mid.hour, mid.minute), + tr("Whether your sleep lines up with your body clock. A midpoint between midnight and about 3:30 am is ideal for most people."), 0.10, ) } @@ -510,41 +513,41 @@ object SleepInsights { val deepPct = score.deepPct val awakePct = score.awakePct val chips = mutableListOf() - if (session.totalMinutes in 420..540) chips.add("Good duration") - if (deepPct in 13..23) chips.add("Deep sleep balanced") - else if (deepPct > 23) chips.add("Deep sleep strong") - if (awakePct != null && awakePct <= 10) chips.add("Awake time low") + if (session.totalMinutes in 420..540) chips.add(tr("Good duration")) + if (deepPct in 13..23) chips.add(tr("Deep sleep balanced")) + else if (deepPct > 23) chips.add(tr("Deep sleep strong")) + if (awakePct != null && awakePct <= 10) chips.add(tr("Awake time low")) if (score.score >= 85) { val body = if ((activitySteps ?: 0) > 5000) - "Looks like a strong night after a more active day. Your duration was solid and deep sleep made up a healthy part of the night, which kept the score high." - else "Your sleep duration and stage balance were strong. Deep sleep looked supportive, which helped keep the overall score high." - return SleepCoach("Strong recovery signal", body, chips.ifEmpty { listOf("Excellent") }.take(3)) + tr("Looks like a strong night after a more active day. Your duration was solid and deep sleep made up a healthy part of the night, which kept the score high.") + else tr("Your sleep duration and stage balance were strong. Deep sleep looked supportive, which helped keep the overall score high.") + return SleepCoach(tr("Strong recovery signal"), body, chips.ifEmpty { listOf(tr("Excellent")) }.take(3)) } if (awakePct != null && awakePct > 15) { return SleepCoach( - "Good sleep, with some restlessness", - "You slept long enough, but awake time was a bit elevated. If this repeats, look at late caffeine, alcohol, temperature, or stress near bedtime.", - (listOf("Awake time elevated") + chips).take(3), + tr("Good sleep, with some restlessness"), + tr("You slept long enough, but awake time was a bit elevated. If this repeats, look at late caffeine, alcohol, temperature, or stress near bedtime."), + (listOf(tr("Awake time elevated")) + chips).take(3), ) } if (session.totalMinutes < 390) { return SleepCoach( - "Duration held the score back", - "The stage mix was useful, but total sleep time was short for a full recovery window. A slightly earlier wind-down would likely improve tomorrow's score.", - (listOf("Short duration") + chips).take(3), + tr("Duration held the score back"), + tr("The stage mix was useful, but total sleep time was short for a full recovery window. A slightly earlier wind-down would likely improve tomorrow's score."), + (listOf(tr("Short duration")) + chips).take(3), ) } return SleepCoach( - "Solid night overall", - "Your sleep was in a workable range, with the score shaped mostly by duration and stage balance. Deep and light sleep were readable enough to give a useful recovery snapshot.", - chips.ifEmpty { listOf("Good") }.take(3), + tr("Solid night overall"), + tr("Your sleep was in a workable range, with the score shaped mostly by duration and stage balance. Deep and light sleep were readable enough to give a useful recovery snapshot."), + chips.ifEmpty { listOf(tr("Good")) }.take(3), ) } val dayNoDataCoach = SleepCoach( - "No sleep tracked last night", - "I don't see sleep data for last night. Wear your ring overnight and sync in the morning so I can compare your sleep against your baseline.", + tr("No sleep tracked last night"), + tr("I don't see sleep data for last night. Wear your ring overnight and sync in the morning so I can compare your sleep against your baseline."), emptyList(), ) @@ -562,8 +565,8 @@ object SleepInsights { if (valid.size < minAggNights) { val nightWord = if (valid.size == 1) "night" else "nights" return SleepCoach( - "Not enough $periodWord data yet", - "I only have ${valid.size} tracked $nightWord for this $periodWord. Wear the ring overnight for a few more nights and I'll build a reliable ${periodWord}ly picture.", + trf("Not enough {0} data yet", periodWord), + trf("I only have {0} tracked {1} for this {2}. Wear the ring overnight for a few more nights and I'll build a reliable {3}ly picture.", valid.size, nightWord, periodWord, periodWord), listOf(nightsTrackedChip(valid.size, expectedNights)), ) } @@ -573,7 +576,7 @@ object SleepInsights { durationConsistency(valid)?.let { consistencyChip(it) }?.let { chips.add(it) } val avgText = SleepFormat.duration(avgMin) - val coveragePhrase = "${valid.size} of $expectedNights nights tracked" + val coveragePhrase = trf("{0} of {1} nights tracked", valid.size, expectedNights) return when (range) { SleepRangeKey.WEEK -> { @@ -581,51 +584,51 @@ object SleepInsights { val missing = expectedNights - valid.size val missingWord = if (missing == 1) "night" else "nights" val body = if (incomplete) - "You averaged $avgText across ${valid.size} tracked nights this week. That's a useful read, but $missing missing $missingWord mean the trend is still incomplete." - else "You averaged $avgText across the full week. Your nights were tracked consistently, so this is a dependable picture of where your sleep sits right now." - SleepCoach("Your week at a glance", body, chips.take(3)) + trf("You averaged {0} across {1} tracked nights this week. That's a useful read, but {2} missing {3} mean the trend is still incomplete.", avgText, valid.size, missing, missingWord) + else trf("You averaged {0} across the full week. Your nights were tracked consistently, so this is a dependable picture of where your sleep sits right now.", avgText) + SleepCoach(tr("Your week at a glance"), body, chips.take(3)) } SleepRangeKey.MONTH -> { val sparse = valid.size.toDouble() < expectedNights.toDouble() * 0.5 val body = if (sparse) - "Your monthly average is $avgText, but coverage is low ($coveragePhrase), so I'd treat that number cautiously. More nights tracked will sharpen the trend." - else "Your monthly average is $avgText across $coveragePhrase. The biggest lever is consistency — a few short nights move this number more than any single great one." - SleepCoach("Your month in sleep", body, chips.take(3)) + trf("Your monthly average is {0}, but coverage is low ({1}), so I'd treat that number cautiously. More nights tracked will sharpen the trend.", avgText, coveragePhrase) + else trf("Your monthly average is {0} across {1}. The biggest lever is consistency — a few short nights move this number more than any single great one.", avgText, coveragePhrase) + SleepCoach(tr("Your month in sleep"), body, chips.take(3)) } else -> SleepCoach( - "Your long-term sleep trend", - "Across the year your tracked average is $avgText over ${valid.size} nights. The long-term trend is still forming — as more months fill in, I'll be able to compare seasonal changes and consistency.", + tr("Your long-term sleep trend"), + trf("Across the year your tracked average is {0} over {1} nights. The long-term trend is still forming — as more months fill in, I'll be able to compare seasonal changes and consistency.", avgText, valid.size), chips.take(3), ) } } - private fun nightsTrackedChip(valid: Int, expected: Int) = "$valid of $expected tracked" + private fun nightsTrackedChip(valid: Int, expected: Int) = trf("{0} of {1} tracked", valid, expected) private fun goalDeltaChip(avgMin: Int, goalMin: Int?): String? { if (goalMin == null) return null val delta = avgMin - goalMin if (abs(delta) <= 20) return "On target" - return if (delta < 0) "Below goal" else "Above goal" + return if (delta < 0) tr("Below goal") else tr("Above goal") } private fun consistencyChip(sd: Double): String? = when { - sd <= 40 -> "Consistent" - sd >= 80 -> "Variable nights" + sd <= 40 -> tr("Consistent") + sd >= 80 -> tr("Variable nights") else -> null } // ── No-data states ─────────────────────────────────────────────────── fun noDataState(range: SleepRangeKey): SleepNoDataState = when (range) { - SleepRangeKey.DAY -> SleepNoDataState("Last Sleep", "No sleep captured last night", - "Wear your ring overnight so PulseLoop can track your next night.") - SleepRangeKey.WEEK -> SleepNoDataState("Weekly Sleep", "Not enough weekly data", - "Wear your ring overnight for a few nights to build a weekly view.") - SleepRangeKey.MONTH -> SleepNoDataState("Monthly Sleep", "Not enough monthly data", - "Track more nights this month to see a monthly average.") - SleepRangeKey.YEAR -> SleepNoDataState("Yearly Sleep", "Not enough yearly data", - "Long-term insights appear as more nights are tracked.") + SleepRangeKey.DAY -> SleepNoDataState(tr("Last Sleep"), tr("No sleep captured last night"), + tr("Wear your ring overnight so PulseLoop can track your next night.")) + SleepRangeKey.WEEK -> SleepNoDataState(tr("Weekly Sleep"), tr("Not enough weekly data"), + tr("Wear your ring overnight for a few nights to build a weekly view.")) + SleepRangeKey.MONTH -> SleepNoDataState(tr("Monthly Sleep"), tr("Not enough monthly data"), + tr("Track more nights this month to see a monthly average.")) + SleepRangeKey.YEAR -> SleepNoDataState(tr("Yearly Sleep"), tr("Not enough yearly data"), + tr("Long-term insights appear as more nights are tracked.")) } // ── Histogram builders ─────────────────────────────────────────────── diff --git a/app/src/main/java/com/pulseloop/service/VitalsThresholdEngine.kt b/app/src/main/java/com/pulseloop/service/VitalsThresholdEngine.kt index b9a1f989..b7bd5d4f 100644 --- a/app/src/main/java/com/pulseloop/service/VitalsThresholdEngine.kt +++ b/app/src/main/java/com/pulseloop/service/VitalsThresholdEngine.kt @@ -1,5 +1,8 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf + import kotlin.math.abs import kotlin.math.roundToInt @@ -126,7 +129,7 @@ object VitalsThresholdEngine { val worse = ZoneSeverity.worst(sysZone.severity, diaZone.severity) // Pick whichever axis produced the worse severity for the label/explanation. val primary = if (worse == sysZone.severity) sysZone else diaZone - val confidence = if (hasCuffReference) "Estimated" else "Estimated · calibrate with a cuff" + val confidence = if (hasCuffReference) tr("Estimated") else tr("Estimated · calibrate with a cuff") return MetricInterpretation( primaryZone = primary, allZones = systolicZones(), @@ -182,40 +185,40 @@ object VitalsThresholdEngine { val lowColor: VitalColorToken when { athlete -> { - lowLabel = "Athletic" + lowLabel = tr("Athletic") lowSeverity = ZoneSeverity.OPTIMAL lowColor = VitalColorToken.MetricAccent(MetricKind.HEART_RATE) - lowExplanation = "A low resting heart rate is common with high fitness." + lowExplanation = tr("A low resting heart rate is common with high fitness.") } profile.usesBetaBlockers -> { - lowLabel = "Low (medication)" + lowLabel = tr("Low (medication)") lowSeverity = ZoneSeverity.NORMAL lowColor = VitalColorToken.Blue - lowExplanation = "Beta-blockers lower heart rate; this is expected on that medication." + lowExplanation = tr("Beta-blockers lower heart rate; this is expected on that medication.") } else -> { - lowLabel = "Low" + lowLabel = tr("Low") lowSeverity = ZoneSeverity.WATCH lowColor = VitalColorToken.Blue - lowExplanation = "Below the typical resting range. Often fine, but worth noting if you feel faint." + lowExplanation = tr("Below the typical resting range. Often fine, but worth noting if you feel faint.") } } val zones = mutableListOf() zones.add(MetricZone("hr.low", lowLabel, null, lowUpper, lowSeverity, lowColor, lowExplanation)) if (athlete && athleticUpper != null) { - zones.add(MetricZone("hr.athletic", "Athletic", lowUpper, athleticUpper, ZoneSeverity.OPTIMAL, VitalColorToken.Mint, "Athletic resting range.")) + zones.add(MetricZone("hr.athletic", tr("Athletic"), lowUpper, athleticUpper, ZoneSeverity.OPTIMAL, VitalColorToken.Mint, tr("Athletic resting range."))) } val normalLow = if (athlete && athleticUpper != null) athleticUpper else lowUpper - zones.add(MetricZone("hr.normal", "Normal", normalLow, elevatedStart, + zones.add(MetricZone("hr.normal", tr("Normal"), normalLow, elevatedStart, ZoneSeverity.NORMAL, VitalColorToken.MetricAccent(MetricKind.HEART_RATE), - "A typical resting heart rate for adults.")) - zones.add(MetricZone("hr.elevated", "Elevated", elevatedStart, highStart, + tr("A typical resting heart rate for adults."))) + zones.add(MetricZone("hr.elevated", tr("Elevated"), elevatedStart, highStart, ZoneSeverity.WATCH, VitalColorToken.Amber, - "Above the typical resting range. Activity, caffeine, or stress can raise it.")) - zones.add(MetricZone("hr.high", "High", highStart, null, + tr("Above the typical resting range. Activity, caffeine, or stress can raise it."))) + zones.add(MetricZone("hr.high", tr("High"), highStart, null, ZoneSeverity.HIGH, VitalColorToken.BrightRed, - "A high resting heart rate. Talk to a clinician if it persists at rest.")) + tr("A high resting heart rate. Talk to a clinician if it persists at rest."))) return zones } @@ -229,27 +232,27 @@ object VitalsThresholdEngine { // and note it, rather than alarming on a normal-for-altitude reading. val highAltitude = (profile.altitudeMeters ?: 0.0) > 2000 val watchUpper = if (highAltitude || profile.hasKnownLungCondition) 93.0 else 95.0 - val altitudeNote = if (highAltitude) " Expected values are lower at altitude." else "" + val altitudeNote = if (highAltitude) tr(" Expected values are lower at altitude.") else "" return listOf( MetricZone( - "spo2.critical", "Very low", null, 89.0, + "spo2.critical", tr("Very low"), null, 89.0, ZoneSeverity.CRITICAL, VitalColorToken.Red, - "An urgently low oxygen reading. Seek care if you also feel unwell.$altitudeNote", + trf("An urgently low oxygen reading. Seek care if you also feel unwell.{0}", altitudeNote), ), MetricZone( - "spo2.high", "Low", 89.0, 93.0, + "spo2.high", tr("Low"), 89.0, 93.0, ZoneSeverity.HIGH, VitalColorToken.Orange, - "Low blood oxygen. Re-measure when still; talk to a clinician if persistent.$altitudeNote", + trf("Low blood oxygen. Re-measure when still; talk to a clinician if persistent.{0}", altitudeNote), ), MetricZone( - "spo2.watch", "Slightly low", 93.0, watchUpper, + "spo2.watch", tr("Slightly low"), 93.0, watchUpper, ZoneSeverity.WATCH, VitalColorToken.Amber, - "Slightly below the typical range.$altitudeNote", + trf("Slightly below the typical range.{0}", altitudeNote), ), MetricZone( - "spo2.normal", "Normal", watchUpper, null, + "spo2.normal", tr("Normal"), watchUpper, null, ZoneSeverity.NORMAL, VitalColorToken.Cyan, - "A normal blood-oxygen level is 95–100%.$altitudeNote", + trf("A normal blood-oxygen level is 95–100%.{0}", altitudeNote), ), ) } @@ -261,9 +264,9 @@ object VitalsThresholdEngine { // No baseline yet → show the metric's own purple accent (not a gray "unknown" color). return listOf( MetricZone( - "hrv.building", "Building baseline", null, null, + "hrv.building", tr("Building baseline"), null, null, ZoneSeverity.UNKNOWN, VitalColorToken.MetricAccent(MetricKind.HRV), - "HRV is personal. Wear your ring for about a week to learn your baseline.", + tr("HRV is personal. Wear your ring for about a week to learn your baseline."), ), ) } @@ -271,24 +274,24 @@ object VitalsThresholdEngine { val sd = baseline.standardDeviation return listOf( MetricZone( - "hrv.below", "Below baseline", null, mean - sd, + "hrv.below", tr("Below baseline"), null, mean - sd, ZoneSeverity.HIGH, VitalColorToken.Amber, - "Notably below your typical HRV — often linked to stress, poor sleep, or strain.", + tr("Notably below your typical HRV — often linked to stress, poor sleep, or strain."), ), MetricZone( - "hrv.slightlyBelow", "Slightly below", mean - sd, mean - 0.5 * sd, + "hrv.slightlyBelow", tr("Slightly below"), mean - sd, mean - 0.5 * sd, ZoneSeverity.WATCH, VitalColorToken.SoftAmber, - "A little below your usual range.", + tr("A little below your usual range."), ), MetricZone( - "hrv.near", "Near baseline", mean - 0.5 * sd, mean + 0.5 * sd, + "hrv.near", tr("Near baseline"), mean - 0.5 * sd, mean + 0.5 * sd, ZoneSeverity.NORMAL, VitalColorToken.MetricAccent(MetricKind.HRV), - "Around your personal baseline.", + tr("Around your personal baseline."), ), MetricZone( - "hrv.above", "Above baseline", mean + 0.5 * sd, null, + "hrv.above", tr("Above baseline"), mean + 0.5 * sd, null, ZoneSeverity.OPTIMAL, VitalColorToken.Mint, - "Above your typical HRV — often a sign of good recovery.", + tr("Above your typical HRV — often a sign of good recovery."), ), ) } @@ -300,7 +303,7 @@ object VitalsThresholdEngine { val zone = zones[0] return MetricInterpretation( primaryZone = zone, allZones = zones, displayLabel = zone.label, - explanation = zone.explanation, confidenceLabel = "Building baseline", isEstimated = false, + explanation = zone.explanation, confidenceLabel = tr("Building baseline"), isEstimated = false, ) } val zone = zoneContaining(value, zones) @@ -310,7 +313,7 @@ object VitalsThresholdEngine { return MetricInterpretation( primaryZone = zone, allZones = zones, displayLabel = zone.label, explanation = zone.explanation, - confidenceLabel = if (delta == 0) "At baseline" else "$delta% $direction baseline", + confidenceLabel = if (delta == 0) tr("At baseline") else trf("{0}% {1} baseline", delta, direction), isEstimated = false, ) } @@ -319,39 +322,39 @@ object VitalsThresholdEngine { private fun stressZones(): List = listOf( MetricZone( - "stress.calm", "Calm", null, 26.0, - ZoneSeverity.OPTIMAL, VitalColorToken.Mint, "Low stress score — relaxed.", + "stress.calm", tr("Calm"), null, 26.0, + ZoneSeverity.OPTIMAL, VitalColorToken.Mint, tr("Low stress score — relaxed."), ), MetricZone( - "stress.normal", "Normal", 26.0, 51.0, - ZoneSeverity.NORMAL, VitalColorToken.Cyan, "A typical daytime stress score.", + "stress.normal", tr("Normal"), 26.0, 51.0, + ZoneSeverity.NORMAL, VitalColorToken.Cyan, tr("A typical daytime stress score."), ), MetricZone( - "stress.elevated", "Elevated", 51.0, 76.0, - ZoneSeverity.WATCH, VitalColorToken.Amber, "Elevated stress — consider a short break.", + "stress.elevated", tr("Elevated"), 51.0, 76.0, + ZoneSeverity.WATCH, VitalColorToken.Amber, tr("Elevated stress — consider a short break."), ), MetricZone( - "stress.high", "High", 76.0, null, - ZoneSeverity.HIGH, VitalColorToken.Red, "High stress score. Wellness estimate, not a diagnosis.", + "stress.high", tr("High"), 76.0, null, + ZoneSeverity.HIGH, VitalColorToken.Red, tr("High stress score. Wellness estimate, not a diagnosis."), ), ) private fun fatigueZones(): List = listOf( MetricZone( - "fatigue.fresh", "Fresh", null, 25.0, - ZoneSeverity.OPTIMAL, VitalColorToken.Mint, "Low fatigue — well recovered.", + "fatigue.fresh", tr("Fresh"), null, 25.0, + ZoneSeverity.OPTIMAL, VitalColorToken.Mint, tr("Low fatigue — well recovered."), ), MetricZone( - "fatigue.mild", "Mild", 25.0, 50.0, - ZoneSeverity.NORMAL, VitalColorToken.Cyan, "Mild fatigue.", + "fatigue.mild", tr("Mild"), 25.0, 50.0, + ZoneSeverity.NORMAL, VitalColorToken.Cyan, tr("Mild fatigue."), ), MetricZone( - "fatigue.tired", "Tired", 50.0, 75.0, - ZoneSeverity.WATCH, VitalColorToken.Amber, "Tired — consider lighter activity and good sleep.", + "fatigue.tired", tr("Tired"), 50.0, 75.0, + ZoneSeverity.WATCH, VitalColorToken.Amber, tr("Tired — consider lighter activity and good sleep."), ), MetricZone( - "fatigue.high", "High fatigue", 75.0, null, - ZoneSeverity.HIGH, VitalColorToken.Red, "High fatigue score. Wellness estimate from the ring.", + "fatigue.high", tr("High fatigue"), 75.0, null, + ZoneSeverity.HIGH, VitalColorToken.Red, tr("High fatigue score. Wellness estimate from the ring."), ), ) @@ -365,52 +368,52 @@ object VitalsThresholdEngine { private fun systolicZones(): List = listOf( MetricZone( - "bp.sys.low", "Low", null, 90.0, - ZoneSeverity.WATCH, VitalColorToken.Blue, "Low systolic pressure (below 90).", + "bp.sys.low", tr("Low"), null, 90.0, + ZoneSeverity.WATCH, VitalColorToken.Blue, tr("Low systolic pressure (below 90)."), ), MetricZone( - "bp.sys.normal", "Normal", 90.0, 120.0, - ZoneSeverity.NORMAL, VitalColorToken.Mint, "Normal blood pressure is below 120/80.", + "bp.sys.normal", tr("Normal"), 90.0, 120.0, + ZoneSeverity.NORMAL, VitalColorToken.Mint, tr("Normal blood pressure is below 120/80."), ), MetricZone( - "bp.sys.elevated", "Elevated", 120.0, 130.0, - ZoneSeverity.WATCH, VitalColorToken.Amber, "Elevated systolic (120–129).", + "bp.sys.elevated", tr("Elevated"), 120.0, 130.0, + ZoneSeverity.WATCH, VitalColorToken.Amber, tr("Elevated systolic (120–129)."), ), MetricZone( - "bp.sys.stage1", "Stage 1", 130.0, 140.0, - ZoneSeverity.HIGH, VitalColorToken.Orange, "Stage 1 hypertension range (systolic 130–139).", + "bp.sys.stage1", tr("Stage 1"), 130.0, 140.0, + ZoneSeverity.HIGH, VitalColorToken.Orange, tr("Stage 1 hypertension range (systolic 130–139)."), ), MetricZone( - "bp.sys.stage2", "Stage 2", 140.0, 180.0, - ZoneSeverity.HIGH, VitalColorToken.Red, "Stage 2 hypertension range (systolic ≥140).", + "bp.sys.stage2", tr("Stage 2"), 140.0, 180.0, + ZoneSeverity.HIGH, VitalColorToken.Red, tr("Stage 2 hypertension range (systolic ≥140)."), ), MetricZone( - "bp.sys.crisis", "Severe", 180.0, null, - ZoneSeverity.CRITICAL, VitalColorToken.Red, "Severe range (systolic >180). Seek care if confirmed.", + "bp.sys.crisis", tr("Severe"), 180.0, null, + ZoneSeverity.CRITICAL, VitalColorToken.Red, tr("Severe range (systolic >180). Seek care if confirmed."), ), ) private fun diastolicZones(): List = listOf( MetricZone( - "bp.dia.low", "Low", null, 60.0, - ZoneSeverity.WATCH, VitalColorToken.Blue, "Low diastolic pressure (below 60).", + "bp.dia.low", tr("Low"), null, 60.0, + ZoneSeverity.WATCH, VitalColorToken.Blue, tr("Low diastolic pressure (below 60)."), ), MetricZone( - "bp.dia.normal", "Normal", 60.0, 80.0, - ZoneSeverity.NORMAL, VitalColorToken.Mint, "Normal diastolic is below 80.", + "bp.dia.normal", tr("Normal"), 60.0, 80.0, + ZoneSeverity.NORMAL, VitalColorToken.Mint, tr("Normal diastolic is below 80."), ), // Note: there is no diastolic "Elevated" category — 80–89 is already Stage 1 by AHA. MetricZone( - "bp.dia.stage1", "Stage 1", 80.0, 90.0, - ZoneSeverity.HIGH, VitalColorToken.Orange, "Stage 1 hypertension range (diastolic 80–89).", + "bp.dia.stage1", tr("Stage 1"), 80.0, 90.0, + ZoneSeverity.HIGH, VitalColorToken.Orange, tr("Stage 1 hypertension range (diastolic 80–89)."), ), MetricZone( - "bp.dia.stage2", "Stage 2", 90.0, 120.0, - ZoneSeverity.HIGH, VitalColorToken.Red, "Stage 2 hypertension range (diastolic ≥90).", + "bp.dia.stage2", tr("Stage 2"), 90.0, 120.0, + ZoneSeverity.HIGH, VitalColorToken.Red, tr("Stage 2 hypertension range (diastolic ≥90)."), ), MetricZone( - "bp.dia.crisis", "Severe", 120.0, null, - ZoneSeverity.CRITICAL, VitalColorToken.Red, "Severe range (diastolic >120). Seek care if confirmed.", + "bp.dia.crisis", tr("Severe"), 120.0, null, + ZoneSeverity.CRITICAL, VitalColorToken.Red, tr("Severe range (diastolic >120). Seek care if confirmed."), ), ) @@ -419,58 +422,58 @@ object VitalsThresholdEngine { private fun glucoseZones(context: MeasurementContext): List = when (context) { MeasurementContext.FASTING -> listOf( MetricZone( - "glucose.low", "Low", null, 70.0, - ZoneSeverity.HIGH, VitalColorToken.Red, "Below 70 mg/dL is low.", + "glucose.low", tr("Low"), null, 70.0, + ZoneSeverity.HIGH, VitalColorToken.Red, tr("Below 70 mg/dL is low."), ), MetricZone( - "glucose.normal", "Normal", 70.0, 100.0, - ZoneSeverity.NORMAL, VitalColorToken.Mint, "Fasting normal is up to 99 mg/dL.", + "glucose.normal", tr("Normal"), 70.0, 100.0, + ZoneSeverity.NORMAL, VitalColorToken.Mint, tr("Fasting normal is up to 99 mg/dL."), ), MetricZone( - "glucose.elevated", "Elevated", 100.0, 126.0, - ZoneSeverity.WATCH, VitalColorToken.Amber, "Fasting 100–125 is above the typical range.", + "glucose.elevated", tr("Elevated"), 100.0, 126.0, + ZoneSeverity.WATCH, VitalColorToken.Amber, tr("Fasting 100–125 is above the typical range."), ), MetricZone( - "glucose.high", "High", 126.0, null, - ZoneSeverity.HIGH, VitalColorToken.Red, "Fasting ≥126. Talk to a clinician if confirmed by a meter.", + "glucose.high", tr("High"), 126.0, null, + ZoneSeverity.HIGH, VitalColorToken.Red, tr("Fasting ≥126. Talk to a clinician if confirmed by a meter."), ), ) MeasurementContext.POST_MEAL -> listOf( MetricZone( - "glucose.low", "Low", null, 70.0, - ZoneSeverity.HIGH, VitalColorToken.Red, "Below 70 mg/dL is low.", + "glucose.low", tr("Low"), null, 70.0, + ZoneSeverity.HIGH, VitalColorToken.Red, tr("Below 70 mg/dL is low."), ), MetricZone( - "glucose.normal", "Normal", 70.0, 140.0, - ZoneSeverity.NORMAL, VitalColorToken.Mint, "Two-hour post-meal normal is up to 140 mg/dL.", + "glucose.normal", tr("Normal"), 70.0, 140.0, + ZoneSeverity.NORMAL, VitalColorToken.Mint, tr("Two-hour post-meal normal is up to 140 mg/dL."), ), MetricZone( - "glucose.elevated", "Elevated", 140.0, 200.0, - ZoneSeverity.WATCH, VitalColorToken.Amber, "Two-hour 140–199 is above the typical range.", + "glucose.elevated", tr("Elevated"), 140.0, 200.0, + ZoneSeverity.WATCH, VitalColorToken.Amber, tr("Two-hour 140–199 is above the typical range."), ), MetricZone( - "glucose.high", "High", 200.0, null, - ZoneSeverity.HIGH, VitalColorToken.Red, "Two-hour ≥200. Confirm with a meter and a clinician.", + "glucose.high", tr("High"), 200.0, null, + ZoneSeverity.HIGH, VitalColorToken.Red, tr("Two-hour ≥200. Confirm with a meter and a clinician."), ), ) else -> // Unknown / random context: conservative labels, NO "prediabetes"/"diabetes" wording. listOf( MetricZone( - "glucose.low", "Low", null, 70.0, - ZoneSeverity.HIGH, VitalColorToken.Red, "Below 70 mg/dL is low.", + "glucose.low", tr("Low"), null, 70.0, + ZoneSeverity.HIGH, VitalColorToken.Red, tr("Below 70 mg/dL is low."), ), MetricZone( - "glucose.typical", "Typical", 70.0, 140.0, - ZoneSeverity.NORMAL, VitalColorToken.Mint, "Within a typical range for a non-fasting reading.", + "glucose.typical", tr("Typical"), 70.0, 140.0, + ZoneSeverity.NORMAL, VitalColorToken.Mint, tr("Within a typical range for a non-fasting reading."), ), MetricZone( - "glucose.elevated", "Elevated", 140.0, 200.0, - ZoneSeverity.WATCH, VitalColorToken.Amber, "Above the typical range. Context (meals) affects this.", + "glucose.elevated", tr("Elevated"), 140.0, 200.0, + ZoneSeverity.WATCH, VitalColorToken.Amber, tr("Above the typical range. Context (meals) affects this."), ), MetricZone( - "glucose.veryHigh", "Very high", 200.0, null, - ZoneSeverity.HIGH, VitalColorToken.Red, "A high reading regardless of context. Confirm with a meter.", + "glucose.veryHigh", tr("Very high"), 200.0, null, + ZoneSeverity.HIGH, VitalColorToken.Red, tr("A high reading regardless of context. Confirm with a meter."), ), ) } @@ -481,7 +484,7 @@ object VitalsThresholdEngine { return MetricInterpretation( primaryZone = zone, allZones = zones, displayLabel = zone.label, explanation = zone.explanation, - confidenceLabel = "Estimated — not for dosing or diagnosis", + confidenceLabel = tr("Estimated — not for dosing or diagnosis"), isEstimated = true, ) } @@ -493,17 +496,17 @@ object VitalsThresholdEngine { // absolute, so we keep a single soft "typical" band and flag extremes only. listOf( MetricZone( - "temp.low", "Cool", null, 31.0, - ZoneSeverity.WATCH, VitalColorToken.Blue, "Cooler than typical skin temperature.", + "temp.low", tr("Cool"), null, 31.0, + ZoneSeverity.WATCH, VitalColorToken.Blue, tr("Cooler than typical skin temperature."), ), MetricZone( - "temp.normal", "Typical", 31.0, 36.0, + "temp.normal", tr("Typical"), 31.0, 36.0, ZoneSeverity.NORMAL, VitalColorToken.MetricAccent(MetricKind.TEMPERATURE), - "A typical skin-temperature range from the ring.", + tr("A typical skin-temperature range from the ring."), ), MetricZone( - "temp.high", "Warm", 36.0, null, - ZoneSeverity.WATCH, VitalColorToken.Amber, "Warmer than typical. Trends matter more than a single reading.", + "temp.high", tr("Warm"), 36.0, null, + ZoneSeverity.WATCH, VitalColorToken.Amber, tr("Warmer than typical. Trends matter more than a single reading."), ), ) diff --git a/app/src/main/java/com/pulseloop/service/VitalsZoneModel.kt b/app/src/main/java/com/pulseloop/service/VitalsZoneModel.kt index e4eceda4..449c970f 100644 --- a/app/src/main/java/com/pulseloop/service/VitalsZoneModel.kt +++ b/app/src/main/java/com/pulseloop/service/VitalsZoneModel.kt @@ -1,5 +1,7 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr + import com.pulseloop.ring.MeasurementKind import kotlin.math.sqrt @@ -47,14 +49,14 @@ enum class MetricKind { val title: String get() = when (this) { - HEART_RATE -> "Heart rate" - SPO2 -> "Blood oxygen" + HEART_RATE -> tr("Heart rate") + SPO2 -> tr("Blood oxygen") HRV -> "HRV" - BLOOD_PRESSURE -> "Blood pressure" - STRESS -> "Stress" - FATIGUE -> "Fatigue" - GLUCOSE -> "Blood sugar" - TEMPERATURE -> "Skin temperature" + BLOOD_PRESSURE -> tr("Blood pressure") + STRESS -> tr("Stress") + FATIGUE -> tr("Fatigue") + GLUCOSE -> tr("Blood sugar") + TEMPERATURE -> tr("Skin temperature") } /** Display unit shown after the big value. Empty for unit-less device scores. */ diff --git a/app/src/main/java/com/pulseloop/service/WeeklyRecap.kt b/app/src/main/java/com/pulseloop/service/WeeklyRecap.kt index 1dcad309..7a89b7ca 100644 --- a/app/src/main/java/com/pulseloop/service/WeeklyRecap.kt +++ b/app/src/main/java/com/pulseloop/service/WeeklyRecap.kt @@ -1,5 +1,7 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr + import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas @@ -30,21 +32,21 @@ object WeeklyRecap { fun rows(thisWeek: WeeklyReport.Week, lastWeek: WeeklyReport.Week?, workouts: Int): List = buildList { thisWeek.avgAsleepMinutes?.let { m -> val d = lastWeek?.avgAsleepMinutes?.let { m - it } - add(Row("Sleep a night", SleepFormat.duration(m), d?.let { if (kotlin.math.abs(it) < 5) "same as last week" else "${if (it > 0) "+" else "−"}${SleepFormat.duration(kotlin.math.abs(it))}" })) + add(Row(tr("Sleep a night"), SleepFormat.duration(m), d?.let { if (kotlin.math.abs(it) < 5) "same as last week" else "${if (it > 0) "+" else "−"}${SleepFormat.duration(kotlin.math.abs(it))}" })) } thisWeek.avgSteps?.let { s -> val d = lastWeek?.avgSteps?.takeIf { it > 0 }?.let { ((s - it) * 100.0 / it).roundToInt() } - add(Row("Steps a day", "%,d".format(s), d?.let { if (kotlin.math.abs(it) < 3) "same as last week" else "${if (it > 0) "+" else "−"}${kotlin.math.abs(it)}%" })) + add(Row(tr("Steps a day"), "%,d".format(s), d?.let { if (kotlin.math.abs(it) < 3) "same as last week" else "${if (it > 0) "+" else "−"}${kotlin.math.abs(it)}%" })) } thisWeek.avgRestingHr?.let { r -> val d = lastWeek?.avgRestingHr?.let { (r - it).roundToInt() } - add(Row("Resting heart rate", "${r.roundToInt()} bpm", d?.let { if (it == 0) "same as last week" else "${if (it > 0) "+" else "−"}${kotlin.math.abs(it)} bpm" })) + add(Row(tr("Resting heart rate"), "${r.roundToInt()} bpm", d?.let { if (it == 0) "same as last week" else "${if (it > 0) "+" else "−"}${kotlin.math.abs(it)} bpm" })) } thisWeek.avgHrv?.let { h -> val d = lastWeek?.avgHrv?.takeIf { it > 0 }?.let { ((h - it) / it * 100).roundToInt() } add(Row("HRV", "${h.roundToInt()} ms", d?.let { if (kotlin.math.abs(it) < 3) "same as last week" else "${if (it > 0) "+" else "−"}${kotlin.math.abs(it)}%" })) } - add(Row("Workouts", "$workouts", null)) + add(Row(tr("Workouts"), "$workouts", null)) } suspend fun load(db: PulseLoopDatabase, now: Long = System.currentTimeMillis(), zone: ZoneId = ZoneId.systemDefault()): Recap { @@ -77,7 +79,7 @@ object WeeklyRecap { this.color = color.toInt(); textSize = size; typeface = Typeface.create(mono, if (bold) Typeface.BOLD else Typeface.NORMAL) } val mint = 0xFF43F3B7; val text = 0xFFF2F2F2; val muted = 0xFF7C7B82; val card = 0xFF1C1B1F - c.drawText("MY WEEK", 80f, 150f, paint(mint, 44f, bold = true)) + c.drawText(tr("MY WEEK"), 80f, 150f, paint(mint, 44f, bold = true)) c.drawText(recap.title, 80f, 220f, paint(text, 64f, bold = true)) var y = 300f val cardPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = card.toInt() } @@ -91,7 +93,7 @@ object WeeklyRecap { } y += 190f } - c.drawText("PulseLoop · from my ring, compared with last week", 80f, h - 70f, paint(muted, 28f)) + c.drawText(tr("PulseLoop · from my ring, compared with last week"), 80f, h - 70f, paint(muted, 28f)) val file = File(context.cacheDir, "pulseloop-week.png") file.outputStream().use { bmp.compress(Bitmap.CompressFormat.PNG, 100, it) } bmp.recycle() diff --git a/app/src/main/java/com/pulseloop/service/WorkoutForegroundService.kt b/app/src/main/java/com/pulseloop/service/WorkoutForegroundService.kt index 5717382a..7c6ab3fe 100644 --- a/app/src/main/java/com/pulseloop/service/WorkoutForegroundService.kt +++ b/app/src/main/java/com/pulseloop/service/WorkoutForegroundService.kt @@ -1,5 +1,8 @@ package com.pulseloop.service +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf + import android.app.* import android.content.Context import android.content.Intent @@ -38,7 +41,7 @@ class WorkoutForegroundService : Service() { private var elapsedSec = 0 private var distanceM = 0.0 private var heartRate: Int? = null - private var activityName = "Workout" + private var activityName = tr("Workout") override fun onCreate() { super.onCreate() @@ -138,11 +141,11 @@ class WorkoutForegroundService : Service() { val hr = heartRate?.let { "$it bpm" } ?: "--" val pauseResumeAction = if (status == "paused") { - NotificationCompat.Action.Builder(android.R.drawable.ic_media_play, "Resume", + NotificationCompat.Action.Builder(android.R.drawable.ic_media_play, tr("Resume"), PendingIntent.getService(this, 3, Intent(this, WorkoutForegroundService::class.java).apply { action = ACTION_RESUME }, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)).build() } else { - NotificationCompat.Action.Builder(android.R.drawable.ic_media_pause, "Pause", + NotificationCompat.Action.Builder(android.R.drawable.ic_media_pause, tr("Pause"), PendingIntent.getService(this, 2, Intent(this, WorkoutForegroundService::class.java).apply { action = ACTION_PAUSE }, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)).build() } @@ -155,7 +158,7 @@ class WorkoutForegroundService : Service() { .setPriority(NotificationCompat.PRIORITY_LOW) .setContentIntent(contentIntent(sessionId = null)) .addAction(pauseResumeAction) - .addAction(NotificationCompat.Action.Builder(android.R.drawable.ic_media_play, "Finish", + .addAction(NotificationCompat.Action.Builder(android.R.drawable.ic_media_play, tr("Finish"), PendingIntent.getService(this, 1, Intent(this, WorkoutForegroundService::class.java).apply { action = ACTION_STOP }, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)).build()) .build() @@ -172,11 +175,11 @@ class WorkoutForegroundService : Service() { val units = com.pulseloop.settings.ApiKeyStore(this).resolvedUnitSystem val parts = mutableListOf(formatElapsed(elapsedSeconds)) formatDistance(distanceMeters, units)?.let { parts += it } - calories?.let { parts += "${it.toInt()} cal" } - avgHeartRate?.let { parts += "avg ${it.toInt()} bpm" } + calories?.let { parts += trf("{0} cal", it.toInt()) } + avgHeartRate?.let { parts += trf("avg {0} bpm", it.toInt()) } return NotificationCompat.Builder(this, CHANNEL_ID) - .setContentTitle("$name complete") + .setContentTitle(trf("{0} complete", name)) .setContentText(parts.joinToString(" · ")) .setSmallIcon(android.R.drawable.ic_dialog_map) .setOngoing(false) @@ -216,7 +219,7 @@ class WorkoutForegroundService : Service() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( CHANNEL_ID, "Workout Live", NotificationManager.IMPORTANCE_LOW - ).apply { description = "Live workout tracking" } + ).apply { description = tr("Live workout tracking") } val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager nm.createNotificationChannel(channel) } diff --git a/app/src/main/java/com/pulseloop/settings/UnitSystem.kt b/app/src/main/java/com/pulseloop/settings/UnitSystem.kt index 746ffe4d..035376ea 100644 --- a/app/src/main/java/com/pulseloop/settings/UnitSystem.kt +++ b/app/src/main/java/com/pulseloop/settings/UnitSystem.kt @@ -1,14 +1,17 @@ package com.pulseloop.settings +import com.pulseloop.ui.i18n.tr + import java.util.Locale /** * Unit system conversion utilities. * Auto-detects from device locale, supports manual toggle. */ -enum class UnitSystem(val label: String) { +enum class UnitSystem(private val labelEn: String) { METRIC("Metric (km, kg, °C)"), IMPERIAL("Imperial (mi, lbs, °F)"); + val label: String get() = tr(labelEn) companion object { fun fromLocale(locale: Locale = Locale.getDefault()): UnitSystem { 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 db6a909a..a0080bd1 100644 --- a/app/src/main/java/com/pulseloop/ui/components/ActivityRings.kt +++ b/app/src/main/java/com/pulseloop/ui/components/ActivityRings.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.components +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import com.pulseloop.ui.theme.trackBrush @@ -57,8 +59,8 @@ fun ActivityRings( ) { // Drawn arcs say nothing to TalkBack; speak each ring's share of its goal instead. val description = tr("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()}%" + val name = labels.getOrNull(i) ?: trf("ring {0}", i + 1) + if (ring.value == null) trf("{0} unavailable", name) else "$name ${(ring.progress * 100).toInt()}%" }.joinToString(", ") Canvas(modifier.size(size).clearAndSetSemantics { contentDescription = description }) { val strokePx = strokeWidth.toPx() 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 7541b836..20a952e9 100644 --- a/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt +++ b/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.components +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import androidx.compose.animation.core.RepeatMode @@ -116,11 +118,11 @@ fun ConnectionStatusPill( } val label = sourceLabel ?: when (state) { RingConnectionState.CONNECTED -> - if (batteryPercent != null && batteryPercent > 0) "Connected · $batteryPercent%" else "Connected" + if (batteryPercent != null && batteryPercent > 0) trf("Connected · {0}%", batteryPercent) else tr("Connected") RingConnectionState.CONNECTING, RingConnectionState.RECONNECTING -> tr("Connecting…") RingConnectionState.FAILED -> tr("Sync failed") else -> if (idleNow) { - if (batteryPercent != null && batteryPercent > 0) "Idle · $batteryPercent%" else "Idle" + if (batteryPercent != null && batteryPercent > 0) trf("Idle · {0}%", batteryPercent) else tr("Idle") } else tr("Disconnected") } // Only run the transition while pulsing: an infinite 1f→1f animation still ticks every frame. 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 bfe16109..d41a1bb2 100644 --- a/app/src/main/java/com/pulseloop/ui/components/Charts.kt +++ b/app/src/main/java/com/pulseloop/ui/components/Charts.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.components +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import com.pulseloop.ui.theme.PulseColors @@ -311,8 +313,8 @@ fun TrendChart( // 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 ?: tr("Chart")}: latest ${v(points.lastIndex)}, " + - "range ${valueFormatter(points.min())}–${valueFormatter(points.max())}, ${points.size} readings" + trf("{0}: latest {1}, ", title ?: tr("Chart"), v(points.lastIndex)) + + trf("range {0}–{1}, {2} readings", valueFormatter(points.min()), valueFormatter(points.max()), points.size) } Column(modifier = modifier) { diff --git a/app/src/main/java/com/pulseloop/ui/components/DeviceHeroStatus.kt b/app/src/main/java/com/pulseloop/ui/components/DeviceHeroStatus.kt index e900ad92..774237b7 100644 --- a/app/src/main/java/com/pulseloop/ui/components/DeviceHeroStatus.kt +++ b/app/src/main/java/com/pulseloop/ui/components/DeviceHeroStatus.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.components +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import androidx.compose.ui.graphics.Color @@ -85,7 +87,7 @@ data class DeviceHeroStatus( val batteryText = batteryPercent?.let { "${it.coerceIn(0, 100)}%" } - val syncText = lastSyncAt?.let { "Synced ${relativeShort(it, now)}" } + val syncText = lastSyncAt?.let { trf("Synced {0}", relativeShort(it, now)) } val action = when (state) { RingConnectionState.CONNECTED -> Action.DISCONNECT @@ -108,9 +110,9 @@ data class DeviceHeroStatus( val seconds = ((nowMillis - fromMillis) / 1000).coerceAtLeast(0) return when { seconds < 60 -> "just now" - seconds < 3_600 -> "${seconds / 60}m ago" - seconds < 86_400 -> "${seconds / 3_600}h ago" - else -> "${seconds / 86_400}d ago" + seconds < 3_600 -> trf("{0}m ago", seconds / 60) + seconds < 86_400 -> trf("{0}h ago", seconds / 3_600) + else -> trf("{0}d ago", seconds / 86_400) } } } diff --git a/app/src/main/java/com/pulseloop/ui/components/MetricThresholds.kt b/app/src/main/java/com/pulseloop/ui/components/MetricThresholds.kt index 0a6168d4..882695f7 100644 --- a/app/src/main/java/com/pulseloop/ui/components/MetricThresholds.kt +++ b/app/src/main/java/com/pulseloop/ui/components/MetricThresholds.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.components +import com.pulseloop.ui.i18n.tr + import androidx.compose.ui.graphics.Color import com.pulseloop.ring.MeasurementKind import com.pulseloop.ui.theme.MetricColors @@ -68,10 +70,10 @@ object MetricThresholdTable { higherIsBetter = false, unitLabel = "bpm", zones = listOf( - ThresholdZone("Low", 40.0, 50.0, MetricColors.ZoneLow), - ThresholdZone("Good", 50.0, 90.0, MetricColors.ZoneGood), - ThresholdZone("Elevated", 90.0, 120.0, MetricColors.ZoneBorderline), - ThresholdZone("High", 120.0, 140.0, MetricColors.ZoneConcern), + ThresholdZone(tr("Low"), 40.0, 50.0, MetricColors.ZoneLow), + ThresholdZone(tr("Good"), 50.0, 90.0, MetricColors.ZoneGood), + ThresholdZone(tr("Elevated"), 90.0, 120.0, MetricColors.ZoneBorderline), + ThresholdZone(tr("High"), 120.0, 140.0, MetricColors.ZoneConcern), ), ) @@ -80,9 +82,9 @@ object MetricThresholdTable { higherIsBetter = true, unitLabel = "%", zones = listOf( - ThresholdZone("Concerning", 85.0, 90.0, MetricColors.ZoneConcern), - ThresholdZone("Low", 90.0, 95.0, MetricColors.ZoneBorderline), - ThresholdZone("Good", 95.0, 100.0, MetricColors.ZoneGood), + ThresholdZone(tr("Concerning"), 85.0, 90.0, MetricColors.ZoneConcern), + ThresholdZone(tr("Low"), 90.0, 95.0, MetricColors.ZoneBorderline), + ThresholdZone(tr("Good"), 95.0, 100.0, MetricColors.ZoneGood), ), ) @@ -91,10 +93,10 @@ object MetricThresholdTable { higherIsBetter = false, unitLabel = "", zones = listOf( - ThresholdZone("Relaxed", 0.0, 30.0, MetricColors.ZoneGood), - ThresholdZone("Normal", 30.0, 60.0, MetricColors.ZoneNormal), - ThresholdZone("Moderate", 60.0, 80.0, MetricColors.ZoneBorderline), - ThresholdZone("High", 80.0, 100.0, MetricColors.ZoneConcern), + ThresholdZone(tr("Relaxed"), 0.0, 30.0, MetricColors.ZoneGood), + ThresholdZone(tr("Normal"), 30.0, 60.0, MetricColors.ZoneNormal), + ThresholdZone(tr("Moderate"), 60.0, 80.0, MetricColors.ZoneBorderline), + ThresholdZone(tr("High"), 80.0, 100.0, MetricColors.ZoneConcern), ), ) @@ -103,10 +105,10 @@ object MetricThresholdTable { higherIsBetter = false, unitLabel = "", zones = listOf( - ThresholdZone("Relaxed", 0.0, 30.0, MetricColors.ZoneGood), - ThresholdZone("Normal", 30.0, 60.0, MetricColors.ZoneNormal), - ThresholdZone("Moderate", 60.0, 80.0, MetricColors.ZoneBorderline), - ThresholdZone("High", 80.0, 100.0, MetricColors.ZoneConcern), + ThresholdZone(tr("Relaxed"), 0.0, 30.0, MetricColors.ZoneGood), + ThresholdZone(tr("Normal"), 30.0, 60.0, MetricColors.ZoneNormal), + ThresholdZone(tr("Moderate"), 60.0, 80.0, MetricColors.ZoneBorderline), + ThresholdZone(tr("High"), 80.0, 100.0, MetricColors.ZoneConcern), ), ) @@ -115,9 +117,9 @@ object MetricThresholdTable { higherIsBetter = true, unitLabel = "ms", zones = listOf( - ThresholdZone("Low", 0.0, 20.0, MetricColors.ZoneConcern), - ThresholdZone("Below avg", 20.0, 50.0, MetricColors.ZoneBorderline), - ThresholdZone("Good", 50.0, 120.0, MetricColors.ZoneGood), + ThresholdZone(tr("Low"), 0.0, 20.0, MetricColors.ZoneConcern), + ThresholdZone(tr("Below avg"), 20.0, 50.0, MetricColors.ZoneBorderline), + ThresholdZone(tr("Good"), 50.0, 120.0, MetricColors.ZoneGood), ), ) @@ -126,9 +128,9 @@ object MetricThresholdTable { higherIsBetter = null, // personal / relative unitLabel = "°C", zones = listOf( - ThresholdZone("Low", 28.0, 31.0, MetricColors.ZoneLow), - ThresholdZone("Normal", 31.0, 36.0, MetricColors.ZoneGood), - ThresholdZone("Elevated", 36.0, 38.0, MetricColors.ZoneBorderline), + ThresholdZone(tr("Low"), 28.0, 31.0, MetricColors.ZoneLow), + ThresholdZone(tr("Normal"), 31.0, 36.0, MetricColors.ZoneGood), + ThresholdZone(tr("Elevated"), 36.0, 38.0, MetricColors.ZoneBorderline), ), ) @@ -137,10 +139,10 @@ object MetricThresholdTable { higherIsBetter = false, unitLabel = "mmHg", zones = listOf( - ThresholdZone("Normal", 80.0, 120.0, MetricColors.ZoneGood), - ThresholdZone("Elevated", 120.0, 130.0, MetricColors.ZoneBorderline), - ThresholdZone("Stage 1", 130.0, 140.0, MetricColors.ZoneElevated), - ThresholdZone("High", 140.0, 180.0, MetricColors.ZoneConcern), + ThresholdZone(tr("Normal"), 80.0, 120.0, MetricColors.ZoneGood), + ThresholdZone(tr("Elevated"), 120.0, 130.0, MetricColors.ZoneBorderline), + ThresholdZone(tr("Stage 1"), 130.0, 140.0, MetricColors.ZoneElevated), + ThresholdZone(tr("High"), 140.0, 180.0, MetricColors.ZoneConcern), ), ) @@ -149,10 +151,10 @@ object MetricThresholdTable { higherIsBetter = false, unitLabel = "mg/dL", zones = listOf( - ThresholdZone("Low", 50.0, 70.0, MetricColors.ZoneLow), - ThresholdZone("Normal", 70.0, 100.0, MetricColors.ZoneGood), - ThresholdZone("Elevated", 100.0, 126.0, MetricColors.ZoneBorderline), - ThresholdZone("High", 126.0, 200.0, MetricColors.ZoneConcern), + ThresholdZone(tr("Low"), 50.0, 70.0, MetricColors.ZoneLow), + ThresholdZone(tr("Normal"), 70.0, 100.0, MetricColors.ZoneGood), + ThresholdZone(tr("Elevated"), 100.0, 126.0, MetricColors.ZoneBorderline), + ThresholdZone(tr("High"), 126.0, 200.0, MetricColors.ZoneConcern), ), ) } @@ -169,28 +171,28 @@ fun bpZone(sys: Double?, dia: Double?): ThresholdZone? { // Diastolic category val diaZone = when { dia == null -> null - dia < 80.0 -> "Normal" - dia < 90.0 -> "Stage1" - else -> "High" + dia < 80.0 -> tr("Normal") + dia < 90.0 -> tr("Stage1") + else -> tr("High") } // Systolic category val sysZone = when { sys == null -> null - sys < 120.0 -> "Normal" - sys < 130.0 -> "Elevated" - sys < 140.0 -> "Stage1" - else -> "High" + sys < 120.0 -> tr("Normal") + sys < 130.0 -> tr("Elevated") + sys < 140.0 -> tr("Stage1") + else -> tr("High") } // Pick the worse category (ordered Normal < Elevated < Stage1 < High) val worst = when { - sysZone == "High" || diaZone == "High" -> "High" - sysZone == "Stage1" || diaZone == "Stage1" -> "Stage1" - sysZone == "Elevated" -> "Elevated" - sysZone == "Normal" && diaZone == "Normal"-> "Normal" - diaZone == "Normal" && sysZone == null -> "Normal" - sysZone == "Normal" && diaZone == null -> "Normal" + sysZone == "High" || diaZone == "High" -> tr("High") + sysZone == "Stage1" || diaZone == "Stage1" -> tr("Stage1") + sysZone == "Elevated" -> tr("Elevated") + sysZone == "Normal" && diaZone == "Normal"-> tr("Normal") + diaZone == "Normal" && sysZone == null -> tr("Normal") + sysZone == "Normal" && diaZone == null -> tr("Normal") else -> null } 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 2cb277d0..c4633a87 100644 --- a/app/src/main/java/com/pulseloop/ui/components/TodayTiles.kt +++ b/app/src/main/java/com/pulseloop/ui/components/TodayTiles.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.components +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import com.pulseloop.ui.theme.dither @@ -286,7 +288,7 @@ fun SleepStageBar(segments: List, modifier: Modifier = Modifi modifier = modifier .fillMaxWidth() .onSizeChanged { barWidthPx = it.width } - .clearAndSetSemantics { contentDescription = "Sleep stages: $spoken" }, + .clearAndSetSemantics { contentDescription = trf("Sleep stages: {0}", spoken) }, verticalArrangement = Arrangement.spacedBy(3.dp), ) { Row(Modifier.fillMaxWidth().height(12.dp), horizontalArrangement = Arrangement.spacedBy(2.dp)) { diff --git a/app/src/main/java/com/pulseloop/ui/components/WorkoutMapView.kt b/app/src/main/java/com/pulseloop/ui/components/WorkoutMapView.kt index 7dbceff2..e3cd9973 100644 --- a/app/src/main/java/com/pulseloop/ui/components/WorkoutMapView.kt +++ b/app/src/main/java/com/pulseloop/ui/components/WorkoutMapView.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.components +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.theme.PulseColors import androidx.compose.foundation.Canvas import androidx.compose.foundation.background @@ -98,7 +100,7 @@ fun WorkoutMapView( // Info overlay val accuracy = points.last().horizontalAccuracy - val infoText = if (accuracy != null) "±${accuracy.toInt()}m · ${points.size} pts" else "${points.size} pts" + val infoText = if (accuracy != null) trf("±{0}m · {1} pts", accuracy.toInt(), points.size) else trf("{0} pts", points.size) Text( infoText, modifier = Modifier.align(Alignment.BottomStart).padding(8.dp), 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 02a8bd76..631ef656 100644 --- a/app/src/main/java/com/pulseloop/ui/components/ZoneLineChart.kt +++ b/app/src/main/java/com/pulseloop/ui/components/ZoneLineChart.kt @@ -1,5 +1,8 @@ package com.pulseloop.ui.components +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf + import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column @@ -86,8 +89,8 @@ fun ZoneLineChart( 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" + trf("{0}: latest {1}, ", label ?: tr("Trend"), fmt.format(values.last())) + + trf("range {0}–{1}, {2} readings", fmt.format(values.min()), fmt.format(values.max()), values.size) } Column(modifier.fillMaxWidth().semantics { contentDescription = summary }) { 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 8a37788b..bbbfcbc7 100644 --- a/app/src/main/java/com/pulseloop/ui/dashboard/DashboardEdit.kt +++ b/app/src/main/java/com/pulseloop/ui/dashboard/DashboardEdit.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.dashboard +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import androidx.compose.foundation.clickable @@ -152,17 +154,17 @@ fun EditableCard( // 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}", + Icons.Filled.Remove, trf("Hide {0}", 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)) { - EditBadge(Icons.Filled.KeyboardArrowUp, "Move ${card.displayName} up") { editState.moveUp(card) } + EditBadge(Icons.Filled.KeyboardArrowUp, trf("Move {0} up", card.displayName)) { editState.moveUp(card) } } if (editState.canMoveDown(card)) { - EditBadge(Icons.Filled.KeyboardArrowDown, "Move ${card.displayName} down") { editState.moveDown(card) } + EditBadge(Icons.Filled.KeyboardArrowDown, trf("Move {0} down", card.displayName)) { editState.moveDown(card) } } } } @@ -211,7 +213,7 @@ fun HiddenMetricsTray(hidden: List, onRestore: (DashboardCard) -> ) { Text(card.displayName, style = MaterialTheme.typography.bodyMedium) IconButton(onClick = { onRestore(card) }) { - Icon(Icons.Filled.Add, contentDescription = "Show ${card.displayName}") + Icon(Icons.Filled.Add, contentDescription = trf("Show {0}", card.displayName)) } } } diff --git a/app/src/main/java/com/pulseloop/ui/i18n/L10n.kt b/app/src/main/java/com/pulseloop/ui/i18n/L10n.kt index 909e7772..92b4301a 100644 --- a/app/src/main/java/com/pulseloop/ui/i18n/L10n.kt +++ b/app/src/main/java/com/pulseloop/ui/i18n/L10n.kt @@ -95,3 +95,14 @@ object L10n { /** The current language's text for an English UI string. */ fun tr(en: String): String = L10n.translate(en) + +/** + * A string with values in it: the key holds `{0}`, `{1}`… where the values go, so the translation + * can move them (`"{0} steps today"` → `"{0} passos hoje"`). Each value is written as a template + * would write it (`toString()`), so the English result is exactly what the template produced. + */ +fun trf(en: String, vararg args: Any?): String { + var s = L10n.translate(en) + args.forEachIndexed { i, a -> s = s.replace("{$i}", a.toString()) } + return s +} 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 8471cbaf..ed0308ac 100644 --- a/app/src/main/java/com/pulseloop/ui/onboarding/Editors.kt +++ b/app/src/main/java/com/pulseloop/ui/onboarding/Editors.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.onboarding +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import com.pulseloop.ui.theme.dither @@ -168,7 +170,7 @@ fun ProfileEditor( Column { PickerRow( title = tr("Age"), - value = draft.age?.let { "$it years" }, + value = draft.age?.let { trf("{0} years", it) }, onClick = { activePicker = ProfilePickerKind.AGE }, ) HorizontalDivider(color = PulseColors.borderSubtle) @@ -193,7 +195,7 @@ fun ProfileEditor( values = (13..100).toList(), initialValue = draft.age, fallback = 30, - label = { "$it years" }, + label = { trf("{0} years", it) }, onSave = { onDraftChange(draft.copy(age = it)) }, onDismiss = { activePicker = null }, ) @@ -229,7 +231,7 @@ private fun heightLabel(draft: ProfileDraft): String? { private fun weightLabel(draft: ProfileDraft): String? { val value = draft.weightDisplayValue ?: return null - return "${LocalizedDecimalInput.format(value)} ${if (draft.units == UnitSystem.METRIC) "kg" else "lb"}" + return "${LocalizedDecimalInput.format(value)} ${if (draft.units == UnitSystem.METRIC) tr("kg") else tr("lb")}" } @Composable @@ -449,7 +451,7 @@ private fun DecimalValueSheet( verticalArrangement = Arrangement.spacedBy(12.dp), ) { Text( - "Enter your weight in $unit", + trf("Enter your weight in {0}", unit), fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, @@ -495,7 +497,7 @@ private fun DecimalValueSheet( modifier = Modifier .fillMaxWidth() .focusRequester(focusRequester) - .semantics { contentDescription = "Weight in $unit" }, + .semantics { contentDescription = trf("Weight in {0}", unit) }, ) } @@ -507,7 +509,7 @@ private fun DecimalValueSheet( if (text.isNotEmpty() && parsedValue == null) { Text( - "Enter a weight between ${validRange.start.toInt()} and ${validRange.endInclusive.toInt()} $unit.", + trf("Enter a weight between {0} and {1} {2}.", validRange.start.toInt(), validRange.endInclusive.toInt(), unit), fontSize = 12.sp, color = PulseColors.danger, ) @@ -561,7 +563,7 @@ fun GoalEditor( value = draft.calories.toFloat(), range = 100f..2_000f, step = 50f, - label = "${draft.calories.toInt()} cal", + label = trf("{0} cal", draft.calories.toInt()), onValueChange = { onDraftChange(draft.copy(calories = it)) }, ) GoalSliderCard( @@ -594,7 +596,7 @@ fun GoalEditor( value = draft.workouts.toFloat(), range = 1f..7f, step = 1f, - label = "${draft.workouts.toInt()} / week", + label = trf("{0} / week", draft.workouts.toInt()), onValueChange = { onDraftChange(draft.copy(workouts = it)) }, ) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt b/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt index 5f3ea6c8..f3217533 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import android.content.ClipData @@ -132,7 +134,7 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { Text(tr("Compare your ring with another device"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text( tr("Wear the ring and a watch or band you trust for a few days. PulseLoop reads that device's data from " + - "Health Connect and shows where the ring agrees and where it falls short."), + tr("Health Connect and shows where the ring agrees and where it falls short.")), fontSize = 13.sp, color = PulseColors.textSecondary, ) Text( @@ -150,7 +152,7 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { } } if (readable.isNotEmpty()) { - OutlinedButton(onClick = { scan() }, enabled = !scanning) { Text("Scan last ${ReferenceSourceScanner.LOOKBACK_DAYS} days") } + OutlinedButton(onClick = { scan() }, enabled = !scanning) { Text(trf("Scan last {0} days", ReferenceSourceScanner.LOOKBACK_DAYS)) } } if (scanning) CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) } @@ -163,7 +165,7 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { if (r != null) { if (r.sources.isEmpty()) { AccuracyCard { - Text("No other app wrote readable data in the last ${ReferenceSourceScanner.LOOKBACK_DAYS} days.", fontSize = 13.sp, color = PulseColors.textSecondary) + Text(trf("No other app wrote readable data in the last {0} days.", ReferenceSourceScanner.LOOKBACK_DAYS), fontSize = 13.sp, color = PulseColors.textSecondary) Text( tr("If your watch syncs through an app like Health Sync, check that it's set to write to Health Connect."), fontSize = 12.sp, color = PulseColors.textMuted, @@ -267,9 +269,9 @@ private fun RunningCard(check: AccuracyCheckEntity, scope: kotlinx.coroutines.Co var confirmEnd by remember { mutableStateOf(false) } val (day, total) = AccuracyUiText.dayOf(check) AccuracyCard { - Text("Accuracy check · day $day of $total", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text("${check.deviceLabel} vs ${check.referenceLabel}, until ${AccuracyUiText.date(check.plannedEndAt)}.", fontSize = 13.sp, color = PulseColors.textSecondary) - Text("Wear both as usual. Health Connect export paused for: ${AccuracyUiText.units(units)}.", fontSize = 12.sp, color = PulseColors.warning) + Text(trf("Accuracy check · day {0} of {1}", day, total), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(trf("{0} vs {1}, until {2}.", check.deviceLabel, check.referenceLabel, AccuracyUiText.date(check.plannedEndAt)), fontSize = 13.sp, color = PulseColors.textSecondary) + Text(trf("Wear both as usual. Health Connect export paused for: {0}.", AccuracyUiText.units(units)), fontSize = 12.sp, color = PulseColors.warning) OutlinedButton(onClick = { confirmEnd = true }) { Text(tr("End now")) } } if (confirmEnd) { @@ -296,7 +298,7 @@ private fun ResumeCard(check: AccuracyCheckEntity, scope: kotlinx.coroutines.Cor Text(tr("Check finished: resume Health Connect export"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(AccuracyUiText.endReason(check) + " ${AccuracyUiText.span(check)}.", fontSize = 13.sp, color = PulseColors.textSecondary) Text( - "During the check, ${check.referenceLabel} wrote the same types to Health Connect. Exporting the ring's copy " + + trf("During the check, {0} wrote the same types to Health Connect. Exporting the ring's copy ", check.referenceLabel) + "of those days now would count them twice.", fontSize = 12.sp, color = PulseColors.textMuted, ) @@ -345,11 +347,11 @@ private fun StartDialog( Text(tr("How long"), fontSize = 13.sp, fontWeight = FontWeight.SemiBold) Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { AccuracyCheckController.DURATIONS_DAYS.forEach { d -> - FilterChip(selected = days == d, onClick = { days = d }, label = { Text("$d days") }) + FilterChip(selected = days == d, onClick = { days = d }, label = { Text(trf("{0} days", d)) }) } } Text( - "Compared: ${AccuracyUiText.units(units)}. These stop exporting to Health Connect until the check ends " + + trf("Compared: {0}. These stop exporting to Health Connect until the check ends ", AccuracyUiText.units(units)) + "and you choose what to do with those days.", fontSize = 12.sp, ) @@ -379,7 +381,7 @@ private fun SourceCard(context: Context, s: ReferenceSourceSurvey, onUse: (() -> ) s.echo?.takeIf { it.looksLikeEcho }?.let { Text( - "${it.matching} of ${it.compared} heart-rate samples match your ring exactly. This looks like PulseLoop's own " + + trf("{0} of {1} heart-rate samples match your ring exactly. This looks like PulseLoop's own ", it.matching, it.compared) + "data coming back — check that the app syncs from your watch only, not from Health Connect.", fontSize = 12.sp, color = PulseColors.danger, ) @@ -395,8 +397,8 @@ private fun MetricRow(m: MetricSurvey) { Column(Modifier.fillMaxWidth().padding(top = 4.dp)) { Text(m.metric.label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) Text( - "${m.sampleCount} samples, ${ReferenceSurveyText.cadence(m)} · latest $last · " + - "arrives ~${ReferenceSurveyText.duration(m.medianDeliveryDelayMs)} late", + trf("{0} samples, {1} · latest {2} · ", m.sampleCount, ReferenceSurveyText.cadence(m), last) + + trf("arrives ~{0} late", ReferenceSurveyText.duration(m.medianDeliveryDelayMs)), fontSize = 12.sp, color = PulseColors.textSecondary, ) if (m.metric == ReferenceMetric.SLEEP) { @@ -424,7 +426,7 @@ internal fun AccuracyCard(content: @Composable () -> Unit) { @Composable internal fun AdjustedCaption(note: String) { Text( - "Adjusted by your accuracy check: $note. Settings → Accuracy check to change.", + trf("Adjusted by your accuracy check: {0}. Settings → Accuracy check to change.", note), fontSize = 11.sp, color = PulseColors.textMuted, ) } @@ -446,7 +448,7 @@ internal fun rememberAccuracyCorrections(): com.pulseloop.health.accuracy.Correc internal fun AccuracyCheckBanner(c: AccuracyCheckEntity, onOpen: () -> Unit) { val text = if (c.state == AccuracyCheckEntity.STATE_RUNNING) { val (day, total) = AccuracyUiText.dayOf(c) - "Accuracy check · day $day of $total · Health Connect export paused" + trf("Accuracy check · day {0} of {1} · Health Connect export paused", day, total) } else tr("Accuracy report ready · choose what to do with the paused export") Row( Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).clickable(onClick = onOpen).padding(12.dp), diff --git a/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt b/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt index 5fa53c04..71e0114b 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import androidx.compose.foundation.background @@ -79,7 +81,7 @@ internal fun AccuracyReportSection( if (force) AccuracyScorer.score(context, check) else AccuracyScorer.scoreIfStale(context, check) }.getOrNull() status = when (r) { - AccuracyScorer.Result.Unavailable, null -> "Couldn't read ${check.referenceLabel} from Health Connect just now." + AccuracyScorer.Result.Unavailable, null -> trf("Couldn't read {0} from Health Connect just now.", check.referenceLabel) else -> null } scoring = false @@ -122,13 +124,13 @@ internal fun AccuracyReportSection( }) { Text(tr("Share")) } } Text( - "How your ring compares with ${check.referenceLabel}, the device you chose to trust. This is agreement between two " + + trf("How your ring compares with {0}, the device you chose to trust. This is agreement between two ", check.referenceLabel) + "consumer devices, not a lab measurement.", fontSize = 12.sp, color = PulseColors.textMuted, ) if (echo?.looksLikeEcho == true) { Text( - "${echo.matching} of ${echo.compared} heart-rate readings from ${check.referenceLabel} match your ring exactly. " + + trf("{0} of {1} heart-rate readings from {2} match your ring exactly. ", echo.matching, echo.compared, check.referenceLabel) + tr("That looks like PulseLoop's own data coming back through a sync app, so this report would compare the ring " + "with itself. Check the sync direction in that app."), fontSize = 12.sp, color = PulseColors.danger, @@ -136,7 +138,7 @@ internal fun AccuracyReportSection( } if (waitingDays > 0) { Text( - "Waiting for ${check.referenceLabel} to deliver $waitingDays day${if (waitingDays == 1) "" else "s"}. Open the app " + + trf("Waiting for {0} to deliver {1} day{2}. Open the app ", check.referenceLabel, waitingDays, if (waitingDays == 1) "" else "s") + "that syncs it to send it sooner; otherwise those days are scored 24 hours after they end.", fontSize = 12.sp, color = PulseColors.warning, ) @@ -219,16 +221,16 @@ private fun MetricCard( if (m.kind != ComparisonMetric.Kind.STAGES && summary.validDays > 0) { val (lo, hi) = summary.limits Text( - "Average difference ${AccuracyReportText.signed(m, summary.bias)}; 95 % of differences between " + - "${AccuracyReportText.signed(m, lo)} and ${AccuracyReportText.signed(m, hi)}" + - if (m.kind == ComparisonMetric.Kind.PAIRED) " (${summary.pairs} matched readings)." else ".", + trf("Average difference {0}; 95 % of differences between ", AccuracyReportText.signed(m, summary.bias)) + + trf("{0} and {1}", AccuracyReportText.signed(m, lo), AccuracyReportText.signed(m, hi)) + + if (m.kind == ComparisonMetric.Kind.PAIRED) trf(" ({0} matched readings).", summary.pairs) else ".", fontSize = 12.sp, color = PulseColors.textMuted, ) } if (m.kind == ComparisonMetric.Kind.STAGES) StageConfusion(days, check.referenceLabel) days.forEach { DayRow(m, it, check.referenceLabel) } if (m.kind != ComparisonMetric.Kind.STAGES) { - Text("Agreement band: ±${AccuracyReportText.magnitude(m, summary.band)}", fontSize = 12.sp, color = PulseColors.textPrimary) + Text(trf("Agreement band: ±{0}", AccuracyReportText.magnitude(m, summary.band)), fontSize = 12.sp, color = PulseColors.textPrimary) var draft by remember(summary.band) { mutableStateOf(summary.band.toFloat()) } val range = bandRange(m) Slider( @@ -258,13 +260,13 @@ private fun DayRow(m: ComparisonMetric, d: AccuracyCheckDayEntity, ref: String) val text = when (m.kind) { ComparisonMetric.Kind.DAILY -> { val diff = AccuracyComparison.diff(m, d.ringValue, d.refValue) - "$date · ring ${AccuracyReportText.value(m, d.ringValue)} · $ref ${AccuracyReportText.value(m, d.refValue)}" + + trf("{0} · ring {1} · {2} {3}", date, AccuracyReportText.value(m, d.ringValue), ref, AccuracyReportText.value(m, d.refValue)) + (diff?.let { " (${AccuracyReportText.signed(m, it)})" } ?: "") } ComparisonMetric.Kind.PAIRED -> - "$date · ${d.pairs} readings · ${if (d.pairs > 0) AccuracyReportText.signed(m, d.sumDiff / d.pairs) else "—"} on average" + trf("{0} · {1} readings · {2} on average", date, d.pairs, if (d.pairs > 0) AccuracyReportText.signed(m, d.sumDiff / d.pairs) else "—") ComparisonMetric.Kind.STAGES -> - "$date · ${if (d.pairs > 0) "${(d.inBand * 100.0 / d.pairs).roundToInt()} % of ${d.pairs} min on the same stage" else "no overlap"}" + "$date · ${if (d.pairs > 0) trf("{0} % of {1} min on the same stage", (d.inBand * 100.0 / d.pairs).roundToInt(), d.pairs) else tr("no overlap")}" } Text(text + (note?.let { " — $it" } ?: ""), fontSize = 12.sp, color = if (d.valid) PulseColors.textSecondary else PulseColors.textMuted) } @@ -277,7 +279,7 @@ private fun StageConfusion(days: List, ref: String) { } if (totals.isEmpty()) return val stages = listOf(Stage.AWAKE, Stage.LIGHT, Stage.DEEP, Stage.REM) - Text("When the ring says… what $ref says (minutes)", fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) + Text(trf("When the ring says… what {0} says (minutes)", ref), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) stages.forEach { ringStage -> val row = stages.map { totals[ringStage to it] ?: 0 } if (row.sum() == 0) return@forEach @@ -307,23 +309,23 @@ internal fun AccuracyCorrectionControl(check: AccuracyCheckEntity, summary: Accu val paired = ring?.let { it.id != RingIdentity.DEMO_DEVICE_ID && RingIdentity.keyOf(it) == check.deviceKey } == true if (!paired) { - Text("This check was run on ${check.deviceLabel}. Pair that ring to apply a correction from it.", fontSize = 12.sp, color = PulseColors.textMuted) + Text(trf("This check was run on {0}. Pair that ring to apply a correction from it.", check.deviceLabel), fontSize = 12.sp, color = PulseColors.textMuted) return } when { existing != null && existing.enabled -> Row(verticalAlignment = Alignment.CenterVertically) { - Text("Correction on: ${AccuracyCorrections.formatValue(metric, existing.value)}", fontSize = 12.sp, + Text(trf("Correction on: {0}", AccuracyCorrections.formatValue(metric, existing.value)), fontSize = 12.sp, color = PulseColors.success, modifier = Modifier.weight(1f)) TextButton(onClick = { editing = true }) { Text(tr("Change")) } TextButton(onClick = { scope.launch { AccuracyCorrections.setEnabled(db, existing, false) } }) { Text(tr("Turn off")) } } existing != null -> Row(verticalAlignment = Alignment.CenterVertically) { - Text("Correction off (${AccuracyCorrections.formatValue(metric, existing.value)})", fontSize = 12.sp, + Text(trf("Correction off ({0})", AccuracyCorrections.formatValue(metric, existing.value)), fontSize = 12.sp, color = PulseColors.textMuted, modifier = Modifier.weight(1f)) TextButton(onClick = { scope.launch { AccuracyCorrections.setEnabled(db, existing, true) } }) { Text(tr("Turn on")) } } else -> Button(onClick = { editing = true }, modifier = Modifier.fillMaxWidth()) { - Text("Apply correction (${AccuracyCorrections.formatValue(metric, fitted)})") + Text(trf("Apply correction ({0})", AccuracyCorrections.formatValue(metric, fitted))) } } if (editing) { @@ -347,13 +349,13 @@ private fun CorrectionDialog( var value by remember { mutableStateOf(start.coerceIn(range.start.toDouble(), range.endInclusive.toDouble())) } AlertDialog( onDismissRequest = onDismiss, - title = { Text("Correct ${metric.label.lowercase()}") }, + title = { Text(trf("Correct {0}", metric.label.lowercase())) }, text = { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Text( - "Fitted from this check so your ring matches $ref: ${AccuracyCorrections.formatValue(metric, fitted)}. " + + trf("Fitted from this check so your ring matches {0}: {1}. ", ref, AccuracyCorrections.formatValue(metric, fitted)) + tr("It changes what PulseLoop shows and what it works out from it (zones, resting baseline, calorie estimate). " + - "Your ring's stored readings and what goes to Health Connect stay as measured."), + tr("Your ring's stored readings and what goes to Health Connect stay as measured.")), fontSize = 12.sp, ) Text(AccuracyCorrections.formatValue(metric, value), fontSize = 20.sp, fontWeight = FontWeight.Bold) @@ -396,7 +398,7 @@ internal fun AccuracyCorrectionsCard() { val key = RingIdentity.keyOf(r) val mine = all.filter { it.deviceKey == key }.sortedBy { ComparisonMetric.byName(it.metric)?.ordinal ?: 99 } AccuracyCard { - Text("Corrections for ${RingIdentity.labelOf(r)}", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(trf("Corrections for {0}", RingIdentity.labelOf(r)), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) if (mine.isEmpty()) { Text( if (all.isNotEmpty()) tr("No accuracy check for this ring yet. Corrections from another ring don't carry over.") @@ -411,7 +413,7 @@ internal fun AccuracyCorrectionsCard() { Column(Modifier.weight(1f)) { Text("${m.label}: ${AccuracyCorrections.formatValue(m, c.value)}", fontSize = 13.sp, color = PulseColors.textPrimary) if (AccuracyCorrections.isStale(c, r)) { - Text("Fitted ${AccuracyUiText.date(c.createdAt)}${if (c.firmware != null && c.firmware != r.firmwareVersion) " on other firmware" else ""}: worth a fresh check.", + Text(trf("Fitted {0}{1}: worth a fresh check.", AccuracyUiText.date(c.createdAt), if (c.firmware != null && c.firmware != r.firmwareVersion) " on other firmware" else ""), fontSize = 11.sp, color = PulseColors.warning) } } 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 d685984c..6207308a 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.i18n.trf + import com.pulseloop.ui.i18n.tr import com.pulseloop.ui.components.switchRow @@ -276,7 +278,7 @@ fun ActivityScreen( text = { Text( tr("Recording a workout needs the Physical activity permission. " + - "You can allow it in Android Settings › Apps › PulseLoop › Permissions."), + tr("You can allow it in Android Settings › Apps › PulseLoop › Permissions.")), ) }, confirmButton = { TextButton(onClick = { permissionDenied = false }) { Text("OK") } }, @@ -505,7 +507,7 @@ fun ActivityWorkoutRow(session: ActivitySessionEntity, units: UnitSystem, onTap: ) } session.avgHeartRate?.let { - Text("${corrections.heartRate(it).toInt()} bpm avg", fontSize = 12.sp, color = PulseColors.textSecondary) + Text(trf("{0} bpm avg", corrections.heartRate(it).toInt()), fontSize = 12.sp, color = PulseColors.textSecondary) } Spacer(Modifier.weight(1f)) if (session.useGps && session.gpsPointCount > 1) { @@ -554,7 +556,7 @@ private fun WeeklyGoalCard(state: ActivityViewModel.ActivityState, days: List Text( - "No activity records synced for $dayLabel yet.", + trf("No activity records synced for {0} yet.", dayLabel), fontSize = 13.sp, color = PulseColors.textMuted, modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 12.dp), ) @@ -883,12 +885,12 @@ private fun ActivityRecordsCard( modifier = Modifier.weight(1f), ) Text( - "${Formats.count(bucket.steps)} steps", + trf("{0} steps", Formats.count(bucket.steps)), fontSize = 13.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, ) if (bucket.distanceMeters > 0) { Text( - " · %.2f %s".format(UnitConverter.distance(bucket.distanceMeters, units), UnitConverter.distanceUnit(units)), + tr(" · %.2f %s").format(UnitConverter.distance(bucket.distanceMeters, units), UnitConverter.distanceUnit(units)), fontSize = 11.sp, color = PulseColors.textMuted, ) } @@ -907,7 +909,7 @@ private fun ActivityRecordsCard( onClick = { visibleCount += ACTIVITY_RECORDS_PAGE_SIZE }, modifier = Modifier.padding(start = 8.dp), ) { - Text("Show ${minOf(ACTIVITY_RECORDS_PAGE_SIZE, rows.size - visibleCount)} more", fontSize = 13.sp) + Text(trf("Show {0} more", minOf(ACTIVITY_RECORDS_PAGE_SIZE, rows.size - visibleCount)), fontSize = 13.sp) } } Spacer(Modifier.height(8.dp)) @@ -922,7 +924,7 @@ private fun ActivityRecordsCard( title = { Text(tr("Delete this activity record?")) }, text = { Text( - "${Formats.count(bucket.steps)} steps at ${timeOf(bucket.startEpoch)}." + + trf("{0} steps at {1}.", Formats.count(bucket.steps), timeOf(bucket.startEpoch)) + tr("\n\nThe day's total drops by that much. This can't be undone, and the record " + "stays deleted the next time this day syncs."), ) @@ -976,7 +978,7 @@ private fun DetectedActivityCard() { val isNap = p.kind == com.pulseloop.service.ActivityDetection.Proposal.Kind.NAP Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { Text( - (if (isNap) tr("Possible nap") else "Possible ${ActivityMeta.label(type).lowercase()}") + " · ${p.minutes} min", + (if (isNap) tr("Possible nap") else trf("Possible {0}", ActivityMeta.label(type).lowercase())) + " · ${p.minutes} min", fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, ) Text( 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 e650ff5d..6a7e9ff4 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.i18n.trf + import com.pulseloop.ui.i18n.tr import com.pulseloop.ui.components.switchRow @@ -131,13 +133,13 @@ fun HealthConnectBodyCard(onUpdated: () -> Unit) { 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(UnitConverter.weight(it, units))} $unit") } - s.heightCm?.takeIf { it > 0 }?.let { h -> add("BMI ${"%.1f".format(w.value / ((h / 100) * (h / 100)))}") } + s.bodyFatPct?.let { add(trf("Body fat {0}%", "%.1f".format(it))) } + s.leanMassKg?.let { add(trf("Lean {0} {1}", "%.1f".format(UnitConverter.weight(it, units)), unit)) } + s.heightCm?.takeIf { it > 0 }?.let { h -> add(trf("BMI {0}", "%.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, units) - Text("From ${w.source}", fontSize = 11.sp, color = PulseColors.textMuted) + Text(trf("From {0}", w.source), fontSize = 11.sp, color = PulseColors.textMuted) } note?.let { Text(it, fontSize = 12.sp, color = PulseColors.textMuted) } if (enabled) { @@ -155,8 +157,8 @@ private fun WeightLine(points: List, units: UnitSystem) { val t1 = points.last().measuredAt 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" + val summary = trf("Weight, last 90 days: latest {0} {1}, ", shown(points.last().value), unit) + + trf("range {0}–{1} {2}, {3} weigh-ins", shown(min), shown(max), unit, points.size) 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 @@ -172,7 +174,7 @@ private fun WeightLine(points: List, units: UnitSystem) { 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} $unit in 90 days", + trf("{0}{1} {2} in 90 days", if (delta >= 0) "+" else "", (delta * 10).roundToInt() / 10.0, unit), 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 181ec821..d8aa3ba4 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CoachModelPicker.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CoachModelPicker.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import androidx.compose.foundation.layout.* @@ -90,7 +92,7 @@ fun CoachModelPicker( if (others.isNotEmpty()) { HorizontalDivider() - MenuHeader("All models from $providerName (${others.size})") + MenuHeader(trf("All models from {0} ({1})", providerName, others.size)) // OpenRouter lists hundreds; a filter beats scrolling, and the cap keeps the // (non-lazy) menu from composing every row. if (others.size > FILTER_THRESHOLD) { @@ -110,12 +112,12 @@ fun CoachModelPicker( matches.take(MAX_ROWS).forEach { e -> val detail = listOfNotNull( e.name?.takeIf { it != e.id }, - e.expiresOn?.let { "retiring $it" }, + e.expiresOn?.let { trf("retiring {0}", it) }, ).joinToString(" · ") Item(e.id, detail) } if (matches.size > MAX_ROWS) { - MenuHeader("${matches.size - MAX_ROWS} more — type to narrow") + MenuHeader(trf("{0} more — type to narrow", matches.size - MAX_ROWS)) } } } @@ -141,13 +143,13 @@ fun CoachModelPicker( } if (unlisted) { Text( - "$providerName doesn't list “$selected” any more — it may have been retired. Pick another model.", + trf("{0} doesn't list “{1}” any more — it may have been retired. Pick another model.", providerName, selected), style = MaterialTheme.typography.bodySmall, color = PulseColors.danger, ) } else if (expiry != null) { Text( - "$providerName is retiring this model on $expiry.", + trf("{0} is retiring this model on {1}.", providerName, expiry), style = MaterialTheme.typography.bodySmall, color = PulseColors.warning, ) 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 70a9a2d7..956eab2d 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import com.pulseloop.ui.theme.dither @@ -139,7 +141,7 @@ fun CoachScreen( if (state.error != null) { item { Text( - "Error: ${state.error}", fontSize = 12.sp, color = PulseColors.danger, + trf("Error: {0}", state.error), fontSize = 12.sp, color = PulseColors.danger, modifier = Modifier.padding(start = 8.dp).semantics { liveRegion = LiveRegionMode.Polite }, ) } 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 a7c82d4c..e44dadaa 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CoachUsageSheet.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CoachUsageSheet.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import com.pulseloop.ui.theme.dither @@ -101,7 +103,7 @@ private fun SummaryCard( Divider() UsageRow(tr("Output tokens"), formatTokens(totalOutputTokens), mono = true) Divider() - UsageRow("Estimated cost", totalCost?.let { "$" + "%.4f".format(it) } ?: "—", mono = true) + UsageRow(tr("Estimated cost"), totalCost?.let { "$" + "%.4f".format(it) } ?: "—", mono = true) } } @@ -155,7 +157,7 @@ private fun BreakdownCard(accounted: List) { @Composable private fun MessageBreakdownRow(message: CoachMessageEntity) { val preview = message.body.replace("\n", " ").take(30) - val tokens = "${message.inputTokens ?: 0} in · ${message.outputTokens ?: 0} out" + val tokens = trf("{0} in · {1} out", message.inputTokens ?: 0, message.outputTokens ?: 0) val cost = message.costUSD?.let { "$" + "%.4f".format(it) } ?: "—" Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { Text(preview.ifEmpty { "(no text)" }, fontSize = 12.sp, color = PulseColors.textPrimary, maxLines = 1) diff --git a/app/src/main/java/com/pulseloop/ui/screens/CycleUi.kt b/app/src/main/java/com/pulseloop/ui/screens/CycleUi.kt index 5216559f..3c2bf6a8 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CycleUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CycleUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import androidx.compose.foundation.background @@ -72,13 +74,13 @@ fun CycleScreen(onBack: () -> Unit) { Text(tr("Log your period to start"), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(tr("PulseLoop shows the day of your cycle and its phase from the dates you log, next to your sleep and recovery."), fontSize = 13.sp, color = PulseColors.textSecondary) } else { - Text("Day ${status.cycleDay} · ${status.phase.label}", fontSize = 22.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(trf("Day {0} · {1}", status.cycleDay, status.phase.label), fontSize = 22.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(status.phase.note, fontSize = 13.sp, color = PulseColors.textSecondary) status.nextStart?.let { next -> val d = status.daysToNext ?: 0 Text( - if (d >= 0) "Next period around ${next.format(fmt)} (in $d day${if (d == 1) "" else "s"}), from your usual ${status.usualLength}-day cycle." - else "Your usual ${status.usualLength}-day cycle would have ended ${-d} day${if (d == -1) "" else "s"} ago.", + if (d >= 0) trf("Next period around {0} (in {1} day{2}), from your usual {3}-day cycle.", next.format(fmt), d, if (d == 1) "" else "s", status.usualLength) + else trf("Your usual {0}-day cycle would have ended {1} day{2} ago.", status.usualLength, -d, if (d == -1) "" else "s"), fontSize = 13.sp, color = PulseColors.textPrimary, ) } @@ -111,7 +113,7 @@ fun CycleScreen(onBack: () -> Unit) { start.format(fmt) + (p.endDay?.let { " – " + LocalDate.ofEpochDay(it).format(fmt) } ?: ""), fontSize = 14.sp, color = PulseColors.textPrimary, ) - next?.let { Text("Cycle of ${it - p.startDay} days", fontSize = 12.sp, color = PulseColors.textMuted) } + next?.let { Text(trf("Cycle of {0} days", it - p.startDay), fontSize = 12.sp, color = PulseColors.textMuted) } } IconButton(onClick = { scope.launch { db.periodDao().delete(p.id) } }) { Icon(Icons.Filled.Delete, tr("Delete"), tint = PulseColors.textMuted, modifier = Modifier.size(18.dp)) 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 0c38a623..5b83bb8c 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.i18n.trf + import com.pulseloop.ui.i18n.tr import com.pulseloop.ui.components.switchRow @@ -69,7 +71,7 @@ fun DebugScreen(viewModel: DiagnosticsViewModel, onBack: () -> Unit = {}) { LazyColumn(Modifier.fillMaxSize().padding(padding).padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { // ── Ring Event Log ────────────────────────────────────────── item { - DebugCard(tr("Ring Events"), trailing = "${events.size} recent") { + DebugCard(tr("Ring Events"), trailing = trf("{0} recent", events.size)) { Text( tr("Connection, command and reply events, stored as they happen. Times are local."), style = MaterialTheme.typography.labelSmall, @@ -112,7 +114,7 @@ fun DebugScreen(viewModel: DiagnosticsViewModel, onBack: () -> Unit = {}) { // ── Raw Packets ───────────────────────────────────────────── item { DebugCard(tr("Raw Packets")) { - Text("$packetCount packets captured", style = MaterialTheme.typography.bodyMedium) + Text(trf("{0} packets captured", packetCount), style = MaterialTheme.typography.bodyMedium) Text("↓ = ring → app (response) ↑ = app → ring (command)", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) TextButton(onClick = { showPackets = !showPackets }) { @@ -126,7 +128,7 @@ fun DebugScreen(viewModel: DiagnosticsViewModel, onBack: () -> Unit = {}) { item { DebugCard(tr("Database")) { Text(tr("Row counts include demo and real rows. Tap a table to see its newest rows. " + - "Stored health rows are never included in a diagnostics export."), + tr("Stored health rows are never included in a diagnostics export.")), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) counts.forEach { count -> Row( @@ -140,7 +142,7 @@ fun DebugScreen(viewModel: DiagnosticsViewModel, onBack: () -> Unit = {}) { }) { Text(count.name, style = MaterialTheme.typography.bodyMedium) } - Text("${count.count} rows", style = MaterialTheme.typography.bodyMedium, + Text(trf("{0} rows", count.count), style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Medium, color = MaterialTheme.colorScheme.primary) } if (expandedTable == count.name) { @@ -212,7 +214,7 @@ fun DebugScreen(viewModel: DiagnosticsViewModel, onBack: () -> Unit = {}) { // ── App Info ──────────────────────────────────────────────── item { DebugCard(tr("App Info")) { - Text("PulseLoop ${BuildConfig.VERSION_NAME} (Android)", style = MaterialTheme.typography.bodyMedium) + Text(trf("PulseLoop {0} (Android)", BuildConfig.VERSION_NAME), style = MaterialTheme.typography.bodyMedium) Text(tr("Port from iOS · Open Source"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt b/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt index 248fed6c..0d823bdd 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import androidx.compose.foundation.Canvas @@ -140,11 +142,11 @@ private fun Stepper(label: String, value: String, onMinus: () -> Unit, onPlus: ( Text(label, fontSize = 14.sp, color = PulseColors.textPrimary) note?.let { Text(it, fontSize = 12.sp, color = PulseColors.textMuted) } } - TextButton(onClick = onMinus, modifier = Modifier.semantics { contentDescription = "Decrease $label" }) { + TextButton(onClick = onMinus, modifier = Modifier.semantics { contentDescription = trf("Decrease {0}", label) }) { Text("−", fontSize = 18.sp, modifier = Modifier.clearAndSetSemantics {}) } Text(value, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary, textAlign = TextAlign.Center, modifier = Modifier.widthIn(min = 36.dp)) - TextButton(onClick = onPlus, modifier = Modifier.semantics { contentDescription = "Increase $label" }) { + TextButton(onClick = onPlus, modifier = Modifier.semantics { contentDescription = trf("Increase {0}", label) }) { Text("+", fontSize = 18.sp, modifier = Modifier.clearAndSetSemantics {}) } } @@ -307,7 +309,7 @@ private fun DrinksWelcome(onStart: () -> Unit) { ) Stepper(tr("Dry days a week"), "$dry", { dry = (dry - 1).coerceAtLeast(0) }, { dry = (dry + 1).coerceAtMost(7) }) Row(Modifier.fillMaxWidth().clickable { showSize = !showSize }, verticalAlignment = Alignment.CenterVertically) { - Text("Standard drink: ${grams.roundToInt()} g of alcohol", fontSize = 13.sp, color = PulseColors.textMuted, modifier = Modifier.weight(1f)) + Text(trf("Standard drink: {0} g of alcohol", grams.roundToInt()), fontSize = 13.sp, color = PulseColors.textMuted, modifier = Modifier.weight(1f)) Icon(if (showSize) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, null, tint = PulseColors.textMuted) } if (showSize) { @@ -368,7 +370,7 @@ private fun WeekHero(s: DrinksRepository.Snapshot) { Text(title, fontSize = 18.sp, fontWeight = FontWeight.Bold, color = if (over) PulseColors.warning else PulseColors.textPrimary) Text(sub, fontSize = 13.sp, color = PulseColors.textSecondary) if (s.streaks.current >= 2) { - Text("${s.streaks.current} dry days in a row", fontSize = 13.sp, color = PulseColors.accent) + Text(trf("{0} dry days in a row", s.streaks.current), fontSize = 13.sp, color = PulseColors.accent) } } } @@ -465,7 +467,7 @@ private fun LogCard(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChang } lastLogged?.let { (text, ids) -> Row(verticalAlignment = Alignment.CenterVertically) { - Text("Logged $text", fontSize = 13.sp, color = PulseColors.accent, modifier = Modifier.weight(1f)) + Text(trf("Logged {0}", text), fontSize = 13.sp, color = PulseColors.accent, modifier = Modifier.weight(1f)) Text( tr("Undo"), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, @@ -481,7 +483,7 @@ private fun LogCard(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChang Column(Modifier.weight(1f).clickable(enabled = s.recent.isNotEmpty()) { showTonight = !showTonight }) { val tonight = s.todayStandard Text( - if (tonight > 0) "Tonight: ${std(tonight)} drink${if (tonight == 1.0) "" else "s"}" else "Nothing tonight", + if (tonight > 0) trf("Tonight: {0} drink{1}", std(tonight), if (tonight == 1.0) "" else "s") else tr("Nothing tonight"), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, ) if (s.recent.isNotEmpty()) { @@ -503,7 +505,7 @@ private fun LogCard(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChang AlertDialog( onDismissRequest = { toDelete = null }, title = { Text(tr("Delete drink?")) }, - text = { Text("This ${DrinkType.of(e.type).label.lowercase()} will be removed from your log.") }, + text = { Text(trf("This {0} will be removed from your log.", DrinkType.of(e.type).label.lowercase())) }, confirmButton = { TextButton(onClick = { toDelete = null @@ -548,7 +550,7 @@ private fun PlanChip(s: DrinksRepository.Snapshot, onClick: () -> Unit) { val label = when { planned == null -> tr("Plan tonight") planned == 0 -> tr("Plan: dry night") - else -> "Plan: $planned" + else -> trf("Plan: {0}", planned) } Text( label, @@ -583,12 +585,12 @@ private fun RecentDrinkRow(e: DrinkEntryEntity, gramsPerStd: Double, fmt: DateTi Column(Modifier.weight(1f)) { Text(DrinkType.of(e.type).label, fontSize = 14.sp, color = PulseColors.textPrimary) Text( - "${Instant.ofEpochMilli(e.timestamp).atZone(zone).format(fmt)} · ${std(DrinkInsights.standardDrinks(e.grams, gramsPerStd))} drink" + + trf("{0} · {1} drink", Instant.ofEpochMilli(e.timestamp).atZone(zone).format(fmt), std(DrinkInsights.standardDrinks(e.grams, gramsPerStd))) + if (e.mealId != null) tr(" · from food log") else "", fontSize = 12.sp, color = PulseColors.textMuted, ) } - IconButton(onClick = onDelete) { Icon(Icons.Filled.Delete, "Delete ${DrinkType.of(e.type).label}", tint = PulseColors.textMuted, modifier = Modifier.size(18.dp)) } + IconButton(onClick = onDelete) { Icon(Icons.Filled.Delete, trf("Delete {0}", DrinkType.of(e.type).label), tint = PulseColors.textMuted, modifier = Modifier.size(18.dp)) } } } @@ -604,7 +606,7 @@ private fun MoreDrinkSheet(onLog: (DrinkType, Int, Long, Double?) -> Unit) { 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) + Text(trf("{0} ml at {1}% · about {2} kcal", type.volumeMl.roundToInt(), type.abvPct, type.kcal.roundToInt()), fontSize = 12.sp, color = PulseColors.textMuted) Stepper(tr("How many"), "$count", { count = (count - 1).coerceAtLeast(1) }, { count = (count + 1).coerceAtMost(12) }) FlowRow(Modifier.selectableGroup(), horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { listOf(0L to "Now", 1L to "1 h ago", 3L to "3 h ago", 12L to "Last night").forEach { (h, l) -> @@ -620,7 +622,7 @@ private fun MoreDrinkSheet(onLog: (DrinkType, Int, Long, Double?) -> Unit) { Button( onClick = { onLog(type, count, hoursAgo, price.replace(',', '.').toDoubleOrNull()?.takeIf { it > 0 }) }, modifier = Modifier.fillMaxWidth(), - ) { Text("Log $count") } + ) { Text(trf("Log {0}", count)) } } } @@ -631,9 +633,9 @@ private fun InsightCard(s: DrinksRepository.Snapshot) { val d = s.dose val learning = d.dryNights < DrinkInsights.MIN_NIGHTS val headline = s.morningAfter?.let { DrinksRepository.morningAfterLine(it) } - ?: d.heavier?.hrvPct?.let { "After 3 or more drinks, your HRV runs ${kotlin.math.abs(it)}% ${if (it < 0) "lower" else "higher"} than on dry nights." } - ?: d.light?.hrvPct?.let { "After 1–2 drinks, your HRV runs ${kotlin.math.abs(it)}% ${if (it < 0) "lower" else "higher"} than on dry nights." } - ?: if (learning) "Learning your dry nights: ${d.dryNights} of ${DrinkInsights.MIN_NIGHTS}. Then PulseLoop shows what each drink does to your sleep." + ?: d.heavier?.hrvPct?.let { trf("After 3 or more drinks, your HRV runs {0}% {1} than on dry nights.", kotlin.math.abs(it), if (it < 0) tr("lower") else tr("higher")) } + ?: d.light?.hrvPct?.let { trf("After 1–2 drinks, your HRV runs {0}% {1} than on dry nights.", kotlin.math.abs(it), if (it < 0) tr("lower") else tr("higher")) } + ?: if (learning) trf("Learning your dry nights: {0} of {1}. Then PulseLoop shows what each drink does to your sleep.", d.dryNights, DrinkInsights.MIN_NIGHTS) else tr("Log a few evenings with drinks and PulseLoop will compare those nights with your dry ones.") DrinkCard(tr("Your nights")) { Row(verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(12.dp)) { @@ -651,9 +653,9 @@ private fun InsightCard(s: DrinksRepository.Snapshot) { ImpactRow(tr("After 1–2 drinks"), d.light) ImpactRow(tr("After 3 or more"), d.heavier) s.recoveryNights?.let { - Text("HRV usually takes ${"%.1f".format(it)} night${if (it > 1.05) "s" else ""} to come back.", fontSize = 13.sp, color = PulseColors.textSecondary) + Text(trf("HRV usually takes {0} night{1} to come back.", "%.1f".format(it), if (it > 1.05) "s" else ""), fontSize = 13.sp, color = PulseColors.textSecondary) } - Text("Against your ${d.dryNights} dry nights since you started. A pattern in your data, not proof of cause.", fontSize = 11.sp, color = PulseColors.textMuted) + Text(trf("Against your {0} dry nights since you started. A pattern in your data, not proof of cause.", d.dryNights), fontSize = 11.sp, color = PulseColors.textMuted) } } } @@ -665,9 +667,9 @@ private fun ImpactRow(label: String, i: DrinkInsights.Impact?) { Text(label, fontSize = 13.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary) val text = if (i == null) tr("Not enough nights yet") else buildList { i.hrvPct?.let { add("HRV ${if (it >= 0) "+" else "−"}${kotlin.math.abs(it)}%") } - i.restingHr?.let { add("resting HR ${if (it >= 0) "+" else "−"}${kotlin.math.abs(it)}") } - i.asleepMinutes?.let { add("sleep ${if (it >= 0) "+" else "−"}${kotlin.math.abs(it)} min") } - }.joinToString(" · ").ifEmpty { tr("No clear difference") } + " · ${i.nights} nights" + i.restingHr?.let { add(trf("resting HR {0}{1}", if (it >= 0) "+" else "−", kotlin.math.abs(it))) } + i.asleepMinutes?.let { add(trf("sleep {0}{1} min", if (it >= 0) "+" else "−", kotlin.math.abs(it))) } + }.joinToString(" · ").ifEmpty { tr("No clear difference") } + trf(" · {0} nights", i.nights) Text(text, fontSize = 12.sp, color = PulseColors.textSecondary) } } @@ -699,7 +701,7 @@ private fun TrendsTab(s: DrinksRepository.Snapshot) { WeeksChart(s) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { Box(Modifier.width(16.dp).height(2.dp).background(PulseColors.textMuted)) - Text("your limit of ${std(s.weeklyLimit)}", fontSize = 11.sp, color = PulseColors.textMuted) + Text(trf("your limit of {0}", std(s.weeklyLimit)), fontSize = 11.sp, color = PulseColors.textMuted) } } s.savings?.takeIf { it.drinksAvoided >= 0.5 }?.let { sv -> @@ -775,7 +777,7 @@ private fun SupportTab(s: DrinksRepository.Snapshot, onBreathe: () -> Unit, onCo SupportRow(Icons.Filled.Air, tr("Ride it out"), tr("3 minutes of slow breathing. An urge usually passes within 20 minutes."), onBreathe) if (onCoach != null) { SupportRow(Icons.Filled.AutoAwesome, tr("Talk it through"), tr("Plan the next few days with the coach.")) { - onCoach("I'd like help with my drinking. This week I'm at ${std(s.week.standardDrinks)} of my ${std(s.weeklyLimit)}-drink limit, with ${s.week.dryDays} dry days. Can you help me plan the next few days?") + onCoach(trf("I'd like help with my drinking. This week I'm at {0} of my {1}-drink limit, with {2} dry days. Can you help me plan the next few days?", std(s.week.standardDrinks), std(s.weeklyLimit), s.week.dryDays)) } } } @@ -800,7 +802,7 @@ private fun AuditCard(s: DrinksRepository.Snapshot, onDone: () -> Unit) { val level = AuditC.level(score, sex) Text(level.label, fontSize = 17.sp, fontWeight = FontWeight.Bold, color = if (level == AuditC.Level.LOW) PulseColors.accent else PulseColors.warning) Text(AuditC.advice(level), fontSize = 13.sp, color = PulseColors.textSecondary) - Text("Score $score of 12 · ${DrinkPrefs.auditDate}", fontSize = 11.sp, color = PulseColors.textMuted) + Text(trf("Score {0} of 12 · {1}", score, DrinkPrefs.auditDate), fontSize = 11.sp, color = PulseColors.textMuted) } else { Text(tr("The WHO's short alcohol check (AUDIT-C). Three questions, under a minute. A screen, not a diagnosis."), fontSize = 13.sp, color = PulseColors.textSecondary) } @@ -911,10 +913,10 @@ fun ColumnScope.DrinksTileContent(week: DrinkInsights.Week?, limit: Double, dryT val total = week?.standardDrinks ?: 0.0 Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(4.dp)) { Text(std(total), fontSize = 22.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, maxLines = 1) - Text("of ${std(limit)} this week", fontSize = 11.sp, color = PulseColors.textMuted, modifier = Modifier.padding(bottom = 4.dp), maxLines = 1) + Text(trf("of {0} this week", std(limit)), fontSize = 11.sp, color = PulseColors.textMuted, modifier = Modifier.padding(bottom = 4.dp), maxLines = 1) } Bar(if (limit > 0) (total / limit).toFloat() else 0f, if (limit > 0 && total > limit) PulseColors.warning else PulseColors.drinks) - Text("${week?.dryDays ?: 0} of $dryTarget dry days", fontSize = 11.sp, color = PulseColors.textSecondary, maxLines = 1) + Text(trf("{0} of {1} dry days", week?.dryDays ?: 0, dryTarget), fontSize = 11.sp, color = PulseColors.textSecondary, maxLines = 1) Spacer(Modifier.weight(1f)) Text( "+ ${DrinkPrefs.lastType.label}", 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 a130a4f1..c15f6af3 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/FoodUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/FoodUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import android.content.Context @@ -104,9 +106,9 @@ fun FoodCard( Text(" kcal eaten", fontSize = 13.sp, color = PulseColors.textSecondary, modifier = Modifier.padding(bottom = 4.dp)) } val parts = buildList { - burned?.takeIf { it > 0 }?.let { add("${fmt.format(it.roundToInt())} burned") } - f.calorieGoal?.takeIf { it > 0 }?.let { add("goal ${fmt.format(it.roundToInt())}") } - if (f.proteinG > 0) add("${f.proteinG.roundToInt()} g protein") + burned?.takeIf { it > 0 }?.let { add(trf("{0} burned", fmt.format(it.roundToInt()))) } + f.calorieGoal?.takeIf { it > 0 }?.let { add(trf("goal {0}", fmt.format(it.roundToInt()))) } + if (f.proteinG > 0) add(trf("{0} g protein", f.proteinG.roundToInt())) if (f.meals == 0) add("nothing logged yet") } if (parts.isNotEmpty()) { diff --git a/app/src/main/java/com/pulseloop/ui/screens/GuidanceUi.kt b/app/src/main/java/com/pulseloop/ui/screens/GuidanceUi.kt index 76f40f85..948ce575 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/GuidanceUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/GuidanceUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import com.pulseloop.ui.theme.dither @@ -77,7 +79,7 @@ fun TonightCard(g: BedtimeGuidance.Result, sleepGoalMinutes: Int) { fontSize = 20.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, ) Text( - "For ${sleepGoalMinutes / 60}h asleep before your usual ${BedtimeGuidance.fmt(g.usualWake)}", + trf("For {0}h asleep before your usual {1}", sleepGoalMinutes / 60, BedtimeGuidance.fmt(g.usualWake)), fontSize = 12.sp, color = PulseColors.textMuted, ) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/HealthConnectSourceUi.kt b/app/src/main/java/com/pulseloop/ui/screens/HealthConnectSourceUi.kt index 45bd7d3f..3a4e78fc 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/HealthConnectSourceUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/HealthConnectSourceUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import androidx.activity.compose.rememberLauncherForActivityResult @@ -94,7 +96,7 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { note = null scope.launch { note = when (val r = runCatching { HealthConnectSourceImporter.run(context) }.getOrNull()) { - is HealthConnectSourceImporter.Outcome.Done -> "Imported ${"%,d".format(r.stored)} readings." + is HealthConnectSourceImporter.Outcome.Done -> trf("Imported {0} readings.", "%,d".format(r.stored)) is HealthConnectSourceImporter.Outcome.Failed -> r.message HealthConnectSourceImporter.Outcome.NoPermission -> tr("PulseLoop isn't allowed to read Health Connect any more.") HealthConnectSourceImporter.Outcome.Unavailable -> tr("Health Connect isn't available on this phone.") @@ -125,7 +127,7 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { Text( tr("No PulseLoop ring? If your Oura, Galaxy Ring, Fitbit or watch app writes to Health Connect, PulseLoop can " + "read it from there: sleep, heart rate, HRV, blood oxygen, steps, calories, workouts and periods. " + - "Every screen, the coach and your insights then work from that data."), + tr("Every screen, the coach and your insights then work from that data.")), fontSize = 13.sp, color = PulseColors.textSecondary, ) Text( @@ -147,19 +149,19 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { if (enabled && source != null) { val pkg = source!! AccuracyCard { - Text("Using ${HealthConnectSource.label(context, pkg)}", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(trf("Using {0}", HealthConnectSource.label(context, pkg)), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) val last = remember(refresh) { HealthConnectSource.lastImportAt(context) } val count = remember(refresh) { HealthConnectSource.lastImportCount(context) } Text( last?.let { "Last import " + DateTimeFormatter.ofPattern("EEE d MMM, HH:mm").format(Instant.ofEpochMilli(it).atZone(ZoneId.systemDefault())) + - " · ${"%,d".format(count)} readings" + trf(" · {0} readings", "%,d".format(count)) } ?: tr("Not imported yet"), fontSize = 13.sp, color = PulseColors.textSecondary, ) Text( tr("PulseLoop checks for new data every hour and whenever you open the app. A night usually appears once ") + - "${HealthConnectSource.label(context, pkg)} has synced it in the morning.", + trf("{0} has synced it in the morning.", HealthConnectSource.label(context, pkg)), fontSize = 12.sp, color = PulseColors.textMuted, ) if (canRead && !HealthConnectSource.canReadInBackground(granted)) { @@ -189,7 +191,7 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { val usable = r.sources.filter { it.echo?.looksLikeEcho != true } if (usable.isEmpty()) { AccuracyCard { - Text("No app wrote health data in the last ${ReferenceSourceScanner.LOOKBACK_DAYS} days.", fontSize = 13.sp, color = PulseColors.textSecondary) + Text(trf("No app wrote health data in the last {0} days.", ReferenceSourceScanner.LOOKBACK_DAYS), fontSize = 13.sp, color = PulseColors.textSecondary) Text( tr("In the Oura app: Settings → Health Connect, and turn on sharing. Then come back and look again."), fontSize = 12.sp, color = PulseColors.textMuted, @@ -208,7 +210,7 @@ fun HealthConnectSourceContent(onEnabled: (() -> Unit)? = null) { // enable() queues the first import as background work, which outlives this // screen; onboarding moves on at once, settings shows the pass running here. if (onEnabled != null) onEnabled() else importNow() - }, modifier = Modifier.fillMaxWidth()) { Text("Use ${HealthConnectSource.label(context, src.packageName)}") } + }, modifier = Modifier.fillMaxWidth()) { Text(trf("Use {0}", HealthConnectSource.label(context, src.packageName))) } } } } @@ -229,7 +231,7 @@ fun HealthConnectSourceHeroCard(onOpen: () -> Unit) { verticalArrangement = Arrangement.spacedBy(4.dp), ) { Text(tr("DATA SOURCE"), fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) - Text("${HealthConnectSource.label(context, pkg)} via Health Connect", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(trf("{0} via Health Connect", HealthConnectSource.label(context, pkg)), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text( last?.let { "Last import " + DateTimeFormatter.ofPattern("EEE HH:mm").format(Instant.ofEpochMilli(it).atZone(ZoneId.systemDefault())) } ?: tr("Waiting for the first import"), 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 d29383a4..d3dae050 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import androidx.compose.foundation.background @@ -192,7 +194,7 @@ fun JournalScreen(db: PulseLoopDatabase, onBack: () -> Unit, onOpenDrinks: (() - when { list == null -> Unit list.isEmpty() -> Text( - "Tag your days for a couple of weeks. Once a tag has at least ${JournalInsights.MIN_NIGHTS} nights after it, PulseLoop compares those nights with your others.", + trf("Tag your days for a couple of weeks. Once a tag has at least {0} nights after it, PulseLoop compares those nights with your others.", JournalInsights.MIN_NIGHTS), fontSize = 13.sp, color = PulseColors.textSecondary, ) else -> Column( @@ -204,7 +206,7 @@ fun JournalScreen(db: PulseLoopDatabase, onBack: () -> Unit, onOpenDrinks: (() - val enough = e.nightsWith >= JournalInsights.MIN_NIGHTS && e.nightsWithout >= JournalInsights.MIN_NIGHTS Text( if (enough) e.summary().replaceFirstChar { it.uppercase() } - else "Tag ${maxOf(0, JournalInsights.MIN_NIGHTS - e.nightsWith)} more ${if (JournalInsights.MIN_NIGHTS - e.nightsWith == 1) "day" else "days"} to see an effect", + else trf("Tag {0} more {1} to see an effect", maxOf(0, JournalInsights.MIN_NIGHTS - e.nightsWith), if (JournalInsights.MIN_NIGHTS - e.nightsWith == 1) tr("day") else tr("days")), fontSize = 13.sp, color = if (enough && e.hasEffect) PulseColors.textSecondary 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 5c1c34e1..473a5d9a 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import com.pulseloop.ui.theme.dither @@ -434,7 +436,7 @@ fun MealAnalysisDialog( // iOS confidence caption (:174-178). Spacer(Modifier.width(8.dp)) Text( - "${confidence.replaceFirstChar { it.uppercase() }} confidence", + trf("{0} confidence", confidence.replaceFirstChar { it.uppercase() }), fontSize = 12.sp, color = PulseColors.textMuted, ) @@ -655,11 +657,11 @@ object MealAnalysisLogic { /** Verbatim system prompt (MealAnalysisSheet.swift:338-342). */ val systemPrompt: String = - "You are a nutrition estimator. Given a meal description and/or photo, " + + tr("You are a nutrition estimator. Given a meal description and/or photo, " + "identify the food and estimate total calories and macros for the portion shown or described. " + - "Be realistic about portion sizes; state your assumptions (portion sizes, preparation) briefly. " + + tr("Be realistic about portion sizes; state your assumptions (portion sizes, preparation) briefly. " + "Use confidence \"high\" only for clearly identifiable, standard portions. " + - "Return only JSON matching the schema." + "Return only JSON matching the schema.")) /** * The verbatim strict meal_estimate json_schema (MealAnalysisSheet.swift:344-362), built @@ -669,12 +671,12 @@ object MealAnalysisLogic { fun described(value: String) = JsonObject(mapOf("type" to JsonPrimitive("string"), "description" to JsonPrimitive(value))) fun number() = JsonObject(mapOf("type" to JsonPrimitive("number"))) val props = JsonObject(mapOf( - "name" to described("Short display name for the meal"), + "name" to described(tr("Short display name for the meal")), "calories" to number(), "protein_g" to number(), "carbs_g" to number(), "fat_g" to number(), - "assumptions" to described("Portion/preparation assumptions, one short sentence, or empty string"), + "assumptions" to described(tr("Portion/preparation assumptions, one short sentence, or empty string")), "confidence" to JsonObject(mapOf( "type" to JsonPrimitive("string"), "enum" to JsonArray(listOf(JsonPrimitive("low"), JsonPrimitive("medium"), JsonPrimitive("high"))), @@ -724,7 +726,7 @@ object MealEstimator { if (!keyStore.coachEnabled || resolution.key == null) { return@withContext Result.Failure( tr("AI analysis needs the coach enabled with a configured provider (Settings → AI Coach). " + - "You can still search the database or enter the meal manually."), + tr("You can still search the database or enter the meal manually.")), ) } val model = CoachClientResolver.activeModel(providerStore.snapshot(), keyStore.model) @@ -744,7 +746,7 @@ object MealEstimator { } // iOS :392 — the description, or the photo-only prompt. - val prompt = description.trim().ifEmpty { "Estimate the nutrition of the meal in the photo." } + val prompt = description.trim().ifEmpty { tr("Estimate the nutrition of the meal in the photo.") } val input = JsonArray(listOf( OpenAIRequestBuilder.message("system", MealAnalysisLogic.systemPrompt), OpenAIRequestBuilder.message("user", prompt, images), @@ -767,7 +769,7 @@ object MealEstimator { } catch (e: CancellationException) { throw e } catch (e: Exception) { - Result.Failure("Analysis failed: ${e.message ?: e.javaClass.simpleName}") + Result.Failure(trf("Analysis failed: {0}", e.message ?: e.javaClass.simpleName)) } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/MedsUi.kt b/app/src/main/java/com/pulseloop/ui/screens/MedsUi.kt index 651251f1..a66f78de 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MedsUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MedsUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import androidx.compose.foundation.background @@ -113,7 +115,7 @@ fun MedsScreen(onBack: () -> Unit) { val adherence = Meds.adherence(m, answers, today) Text( (if (m.kind == "supplement") tr("Supplement") else tr("Medication")) + " · " + Meds.times(m).joinToString(", ") + - (adherence?.let { " · $it% taken this week" } ?: "") + if (!m.active) tr(" · paused") else "", + (adherence?.let { trf(" · {0}% taken this week", it) } ?: "") + if (!m.active) tr(" · paused") else "", fontSize = 12.sp, color = PulseColors.textMuted, ) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt b/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt index 861b6704..d1d767d8 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,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import com.pulseloop.ui.components.rememberReduceMotion @@ -195,7 +197,7 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () verticalAlignment = Alignment.CenterVertically, ) { Column(Modifier.weight(1f)) { - Text(cycle?.let { "Cycle · day ${it.cycleDay} · ${it.phase.label}" } ?: "Cycle", fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(cycle?.let { trf("Cycle · day {0} · {1}", it.cycleDay, it.phase.label) } ?: tr("Cycle"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(cycle?.phase?.note ?: tr("Log your period to see its phase beside your sleep and recovery"), fontSize = 12.sp, color = PulseColors.textMuted) } Text("›", fontSize = 22.sp, color = PulseColors.textMuted) @@ -248,7 +250,7 @@ fun MyHealthScreen(onBack: () -> Unit, onBreathe: () -> Unit, onWhatChanged: () private fun RadarSection(r: SymptomRadar.Result?, restUntil: java.time.LocalDate?, onRest: (Int?) -> Unit) { Section(tr("Symptom Radar")) { if (r == null || r.baselineNights < SymptomRadar.MIN_BASELINE) { - Text("Learning your normal: ${r?.baselineNights ?: 0} of ${SymptomRadar.MIN_BASELINE} nights.", fontSize = 13.sp, color = PulseColors.textSecondary) + Text(trf("Learning your normal: {0} of {1} nights.", r?.baselineNights ?: 0, SymptomRadar.MIN_BASELINE), fontSize = 13.sp, color = PulseColors.textSecondary) } else { val color = when (r.level) { SymptomRadar.Level.NONE -> PulseColors.success @@ -269,7 +271,7 @@ private fun RadarSection(r: SymptomRadar.Result?, restUntil: java.time.LocalDate Column(Modifier.weight(1f)) { Text(tr("Rest Mode"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text( - restUntil?.let { "On until ${it.dayOfMonth}/${it.monthValue}: activity nudges paused, the coach eases off." } + restUntil?.let { trf("On until {0}/{1}: activity nudges paused, the coach eases off.", it.dayOfMonth, it.monthValue) } ?: tr("Feeling unwell? Pause activity nudges for 3 days."), fontSize = 12.sp, color = PulseColors.textMuted, ) @@ -289,10 +291,10 @@ private fun SleepSection(s: HealthInsightsRepository.Snapshot) { SleepDebt.Level.NONE -> PulseColors.success; SleepDebt.Level.LOW -> PulseColors.info SleepDebt.Level.MODERATE -> PulseColors.warning; SleepDebt.Level.HIGH -> PulseColors.danger } - Fact(tr("Sleep debt"), "${d.level.label} · ${SleepFormat.duration(d.minutes)}", "Last 14 nights, recent nights weigh more", color) + Fact(tr("Sleep debt"), "${d.level.label} · ${SleepFormat.duration(d.minutes)}", tr("Last 14 nights, recent nights weigh more"), color) } ?: Fact(tr("Sleep debt"), "—", tr("Needs 5 nights in the last 2 weeks")) s.bodyClock?.let { c -> - Fact(tr("Body clock"), c.chronotype.label, "Usual sleep midpoint ${c.midpointLabel()} · this week ${c.alignment.label.lowercase()}" + + Fact(tr("Body clock"), c.chronotype.label, trf("Usual sleep midpoint {0} · this week {1}", c.midpointLabel(), c.alignment.label.lowercase()) + if (c.alignment != BodyClock.Alignment.ALIGNED) " (${if (c.recentShiftMin > 0) "+" else ""}${c.recentShiftMin} min)" else "") } } @@ -306,7 +308,7 @@ private fun StressSection(s: HealthInsightsRepository.Snapshot, onBreathe: () -> if (z == null) { Text(tr("No daytime stress readings today yet."), fontSize = 13.sp, color = PulseColors.textMuted) } else { - Text("Today: ${z.summary.label}", fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(trf("Today: {0}", z.summary.label), fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) val total = z.totalMin.coerceAtLeast(1).toFloat() Row(Modifier.fillMaxWidth().height(10.dp).clip(RoundedCornerShape(2.dp))) { listOf(z.restoredMin to PulseColors.success, z.relaxedMin to PulseColors.info, @@ -314,10 +316,10 @@ private fun StressSection(s: HealthInsightsRepository.Snapshot, onBreathe: () -> if (m > 0) Box(Modifier.weight(m / total).fillMaxHeight().background(c)) } } - Text("Restored ${SleepFormat.duration(z.restoredMin)} · relaxed ${SleepFormat.duration(z.relaxedMin)} · engaged ${SleepFormat.duration(z.engagedMin)} · stressed ${SleepFormat.duration(z.stressedMin)}", + Text(trf("Restored {0} · relaxed {1} · engaged {2} · stressed {3}", SleepFormat.duration(z.restoredMin), SleepFormat.duration(z.relaxedMin), SleepFormat.duration(z.engagedMin), SleepFormat.duration(z.stressedMin)), fontSize = 12.sp, color = PulseColors.textMuted) } - s.resilience?.let { Fact(tr("Resilience"), it.level.label, "Daytime recovery against stress, and how well nights restore you (${it.daysUsed} days)") } + s.resilience?.let { Fact(tr("Resilience"), it.level.label, trf("Daytime recovery against stress, and how well nights restore you ({0} days)", it.daysUsed)) } val sessions = remember { MindfulSessions.all(context) } val week = sessions.filter { it.startAt >= System.currentTimeMillis() - 7 * 86_400_000L } Fact(tr("Breathing sessions this week"), "${week.size} · ${week.sumOf { it.minutes }} min") @@ -326,7 +328,7 @@ private fun StressSection(s: HealthInsightsRepository.Snapshot, onBreathe: () -> effect?.let { e -> Fact( tr("After a session"), "HRV ${if (e.hrvChangePct >= 0) "+" else ""}${e.hrvChangePct}%", - "Two hours after against two hours before, over ${e.sessions} sessions. Readings during a session aren't counted: slow breathing raises HRV while it lasts.", + trf("Two hours after against two hours before, over {0} sessions. Readings during a session aren't counted: slow breathing raises HRV while it lasts.", e.sessions), ) } OutlinedButton(onClick = onBreathe, modifier = Modifier.fillMaxWidth()) { Text(tr("Start a breathing session")) } @@ -346,12 +348,12 @@ private fun HeartSection(s: HealthInsightsRepository.Snapshot) { s.cardioLoad?.let { l -> Fact( tr("Cardio load today"), "${l.load}" + (l.band?.let { " · ${it.label}" } ?: ""), - "Heart rate above your quiet waking ${l.quietHr} bpm, ${l.elevatedMinutes} min well above it" + - (l.usual?.let { ". Your usual day: $it" } ?: ""), + trf("Heart rate above your quiet waking {0} bpm, {1} min well above it", l.quietHr, l.elevatedMinutes) + + (l.usual?.let { trf(". Your usual day: {0}", it) } ?: ""), ) } s.cardio?.let { c -> - Fact("Cardio capacity (VO₂max)", "%.0f · %s".format(c.vo2max, c.level.label), + Fact(tr("Cardio capacity (VO₂max)"), "%.0f · %s".format(c.vo2max, c.level.label), if (c.fromRing) tr("Measured by your ring") else tr("Estimated from resting heart rate and age")) // No "cardiovascular age": from a ring it would only restate resting heart rate and age // as a number of years, which reads as far more than it is (OpenStrap Edge dropped its @@ -374,8 +376,8 @@ private fun Legend(color: Color, label: String) { fun HeartRateContextChart(samples: List, sleep: List, workouts: List) { val sorted = remember(samples) { samples.sortedBy { it.timestampMs } } 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" + trf("Heart rate since last night: latest {0} bpm, ", sorted.last().value.roundToInt()) + + trf("range {0}–{1} bpm, {2} readings", sorted.minOf { it.value }.roundToInt(), sorted.maxOf { it.value }.roundToInt(), sorted.size) } Canvas(Modifier.fillMaxWidth().height(90.dp).semantics { contentDescription = summary }) { val t0 = sorted.first().timestampMs; val t1 = sorted.last().timestampMs.coerceAtLeast(t0 + 1) @@ -401,7 +403,7 @@ private fun HabitsSection(h: HealthInsightsRepository.Habits) { h.bedtime?.let { Fact(tr("Bedtime"), it) } h.wake?.let { Fact(tr("Wake-up"), it) } h.sleepMin?.let { Fact(tr("Sleep"), SleepFormat.duration(it)) } - h.steps?.let { Fact("Steps", "%,d".format(it)) } + h.steps?.let { Fact(tr("Steps"), "%,d".format(it)) } h.activeMin?.let { Fact(tr("Active minutes"), "$it min") } h.restingHr?.let { Fact(tr("Resting heart rate"), "${it.roundToInt()} bpm") } if (listOf(h.bedtime, h.steps, h.restingHr).all { it == null }) { @@ -445,14 +447,14 @@ private fun TrendsSection(db: PulseLoopDatabase) { } val pts = points when { - pts == null && trendFailed -> Text("Couldn't load ${metric.label.lowercase()} trends.", fontSize = 12.sp, color = PulseColors.warning) + pts == null && trendFailed -> Text(trf("Couldn't load {0} trends.", metric.label.lowercase()), fontSize = 12.sp, color = PulseColors.warning) pts == null -> Text(tr("Loading…"), fontSize = 12.sp, color = PulseColors.textMuted) - pts.size < 2 -> Text("Not enough ${metric.label.lowercase()} data for this view yet.", fontSize = 12.sp, color = PulseColors.textMuted) + pts.size < 2 -> Text(trf("Not enough {0} data for this view yet.", metric.label.lowercase()), fontSize = 12.sp, color = PulseColors.textMuted) else -> { val shown = pts.takeLast(if (period == Trends.Period.DAY) 30 else 26) val fmt = if (metric == TrendMetric.TEMPERATURE || metric == TrendMetric.SLEEP || metric == TrendMetric.WEIGHT) "%.1f" else "%.0f" - val summary = "${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" + val summary = trf("{0} by {1}: latest {2} {3}, ", metric.label, period.label.lowercase(), fmt.format(shown.last().value), metric.unit) + + trf("range {0}–{1} {2}, {3} points", fmt.format(shown.minOf { it.value }), fmt.format(shown.maxOf { it.value }), metric.unit, shown.size) 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)) @@ -465,7 +467,7 @@ private fun TrendsSection(db: PulseLoopDatabase) { } } val last = shown.last() - Text("Latest ${period.label.lowercase()}: ${fmt.format(last.value)} ${metric.unit} · average ${fmt.format(shown.map { it.value }.average())} ${metric.unit}", + Text(trf("Latest {0}: {1} {2} · average {3} {4}", period.label.lowercase(), fmt.format(last.value), metric.unit, fmt.format(shown.map { it.value }.average()), metric.unit), fontSize = 12.sp, color = PulseColors.textSecondary) } } @@ -549,9 +551,9 @@ fun BreatheScreen(onBack: () -> Unit) { } r != null -> { Text(tr("Session saved"), fontSize = 22.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - Text("${r.minutes} min" + (r.avgHr?.let { " · average $it bpm" } ?: ""), fontSize = 15.sp, color = PulseColors.textSecondary) + Text("${r.minutes} min" + (r.avgHr?.let { trf(" · average {0} bpm", it) } ?: ""), fontSize = 15.sp, color = PulseColors.textSecondary) if (r.startHr != null && r.endHr != null) { - Text("Heart rate ${r.startHr} → ${r.endHr} bpm", fontSize = 15.sp, color = PulseColors.textSecondary) + Text(trf("Heart rate {0} → {1} bpm", r.startHr, r.endHr), fontSize = 15.sp, color = PulseColors.textSecondary) } else { Text(tr("Your ring logs heart rate every few minutes, so short sessions may show none."), fontSize = 12.sp, color = PulseColors.textMuted) } @@ -595,7 +597,7 @@ fun MyHealthEntryCard(onClick: () -> Unit) { Column(Modifier.weight(1f)) { Text(tr("My Health & Trends"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text( - if (restUntil != null) "Rest Mode on until ${restUntil.dayOfWeek.getDisplayName(java.time.format.TextStyle.SHORT, java.util.Locale.getDefault())}" + if (restUntil != null) trf("Rest Mode on until {0}", restUntil.dayOfWeek.getDisplayName(java.time.format.TextStyle.SHORT, java.util.Locale.getDefault())) else tr("Symptom radar, sleep debt, stress, body clock, cardio capacity"), fontSize = 12.sp, color = if (restUntil != null) PulseColors.accent else PulseColors.textMuted, ) @@ -634,7 +636,7 @@ private fun StepCalibrationCard(db: PulseLoopDatabase) { }, modifier = Modifier.fillMaxWidth()) { Text(tr("Compare with my phone")) } } result == null -> Text( - "Collecting: needs ${com.pulseloop.service.StepCalibration.MIN_DAYS} days with at least ${com.pulseloop.service.StepCalibration.MIN_STEPS} steps on both. Carry your phone as usual.", + trf("Collecting: needs {0} days with at least {1} steps on both. Carry your phone as usual.", com.pulseloop.service.StepCalibration.MIN_DAYS, com.pulseloop.service.StepCalibration.MIN_STEPS), fontSize = 13.sp, color = PulseColors.textMuted, ) else -> { @@ -642,9 +644,9 @@ private fun StepCalibrationCard(db: PulseLoopDatabase) { val pct = ((r.factor - 1) * 100).roundToInt() Text( when { - kotlin.math.abs(pct) < 5 -> "Your ring and phone agree within 5% (${r.days} days)." - pct > 0 -> "Your ring counts about $pct% fewer steps than your phone (${r.days} days)." - else -> "Your ring counts about ${-pct}% more steps than your phone (${r.days} days)." + kotlin.math.abs(pct) < 5 -> trf("Your ring and phone agree within 5% ({0} days).", r.days) + pct > 0 -> trf("Your ring counts about {0}% fewer steps than your phone ({1} days).", pct, r.days) + else -> trf("Your ring counts about {0}% more steps than your phone ({1} days).", -pct, r.days) }, fontSize = 14.sp, color = PulseColors.textPrimary, ) diff --git a/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt index 0a677ca4..dd183c6c 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import androidx.compose.foundation.layout.* @@ -188,9 +190,9 @@ fun NutritionScreen( onDiscuss = onDiscuss?.let { discuss -> { discuss( - "For my next meal (${idea.slot}) you suggested: " + + trf("For my next meal ({0}) you suggested: ", idea.slot) + idea.items.joinToString(", ") { "${it.name} (${it.portion})" } + - ", about ${idea.totalKcal} kcal. Can we look at alternatives?" + trf(", about {0} kcal. Can we look at alternatives?", idea.totalKcal) ) } }, @@ -214,7 +216,7 @@ fun NutritionScreen( 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 = { mealToDelete = meal }) { - Icon(Icons.Filled.Delete, "Delete ${meal.name}", tint = PulseColors.danger, modifier = Modifier.size(18.dp)) + Icon(Icons.Filled.Delete, trf("Delete {0}", meal.name), tint = PulseColors.danger, modifier = Modifier.size(18.dp)) } } } @@ -265,7 +267,7 @@ fun NutritionScreen( AlertDialog( onDismissRequest = { mealToDelete = null }, title = { Text(tr("Delete meal?")) }, - text = { Text("\"${meal.name}\" will be removed from this day's log.") }, + text = { Text(trf("\"{0}\" will be removed from this day's log.", meal.name)) }, confirmButton = { TextButton(onClick = { mealToDelete = null @@ -567,7 +569,7 @@ private fun NextMealCard( border = androidx.compose.foundation.BorderStroke(1.dp, PulseColors.accent), ) { Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { - Text("NEXT MEAL IDEA · ${idea.slot.uppercase()}", fontSize = 11.sp, letterSpacing = 1.4.sp, color = PulseColors.accent) + Text(trf("NEXT MEAL IDEA · {0}", idea.slot.uppercase()), fontSize = 11.sp, letterSpacing = 1.4.sp, color = PulseColors.accent) if (idea.items.isEmpty()) { Text(idea.note ?: "", fontSize = 14.sp, color = PulseColors.textPrimary) } else { @@ -581,7 +583,7 @@ private fun NextMealCard( } } Text( - "≈ ${idea.totalKcal} kcal · ${idea.totalProteinG} g protein · leaves ${idea.leavesKcal} kcal", + trf("≈ {0} kcal · {1} g protein · leaves {2} kcal", idea.totalKcal, idea.totalProteinG, idea.leavesKcal), fontSize = 13.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, ) if (idea.fromPreferences.isNotEmpty()) { 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 618650c7..d6171e59 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/OnboardingScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/OnboardingScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import com.pulseloop.ui.theme.dither @@ -268,7 +270,7 @@ private fun OnboardingTopBar( } } Text( - "Step ${step.index + 1} of $total", + trf("Step {0} of {1}", step.index + 1, total), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, fontFamily = com.pulseloop.ui.theme.UbuntuMono, @@ -337,7 +339,7 @@ private fun WelcomeStep( if (permissionDenied) { Text( tr("PulseLoop needs Bluetooth permission to find and connect to your ring. " + - "Allow it in Settings, or continue without a ring and pair one later."), + tr("Allow it in Settings, or continue without a ring and pair one later.")), fontSize = 13.sp, color = PulseColors.textSecondary, textAlign = TextAlign.Center, 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 a2c533c9..997b23e2 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/PairingScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/PairingScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import android.Manifest @@ -524,8 +526,8 @@ private fun ScanningCard( color = PulseColors.accent, ) Text( - if (connecting) "Connecting to ${selectedModel.displayName}…" - else "Scanning for ${selectedModel.displayName}…", + if (connecting) trf("Connecting to {0}…", selectedModel.displayName) + else trf("Scanning for {0}…", selectedModel.displayName), fontSize = 12.sp, color = PulseColors.textMuted, ) @@ -661,7 +663,7 @@ private fun ConnectedCard( tint = PulseColors.success, ) Text( - "Connected to $deviceName", + trf("Connected to {0}", deviceName), fontSize = 17.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, @@ -741,12 +743,12 @@ private fun BluetoothPermissionCard(permanentlyDenied: Boolean, onRequest: () -> Text( if (permanentlyDenied) { tr("PulseLoop uses Bluetooth to find and connect your ring. " + - "Allow ") + + tr("Allow ")) + (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) tr("\"Nearby devices\"") else tr("Location")) + " for PulseLoop in Settings." } else { tr("PulseLoop uses Bluetooth to find and connect your ring. " + - "Nothing is shared off your phone.") + tr("Nothing is shared off your phone.")) }, fontSize = 14.sp, color = PulseColors.textSecondary, 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 7b703d5c..6669c44c 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import com.pulseloop.ui.theme.dither @@ -82,7 +84,7 @@ fun ScoreRing( 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" } ?: tr("No score") + contentDescription = value?.let { trf("Score {0} out of 100", it) } ?: tr("No score") if (value != null) progressBarRangeInfo = ProgressBarRangeInfo(value.coerceIn(0, 100).toFloat(), 0f..100f) }, contentAlignment = Alignment.Center, @@ -384,7 +386,7 @@ fun activityHeadline(result: com.pulseloop.service.ActivityScore.Result?): Strin Readiness.Band.OPTIMAL -> tr("Great balance of movement and recovery. Keep it up.") Readiness.Band.GOOD -> tr("A solid active day so far.") Readiness.Band.FAIR, Readiness.Band.PAY_ATTENTION -> - if (weakest != null) "There's room to move more. Start with your $weakest." else "There's room to move more today." + if (weakest != null) trf("There's room to move more. Start with your {0}.", weakest) else tr("There's room to move more today.") } } @@ -428,7 +430,7 @@ private fun DataBehindScore(db: PulseLoopDatabase, result: Readiness.Result?) { Text(v, fontSize = 13.sp, color = PulseColors.textPrimary) } } - night?.withheld?.values?.forEach { Text("Withheld: $it.", fontSize = 12.sp, color = PulseColors.warning) } + night?.withheld?.values?.forEach { Text(trf("Withheld: {0}.", it), fontSize = 12.sp, color = PulseColors.warning) } } } } 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 d13b767a..2d096085 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/Screens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/Screens.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import com.pulseloop.ui.theme.dither @@ -410,7 +412,7 @@ fun VitalsScreen( onClick = { runMeasurement( coordinator.remainingLegsMeasureSeconds, remainingLegsLabel, - caption = "Keep still — measuring $remainingLegsLabel…", + caption = trf("Keep still — measuring {0}…", remainingLegsLabel), failed = { (coordinator.canMeasureBloodPressure && coordinator.bloodPressureState == failedState) || @@ -438,7 +440,7 @@ fun VitalsScreen( onClick = { runMeasurement( coordinator.spotVitalMeasureSeconds, label, - caption = "Keep still — measuring ${vital.description}…", + caption = trf("Keep still — measuring {0}…", vital.description), failed = { coordinator.vitalState(vital) == failedState }, ) { coordinator.measureVitalOnly(vital) } }, @@ -472,7 +474,7 @@ fun VitalsScreen( }, ) { Text( - if (measuring) "Measuring… ${remaining}s" else tr("Measure"), + if (measuring) trf("Measuring… {0}s", remaining) else tr("Measure"), color = androidx.compose.ui.graphics.Color.Unspecified, ) } @@ -1052,7 +1054,7 @@ private fun ReadingsCard( onClick = { visibleCount += READINGS_PAGE_SIZE }, modifier = Modifier.padding(start = 8.dp), ) { - Text("Show ${minOf(READINGS_PAGE_SIZE, readings.size - visibleCount)} more", fontSize = 13.sp) + Text(trf("Show {0} more", minOf(READINGS_PAGE_SIZE, readings.size - visibleCount)), fontSize = 13.sp) } } Spacer(Modifier.height(8.dp)) @@ -1202,11 +1204,11 @@ private fun zoneRangeText( private fun metricDisclaimer(metric: String, isDerived: Boolean): String? = when { metric == "stress" && isDerived -> tr("Estimated from HRV — your ring doesn't measure stress. Scored against your own recent " + - "HRV readings, so it says how this reading compares with your normal, not how you compare " + - "with anyone else.") + tr("HRV readings, so it says how this reading compares with your normal, not how you compare " + + "with anyone else.")) metric == "glucose" -> tr("Estimated wellness metric — not for dosing or diabetes decisions. No smart ring or watch is " + - "FDA-authorized to measure or estimate glucose on its own.") + tr("FDA-authorized to measure or estimate glucose on its own.")) metric == "bp" -> tr("Ring blood pressure is an estimate. Calibrate against a validated cuff in Settings → Calibration, " + "and talk to a clinician about persistent high or low readings.") @@ -1235,15 +1237,15 @@ private fun metricExplainer(metric: String): String = when (metric) { "hrv" -> tr("Heart-rate variability is the variation between beats. It's highly individual, so we track it " + "against your personal baseline rather than a universal cutoff.") "bp" -> tr("Blood pressure is systolic over diastolic (mmHg). The category is the worse of the two. " + - "A ring estimate is not a substitute for a cuff.") + tr("A ring estimate is not a substitute for a cuff.")) "stress" -> tr("A device wellness score from 0–100 based on heart-rate patterns. Lower is calmer. " + - "It's an estimate, not a medical stress measure.") + tr("It's an estimate, not a medical stress measure.")) "fatigue" -> tr("A device wellness score from 0–100 estimating tiredness. Higher means more fatigue. " + - "It's a ring estimate, not a clinical scale.") + tr("It's a ring estimate, not a clinical scale.")) "glucose" -> tr("An estimated glucose value. No smart ring is cleared to measure glucose, so treat this " + "as a wellness estimate only.") "temp" -> tr("Skin temperature from the ring runs cooler than core body temperature. " + - "Trends over time matter more than any single reading.") + tr("Trends over time matter more than any single reading.")) else -> "" } 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 32d61b28..e8416c17 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import androidx.compose.foundation.layout.* @@ -72,7 +74,7 @@ fun SettingsScreen( val accuracyTrailing = openCheck?.let { c -> if (c.state == com.pulseloop.data.entity.AccuracyCheckEntity.STATE_RUNNING) { val (day, total) = AccuracyUiText.dayOf(c) - "Day $day of $total" + trf("Day {0} of {1}", day, total) } else tr("Report ready") } 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 db71e146..3eff61c7 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.i18n.trf + import com.pulseloop.ui.i18n.tr import com.pulseloop.ui.components.switchRow @@ -231,7 +233,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { val activeModel = if (isLocal) providerStore.localModel.ifBlank { "local server" } else selectedModel Text( - if (coachEnabled && ready) "Active — $activeModel" + if (coachEnabled && ready) trf("Active — {0}", activeModel) else if (coachEnabled && isLocal) tr("Server address needed") else if (coachEnabled) tr("API key needed") else tr("Disabled"), @@ -505,7 +507,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { Text( urlProblem?.let { LocalEndpoint.message(it) } ?: tr("Default ports — Ollama 11434 · LM Studio 1234 · llama.cpp 8080 · vLLM 8000 · SGLang 30000. " + - "The /v1 path is added for you."), + tr("The /v1 path is added for you.")), style = MaterialTheme.typography.bodySmall, color = if (urlProblem != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, @@ -823,7 +825,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Text(tr("Coach Memory"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) TextButton(onClick = { showMemory = !showMemory }) { - Text(if (showMemory) tr("Hide") else "Show (${memories.size})") + Text(if (showMemory) tr("Hide") else trf("Show ({0})", memories.size)) } } if (showMemory) { @@ -839,7 +841,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { Text(memory.value, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 2) } IconButton(onClick = { memoryToDelete = memory.key }) { - Icon(Icons.Filled.Delete, "Delete ${memory.key}", tint = MaterialTheme.colorScheme.error) + Icon(Icons.Filled.Delete, trf("Delete {0}", memory.key), tint = MaterialTheme.colorScheme.error) } } } @@ -854,7 +856,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { AlertDialog( onDismissRequest = { memoryToDelete = null }, title = { Text(tr("Delete memory?")) }, - text = { Text("The coach will forget \"$key\". This can't be undone.") }, + text = { Text(trf("The coach will forget \"{0}\". This can't be undone.", key)) }, confirmButton = { TextButton(onClick = { memoryToDelete = null @@ -1189,7 +1191,7 @@ fun ProfileSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> Unit) SettingsSubScreen(title = tr("User Profile"), onBack = onBack) { Text( tr("Your age, sex, height and weight let the ring compute accurate calories (and, on " + - "56ff/Jring rings, blood sugar). Blood pressure is measured directly by the sensor."), + tr("56ff/Jring rings, blood sugar). Blood pressure is measured directly by the sensor.")), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -1285,7 +1287,7 @@ fun PhysiologySettingsScreen(onBack: () -> Unit) { SettingsSubScreen(title = tr("Physiology"), onBack = onBack) { Text( tr("Optional refinements to how your vitals are interpreted. Leave anything unset and " + - "PulseLoop uses sensible defaults."), + tr("PulseLoop uses sensible defaults.")), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -1474,7 +1476,7 @@ fun CalibrationSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U Text(tr("Blood sugar calibration"), style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.SemiBold) Text( tr("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."), + tr("Enter a recent lab/meter reading (mg/dL) to offset the displayed value to match.")), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -1504,7 +1506,7 @@ fun CalibrationSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U keyStore.glucoseOffsetMgdl = ref - latestRaw keyStore.glucoseRefMgdl = ref glucoseOffset = keyStore.glucoseOffsetMgdl - glucoseMsg = "Calibrated ✓ (offset %+.0f mg/dL)".format(glucoseOffset) + glucoseMsg = tr("Calibrated ✓ (offset %+.0f mg/dL)").format(glucoseOffset) } }, modifier = Modifier.weight(1f), @@ -1512,7 +1514,7 @@ fun CalibrationSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U } Row(verticalAlignment = Alignment.CenterVertically) { Text( - if (glucoseOffset != 0.0) "Current offset: %+.0f mg/dL".format(glucoseOffset) else "No calibration set", + if (glucoseOffset != 0.0) tr("Current offset: %+.0f mg/dL").format(glucoseOffset) else tr("No calibration set"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f), @@ -1679,7 +1681,7 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U VitalToggle(tr("All-day heart rate"), cfgHrEnabled) { cfgHrEnabled = it } if (cfgHrEnabled) { Text( - "Every $cfgHrInterval min", + trf("Every {0} min", cfgHrInterval), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -1700,7 +1702,7 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U // running both monitors hourly that is most of the battery (issue #66). if (cfgSpo2 && supportsSpo2Interval) { Text( - if (cfgSpo2Interval <= 0) tr("Same as heart rate") else "Every $cfgSpo2Interval min", + if (cfgSpo2Interval <= 0) tr("Same as heart rate") else trf("Every {0} min", cfgSpo2Interval), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -1870,10 +1872,10 @@ private fun QuietHoursCard() { Spacer(Modifier.height(4.dp)) Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { OutlinedButton(onClick = { picking = "start" }, modifier = Modifier.weight(1f)) { - Text("From ${formatMinutesOfDay(start)}") + Text(trf("From {0}", formatMinutesOfDay(start))) } OutlinedButton(onClick = { picking = "end" }, modifier = Modifier.weight(1f)) { - Text("Until ${formatMinutesOfDay(end)}") + Text(trf("Until {0}", formatMinutesOfDay(end))) } } } @@ -1889,8 +1891,8 @@ private fun QuietHoursCard() { tr("To log when Bedtime or Do Not Disturb turns on and off while PulseLoop is " + "in the background, Android requires Notification access. PulseLoop only " + "listens for Mode changes and does not read your notifications.\n\n" + - "If the switch is greyed out, open PulseLoop's App info, tap ⋮ → " + - "Allow restricted settings, then come back here."), + tr("If the switch is greyed out, open PulseLoop's App info, tap ⋮ → " + + tr("Allow restricted settings, then come back here."))), ) }, confirmButton = { @@ -1999,8 +2001,8 @@ fun WearableSettingsScreen( ) Spacer(Modifier.width(8.dp)) Text( - if (isConnected) "Connected — $wearableDisplayName · ${battery ?: 0}%" - else device?.let { "Last seen: $wearableDisplayName" } ?: tr("No ring paired"), + if (isConnected) trf("Connected — {0} · {1}%", wearableDisplayName, battery ?: 0) + else device?.let { trf("Last seen: {0}", wearableDisplayName) } ?: tr("No ring paired"), style = MaterialTheme.typography.bodyMedium, ) } @@ -2009,12 +2011,12 @@ fun WearableSettingsScreen( if (device?.firmwareVersion != null) { val rawFw = device!!.firmwareVersion!! val fwDisplay = if (rawFw.contains("V")) "V" + rawFw.substringAfterLast("V") else rawFw - Text("Firmware: $fwDisplay", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp)) + Text(trf("Firmware: {0}", fwDisplay), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp)) } else if (device != null) { Text(tr("Firmware: reading… (connect ring to read)"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp)) } if (device != null) { - Text("Last synced: $lastSyncedLabel", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp)) + Text(trf("Last synced: {0}", lastSyncedLabel), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp)) } if (device == null) { @@ -2734,7 +2736,7 @@ fun PrivacyDataSettingsScreen( text = { Text( tr("Removes all demo measurements, activity, sleep, and the demo device. " + - "Synced ring data is not affected."), + tr("Synced ring data is not affected.")), ) }, confirmButton = { @@ -2812,7 +2814,7 @@ fun AboutSettingsScreen(onOpenDebug: () -> Unit, onBack: () -> Unit) { showToast(tr("You are now a developer!")) onOpenDebug() } else if (remaining <= 3) { - showToast("You're $remaining step${if (remaining == 1) "" else "s"} away from Developer options.") + showToast(trf("You're {0} step{1} away from Developer options.", remaining, if (remaining == 1) "" else "s")) } } @@ -2855,7 +2857,7 @@ fun AboutSettingsScreen(onOpenDebug: () -> Unit, onBack: () -> Unit) { Text(tr("Version"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(4.dp)) Text( - "PulseLoop v${com.pulseloop.BuildConfig.VERSION_NAME} (${com.pulseloop.BuildConfig.VERSION_CODE})", + trf("PulseLoop v{0} ({1})", com.pulseloop.BuildConfig.VERSION_NAME, com.pulseloop.BuildConfig.VERSION_CODE), style = MaterialTheme.typography.bodyMedium, ) } @@ -3064,7 +3066,7 @@ fun StravaSettingsScreen(onBack: () -> Unit) { Text(tr("Strava Integration"), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Spacer(Modifier.height(8.dp)) Text( - if (isConnected) "Connected as $athleteName. Workouts sync automatically when finished." + if (isConnected) trf("Connected as {0}. Workouts sync automatically when finished.", athleteName) else "Connect your Strava account to automatically upload workouts with GPS routes and heart rate data.", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, @@ -3084,10 +3086,10 @@ fun StravaSettingsScreen(onBack: () -> Unit) { ?: when (count) { 0 -> tr("Nothing new to upload") 1 -> tr("Uploaded 1 workout") - else -> "Uploaded $count workouts" + else -> trf("Uploaded {0} workouts", count) } } catch (e: Exception) { - statusMessage = "Upload failed: ${e.message ?: "unknown error"}" + statusMessage = trf("Upload failed: {0}", e.message ?: tr("unknown error")) } isUploading = false } @@ -3257,7 +3259,7 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { statusMessage = if (got.isEmpty()) { tr("No Health Connect permissions granted — nothing to export.") } else { - "Connected. ${got.size} of ${HealthConnectPermissions.all.size} permission types granted." + trf("Connected. {0} of {1} permission types granted.", got.size, HealthConnectPermissions.all.size) } // First-enable backfill dialog: the derived showBackfillDialog above now turns true from // the persisted state (enabled + connected + NOT_ASKED) this callback just set, so there @@ -3498,7 +3500,7 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { if (syncedAt != null) { // The label promises a time, so show one (review pass 5): the summary // alone read as "Last sync: skipped: …" with no indication of when. - "Last sync ${DeviceHeroStatus.relativeShort(syncedAt, System.currentTimeMillis())} — " + + trf("Last sync {0} — ", DeviceHeroStatus.relativeShort(syncedAt, System.currentTimeMillis())) + (prefs.lastSyncSummary ?: "unknown") } else { tr("No export has run yet. With the master switch on and a backfill choice made, PulseLoop exports automatically.") @@ -3701,12 +3703,12 @@ private fun BatteryRuntimeEstimate(samples: List) { } Column { Text( - "About ${estimate.label} left", + trf("About {0} left", estimate.label), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold, ) Text( - "Estimated from the current discharge at %.1f %%/h.".format(estimate.percentPerHour), + tr("Estimated from the current discharge at %.1f %%/h.").format(estimate.percentPerHour), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -3740,7 +3742,7 @@ private fun CoachManagedCard(fields: Set, } }), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { - Text("Coach goal: ${g.description}", fontWeight = FontWeight.Medium) + Text(trf("Coach goal: {0}", g.description), fontWeight = FontWeight.Medium) Text( if (managed.isEmpty()) tr("Your goal doesn't set any of these.") else tr("Set by your goal: ") + managed.joinToString(", ") { it.label } + ". Change one here and it stops following.", @@ -3794,7 +3796,7 @@ private fun AutoBackupCard() { } Row(verticalAlignment = Alignment.CenterVertically) { Text( - "Folder: ${folderName ?: "not chosen"}", + trf("Folder: {0}", folderName ?: tr("not chosen")), style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f), ) TextButton(onClick = { picker.launch(null) }) { Text(if (folderName == null) tr("Choose") else tr("Change")) } 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 58e2123e..803d980c 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import com.pulseloop.ui.theme.dither @@ -297,9 +299,9 @@ private fun androidx.compose.foundation.lazy.LazyListScope.aggregateItems( label = SleepInsights.rangeHeroLabel[state.range] ?: tr("Sleep"), value = if (enough) SleepFormat.duration(state.avgMinutes ?: 0) else noData.value, support = if (state.range == SleepRangeKey.YEAR) - "Tracked ${valid.size} ${if (valid.size == 1) "night" else "nights"} this year" + trf("Tracked {0} {1} this year", valid.size, if (valid.size == 1) tr("night") else tr("nights")) else - "${valid.size} of ${state.expectedNights} nights tracked", + trf("{0} of {1} nights tracked", valid.size, state.expectedNights), score = if (enough) state.avgScore else null, scoreLabel = if (enough) state.avgScore?.let { qualityText(com.pulseloop.service.SleepScore.qualityLabel(it)) } else null, noData = !enough, @@ -557,7 +559,7 @@ private fun SleepHypnogram( 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)}" + + trf("Sleep stages from {0} to {1}", clockTime(startTs), clockTime(startTs + safeTotal * 60_000L)) + if (parts.isEmpty()) ": no stage data" else ": " + parts.joinToString(", ") } @@ -810,10 +812,10 @@ private fun SleepDurationHistogram( val summary = remember(bars, goalMin) { val tracked = bars.filter { it.present }.mapNotNull { it.durationMin } if (tracked.isEmpty()) tr("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)}" } ?: "") + else trf("Nightly sleep: latest {0}, ", SleepFormat.duration(tracked.last())) + + trf("range {0}–{1}, ", SleepFormat.duration(tracked.min()), SleepFormat.duration(tracked.max())) + + trf("{0} of {1} nights tracked", tracked.size, bars.size) + + (goalMin?.takeIf { it > 0 }?.let { trf(", goal {0}", SleepFormat.duration(it)) } ?: "") } Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { @@ -1057,7 +1059,7 @@ private fun SleepRecordsCard( eyebrow = tr("Records"), // One run only happens on a carousel page, which may be a nap rather than a night. title = if (runs.size == 1) tr("The ring recorded this as one record") - else "The ring recorded this night in ${runs.size} parts", + else trf("The ring recorded this night in {0} parts", runs.size), legend = false, ) { Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { @@ -1076,7 +1078,7 @@ private fun SleepRecordsCard( color = PulseColors.textPrimary, ) Text( - "Asleep ${SleepFormat.duration(run.asleepMinutes)}", + trf("Asleep {0}", SleepFormat.duration(run.asleepMinutes)), fontSize = 12.sp, color = PulseColors.textMuted, ) @@ -1109,7 +1111,7 @@ private fun SleepRecordsCard( } else 0 if (gapMinutes > 0) { Text( - "Awake ${SleepFormat.duration(gapMinutes)} between", + trf("Awake {0} between", SleepFormat.duration(gapMinutes)), fontSize = 12.sp, color = PulseColors.textMuted, modifier = Modifier.padding(start = 18.dp), @@ -1200,19 +1202,19 @@ private fun SleepRecordEditDialog( onClick = { pickingTime = "start" }, modifier = Modifier.weight(1f), ) { - Text("Start: ${SleepFormat.clockTime(currentStart)}") + Text(trf("Start: {0}", SleepFormat.clockTime(currentStart))) } OutlinedButton( onClick = { pickingTime = "end" }, modifier = Modifier.weight(1f), ) { - Text("End: ${SleepFormat.clockTime(currentEnd)}") + Text(trf("End: {0}", SleepFormat.clockTime(currentEnd))) } } if (pickedOutside) { Text( - "This record runs ${SleepFormat.clockTime(run.startAt)} – " + - "${SleepFormat.clockTime(run.endAt)}. You can only shorten it.", + trf("This record runs {0} – ", SleepFormat.clockTime(run.startAt)) + + trf("{0}. You can only shorten it.", SleepFormat.clockTime(run.endAt)), color = PulseColors.danger, fontSize = 12.sp, ) diff --git a/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt b/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt index 1f11d6dc..259e604c 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import androidx.compose.foundation.background @@ -174,7 +176,7 @@ fun LastNightCard( Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(12.dp)) { Text(durationText, fontSize = 26.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) score?.let { - Text("score $it", fontSize = 14.sp, color = PulseColors.textSecondary, modifier = Modifier.padding(bottom = 4.dp)) + Text(trf("score {0}", it), fontSize = 14.sp, color = PulseColors.textSecondary, modifier = Modifier.padding(bottom = 4.dp)) } } window?.let { Text(it, fontSize = 13.sp, color = PulseColors.textMuted) } 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 44433405..ed856011 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import androidx.compose.foundation.background @@ -591,9 +593,9 @@ private fun deriveHero(state: TodayViewModel.TodayState, sleep: SleepViewModel.S val hrStr = state.heartRate?.let { "$it bpm" } ?: "—" val night = sleep.lastNight val summary = if (night == null) { - "You're at %,d steps. Sync after waking to add recovery context.".format(steps) + tr("You're at %,d steps. Sync after waking to add recovery context.").format(steps) } else { - "You're at %,d steps, %dh %02dm of sleep, and your latest reading is %s.".format( + tr("You're at %,d steps, %dh %02dm of sleep, and your latest reading is %s.").format( steps, night.totalMinutes / 60, night.totalMinutes % 60, hrStr, ) } @@ -609,7 +611,7 @@ private fun deriveHero(state: TodayViewModel.TodayState, sleep: SleepViewModel.S summary = summary, chips = listOf( ToneChip( - if (series.size > 1) "Steps ${if (stepsDelta >= 0) "+" else ""}$stepsDelta%" else "Steps collected", + if (series.size > 1) trf("Steps {0}{1}%", if (stepsDelta >= 0) "+" else "", stepsDelta) else tr("Steps collected"), stepsTone, ), ToneChip(if (state.heartRate == null) tr("HR pending") else tr("HR collected"), hrTone), diff --git a/app/src/main/java/com/pulseloop/ui/screens/WhatChangedUi.kt b/app/src/main/java/com/pulseloop/ui/screens/WhatChangedUi.kt index 0ebd579b..394a7c69 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/WhatChangedUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/WhatChangedUi.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import androidx.compose.foundation.background @@ -83,7 +85,7 @@ fun WhatChangedScreen(onBack: () -> Unit) { } Text( tr("Each night is compared with your own previous four weeks once there are two weeks to compare with. ") + - "Findings carry the formula version that made them (now v${Algorithms.VERSION}). Patterns, not diagnoses.", + trf("Findings carry the formula version that made them (now v{0}). Patterns, not diagnoses.", Algorithms.VERSION), fontSize = 11.sp, color = PulseColors.textMuted, ) Spacer(Modifier.height(24.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 513f14fb..250e0e84 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,7 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import android.content.res.Configuration @@ -241,7 +243,7 @@ private fun EditWorkoutSheet( endedAt > System.currentTimeMillis() -> tr("End time can't be in the future.") endedAt - startedAt <= pauseMs -> if (session.totalPauseSeconds > 0) - "The window must be longer than the ${maxOf(1, (session.totalPauseSeconds / 60).toInt())} min of pauses in this workout." + trf("The window must be longer than the {0} min of pauses in this workout.", maxOf(1, (session.totalPauseSeconds / 60).toInt())) else tr("End must be after the start.") else -> null } 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 6640bd1c..f98c9be6 100644 --- a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt +++ b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.viewmodels +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import androidx.lifecycle.ViewModel @@ -1126,7 +1128,7 @@ class CoachViewModel( if (currentConversation.id == conversationId) currentConversation = touched } catch (e: Exception) { _state.update { it.copy( - messages = it.messages + ChatMessage("assistant", "Sorry, something went wrong: ${e.message}"), + messages = it.messages + ChatMessage("assistant", trf("Sorry, something went wrong: {0}", e.message)), isThinking = false, error = e.message, ) } } diff --git a/app/src/main/java/com/pulseloop/ui/viewmodels/VitalCardState.kt b/app/src/main/java/com/pulseloop/ui/viewmodels/VitalCardState.kt index ac14ce32..a7bb0ed0 100644 --- a/app/src/main/java/com/pulseloop/ui/viewmodels/VitalCardState.kt +++ b/app/src/main/java/com/pulseloop/ui/viewmodels/VitalCardState.kt @@ -1,5 +1,7 @@ package com.pulseloop.ui.viewmodels +import com.pulseloop.ui.i18n.trf + import com.pulseloop.ui.i18n.tr import com.pulseloop.service.BaselineStats @@ -89,7 +91,7 @@ data class TrendSummary( // Sub-unit deltas keep one decimal (truncated, matching iOS Int-cast); larger deltas round. val rounded = if (abs(delta) < 1 && delta != 0.0) (delta * 10).toInt() / 10.0 else roundAwayFromZero(delta) if (abs(rounded) < 0.5) { - return TrendSummary(TrendDirection.STABLE, "Stable $suffix", "→") + return TrendSummary(TrendDirection.STABLE, trf("Stable {0}", suffix), "→") } val unit = if (unitLabel.isEmpty()) "" else " $unitLabel" val sign = if (rounded > 0) "+" else "−" @@ -209,8 +211,8 @@ object VitalsCardFactory { val interp = latest?.let { VitalsThresholdEngine.interpret(it, MetricKind.HEART_RATE, profile) } val valueText = rangeLabel(samples, latest) - val resting = inputs.restingHr?.let { "Resting ${it.toInt()}" } ?: "Resting calibrating" - val peak = inputs.peakHr?.let { "Peak ${it.toInt()}" } ?: "Peak —" + val resting = inputs.restingHr?.let { trf("Resting {0}", it.toInt()) } ?: tr("Resting calibrating") + val peak = inputs.peakHr?.let { trf("Peak {0}", it.toInt()) } ?: tr("Peak —") val domain = clampedDomain(samples, 40.0..140.0, pad = 8.0, hardLower = 40.0, hardUpper = 220.0) return VitalCardState( metric = MetricKind.HEART_RATE, title = MetricKind.HEART_RATE.title, @@ -237,7 +239,7 @@ object VitalsCardFactory { val quality = quality(MetricKind.SPO2, samples.lastOrNull()?.timestampMs, inputs) val interp = latest?.let { VitalsThresholdEngine.interpret(it, MetricKind.SPO2, profile) } val lowest = samples.map { it.value }.filter { it > 0 }.minOrNull() - val subtitle = lowest?.let { "Lowest ${it.toInt()} · ${samples.size} readings" } + val subtitle = lowest?.let { trf("Lowest {0} · {1} readings", it.toInt(), samples.size) } return VitalCardState( metric = MetricKind.SPO2, title = MetricKind.SPO2.title, valueText = averageLabel(samples, latest), latestValue = latest, @@ -273,7 +275,7 @@ object VitalsCardFactory { ) } val subtitle = if (baseline != null && baseline.isEstablished) { - "Baseline ${baseline.mean.toInt()} ms" + trf("Baseline {0} ms", baseline.mean.toInt()) } else { tr("Building baseline") } diff --git a/app/src/main/java/com/pulseloop/widgets/WidgetConfigActivity.kt b/app/src/main/java/com/pulseloop/widgets/WidgetConfigActivity.kt index d9f61488..4c9b72cb 100644 --- a/app/src/main/java/com/pulseloop/widgets/WidgetConfigActivity.kt +++ b/app/src/main/java/com/pulseloop/widgets/WidgetConfigActivity.kt @@ -1,5 +1,7 @@ package com.pulseloop.widgets +import com.pulseloop.ui.i18n.tr + import android.appwidget.AppWidgetManager import android.content.Intent import android.os.Bundle @@ -116,30 +118,30 @@ private fun ConfigScreen( verticalArrangement = Arrangement.spacedBy(8.dp), ) { Text( - if (isDual) "Choose Metrics" else "Choose Metric", + if (isDual) tr("Choose Metrics") else tr("Choose Metric"), fontSize = 24.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, ) Text( - if (isDual) "Pick the left and right PulseLoop metrics." - else "Pick which PulseLoop metric this widget shows.", + if (isDual) tr("Pick the left and right PulseLoop metrics.") + else tr("Pick which PulseLoop metric this widget shows."), fontSize = 14.sp, color = PulseColors.textSecondary, ) Spacer(Modifier.height(8.dp)) if (isDual) { - MetricPicker("LEFT METRIC", left) { left = it } + MetricPicker(tr("LEFT METRIC"), left) { left = it } Spacer(Modifier.height(12.dp)) - MetricPicker("RIGHT METRIC", right) { right = it } + MetricPicker(tr("RIGHT METRIC"), right) { right = it } } else { MetricPicker(null, single) { single = it } } Spacer(Modifier.height(16.dp)) Button(onClick = { onDone(single, left, right) }, modifier = Modifier.fillMaxWidth()) { - Text("Add Widget") + Text(tr("Add Widget")) } } } diff --git a/app/src/main/java/com/pulseloop/widgets/WidgetMetric.kt b/app/src/main/java/com/pulseloop/widgets/WidgetMetric.kt index f082c95f..bb522c81 100644 --- a/app/src/main/java/com/pulseloop/widgets/WidgetMetric.kt +++ b/app/src/main/java/com/pulseloop/widgets/WidgetMetric.kt @@ -1,5 +1,7 @@ package com.pulseloop.widgets +import com.pulseloop.ui.i18n.tr + import androidx.compose.ui.graphics.Color import com.pulseloop.service.MetricKind import com.pulseloop.ui.components.ZonePalette @@ -51,8 +53,8 @@ enum class WidgetMetric(val key: String, val displayName: String) { /** Header eyebrow label, matching the in-app tile chrome. */ val headerLabel: String get() = when (this) { - ACTIVITY -> "Activity" - SLEEP -> "Sleep" + ACTIVITY -> tr("Activity") + SLEEP -> tr("Sleep") else -> metricKind?.title ?: key } diff --git a/app/src/main/java/com/pulseloop/widgets/WidgetTileRenderer.kt b/app/src/main/java/com/pulseloop/widgets/WidgetTileRenderer.kt index 0cdf4e49..69408662 100644 --- a/app/src/main/java/com/pulseloop/widgets/WidgetTileRenderer.kt +++ b/app/src/main/java/com/pulseloop/widgets/WidgetTileRenderer.kt @@ -1,5 +1,7 @@ package com.pulseloop.widgets +import com.pulseloop.ui.i18n.tr + import android.graphics.Bitmap import android.graphics.BlurMaskFilter import android.graphics.Canvas @@ -107,7 +109,7 @@ class WidgetTileRenderer(private val density: Float) { if (payload == null || rolledOver) { drawEmptyMessage( canvas, rect, - if (rolledOver) "No data yet today" else "Open PulseLoop to sync", + if (rolledOver) tr("No data yet today") else tr("Open PulseLoop to sync"), PulseColors.steps.toArgb(), ) } else { @@ -172,7 +174,7 @@ class WidgetTileRenderer(private val density: Float) { if (payload == null) { drawEmptyMessage( canvas, content, - if (snapshot == null) "Open PulseLoop to sync" else "No data", + if (snapshot == null) tr("Open PulseLoop to sync") else tr("No data"), accent, ) } else { @@ -265,7 +267,7 @@ class WidgetTileRenderer(private val density: Float) { if (values.isEmpty()) { drawEmptyMessage( canvas, rect, - if (rolledOver) "No data yet today" else "Open PulseLoop to sync", + if (rolledOver) tr("No data yet today") else tr("Open PulseLoop to sync"), PulseColors.steps.toArgb(), ) return @@ -323,14 +325,14 @@ class WidgetTileRenderer(private val density: Float) { val rowH = textHeight(textPaint(15f, 0)) + dp(5f) + textHeight(textPaint(32f, 0)) val totalH = rowH * 2 + dp(14f) val top = rect.top + ((rect.height() - totalH) / 2f).coerceAtLeast(0f) - metricBlock(rect.left, top, "Steps", payload.stepsText, null, PulseColors.steps.toArgb(), colW - dp(6f)) + metricBlock(rect.left, top, tr("Steps"), payload.stepsText, null, PulseColors.steps.toArgb(), colW - dp(6f)) metricBlock( - rect.left + colW, top, "Distance", payload.distanceText, + rect.left + colW, top, tr("Distance"), payload.distanceText, if (payload.distanceText != null) payload.distanceUnitLabel.lowercase() else null, PulseColors.distance.toArgb(), colW - dp(6f), ) metricBlock( - rect.left, top + rowH + dp(14f), "Calories", payload.caloriesText, + rect.left, top + rowH + dp(14f), tr("Calories"), payload.caloriesText, if (payload.caloriesText != null) "cal" else null, PulseColors.calories.toArgb(), colW - dp(6f), ) @@ -340,7 +342,7 @@ class WidgetTileRenderer(private val density: Float) { private fun drawSleepContent(canvas: Canvas, rect: RectF, payload: WidgetSleepPayload?, rolledOver: Boolean) { if (payload == null || rolledOver) { - drawEmptyMessage(canvas, rect, "No sleep recorded", PulseColors.sleep.toArgb()) + drawEmptyMessage(canvas, rect, tr("No sleep recorded"), PulseColors.sleep.toArgb()) return } var y = rect.top diff --git a/app/src/test/java/com/pulseloop/ui/i18n/PortugueseCatalogTest.kt b/app/src/test/java/com/pulseloop/ui/i18n/PortugueseCatalogTest.kt index 9595c0d4..8343c39e 100644 --- a/app/src/test/java/com/pulseloop/ui/i18n/PortugueseCatalogTest.kt +++ b/app/src/test/java/com/pulseloop/ui/i18n/PortugueseCatalogTest.kt @@ -42,6 +42,20 @@ class PortugueseCatalogTest { } } + @Test + fun `value placeholders survive translation`() { + val ph = Regex("\\{\\d+\\}") + catalog.forEach { (en, pt) -> + assertEquals("placeholders: $en", ph.findAll(en).map { it.value }.sorted().toList(), ph.findAll(pt).map { it.value }.sorted().toList()) + } + } + + @Test + fun `a string with values reads exactly as its template did in English`() { + assertEquals("7 of 10 dry days", trf("{0} of {1} dry days", 7, 10)) + assertEquals("HRV usually takes 2 nights to come back.", trf("HRV usually takes {0} night{1} to come back.", 2, "s")) + } + @Test fun `an untranslated string falls back to English`() { assertEquals("Not in any catalog 123", tr("Not in any catalog 123")) From 91911b9ab180ed251beb74acf01df202a0caf493 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 11:30:05 +0000 Subject: [PATCH 2/6] Keep model-facing text English; add postpartum and breastfeeding research The meal-analysis prompt, its schema descriptions and a developer error were re-wrapped by the second translation pass; they go to the model or the log, not the screen. docs/postpartum-breastfeeding-research.md: what ring-based apps can and can't offer breastfeeding mothers, with sources and a prioritised list. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- .../CoachNotificationDataTrigger.kt | 2 +- .../pulseloop/ui/screens/MealAnalysisSheet.kt | 10 +- docs/postpartum-breastfeeding-research.md | 269 ++++++++++++++++++ 3 files changed, 275 insertions(+), 6 deletions(-) create mode 100644 docs/postpartum-breastfeeding-research.md diff --git a/app/src/main/java/com/pulseloop/notifications/CoachNotificationDataTrigger.kt b/app/src/main/java/com/pulseloop/notifications/CoachNotificationDataTrigger.kt index 7c33ba6f..01d3166c 100644 --- a/app/src/main/java/com/pulseloop/notifications/CoachNotificationDataTrigger.kt +++ b/app/src/main/java/com/pulseloop/notifications/CoachNotificationDataTrigger.kt @@ -42,7 +42,7 @@ class CoachNotificationDataTrigger( private val slotRun: suspend () -> CoachNotificationOutcome = runDueSlot ?: { val c = requireNotNull(context) { - tr("CoachNotificationDataTrigger needs a Context when the production runner is used") + "CoachNotificationDataTrigger needs a Context when the production runner is used" } CoachNotificationSlotRunner.forContext(c).runDueSlot() } 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 473a5d9a..f9bea8d2 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt @@ -657,11 +657,11 @@ object MealAnalysisLogic { /** Verbatim system prompt (MealAnalysisSheet.swift:338-342). */ val systemPrompt: String = - tr("You are a nutrition estimator. Given a meal description and/or photo, " + + "You are a nutrition estimator. Given a meal description and/or photo, " + "identify the food and estimate total calories and macros for the portion shown or described. " + tr("Be realistic about portion sizes; state your assumptions (portion sizes, preparation) briefly. " + "Use confidence \"high\" only for clearly identifiable, standard portions. " + - "Return only JSON matching the schema.")) + "Return only JSON matching the schema.") /** * The verbatim strict meal_estimate json_schema (MealAnalysisSheet.swift:344-362), built @@ -671,12 +671,12 @@ object MealAnalysisLogic { fun described(value: String) = JsonObject(mapOf("type" to JsonPrimitive("string"), "description" to JsonPrimitive(value))) fun number() = JsonObject(mapOf("type" to JsonPrimitive("number"))) val props = JsonObject(mapOf( - "name" to described(tr("Short display name for the meal")), + "name" to described("Short display name for the meal"), "calories" to number(), "protein_g" to number(), "carbs_g" to number(), "fat_g" to number(), - "assumptions" to described(tr("Portion/preparation assumptions, one short sentence, or empty string")), + "assumptions" to described("Portion/preparation assumptions, one short sentence, or empty string"), "confidence" to JsonObject(mapOf( "type" to JsonPrimitive("string"), "enum" to JsonArray(listOf(JsonPrimitive("low"), JsonPrimitive("medium"), JsonPrimitive("high"))), @@ -746,7 +746,7 @@ object MealEstimator { } // iOS :392 — the description, or the photo-only prompt. - val prompt = description.trim().ifEmpty { tr("Estimate the nutrition of the meal in the photo.") } + val prompt = description.trim().ifEmpty { "Estimate the nutrition of the meal in the photo." } val input = JsonArray(listOf( OpenAIRequestBuilder.message("system", MealAnalysisLogic.systemPrompt), OpenAIRequestBuilder.message("user", prompt, images), diff --git a/docs/postpartum-breastfeeding-research.md b/docs/postpartum-breastfeeding-research.md new file mode 100644 index 00000000..66def1b6 --- /dev/null +++ b/docs/postpartum-breastfeeding-research.md @@ -0,0 +1,269 @@ +# Postpartum & breastfeeding: what a ring app can (and can't) offer + +Research note, 2026-10-22. Question: are there health metrics or tracking features specific to women +with a newborn who are breastfeeding, and which could PulseLoop realistically offer with what it +already has (sleep stages, HR, HRV, SpO2, skin temperature on some rings, steps, workouts, nutrition, +drinks with standard drinks, medications, cycle tracking, journal tags, AI coach, Health Connect)? + +**Short answer:** yes, but the ring's own signals are mostly *context*, not diagnostics. The +evidence supports showing postpartum recovery trends (RHR/HRV returning toward baseline, sleep +fragmentation improving) against the user's *own* pre-pregnancy baseline, and supports a set of +well-established, guideline-backed logging aids (alcohol-to-feed timing, calorie/fluid targets, +medication-in-lactation lookups, EPDS screen, warning signs). Nothing in the literature supports a +ring detecting mastitis, return of ovulation during breastfeeding, milk supply, or postpartum +depression on its own, and the app must not claim it. + +Confidence labels used below: **Strong** = official guideline or multiple consistent studies; +**Moderate** = a few cohort/observational studies, consistent direction; **Weak** = single small +studies, vendor material, or extrapolation from non-postpartum populations. + +--- + +## 1. What existing apps and wearables do + +| Product | Postpartum / breastfeeding features (concrete) | Notes | +| --- | --- | --- | +| **Oura** | Pregnancy Insights (Gen3+): gestational-age tracking, weekly education on how sleep/HR change, pregnancy symptom tags. Postpartum is served by generic Sleep/Readiness, tags, and Explore meditations/breathwork; the company's own postpartum stories are about going to bed earlier to offset night feeds and using a low Readiness score as a "take it easy" cue. | No dedicated breastfeeding/feeding log, no published postpartum mode or temperature handling after birth found. | +| **WHOOP** | Journal toggles and insights for trying to conceive, pregnancy, **postpartum**, perimenopause, postmenopause; WHOOP's own perinatal study (18 women) showed HRV rising / RHR falling from ~7 weeks before birth into postpartum. | "Coaching" specific to postpartum was not confirmed; it is journal-plus-insights. | +| **Garmin** | Pregnancy tracking (built on its cycle tracking); integration with Natural Cycles, where overnight wrist skin temperature syncs each morning. | Postpartum specifics not documented in sources found. Garmin itself states its watches are wellness devices, not medical devices. | +| **Natural Cycles** | **NC° Postpartum** mode (for users who log a pregnancy ending after 28 weeks): check-ins on mental and physical health, postpartum bleeding, sleep, pain, skin/hair changes; education on when fertility returns; shareable with clinicians/partners. While breastfeeding the birth-control mode shows only "Red Days" until the first post-birth ovulation is detected. | The most conservative and clinically framed of the group: it does not try to predict fertility under lactational suppression. | +| **Huckleberry** | One-touch logging of feeds, **breastfeeding timer per side**, pumping, diapers, sleep, growth, medicine; caregiver sync; paid "SweetSpot" nap prediction. | Baby-centric. | +| **Glow Baby** | Breastfeeding, diaper, sleep trackers; **Pump Log** (sessions, supply, storage); AI insights; export to the baby's clinician. | Baby-centric. | +| **Ovia Parenting** | Feeds (breast/bottle), diapers, sleep, milestones, family photo sharing. | Baby-centric. | +| **Elvie / Willow pump apps** | (Not researched in depth this pass.) Smart pumps log session time and expressed volume per breast automatically. | Volume data would only reach PulseLoop through manual entry or a future integration. | + +**Gap PulseLoop could fill:** baby apps track the *baby* and ignore the mother's physiology; +wearable apps track the *mother's* physiology and ignore feeds. Nobody in this list joins +"feed at 02:40" with "HRV, sleep fragmentation and wake bouts tonight", or the drinks log with +"next safe feed". PulseLoop already has both halves. + +--- + +## 2. What changes physiologically, and what a ring can measure + +### Resting heart rate and HRV — **Moderate** +- **Sarhaddi et al., 2022, JMIR mHealth uHealth** (58 women, Samsung Gear Sport PPG, pregnancy + through 3 months postpartum): HR rose and HRV fell through pregnancy; in the third trimester the + trend began to reverse; values **returned to normal after delivery** within the 12-week window. +- **Scripps / PowerMom, 2025, eBioMedicine** (Quer, Àjàyí et al.; >5,600 enrolled, 108 with + continuous data from 3 months pre-pregnancy to 6 months postpartum; Apple Watch, Fitbit, Garmin): + RHR peaked ~9.4 bpm above baseline before delivery, then **dropped below pre-pregnancy levels, + reaching a minimum ~7 weeks postpartum**, and took roughly **6 months** to settle back to baseline. +- **WHOOP perinatal cohort, 2022, BMC Pregnancy and Childbirth** ("Monitoring one heart to help + two", 18 active women): from ~49 days before birth, daily HRV rose and RHR fell regardless of + activity level, continuing into postpartum (modelled to 8 weeks). +- **Byfield et al., 2025, Biological Research for Nursing** (scoping review of wearable HRV in + perinatal people): HRV moves back toward pre-pregnancy levels postpartum, but individual recovery + patterns vary and measurement methods are not standardised. + +**Implication:** a "postpartum recovery" view comparing current RHR/HRV with the user's own +pre-pregnancy baseline is well grounded — *if* the app has that baseline (most PulseLoop users who +wore a ring before pregnancy will). Population norms are not; individual variation is large. +Note the RHR undershoot: a postpartum RHR *below* baseline at 6–8 weeks is expected, not a problem. + +### HRV and postpartum depression — **Weak (research only)** +- **Shinba et al., 2024** (45 EPDS-positive women, wearable ECG, 1–4 weeks postpartum): women with + PPD showed poor HRV regulation under task load and high resting LF/HF, distinguishing them from + adjustment disorder. Research-grade ECG protocol, not passive consumer PPG. +- **Eriksson et al., 2024**: lower HRV at gestational week 38 associated with depressive/anxious + symptoms at 6 weeks postpartum; HRV alone was **not predictive**, only in a combined model. +- A narrative review (2025, PMC11773373) and the scoping review both call the evidence inconsistent. + +**Implication:** never present HRV as a depression signal. Use the validated questionnaire (EPDS) +for screening; HRV can at most be shown beside it as context. + +### Sleep — **Strong for the pattern, mixed for feeding effects** +- **Montgomery-Downs et al., 2010, AJOG** (actigraphy, weeks 2–16): nocturnal sleep ~**7.2 h** and + stable across the 16 weeks, but highly fragmented: efficiency rose from ~**80% at week 2 to ~90% + at week 16** as fragmentation fell (21.7 → 12.8). "Total sleep is not the problem; continuity is." +- **Srimoragot et al., 2023, J Sleep Res** (systematic review/meta-analysis): breastfeeding mothers + had somewhat longer night-time sleep, and exclusively breastfeeding mothers had **more** actigraphic + wake after sleep onset. +- **Doan et al., 2014, J Clin Sleep Med** (first-time mothers, 1 month): exclusive breastfeeding + ≈ 30 min more nocturnal sleep, no WASO difference. Other studies (incl. a mixed-methods study of + women at risk of PPD, PMC9665349) found **no difference** by feeding type. + +**Implication:** the metric that matters postpartum is **fragmentation / number of wake bouts / +longest uninterrupted stretch**, not total sleep or a sleep score built for adults without infants. +A standard score will read "poor" for months and demoralise. Also: ring sleep staging in highly +fragmented sleep is less reliable than in consolidated sleep, so stage breakdowns should be +de-emphasised. Daytime naps ("sleep when the baby sleeps") should count. + +### Skin temperature — **Weak for postpartum use** +- Wearable skin temperature tracks the menstrual cycle in non-postpartum women (Zurich wrist study: + sustained 3-day shift in 82% of cycles; Gombert-Labedens et al., 2024). The wrist-vs-BBT validation + study (PMC8238491) **excluded actively breastfeeding women**. +- In older BBT work in breastfeeding women (PubMed 10899480 and related), the first bleeding during + lactation was often **anovulatory** (none of 8 women who bled before weaning had an adequate thermal + shift), and in the first cycles after lactational amenorrhoea BBT-defined ovulation lagged the LH + peak by ~4 days, converging over three cycles. +- No peer-reviewed study was found that validates ring/wrist temperature for detecting the *first* + postpartum ovulation while breastfeeding. Night feeds, room temperature, bedding and finger + perfusion all disturb finger temperature. +- Fever: CDC's urgent warning sign is **≥ 38.0 °C (100.4 °F)**. A ring measures *skin* temperature + deviation, not core temperature, so it cannot confirm fever; at most it can prompt "your + temperature deviation is unusually high — if you feel unwell, take your temperature". + +**Implication:** keep cycle predictions **off** while breastfeeding (as Natural Cycles does) and +show temperature only as raw trend. A large deviation can trigger a "check with a thermometer" +nudge, never "possible mastitis". + +### SpO2 — **no postpartum-specific evidence found** +Nothing found suggesting SpO2 changes meaningfully during lactation. Shortness of breath and chest +pain are warning signs (CDC), but those are symptoms to act on, not ring readings to wait for. + +### Activity — **Strong (guideline)** +ACOG Committee Opinion 804 (2020): resuming or starting exercise postpartum is beneficial and may +help prevent postpartum depressive symptoms; avoid routine restriction; individualise. Practical +tip in the same guidance: breastfeed or express before exercise to avoid engorgement discomfort. +Adult target (WHO): 150–300 min/week moderate activity. Timing of return (vaginal vs caesarean, +pelvic floor) is a clinician decision; the app should not set a date. + +--- + +## 3. Breastfeeding-specific logging that matters clinically + +| Item | Guidance | Strength | +| --- | --- | --- | +| **Feed timing / side / duration** | Standard in every baby app; LAM requires feeds "at least 6–10 times a day including night feeds". Mainly useful to the mother for alternation and to correlate with her night wakings. | Practice standard | +| **Pumping volume** | Pump apps log per-session, per-breast volume. Useful for working mothers and supply worries; not something the ring can infer. | Practice standard | +| **Diapers as intake proxy** | Used clinically for the *baby's* intake in the first weeks. Out of PulseLoop's scope (baby app territory) — mention, don't build. | — | +| **Extra energy** | **Dietary Guidelines for Americans 2020–2025**: ~**+330 kcal/day** in months 0–6 (500 for milk minus 170 from weight loss) and **+400 kcal/day** in months 7–12, for a healthy pre-pregnancy weight; individualise. Lactation textbooks quote 400–500 kcal. Very low intakes (below ~1,500–1,800 kcal) are commonly cited as a supply risk. | Strong | +| **Fluids** | No fixed extra-water rule; the US IOM reports median fluid intake of breastfeeding women ~**3.1 L/day**. "Drink to thirst, keep water by the feeding chair" is the consistent advice. | Moderate | +| **Alcohol** | **CDC**: not drinking is safest; up to 1 standard drink/day (14 g alcohol) is not known to harm the infant. Wait **at least 2 h per drink** before nursing; alcohol is detectable in milk ~2–3 h per drink (2 drinks ≈ 4–5 h, 3 drinks ≈ 6–8 h). Pumping and dumping does **not** speed clearance. Caring for an infant while intoxicated is unsafe. | Strong | +| **Caffeine** | Commonly quoted limit ~200–300 mg/day; could not confirm the CDC's own page in this pass, so quote it as a range from secondary sources. | Moderate | +| **Medication safety** | **LactMed** (NIH/NLM, free, peer-reviewed, per-drug levels in milk/infant and alternatives) and **e-lactancia.org** (APILAM, Spanish/English/Portuguese, tiers: compatible → limited compatibility → unsafe, with alternatives; ratings revised as evidence changes, e.g. lisinopril re-rated Dec 2025). Both say they don't replace a clinician. | Strong (as references) | +| **Supplements** | DHA ~200 mg/day if eating fish less than twice a week; iodine supplementation recommended in several guidelines (German network: 100 µg/day + iodised salt; US RDA for lactation is 290 µg — background knowledge, not re-verified this pass); infant vitamin D drops 400 IU (10 µg) for breastfed babies. Brazil iodises table salt, which changes the calculus. Many commercial lactation supplements don't meet iodine/DHA targets (Ernährungs Umschau 2023). | Moderate | +| **Return of menstruation / contraception (LAM)** | LAM is ≥98% effective in the first 6 months **only while all three hold**: baby < 6 months, no return of menses (bleeding after day 56), fully or nearly fully breastfeeding (no long gaps, no supplements). If any one lapses, another method is needed. No STI protection. | Strong | +| **Postpartum depression screen** | **EPDS**, 10 items, 0–30. Validation cut-offs range 9–13 (higher = more specific). Validated in Brazil (Pelotas cohort, Cad Saúde Pública 2007). **Item 10 (self-harm) must be acted on regardless of total score.** | Strong | +| **Pelvic floor** | Pelvic floor muscle training is standard postpartum advice; specifics weren't confirmed in ACOG 804's summaries found. A reminder/log is low-risk. | Moderate (not re-verified) | +| **Sleep debt** | Fragmentation, not duration, is the postpartum signature (Montgomery-Downs 2010). | Moderate | + +--- + +## 4. Safety and wording + +### What PulseLoop must not claim +- That the ring **detects** mastitis, infection, fever, postpartum depression, preeclampsia, + haemorrhage, milk supply, or fertility/ovulation return during breastfeeding. +- That an alcohol timer makes milk "safe" or "alcohol-free" — it is an estimate based on CDC's + per-drink rule; metabolism varies. Say "CDC suggests waiting at least 2 h per drink; estimate + ready around 23:40". +- That LAM status is contraception advice. Show the three criteria and "if any changes, talk to + your clinician about another method". +- That a medication is safe — link to LactMed/e-lactancia and the clinician; don't render our own + verdict. +- That a calorie deficit is fine to chase; avoid weight-loss framing in early postpartum. +- That HRV/Readiness scores mean the same as before pregnancy; label postpartum baselines. + +### Red flags that should prompt care (show plainly, not buried) +From **CDC Hear Her urgent maternal warning signs** (apply up to a year after birth): +headache that won't go away or worsens; dizziness or fainting; vision changes; fever ≥ 38.0 °C +(100.4 °F); extreme swelling of hands or face; thoughts of harming yourself or the baby; trouble +breathing; chest pain or fast-beating heart; severe nausea/vomiting; severe belly pain; vaginal +bleeding or discharge after pregnancy; severe swelling, redness or pain in a leg or arm (to 6 weeks); +overwhelming tiredness. + +Additional specifics: +- **Postpartum preeclampsia** can appear up to 6 weeks after delivery (typically days 7–10): any + BP ≥ 160/110 is an emergency; ≥ 140/90 with headache, vision change, or upper-abdominal pain needs + urgent assessment. Relevant because PulseLoop has a BP vital on some rings — but **ring BP is not + validated**, so a high ring BP must say "confirm with a cuff", and a normal one must never reassure. +- **Mastitis** (NHS; ABM Protocol #36, 2022, which reframes it as a spectrum from engorgement to + abscess): hot, painful, red/swollen area or wedge-shaped lump, burning pain, flu-like symptoms with + fever/chills. See a clinician if no improvement in 12–24 h of home care or 48 h after antibiotics, + or immediately if systemically unwell. +- **EPDS** high score → contact a health professional; **item 10 endorsed → show crisis resources + immediately**, whatever the total. + +### Brazil-specific resources +- **CVV — 188**: free, 24 h, anonymous, nationwide (also chat/e-mail with narrower hours). +- **SAMU — 192** for emergencies (background knowledge). +- **Rede Brasileira de Bancos de Leite Humano (rBLH-BR, Fiocruz/Ministério da Saúde)**: ~220+ + milk banks (counts vary by date), help with breastfeeding difficulties and milk donation; home + collection in some places; Disque Saúde **136** to find the nearest bank. In 2024, 193k donors + supplied ~245.7k litres to >219k babies. +- **SUS**: postpartum visit at the UBS (puerpério) and Caderneta da Gestante / da Criança + (background knowledge, not re-verified). +- **Guia Alimentar para Crianças Brasileiras Menores de 2 Anos** (Ministério da Saúde, 2019): + exclusive breastfeeding to 6 months, continued to 2 years or more. Its specific alcohol wording + for the mother was not found in this pass; use CDC's rule and note "Ministério da Saúde advises + avoiding alcohol" only after verifying. +- **e-lactancia.org** has a Portuguese interface and is widely used by Brazilian lactation + consultants. + +--- + +## 5. Recommendations for PulseLoop (prioritised) + +All of these assume an opt-in **"Postpartum / breastfeeding" life-stage mode** (date of birth of the +baby, feeding type: exclusive / mixed / not breastfeeding). The mode's first job is to *change +defaults* — and several items below are mostly defaults. + +| # | Feature | What it shows | Data it needs | Evidence | +| --- | --- | --- | --- | --- | +| 1 | **Postpartum mode that changes defaults** | Pauses cycle/fertility predictions and period-late alerts while breastfeeding (Natural Cycles' approach); relabels baselines "postpartum"; suppresses "your RHR is unusually low" and readiness penalties built for non-postpartum adults; counts naps toward daily sleep. | Baby DOB, feeding type; existing cycle and readiness code. | Strong (avoids known false signals) | +| 2 | **Alcohol → next-feed estimate** | After a drink is logged, "CDC suggests waiting ≥ 2 h per standard drink; estimated clear for feeding around HH:MM", with "pumping and dumping doesn't speed this up". Daily guidance ≤ 1 drink. | Existing drinks tracker (already computes standard drinks) + mode flag. | Strong | +| 3 | **Warning-signs card + EPDS check-in** | Always-reachable CDC warning-sign list; optional EPDS at ~2 weeks, 6 weeks, 3 and 6 months; score shown with "talk to a professional" above cut-off; **item 10 → CVV 188 / SAMU 192 immediately**. Answers stay local, never in diagnostics exports. | Questionnaire storage; pt-BR translation (EPDS pt-BR validated). | Strong | +| 4 | **Night-feed / sleep fragmentation view** | Per night: wake bouts, longest uninterrupted sleep, total sleep including naps, with optional feed markers (one-tap "feed" with side, or imported). Trend vs week 2 (Montgomery-Downs: efficiency ~80 → 90% by week 16) framed as "this is normal and improves". | Existing sleep sessions/blocks + new feed log entries (journal tag or dedicated table). | Moderate–Strong | +| 5 | **Recovery-to-baseline trend** | RHR and HRV vs the user's own pre-pregnancy baseline, with expected shape annotated (RHR dips below baseline around week 7, ~6 months to settle; HRV rises back). No score, no colour-coded "bad". | Existing measurements; baseline from data ≥ 10 months before baby DOB if present. | Moderate | +| 6 | **Lactation-aware nutrition & fluid targets** | Calorie target +330 kcal (0–6 mo) / +400 (7–12 mo) for exclusive breastfeeding, scaled down for mixed feeding; floor warning if logged intake is persistently very low; fluid nudge (~3 L/day median, "drink to thirst"); DHA/iodine/infant vit D reminders as education. No weight-loss goal in the first months by default. | Existing nutrition/calorie log + mode. | Strong (calories), Moderate (fluids/supplements) | +| 7 | **Medication log: lactation lookup** | On each logged medication, a "Check in LactMed / e-lactancia" link (deep link by drug name); no in-app verdict. | Existing medications log. | Strong (as reference) | +| 8 | **LAM status helper** | Shows the three criteria, days until baby is 6 months, and flips to "LAM no longer applies" when a period is logged or feeding type changes to mixed. Explicitly informational. | Baby DOB, cycle log (bleed after day 56), feeding type. | Strong | +| 9 | **Temperature-deviation nudge** | If nightly skin-temp deviation is unusually high, "If you feel unwell or have breast pain, take your temperature; ≥ 38 °C after birth is a reason to call your clinician". Never "possible mastitis". | Existing skin temp (rings that have it). | Weak (signal), Strong (the fever threshold) | +| 10 | **Coach + Brazil resources** | Coach prompt gets the life-stage context (postpartum week, feeding type) and the do-not-claim rules above; resources screen with CVV 188, SAMU 192, Disque Saúde 136 / rBLH, e-lactancia. | Existing coach; static content via `tr()`. | — | + +**Deliberately not recommended:** detecting first postpartum ovulation from ring temperature (no +validation in breastfeeding women); inferring milk supply or feed events from HR/motion; HRV-based +depression risk; a full baby tracker (diapers, growth, milestones) — that is Huckleberry/Glow +territory, and Health Connect has no baby data types to import it from. + +**Privacy note:** postpartum mood answers, EPDS scores and feed logs are sensitive. Per the +existing diagnostics rule in `AGENTS.md`, none of them should appear in the diagnostics export. +Health Connect has no record type for EPDS or feeds, so nothing new would be exported there. + +--- + +## Sources + +- [Sarhaddi et al. 2022 — Trends in HR and HRV during pregnancy and the 3-month postpartum period (JMIR mHealth uHealth)](https://mhealth.jmir.org/2022/6/e33458/) · [DOAJ record](https://doaj.org/article/f6ff721b9ac14fba97ef6ecaa7f697b2) +- [Association between wearable sensor signals and expected hormonal changes in pregnancy (eBioMedicine 2025)](https://www.thelancet.com/journals/ebiom/article/PIIS2352-3964(25)00332-9/fulltext) · [Scripps press release](https://www.scripps.edu/news-and-events/press-room/2025/20250911-quer-wearables.html) +- [Monitoring one heart to help two: HRV and RHR with wearables across the perinatal period (BMC Pregnancy Childbirth 2022)](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC9710029/) +- [Byfield et al. 2025 — Scoping review of wearable HRV in pregnant and postpartum people](https://journals.sagepub.com/doi/10.1177/10998004251325212) +- [Shinba et al. 2024 — HRV as a point-of-care tool for screening postpartum depression](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC10934039/) +- [Eriksson et al. 2024 — Pregnancy HRV as predictor of postpartum depression and anxiety](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC11094065/) +- [Depressive symptoms and HRV in perinatal women: narrative review](https://pmc.ncbi.nlm.nih.gov/articles/PMC11773373) +- [Montgomery-Downs et al. 2010 — Normative longitudinal maternal sleep, first 4 postpartum months (AJOG)](https://pubmed.ncbi.nlm.nih.gov/20719289/) +- [Srimoragot et al. 2023 — Infant feeding type and maternal sleep: systematic review and meta-analysis (J Sleep Res)](https://onlinelibrary.wiley.com/doi/full/10.1111/jsr.13625) +- [Doan et al. 2014 — Nighttime breastfeeding and nocturnal sleep at one month (JCSM)](https://jcsm.aasm.org/doi/full/10.5664/jcsm.3538) +- [Mixed-methods study of perinatal sleep and breastfeeding in women at risk for PPD](https://pmc.ncbi.nlm.nih.gov/articles/PMC9665349/) +- [Using complete breastfeeding and lactational amenorrhoea as birth spacing methods (PubMed)](https://pubmed.ncbi.nlm.nih.gov/10899480/) +- [Wrist wearables capture menstrual-cycle temperature changes](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6265623/) +- [Accuracy of wrist skin temperature vs BBT for ovulation (excludes breastfeeding women)](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC8238491/) +- [Gombert-Labedens et al. 2024 — Wearable skin temperature and the menstrual cycle](https://pmc.ncbi.nlm.nih.gov/articles/PMC11294004/) +- [Contraceptive efficacy of lactational amenorrhoea (Lancet 1992, PubMed)](https://pubmed.ncbi.nlm.nih.gov/1346183/) · [IRH LAM FAQs](https://www.irh.org/wp-content/uploads/2013/04/LAM_FAQs.pdf) +- [CDC — Alcohol and breastfeeding](https://www.cdc.gov/breastfeeding-special-circumstances/hcp/vaccine-medication-drugs/alcohol.html) +- [CDC Hear Her — Urgent maternal warning signs](https://www.cdc.gov/hearher/maternal-warning-signs/index.html) +- [health.gov — Nutrition during breastfeeding (DGA 2020–2025 energy needs)](https://health.gov/news/202108/nutrition-during-breastfeeding-how-health-professionals-can-support-healthy-moms-and-babies) +- [KellyMom — Do breastfeeding mothers need extra calories / fluids](https://kellymom.com/nutrition/mothers-diet/mom-calories-fluids/) +- [Ernährungs Umschau 2023 — Supplements during lactation](https://www.ernaehrungs-umschau.de/english-articles/25-10-2023-supplements-during-lactation) +- [LactMed introduction (PubMed)](https://pubmed.ncbi.nlm.nih.gov/17210549/) +- [e-lactancia — drug compatibility explainer (LactApp)](https://blog.lactapp.es/en/drug-compatibility-and-breastfeeding/) · [e-lactancia example record](https://e-lactancia.org/breastfeeding/apasmo/tradename/) +- [ABM Protocol #36 commentary (Int Breastfeed J 2023)](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC10481477/) · [LactApp summary of ABM #36](https://blog.lactapp.es/en/the-abm-protocol-on-mastitis/) +- [NHS — Mastitis](https://www.nhs.uk/conditions/mastitis/) +- [ACOG District II — Postpartum preeclampsia in the ED checklist](https://www.scdhhs.gov/sites/default/files/ACOG-District-II-Checklist-Postpartum-Preeclampsia-in-the-ED.pdf) · [JUCM — Postpartum presentations: headache](https://www.jucm.com/postpartum-presentations-when-risk-arises-after-delivery-headache/) +- [ACOG Committee Opinion 804 summary (OPQIC)](https://opqic.org/acog-committee-opinion-no-804-physical-activity-and-exercise-during-pregnancy-and-the-postpartum-period/) +- [EPDS validation in a Brazilian general population (PMC4203969)](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4203969/) · [EPDS validation, Pelotas postpartum cohort (Cad Saúde Pública 2007)](https://scielosp.org/pdf/csp/2007.v23n11/2577-2588/en) · [EPDS scoring and item 10 guidance](https://help.blueprint.ai/en/articles/3945631-edinburgh-postnatal-depression-scale-epds) +- [Oura — supporting members during pregnancy and beyond](https://ouraring.com/blog/oura-supports-members-during-pregnancy-and-beyond/) · [TechRadar — Oura Pregnancy Insights](https://www.techradar.com/health-fitness/fitness-trackers/ouras-new-pregnancy-insights-feature-is-a-step-in-the-right-direction-for-womens-health-monitoring) +- [WHOOP — reproductive health through all life stages](https://www.whoop.com/de/en/thelocker/whoop-features-support-reproductive-health-through-all-life-stages) +- [Natural Cycles — How NC° Postpartum works](https://help.naturalcycles.com/hc/en-us/articles/18589315952285-How-NC-Postpartum-works) · [Using the app while breastfeeding](https://help.naturalcycles.com/hc/en-us/articles/360003291094-How-to-use-the-app-while-breastfeeding) +- [Garmin — Natural Cycles integration](https://www.garmin.com/en-NZ/blog/natural-cycles-integration-unlocks-non-hormonal-birth-control-app-for-users-with-select-garmin-smartwatches/) · [MobiHealthNews — Garmin adds pregnancy tracking](https://www.mobihealthnews.com/news/garmin-adds-pregnancy-tracking-capabilities-smartwatches) +- [Huckleberry (App Store)](https://apps.apple.com/us/app/huckleberry-baby-tracker/id1169136078) · [Glow Baby (App Store)](https://apps.apple.com/us/app/-/id1077177456) · [Ovia Parenting (App Store)](https://apps.apple.com/app/id1106614359) +- [RingConn — postpartum sleep and recovery trends (finger temperature caveats)](https://ringconn.com/blogs/guides/postpartum-recovery) +- [CONASS — CVV 188 free nationwide](https://www.conass.org.br/?p=14185) · [CVV quarterly report Q4 2025](https://cvv.org.br/wp-content/uploads/2026/02/RelatorioCVV_4Tri_2025.pdf) +- [Ministério da Saúde campaign on milk donation (Itatiaia)](https://www.itatiaia.com.br/brasil/leite-materno-ministerio-da-saude-lanca-campanha-nacional-e-incentiva-a-doacao/) · [SBP — importance of human milk donation](https://www.sbp.com.br/importancia-da-doacao-de-leite-humano-e-ressaltada-em-novo-documento-da-sbp/) +- [Guia Alimentar para Crianças Brasileiras Menores de 2 Anos (SES-MG PDF)](https://www.saude.mg.gov.br/wp-content/uploads/2018/03/23-03-guia_alimentar_2anos-85b.pdf) + +Items marked "background knowledge" or "not re-verified" (US iodine RDA 290 µg, SAMU 192, SUS +puerpério visit, Ministério da Saúde's alcohol wording, pelvic-floor specifics) should be checked +against the primary source before they reach UI copy. From e07302e6a8dcaf5412cd880b12b272f223875e18 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 11:32:20 +0000 Subject: [PATCH 3/6] Portuguese: whole sentences as keys, catalog complete (1,716 strings) Re-ran the conversion so a sentence split across '+' becomes one key with its values as placeholders, instead of fragments translated separately. Threshold zone labels stay English where they are compared; a const that became translatable is a getter; the lint annotation is a constant again. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- app/src/main/assets/i18n/pt-BR.json | 737 +++++++++++++++++- .../CoachNotificationDataTrigger.kt | 2 - .../pulseloop/notifications/GuidanceWorker.kt | 5 +- .../java/com/pulseloop/service/Readiness.kt | 2 +- .../com/pulseloop/ui/components/Charts.kt | 3 +- .../ui/components/MetricThresholds.kt | 86 +- .../pulseloop/ui/components/ZoneLineChart.kt | 3 +- .../pulseloop/ui/screens/AccuracyCheckUi.kt | 12 +- .../pulseloop/ui/screens/AccuracyReportUi.kt | 9 +- .../java/com/pulseloop/ui/screens/BodyUi.kt | 3 +- .../pulseloop/ui/screens/MealAnalysisSheet.kt | 4 +- .../com/pulseloop/ui/screens/MyHealthUi.kt | 6 +- .../java/com/pulseloop/ui/screens/Screens.kt | 3 +- .../ui/screens/SettingsSubScreens.kt | 3 +- .../com/pulseloop/ui/screens/SleepScreen.kt | 10 +- 15 files changed, 778 insertions(+), 110 deletions(-) diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index 9584b9f8..785fcd79 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -1,34 +1,90 @@ { "\n\nThe day's total drops by that much. This can't be undone, and the record stays deleted the next time this day syncs.": "\n\nO total do dia diminui nesse valor. Isso não pode ser desfeito, e o registro continua excluído na próxima vez que este dia sincronizar.", + " ({0} matched readings).": " ({0} leituras pareadas).", + " ({0} min vs last week)": " ({0} min vs. semana passada)", + " ({0} vs last week)": " ({0} vs. semana passada)", " Delete": " Excluir", + " Drinks: {0} of {1}, {2} dry day{3}.": " Bebidas: {0} de {1}, {2} dia{3} sem álcool.", + " Expected values are lower at altitude.": " Valores esperados são mais baixos em altitude.", " The reading stays deleted the next time this day syncs.": " A leitura continua excluída na próxima vez que este dia sincronizar.", + " instead of {0}": " em vez de {0}", + " · %.2f %s": " · %.2f %s", " · Health Connect": " · Health Connect", + " · average {0} bpm": " · média de {0} bpm", " · from food log": " · do diário alimentar", " · paused": " · pausado", " · tap for this week's plan": " · toque para ver o plano da semana", + " · {0} nights": " · {0} noites", + " · {0} readings": " · {0} leituras", + " · {0}% taken this week": " · {0}% tomados nesta semana", "\"Nearby devices\"": "\"Dispositivos próximos\"", + "\"{0}\" will be removed from this day's log.": "\"{0}\" será removido do registro deste dia.", + "%,d of %,d steps": "%,d de %,d passos", + "%,d steps": "%,d passos", + "%,d steps a day": "%,d passos por dia", + "%,d steps yesterday vs your usual %,d": "%,d passos ontem vs. seus habituais %,d", + "+%.1f °C from your usual": "+%.1f °C acima do seu habitual", + "+%.1f °C last night against your usual. Can come with illness, a late workout, alcohol or the menstrual cycle.": "+%.1f °C na noite passada em relação ao seu habitual. Pode acompanhar doença, treino tarde, álcool ou o ciclo menstrual.", + ", about {0} kcal. Can we look at alternatives?": ", cerca de {0} kcal. Podemos ver alternativas?", + ", goal {0}": ", meta {0}", + ", or a {0} if you need something ({1} kcal).": ", ou um(a) {0} se precisar de algo ({1} kcal).", + ". Your usual day: {0}": ". Seu dia habitual: {0}", + "1 bowl": "1 tigela", + "1 cup": "1 xícara", + "1 ladle (100 g)": "1 concha (100 g)", + "1 medium": "1 médio", + "1 or 2": "1 ou 2", + "1 plate": "1 prato", + "1 plate, 1 tsp olive oil": "1 prato, 1 colher de chá de azeite", + "1 portion": "1 porção", + "1 pot (170 g)": "1 pote (170 g)", + "1 roll + 30 g": "1 pão + 30 g", + "10 or more": "10 ou mais", + "100 g": "100 g", + "120 g": "120 g", + "150 g": "150 g", + "2 eggs": "2 ovos", + "2 slices": "2 fatias", + "2 small": "2 pequenos", + "2-egg cheese omelette": "Omelete de queijo com 2 ovos", "24h": "24h", + "2–3 times a week": "2–3 vezes por semana", + "2–4 times a month": "2–4 vezes por mês", "3 minutes of slow breathing. An urge usually passes within 20 minutes.": "3 minutos de respiração lenta. A vontade geralmente passa em até 20 minutos.", + "3 or 4": "3 ou 4", "3-question check": "Verificação de 3 perguntas", + "30 g": "30 g", + "4 or more times a week": "4 ou mais vezes por semana", + "4 tbsp (100 g)": "4 colheres de sopa (100 g)", + "5 or 6": "5 ou 6", + "56ff/Jring rings, blood sugar). Blood pressure is measured directly by the sensor.": "anéis 56ff/Jring, glicemia). A pressão arterial é medida diretamente pelo sensor.", "600 ml": "600 ml", + "7 to 9": "7 a 9", "7d": "7d", "8 hours before bed": "8 horas antes de dormir", "A bridge app: it copies another app's data (for example Huawei Health) into Health Connect.": "Um app ponte: ele copia dados de outro app (por exemplo, Huawei Health) para o Health Connect.", "A bridge app: name the watch behind it.": "Um app ponte: informe o relógio por trás dele.", "A check is already open.": "Já há uma verificação em andamento.", - "A device wellness score from 0–100 based on heart-rate patterns. Lower is calmer. It's an estimate, not a medical stress measure.": "Uma pontuação de bem-estar de 0 a 100 baseada nos padrões de frequência cardíaca. Quanto menor, mais calmo. É uma estimativa, não uma medição médica de estresse.", - "A device wellness score from 0–100 estimating tiredness. Higher means more fatigue. It's a ring estimate, not a clinical scale.": "Uma pontuação de bem-estar de 0 a 100 que estima o cansaço. Quanto maior, mais fadiga. É uma estimativa do anel, não uma escala clínica.", "A few more days of data and your routines show up here.": "Mais alguns dias de dados e suas rotinas aparecem aqui.", + "A high reading regardless of context. Confirm with a meter.": "Uma leitura alta independentemente do contexto. Confirme com um medidor.", + "A high resting heart rate. Talk to a clinician if it persists at rest.": "Frequência cardíaca em repouso alta. Fale com um profissional de saúde se persistir em repouso.", + "A little below your usual range.": "Um pouco abaixo da sua faixa habitual.", + "A low resting heart rate is common with high fitness.": "Frequência cardíaca em repouso baixa é comum em quem tem bom condicionamento.", + "A normal blood-oxygen level is 95–100%.{0}": "Um nível normal de oxigênio no sangue é 95–100%.{0}", "A nudge about 30 minutes before your suggested bedtime.": "Um lembrete cerca de 30 minutos antes do horário sugerido para dormir.", "A record for you and your doctor. PulseLoop doesn't check interactions or doses; ask your pharmacist.": "Um registro para você e seu médico. O PulseLoop não verifica interações nem doses; consulte seu farmacêutico.", + "A ring estimate is not a substitute for a cuff.": "Uma estimativa do anel não substitui um medidor de pressão de braço.", "A ring is paired. Forget it in Settings → Wearable first: the two would count the same steps and nights.": "Há um anel pareado. Esqueça-o primeiro em Configurações → Wearable: os dois contariam os mesmos passos e noites.", "A solid active day so far.": "Um dia ativo e consistente até agora.", + "A steady week. Keep it up.": "Uma semana estável. Continue assim.", + "A typical daytime stress score.": "Um nível de estresse diurno típico.", + "A typical resting heart rate for adults.": "Uma frequência cardíaca em repouso típica para adultos.", + "A typical skin-temperature range from the ring.": "Uma faixa típica de temperatura da pele medida pelo anel.", "A typical week now": "Uma semana típica agora", "A weekly limit and dry days you choose": "Um limite semanal e dias sem álcool que você escolhe", "ADD DETAIL (OPTIONAL)": "ADICIONAR DETALHES (OPCIONAL)", "AI Coach": "Coach de IA", "AI Coach is off": "Coach de IA desativado", - "AI analysis needs the coach enabled with a configured provider (Settings → AI Coach). You can still search the database or enter the meal manually.": "A análise por IA precisa do coach ativado com um provedor configurado (Configurações → Coach de IA). Você ainda pode buscar no banco de dados ou inserir a refeição manualmente.", "AI estimate": "Estimativa da IA", "AI health coach": "Coach de saúde com IA", "AI meal log": "Registro de refeição com IA", @@ -36,19 +92,33 @@ "API key needed": "Chave de API necessária", "About": "Sobre", "About PulseLoop": "Sobre o PulseLoop", + "About {0} left": "Faltam cerca de {0}", + "Above baseline": "Acima da linha de base", + "Above goal": "Acima da meta", + "Above the typical range. Context (meals) affects this.": "Acima da faixa típica. O contexto (refeições) influencia.", + "Above the typical resting range. Activity, caffeine, or stress can raise it.": "Acima da faixa típica em repouso. Atividade, cafeína ou estresse podem elevá-la.", + "Above your typical HRV — often a sign of good recovery.": "Acima da sua HRV típica — geralmente sinal de boa recuperação.", "Above ~2000 m, normal blood-oxygen readings run lower. We use this to avoid false low-oxygen warnings.": "Acima de ~2000 m, as leituras normais de oxigênio no sangue ficam mais baixas. Usamos isso para evitar alertas falsos de oxigênio baixo.", "Accuracy check": "Verificação de precisão", "Accuracy check sources": "Fontes da verificação de precisão", + "Accuracy check · day {0} of {1}": "Verificação de precisão · dia {0} de {1}", + "Accuracy check · day {0} of {1} · Health Connect export paused": "Verificação de precisão · dia {0} de {1} · exportação para o Health Connect pausada", "Accuracy report": "Relatório de precisão", "Accuracy report ready · choose what to do with the paused export": "Relatório de precisão pronto · escolha o que fazer com a exportação pausada", + "Across the year your tracked average is {0} over {1} nights. The long-term trend is still forming — as more months fill in, I'll be able to compare seasonal changes and consistency.": "Ao longo do ano, sua média registrada é {0} em {1} noites. A tendência de longo prazo ainda está se formando — conforme mais meses forem preenchidos, poderei comparar mudanças sazonais e consistência.", "Active": "Ativo", + "Active calories": "Calorias ativas", + "Active every hour since {0}:00": "Ativo a cada hora desde {0}:00", "Active minutes": "Minutos ativos", + "Active — {0}": "Ativo — {0}", "Activity": "Atividade", "Activity and live vitals, right away": "Atividade e sinais vitais ao vivo, na hora", + "Activity balance": "Equilíbrio de atividade", "Activity is estimated by PulseLoop from your ring's steps and the workouts you log. It is not a medical measurement.": "A atividade é estimada pelo PulseLoop a partir dos passos do seu anel e dos treinos que você registra. Não é uma medição médica.", "Activity recording": "Gravação de atividade", "Activity type": "Tipo de atividade", "Add": "Adicionar", + "Add Widget": "Adicionar widget", "Add a ring": "Adicionar um anel", "Add a workout you forgot to record": "Adicione um treino que você esqueceu de gravar", "Add by hand": "Adicionar manualmente", @@ -58,23 +128,39 @@ "Add workout": "Adicionar treino", "Add your age in Settings → User Profile for cardio capacity.": "Adicione sua idade em Configurações → Perfil do usuário para a capacidade cardiorrespiratória.", "Add your ring": "Adicione seu anel", + "Adequate": "Adequado", "Adjust end time": "Ajustar horário de término", "Adjust start or end time to trim this record. Stages outside the new range will be removed.": "Ajuste o horário de início ou de término para recortar este registro. As fases fora do novo intervalo serão removidas.", "Adjust start time": "Ajustar horário de início", + "Adjusted by your accuracy check: {0}. Settings → Accuracy check to change.": "Ajustado pela sua verificação de precisão: {0}. Configurações → Verificação de precisão para alterar.", "After 1–2 drinks": "Depois de 1–2 doses", + "After 1–2 drinks, your HRV runs {0}% {1} than on dry nights.": "Depois de 1–2 bebidas, sua HRV fica {0}% {1} do que nas noites sem álcool.", "After 3 or more": "Depois de 3 ou mais", + "After 3 or more drinks, your HRV runs {0}% {1} than on dry nights.": "Depois de 3 ou mais bebidas, sua HRV fica {0}% {1} do que nas noites sem álcool.", "After a session": "Depois de uma sessão", + "After the period, until about two weeks before the next one.": "Depois da menstruação, até cerca de duas semanas antes da próxima.", + "Against your {0} dry nights since you started. A pattern in your data, not proof of cause.": "Comparado com suas {0} noites sem álcool desde que começou. Um padrão nos seus dados, não prova de causa.", "Age": "Idade", + "Agreement band: ±{0}": "Faixa de concordância: ±{0}", + "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", "Alcoólicos Anônimos": "Alcoólicos Anônimos", + "Alerts when your ring's battery runs low": "Alerta quando a bateria do anel estiver baixa", + "All models from {0} ({1})": "Todos os modelos de {0} ({1})", "All-day heart rate": "Frequência cardíaca o dia todo", + "Allow ": "Permitir ", "Allow Bluetooth access": "Permitir acesso ao Bluetooth", "Allow access": "Permitir acesso", "Allow background access so imports also run while PulseLoop is closed.": "Permita o acesso em segundo plano para que as importações também rodem com o PulseLoop fechado.", "Allow background sync": "Permitir sincronização em segundo plano", "Allow camera access in Settings to scan barcodes, or enter the food manually instead.": "Permita o acesso à câmera em Configurações para ler códigos de barras, ou insira o alimento manualmente.", + "Allow it in Settings, or continue without a ring and pair one later.": "Permita nas Configurações ou continue sem anel e pareie um depois.", "Allow more": "Permitir mais", "An LLM-native health app that turns a cheap Bluetooth smart ring into a real, conversational health tracker. It talks to the ring directly over Bluetooth — no vendor cloud, no account — and layers an AI coach on top of your own data.": "Um app de saúde nativo de LLM que transforma um anel inteligente Bluetooth barato em um monitor de saúde de verdade, com conversa. Ele se comunica com o anel diretamente via Bluetooth — sem nuvem do fabricante, sem conta — e adiciona um coach de IA sobre os seus próprios dados.", "An estimated glucose value. No smart ring is cleared to measure glucose, so treat this as a wellness estimate only.": "Um valor estimado de glicose. Nenhum anel inteligente é aprovado para medir glicose, então trate isto apenas como uma estimativa de bem-estar.", + "An urgently low oxygen reading. Seek care if you also feel unwell.{0}": "Uma leitura de oxigênio urgentemente baixa. Procure atendimento se também estiver se sentindo mal.{0}", + "Analysis failed: {0}": "Falha na análise: {0}", "Analyze": "Analisar", "Android may delay background syncs by hours while your phone is idle. Your ring keeps recording either way; allowing this keeps the app up to date.": "O Android pode atrasar as sincronizações em segundo plano por horas enquanto o celular está ocioso. Seu anel continua gravando de qualquer forma; permitir isso mantém o app atualizado.", "Anonymize export": "Anonimizar exportação", @@ -84,10 +170,19 @@ "App Info": "Informações do app", "Applied to what PulseLoop shows, never to stored readings or Health Connect.": "Aplicado ao que o PulseLoop mostra, nunca às leituras armazenadas nem ao Health Connect.", "Apply": "Aplicar", + "Apply correction ({0})": "Aplicar correção ({0})", "Around lunch and dinner, only when nothing is logged yet. Needs nutrition tracking on.": "Perto do almoço e do jantar, só quando ainda não há nada registrado. Requer o acompanhamento de nutrição ativado.", + "Around your personal baseline.": "Perto da sua linha de base pessoal.", + "Arroz branco": "Arroz branco", "Ask the coach about it": "Pergunte ao coach", "Ask the coach...": "Pergunte ao coach...", + "Asleep {0}": "Dormindo {0}", + "At 1% of body weight a week this takes about {0} days.": "A 1% do peso corporal por semana, isso leva cerca de {0} dias.", + "At baseline": "Na linha de base", + "At your usual": "No seu habitual", "Athlete mode": "Modo atleta", + "Athletic": "Atlético", + "Athletic resting range.": "Faixa de repouso de atleta.", "Attach photo": "Anexar foto", "Attach photos to coach messages": "Anexar fotos às mensagens do coach", "Attached photo": "Foto anexada", @@ -96,52 +191,78 @@ "Automatic backups": "Backups automáticos", "Automatically align quiet hours with Android's Bedtime or Do Not Disturb mode.": "Alinhar automaticamente o horário de silêncio com o modo Hora de dormir ou Não perturbe do Android.", "Average": "Média", + "Average difference {0}; 95 % of differences between {1} and {2}": "Diferença média {0}; 95 % das diferenças entre {1} e {2}", + "Averaging {0} against a need of {1}": "Média de {0} contra uma necessidade de {1}", + "Averaging {0} over {1} nights": "Média de {0} em {1} noites", "Avg ": "Méd. ", "Awaiting permission": "Aguardando permissão", "Awake": "Acordado", + "Awake time elevated": "Tempo acordado elevado", + "Awake time low": "Tempo acordado baixo", + "Awake {0} between": "Acordado {0} entre", + "BMI {0}": "IMC {0}", "BP & HRV": "PA e HRV", "Back": "Voltar", "Back up now": "Fazer backup agora", "Backend proxy": "Proxy de backend", "Backing up…": "Fazendo backup…", "Balance Macros (30/40/30)": "Equilibrar macros (30/40/30)", + "Banana": "Banana", "Barcode": "Código de barras", "Barcode scanning needs a working device camera. Enter the food manually instead.": "A leitura de código de barras precisa de uma câmera funcionando. Insira o alimento manualmente.", "Baseline pending": "Linha de base pendente", + "Baseline {0} ms": "Linha de base {0} ms", + "Batata-doce": "Batata-doce", "Battery critically low": "Bateria criticamente baixa", "Battery healthy": "Bateria saudável", "Battery history": "Histórico da bateria", "Battery low": "Bateria baixa", + "Be realistic about portion sizes; state your assumptions (portion sizes, preparation) briefly. Use confidence \"high\" only for clearly identifiable, standard portions. Return only JSON matching the schema.": "Seja realista quanto ao tamanho das porções; informe brevemente suas suposições (tamanho das porções, preparo). Use a confiança \"high\" apenas para porções padrão claramente identificáveis. Retorne apenas JSON de acordo com o schema.", "Bedtime": "Hora de dormir", + "Bedtimes within about 30 minutes help sleep quality": "Horários de dormir com variação de até uns 30 minutos ajudam a qualidade do sono", "Beer": "Cerveja", + "Beer (600 ml)": "Cerveja (600 ml)", + "Beer (can)": "Cerveja (lata)", + "Below 70 mg/dL is low.": "Abaixo de 70 mg/dL é baixo.", + "Below average": "Abaixo da média", "Below avg": "Abaixo da média", + "Below baseline": "Abaixo da linha de base", + "Below goal": "Abaixo da meta", + "Below the typical resting range. Often fine, but worth noting if you feel faint.": "Abaixo da faixa típica em repouso. Geralmente tudo bem, mas vale atenção se você sentir tontura.", "Beta-blockers": "Betabloqueadores", + "Beta-blockers lower heart rate; this is expected on that medication.": "Betabloqueadores reduzem a frequência cardíaca; isso é esperado com esse medicamento.", "Blood Pressure": "Pressão arterial", "Blood oxygen": "Oxigênio no sangue", "Blood oxygen (SpO₂)": "Oxigênio no sangue (SpO₂)", "Blood oxygen (SpO₂) is the percentage of oxygen your blood carries. 95–100% is normal; altitude and lung conditions can lower it.": "O oxigênio no sangue (SpO₂) é a porcentagem de oxigênio que seu sangue transporta. De 95 a 100% é normal; altitude e problemas pulmonares podem reduzi-lo.", "Blood pressure": "Pressão arterial", "Blood pressure calibration": "Calibração da pressão arterial", - "Blood pressure is systolic over diastolic (mmHg). The category is the worse of the two. A ring estimate is not a substitute for a cuff.": "A pressão arterial é a sistólica sobre a diastólica (mmHg). A categoria é a pior das duas. Uma estimativa do anel não substitui um medidor de braçadeira.", "Blood sugar": "Glicemia", "Blood sugar calibration": "Calibração da glicemia", "Bluetooth access needed": "Acesso ao Bluetooth necessário", "Bluetooth is off": "Bluetooth desativado", "Body clock": "Relógio biológico", + "Body fat {0}%": "Gordura corporal {0}%", "Body metrics": "Medidas corporais", + "Body temperature": "Temperatura corporal", "Breathe": "Respirar", "Breathe in": "Inspire", "Breathe out": "Expire", "Breathing sessions this week": "Sessões de respiração nesta semana", + "Building a picture from your data": "Montando um retrato a partir dos seus dados", "Building baseline": "Criando linha de base", "Building momentum": "Ganhando ritmo", "Built on your phone from your ring's data. No AI key needed.": "Gerado no seu celular a partir dos dados do anel. Não precisa de chave de IA.", "CAPS AD": "CAPS AD", "CVV · 188": "CVV · 188", + "Caffeine after 2 pm": "Cafeína depois das 14h", + "Café com leite": "Café com leite", "Caipirinha": "Caipirinha", "Calibrate": "Calibrar", + "Calibrated ✓ (offset %+.0f mg/dL)": "Calibrado ✓ (ajuste %+.0f mg/dL)", "Calibration": "Calibração", "Calibration cleared": "Calibração apagada", + "Calm": "Calmo", "Calories": "Calorias", "Calories (kcal)": "Calorias (kcal)", "Camera": "Câmera", @@ -150,16 +271,24 @@ "Carbs": "Carboidratos", "Carbs (g)": "Carboidratos (g)", "Cardio": "Cardio", + "Cardio capacity (VO₂max)": "Capacidade cardio (VO₂max)", + "Cardio capacity {0}, estimated from resting heart rate and age": "Capacidade cardio {0}, estimada a partir da frequência cardíaca em repouso e da idade", "Cardio load today": "Carga cardio hoje", + "Castanhas": "Castanhas", "Casual or brisk walking": "Caminhada leve ou rápida", "Change": "Alterar", "Charge before bed": "Carregue antes de dormir", + "Charge your ring before bed": "Carregue seu anel antes de dormir", "Chart": "Gráfico", "Check finished: resume Health Connect export": "Verificação concluída: retomar exportação para o Health Connect", "Choose": "Escolher", + "Choose Metric": "Escolher métrica", + "Choose Metrics": "Escolher métricas", "Choose a model": "Escolha um modelo", + "Choose a valid activity type.": "Escolha um tipo de atividade válido.", "Choose an activity, when it started, and how long it lasted.": "Escolha uma atividade, quando ela começou e quanto tempo durou.", "Chopp": "Chopp", + "Cider / other": "Sidra / outros", "Clear": "Limpar", "Clear Demo Data": "Apagar dados de demonstração", "Clear Demo Data?": "Apagar dados de demonstração?", @@ -167,54 +296,79 @@ "Coach": "Coach", "Coach Check-Ins": "Check-ins do coach", "Coach Memory": "Memória do coach", + "Coach goal: {0}": "Meta do Coach: {0}", "Coach is thinking…": "O coach está pensando…", "Cocktail": "Coquetel", "Collapsed": "Recolhido", + "Collecting: needs {0} days with at least {1} steps on both. Carry your phone as usual.": "Coletando: são necessários {0} dias com pelo menos {1} passos em ambos. Leve o celular como de costume.", "Compare my ring with this": "Comparar meu anel com isto", "Compare with my phone": "Comparar com meu celular", "Compare your ring with another device": "Compare seu anel com outro dispositivo", "Compared with your own recent nights. This can follow illness, stress, alcohol or a hard day. It isn't a diagnosis; consider an easier day.": "Comparado com suas noites recentes. Isso pode acompanhar doença, estresse, álcool ou um dia puxado. Não é um diagnóstico; considere um dia mais leve.", "Compared with your typical week": "Comparado com sua semana típica", + "Compared: {0}. These stop exporting to Health Connect until the check ends and you choose what to do with those days.": "Comparados: {0}. Eles deixam de ser exportados para o Health Connect até a verificação terminar e você escolher o que fazer com esses dias.", "Concerning": "Preocupante", "Connect": "Conectar", "Connect + Query": "Conectar + consultar", "Connect Strava": "Conectar Strava", "Connect ring": "Conectar anel", "Connected": "Conectado", + "Connected as {0}. Workouts sync automatically when finished.": "Conectado como {0}. Os treinos são sincronizados automaticamente ao terminar.", + "Connected to {0}": "Conectado a {0}", + "Connected · {0}%": "Conectado · {0}%", + "Connected — {0} · {1}%": "Conectado — {0} · {1}%", + "Connected. {0} of {1} permission types granted.": "Conectado. {0} de {1} tipos de permissão concedidos.", + "Connecting to {0}…": "Conectando a {0}…", "Connecting…": "Conectando…", "Connection failed": "Falha na conexão", "Connection, command and reply events, stored as they happen. Times are local.": "Eventos de conexão, comando e resposta, armazenados à medida que acontecem. Horários locais.", + "Consistent": "Consistente", "Continue": "Continuar", "Continue without ring": "Continuar sem anel", "Contributors": "Colaboradores", + "Cool": "Fria", + "Cooler than typical skin temperature.": "Mais fria que a temperatura típica da pele.", "Copy summary": "Copiar resumo", + "Correct {0}": "Corrigir {0}", + "Correction off ({0})": "Correção desativada ({0})", + "Correction on: {0}": "Correção ativada: {0}", + "Corrections for {0}": "Correções para {0}", "Cost estimates aren't available for on-device or custom models.": "Estimativas de custo não estão disponíveis para modelos locais ou personalizados.", "Could not export diagnostics.": "Não foi possível exportar os diagnósticos.", "Could not open browser": "Não foi possível abrir o navegador", "Couldn't delete this record": "Não foi possível excluir este registro", "Couldn't get a steady reading. Keep the ring snug and your hand still, then try again.": "Não foi possível obter uma leitura estável. Mantenha o anel justo e a mão parada, e tente de novo.", "Couldn't load your health history.": "Não foi possível carregar seu histórico de saúde.", + "Couldn't load {0} trends.": "Não foi possível carregar as tendências de {0}.", "Couldn't look up that barcode. Check your connection or enter the meal manually.": "Não foi possível consultar esse código de barras. Verifique sua conexão ou insira a refeição manualmente.", "Couldn't process that photo. Try again or describe the meal.": "Não foi possível processar essa foto. Tente de novo ou descreva a refeição.", "Couldn't reach the server.": "Não foi possível acessar o servidor.", "Couldn't read Health Connect. Try again in a moment.": "Não foi possível ler o Health Connect. Tente de novo em instantes.", + "Couldn't read {0} from Health Connect just now.": "Não foi possível ler {0} do Health Connect agora.", "Couldn't read: ": "Não foi possível ler: ", "Couldn't save these changes. Check the times and try again.": "Não foi possível salvar as alterações. Verifique os horários e tente de novo.", "Couldn't update this record": "Não foi possível atualizar este registro", "Court sessions": "Sessões em quadra", "Critical": "Crítico", + "Current offset: %+.0f mg/dL": "Ajuste atual: %+.0f mg/dL", + "Cuscuz com ovo": "Cuscuz com ovo", "Custom model slug (vendor/model)": "Slug de modelo personalizado (fornecedor/modelo)", "Customize": "Personalizar", "Cycle": "Ciclo", + "Cycle of {0} days": "Ciclo de {0} dias", + "Cycle · day {0} · {1}": "Ciclo · dia {0} · {1}", "Cycling": "Ciclismo", "DATA SOURCE": "FONTE DE DADOS", "DETECTED · REVIEW": "DETECTADO · REVISAR", + "Daily AI-generated health insights based on your ring data": "Insights de saúde diários gerados por IA com base nos dados do seu anel", "Daily Check-in Notifications": "Notificações de check-in diário", "Daily Goals": "Metas diárias", "Daily and weekly targets behind the activity rings.": "Metas diárias e semanais por trás dos anéis de atividade.", "Daily check-ins": "Check-ins diários", + "Daily goal": "Meta diária", "Daily goals": "Metas diárias", "Daily guidance": "Orientação diária", + "Daily or almost daily": "Diariamente ou quase", "Daily targets": "Metas diárias", "Dance": "Dança", "Data Backup": "Backup de dados", @@ -223,12 +377,20 @@ "Data stays on device": "Os dados ficam no dispositivo", "Database": "Banco de dados", "Day": "Dia", + "Day {0} of {1}": "Dia {0} de {1}", + "Day {0} · {1}": "Dia {0} · {1}", "Days 3–7": "Dias 3–7", + "Daytime nap": "Cochilo diurno", + "Daytime recovery against stress, and how well nights restore you ({0} days)": "Recuperação diurna frente ao estresse e o quanto as noites te restauram ({0} dias)", "Debug": "Depuração", "Decrease duration by 5 minutes": "Diminuir a duração em 5 minutos", + "Decrease {0}": "Diminuir {0}", "Deep": "Profundo", + "Deep sleep": "Sono profundo", + "Deep sleep balanced": "Sono profundo equilibrado", + "Deep sleep is when the body does most of its physical recovery. Around 1 to 1.5 hours is typical for younger adults, and it tends to shrink with age.": "O sono profundo é quando o corpo faz a maior parte da recuperação física. Cerca de 1 a 1,5 hora é típico para adultos mais jovens, e tende a diminuir com a idade.", + "Deep sleep strong": "Sono profundo forte", "Default": "Padrão", - "Default ports — Ollama 11434 · LM Studio 1234 · llama.cpp 8080 · vLLM 8000 · SGLang 30000. The /v1 path is added for you.": "Portas padrão — Ollama 11434 · LM Studio 1234 · llama.cpp 8080 · vLLM 8000 · SGLang 30000. O caminho /v1 é adicionado para você.", "Delete": "Excluir", "Delete drink?": "Excluir bebida?", "Delete every record PulseLoop wrote to Health Connect and reset the export to start fresh. Your ring data in PulseLoop is untouched.": "Exclua todos os registros que o PulseLoop gravou no Health Connect e redefina a exportação para começar do zero. Os dados do anel no PulseLoop não são afetados.", @@ -243,6 +405,7 @@ "Delete this record?": "Excluir este registro?", "Delete workout": "Excluir treino", "Delete workout?": "Excluir treino?", + "Delete {0}": "Excluir {0}", "Deleting needs write permission, and PulseLoop has none right now — re-grant above, or delete the data in the Health Connect app.": "A exclusão precisa de permissão de gravação, e o PulseLoop não tem nenhuma agora — conceda de novo acima ou exclua os dados no app Health Connect.", "Demo Data": "Dados de demonstração", "Describe": "Descrever", @@ -250,6 +413,7 @@ "Destructive actions: unpair the ring, factory-reset app data, or both.": "Ações destrutivas: desparear o anel, redefinir os dados do app ou ambos.", "Details": "Detalhes", "Detect server & configure": "Detectar servidor e configurar", + "Detected by PulseLoop and confirmed": "Detectado pelo PulseLoop e confirmado", "Detecting…": "Detectando…", "Developer": "Desenvolvedor", "Developer options are already enabled.": "As opções de desenvolvedor já estão ativadas.", @@ -270,18 +434,28 @@ "Drink less, sleep better": "Beba menos, durma melhor", "Drinks": "Bebidas", "Drinks settings": "Configurações de bebidas", + "Drinks the user logged themselves, in standard drinks of the given grams. Effects compare the user's own nights after drinking with their dry nights; a pattern, not proof.": "Bebidas que o usuário registrou, em doses padrão com os gramas informados. Os efeitos comparam as noites do próprio usuário após beber com suas noites sem álcool; um padrão, não prova.", "Drinks tonight": "Bebidas hoje à noite", "Dry": "Sem álcool", "Dry days a week": "Dias sem álcool por semana", + "Dry-day goal reached: {0} of {1}": "Meta de dias sem álcool atingida: {0} de {1}", + "Due": "Pendente", "Duration": "Duração", + "Duration held the score back": "A duração limitou a pontuação", + "Duration must be greater than zero.": "A duração deve ser maior que zero.", + "During the check, {0} wrote the same types to Health Connect. Exporting the ring's copy of those days now would count them twice.": "Durante a verificação, {0} gravou os mesmos tipos no Health Connect. Exportar agora a cópia do anel desses dias contaria tudo duas vezes.", "Each night is compared with your own previous four weeks once there are two weeks to compare with. ": "Cada noite é comparada com suas próprias quatro semanas anteriores assim que houver duas semanas para comparar. ", + "Early bird": "Matutino", "Early evening, when you're under 70% of your step goal. Off in Rest Mode.": "No início da noite, quando você estiver abaixo de 70% da sua meta de passos. Desativado no Modo Descanso.", "Edit": "Editar", "Edit goals": "Editar metas", "Edit sleep record": "Editar registro de sono", "Edit this record's times": "Editar os horários deste registro", "Edit workout": "Editar treino", + "Efficiency": "Eficiência", "Elevated": "Elevado", + "Elevated stress — consider a short break.": "Estresse elevado — considere uma pausa curta.", + "Elevated systolic (120–129).": "Sistólica elevada (120–129).", "Enable": "Ativar", "Enable AI Coach": "Ativar Coach de IA", "Enable Coach Check-Ins?": "Ativar check-ins do Coach?", @@ -292,24 +466,36 @@ "End session": "Encerrar sessão", "End the check now?": "Encerrar a verificação agora?", "End time can't be in the future.": "O horário de término não pode estar no futuro.", + "End: {0}": "Fim: {0}", "Ended early.": "Encerrado antes do previsto.", "Ended early: a different ring was paired.": "Encerrado antes do previsto: outro anel foi pareado.", "Ends": "Termina", + "Energy and sleep can dip; resting heart rate is often at its lowest.": "Energia e sono podem cair; a frequência cardíaca em repouso costuma estar no ponto mais baixo.", + "Enter a recent lab/meter reading (mg/dL) to offset the displayed value to match.": "Informe uma leitura recente de laboratório/medidor (mg/dL) para ajustar o valor exibido.", "Enter a valid mg/dL reading": "Insira uma leitura válida em mg/dL", + "Enter a weight between {0} and {1} {2}.": "Informe um peso entre {0} e {1} {2}.", + "Enter your weight in {0}": "Informe seu peso em {0}", "Environment": "Ambiente", "Error": "Erro", + "Error: {0}": "Erro: {0}", "Estimated": "Estimado", + "Estimated cost": "Custo estimado", "Estimated from HRV — your ring doesn't measure stress": "Estimado a partir da HRV — seu anel não mede estresse", - "Estimated from HRV — your ring doesn't measure stress. Scored against your own recent HRV readings, so it says how this reading compares with your normal, not how you compare with anyone else.": "Estimado a partir da HRV — seu anel não mede estresse. Calculado com base nas suas próprias leituras recentes de HRV, então mostra como esta leitura se compara ao seu normal, não como você se compara a outras pessoas.", "Estimated from resting heart rate and age": "Estimado a partir da frequência cardíaca em repouso e da idade", + "Estimated from the current discharge at %.1f %%/h.": "Estimado a partir da descarga atual de %.1f %%/h.", "Estimated wellness metric": "Métrica de bem-estar estimada", - "Estimated wellness metric — not for dosing or diabetes decisions. No smart ring or watch is FDA-authorized to measure or estimate glucose on its own.": "Métrica de bem-estar estimada — não use para dosagem ou decisões sobre diabetes. Nenhum anel inteligente ou relógio é autorizado pela FDA a medir ou estimar glicose por conta própria.", "Estimated · calibrate with a cuff": "Estimado · calibre com um medidor de pressão", + "Estimated — not for dosing or diagnosis": "Estimado — não serve para dosagem nem diagnóstico", "Estimates from your ring compared with your own recent normal, not medical measurements.": "Estimativas do seu anel comparadas com o seu próprio normal recente, não medições médicas.", "Estimating nutrition…": "Estimando nutrição…", "Evening": "Noite", + "Evening check-in": "Check-in da noite", + "Evening type": "Vespertino", + "Every screen, the coach and your insights then work from that data.": "Todas as telas, o Coach e seus insights passam a usar esses dados.", + "Every {0} min": "A cada {0} min", "Everything compared agrees within its band.": "Tudo o que foi comparado está dentro da faixa.", "Excellent": "Excelente", + "Exceptional": "Excepcional", "Expanded": "Expandido", "Explain my heart rate trend": "Explique minha tendência de frequência cardíaca", "Explore the app without a ring. Seeds activity, HR, SpO2, sleep, and a coach conversation.": "Explore o app sem um anel. Gera dados de atividade, HR, SpO2, sono e uma conversa com o coach.", @@ -330,34 +516,54 @@ "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.", "Exporting all history can take a while on the first run.": "Exportar todo o histórico pode demorar um pouco na primeira vez.", "Exporting…": "Exportando…", + "FDA-authorized to measure or estimate glucose on its own.": "Autorizado pela FDA para medir ou estimar glicose por conta própria.", "Factory Reset Ring": "Restaurar anel de fábrica", "Factory reset erases all data stored on the ring itself and resets it to factory state. Your synced data in the app is kept.": "A restauração de fábrica apaga todos os dados armazenados no próprio anel e o retorna ao estado de fábrica. Seus dados sincronizados no app são mantidos.", "Factory reset ring?": "Restaurar anel de fábrica?", "Fair": "Razoável", "Fallback schedule (used when no Bedtime/DND mode was active):": "Horário alternativo (usado quando nenhum modo Hora de dormir/Não perturbe estava ativo):", + "Fasting 100–125 is above the typical range.": "Em jejum, 100–125 está acima da faixa típica.", + "Fasting normal is up to 99 mg/dL.": "Em jejum, o normal é até 99 mg/dL.", + "Fasting ≥126. Talk to a clinician if confirmed by a meter.": "Em jejum ≥126. Fale com um profissional de saúde se for confirmado por um medidor.", "Fat": "Gordura", "Fat (g)": "Gordura (g)", "Fat Burn": "Queima de gordura", "Fatigue": "Fadiga", + "Feeling unwell": "Sentindo-se mal", "Feeling unwell? Pause activity nudges for 3 days.": "Não está se sentindo bem? Pause os lembretes de atividade por 3 dias.", + "Feijão": "Feijão", + "Fell asleep": "Adormeceu", "Female": "Feminino", "Filter models": "Filtrar modelos", "Filter, e.g. claude": "Filtrar, ex.: claude", "Find ring": "Encontrar anel", + "Findings carry the formula version that made them (now v{0}). Patterns, not diagnoses.": "Os achados indicam a versão da fórmula que os gerou (agora v{0}). Padrões, não diagnósticos.", "Finish": "Concluir", "Firmware: reading… (connect ring to read)": "Firmware: lendo… (conecte o anel para ler)", + "Firmware: {0}": "Firmware: {0}", "First sync": "Primeira sincronização", "Fitness": "Condicionamento", + "Fitted from this check so your ring matches {0}: {1}. ": "Ajustado a partir desta verificação para que seu anel corresponda a {0}: {1}. ", + "Fitted {0}{1}: worth a fresh check.": "Ajustado {0}{1}: vale uma nova verificação.", "Flow, stretch, or breathwork": "Flow, alongamento ou respiração", + "Folder: {0}": "Pasta: {0}", + "Follicular": "Folicular", + "Food the user logged themselves; totals are only as complete as the log.": "Alimentos que o usuário registrou; os totais são tão completos quanto o registro.", "For drinks, money and calories saved": "Para bebidas, dinheiro e calorias economizados", + "For my next meal ({0}) you suggested: ": "Para minha próxima refeição ({0}) você sugeriu: ", + "For {0}h asleep before your usual {1}": "Para {0}h de sono antes do seu horário habitual {1}", "Forget": "Esquecer", "Forget Ring": "Esquecer anel", "Forget ring?": "Esquecer anel?", "Forget unbinds the ring and removes it from the app so it can be paired elsewhere. The app stays connected automatically the rest of the time.": "Esquecer desvincula o anel e o remove do app para que possa ser pareado em outro lugar. No restante do tempo, o app permanece conectado automaticamente.", "Formula version": "Versão da fórmula", + "Frango grelhado": "Frango grelhado", "Free emotional support, any time, by phone or chat.": "Apoio emocional gratuito, a qualquer hora, por telefone ou chat.", "Free public care for alcohol use. Ask at your local health unit.": "Atendimento público e gratuito para uso de álcool. Pergunte na sua unidade de saúde.", + "Fresh": "Descansado", "From the next-meal suggestion": "Da sugestão de próxima refeição", + "From the user's smart scale via Health Connect. Day-to-day weight swings are mostly water; talk about the trend only.": "Da balança inteligente do usuário via Health Connect. As oscilações diárias de peso são principalmente água; fale apenas da tendência.", + "From {0}": "De {0}", "Gemini": "Gemini", "Gemini API Key": "Chave de API do Gemini", "General": "Geral", @@ -366,24 +572,38 @@ "Get started": "Começar", "Glucose": "Glicose", "Glucose unit": "Unidade de glicose", + "Goal met on {0} of the last {1} days": "Meta atingida em {0} dos últimos {1} dias", "Goal progress: ": "Progresso da meta: ", "Goals": "Metas", "Goals, scores and Health Connect keep the ring's own count.": "Metas, pontuações e Health Connect mantêm a contagem do próprio anel.", "Good": "Bom", "Good afternoon": "Boa tarde", + "Good duration": "Boa duração", "Good evening": "Boa noite", "Good morning": "Bom dia", + "Good morning{0}": "Bom dia{0}", "Good night": "Boa noite", + "Good sleep, with some restlessness": "Sono bom, com alguma inquietação", "Great balance of movement and recovery. Keep it up.": "Ótimo equilíbrio entre movimento e recuperação. Continue assim.", "Grounds suggestions in your city's current weather": "Baseia as sugestões no clima atual da sua cidade", "Gym": "Academia", "HR collected": "HR coletada", "HR pending": "HR pendente", "HR, SpO₂, HRV & stress": "HR, SpO₂, HRV e estresse", + "HRV": "HRV", + "HRV balance": "Equilíbrio de HRV", "HRV is exported as RMSSD — Health Connect has no SDNN type, and the rings' metric is vendor-undocumented.": "A HRV é exportada como RMSSD — o Health Connect não tem um tipo SDNN, e a métrica dos anéis não é documentada pelo fabricante.", + "HRV is personal. Wear your ring for about a week to learn your baseline.": "A HRV é pessoal. Use seu anel por cerca de uma semana para aprendermos sua linha de base.", + "HRV lower than usual": "HRV mais baixa que o normal", "HRV readings": "Leituras de HRV", + "HRV readings, so it says how this reading compares with your normal, not how you compare with anyone else.": "leituras de HRV, então indica como esta leitura se compara com o seu normal, não com outras pessoas.", + "HRV trending up": "HRV em alta", + "HRV usually takes {0} night{1} to come back.": "A HRV geralmente leva {0} noite{1} para se recuperar.", + "HRV {0}% {1} your dry nights": "HRV {0}% {1} que nas suas noites sem álcool", "Habits & routines · 30-day averages": "Hábitos e rotinas · médias de 30 dias", + "Hard workout": "Treino intenso", "Health Connect": "Health Connect", + "Health Connect and shows where the ring agrees and where it falls short.": "Health Connect e mostra onde o anel concorda e onde fica aquém.", "Health Connect isn't available on this device. Install the Health Connect app to use this feature.": "O Health Connect não está disponível neste dispositivo. Instale o app Health Connect para usar este recurso.", "Health Connect isn't available on this phone.": "O Health Connect não está disponível neste celular.", "Health Connect permissions revoked": "Permissões do Health Connect revogadas", @@ -391,8 +611,17 @@ "Health context": "Contexto de saúde", "Heart": "Coração", "Heart Rate": "Frequência cardíaca", + "Heart health": "Saúde do coração", "Heart rate": "Frequência cardíaca", + "Heart rate above your quiet waking {0} bpm, {1} min well above it": "Frequência cardíaca acima do seu nível tranquilo acordado de {0} bpm, {1} min bem acima", + "Heart rate at rest": "Frequência cardíaca em repouso", "Heart rate since last night": "Frequência cardíaca desde ontem à noite", + "Heart rate since last night: latest {0} bpm, range {1}–{2} bpm, {3} readings": "Frequência cardíaca desde ontem à noite: última {0} bpm, faixa {1}–{2} bpm, {3} leituras", + "Heart rate stayed at your quiet level with no steps": "A frequência cardíaca ficou no seu nível tranquilo, sem passos", + "Heart rate up to {0} bpm": "Frequência cardíaca até {0} bpm", + "Heart rate variability": "Variabilidade da frequência cardíaca", + "Heart rate when active": "Frequência cardíaca em atividade", + "Heart rate {0} → {1} bpm": "Frequência cardíaca {0} → {1} bpm", "Heart-rate readings": "Leituras de frequência cardíaca", "Heart-rate variability is the variation between beats. It's highly individual, so we track it against your personal baseline rather than a universal cutoff.": "A variabilidade da frequência cardíaca é a variação entre os batimentos. Ela é muito individual, então a acompanhamos em relação à sua linha de base pessoal, e não a um limite universal.", "Height": "Altura", @@ -403,34 +632,65 @@ "Hide key": "Ocultar chave", "Hide packets": "Ocultar pacotes", "Hide readings": "Ocultar leituras", + "Hide {0}": "Ocultar {0}", "High": "Alto", + "High fatigue": "Fadiga alta", + "High fatigue score. Wellness estimate from the ring.": "Pontuação de fadiga alta. Estimativa de bem-estar do anel.", + "High stress score. Wellness estimate, not a diagnosis.": "Pontuação de estresse alta. Estimativa de bem-estar, não um diagnóstico.", + "Higher risk": "Risco maior", "Hiking": "Trilha", "How am I doing on my goal? What should I focus on this week?": "Como estou indo na minha meta? No que devo focar esta semana?", "How am I doing today?": "Como estou hoje?", "How can I sleep better?": "Como posso dormir melhor?", + "How consistent the timing of your sleep has been over the last two weeks. A steady rhythm helps recovery.": "Quão consistente foi o horário do seu sono nas últimas duas semanas. Um ritmo estável ajuda na recuperação.", + "How did today feel? Sync your ring and I'll recap your day.": "Como foi o seu dia? Sincronize seu anel e eu faço um resumo do dia.", + "How early in the night your heart rate reached its lowest. An early low means your body had time to recover; a low just before waking means it was still working, often after a late meal, alcohol or an evening workout.": "Quão cedo na noite sua frequência cardíaca chegou ao ponto mais baixo. Um mínimo cedo indica que seu corpo teve tempo para se recuperar; um mínimo logo antes de acordar indica que ele ainda estava trabalhando, muitas vezes após uma refeição tardia, álcool ou um treino à noite.", "How long": "Quanto tempo", + "How long you were asleep, compared with your sleep goal. Most adults need 7 to 9 hours.": "Quanto tempo você dormiu, comparado com sua meta de sono. A maioria dos adultos precisa de 7 a 9 horas.", "How many": "Quantas", + "How many recent days you reached your step goal. Aim for at least 3 days a week, ideally 5 or more.": "Em quantos dias recentes você atingiu sua meta de passos. Tente pelo menos 3 dias por semana, de preferência 5 ou mais.", "How much history should we export?": "Quanto do histórico devemos exportar?", + "How much you slept last night compared with your sleep need, learned from the nights you woke up recovered (your sleep goal until then).": "Quanto você dormiu na noite passada comparado com sua necessidade de sono, aprendida com as noites em que você acordou recuperado (até lá, sua meta de sono).", + "How much you were awake once asleep. Some waking is normal; long or frequent wake-ups lower this.": "Quanto tempo você ficou acordado depois de adormecer. Despertar um pouco é normal; despertares longos ou frequentes reduzem esta nota.", "How often the ring measures in the background. Shorter heart-rate intervals give finer history at the cost of battery.": "Com que frequência o anel mede em segundo plano. Intervalos menores de frequência cardíaca dão um histórico mais detalhado, mas gastam mais bateria.", + "How often you exercised this week. Three or more sessions a week is a good target.": "Com que frequência você se exercitou nesta semana. Três ou mais sessões por semana é uma boa meta.", + "How your ring compares with {0}, the device you chose to trust. This is agreement between two consumer devices, not a lab measurement.": "Como seu anel se compara com {0}, o dispositivo em que você escolheu confiar. É a concordância entre dois aparelhos de consumo, não uma medição de laboratório.", + "I don't see sleep data for last night. Wear your ring overnight and sync in the morning so I can compare your sleep against your baseline.": "Não vejo dados de sono da noite passada. Use o anel durante a noite e sincronize de manhã para eu comparar seu sono com sua linha de base.", + "I only have {0} tracked {1} for this {2}. Wear the ring overnight for a few more nights and I'll build a reliable {3}ly picture.": "Só tenho {0} {1} registradas para este período ({2}). Use o anel à noite por mais algumas noites e vou montar uma visão confiável por {3}.", "I wear an Oura or another device": "Uso um Oura ou outro dispositivo", + "I'd like help with my drinking. This week I'm at {0} of my {1}-drink limit, with {2} dry days. Can you help me plan the next few days?": "Quero ajuda com a bebida. Nesta semana estou em {0} do meu limite de {1} doses, com {2} dias sem álcool. Você pode me ajudar a planejar os próximos dias?", "I'd like to set a goal. Ask me what I want and help me make it realistic for my data.": "Quero definir uma meta. Pergunte o que eu quero e me ajude a torná-la realista para os meus dados.", "Identity": "Identidade", + "Idle": "Inativo", "Idle between syncs": "Ocioso entre sincronizações", + "Idle · {0}%": "Inativo · {0}%", + "If the switch is greyed out, open PulseLoop's App info, tap ⋮ → Allow restricted settings, then come back here.": "Se a chave estiver cinza, abra as Informações do app do PulseLoop, toque em ⋮ → Permitir configurações restritas e volte aqui.", "If your watch syncs through an app like Health Sync, check that it's set to write to Health Connect.": "Se o seu relógio sincroniza por um app como o Health Sync, verifique se ele está configurado para gravar no Health Connect.", "Image attachments": "Anexos de imagem", "Imperial": "Imperial", + "Imperial (mi, lbs, °F)": "Imperial (mi, lbs, °F)", "Import Complete": "Importação concluída", "Import Data": "Importar dados", "Import failed — the file may be corrupt or from a newer version.": "Falha na importação — o arquivo pode estar corrompido ou ser de uma versão mais recente.", "Import now": "Importar agora", + "Imported {0} readings.": "{0} leituras importadas.", "Importing from Health Connect. Your steps, sleep and heart rate appear once your device's app has synced.": "Importando do Health Connect. Seus passos, sono e frequência cardíaca aparecem assim que o app do seu dispositivo sincronizar.", "Importing…": "Importando…", + "In between": "Intermediário", "In drinks, roughly": "Em doses, aproximadamente", + "In line with your usual {0} ms": "Dentro do seu habitual de {0} ms", + "In sync": "Em sincronia", "In the Oura app: Settings → Health Connect, and turn on sharing. Then come back and look again.": "No app Oura: Configurações → Health Connect, e ative o compartilhamento. Depois volte e verifique novamente.", + "Inactivity": "Inatividade", "Increase duration by 5 minutes": "Aumentar a duração em 5 minutos", + "Increase {0}": "Aumentar {0}", + "Increasing risk": "Risco crescente", "Input tokens": "Tokens de entrada", "Install Health Connect": "Instalar Health Connect", - "It changes what PulseLoop shows and what it works out from it (zones, resting baseline, calorie estimate). Your ring's stored readings and what goes to Health Connect stay as measured.": "Isso muda o que o PulseLoop mostra e o que ele calcula a partir disso (zonas, linha de base em repouso, estimativa de calorias). As leituras armazenadas no anel e o que vai para o Health Connect permanecem como medidos.", + "Iogurte natural": "Iogurte natural", + "It's a ring estimate, not a clinical scale.": "É uma estimativa do anel, não uma escala clínica.", + "It's an estimate, not a medical stress measure.": "É uma estimativa, não uma medida médica de estresse.", + "It's at {0}%. A short charge now keeps tonight's sleep tracked.": "Está em {0}%. Uma carga rápida agora garante o registro do sono desta noite.", "Journal": "Diário", "Keep": "Manter", "Keep going": "Continue", @@ -439,25 +699,50 @@ "Keep still — measuring blood pressure, SpO₂, stress, fatigue & blood sugar…": "Fique parado — medindo pressão arterial, SpO₂, estresse, fadiga e glicose…", "Keep still — measuring heart rate & SpO₂…": "Fique parado — medindo frequência cardíaca e SpO₂…", "Keep still — measuring heart rate…": "Fique parado — medindo frequência cardíaca…", + "Keep still — measuring {0}…": "Fique parado — medindo {0}…", "Known lung condition": "Doença pulmonar conhecida", "LAST 3 DAYS": "ÚLTIMOS 3 DIAS", "LAST CAFFEINE": "ÚLTIMA CAFEÍNA", "LAST NIGHT": "ONTEM À NOITE", + "LEFT METRIC": "MÉTRICA DA ESQUERDA", "Language": "Idioma", + "Laranja": "Laranja", + "Last 14 nights, recent nights weigh more": "Últimas 14 noites, as mais recentes pesam mais", + "Last 7 nights against the 3 weeks before; falling means fitter or better recovered": "Últimas 7 noites contra as 3 semanas anteriores; queda indica mais condicionamento ou melhor recuperação", + "Last 7 nights against the 3 weeks before; rising means better recovery": "Últimas 7 noites contra as 3 semanas anteriores; alta indica melhor recuperação", "Last 8 weeks": "Últimas 8 semanas", "Last Sleep": "Último sono", "Last night": "Ontem à noite", + "Last night's heart rate and HRV readings weren't enough to score recovery": "As leituras de frequência cardíaca e HRV da noite passada não foram suficientes para calcular a recuperação", + "Last night: {0}. A few dry nights will show what it does to you.": "Noite passada: {0}. Algumas noites sem álcool vão mostrar o efeito em você.", + "Last night: {0}. Your night looked close to your dry ones.": "Noite passada: {0}. Sua noite ficou parecida com as noites sem álcool.", + "Last night: {0}. {1}.": "Noite passada: {0}. {1}.", + "Last seen: {0}": "Visto por último: {0}", + "Last sync {0} — ": "Última sincronização {0} — ", + "Last synced: {0}": "Última sincronização: {0}", + "Late meal": "Refeição tardia", + "Later": "Mais tarde", + "Later than your usual cycle length. Log it when it starts.": "Mais tarde que a duração habitual do seu ciclo. Registre quando começar.", "Latest": "Mais recente", + "Latest {0}: {1} {2} · average {3} {4}": "{0} mais recente: {1} {2} · média {3} {4}", + "Lean {0} {1}": "Massa magra {0} {1}", "Learned from nights you woke recovered": "Aprendido com noites em que você acordou recuperado", "Learning": "Aprendendo", + "Learning your baseline: {0} of {1} nights. Keep wearing your ring to bed.": "Aprendendo sua linha de base: {0} de {1} noites. Continue dormindo com o anel.", + "Learning your dry nights: {0} of {1}. Then PulseLoop shows what each drink does to your sleep.": "Aprendendo suas noites sem álcool: {0} de {1}. Depois o PulseLoop mostra o que cada bebida faz com seu sono.", + "Learning your normal: {0} of {1} nights.": "Aprendendo seu normal: {0} de {1} noites.", "Learns your baseline": "Aprende sua linha de base", "Leave max tokens blank to let the server decide. Raise the timeout for a large model on CPU — a slow reply is not retried.": "Deixe o máximo de tokens em branco para o servidor decidir. Aumente o tempo limite para um modelo grande em CPU — uma resposta lenta não é repetida.", + "Legumes cozidos": "Legumes cozidos", "Less": "Menos", + "Less than monthly": "Menos de uma vez por mês", "Let my goal manage these": "Deixar minha meta gerenciar isso", "Lets the coach read your data. Detect sets this for you; turn it off if your server rejects tools (vLLM needs --enable-auto-tool-choice).": "Permite que o coach leia seus dados. Detectar define isso para você; desative se o seu servidor rejeitar ferramentas (o vLLM precisa de --enable-auto-tool-choice).", "Library": "Biblioteca", "License": "Licença", "Light": "Leve", + "Limited": "Limitado", + "Limited HR data available for today.": "Poucos dados de FC disponíveis para hoje.", "Live Measurements": "Medições ao vivo", "Live measurements and trends": "Medições ao vivo e tendências", "Live workout tracking": "Acompanhamento de treino ao vivo", @@ -475,21 +760,43 @@ "Log drinks": "Registrar bebidas", "Log meal": "Registrar refeição", "Log meals and track calories & macros": "Registre refeições e acompanhe calorias e macros", + "Log meals to compare intake with the plan": "Registre refeições para comparar o consumo com o plano", "Log meals to see food next to the calories you burn, and to link late meals and drinks to your sleep.": "Registre refeições para ver a alimentação ao lado das calorias que você queima e relacionar refeições e bebidas tardias ao seu sono.", "Log this": "Registrar isto", + "Log two periods to see phases and an estimate of the next one.": "Registre duas menstruações para ver as fases e uma estimativa da próxima.", "Log your period to see its phase beside your sleep and recovery": "Registre sua menstruação para ver a fase do ciclo ao lado do seu sono e recuperação", "Log your period to start": "Registre sua menstruação para começar", + "Log {0}": "Registrar {0}", + "Logged {0}": "{0} registrado", + "Long stretches without moving are linked to poorer health, even on days you exercise. A short walk every hour helps.": "Longos períodos sem se mexer estão ligados a uma saúde pior, mesmo nos dias em que você se exercita. Uma caminhada curta a cada hora ajuda.", + "Long-term insights appear as more nights are tracked.": "Insights de longo prazo aparecem conforme mais noites são registradas.", "Look again": "Verificar novamente", "Looking for apps writing to Health Connect…": "Procurando apps que gravam no Health Connect…", + "Looks like a strong night after a more active day. Your duration was solid and deep sleep made up a healthy part of the night, which kept the score high.": "Parece uma noite forte depois de um dia mais ativo. A duração foi boa e o sono profundo ocupou uma parte saudável da noite, o que manteve a pontuação alta.", "Low": "Baixo", + "Low (medication)": "Baixa (medicação)", "Low Battery Notifications": "Notificações de bateria fraca", + "Low blood oxygen. Re-measure when still; talk to a clinician if persistent.{0}": "Oxigênio no sangue baixo. Meça de novo parado; procure um profissional de saúde se persistir.{0}", + "Low diastolic pressure (below 60).": "Pressão diastólica baixa (abaixo de 60).", + "Low fatigue — well recovered.": "Fadiga baixa — bem recuperado.", + "Low stress score — relaxed.": "Estresse baixo — relaxado.", + "Low systolic pressure (below 90).": "Pressão sistólica baixa (abaixo de 90).", "Lower is calmer": "Quanto menor, mais calmo", + "Lower risk": "Risco menor", + "Lowest heart rate {0} before waking": "Frequência cardíaca mais baixa {0} antes de acordar", + "Lowest {0} · {1} readings": "Mínimo {0} · {1} leituras", + "Luteal": "Lútea", + "MY WEEK": "MINHA SEMANA", + "Major signs": "Sinais fortes", "Male": "Masculino", + "Mamão papaia": "Mamão papaia", "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", "Mask sensitive data": "Mascarar dados sensíveis", "Max": "Máx.", "Max tokens": "Máximo de tokens", + "Maçã": "Maçã", "Meal": "Refeição", "Meal details": "Detalhes da refeição", "Meal name": "Nome da refeição", @@ -500,90 +807,139 @@ "Measurement Frequency": "Frequência de medição", "Measurement units": "Unidades de medida", "Measuring… updates when complete": "Medindo… atualiza ao concluir", + "Measuring… {0}s": "Medindo… {0}s", "Medication": "Medicamento", "Medication reminders": "Lembretes de medicamentos", "Medications & supplements": "Medicamentos e suplementos", + "Meditation or relaxing": "Meditação ou relaxamento", + "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", "Message the coach": "Enviar mensagem ao coach", "Metric": "Métrico", + "Metric (km, kg, °C)": "Métrico (km, kg, °C)", "Metrics": "Métricas", + "Midpoint of sleep at %02d:%02d": "Ponto médio do sono às %02d:%02d", + "Mild": "Leve", + "Mild fatigue.": "Fadiga leve.", "Min": "Mín.", "MiniMax": "MiniMax", "MiniMax API Key": "Chave de API do MiniMax", + "Minor signs": "Sinais leves", + "Missed": "Perdida", "Model": "Modelo", "Model name": "Nome do modelo", "Models": "Modelos", "Moderate": "Moderado", "Month": "Mês", + "Monthly": "Mensalmente", + "Monthly Sleep": "Sono mensal", "Monthly average": "Média mensal", + "Monthly or less": "Uma vez por mês ou menos", "More": "Mais", "Morning": "Manhã", + "Morning type": "Matutino", + "Move every hour": "Mexa-se a cada hora", "Move reminder": "Lembrete para se mexer", + "Move {0} down": "Mover {0} para baixo", + "Move {0} up": "Mover {0} para cima", "My Health": "Minha saúde", "My Health & Trends": "Minha saúde e tendências", + "NEXT MEAL IDEA · {0}": "IDEIA PARA A PRÓXIMA REFEIÇÃO · {0}", "Name": "Nome", + "Near baseline": "Perto da linha de base", "Needs 5 nights in the last 2 weeks": "Precisa de 5 noites nas últimas 2 semanas", + "Needs care": "Requer atenção", "Needs work": "Precisa melhorar", + "Never": "Nunca", "New chat": "Nova conversa", "Next": "Próximo", "Next day": "Próximo dia", + "Next period around {0} (in {1} day{2}), from your usual {3}-day cycle.": "Próxima menstruação por volta de {0} (em {1} dia{2}), com base no seu ciclo habitual de {3} dias.", "Next: end date": "Próximo: data de término", "Night covered by the ring": "Noite registrada pelo anel", + "Night owl": "Noturno", "Nightly sleep": "Sono por noite", + "Nightly sleep: latest {0}, range {1}–{2}, {3} of {4} nights tracked": "Sono por noite: última {0}, faixa {1}–{2}, {3} de {4} noites registradas", "Nightly sleep: no nights tracked in this range": "Sono por noite: nenhuma noite registrada neste período", "Nights in your baseline": "Noites na sua linha de base", "No HR samples yet — sync your ring to start your trend.": "Ainda não há amostras de HR — sincronize seu anel para começar sua tendência.", "No HRV data yet — HRV builds up over a few hours of wear.": "Ainda não há dados de HRV — a HRV se forma após algumas horas de uso.", "No Health Connect permissions granted — nothing to export.": "Nenhuma permissão do Health Connect concedida — nada para exportar.", - "No PulseLoop ring? If your Oura, Galaxy Ring, Fitbit or watch app writes to Health Connect, PulseLoop can read it from there: sleep, heart rate, HRV, blood oxygen, steps, calories, workouts and periods. Every screen, the coach and your insights then work from that data.": "Não tem um anel PulseLoop? Se o app do seu Oura, Galaxy Ring, Fitbit ou relógio grava no Health Connect, o PulseLoop pode ler esses dados de lá: sono, frequência cardíaca, HRV, oxigênio no sangue, passos, calorias, treinos e menstruação. Todas as telas, o coach e seus insights passam a usar esses dados.", "No SpO₂ samples yet — take a reading to start your trend.": "Ainda não há amostras de SpO₂ — faça uma medição para começar sua tendência.", "No access granted. You can allow it in Health Connect's settings.": "Acesso não concedido. Você pode permitir nas configurações do Health Connect.", "No accuracy check for this ring yet. Corrections from another ring don't carry over.": "Ainda não há verificação de precisão para este anel. Correções de outro anel não são aproveitadas.", + "No activity records synced for {0} yet.": "Nenhum registro de atividade sincronizado para {0} ainda.", + "No app wrote health data in the last {0} days.": "Nenhum app gravou dados de saúde nos últimos {0} dias.", "No blood pressure data yet.": "Ainda não há dados de pressão arterial.", "No blood sugar data yet.": "Ainda não há dados de glicemia.", "No body measurements found in Health Connect yet.": "Nenhuma medida corporal encontrada no Health Connect ainda.", + "No calibration set": "Nenhuma calibração definida", "No clear difference": "Sem diferença clara", "No data": "Sem dados", + "No data yet today": "Ainda sem dados hoje", "No daytime stress readings today yet.": "Ainda não há leituras de estresse diurno hoje.", + "No drinks this week": "Nenhuma bebida nesta semana", + "No drinks yet this week": "Nenhuma bebida ainda nesta semana", "No estimate": "Sem estimativa", "No events yet. Sync the ring or trigger a measurement to see data.": "Nenhum evento ainda. Sincronize o anel ou inicie uma medição para ver os dados.", "No export has run yet. With the master switch on and a backfill choice made, PulseLoop exports automatically.": "Nenhuma exportação foi feita ainda. Com a chave principal ativada e uma opção de histórico escolhida, o PulseLoop exporta automaticamente.", "No fatigue data yet — take a measurement.": "Ainda não há dados de fadiga — faça uma medição.", + "No meals logged this week": "Nenhuma refeição registrada nesta semana", "No nights tracked in this range yet.": "Nenhuma noite registrada neste período ainda.", + "No obvious signs in your biometrics of something straining your body.": "Nenhum sinal claro nos seus dados biométricos de algo sobrecarregando seu corpo.", + "No other app wrote readable data in the last {0} days.": "Nenhum outro app gravou dados legíveis nos últimos {0} dias.", + "No readiness today: {0}. Wear the ring snugly tonight.": "Sem prontidão hoje: {0}. Use o anel bem ajustado esta noite.", "No reading": "Sem leitura", "No ring connected": "Nenhum anel conectado", "No ring paired": "Nenhum anel pareado", "No rings found yet": "Nenhum anel encontrado ainda", "No rows to display.": "Nenhuma linha para exibir.", "No score": "Sem pontuação", + "No signs": "Sem sinais", + "No sleep captured last night": "Nenhum sono captado na noite passada", "No sleep recorded": "Nenhum sono registrado", + "No sleep recorded for last night yet. Sync your ring after you wake up.": "Ainda não há sono registrado da noite passada. Sincronize o anel depois de acordar.", "No sleep stages, only time asleep": "Sem fases do sono, só o tempo dormindo", + "No sleep tracked last night": "Nenhum sono registrado na noite passada", "No sleep yet": "Ainda sem sono", "No stress data yet — take a measurement.": "Ainda não há dados de estresse — faça uma medição.", "No subscription": "Sem assinatura", "No temperature data yet — temperature trends appear after overnight wear.": "Ainda não há dados de temperatura — as tendências de temperatura aparecem após usar o anel durante a noite.", "No workouts recorded today": "Nenhum treino registrado hoje", "No workouts yet — recorded workouts will appear here.": "Nenhum treino ainda — os treinos registrados aparecerão aqui.", + "None": "Nenhum", "None. A finished check offers one wherever the ring is consistently off.": "Nenhuma. Uma verificação concluída oferece uma sempre que o anel estiver consistentemente desviado.", "Normal": "Normal", + "Normal blood pressure is below 120/80.": "A pressão arterial normal é abaixo de 120/80.", + "Normal diastolic is below 80.": "A diastólica normal é abaixo de 80.", "Not a diagnosis. Rest, fluids and an easier day help; see a doctor if you feel unwell.": "Não é um diagnóstico. Descanso, hidratação e um dia mais leve ajudam; procure um médico se não estiver se sentindo bem.", "Not allowed to read: ": "Sem permissão para ler: ", "Not connected": "Não conectado", "Not enough data for this period.": "Dados insuficientes para este período.", "Not enough data yet — battery history builds up as the ring reports its level.": "Dados insuficientes por enquanto — o histórico de bateria se forma à medida que o anel informa o nível.", "Not enough data yet: ": "Dados insuficientes por enquanto: ", + "Not enough monthly data": "Dados mensais insuficientes", "Not enough nights yet": "Noites insuficientes por enquanto", "Not enough of a trend to estimate runtime yet — it appears after a few hours of discharge.": "Ainda não há tendência suficiente para estimar a autonomia — ela aparece após algumas horas de descarga.", + "Not enough recent weigh-ins for a trend yet (needs 3 across a week).": "Ainda não há pesagens recentes suficientes para uma tendência (são necessárias 3 em uma semana).", + "Not enough weekly data": "Dados semanais insuficientes", + "Not enough yearly data": "Dados anuais insuficientes", + "Not enough {0} data for this view yet.": "Ainda não há dados de {0} suficientes para esta visualização.", + "Not enough {0} data yet": "Ainda não há dados de {0} suficientes", "Not imported yet": "Ainda não importado", "Not measured": "Não medido", "Not now": "Agora não", "Not set": "Não definido", "Not this": "Não é isso", "Not yet": "Ainda não", + "Notably below your typical HRV — often linked to stress, poor sleep, or strain.": "Bem abaixo da sua HRV habitual — muitas vezes ligado a estresse, sono ruim ou sobrecarga.", + "Nothing is shared off your phone.": "Nada é compartilhado para fora do seu celular.", "Nothing logged yet": "Nada registrado ainda", "Nothing new to upload": "Nada novo para enviar", "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 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", @@ -592,16 +948,22 @@ "OR DESCRIBE IT": "OU DESCREVA", "Off": "Desativado", "Offline": "Offline", + "Omelete de 2 ovos com queijo": "Omelete de 2 ovos com queijo", "On": "Ativado", + "On track": "No caminho certo", + "On until {0}/{1}: activity nudges paused, the coach eases off.": "Ativo até {0}/{1}: lembretes de atividade pausados, o Coach pega mais leve.", "On. 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.", "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", + "Only {0} day(s) of food logged this week; intake may be incomplete.": "Só {0} dia(s) com refeições registradas nesta semana; o consumo pode estar incompleto.", + "Only {0} kcal left: ": "Restam só {0} kcal: ", "Open": "Abrir", "Open Drinks: this week, your plan and what drinking does to your nights": "Abrir Bebidas: esta semana, seu plano e o que beber faz com suas noites", "Open Health Connect": "Abrir Health Connect", "Open Nutrition Log": "Abrir registro de nutrição", + "Open PulseLoop to sync": "Abra o PulseLoop para sincronizar", "Open Settings": "Abrir Configurações", "Open ring settings": "Abrir configurações do anel", "Open settings": "Abrir configurações", @@ -611,41 +973,53 @@ "OpenAI API Key": "Chave de API da OpenAI", "OpenRouter": "OpenRouter", "OpenRouter API Key": "Chave de API do OpenRouter", + "Optimal": "Ideal", "Optional": "Opcional", - "Optional refinements to how your vitals are interpreted. Leave anything unset and PulseLoop uses sensible defaults.": "Configurações opcionais na forma como seus sinais vitais são interpretados. Deixe qualquer item em branco e o PulseLoop usa padrões adequados.", "Optional. Both can change what's expected for your heart rate or oxygen, so we adjust labels instead of alarming.": "Opcional. Ambos podem mudar o esperado para sua frequência cardíaca ou oxigenação, então ajustamos os rótulos em vez de alarmar.", "Optional. Enter a recent cuff reading so the ring offsets its values to match.": "Opcional. Informe uma medição recente de um medidor de braço para o anel ajustar os valores dele.", - "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 real. Informe uma medição recente de laboratório/glicosímetro (mg/dL) para ajustar o valor exibido.", "Other": "Outro", "Other ideas": "Outras ideias", + "Out of sync": "Fora de sincronia", "Outdoor or treadmill runs": "Corridas ao ar livre ou na esteira", "Output tokens": "Tokens de saída", + "Ovos mexidos": "Ovos mexidos", "Own your ring data": "Seus dados do anel são seus", "Pace": "Ritmo", "Pair a ring to configure its all-day measurements.": "Pareie um anel para configurar as medições contínuas.", "Pair your ring first.": "Pareie seu anel primeiro.", "Pair your ring first: a check compares it against the other device.": "Pareie seu anel primeiro: a verificação o compara com o outro dispositivo.", "Past checks": "Verificações anteriores", + "Patinho moído": "Patinho moído", "Pause": "Pausar", "Paused by the accuracy check": "Pausado pela verificação de precisão", "Paused by the accuracy check: ": "Pausado pela verificação de precisão: ", + "Pay attention": "Atenção", "Peak": "Pico", + "Peak {0}": "Pico {0}", + "Peak —": "Pico —", "Per-message breakdown": "Detalhamento por mensagem", + "Period": "Menstruação", "Period ended today": "Menstruação terminou hoje", + "Period later than usual": "Menstruação atrasada", "Period started today": "Menstruação começou hoje", "Permission needed": "Permissão necessária", "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", "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.", + "Pick which PulseLoop metric this widget shows.": "Escolha qual métrica do PulseLoop este widget mostra.", "Plan the next few days with the coach.": "Planeje os próximos dias com o coach.", "Plan tonight": "Planejar esta noite", "Plan: dry night": "Plano: noite sem álcool", + "Plan: {0}": "Plano: {0}", "Port from iOS · Open Source": "Portado do iOS · Código aberto", "Possible nap": "Possível cochilo", + "Possible {0}": "Possível {0}", "Previous": "Anterior", "Previous day": "Dia anterior", + "Previous day activity": "Atividade do dia anterior", "Price each (optional)": "Preço unitário (opcional)", "Privacy & Data": "Privacidade e dados", "Privacy first": "Privacidade em primeiro lugar", @@ -661,31 +1035,40 @@ "PulseLoop checks for new data every hour and whenever you open the app. A night usually appears once ": "O PulseLoop verifica novos dados a cada hora e sempre que você abre o app. Uma noite costuma aparecer quando ", "PulseLoop isn't allowed to read Health Connect any more.": "O PulseLoop não tem mais permissão para ler o Health Connect.", "PulseLoop learns your baseline over time": "O PulseLoop aprende sua linha de base com o tempo", - "PulseLoop needs Bluetooth permission to find and connect to your ring. Allow it in Settings, or continue without a ring and pair one later.": "O PulseLoop precisa da permissão de Bluetooth para encontrar e conectar seu anel. Permita nas Configurações ou continue sem anel e pareie um depois.", "PulseLoop no longer has any Health Connect permissions. Reset the export so a later re-grant re-exports your history?": "O PulseLoop não tem mais nenhuma permissão do Health Connect. Redefinir a exportação para que, se você conceder de novo, seu histórico seja exportado novamente?", "PulseLoop reads only the app you choose, and doesn't write that data back to Health Connect.": "O PulseLoop lê apenas o app que você escolher e não grava esses dados de volta no Health Connect.", "PulseLoop shows the day of your cycle and its phase from the dates you log, next to your sleep and recovery.": "O PulseLoop mostra o dia do seu ciclo e a fase dele a partir das datas que você registra, junto ao seu sono e recuperação.", - "PulseLoop uses Bluetooth to find and connect your ring. Allow ": "O PulseLoop usa Bluetooth para encontrar e conectar seu anel. Permita ", - "PulseLoop uses Bluetooth to find and connect your ring. Nothing is shared off your phone.": "O PulseLoop usa Bluetooth para encontrar e conectar seu anel. Nada sai do seu celular.", + "PulseLoop uses sensible defaults.": "O PulseLoop usa padrões sensatos.", + "PulseLoop v{0} ({1})": "PulseLoop v{0} ({1})", "PulseLoop will stop uploading workouts. Workouts already on Strava stay there.": "O PulseLoop vai parar de enviar treinos. Os treinos que já estão no Strava continuam lá.", + "PulseLoop {0} (Android)": "PulseLoop {0} (Android)", + "PulseLoop · from my ring, compared with last week": "PulseLoop · do meu anel, comparado com a semana passada", + "Pão de queijo": "Pão de queijo", + "Pão francês com queijo minas": "Pão francês com queijo minas", "Quick Access": "Acesso rápido", "Quiet from": "Silêncio a partir de", "Quiet hours schedule:": "Horário de silêncio:", "Quiet until": "Silêncio até", "REFERENCE ZONES": "ZONAS DE REFERÊNCIA", + "REM sleep": "Sono REM", + "REM sleep supports memory and mood. It usually makes up 20 to 25% of a night, about 90 minutes or more.": "O sono REM ajuda a memória e o humor. Normalmente ocupa de 20 a 25% da noite, cerca de 90 minutos ou mais.", + "RIGHT METRIC": "MÉTRICA DA DIREITA", "Raw Packets": "Pacotes brutos", "Re-analyze": "Reanalisar", "Readiness": "Prontidão", + "Readiness is estimated by PulseLoop from your ring's sleep, heart rate, HRV and activity, compared with your own recent nights. It is not a medical measurement.": "A Prontidão é estimada pelo PulseLoop a partir do sono, da frequência cardíaca, da HRV e da atividade medidos pelo anel, comparados com suas próprias noites recentes. Não é uma medida médica.", "Reading (mg/dL)": "Medição (mg/dL)", "Reading your drinks…": "Lendo suas bebidas…", "Reading your history…": "Lendo seu histórico…", + "Ready to start the day? Take a measurement and I'll help you plan it.": "Pronto para começar o dia? Faça uma medição e eu ajudo você a planejá-lo.", "Reasoning effort": "Nível de raciocínio", "Recommended": "Recomendado", "Recompute": "Recalcular", "Reconnect last ring": "Reconectar último anel", "Record activity": "Registrar atividade", - "Recording a workout needs the Physical activity permission. You can allow it in Android Settings › Apps › PulseLoop › Permissions.": "Registrar um treino exige a permissão de Atividade física. Você pode permiti-la em Configurações do Android › Apps › PulseLoop › Permissões.", "Records": "Registros", + "Recovery index": "Índice de recuperação", + "Recovery time": "Tempo de recuperação", "Reference device": "Dispositivo de referência", "Refresh": "Atualizar", "Relaxed": "Relaxado", @@ -695,7 +1078,6 @@ "Remove PulseLoop data?": "Remover dados do PulseLoop?", "Remove exported data": "Remover dados exportados", "Remove photo": "Remover foto", - "Removes all demo measurements, activity, sleep, and the demo device. Synced ring data is not affected.": "Remove todas as medições, atividades, sono e o dispositivo de demonstração. Os dados sincronizados do anel não são afetados.", "Removes health values, ring serial & MAC addresses. Keeps models, opcodes & errors.": "Remove valores de saúde, número de série e endereços MAC do anel. Mantém modelos, opcodes e erros.", "Removing…": "Removendo…", "Reorder or hide cards": "Reordenar ou ocultar cartões", @@ -713,29 +1095,46 @@ "Reset ring": "Redefinir anel", "Reset units to auto-detect": "Redefinir unidades para detecção automática", "Reset zoom": "Redefinir zoom", + "Resetting ring…": "Redefinindo o anel…", "Resetting…": "Redefinindo…", "Resilience": "Resiliência", + "Resilience {0} over {1} days": "Resiliência {0} em {1} dias", "Resources": "Recursos", + "Respiratory rate": "Frequência respiratória", "Response format": "Formato da resposta", "Rest": "Descanso", "Rest Mode": "Modo descanso", + "Rest Mode on until {0}": "Modo Descanso ativo até {0}", + "Rest days let your body adapt to training. One or two easier days a week is enough for most people.": "Dias de descanso permitem que o corpo se adapte ao treino. Um ou dois dias mais leves por semana bastam para a maioria das pessoas.", + "Restfulness": "Tranquilidade", + "Resting HR": "FC em repouso", + "Resting calibrating": "Calibrando repouso", "Resting heart rate": "Frequência cardíaca em repouso", "Resting heart rate reflects how hard your heart works at rest. A typical adult range is 60–100 bpm; fitness, medication, caffeine, and stress all shift it.": "A frequência cardíaca em repouso mostra o quanto seu coração trabalha em repouso. A faixa típica de um adulto é de 60–100 bpm; condicionamento, medicamentos, cafeína e estresse a alteram.", + "Resting heart rate trending down": "Frequência cardíaca em repouso em queda", + "Resting heart rate up": "Frequência cardíaca em repouso em alta", + "Resting heart rate {0} bpm": "Frequência cardíaca em repouso {0} bpm", + "Resting {0}": "Repouso {0}", + "Restored": "Restaurado", + "Restored {0} · relaxed {1} · engaged {2} · stressed {3}": "Restaurado {0} · relaxado {1} · engajado {2} · estressado {3}", "Resume": "Retomar", "Retake (every 3 months)": "Refazer (a cada 3 meses)", "Retry": "Tentar novamente", "Review & adjust": "Revisar e ajustar", "Ride it out": "Aguentar firme", + "Right at your limit": "Exatamente no seu limite", + "Right at your usual {0} bpm": "Exatamente no seu habitual de {0} bpm", "Ring Events": "Eventos do anel", "Ring battery alerts": "Alertas de bateria do anel", "Ring blood pressure is an estimate. Calibrate against a validated cuff in Settings → Calibration, and talk to a clinician about persistent high or low readings.": "A pressão arterial do anel é uma estimativa. Calibre com um medidor de braço validado em Configurações → Calibração e converse com um profissional de saúde sobre leituras persistentemente altas ou baixas.", + "Ring hasn't synced in >12h — today's data may be stale.": "O anel não sincroniza há mais de 12h — os dados de hoje podem estar desatualizados.", "Ring management": "Gerenciamento do anel", "Ring model estimate": "Estimativa do modelo do anel", "Ring steps vs your phone": "Passos do anel vs. do seu celular", "Road, trail, or stationary": "Rua, trilha ou estacionária", "Route by": "Rotear por", - "Row counts include demo and real rows. Tap a table to see its newest rows. Stored health rows are never included in a diagnostics export.": "A contagem de linhas inclui linhas de demonstração e reais. Toque em uma tabela para ver as linhas mais recentes. Linhas de saúde armazenadas nunca são incluídas em uma exportação de diagnóstico.", "Running": "Corrida", + "Salada verde com tomate": "Salada verde com tomate", "Same as heart rate": "Igual à frequência cardíaca", "Save": "Salvar", "Save Key": "Salvar chave", @@ -752,7 +1151,13 @@ "Saves the same file as Export to a folder you choose, and keeps the latest 5.": "Salva o mesmo arquivo de Exportar em uma pasta que você escolher e mantém os 5 mais recentes.", "Scan a packaged food": "Escanear um alimento embalado", "Scan barcode": "Escanear código de barras", + "Scan last {0} days": "Verificar últimos {0} dias", + "Scanning for {0}…": "Procurando {0}…", "Scanning unavailable": "Leitura indisponível", + "Score {0} of 12 · {1}": "Pontuação {0} de 12 · {1}", + "Score {0} out of 100": "Pontuação {0} de 100", + "Scores are PulseLoop estimates from ring data compared with the user's own baseline, not medical measurements.": "As pontuações são estimativas do PulseLoop a partir dos dados do anel comparados com a linha de base do próprio usuário, não medidas médicas.", + "Screens in bed": "Telas na cama", "Searching…": "Procurando…", "See Raw Packets above.": "Veja Pacotes brutos acima.", "See Ring Events above.": "Veja Eventos do anel acima.", @@ -776,13 +1181,18 @@ "Set your typical week in settings to see drinks, money and calories saved.": "Defina sua semana típica nas configurações para ver as bebidas, o dinheiro e as calorias economizados.", "Settings": "Configurações", "Setup complete": "Configuração concluída", + "Severe": "Grave", + "Severe range (diastolic >120). Seek care if confirmed.": "Faixa grave (diastólica >120). Procure atendimento se confirmado.", + "Severe range (systolic >180). Seek care if confirmed.": "Faixa grave (sistólica >180). Procure atendimento se confirmado.", "Sex": "Sexo", "Shaded: your usual range over the last 30 days": "Área sombreada: sua faixa habitual nos últimos 30 dias", "Share": "Compartilhar", "Share accuracy report": "Compartilhar relatório de precisão", "Share my week": "Compartilhar minha semana", + "Short duration": "Duração curta", "Shot": "Dose", "Show": "Mostrar", + "Show ({0})": "Mostrar ({0})", "Show activity records": "Mostrar registros de atividade", "Show connection details": "Mostrar detalhes da conexão", "Show fewer events": "Mostrar menos eventos", @@ -791,36 +1201,68 @@ "Show phone-calibrated steps on Today": "Mostrar passos calibrados pelo celular em Hoje", "Show readings": "Mostrar leituras", "Show recent packets": "Mostrar pacotes recentes", + "Show {0}": "Mostrar {0}", + "Show {0} more": "Mostrar mais {0}", "Skin temperature": "Temperatura da pele", - "Skin temperature from the ring runs cooler than core body temperature. Trends over time matter more than any single reading.": "A temperatura da pele medida pelo anel é mais baixa que a temperatura corporal central. As tendências ao longo do tempo importam mais do que uma leitura isolada.", + "Skin temperature up": "Temperatura da pele em alta", "Skip": "Pular", "Skip for now": "Pular por enquanto", "Skip these days (recommended)": "Pular estes dias (recomendado)", + "Skipped": "Pulado", "Sleep": "Sono", + "Sleep a night": "Dormir uma noite", "Sleep architecture": "Arquitetura do sono", + "Sleep balance": "Equilíbrio do sono", "Sleep contributors": "Fatores do sono", "Sleep debt": "Débito de sono", + "Sleep health": "Saúde do sono", "Sleep insights": "Insights de sono", + "Sleep midpoint varies by about {0} min": "O ponto médio do sono varia cerca de {0} min", "Sleep need": "Necessidade de sono", "Sleep pending": "Sono pendente", "Sleep quiet hours": "Horário de silêncio do sono", + "Sleep regularity": "Regularidade do sono", + "Sleep stages": "Estágios do sono", "Sleep stages and nightly trends": "Estágios do sono e tendências noturnas", + "Sleep stages from {0} to {1}": "Estágios do sono de {0} a {1}", + "Sleep stages: {0}": "Estágios do sono: {0}", "Sleep synced": "Sono sincronizado", "Sleep tracking": "Monitoramento do sono", + "Sleep {0} a night": "Dormir {0} por noite", + "Sleeping less this week": "Dormindo menos nesta semana", + "Sleeping more this week": "Dormindo mais nesta semana", + "Slightly below": "Um pouco abaixo", + "Slightly below the typical range.{0}": "Um pouco abaixo da faixa típica.{0}", + "Slightly low": "Um pouco baixo", + "Slightly off": "Um pouco fora", "Slow breathing: in for 4 seconds, out for 6.": "Respiração lenta: inspire por 4 segundos, expire por 6.", + "Small signs in your biometrics of something straining your body.": "Sinais leves nos seus dados biométricos de algo sobrecarregando seu corpo.", "Snap your plate; the AI estimates it": "Fotografe seu prato; a IA faz a estimativa", "So far (preliminary)": "Até agora (preliminar)", + "Solid": "Boa", + "Solid night overall": "Boa noite no geral", + "Some of your signals look unusual": "Alguns dos seus sinais parecem incomuns", "Some signals look unusual": "Alguns sinais parecem fora do comum", + "Sopa de legumes com frango": "Sopa de legumes com frango", + "Sorry, something went wrong: {0}": "Desculpe, algo deu errado: {0}", "Source on GitHub": "Código-fonte no GitHub", "SpO₂": "SpO₂", "Speed": "Velocidade", + "Spirit (shot)": "Destilado (dose)", "Sport": "Esporte", "Squash": "Squash", + "Stable {0}": "Estável {0}", "Stage 1": "Estágio 1", + "Stage 1 hypertension range (diastolic 80–89).": "Faixa de hipertensão estágio 1 (diastólica 80–89).", + "Stage 1 hypertension range (systolic 130–139).": "Faixa de hipertensão estágio 1 (sistólica 130–139).", + "Stage 2": "Estágio 2", + "Stage 2 hypertension range (diastolic ≥90).": "Faixa de hipertensão estágio 2 (diastólica ≥90).", + "Stage 2 hypertension range (systolic ≥140).": "Faixa de hipertensão estágio 2 (sistólica ≥140).", "Staged photo": "Foto encenada", "Stages": "Estágios", "Stages and trends": "Estágios e tendências", "Standard drink": "Dose padrão", + "Standard drink: {0} g of alcohol": "Dose padrão: {0} g de álcool", "Start": "Iniciar", "Start a breathing session": "Iniciar uma sessão de respiração", "Start an accuracy check": "Iniciar uma verificação de precisão", @@ -829,19 +1271,31 @@ "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", "Starts": "Início", "Steady build": "Evolução constante", "Step progress": "Progresso de passos", + "Step {0} of {1}": "Etapa {0} de {1}", "Steps": "Passos", + "Steps a day": "Passos por dia", + "Steps collected": "Passos coletados", + "Steps {0}{1}%": "Passos {0}{1}%", "Stop scanning": "Parar busca", "Stop using Health Connect": "Parar de usar o Health Connect", + "Stored health rows are never included in a diagnostics export.": "Os dados de saúde armazenados nunca são incluídos em uma exportação de diagnóstico.", "Stored securely in Android Keystore. Never leaves your device except to call the model. Provider changes apply from your next message.": "Armazenada com segurança no Android Keystore. Nunca sai do seu dispositivo, exceto para chamar o modelo. Mudanças de provedor valem a partir da sua próxima mensagem.", "Strava": "Strava", "Strava Integration": "Integração com o Strava", "Strava Not Configured": "Strava não configurado", "Strength or circuit training": "Musculação ou treino em circuito", "Stress": "Estresse", + "Stress management": "Gestão do estresse", + "Stressful": "Estressante", + "Stressful day": "Dia estressante", + "Strong": "Forte", + "Strong recovery signal": "Sinal forte de recuperação", + "Stronger signs in your biometrics of something straining your body.": "Sinais fortes nos seus dados biométricos de algo sobrecarregando seu corpo.", "Studio, cardio, or freestyle": "Aula, cardio ou livre", "Summarize my week": "Resumir minha semana", "Summary copied. It holds counts and timings only, no readings.": "Resumo copiado. Ele contém apenas contagens e horários, nenhuma leitura.", @@ -851,6 +1305,7 @@ "Support in Brazil": "Suporte no Brasil", "Swipe to find your model, then tap to connect.\nYou can also explore first and pair later.": "Deslize para encontrar seu modelo e toque para conectar.\nVocê também pode explorar primeiro e parear depois.", "Symptom Radar": "Radar de sintomas", + "Symptom Radar: {0}": "Radar de Sintomas: {0}", "Symptom radar, sleep debt, stress, body clock, cardio capacity": "Radar de sintomas, débito de sono, estresse, relógio biológico, capacidade cardiorrespiratória", "Sync Now": "Sincronizar agora", "Sync all history": "Sincronizar todo o histórico", @@ -858,6 +1313,8 @@ "Sync from your scale": "Sincronizar com sua balança", "Sync now": "Sincronizar agora", "Sync your ring to start collecting movement, heart rate, blood oxygen, and recovery context.": "Sincronize seu anel para começar a coletar movimento, frequência cardíaca, oxigênio no sangue e dados de recuperação.", + "Synced ring data is not affected.": "Os dados sincronizados do anel não são afetados.", + "Synced {0}": "Sincronizado {0}", "Syncing latest data…": "Sincronizando dados mais recentes…", "Syncing…": "Sincronizando…", "System default": "Padrão do sistema", @@ -867,51 +1324,94 @@ "Tag day": "Marcar dia", "Tag yesterday": "Marcar ontem", "Tag your day": "Marque seu dia", + "Tag your days for a couple of weeks. Once a tag has at least {0} nights after it, PulseLoop compares those nights with your others.": "Marque seus dias por algumas semanas. Quando uma marcação tiver pelo menos {0} noites depois dela, o PulseLoop compara essas noites com as outras.", + "Tag {0} more {1} to see an effect": "Marque mais {0} {1} para ver um efeito", "Tagged as \"Meditation or relaxing\" in today's journal.": "Marcado como \"Meditação ou relaxamento\" no diário de hoje.", "Take a blood sugar measurement first, then calibrate": "Faça primeiro uma medição de glicose e depois calibre", "Take it easy": "Vá com calma", "Take the check": "Fazer o teste", "Taken": "Tomado", "Talk it through": "Conversar sobre isso", + "Tapioca com ovo": "Tapioca com ovo", "Tatá, te amo!": "Tatá, te amo!", "Team or racket sports": "Esportes coletivos ou de raquete", "Tell the coach, and it plans with your scale, ring and food data.": "Conte ao coach, e ele planeja com os dados da sua balança, do anel e da alimentação.", "Temperature": "Temperatura", + "Temperature trend": "Tendência de temperatura", "That app shares nothing PulseLoop can compare.": "Esse app não compartilha nada que o PulseLoop possa comparar.", "That looks like PulseLoop's own data coming back through a sync app, so this report would compare the ring with itself. Check the sync direction in that app.": "Parecem ser dados do próprio PulseLoop voltando por um app de sincronização, então este relatório compararia o anel com ele mesmo. Verifique a direção da sincronização nesse app.", + "The /v1 path is added for you.": "O caminho /v1 é adicionado para você.", "The AI didn't return a usable estimate. Try again or enter the meal manually.": "A IA não retornou uma estimativa utilizável. Tente novamente ou insira a refeição manualmente.", "The Health Connect app on this device needs an update before it can be used.": "O app Health Connect deste dispositivo precisa ser atualizado antes de ser usado.", "The WHO's short alcohol check (AUDIT-C). Three questions, under a minute. A screen, not a diagnosis.": "O teste rápido sobre álcool da OMS (AUDIT-C). Três perguntas, menos de um minuto. Uma triagem, não um diagnóstico.", + "The activity must end in the past.": "A atividade precisa terminar no passado.", "The coach also replies in the language you choose.": "O coach também responde no idioma que você escolher.", + "The coach will forget \"{0}\". This can't be undone.": "O Coach vai esquecer \"{0}\". Isso não pode ser desfeito.", + "The date needs more of a deficit than is safe; the suggestion is held at the floor.": "A data exige um déficit maior do que o seguro; a sugestão fica no limite mínimo.", "The import failed. Try again in a moment.": "A importação falhou. Tente novamente em instantes.", "The report covers the days so far. You'll then choose what happens to the paused Health Connect export.": "O relatório abrange os dias até agora. Depois você escolherá o que acontece com a exportação pausada para o Health Connect.", "The ring disconnected during measurement.": "O anel se desconectou durante a medição.", "The ring isn't detecting your finger. Put it on snugly, then try again.": "O anel não está detectando seu dedo. Coloque-o bem justo e tente novamente.", "The ring recorded this as one record": "O anel registrou isto como um único registro", + "The ring recorded this night in {0} parts": "O anel registrou esta noite em {0} partes", "The scan failed. Try again in a moment.": "A busca falhou. Tente novamente em instantes.", + "The share of your time in bed spent asleep. Around 85% or more is considered good.": "A parte do seu tempo na cama em que você dormiu. Cerca de 85% ou mais é considerado bom.", + "The stage mix was useful, but total sleep time was short for a full recovery window. A slightly earlier wind-down would likely improve tomorrow's score.": "A combinação de estágios foi boa, mas o tempo total de sono foi curto para uma recuperação completa. Começar a relaxar um pouco mais cedo deve melhorar a pontuação de amanhã.", + "The target date has passed; agree a new one.": "A data-alvo já passou; defina uma nova.", "The tile and the morning-after line disappear. Your logged drinks stay on this phone until you delete them or clear your data.": "O bloco e a linha da manhã seguinte desaparecem. Suas bebidas registradas ficam neste celular até você excluí-las ou apagar seus dados.", + "The two weeks before a period: skin temperature and resting heart rate often run a little higher.": "As duas semanas antes da menstruação: a temperatura da pele e a frequência cardíaca em repouso costumam ficar um pouco mais altas.", + "The window must be longer than the {0} min of pauses in this workout.": "A janela precisa ser maior que os {0} min de pausas deste treino.", "The workout must finish before now.": "O treino deve terminar antes de agora.", + "There's room to move more today.": "Ainda dá para se mexer mais hoje.", + "There's room to move more. Start with your {0}.": "Ainda dá para se mexer mais. Comece pelo seu {0}.", "These are patterns in your own data, not proof of cause and effect. Every tag is checked against your sleep, HRV and resting heart rate together, so a difference that could easily be chance isn't shown. They get more reliable the more days you tag.": "Estes são padrões nos seus próprios dados, não prova de causa e efeito. Cada marcação é verificada em conjunto com seu sono, HRV e frequência cardíaca em repouso, então uma diferença que poderia facilmente ser acaso não é exibida. Eles ficam mais confiáveis quanto mais dias você marcar.", + "This check was run on {0}. Pair that ring to apply a correction from it.": "Esta verificação foi feita com {0}. Pareie esse anel para aplicar uma correção a partir dela.", "This deletes every record PulseLoop wrote to Health Connect and resets the export. It cannot be undone, and your ring data in PulseLoop is not affected.": "Isso exclui todos os registros que o PulseLoop gravou no Health Connect e redefine a exportação. Não é possível desfazer, e os dados do seu anel no PulseLoop não são afetados.", "This erases all data stored on the ring and resets it to factory state. We'll sync its latest data into the app first, but this can't be undone. The ring will need to be re-paired afterward.": "Isso apaga todos os dados armazenados no anel e o restaura para o estado de fábrica. Primeiro vamos sincronizar os dados mais recentes com o app, mas isso não pode ser desfeito. O anel precisará ser pareado novamente depois.", "This is a test check-in notification.": "Esta é uma notificação de check-in de teste.", "This permanently deletes everything currently in the app and replaces it with the contents of this file. This can't be undone.": "Isso exclui permanentemente tudo o que está no app e substitui pelo conteúdo deste arquivo. Não é possível desfazer.", "This permanently erases all your data — metrics, sleep, activity, coach history, settings, and saved API keys — and can't be undone.": "Isso apaga permanentemente todos os seus dados — métricas, sono, atividade, histórico do coach, configurações e chaves de API salvas — e não pode ser desfeito.", + "This record runs {0} – {1}. You can only shorten it.": "Este registro vai de {0} a {1}. Você só pode encurtá-lo.", "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.": "Isso desvincula o anel e o remove do app. Seus dados sincronizados são mantidos, mas você precisará parear o anel novamente para continuar sincronizando.", "This unpairs your ring, then permanently erases all your data — metrics, sleep, activity, coach history, settings, and saved API keys — and can't be undone.": "Isso despareia seu anel e depois apaga permanentemente todos os seus dados — métricas, sono, atividade, histórico do coach, configurações e chaves de API salvas — e não pode ser desfeito.", "This week": "Esta semana", + "This week is {0}% less active than your monthly average": "Esta semana está {0}% menos ativa que sua média mensal", + "This week is {0}% more active than your monthly average": "Esta semana está {0}% mais ativa que sua média mensal", + "This week matches your monthly rhythm": "Esta semana segue seu ritmo mensal", + "This week's activity compared with your monthly average. It flags both overdoing it and a drop in activity.": "A atividade desta semana comparada com sua média mensal. Sinaliza tanto excessos quanto quedas de atividade.", "This will replace all existing demo data. Your synced ring data — including sleep history — will not be affected.": "Isso substituirá todos os dados de demonstração existentes. Os dados sincronizados do anel — incluindo o histórico de sono — não serão afetados.", "This workout is no longer in local storage. It may have been deleted or replaced.": "Este treino não está mais no armazenamento local. Ele pode ter sido excluído ou substituído.", + "This {0} will be removed from your log.": "Este item ({0}) será removido do seu registro.", + "Thriving": "Excelente", + "Tilápia grelhada": "Tilápia grelhada", "Time": "Horário", + "Time asleep": "Tempo dormindo", + "Time for {0}": "Hora de {0}", + "Time to move": "Hora de se mexer", + "Time to wind down": "Hora de relaxar", "Timeout (s)": "Tempo limite (s)", "Times": "Horários", - "To log when Bedtime or Do Not Disturb turns on and off while PulseLoop is in the background, Android requires Notification access. PulseLoop only listens for Mode changes and does not read your notifications.\n\nIf the switch is greyed out, open PulseLoop's App info, tap ⋮ → Allow restricted settings, then come back here.": "Para registrar quando o modo Hora de dormir ou Não perturbe é ativado e desativado com o PulseLoop em segundo plano, o Android exige acesso às notificações. O PulseLoop só detecta mudanças de modo e não lê suas notificações.\n\nSe a chave estiver desativada, abra Informações do app do PulseLoop, toque em ⋮ → Permitir configurações restritas e volte aqui.", + "Timing": "Horário", + "Tired": "Cansado", + "Tired — consider lighter activity and good sleep.": "Cansado — prefira atividades mais leves e uma boa noite de sono.", "Today": "Hoje", + "Today's steps against your step goal. It fills up as the day goes on.": "Os passos de hoje em relação à sua meta. A barra enche ao longo do dia.", + "Today: {0}": "Hoje: {0}", + "Tonight: {0} drink{1}": "Hoje à noite: {0} bebida{1}", "Tool calling": "Chamada de ferramentas", + "Total sleep": "Sono total", + "Total workout time this week. Health guidelines suggest at least 150 minutes of moderate activity a week.": "Tempo total de treino nesta semana. As diretrizes de saúde sugerem pelo menos 150 minutos de atividade moderada por semana.", "Track Bedtime / DND mode": "Monitorar modo Hora de dormir / Não perturbe", + "Track more nights this month to see a monthly average.": "Registre mais noites este mês para ver uma média mensal.", + "Tracked {0} {1} this year": "Este ano você registrou {0} {1}", "Trails and elevation": "Trilhas e elevação", + "Training frequency": "Frequência de treinos", + "Training volume": "Volume de treino", + "Travel": "Viagem", "Treats a low resting heart rate as a sign of fitness rather than a concern, and relaxes the low-HR threshold.": "Trata uma frequência cardíaca em repouso baixa como sinal de condicionamento, e não de preocupação, e flexibiliza o limite de HR baixa.", + "Trend": "Tendência", "Trends": "Tendências", + "Trends over time matter more than any single reading.": "A tendência ao longo do tempo importa mais que qualquer leitura isolada.", "Trigger real-time ring readings": "Acionar leituras do anel em tempo real", "Try again": "Tentar novamente", "Turn off": "Desativar", @@ -919,11 +1419,17 @@ "Turn off Drinks?": "Desativar Bebidas?", "Turn on": "Ativar", "Turn on Bluetooth to find and connect your ring.": "Ative o Bluetooth para encontrar e conectar seu anel.", + "Two hours after against two hours before, over {0} sessions. Readings during a session aren't counted: slow breathing raises HRV while it lasts.": "Duas horas depois comparadas com duas horas antes, em {0} sessões. Leituras durante a sessão não contam: a respiração lenta eleva a HRV enquanto dura.", + "Two-hour 140–199 is above the typical range.": "Duas horas após: 140–199 está acima da faixa típica.", + "Two-hour post-meal normal is up to 140 mg/dL.": "O normal duas horas após a refeição é até 140 mg/dL.", + "Two-hour ≥200. Confirm with a meter and a clinician.": "Duas horas após: ≥200. Confirme com um medidor e com um médico.", "Type the name and calories": "Digite o nome e as calorias", + "Typical": "Típico", "Typical altitude (ft)": "Altitude típica (ft)", "Typical altitude (m)": "Altitude típica (m)", "Typical week before": "Semana típica antes", "Under 100 steps in an hour, 9:00 to 20:00, at most every two hours. Off in Rest Mode.": "Menos de 100 passos em uma hora, das 9:00 às 20:00, no máximo a cada duas horas. Desativado no Modo descanso.", + "Under 100 steps in the last hour. A few minutes on your feet helps your energy and your sleep.": "Menos de 100 passos na última hora. Alguns minutos de pé ajudam sua energia e seu sono.", "Undo": "Desfazer", "Units": "Unidades", "Unpair & Reset": "Desparear e redefinir", @@ -933,23 +1439,35 @@ "Unpair ring & reset app data?": "Desparear anel e redefinir dados do app?", "Unpair ring?": "Desparear anel?", "Unpair your ring? The ring will forget this phone; your data stays.": "Desparear seu anel? O anel vai esquecer este celular; seus dados permanecem.", + "Until {0}": "Até {0}", "Unusual last night: ": "Incomum na última noite: ", "Unusual signals alert": "Alerta de sinais incomuns", + "Unusual-signal alerts, your weekly report and wind-down reminders": "Alertas de sinais incomuns, seu relatório semanal e lembretes para relaxar", "Update Health Connect": "Atualizar o Health Connect", "Update Key": "Atualizar chave", + "Upload failed: {0}": "Falha no envio: {0}", "Uploaded 1 workout": "1 treino enviado", + "Uploaded {0} workouts": "{0} treinos enviados", "Usage & cost": "Uso e custo", "Use location & weather": "Usar localização e clima", "Use the device you already wear": "Use o dispositivo que você já usa", "Use the fitted value": "Usar o valor ajustado", "Use without a ring": "Usar sem anel", "Use your device's data": "Usar os dados do seu dispositivo", + "Use {0}": "Usar {0}", "Used to tune calories, activity goals, and summaries.": "Usado para ajustar calorias, metas de atividade e resumos.", "User Profile": "Perfil do usuário", + "User profile is incomplete — insights may be less personalized.": "O perfil do usuário está incompleto — os insights podem ser menos personalizados.", "Uses additional tokens": "Usa tokens adicionais", "Using your latest ring sync": "Usando a sincronização mais recente do anel", + "Using {0}": "Usando {0}", + "Usual": "Habitual", "Usual price of a drink (optional)": "Preço habitual de uma bebida (opcional)", + "Usual sleep midpoint {0} · this week {1}": "Ponto médio habitual do sono {0} · esta semana {1}", + "Variable nights": "Noites irregulares", "Version": "Versão", + "Very high": "Muito alto", + "Very low": "Muito baixo", "View": "Ver", "Vitals": "Sinais vitais", "WEEKLY GOAL": "META SEMANAL", @@ -957,24 +1475,33 @@ "Waiting for BLE connection events…": "Aguardando eventos de conexão BLE…", "Waiting for first sync": "Aguardando a primeira sincronização", "Waiting for the first import": "Aguardando a primeira importação", + "Waiting for {0} to deliver {1} day{2}. Open the app that syncs it to send it sooner; otherwise those days are scored 24 hours after they end.": "Aguardando {0} entregar {1} dia{2}. Abra o app que sincroniza para enviar antes; caso contrário, esses dias são avaliados 24 horas depois de terminarem.", "Wake the ring by tapping or moving it, and keep it close.": "Desperte o anel tocando ou movendo-o, e mantenha-o por perto.", "Wake-up": "Despertar", "Walking": "Caminhada", "Want to drink less? Track drinks, set a weekly limit and see what each drink does to your nights": "Quer beber menos? Registre as bebidas, defina um limite semanal e veja o que cada dose faz com suas noites", + "Warm": "Quente", + "Warmer than typical. Trends matter more than a single reading.": "Mais quente que o normal. A tendência importa mais que uma leitura isolada.", "We suggest a quarter less to start": "Sugerimos um quarto a menos para começar", + "Wear both as usual. Health Connect export paused for: {0}.": "Use os dois normalmente. Exportação para o Health Connect pausada para: {0}.", "Wear both devices as you normally would, including at night.": "Use os dois dispositivos normalmente, inclusive à noite.", - "Wear the ring and a watch or band you trust for a few days. PulseLoop reads that device's data from Health Connect and shows where the ring agrees and where it falls short.": "Use o anel e um relógio ou pulseira em que você confia por alguns dias. O PulseLoop lê os dados desse dispositivo no Health Connect e mostra onde o anel concorda e onde ele deixa a desejar.", "Wear your ring during the day and sync after sleep. Trends become more personal after a few days.": "Use o anel durante o dia e sincronize depois de dormir. As tendências ficam mais personalizadas após alguns dias.", + "Wear your ring overnight for a few nights to build a weekly view.": "Use o anel durante a noite por algumas noites para montar uma visão semanal.", + "Wear your ring overnight so PulseLoop can track your next night.": "Use o anel durante a noite para que o PulseLoop acompanhe sua próxima noite.", "Wear your ring overnight to see your hypnogram here.": "Use o anel durante a noite para ver seu hipnograma aqui.", "Wear your ring today. Your baseline builds from here.": "Use o anel hoje. Sua linha de base começa a ser construída a partir daqui.", "Wearable": "Wearable", "Web Search": "Pesquisa na web", "Week": "Semana", + "Weekly": "Semanal", + "Weekly Sleep": "Sono semanal", "Weekly limit": "Limite semanal", "Weekly report": "Relatório semanal", "Weekly target": "Meta semanal", "Weight": "Peso", + "Weight in {0}": "Peso em {0}", "Weight, height and body composition from Health Connect (Fitdays and other scale apps).": "Peso, altura e composição corporal do Health Connect (Fitdays e outros apps de balança).", + "Weight, last 90 days: latest {0} {1}, range {2}–{3} {4}, {5} weigh-ins": "Peso, últimos 90 dias: último {0} {1}, faixa {2}–{3} {4}, {5} pesagens", "What affects you": "O que afeta você", "What changed": "O que mudou", "What did you do?": "O que você fez?", @@ -984,14 +1511,19 @@ "When did it start?": "Quando começou?", "When on, sleep the ring records outside the window is trimmed off on import — a still wrist reads as sleep, so an evening on the sofa can log a phantom session and run the night high. Set the start to when you actually go to bed. Naps outside the window are skipped too. Already-imported nights are never touched, and what the gate skips while it is narrower stays skipped.": "Quando ativado, o sono que o anel registra fora da janela é cortado na importação — um pulso parado parece sono, então uma noite no sofá pode registrar uma sessão fantasma e inflar a noite. Defina o início para quando você realmente vai para a cama. Cochilos fora da janela também são ignorados. Noites já importadas nunca são alteradas, e o que o filtro ignora enquanto está mais estreito continua ignorado.", "When the ring is at 30% or less a couple of hours before your usual bedtime.": "Quando o anel estiver com 30% ou menos algumas horas antes do seu horário habitual de dormir.", + "When the ring says… what {0} says (minutes)": "Quando o anel diz… o que {0} diz (minutos)", "When two or more of last night's signals are outside your usual range.": "Quando dois ou mais sinais da última noite estiverem fora da sua faixa habitual.", "When you want a drink": "Quando você quiser beber", "Where the ring falls short": "Onde o anel deixa a desejar", + "Whether your sleep lines up with your body clock. A midpoint between midnight and about 3:30 am is ideal for most people.": "Se o seu sono está alinhado com seu relógio biológico. Um ponto médio entre meia-noite e cerca de 3h30 é o ideal para a maioria das pessoas.", "While a check runs, PulseLoop stops exporting the types the other device also writes, so Health Connect doesn't count your steps, sleep and heart rate twice.": "Enquanto uma verificação está em andamento, o PulseLoop para de exportar os tipos que o outro dispositivo também grava, para que o Health Connect não conte seus passos, sono e frequência cardíaca em dobro.", "Why there's no score today": "Por que não há pontuação hoje", "Wind-down reminder": "Lembrete para relaxar", "Wine": "Vinho", "With stages: ": "Com estágios: ", + "Withheld: {0}.": "Retido: {0}.", + "Within a typical range for a non-fasting reading.": "Dentro da faixa típica para uma leitura sem jejum.", + "Woke up": "Acordou", "Workout": "Treino", "Workout history": "Histórico de treinos", "Workout in progress": "Treino em andamento", @@ -1000,26 +1532,187 @@ "Workouts / week": "Treinos / semana", "Write Actions": "Ações de escrita", "YOUR GOAL": "SUA META", + "Year": "Ano", + "Yearly Sleep": "Sono anual", "Yes, a nap": "Sim, um cochilo", "Yesterday": "Ontem", + "Yesterday's steps compared with your usual. Both a very inactive day and an unusually heavy one lower this.": "Os passos de ontem comparados com o seu habitual. Tanto um dia muito parado quanto um dia excepcionalmente puxado reduzem este valor.", "Yoga": "Ioga", "You are now a developer!": "Agora você é um desenvolvedor!", + "You averaged {0} across the full week. Your nights were tracked consistently, so this is a dependable picture of where your sleep sits right now.": "Sua média foi {0} na semana inteira. Suas noites foram registradas com regularidade, então este é um retrato confiável de como está seu sono agora.", + "You averaged {0} across {1} tracked nights this week. That's a useful read, but {2} missing {3} mean the trend is still incomplete.": "Sua média foi {0} em {1} noites registradas esta semana. É uma boa leitura, mas {2} {3} faltando indicam que a tendência ainda está incompleta.", + "You can allow it in Android Settings › Apps › PulseLoop › Permissions.": "Você pode permitir em Configurações do Android › Apps › PulseLoop › Permissões.", "You can pair a ring later from Settings.": "Você pode parear um anel depois em Configurações.", + "You can still search the database or enter the meal manually.": "Você ainda pode pesquisar no banco de dados ou inserir a refeição manualmente.", "You can use either a comma or a period as the decimal separator.": "Você pode usar vírgula ou ponto como separador decimal.", + "You hit your {0} step goal — nice work.": "Você bateu sua meta de {0} passos — muito bem.", + "You logged {0}h {1}m of sleep. Here's to a strong day — get moving when you can.": "Você registrou {0}h {1}m de sono. Que seja um ótimo dia — mexa-se quando puder.", + "You moved less than last week. A daily walk is an easy way back.": "Você se mexeu menos que na semana passada. Uma caminhada diária é um jeito fácil de retomar.", + "You slept long enough, but awake time was a bit elevated. If this repeats, look at late caffeine, alcohol, temperature, or stress near bedtime.": "Você dormiu o suficiente, mas o tempo acordado ficou um pouco alto. Se isso se repetir, observe cafeína tarde, álcool, temperatura ou estresse perto da hora de dormir.", "You're all set": "Tudo pronto", - "Your age, sex, height and weight let the ring compute accurate calories (and, on 56ff/Jring rings, blood sugar). Blood pressure is measured directly by the sensor.": "Sua idade, sexo, altura e peso permitem que o anel calcule as calorias com precisão (e, nos anéis 56ff/Jring, a glicose). A pressão arterial é medida diretamente pelo sensor.", + "You're at %,d steps, %dh %02dm of sleep, and your latest reading is %s.": "Você está com %,d passos, %dh %02dm de sono, e sua leitura mais recente é %s.", + "You're at %,d steps. Sync after waking to add recovery context.": "Você está com %,d passos. Sincronize depois de acordar para adicionar o contexto de recuperação.", + "You're at {0} of {1}. About {2} minutes of walking closes it.": "Você está em {0} de {1}. Cerca de {2} minutos de caminhada completam.", + "You're in good shape today. Your usual plans should feel fine.": "Você está em boa forma hoje. Seus planos habituais devem correr bem.", + "You're well recovered. A good day to take on something demanding.": "Você está bem recuperado. Um bom dia para encarar algo exigente.", + "You're {0} g short of today's protein, so this leans on protein.": "Faltam {0} g da proteína de hoje, então esta opção prioriza proteína.", + "You're {0} step{1} away from Developer options.": "Faltam {0} passo{1} para as Opções do desenvolvedor.", + "You've reached today's target. Water or tea if you're hungry": "Você atingiu a meta de hoje. Água ou chá se estiver com fome", + "Your HRV dipped this week. Lighter days and consistent sleep help it recover.": "Sua HRV caiu esta semana. Dias mais leves e sono regular ajudam a recuperá-la.", + "Your answers suggest drinking at a level that is likely affecting your health. Please talk to a doctor. If you drink most days, don't stop all at once: stopping suddenly can be dangerous, and a doctor can help you cut down safely.": "Suas respostas sugerem um consumo de álcool que provavelmente está afetando sua saúde. Converse com um médico. Se você bebe na maioria dos dias, não pare de uma vez: parar de repente pode ser perigoso, e um médico pode ajudar você a reduzir com segurança.", + "Your answers suggest drinking at a level that raises health risks. Cutting down gradually, with a weekly limit and dry days, is the usual first step.": "Suas respostas sugerem um consumo de álcool que aumenta os riscos à saúde. Reduzir aos poucos, com um limite semanal e dias sem álcool, é o primeiro passo habitual.", + "Your answers suggest lower-risk drinking. Keeping some dry days each week helps keep it that way.": "Suas respostas sugerem um consumo de menor risco. Manter alguns dias sem álcool por semana ajuda a continuar assim.", + "Your average sleep over the last two weeks compared with your goal. It shows whether sleep debt is building up.": "Seu sono médio nas últimas duas semanas comparado com sua meta. Mostra se está acumulando dívida de sono.", + "Your body is asking for rest. Make recovery today's priority.": "Seu corpo está pedindo descanso. Faça da recuperação a prioridade de hoje.", + "Your body is asking for rest. Make recovery today's priority: your {0} is furthest from your usual.": "Seu corpo está pedindo descanso. Faça da recuperação a prioridade de hoje: seu {0} é o que está mais longe do habitual.", + "Your body is still recovering. Go a little easier today and watch your {0}.": "Seu corpo ainda está se recuperando. Pegue um pouco mais leve hoje e fique de olho no seu {0}.", + "Your body is still recovering. Go a little easier today.": "Seu corpo ainda está se recuperando. Pegue um pouco mais leve hoje.", "Your data has been restored from the backup.": "Seus dados foram restaurados a partir do backup.", "Your drinks stay on this phone. They aren't sent to Health Connect or included in diagnostics.": "Suas bebidas ficam neste celular. Elas não são enviadas ao Health Connect nem incluídas nos diagnósticos.", "Your goal doesn't set any of these.": "Sua meta não define nenhum destes.", "Your goal, until 5 recovered nights teach the app yours": "Sua meta, até que 5 noites de recuperação ensinem ao app a sua", "Your health, on your terms — no subscription, no cloud.": "Sua saúde, do seu jeito — sem assinatura, sem nuvem.", + "Your heart rate variability over the last few nights, weighted toward last night, compared with your usual. Higher than usual generally means you're well recovered; a drop suggests strain.": "Sua variabilidade da frequência cardíaca nas últimas noites, com mais peso para a última, comparada com o seu habitual. Acima do habitual geralmente indica boa recuperação; uma queda sugere sobrecarga.", + "Your long-term sleep trend": "Sua tendência de sono no longo prazo", + "Your lowest sustained heart rate last night, compared with your usual over recent nights. A resting heart rate a few beats above normal can mean your body is working on recovery, stress, or an oncoming illness.": "Sua frequência cardíaca mais baixa sustentada na noite passada, comparada com o seu habitual nas noites recentes. Uma frequência cardíaca em repouso alguns batimentos acima do normal pode indicar que seu corpo está lidando com recuperação, estresse ou uma doença chegando.", + "Your month in sleep": "Seu mês de sono", + "Your monthly average is {0} across {1}. The biggest lever is consistency — a few short nights move this number more than any single great one.": "Sua média mensal é {0} em {1}. A maior alavanca é a regularidade — algumas noites curtas mexem mais nesse número do que qualquer noite excelente.", + "Your monthly average is {0}, but coverage is low ({1}), so I'd treat that number cautiously. More nights tracked will sharpen the trend.": "Sua média mensal é {0}, mas a cobertura é baixa ({1}), então eu trataria esse número com cautela. Registrar mais noites vai deixar a tendência mais clara.", "Your nights": "Suas noites", "Your nights against your own normal, kept as a log": "Suas noites comparadas ao seu próprio normal, guardadas como registro", "Your nights look like your usual. That's an answer too.": "Suas noites parecem as de sempre. Isso também é uma resposta.", "Your personalized baseline unlocks": "Sua linha de base personalizada é liberada", "Your phone counts steps too. Comparing the two over a few days shows whether your ring over- or under-counts.": "Seu celular também conta passos. Comparar os dois por alguns dias mostra se o seu anel conta passos a mais ou a menos.", "Your preference: ": "Sua preferência: ", + "Your resting heart rate is up on last week. Prioritise recovery and sleep.": "Sua frequência cardíaca em repouso subiu em relação à semana passada. Priorize recuperação e sono.", + "Your ring and phone agree within 5% ({0} days).": "Seu anel e seu celular concordam dentro de 5% ({0} dias).", + "Your ring counts about {0}% fewer steps than your phone ({1} days).": "Seu anel conta cerca de {0}% menos passos que seu celular ({1} dias).", + "Your ring counts about {0}% more steps than your phone ({1} days).": "Seu anel conta cerca de {0}% mais passos que seu celular ({1} dias).", "Your ring logs heart rate every few minutes, so short sessions may show none.": "Seu anel registra a frequência cardíaca a cada poucos minutos, então sessões curtas podem não mostrar nenhuma.", + "Your ring's stored readings and what goes to Health Connect stay as measured.": "As leituras armazenadas do anel e o que vai para o Health Connect continuam como foram medidos.", "Your schedule, today's doses and a week's record": "Seus horários, as doses de hoje e o registro da semana", - "Your workout is still recording. Finish it now, or keep recording?": "Seu treino ainda está sendo gravado. Finalizar agora ou continuar gravando?" + "Your skin temperature last night compared with your usual. A rise of half a degree or more can come with illness, a hard training load, alcohol or the menstrual cycle.": "Sua temperatura da pele na noite passada comparada com o seu habitual. Um aumento de meio grau ou mais pode acompanhar doença, treino pesado, álcool ou o ciclo menstrual.", + "Your sleep duration and stage balance were strong. Deep sleep looked supportive, which helped keep the overall score high.": "A duração do sono e o equilíbrio entre os estágios foram ótimos. O sono profundo ajudou, o que manteve a pontuação geral alta.", + "Your sleep was in a workable range, with the score shaped mostly by duration and stage balance. Deep and light sleep were readable enough to give a useful recovery snapshot.": "Seu sono ficou numa faixa razoável, com a pontuação definida principalmente pela duração e pelo equilíbrio dos estágios. O sono profundo e o leve foram legíveis o bastante para dar um bom retrato da recuperação.", + "Your usual {0}-day cycle would have ended {1} day{2} ago.": "Seu ciclo habitual de {0} dias teria terminado há {1} dia{2}.", + "Your week at a glance": "Sua semana num relance", + "Your workout is still recording. Finish it now, or keep recording?": "Seu treino ainda está sendo gravado. Finalizar agora ou continuar gravando?", + "a {0} fits.": "cabe um(a) {0}.", + "above": "acima", + "any meal": "qualquer refeição", + "avg {0} bpm": "média {0} bpm", + "below": "abaixo", + "daily calories": "calorias diárias", + "daily calories {0} kcal": "calorias diárias {0} kcal", + "day": "dia", + "days": "dias", + "down": "a menos", + "goal {0}": "meta {0}", + "higher": "maior", + "hour": "hora", + "hours": "horas", + "kg": "kg", + "lb": "lb", + "less": "menos", + "lower": "menor", + "more": "mais", + "night": "noite", + "nights": "noites", + "no overlap": "sem sobreposição", + "not chosen": "não escolhido", + "of {0} this week": "de {0} esta semana", + "resting HR {0}{1}": "HR em repouso {0}{1}", + "resting heart rate {0} bpm {1}": "frequência cardíaca em repouso {0} bpm {1}", + "resting heart rate {0}{1} bpm": "frequência cardíaca em repouso {0}{1} bpm", + "retiring {0}": "sai de linha em {0}", + "ring {0}": "anel {0}", + "score {0}": "pontuação {0}", + "sleep {0} h": "sono {0} h", + "sleep {0}{1} min": "sono {0}{1} min", + "steps {0} a day": "passos {0} por dia", + "unknown error": "erro desconhecido", + "up": "a mais", + "workout": "treino", + "workouts": "treinos", + "workouts a week": "treinos por semana", + "your limit of {0}": "seu limite de {0}", + "{0} % of {1} min on the same stage": "{0} % de {1} min no mesmo estágio", + "{0} / week": "{0} / semana", + "{0} awake during the night": "{0} acordado durante a noite", + "{0} bpm above your usual {1}": "{0} bpm acima do seu habitual de {1}", + "{0} bpm avg": "{0} bpm média", + "{0} bpm below your usual {1}": "{0} bpm abaixo do seu habitual de {1}", + "{0} bpm lower over two weeks than the four before. Often a sign of improving fitness or recovery.": "{0} bpm mais baixa nas últimas duas semanas que nas quatro anteriores. Muitas vezes é sinal de melhora do condicionamento ou da recuperação.", + "{0} bpm over the last 3 nights against your usual {1}. Illness, alcohol, stress, heat or hard training can all raise it.": "{0} bpm nas últimas 3 noites contra seu habitual de {1}. Doença, álcool, estresse, calor ou treino pesado podem elevá-la.", + "{0} burned": "{0} queimadas", + "{0} by {1}: latest {2} {3}, range {4}–{5} {6}, {7} points": "{0} por {1}: último {2} {3}, faixa {4}–{5} {6}, {7} pontos", + "{0} cal": "{0} cal", + "{0} complete": "{0} concluído", + "{0} confidence": "Confiança {0}", + "{0} days": "{0} dias", + "{0} days left": "Faltam {0} dias", + "{0} doesn't list “{1}” any more — it may have been retired. Pick another model.": "{0} não lista mais “{1}” — ele pode ter sido descontinuado. Escolha outro modelo.", + "{0} drinks this week": "{0} bebidas esta semana", + "{0} drink{1}": "{0} bebida{1}", + "{0} dry days in a row": "{0} dias seguidos sem álcool", + "{0} dry day{1} so far": "{0} dia{1} sem álcool até agora", + "{0} g protein": "{0} g de proteína", + "{0} has synced it in the morning.": "{0} a sincroniza pela manhã.", + "{0} in · {1} out": "{0} entrada · {1} saída", + "{0} inactive {1} since {2}:00": "{0} {1} sem se mexer desde as {2}:00", + "{0} is retiring this model on {1}.": "{0} vai descontinuar este modelo em {1}.", + "{0} left this week": "Restam {0} esta semana", + "{0} min a night less than your usual over the last 7 nights.": "{0} min por noite a menos que o seu habitual nas últimas 7 noites.", + "{0} min a night more than your usual over the last 7 nights.": "{0} min por noite a mais que o seu habitual nas últimas 7 noites.", + "{0} min {1} sleep": "{0} min de sono {1}", + "{0} ml at {1}% · about {2} kcal": "{0} ml a {1}% · cerca de {2} kcal", + "{0} more dry day{1} to reach {2}": "Mais {0} dia{1} sem álcool para chegar a {2}", + "{0} more — type to narrow": "Mais {0} — digite para filtrar", + "{0} ms over the last 3 nights against your usual {1} ({2}%). Your body may be under extra load.": "{0} ms nas últimas 3 noites contra seu habitual de {1} ({2}%). Seu corpo pode estar sob carga extra.", + "{0} of 7 active days": "{0} de 7 dias ativos", + "{0} of exercise in the last 7 days": "{0} de exercício nos últimos 7 dias", + "{0} of {1} dry days": "{0} de {1} dias sem álcool", + "{0} of {1} dry days; a fresh week starts Monday": "{0} de {1} dias sem álcool; uma nova semana começa na segunda", + "{0} of {1} goal": "{0} de {1} da meta", + "{0} of {1} heart-rate readings from {2} match your ring exactly. ": "{0} de {1} leituras de frequência cardíaca de {2} coincidem exatamente com seu anel. ", + "{0} of {1} heart-rate samples match your ring exactly. This looks like PulseLoop's own data coming back — check that the app syncs from your watch only, not from Health Connect.": "{0} de {1} amostras de frequência cardíaca batem exatamente com o seu anel. Parecem ser dados do próprio PulseLoop voltando — confira se o app sincroniza só do seu relógio, não do Health Connect.", + "{0} of {1} nights tracked": "{0} de {1} noites registradas", + "{0} of {1} tracked": "{0} de {1} registrados", + "{0} over your limit": "{0} acima do seu limite", + "{0} packets captured": "{0} pacotes capturados", + "{0} pts": "{0} pts", + "{0} recent": "{0} recentes", + "{0} rest {1} in the last 7": "{0} {1} de descanso nos últimos 7", + "{0} rows": "{0} linhas", + "{0} samples, {1} · latest {2} · arrives ~{3} late": "{0} amostras, {1} · última {2} · chega com ~{3} de atraso", + "{0} steps": "{0} passos", + "{0} steps at {1}.": "{0} passos às {1}.", + "{0} steps to your goal.": "Faltam {0} passos para sua meta.", + "{0} steps today. {1} Time to start winding down.": "{0} passos hoje. {1} Hora de começar a relaxar.", + "{0} unavailable": "{0} indisponível", + "{0} via Health Connect": "{0} via Health Connect", + "{0} vs {1}, until {2}.": "{0} vs {1}, até {2}.", + "{0} workouts a week": "{0} treinos por semana", + "{0} years": "{0} anos", + "{0} {1} in the last 7 days": "{0} {1} nos últimos 7 dias", + "{0} · ring {1} · {2} {3}": "{0} · anel {1} · {2} {3}", + "{0} · {1} drink": "{0} · {1} bebida", + "{0} · {1} readings · {2} on average": "{0} · {1} leituras · {2} em média", + "{0} – {1} leaves tonight's totals and the hypnogram, and it won't come back on re-sync.": "{0} – {1} sai dos totais desta noite e do hipnograma, e não volta numa nova sincronização.", + "{0}% above your usual {1} ms": "{0}% acima do seu habitual de {1} ms", + "{0}% below your usual {1} ms": "{0}% abaixo do seu habitual de {1} ms", + "{0}% higher over two weeks than the four before.": "{0}% mais alta nas últimas duas semanas que nas quatro anteriores.", + "{0}% of the night asleep": "{0}% da noite dormindo", + "{0}% {1} baseline": "{0}% {1} da linha de base", + "{0}, higher than your usual {1}": "{0}, acima do seu habitual de {1}", + "{0}, lower than your usual {1}": "{0}, abaixo do seu habitual de {1}", + "{0}. Open PulseLoop to mark it taken or skipped.": "{0}. Abra o PulseLoop para marcar como tomado ou pulado.", + "{0}: latest {1}, range {2}–{3}, {4} readings": "{0}: última {1}, faixa {2}–{3}, {4} leituras", + "{0}d ago": "há {0}d", + "{0}h ago": "há {0}h", + "{0}m ago": "há {0}m", + "{0}{1} {2} in 90 days": "{0}{1} {2} em 90 dias", + "±{0}m · {1} pts": "±{0}m · {1} pts", + "−%.1f °C from your usual": "−%.1f °C em relação ao seu habitual", + "≈ {0} kcal · {1} g protein · leaves {2} kcal": "≈ {0} kcal · {1} g de proteína · sobram {2} kcal" } \ No newline at end of file diff --git a/app/src/main/java/com/pulseloop/notifications/CoachNotificationDataTrigger.kt b/app/src/main/java/com/pulseloop/notifications/CoachNotificationDataTrigger.kt index 01d3166c..522b19cf 100644 --- a/app/src/main/java/com/pulseloop/notifications/CoachNotificationDataTrigger.kt +++ b/app/src/main/java/com/pulseloop/notifications/CoachNotificationDataTrigger.kt @@ -1,7 +1,5 @@ package com.pulseloop.notifications -import com.pulseloop.ui.i18n.tr - import android.content.Context import com.pulseloop.ring.PulseEvent import com.pulseloop.ring.PulseEventBus diff --git a/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt b/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt index 02b223c1..79cd5d6a 100644 --- a/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt +++ b/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt @@ -144,8 +144,7 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork // Drinks, for users who track them: the week that is ending, in one line. val drinks = if (com.pulseloop.service.DrinkPrefs.enabled) runCatching { val d = com.pulseloop.service.DrinksRepository.load(db, now, zone) - trf(" Drinks: {0} of {1}, ", com.pulseloop.service.DrinkInsights.fmt(d.week.standardDrinks), com.pulseloop.service.DrinkInsights.fmt(d.weeklyLimit)) + - trf("{0} dry day{1}.", d.week.dryDays, if (d.week.dryDays == 1) "" else "s") + trf(" Drinks: {0} of {1}, {2} dry day{3}.", com.pulseloop.service.DrinkInsights.fmt(d.week.standardDrinks), com.pulseloop.service.DrinkInsights.fmt(d.weeklyLimit), d.week.dryDays, if (d.week.dryDays == 1) "" else "s") }.getOrNull().orEmpty() else "" val body = report + drinks notify(ctx, ID_WEEKLY, title, body) @@ -269,7 +268,7 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED - @android.annotation.SuppressLint(tr("MissingPermission")) // checked by canNotify before every call + @android.annotation.SuppressLint("MissingPermission") // checked by canNotify before every call private fun notify(context: Context, id: Int, title: String, body: String, openMealLog: Boolean = false) { val intent = Intent(context, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK diff --git a/app/src/main/java/com/pulseloop/service/Readiness.kt b/app/src/main/java/com/pulseloop/service/Readiness.kt index 94dad430..bbfceed4 100644 --- a/app/src/main/java/com/pulseloop/service/Readiness.kt +++ b/app/src/main/java/com/pulseloop/service/Readiness.kt @@ -514,7 +514,7 @@ object ReadinessCopy { const val LOW_COVERAGE = 0.6 - const val DERIVED_FOOTER = + val DERIVED_FOOTER: String get() = tr("Readiness is estimated by PulseLoop from your ring's sleep, heart rate, HRV and activity, compared with your own recent nights. It is not a medical measurement.") /** What each contributor measures, for its detail sheet. */ 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 d41a1bb2..e4738d42 100644 --- a/app/src/main/java/com/pulseloop/ui/components/Charts.kt +++ b/app/src/main/java/com/pulseloop/ui/components/Charts.kt @@ -313,8 +313,7 @@ fun TrendChart( // 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) } ?: "") - trf("{0}: latest {1}, ", title ?: tr("Chart"), v(points.lastIndex)) + - trf("range {0}–{1}, {2} readings", valueFormatter(points.min()), valueFormatter(points.max()), points.size) + trf("{0}: latest {1}, range {2}–{3}, {4} readings", title ?: tr("Chart"), v(points.lastIndex), valueFormatter(points.min()), valueFormatter(points.max()), points.size) } Column(modifier = modifier) { diff --git a/app/src/main/java/com/pulseloop/ui/components/MetricThresholds.kt b/app/src/main/java/com/pulseloop/ui/components/MetricThresholds.kt index 882695f7..0a6168d4 100644 --- a/app/src/main/java/com/pulseloop/ui/components/MetricThresholds.kt +++ b/app/src/main/java/com/pulseloop/ui/components/MetricThresholds.kt @@ -1,7 +1,5 @@ package com.pulseloop.ui.components -import com.pulseloop.ui.i18n.tr - import androidx.compose.ui.graphics.Color import com.pulseloop.ring.MeasurementKind import com.pulseloop.ui.theme.MetricColors @@ -70,10 +68,10 @@ object MetricThresholdTable { higherIsBetter = false, unitLabel = "bpm", zones = listOf( - ThresholdZone(tr("Low"), 40.0, 50.0, MetricColors.ZoneLow), - ThresholdZone(tr("Good"), 50.0, 90.0, MetricColors.ZoneGood), - ThresholdZone(tr("Elevated"), 90.0, 120.0, MetricColors.ZoneBorderline), - ThresholdZone(tr("High"), 120.0, 140.0, MetricColors.ZoneConcern), + ThresholdZone("Low", 40.0, 50.0, MetricColors.ZoneLow), + ThresholdZone("Good", 50.0, 90.0, MetricColors.ZoneGood), + ThresholdZone("Elevated", 90.0, 120.0, MetricColors.ZoneBorderline), + ThresholdZone("High", 120.0, 140.0, MetricColors.ZoneConcern), ), ) @@ -82,9 +80,9 @@ object MetricThresholdTable { higherIsBetter = true, unitLabel = "%", zones = listOf( - ThresholdZone(tr("Concerning"), 85.0, 90.0, MetricColors.ZoneConcern), - ThresholdZone(tr("Low"), 90.0, 95.0, MetricColors.ZoneBorderline), - ThresholdZone(tr("Good"), 95.0, 100.0, MetricColors.ZoneGood), + ThresholdZone("Concerning", 85.0, 90.0, MetricColors.ZoneConcern), + ThresholdZone("Low", 90.0, 95.0, MetricColors.ZoneBorderline), + ThresholdZone("Good", 95.0, 100.0, MetricColors.ZoneGood), ), ) @@ -93,10 +91,10 @@ object MetricThresholdTable { higherIsBetter = false, unitLabel = "", zones = listOf( - ThresholdZone(tr("Relaxed"), 0.0, 30.0, MetricColors.ZoneGood), - ThresholdZone(tr("Normal"), 30.0, 60.0, MetricColors.ZoneNormal), - ThresholdZone(tr("Moderate"), 60.0, 80.0, MetricColors.ZoneBorderline), - ThresholdZone(tr("High"), 80.0, 100.0, MetricColors.ZoneConcern), + ThresholdZone("Relaxed", 0.0, 30.0, MetricColors.ZoneGood), + ThresholdZone("Normal", 30.0, 60.0, MetricColors.ZoneNormal), + ThresholdZone("Moderate", 60.0, 80.0, MetricColors.ZoneBorderline), + ThresholdZone("High", 80.0, 100.0, MetricColors.ZoneConcern), ), ) @@ -105,10 +103,10 @@ object MetricThresholdTable { higherIsBetter = false, unitLabel = "", zones = listOf( - ThresholdZone(tr("Relaxed"), 0.0, 30.0, MetricColors.ZoneGood), - ThresholdZone(tr("Normal"), 30.0, 60.0, MetricColors.ZoneNormal), - ThresholdZone(tr("Moderate"), 60.0, 80.0, MetricColors.ZoneBorderline), - ThresholdZone(tr("High"), 80.0, 100.0, MetricColors.ZoneConcern), + ThresholdZone("Relaxed", 0.0, 30.0, MetricColors.ZoneGood), + ThresholdZone("Normal", 30.0, 60.0, MetricColors.ZoneNormal), + ThresholdZone("Moderate", 60.0, 80.0, MetricColors.ZoneBorderline), + ThresholdZone("High", 80.0, 100.0, MetricColors.ZoneConcern), ), ) @@ -117,9 +115,9 @@ object MetricThresholdTable { higherIsBetter = true, unitLabel = "ms", zones = listOf( - ThresholdZone(tr("Low"), 0.0, 20.0, MetricColors.ZoneConcern), - ThresholdZone(tr("Below avg"), 20.0, 50.0, MetricColors.ZoneBorderline), - ThresholdZone(tr("Good"), 50.0, 120.0, MetricColors.ZoneGood), + ThresholdZone("Low", 0.0, 20.0, MetricColors.ZoneConcern), + ThresholdZone("Below avg", 20.0, 50.0, MetricColors.ZoneBorderline), + ThresholdZone("Good", 50.0, 120.0, MetricColors.ZoneGood), ), ) @@ -128,9 +126,9 @@ object MetricThresholdTable { higherIsBetter = null, // personal / relative unitLabel = "°C", zones = listOf( - ThresholdZone(tr("Low"), 28.0, 31.0, MetricColors.ZoneLow), - ThresholdZone(tr("Normal"), 31.0, 36.0, MetricColors.ZoneGood), - ThresholdZone(tr("Elevated"), 36.0, 38.0, MetricColors.ZoneBorderline), + ThresholdZone("Low", 28.0, 31.0, MetricColors.ZoneLow), + ThresholdZone("Normal", 31.0, 36.0, MetricColors.ZoneGood), + ThresholdZone("Elevated", 36.0, 38.0, MetricColors.ZoneBorderline), ), ) @@ -139,10 +137,10 @@ object MetricThresholdTable { higherIsBetter = false, unitLabel = "mmHg", zones = listOf( - ThresholdZone(tr("Normal"), 80.0, 120.0, MetricColors.ZoneGood), - ThresholdZone(tr("Elevated"), 120.0, 130.0, MetricColors.ZoneBorderline), - ThresholdZone(tr("Stage 1"), 130.0, 140.0, MetricColors.ZoneElevated), - ThresholdZone(tr("High"), 140.0, 180.0, MetricColors.ZoneConcern), + ThresholdZone("Normal", 80.0, 120.0, MetricColors.ZoneGood), + ThresholdZone("Elevated", 120.0, 130.0, MetricColors.ZoneBorderline), + ThresholdZone("Stage 1", 130.0, 140.0, MetricColors.ZoneElevated), + ThresholdZone("High", 140.0, 180.0, MetricColors.ZoneConcern), ), ) @@ -151,10 +149,10 @@ object MetricThresholdTable { higherIsBetter = false, unitLabel = "mg/dL", zones = listOf( - ThresholdZone(tr("Low"), 50.0, 70.0, MetricColors.ZoneLow), - ThresholdZone(tr("Normal"), 70.0, 100.0, MetricColors.ZoneGood), - ThresholdZone(tr("Elevated"), 100.0, 126.0, MetricColors.ZoneBorderline), - ThresholdZone(tr("High"), 126.0, 200.0, MetricColors.ZoneConcern), + ThresholdZone("Low", 50.0, 70.0, MetricColors.ZoneLow), + ThresholdZone("Normal", 70.0, 100.0, MetricColors.ZoneGood), + ThresholdZone("Elevated", 100.0, 126.0, MetricColors.ZoneBorderline), + ThresholdZone("High", 126.0, 200.0, MetricColors.ZoneConcern), ), ) } @@ -171,28 +169,28 @@ fun bpZone(sys: Double?, dia: Double?): ThresholdZone? { // Diastolic category val diaZone = when { dia == null -> null - dia < 80.0 -> tr("Normal") - dia < 90.0 -> tr("Stage1") - else -> tr("High") + dia < 80.0 -> "Normal" + dia < 90.0 -> "Stage1" + else -> "High" } // Systolic category val sysZone = when { sys == null -> null - sys < 120.0 -> tr("Normal") - sys < 130.0 -> tr("Elevated") - sys < 140.0 -> tr("Stage1") - else -> tr("High") + sys < 120.0 -> "Normal" + sys < 130.0 -> "Elevated" + sys < 140.0 -> "Stage1" + else -> "High" } // Pick the worse category (ordered Normal < Elevated < Stage1 < High) val worst = when { - sysZone == "High" || diaZone == "High" -> tr("High") - sysZone == "Stage1" || diaZone == "Stage1" -> tr("Stage1") - sysZone == "Elevated" -> tr("Elevated") - sysZone == "Normal" && diaZone == "Normal"-> tr("Normal") - diaZone == "Normal" && sysZone == null -> tr("Normal") - sysZone == "Normal" && diaZone == null -> tr("Normal") + sysZone == "High" || diaZone == "High" -> "High" + sysZone == "Stage1" || diaZone == "Stage1" -> "Stage1" + sysZone == "Elevated" -> "Elevated" + sysZone == "Normal" && diaZone == "Normal"-> "Normal" + diaZone == "Normal" && sysZone == null -> "Normal" + sysZone == "Normal" && diaZone == null -> "Normal" else -> null } 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 631ef656..31cb0f42 100644 --- a/app/src/main/java/com/pulseloop/ui/components/ZoneLineChart.kt +++ b/app/src/main/java/com/pulseloop/ui/components/ZoneLineChart.kt @@ -89,8 +89,7 @@ fun ZoneLineChart( val summary = remember(samples, label) { val values = samples.map { it.value } val fmt = if (values.all { it % 1.0 == 0.0 }) "%.0f" else "%.1f" - trf("{0}: latest {1}, ", label ?: tr("Trend"), fmt.format(values.last())) + - trf("range {0}–{1}, {2} readings", fmt.format(values.min()), fmt.format(values.max()), values.size) + trf("{0}: latest {1}, range {2}–{3}, {4} readings", label ?: tr("Trend"), fmt.format(values.last()), fmt.format(values.min()), fmt.format(values.max()), values.size) } Column(modifier.fillMaxWidth().semantics { contentDescription = summary }) { diff --git a/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt b/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt index f3217533..20ee4a67 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt @@ -298,8 +298,7 @@ private fun ResumeCard(check: AccuracyCheckEntity, scope: kotlinx.coroutines.Cor Text(tr("Check finished: resume Health Connect export"), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) Text(AccuracyUiText.endReason(check) + " ${AccuracyUiText.span(check)}.", fontSize = 13.sp, color = PulseColors.textSecondary) Text( - trf("During the check, {0} wrote the same types to Health Connect. Exporting the ring's copy ", check.referenceLabel) + - "of those days now would count them twice.", + trf("During the check, {0} wrote the same types to Health Connect. Exporting the ring's copy of those days now would count them twice.", check.referenceLabel), fontSize = 12.sp, color = PulseColors.textMuted, ) Button(onClick = { @@ -351,8 +350,7 @@ private fun StartDialog( } } Text( - trf("Compared: {0}. These stop exporting to Health Connect until the check ends ", AccuracyUiText.units(units)) + - "and you choose what to do with those days.", + trf("Compared: {0}. These stop exporting to Health Connect until the check ends and you choose what to do with those days.", AccuracyUiText.units(units)), fontSize = 12.sp, ) Text(tr("Wear both devices as you normally would, including at night."), fontSize = 12.sp) @@ -381,8 +379,7 @@ private fun SourceCard(context: Context, s: ReferenceSourceSurvey, onUse: (() -> ) s.echo?.takeIf { it.looksLikeEcho }?.let { Text( - trf("{0} of {1} heart-rate samples match your ring exactly. This looks like PulseLoop's own ", it.matching, it.compared) + - "data coming back — check that the app syncs from your watch only, not from Health Connect.", + trf("{0} of {1} heart-rate samples match your ring exactly. This looks like PulseLoop's own data coming back — check that the app syncs from your watch only, not from Health Connect.", it.matching, it.compared), fontSize = 12.sp, color = PulseColors.danger, ) } @@ -397,8 +394,7 @@ private fun MetricRow(m: MetricSurvey) { Column(Modifier.fillMaxWidth().padding(top = 4.dp)) { Text(m.metric.label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) Text( - trf("{0} samples, {1} · latest {2} · ", m.sampleCount, ReferenceSurveyText.cadence(m), last) + - trf("arrives ~{0} late", ReferenceSurveyText.duration(m.medianDeliveryDelayMs)), + trf("{0} samples, {1} · latest {2} · arrives ~{3} late", m.sampleCount, ReferenceSurveyText.cadence(m), last, ReferenceSurveyText.duration(m.medianDeliveryDelayMs)), fontSize = 12.sp, color = PulseColors.textSecondary, ) if (m.metric == ReferenceMetric.SLEEP) { diff --git a/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt b/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt index 71e0114b..0392bbb5 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt @@ -124,8 +124,7 @@ internal fun AccuracyReportSection( }) { Text(tr("Share")) } } Text( - trf("How your ring compares with {0}, the device you chose to trust. This is agreement between two ", check.referenceLabel) + - "consumer devices, not a lab measurement.", + trf("How your ring compares with {0}, the device you chose to trust. This is agreement between two consumer devices, not a lab measurement.", check.referenceLabel), fontSize = 12.sp, color = PulseColors.textMuted, ) if (echo?.looksLikeEcho == true) { @@ -138,8 +137,7 @@ internal fun AccuracyReportSection( } if (waitingDays > 0) { Text( - trf("Waiting for {0} to deliver {1} day{2}. Open the app ", check.referenceLabel, waitingDays, if (waitingDays == 1) "" else "s") + - "that syncs it to send it sooner; otherwise those days are scored 24 hours after they end.", + trf("Waiting for {0} to deliver {1} day{2}. Open the app that syncs it to send it sooner; otherwise those days are scored 24 hours after they end.", check.referenceLabel, waitingDays, if (waitingDays == 1) "" else "s"), fontSize = 12.sp, color = PulseColors.warning, ) } @@ -221,8 +219,7 @@ private fun MetricCard( if (m.kind != ComparisonMetric.Kind.STAGES && summary.validDays > 0) { val (lo, hi) = summary.limits Text( - trf("Average difference {0}; 95 % of differences between ", AccuracyReportText.signed(m, summary.bias)) + - trf("{0} and {1}", AccuracyReportText.signed(m, lo), AccuracyReportText.signed(m, hi)) + + trf("Average difference {0}; 95 % of differences between {1} and {2}", AccuracyReportText.signed(m, summary.bias), AccuracyReportText.signed(m, lo), AccuracyReportText.signed(m, hi)) + if (m.kind == ComparisonMetric.Kind.PAIRED) trf(" ({0} matched readings).", summary.pairs) else ".", fontSize = 12.sp, color = PulseColors.textMuted, ) 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 6a7e9ff4..3b0851e8 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/BodyUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/BodyUi.kt @@ -157,8 +157,7 @@ private fun WeightLine(points: List, units: UnitSystem) { val t1 = points.last().measuredAt val unit = UnitConverter.weightUnit(units) fun shown(kg: Double) = "%.1f".format(UnitConverter.weight(kg, units)) - val summary = trf("Weight, last 90 days: latest {0} {1}, ", shown(points.last().value), unit) + - trf("range {0}–{1} {2}, {3} weigh-ins", shown(min), shown(max), unit, points.size) + val summary = trf("Weight, last 90 days: latest {0} {1}, range {2}–{3} {4}, {5} weigh-ins", shown(points.last().value), unit, shown(min), shown(max), unit, points.size) 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 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 f9bea8d2..6d34ace3 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt @@ -659,9 +659,7 @@ object MealAnalysisLogic { val systemPrompt: String = "You are a nutrition estimator. Given a meal description and/or photo, " + "identify the food and estimate total calories and macros for the portion shown or described. " + - tr("Be realistic about portion sizes; state your assumptions (portion sizes, preparation) briefly. " + - "Use confidence \"high\" only for clearly identifiable, standard portions. " + - "Return only JSON matching the schema.") + tr("Be realistic about portion sizes; state your assumptions (portion sizes, preparation) briefly. Use confidence \"high\" only for clearly identifiable, standard portions. Return only JSON matching the schema.") /** * The verbatim strict meal_estimate json_schema (MealAnalysisSheet.swift:344-362), built 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 d1d767d8..0c6514e0 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt @@ -376,8 +376,7 @@ private fun Legend(color: Color, label: String) { fun HeartRateContextChart(samples: List, sleep: List, workouts: List) { val sorted = remember(samples) { samples.sortedBy { it.timestampMs } } val summary = remember(sorted) { - trf("Heart rate since last night: latest {0} bpm, ", sorted.last().value.roundToInt()) + - trf("range {0}–{1} bpm, {2} readings", sorted.minOf { it.value }.roundToInt(), sorted.maxOf { it.value }.roundToInt(), sorted.size) + trf("Heart rate since last night: latest {0} bpm, range {1}–{2} bpm, {3} readings", sorted.last().value.roundToInt(), sorted.minOf { it.value }.roundToInt(), sorted.maxOf { it.value }.roundToInt(), sorted.size) } Canvas(Modifier.fillMaxWidth().height(90.dp).semantics { contentDescription = summary }) { val t0 = sorted.first().timestampMs; val t1 = sorted.last().timestampMs.coerceAtLeast(t0 + 1) @@ -453,8 +452,7 @@ private fun TrendsSection(db: PulseLoopDatabase) { else -> { val shown = pts.takeLast(if (period == Trends.Period.DAY) 30 else 26) val fmt = if (metric == TrendMetric.TEMPERATURE || metric == TrendMetric.SLEEP || metric == TrendMetric.WEIGHT) "%.1f" else "%.0f" - val summary = trf("{0} by {1}: latest {2} {3}, ", metric.label, period.label.lowercase(), fmt.format(shown.last().value), metric.unit) + - trf("range {0}–{1} {2}, {3} points", fmt.format(shown.minOf { it.value }), fmt.format(shown.maxOf { it.value }), metric.unit, shown.size) + val summary = trf("{0} by {1}: latest {2} {3}, range {4}–{5} {6}, {7} points", metric.label, period.label.lowercase(), fmt.format(shown.last().value), metric.unit, fmt.format(shown.minOf { it.value }), fmt.format(shown.maxOf { it.value }), metric.unit, shown.size) 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)) 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 2d096085..b14b6a66 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/Screens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/Screens.kt @@ -1204,8 +1204,7 @@ private fun zoneRangeText( private fun metricDisclaimer(metric: String, isDerived: Boolean): String? = when { metric == "stress" && isDerived -> tr("Estimated from HRV — your ring doesn't measure stress. Scored against your own recent " + - tr("HRV readings, so it says how this reading compares with your normal, not how you compare " + - "with anyone else.")) + tr("HRV readings, so it says how this reading compares with your normal, not how you compare with anyone else.")) metric == "glucose" -> tr("Estimated wellness metric — not for dosing or diabetes decisions. No smart ring or watch is " + tr("FDA-authorized to measure or estimate glucose on its own.")) 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 3eff61c7..d8315087 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt @@ -1891,8 +1891,7 @@ private fun QuietHoursCard() { tr("To log when Bedtime or Do Not Disturb turns on and off while PulseLoop is " + "in the background, Android requires Notification access. PulseLoop only " + "listens for Mode changes and does not read your notifications.\n\n" + - tr("If the switch is greyed out, open PulseLoop's App info, tap ⋮ → " + - tr("Allow restricted settings, then come back here."))), + tr("If the switch is greyed out, open PulseLoop's App info, tap ⋮ → Allow restricted settings, then come back here.")), ) }, confirmButton = { 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 803d980c..2ff79833 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt @@ -812,9 +812,7 @@ private fun SleepDurationHistogram( val summary = remember(bars, goalMin) { val tracked = bars.filter { it.present }.mapNotNull { it.durationMin } if (tracked.isEmpty()) tr("Nightly sleep: no nights tracked in this range") - else trf("Nightly sleep: latest {0}, ", SleepFormat.duration(tracked.last())) + - trf("range {0}–{1}, ", SleepFormat.duration(tracked.min()), SleepFormat.duration(tracked.max())) + - trf("{0} of {1} nights tracked", tracked.size, bars.size) + + else trf("Nightly sleep: latest {0}, range {1}–{2}, {3} of {4} nights tracked", SleepFormat.duration(tracked.last()), SleepFormat.duration(tracked.min()), SleepFormat.duration(tracked.max()), tracked.size, bars.size) + (goalMin?.takeIf { it > 0 }?.let { trf(", goal {0}", SleepFormat.duration(it)) } ?: "") } @@ -1145,8 +1143,7 @@ private fun SleepRecordsCard( title = { Text(tr("Delete this record?")) }, text = { Text( - "${SleepFormat.clockTime(run.startAt)} – ${SleepFormat.clockTime(run.endAt)} " + - "leaves tonight's totals and the hypnogram, and it won't come back on re-sync.", + trf("{0} – {1} leaves tonight's totals and the hypnogram, and it won't come back on re-sync.", SleepFormat.clockTime(run.startAt), SleepFormat.clockTime(run.endAt)), ) }, confirmButton = { @@ -1213,8 +1210,7 @@ private fun SleepRecordEditDialog( } if (pickedOutside) { Text( - trf("This record runs {0} – ", SleepFormat.clockTime(run.startAt)) + - trf("{0}. You can only shorten it.", SleepFormat.clockTime(run.endAt)), + trf("This record runs {0} – {1}. You can only shorten it.", SleepFormat.clockTime(run.startAt), SleepFormat.clockTime(run.endAt)), color = PulseColors.danger, fontSize = 12.sp, ) From cd9e7274edbdfbd1b524770039e781138dbea52e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 11:35:48 +0000 Subject: [PATCH 4/6] F*cking Health voice: language stacks, picker warning, coach persona (catalog to follow) Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- AGENTS.md | 20 +++++ app/src/main/assets/i18n/pt-BR.json | 5 ++ .../main/java/com/pulseloop/ui/i18n/L10n.kt | 85 ++++++++++++++----- .../ui/screens/LanguageSettingsScreen.kt | 63 +++++++++++--- .../ui/i18n/FuckingHealthCatalogTest.kt | 57 +++++++++++++ 5 files changed, 199 insertions(+), 31 deletions(-) create mode 100644 app/src/test/java/com/pulseloop/ui/i18n/FuckingHealthCatalogTest.kt diff --git a/AGENTS.md b/AGENTS.md index ae2164d4..9aa6d6b6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1054,3 +1054,23 @@ English up in `assets/i18n/pt-BR.json`, falling back to the English when there i value, or leave it English. Many still are; templates and service-layer text (insights, notifications) are the known gaps. - The coach answers in the app's language through `L10n.coachInstruction()`, appended to its prompts. + +## A voice is a catalog layered on a language — and it stops at anything serious + +**F*cking Health** (Settings → Language) is English with attitude: `AppLanguage.FUCKING_HEALTH_EN` +reads `assets/i18n/en-FH.json` first and falls back to the plain English key, and `Voice.FUNNY` +gives the coach and its notifications the persona through `L10n.coachInstruction()`. + +- **A voice rewrites only some strings, on purpose.** A missing entry shows plain English, which is + right for settings, units, metric names and anything technical. +- **Safety text is never rewritten.** Crisis lines, clinician/pharmacist advice, warnings, + disclaimers, pregnancy/postpartum, medication and alcohol-support text keep their plain wording; + `FuckingHealthCatalogTest` fails if one appears in the catalog. The coach drops the act for the + same topics (`FUNNY_VOICE`). +- **The joke wraps the content.** Same facts, same values (`{0}` placeholders), same advice. + Roast habits, never the person. Swearing is censored (`f*cking`), and the test checks that too. +- **Adding the Portuguese version** is one enum entry and one file: `FUCKING_HEALTH_PT` with + `localeTag = "pt-BR"` and `catalogs = listOf("i18n/pt-BR-FH.json", "i18n/pt-BR.json")`, so a + string the Portuguese voice doesn't rewrite reads as plain Portuguese. Write the catalog in + Brazilian Portuguese (Brazilian censored swearing: p*rra, c*ralho, m*rda), not as a translation + of the English jokes, and extend `FuckingHealthCatalogTest` to cover it. diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index 785fcd79..741cb93c 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -249,6 +249,7 @@ "Breathe in": "Inspire", "Breathe out": "Expire", "Breathing sessions this week": "Sessões de respiração nesta semana", + "Bring it on": "Manda ver", "Building a picture from your data": "Montando um retrato a partir dos seus dados", "Building baseline": "Criando linha de base", "Building momentum": "Ganhando ritmo", @@ -471,6 +472,7 @@ "Ended early: a different ring was paired.": "Encerrado antes do previsto: outro anel foi pareado.", "Ends": "Termina", "Energy and sleep can dip; resting heart rate is often at its lowest.": "Energia e sono podem cair; a frequência cardíaca em repouso costuma estar no ponto mais baixo.", + "English, with attitude. Strong language.": "Em inglês, com atitude. Linguagem forte.", "Enter a recent lab/meter reading (mg/dL) to offset the displayed value to match.": "Informe uma leitura recente de laboratório/medidor (mg/dL) para ajustar o valor exibido.", "Enter a valid mg/dL reading": "Insira uma leitura válida em mg/dL", "Enter a weight between {0} and {1} {2}.": "Informe um peso entre {0} e {1} {2}.", @@ -852,6 +854,7 @@ "Needs care": "Requer atenção", "Needs work": "Precisa melhorar", "Never": "Nunca", + "Never mind": "Deixa pra lá", "New chat": "Nova conversa", "Next": "Próximo", "Next day": "Próximo dia", @@ -1294,6 +1297,7 @@ "Stressful": "Estressante", "Stressful day": "Dia estressante", "Strong": "Forte", + "Strong language ahead": "Palavrões à vista", "Strong recovery signal": "Sinal forte de recuperação", "Stronger signs in your biometrics of something straining your body.": "Sinais fortes nos seus dados biométricos de algo sobrecarregando seu corpo.", "Studio, cardio, or freestyle": "Aula, cardio ou livre", @@ -1689,6 +1693,7 @@ "{0} steps at {1}.": "{0} passos às {1}.", "{0} steps to your goal.": "Faltam {0} passos para sua meta.", "{0} steps today. {1} Time to start winding down.": "{0} passos hoje. {1} Hora de começar a relaxar.", + "{0} swears, grumbles and judges your habits — the coach too. The numbers stay exactly as accurate, and anything serious is said plainly. If you easily get offended, maybe stick with the boring version.": "{0} xinga, resmunga e julga seus hábitos — o coach também. Os números continuam exatamente tão precisos, e tudo o que é sério é dito com clareza. Se você se ofende fácil, talvez seja melhor ficar com a versão sem graça.", "{0} unavailable": "{0} indisponível", "{0} via Health Connect": "{0} via Health Connect", "{0} vs {1}, until {2}.": "{0} vs {1}, até {2}.", diff --git a/app/src/main/java/com/pulseloop/ui/i18n/L10n.kt b/app/src/main/java/com/pulseloop/ui/i18n/L10n.kt index 92b4301a..1c80c4ac 100644 --- a/app/src/main/java/com/pulseloop/ui/i18n/L10n.kt +++ b/app/src/main/java/com/pulseloop/ui/i18n/L10n.kt @@ -9,17 +9,38 @@ import androidx.compose.runtime.setValue import org.json.JSONObject import java.util.Locale -/** The languages PulseLoop speaks. [SYSTEM] follows the phone. */ -enum class AppLanguage(val key: String, val label: String) { - SYSTEM("system", "System default"), - ENGLISH("en", "English"), - PORTUGUESE("pt-BR", "Português (Brasil)"), +/** How the app talks: plainly, or like F*cking Health (sarcastic, grumbling, censored swearing). */ +enum class Voice { PLAIN, FUNNY } + +/** + * The languages PulseLoop speaks, each a locale, a stack of catalogs and a [Voice]. A lookup takes + * the first catalog that has the English key, then falls back to the English itself, so a voice + * layers on top of its language: F*cking Health in Portuguese would be + * `listOf("i18n/pt-BR-FH.json", "i18n/pt-BR.json")`, and any string it doesn't rewrite reads as + * plain Portuguese. [SYSTEM] follows the phone. + */ +enum class AppLanguage( + val key: String, + val label: String, + val localeTag: String?, + val catalogs: List, + val voice: Voice = Voice.PLAIN, + /** Shown under the option in the picker. */ + val caption: String? = null, +) { + SYSTEM("system", "System default", null, emptyList()), + ENGLISH("en", "English", "en", emptyList()), + PORTUGUESE("pt-BR", "Português (Brasil)", "pt-BR", listOf("i18n/pt-BR.json")), + FUCKING_HEALTH_EN( + "fh-en", "F*cking Health", "en", listOf("i18n/en-FH.json"), Voice.FUNNY, + caption = "English, with attitude. Strong language.", + ), } /** * The app's language (Settings → Language). The UI is written in English, and every displayed - * literal goes through [tr], which looks the English text up in the language's catalog - * (`assets/i18n/pt-BR.json`) and falls back to the English when a string has no entry yet. The + * literal goes through [tr], which looks the English text up in the language's catalogs + * (`assets/i18n/*.json`) and falls back to the English when a string has no entry yet. The * English text *is* the key, so a reworded string simply shows in English until it is translated * again. * @@ -31,7 +52,7 @@ object L10n { var language by mutableStateOf(AppLanguage.SYSTEM) private set - @Volatile private var catalog: Map = emptyMap() + @Volatile private var catalogs: List> = emptyList() private var appContext: Context? = null private var systemLocale: Locale = Locale.getDefault() @@ -53,16 +74,20 @@ object L10n { /** Whether the UI is currently in Portuguese (chosen, or the phone's language under [AppLanguage.SYSTEM]). */ val isPortuguese: Boolean get() = locale().language == "pt" - fun locale(): Locale = when (language) { - AppLanguage.ENGLISH -> Locale.ENGLISH - AppLanguage.PORTUGUESE -> Locale("pt", "BR") - AppLanguage.SYSTEM -> systemLocale + val voice: Voice get() = language.voice + + fun locale(): Locale = language.localeTag?.let { Locale.forLanguageTag(it) } ?: systemLocale + + /** The catalogs in force: the language's own, or under [AppLanguage.SYSTEM] the phone's language's. */ + private fun catalogPaths(): List = when { + language != AppLanguage.SYSTEM -> language.catalogs + systemLocale.language == "pt" -> AppLanguage.PORTUGUESE.catalogs + else -> emptyList() } private fun apply() { - val locale = locale() - Locale.setDefault(locale) - catalog = if (locale.language == "pt") load("i18n/pt-BR.json") else emptyMap() + Locale.setDefault(locale()) + catalogs = catalogPaths().map(::load) } private fun load(asset: String): Map = runCatching { @@ -73,14 +98,34 @@ object L10n { fun translate(en: String): String { @Suppress("UNUSED_VARIABLE") val l = language // read, so composition follows a change - return catalog[en] ?: en + for (c in catalogs) c[en]?.let { return it } + return en } /** Appended to the coach's prompts: the coach answers in the app's language. */ - fun coachInstruction(): String = - if (isPortuguese) "\n\nThe user's app is in Brazilian Portuguese. Always reply in Brazilian Portuguese (pt-BR), " + - "naturally and warmly, keeping metric names the app shows (HRV, SpO2) as they are." - else "" + fun coachInstruction(): String = buildString { + if (isPortuguese) append( + "\n\nThe user's app is in Brazilian Portuguese. Always reply in Brazilian Portuguese (pt-BR), " + + "naturally and warmly, keeping metric names the app shows (HRV, SpO2) as they are.", + ) + if (voice == Voice.FUNNY) append(FUNNY_VOICE) + } + + /** + * The F*cking Health voice for the coach and its notifications. The joke rides on top of the + * data; it never replaces it, and it stops at anything that could hurt someone. + */ + private const val FUNNY_VOICE = + "\n\nVOICE: The user picked \"F*cking Health\", the app's sarcastic, foul-mouthed persona. Talk like a " + + "grumpy best friend who happens to know physiology: blunt, funny, a bit theatrical, complaining about " + + "the numbers even when they're good. Swear, but censor it with asterisks the way the app does " + + "(f*cking, sh*t, WTF, damn). Short punchy sentences, rhetorical questions, the odd exclamation. " + + "The facts, numbers and advice must stay exactly as accurate and useful as in plain mode; the " + + "attitude is the wrapping, not the content. Roast the habits, never the person: no jokes about " + + "weight, body shape, age, gender, illness or appearance. Drop the act completely and be calm, kind " + + "and clear for anything serious: chest pain, fainting, shortness of breath, very high or low " + + "readings, pregnancy or postpartum health, medications, mental health or self-harm, eating " + + "disorders, alcohol dependence. If the user seems upset, stressed or asks you to stop, go plain." /** The Activity's context in the chosen language, so Android resources and system UI follow it. */ fun wrap(base: Context): Context { diff --git a/app/src/main/java/com/pulseloop/ui/screens/LanguageSettingsScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/LanguageSettingsScreen.kt index af906fc7..ef48eeab 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/LanguageSettingsScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/LanguageSettingsScreen.kt @@ -1,17 +1,23 @@ package com.pulseloop.ui.screens import android.app.Activity +import android.content.Context import androidx.compose.foundation.background import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.AlertDialog import androidx.compose.material3.RadioButton import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip @@ -20,13 +26,21 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.pulseloop.ui.i18n.AppLanguage import com.pulseloop.ui.i18n.L10n +import com.pulseloop.ui.i18n.Voice import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf import com.pulseloop.ui.theme.PulseColors -/** Settings → Language. Each option names itself in its own language, so anyone can find theirs. */ +/** + * Settings → Language. Each option names itself in its own language, so anyone can find theirs. + * A voice with strong language asks once before switching, the way F*cking Health's inspiration + * warns the easily offended. + */ @Composable fun LanguageSettingsScreen(onBack: () -> Unit) { val context = LocalContext.current + var confirming by remember { mutableStateOf(null) } + SettingsSubScreen(title = tr("Language"), onBack = onBack) { Column( Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card), @@ -34,20 +48,22 @@ fun LanguageSettingsScreen(onBack: () -> Unit) { AppLanguage.entries.forEach { lang -> Row( Modifier.fillMaxWidth().clickable { - if (lang != L10n.language) { - L10n.set(context, lang) - // Rebuild the Activity so dates, numbers and Android's own text follow too. - (context as? Activity)?.recreate() + when { + lang == L10n.language -> Unit + lang.voice == Voice.FUNNY -> confirming = lang + else -> switchTo(context, lang) } }.padding(horizontal = 12.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically, ) { RadioButton(selected = L10n.language == lang, onClick = null) - Text( - if (lang == AppLanguage.SYSTEM) tr("System default") else lang.label, - fontSize = 15.sp, color = PulseColors.textPrimary, - modifier = Modifier.padding(start = 12.dp), - ) + Column(Modifier.padding(start = 12.dp, top = 6.dp, bottom = 6.dp)) { + Text( + if (lang == AppLanguage.SYSTEM) tr("System default") else lang.label, + fontSize = 15.sp, color = PulseColors.textPrimary, + ) + lang.caption?.let { Text(tr(it), fontSize = 12.sp, color = PulseColors.textMuted) } + } } } } @@ -56,4 +72,29 @@ fun LanguageSettingsScreen(onBack: () -> Unit) { fontSize = 12.sp, color = PulseColors.textMuted, ) } + + confirming?.let { lang -> + AlertDialog( + onDismissRequest = { confirming = null }, + title = { Text(tr("Strong language ahead")) }, + text = { + Text( + trf( + "{0} swears, grumbles and judges your habits — the coach too. The numbers stay exactly as " + + "accurate, and anything serious is said plainly. If you easily get offended, maybe stick " + + "with the boring version.", + lang.label, + ), + ) + }, + confirmButton = { TextButton(onClick = { confirming = null; switchTo(context, lang) }) { Text(tr("Bring it on")) } }, + dismissButton = { TextButton(onClick = { confirming = null }) { Text(tr("Never mind")) } }, + ) + } +} + +private fun switchTo(context: Context, lang: AppLanguage) { + L10n.set(context, lang) + // Rebuild the Activity so dates, numbers and Android's own text follow too. + (context as? Activity)?.recreate() } diff --git a/app/src/test/java/com/pulseloop/ui/i18n/FuckingHealthCatalogTest.kt b/app/src/test/java/com/pulseloop/ui/i18n/FuckingHealthCatalogTest.kt new file mode 100644 index 00000000..59b69129 --- /dev/null +++ b/app/src/test/java/com/pulseloop/ui/i18n/FuckingHealthCatalogTest.kt @@ -0,0 +1,57 @@ +package com.pulseloop.ui.i18n + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.File + +/** + * The F*cking Health voice (assets/i18n/en-FH.json). The joke wraps the content, so every entry + * must keep its values and spacing, and the safety text must not be in it at all: an entry + * missing here means the plain wording shows, which is what crisis lines and warnings need. + */ +class FuckingHealthCatalogTest { + + private val catalog: Map = run { + val f = listOf("src/main/assets/i18n/en-FH.json", "app/src/main/assets/i18n/en-FH.json").map(::File).first { it.exists() } + Json.parseToJsonElement(f.readText()).jsonObject.mapValues { it.value.jsonPrimitive.content } + } + + @Test + fun `safety, medical and crisis text keeps its plain wording`() { + val serious = Regex( + "CVV|\\b188\\b|\\b192\\b|SAMU|emergenc|clinician|doctor|pharmacist|medical|contracept|pregnan|postpartum|" + + "self-harm|suicid|AUDIT|dependen|fever|crisis|Alcoólicos|CAPS|interaction|not a diagnosis", + RegexOption.IGNORE_CASE, + ) + val offenders = catalog.keys.filter { serious.containsMatchIn(it) } + assertTrue("rewritten safety text: $offenders", offenders.isEmpty()) + } + + @Test + fun `values, format specifiers and spacing survive the attitude`() { + val ph = Regex("\\{\\d+\\}") + val spec = Regex("%[0-9$,.]*[sdf]") + catalog.forEach { (en, fh) -> + assertEquals("placeholders: $en", ph.findAll(en).map { it.value }.sorted().toList(), ph.findAll(fh).map { it.value }.sorted().toList()) + assertEquals("specifiers: $en", spec.findAll(en).map { it.value }.sorted().toList(), spec.findAll(fh).map { it.value }.sorted().toList()) + assertEquals("leading space: $en", en.startsWith(" "), fh.startsWith(" ")) + assertEquals("trailing space: $en", en.endsWith(" "), fh.endsWith(" ")) + } + } + + @Test + fun `the swearing is censored`() { + val raw = Regex("\\b(fuck\\w*|shit\\w*|asshole|bitch\\w*|cunt|dick)\\b", RegexOption.IGNORE_CASE) + val uncensored = catalog.values.filter { raw.containsMatchIn(it) } + assertTrue("uncensored: ${uncensored.take(5)}", uncensored.isEmpty()) + } + + @Test + fun `the voice actually has a voice`() { + assertTrue(catalog.size > 300) + } +} From bef6bf9b01870ef3046451cfc4553e21619abee8 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 11:36:41 +0000 Subject: [PATCH 5/6] F*cking Health catalog: 460 lines of attitude, none on safety text Food-shaming lines were dropped on review (calorie targets, missed meals, late meals), and the last fragment of the meal-analysis prompt is plain English again. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- app/src/main/assets/i18n/en-FH.json | 462 ++++++++++++++++++ app/src/main/assets/i18n/pt-BR.json | 1 - .../pulseloop/ui/screens/MealAnalysisSheet.kt | 4 +- 3 files changed, 465 insertions(+), 2 deletions(-) create mode 100644 app/src/main/assets/i18n/en-FH.json diff --git a/app/src/main/assets/i18n/en-FH.json b/app/src/main/assets/i18n/en-FH.json new file mode 100644 index 00000000..4f26a96c --- /dev/null +++ b/app/src/main/assets/i18n/en-FH.json @@ -0,0 +1,462 @@ +{ + " Drinks: {0} of {1}, {2} dry day{3}.": " Drinks: {0} of {1}, {2} dry day{3}. Cheers, I guess.", + " · tap for this week's plan": " · tap for this week's damn plan", + "\"{0}\" will be removed from this day's log.": "\"{0}\" gets yeeted from this day's log.", + "%,d steps yesterday vs your usual %,d": "%,d steps yesterday vs your usual %,d. Interesting choice.", + "A few more days of data and your routines show up here.": "Give it a few more damn days of data and your routines show up here.", + "A little below your usual range.": "A little below your usual range. Hmm.", + "A low resting heart rate is common with high fitness.": "A low resting heart rate is common with high fitness. Show-off.", + "A nudge about 30 minutes before your suggested bedtime.": "A nag about 30 minutes before your suggested bedtime. You're welcome.", + "A solid active day so far.": "A solid active day so far. Don't let it go to your head.", + "A steady week. Keep it up.": "A steady week. Don't you dare screw it up.", + "A typical daytime stress score.": "A typical daytime stress score. Boring, but fine.", + "A typical resting heart rate for adults.": "A typical resting heart rate for adults. Thrilling.", + "A typical skin-temperature range from the ring.": "A typical skin-temperature range from the ring. Nothing to see here.", + "A typical week now": "A typical week now. Yawn.", + "AI Coach is off": "AI Coach is off. Enjoy the silence.", + "Above the typical resting range. Activity, caffeine, or stress can raise it.": "Above the typical resting range. Too much coffee? Activity, caffeine, or stress can raise it.", + "Above your typical HRV — often a sign of good recovery.": "Above your typical HRV — often a sign of good recovery. Fine, I'm impressed. Barely.", + "Across the year your tracked average is {0} over {1} nights. The long-term trend is still forming — as more months fill in, I'll be able to compare seasonal changes and consistency.": "Across the year your tracked average is {0} over {1} nights. The long-term trend is still cooking — give it more months and I'll tell you how your seasons and consistency really stack up.", + "Active every hour since {0}:00": "Active every damn hour since {0}:00. Who even are you?", + "Activity and live vitals, right away": "Activity and live vitals, right the hell away", + "Add a workout you forgot to record": "Add the workout you \"forgot\" to record", + "Add your ring": "Add your ring already", + "After 1–2 drinks, your HRV runs {0}% {1} than on dry nights.": "After 1–2 drinks, your HRV runs {0}% {1} than on dry nights. Just saying.", + "After 3 or more drinks, your HRV runs {0}% {1} than on dry nights.": "After 3 or more drinks, your HRV runs {0}% {1} than on dry nights. Worth it? Your call.", + "Aim for an earlier bedtime: you averaged {0} against a {1} goal.": "Go to bed earlier, for f*ck's sake: you averaged {0} against a {1} goal.", + "Aim to be in bed by {0} to get your {1} hours before your usual {2} wake-up.": "Be in bed by {0}. No excuses. That gets you your {1} hours before your usual {2} wake-up.", + "Alerts when your ring's battery runs low": "Nags you when your ring's battery runs low", + "An LLM-native health app that turns a cheap Bluetooth smart ring into a real, conversational health tracker. It talks to the ring directly over Bluetooth — no vendor cloud, no account — and layers an AI coach on top of your own data.": "An LLM-native health app that turns a cheap Bluetooth smart ring into a real, conversational health tracker — one that talks back. It talks to the ring directly over Bluetooth — no vendor cloud, no account, no BS — and layers an AI coach on top of your own data.", + "Analysis failed: {0}": "Analysis failed, damn it: {0}", + "Around lunch and dinner, only when nothing is logged yet. Needs nutrition tracking on.": "Pesters you around lunch and dinner, only when nothing is logged yet. Needs nutrition tracking on.", + "Around your personal baseline.": "Around your personal baseline. Shockingly normal.", + "Ask the coach about it": "Go bug the coach about it", + "Ask the coach...": "Ask the coach, if you dare...", + "Athletic resting range.": "Athletic resting range. Look at you.", + "Averaging {0} against a need of {1}": "Averaging {0} against a need of {1}. Do the math.", + "Awake time elevated": "Awake time elevated. Tossing and turning much?", + "Awake time low": "Awake time low. Slept like a rock, huh.", + "Baseline pending": "Baseline pending. Patience, damn it.", + "Battery critically low": "Battery critically low. Charge the damn thing.", + "Battery healthy": "Battery healthy. Shocking.", + "Battery low": "Battery low. Feed it.", + "Bedtimes within about 30 minutes help sleep quality": "Bedtimes within about 30 minutes help sleep quality. Pick one and stick to it, damn it.", + "Bring it on": "Bring it the f*ck on", + "Building a picture from your data": "Building a picture from your data. Hold your damn horses.", + "Building baseline": "Building baseline. Be patient.", + "Building momentum": "Building momentum. Finally.", + "Built on your phone from your ring's data. No AI key needed.": "Cooked up on your phone from your ring's data. No AI key needed. You're welcome.", + "Charge your ring before bed": "Charge your ring before bed. Don't make me ask twice.", + "Choose a valid activity type.": "Choose a valid activity type. Come on.", + "Choose an activity, when it started, and how long it lasted.": "Choose an activity, when it started, and how long it lasted. Be honest.", + "Coach is thinking…": "Coach is thinking… don't rush me.", + "Connection failed": "Connection failed. Of f*cking course.", + "Continue without ring": "Continue without ring (bold move)", + "Cooler than typical skin temperature.": "Cooler than typical skin temperature. Chill.", + "Couldn't delete this record": "Couldn't delete this damn record", + "Couldn't get a steady reading. Keep the ring snug and your hand still, then try again.": "Couldn't get a steady reading. Stop wiggling: keep the ring snug and your hand still, then try again.", + "Couldn't load your health history.": "Couldn't load your health history. Great. Just great.", + "Couldn't load {0} trends.": "Couldn't load {0} trends. Ugh.", + "Couldn't look up that barcode. Check your connection or enter the meal manually.": "Couldn't look up that damn barcode. Check your connection or enter the meal manually.", + "Couldn't process that photo. Try again or describe the meal.": "WTF is in that photo? Couldn't process it. Try again or describe the meal.", + "Couldn't reach the server.": "Couldn't reach the server. It's ghosting us.", + "Couldn't save these changes. Check the times and try again.": "Couldn't save these changes. Check the damn times and try again.", + "Couldn't update this record": "Couldn't update this record. Ugh.", + "Daily AI-generated health insights based on your ring data": "Daily AI-generated health insights (with attitude) based on your ring data", + "Daily and weekly targets behind the activity rings.": "Daily and weekly targets behind the activity rings. Yes, those ones.", + "Deep sleep balanced": "Deep sleep balanced. Huh, not bad.", + "Deep sleep strong": "Deep sleep strong. Damn, look at you.", + "Delete drink?": "Delete drink? Hiding the evidence?", + "Delete memory?": "Delete memory? The coach will act like it never happened.", + "Delete workout?": "Delete workout? All that sweat, gone.", + "Describe your meal": "Describe your meal. Spill it.", + "Drink less, sleep better": "Drink less, sleep better. Shocking, I know.", + "Drinks tonight": "Drinks tonight? Really?", + "Dry": "Dry. Look at you.", + "Dry-day goal reached: {0} of {1}": "Dry-day goal reached: {0} of {1}. Damn, sober and smug.", + "Duration held the score back": "Duration dragged the damn score down", + "Duration must be greater than zero.": "Duration must be greater than zero. Zero isn't a workout.", + "Early bird": "Early bird. Ugh.", + "Elevated stress — consider a short break.": "Stress is up — take a short f*cking break.", + "Enable Coach Check-Ins?": "Want the coach nagging you daily?", + "End must be after the start.": "End must be after the start. Time doesn't run backwards.", + "End time can't be in the future.": "End time can't be in the future. Nice try, time traveler.", + "Ended early.": "Ended early. Of course.", + "Energy and sleep can dip; resting heart rate is often at its lowest.": "Energy and sleep can dip — fun. Resting heart rate is often at its lowest, at least.", + "Evening check-in": "Evening check-in. Spill it.", + "Evening type": "Night owl", + "Everything compared agrees within its band.": "Everything compared agrees within its band. Annoyingly fine.", + "Excellent": "Excellent. Don't get cocky.", + "Exceptional": "Exceptional?! WTF.", + "Explain my heart rate trend": "WTF is my heart rate doing?", + "Explore the app without a ring. Seeds activity, HR, SpO2, sleep, and a coach conversation.": "No ring? Fine. Poke around anyway — seeds activity, HR, SpO2, sleep, and a coach conversation.", + "Explore without ring": "Snoop around without a ring", + "Fair": "Fair. Meh.", + "Feeling unwell? Pause activity nudges for 3 days.": "Feeling unwell? I'll shut up about moving for 3 days.", + "Fell asleep": "Finally passed out", + "Finish": "Finally, finish", + "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 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?", + "Good": "Good. Ugh, fine.", + "Good afternoon": "Afternoon. Still alive?", + "Good duration": "Decent duration, for once", + "Good evening": "Evening. Finally.", + "Good morning": "Morning. Ugh.", + "Good morning{0}": "Morning{0}. Ugh.", + "Good night": "Go the f*ck to sleep", + "Good sleep, with some restlessness": "Good sleep, but WTF was all that tossing?", + "Great balance of movement and recovery. Keep it up.": "Great balance of movement and recovery. Don't screw it up.", + "HRV is personal. Wear your ring for about a week to learn your baseline.": "HRV is personal. Wear the damn ring for about a week so it learns your baseline.", + "HRV lower than usual": "HRV lower than usual. What did you do?", + "HRV trending up": "HRV trending up. Huh. Nice.", + "HRV usually takes {0} night{1} to come back.": "HRV usually takes {0} night{1} to crawl back. Worth it?", + "Hard workout": "Brutal workout", + "Heart rate stayed at your quiet level with no steps": "Heart rate stayed at your quiet level with no steps. Couch mode, huh?", + "Heart rate up to {0} bpm": "Heart rate up to {0} bpm. Easy, tiger.", + "Hi! I'm your PulseLoop coach. I can answer questions about your sleep, heart rate, activity, and recovery. What would you like to know?": "Oh, hi. I'm your PulseLoop coach. Ask me about your sleep, heart rate, activity, and recovery — I'll be honest, brutally. What do you want to know?", + "High fatigue": "Wiped the hell out", + "How am I doing on my goal? What should I focus on this week?": "How bad am I doing on my goal? What should I fix this week?", + "How am I doing today?": "How screwed am I today?", + "How can I sleep better?": "WTF do I do to sleep better?", + "How did today feel? Sync your ring and I'll recap your day.": "So, how was today? Sync your ring and I'll roast — er, recap — your day.", + "How many recent days you reached your step goal. Aim for at least 3 days a week, ideally 5 or more.": "How many recent days you actually hit your step goal. Aim for at least 3 days a week, ideally 5 or more. Not a big ask.", + "How much you were awake once asleep. Some waking is normal; long or frequent wake-ups lower this.": "How much you were awake once asleep. Some waking is normal; long or frequent wake-ups tank this.", + "How often you exercised this week. Three or more sessions a week is a good target.": "How often you bothered to exercise this week. Three or more sessions a week is a good target.", + "I don't see sleep data for last night. Wear your ring overnight and sync in the morning so I can compare your sleep against your baseline.": "No sleep data for last night. Did you even go to bed? Wear your ring overnight and sync in the morning so I can compare your sleep against your baseline.", + "I only have {0} tracked {1} for this {2}. Wear the ring overnight for a few more nights and I'll build a reliable {3}ly picture.": "I only have {0} tracked {1} for this {2}. Seriously? Wear the ring overnight for a few more nights and I'll build a reliable {3}ly picture.", + "I'd like to set a goal. Ask me what I want and help me make it realistic for my data.": "I want a goal. Ask me what I want and talk me down to something realistic for my data.", + "Idle": "Slacking", + "Idle between syncs": "Slacking between syncs", + "In line with your usual {0} ms": "In line with your usual {0} ms. Boring, but fine.", + "Inactivity": "Couch time", + "Increase duration by 5 minutes": "Add 5 more damn minutes", + "It's at {0}%. A short charge now keeps tonight's sleep tracked.": "It's at {0}%. Charge the damn thing now so tonight's sleep gets tracked.", + "Keep going": "Keep going, damn it", + "Keep recording": "Keep recording, damn it", + "Keep still — measuring blood oxygen…": "Hold still, for f*ck's sake — measuring blood oxygen…", + "Keep still — measuring blood pressure, SpO₂, stress, fatigue & blood sugar…": "Freeze. Seriously — measuring blood pressure, SpO₂, stress, fatigue & blood sugar…", + "Keep still — measuring heart rate & SpO₂…": "Stop fidgeting — measuring heart rate & SpO₂…", + "Keep still — measuring heart rate…": "Stop fidgeting — measuring heart rate…", + "Keep still — measuring {0}…": "Hold still, damn it — measuring {0}…", + "Last night's heart rate and HRV readings weren't enough to score recovery": "Last night's heart rate and HRV readings were too damn thin to score recovery", + "Last night: {0}. A few dry nights will show what it does to you.": "Last night: {0}. A few dry nights will show what that sh*t does to you.", + "Last night: {0}. Your night looked close to your dry ones.": "Last night: {0}. Your night looked close to your dry ones. Got lucky.", + "Later": "Ugh, later", + "Learned from nights you woke recovered": "Learned from the rare nights you woke recovered", + "Learning your baseline: {0} of {1} nights. Keep wearing your ring to bed.": "Learning your baseline: {0} of {1} nights. Keep wearing the damn ring to bed.", + "Learning your dry nights: {0} of {1}. Then PulseLoop shows what each drink does to your sleep.": "Learning your dry nights: {0} of {1}. Then PulseLoop shows what each drink does to your sleep. Brace yourself.", + "Learning your normal: {0} of {1} nights.": "Learning your normal: {0} of {1} nights. Patience, damn it.", + "Learns your baseline": "Learns your baseline (give it time, damn)", + "Limited HR data available for today.": "Barely any HR data today. Where's the ring?", + "Log Meal": "Feed the Log", + "Log a drink": "Confess a drink", + "Log a drink in one tap": "Confess a drink in one tap", + "Log a few evenings with drinks and PulseLoop will compare those nights with your dry ones.": "Log a few boozy evenings and PulseLoop will compare those nights with your dry ones. The truth hurts.", + "Log a meal": "Feed the log", + "Log drinks": "Confess drinks", + "Log meal": "Feed the log", + "Log meals to see food next to the calories you burn, and to link late meals and drinks to your sleep.": "Log meals to see food next to the calories you burn — and to catch late meals and drinks wrecking your sleep.", + "Log this": "Log this, damn it", + "Long stretches without moving are linked to poorer health, even on days you exercise. A short walk every hour helps.": "Sitting for hours is linked to poorer health, even on days you exercise. Get your a** up for a short walk every hour.", + "Long-term insights appear as more nights are tracked.": "Long-term insights show up once you track more nights. No shortcuts.", + "Looks like a strong night after a more active day. Your duration was solid and deep sleep made up a healthy part of the night, which kept the score high.": "Huh, a strong night after a more active day. Duration was solid and deep sleep made up a healthy chunk of the night, so the score stayed high. Don't let it go to your head.", + "Low fatigue — well recovered.": "Low fatigue — well recovered. Suspicious.", + "Low stress score — relaxed.": "Low stress score — relaxed. Who are you?", + "Lowest heart rate {0} before waking": "Lowest heart rate {0} before waking. Body was still working overtime.", + "Measuring… updates when complete": "Measuring… chill, it updates when done", + "Measuring… {0}s": "Measuring… {0}s. Patience.", + "Meet daily goals": "Hit your damn daily goals", + "Message the coach": "Bother the coach", + "Mild fatigue.": "Mild fatigue. Meh.", + "Missed": "Missed. Again.", + "Morning": "Morning. Ugh.", + "Morning type": "Annoying morning person", + "Move every hour": "Move your a** every hour", + "Move reminder": "Get-up nag", + "Near baseline": "Near baseline. Boring.", + "Needs 5 nights in the last 2 weeks": "Needs 5 nights in the last 2 weeks. Wear the ring.", + "Needs care": "Needs care. Seriously.", + "Needs work": "Needs work. Lots.", + "Never mind": "Forget it", + "New chat": "Fresh rant", + "Night owl": "Night owl. Of course you are.", + "Nightly sleep": "Nightly sleep (or lack of it)", + "Nightly sleep: no nights tracked in this range": "Nightly sleep: zero nights tracked in this range. Zero.", + "No HR samples yet — sync your ring to start your trend.": "No HR samples yet. Sync your damn ring to start your trend.", + "No HRV data yet — HRV builds up over a few hours of wear.": "No HRV data yet. Wear the thing a few hours, HRV doesn't build itself.", + "No SpO₂ samples yet — take a reading to start your trend.": "No SpO₂ samples yet. Take a reading already to start your trend.", + "No activity records synced for {0} yet.": "No activity synced for {0} yet. Did you even move?", + "No blood pressure data yet.": "No blood pressure data yet. Nothing. Nada.", + "No blood sugar data yet.": "No blood sugar data yet. Shocking.", + "No data yet today": "No data yet today. Wake up, ring.", + "No daytime stress readings today yet.": "No daytime stress readings yet. Enjoy it while it lasts.", + "No drinks this week": "No drinks this week. Who even are you?", + "No drinks yet this week": "No drinks yet this week. Yet.", + "No events yet. Sync the ring or trigger a measurement to see data.": "No events yet. Sync the ring or trigger a measurement, for f*ck's sake, then you'll see data.", + "No nights tracked in this range yet.": "No nights tracked in this range yet. WTF were you doing?", + "No obvious signs in your biometrics of something straining your body.": "No obvious signs of something straining your body. Huh. Boring, but good.", + "No readiness today: {0}. Wear the ring snugly tonight.": "No readiness today: {0}. Wear the damn ring snugly tonight.", + "No ring connected": "No ring connected. Lonely.", + "No ring paired": "No ring paired. So what are we doing here?", + "No rings found yet": "No rings found yet. Hide and seek, apparently.", + "No signs": "No signs. Phew.", + "No sleep captured last night": "No sleep captured last night. WTF happened?", + "No sleep recorded": "No sleep recorded. Did you even go to bed?", + "No sleep recorded for last night yet. Sync your ring after you wake up.": "No sleep for last night yet. Sync your ring after you wake up, sleepyhead.", + "No sleep tracked last night": "No sleep tracked last night. Vampire much?", + "No sleep yet": "No sleep yet. Obviously.", + "No stress data yet — take a measurement.": "No stress data yet. Take a measurement. Stressful, I know.", + "No temperature data yet — temperature trends appear after overnight wear.": "No temperature data yet. Wear it overnight and the trends show up. Patience, damn it.", + "No workouts recorded today": "No workouts today. The couch thanks you.", + "No workouts yet — recorded workouts will appear here.": "No workouts yet. When you finally sweat, they'll appear here.", + "Not enough data for this period.": "Not enough data for this period. Can't work with crumbs.", + "Not enough monthly data": "Not enough monthly data. Keep wearing it.", + "Not enough nights yet": "Not enough nights yet. Sleep more. With the ring on.", + "Not enough of a trend to estimate runtime yet — it appears after a few hours of discharge.": "Not enough of a trend to guess runtime yet. Give it a few hours of discharge, jeez.", + "Not enough recent weigh-ins for a trend yet (needs 3 across a week).": "Not enough recent weigh-ins for a trend (needs 3 across a week). Step on the damn scale.", + "Not enough weekly data": "Not enough weekly data. Keep wearing it.", + "Not enough yearly data": "Not enough yearly data. Come back in, oh, a year.", + "Not enough {0} data for this view yet.": "Not enough {0} data for this view yet. Patience, damn it.", + "Not enough {0} data yet": "Not enough {0} data yet. Ugh.", + "Not now": "Ugh, not now", + "Not yet": "Not yet, chill", + "Notably below your typical HRV — often linked to stress, poor sleep, or strain.": "Way below your typical HRV. Stress, crap sleep, or strain? Pick one, probably all three.", + "Nothing logged yet": "Nothing logged yet. Shocker.", + "Nothing new to upload": "Nothing new to upload. Go do something.", + "Nothing stood out": "Nothing stood out. Wow. Riveting.", + "Nothing to compare yet. Check back after the first full day and night.": "Nothing to compare yet. Come back after a full day and night, impatient one.", + "Nothing tonight": "Nothing tonight. Sure. We'll see.", + "On track": "On track. Don't get cocky.", + "On until {0}/{1}: activity nudges paused, the coach eases off.": "On until {0}/{1}: no activity nudges, the coach shuts up a bit.", + "Open Drinks: this week, your plan and what drinking does to your nights": "Open Drinks: this week, your plan and what the hell drinking does to your nights", + "Open PulseLoop to sync": "Open PulseLoop to sync, damn it", + "Optimal": "Optimal. Suspicious.", + "Other ideas": "Other bright ideas", + "Out of sync": "Out of sync. Typical.", + "Own your ring data": "Own your damn ring data", + "Pair your ring first.": "Pair your ring first. Come on.", + "Pay attention": "Hey! Pay attention", + "Pick the number before the first drink. It's easier to keep a number you chose beforehand.": "Pick the number BEFORE the first drink. After it, you'll negotiate like a lawyer.", + "Plan the next few days with the coach.": "Plan the next few days with the coach. Somebody has to.", + "Plan tonight": "Plan tonight (before it plans you)", + "Plan: dry night": "Plan: dry night. Bold.", + "Possible nap": "Possible nap. Lazy a** afternoon?", + "PulseLoop learns your baseline over time": "PulseLoop learns your baseline over time. It's not psychic.", + "PulseLoop uses sensible defaults.": "PulseLoop uses sensible defaults. Unlike some people.", + "PulseLoop · from my ring, compared with last week": "PulseLoop · from my ring, vs. last week. Brace yourself.", + "REM sleep supports memory and mood. It usually makes up 20 to 25% of a night, about 90 minutes or more.": "REM sleep keeps your memory and mood from going to sh*t. Usually 20 to 25% of a night, about 90 minutes or more.", + "Reading your drinks…": "Reading your drinks… oh boy…", + "Reading your history…": "Digging through your history…", + "Ready to start the day? Take a measurement and I'll help you plan it.": "Up already? Fine. Take a measurement and I'll help you plan the damn day.", + "Reconnect last ring": "Get the last ring back", + "Relaxed": "Relaxed. For once.", + "Resilience {0} over {1} days": "Resilience {0} over {1} days. Not bad, not great.", + "Rest days let your body adapt to training. One or two easier days a week is enough for most people.": "Rest days are when your body actually adapts. One or two easier days a week is enough for most people. No, not seven.", + "Resting heart rate trending down": "Resting heart rate trending down. Fine, good job, whatever.", + "Resting heart rate up": "Resting heart rate up. What did you do?", + "Restored {0} · relaxed {1} · engaged {2} · stressed {3}": "Restored {0} · chill {1} · busy {2} · freaking out {3}", + "Ride it out": "Ride it out, tough guy", + "Right at your limit": "Right at your limit. Stop. Right. There.", + "Right at your usual {0} bpm": "Right at your usual {0} bpm. Boring. Good.", + "Ring hasn't synced in >12h — today's data may be stale.": "Ring hasn't synced in >12h. Today's data may be stale as hell.", + "Saved & sent to ring ✓": "Saved & shoved to the ring ✓", + "Saved — will sync on next connect": "Saved. Syncs next connect, relax", + "Screens in bed": "Screens in bed. Seriously?", + "See what affects you": "See what the hell affects you", + "See what drinking does to your own nights": "See what drinking does to your own nights. Spoiler: nothing good.", + "See your vitals": "See your vitals. If you dare.", + "Set up · under a minute": "Set up · under a minute. No excuses.", + "Set your typical week in settings to see drinks, money and calories saved.": "Set your typical week in settings to see the drinks, money and calories you didn't blow.", + "Setup complete": "Setup complete. Finally.", + "Shaded: your usual range over the last 30 days": "Shaded: your usual range over the last 30 days. Stay in it.", + "Share my week": "Share my week (brave)", + "Short duration": "Short. Way too short.", + "Skip for now": "Skip for now, coward", + "Sleep a night": "Sleep a night. A whole one.", + "Sleep midpoint varies by about {0} min": "Sleep midpoint varies by about {0} min. Pick a bedtime, damn it.", + "Sleep pending": "Sleep pending. Waiting…", + "Sleep synced": "Sleep synced. Let's see the damage.", + "Sleep {0} a night": "Sleep {0} a night. Not a suggestion.", + "Sleeping less this week": "Sleeping less this week. WTF is going on with your sleep?!", + "Sleeping more this week": "Sleeping more this week. Look at you, hibernating.", + "Slightly below": "Slightly below. Meh.", + "Slightly low": "Slightly low. Hmm.", + "Slightly off": "Slightly off. Like you.", + "Slow breathing: in for 4 seconds, out for 6.": "Slow breathing: in for 4 seconds, out for 6. Calm the hell down.", + "Small signs in your biometrics of something straining your body.": "Small signs in your biometrics that something's straining your body. Ugh.", + "Snap your plate; the AI estimates it": "Snap your plate; the AI judges it", + "So far (preliminary)": "So far (don't get excited)", + "Solid": "Solid. Annoyingly.", + "Solid night overall": "Solid night overall. Don't let it go to your head.", + "Some of your signals look unusual": "Some of your signals look weird as hell", + "Some signals look unusual": "Some signals look weird", + "Sorry, something went wrong: {0}": "Well, sh*t. Something went wrong: {0}", + "Start a breathing session": "Breathe, damn it", + "Start tracking": "Start tracking already", + "Start using PulseLoop": "Fine, start using PulseLoop", + "Start with recommended targets. You can change these anytime.": "Start with recommended targets. Change them anytime, you'll fiddle anyway.", + "Steady build": "Steady build. Slow but OK.", + "Stop scanning": "Stop scanning already", + "Stressful day": "Stressful day. Of course it was.", + "Strong language ahead": "F*cking strong language ahead", + "Strong recovery signal": "Strong recovery signal. Don't let it go to your head.", + "Stronger signs in your biometrics of something straining your body.": "Your biometrics are yelling louder now. Something is straining your body, damn it.", + "Summarize my week": "Roast my week", + "Sunday evening: your week compared with the last one, and one thing to focus on.": "Sunday evening: your week vs. the last one, and the one damn thing to fix.", + "Swipe to find your model, then tap to connect.\nYou can also explore first and pair later.": "Swipe to find your model, then tap to connect. Not rocket science.\nYou can also explore first and pair later.", + "Sync Now": "Sync Now, damn it", + "Sync all history": "Drag out all history", + "Sync failed": "Sync failed. Ugh.", + "Sync now": "Sync now, damn it", + "Sync your ring to start collecting movement, heart rate, blood oxygen, and recovery context.": "Sync your ring already. No sync, no movement, heart rate, blood oxygen or recovery context. Just sad empty cards.", + "Syncing latest data…": "Dragging the latest data out of your ring…", + "Syncing…": "Syncing… hold your damn horses.", + "TODAY'S BRIEF": "TODAY'S DAMN BRIEF", + "Tag your day": "Confess your day", + "Tag your days for a couple of weeks. Once a tag has at least {0} nights after it, PulseLoop compares those nights with your others.": "Tag your days for a couple of weeks. Once a tag has at least {0} nights after it, PulseLoop compares those nights with your others and tells you what's wrecking them.", + "Tag {0} more {1} to see an effect": "Tag {0} more {1}. Then we'll talk.", + "Take it easy": "Take it easy. Seriously.", + "Talk it through": "Spill it", + "Tell the coach, and it plans with your scale, ring and food data.": "Tell the coach. It'll plan with your scale, ring and food data, and judge you a little.", + "That app shares nothing PulseLoop can compare.": "That app shares nothing PulseLoop can compare. Useless.", + "The AI didn't return a usable estimate. Try again or enter the meal manually.": "The AI choked and gave back sh*t. Try again or enter the meal manually.", + "The activity must end in the past.": "The activity must end in the past. You can't log the future, genius.", + "The import failed. Try again in a moment.": "The import failed. Of course. Try again in a moment.", + "The ring disconnected during measurement.": "The ring bailed in the middle of the measurement. Rude.", + "The ring recorded this night in {0} parts": "The ring recorded this night in {0} parts. What were you doing in there?", + "The scan failed. Try again in a moment.": "The scan failed. Ugh. Try again in a moment.", + "The share of your time in bed spent asleep. Around 85% or more is considered good.": "How much of your time in bed you actually slept, not scrolled. Around 85% or more is considered good.", + "The stage mix was useful, but total sleep time was short for a full recovery window. A slightly earlier wind-down would likely improve tomorrow's score.": "The stage mix was fine, but you slept too damn little for a full recovery window. Wind down a bit earlier and tomorrow's score will thank you.", + "The target date has passed; agree a new one.": "The target date came and went. Pick a new one, and maybe mean it this time.", + "The workout must finish before now.": "The workout must finish before now. No time travel, champ.", + "There's room to move more today.": "There's room to move more today. Like, a lot.", + "There's room to move more. Start with your {0}.": "Your couch is winning. Start with your {0}.", + "This is a test check-in notification.": "This is a test check-in notification. Hi. Ugh.", + "This week is {0}% less active than your monthly average": "This week is {0}% less active than your monthly average. WTF happened?", + "This week is {0}% more active than your monthly average": "This week is {0}% more active than your monthly average. Show-off.", + "This week matches your monthly rhythm": "This week matches your monthly rhythm. Thrilling.", + "This workout is no longer in local storage. It may have been deleted or replaced.": "This workout is gone from local storage. Deleted or replaced. Poof.", + "Thriving": "Thriving, apparently", + "Time asleep": "Time actually asleep", + "Time for {0}": "Time for {0}. Move it.", + "Time to move": "Get off your a**", + "Time to wind down": "Time to wind down. Put the damn phone away.", + "Tired": "Tired. Shocker.", + "Tired — consider lighter activity and good sleep.": "Tired. Go easy today and actually sleep tonight, for f*ck's sake.", + "Today's steps against your step goal. It fills up as the day goes on.": "Today's steps against your step goal. It fills up as the day goes on. If you move.", + "Tonight: {0} drink{1}": "Tonight: {0} drink{1}. Cheers, I guess.", + "Total workout time this week. Health guidelines suggest at least 150 minutes of moderate activity a week.": "Total workout time this week. Health guidelines want at least 150 minutes of moderate activity a week. No excuses.", + "Track more nights this month to see a monthly average.": "Track more nights this month. Can't average what you didn't wear.", + "Tracked {0} {1} this year": "Tracked {0} {1} this year. Not bad, I guess.", + "Trends over time matter more than any single reading.": "Trends over time matter more than any single reading. Stop obsessing over one number.", + "Try again": "Try again, damn it", + "Turn on Bluetooth to find and connect your ring.": "Turn on Bluetooth. I can't find your ring by telepathy.", + "Two-hour 140–199 is above the typical range.": "Two-hour 140–199 is above the typical range. Hmm.", + "Under 100 steps in an hour, 9:00 to 20:00, at most every two hours. Off in Rest Mode.": "Nags you after under 100 steps in an hour, 9:00 to 20:00, at most every two hours. Shuts up in Rest Mode.", + "Under 100 steps in the last hour. A few minutes on your feet helps your energy and your sleep.": "Under 100 steps in the last hour?! Get on your feet for a few minutes. Your energy and your sleep will thank you.", + "Unusual last night: ": "Weird sh*t last night: ", + "Unusual signals alert": "Something's-weird alert", + "Upload failed: {0}": "Upload failed, ugh: {0}", + "Uploaded 1 workout": "Uploaded 1 workout. One. Wow.", + "Uploaded {0} workouts": "Uploaded {0} workouts. Look at you.", + "Use without a ring": "Go ringless", + "User profile is incomplete — insights may be less personalized.": "Your profile is half-assed — insights may be less personalized. Fill it in.", + "Usual sleep midpoint {0} · this week {1}": "Usual sleep midpoint {0} · this week {1}. Hmm.", + "Variable nights": "Chaotic nights", + "Waiting for first sync": "Waiting for the first sync. Still waiting…", + "Waiting for the first import": "Waiting for the first import. Tapping foot.", + "Waiting for {0} to deliver {1} day{2}. Open the app that syncs it to send it sooner; otherwise those days are scored 24 hours after they end.": "Still waiting for {0} to cough up {1} day{2}. Open the app that syncs it to send it sooner; otherwise those days are scored 24 hours after they end.", + "Wake the ring by tapping or moving it, and keep it close.": "Wake the damn ring up by tapping or moving it, and keep it close.", + "Want to drink less? Track drinks, set a weekly limit and see what each drink does to your nights": "Want to drink less? Track drinks, set a weekly limit and see exactly what each one does to your nights. Spoiler: nothing good.", + "Warmer than typical. Trends matter more than a single reading.": "Warmer than typical. Don't panic, trends matter more than a single reading.", + "Wear your ring during the day and sync after sleep. Trends become more personal after a few days.": "Wear your ring during the day and sync after sleep. Give it a few days before the trends get personal. And judgy.", + "Wear your ring overnight for a few nights to build a weekly view.": "Wear your ring overnight for a few nights. No ring, no weekly view. Simple.", + "Wear your ring overnight so PulseLoop can track your next night.": "Wear your ring to bed, for f*ck's sake, so PulseLoop can track your next night.", + "Wear your ring overnight to see your hypnogram here.": "Wear your ring overnight, then you get a hypnogram. Not before.", + "Wear your ring today. Your baseline builds from here.": "Wear your ring today. Your baseline won't build itself.", + "What affects you": "What screws with you", + "What changed": "What the hell changed", + "What did you do?": "What the hell did you do?", + "What's your goal?": "So what's the damn goal?", + "When the ring is at 30% or less a couple of hours before your usual bedtime.": "When the ring is at 30% or less a couple of hours before your usual bedtime. Charge the damn thing.", + "When two or more of last night's signals are outside your usual range.": "When two or more of last night's signals go off the rails from your usual range.", + "When you want a drink": "When the drink craving hits", + "Where the ring falls short": "Where the ring screws up", + "Whether your sleep lines up with your body clock. A midpoint between midnight and about 3:30 am is ideal for most people.": "Whether your sleep lines up with your body clock or you're living like a vampire. A midpoint between midnight and about 3:30 am is ideal for most people.", + "Why there's no score today": "Why the hell there's no score today", + "Wind-down reminder": "Go-to-bed nagging", + "Woke up": "Woke up. Ugh.", + "Workout history": "Workout history (the receipts)", + "Workout in progress": "Workout in progress. Keep going.", + "Workout not found": "Workout not found. Did it even happen?", + "Yes, a nap": "Yes, a nap. Judge me.", + "Yesterday's steps compared with your usual. Both a very inactive day and an unusually heavy one lower this.": "Yesterday's steps vs. your usual. A couch-potato day and a lunatic one both drag this down.", + "You are now a developer!": "You are now a developer! God help us.", + "You averaged {0} across the full week. Your nights were tracked consistently, so this is a dependable picture of where your sleep sits right now.": "You averaged {0} across the full week. You actually tracked every night, so for once this is a dependable picture of where your sleep sits.", + "You averaged {0} across {1} tracked nights this week. That's a useful read, but {2} missing {3} mean the trend is still incomplete.": "You averaged {0} across {1} tracked nights this week. Useful-ish, but {2} missing {3} mean the trend is still full of holes.", + "You can pair a ring later from Settings.": "Fine, pair a ring later from Settings.", + "You can still search the database or enter the meal manually.": "You can still search the database or type the meal in yourself. Old school.", + "You hit your {0} step goal — nice work.": "You hit your {0} step goal. Damn. Didn't think you had it in you.", + "You logged {0}h {1}m of sleep. Here's to a strong day — get moving when you can.": "You logged {0}h {1}m of sleep. Here's to a strong day — now get moving when you can.", + "You moved less than last week. A daily walk is an easy way back.": "You moved less than last week. WTF? A daily walk is an easy way back.", + "You slept long enough, but awake time was a bit elevated. If this repeats, look at late caffeine, alcohol, temperature, or stress near bedtime.": "You slept long enough, but you kept waking up like a damn owl. If this repeats, look at late caffeine, alcohol, temperature, or stress near bedtime.", + "You're all set": "You're all set. Finally.", + "You're at %,d steps, %dh %02dm of sleep, and your latest reading is %s.": "You're at %,d steps, %dh %02dm of sleep, and your latest reading is %s. Could be worse.", + "You're at %,d steps. Sync after waking to add recovery context.": "You're at %,d steps. Sync after waking, or I can't tell you how wrecked you are.", + "You're at {0} of {1}. About {2} minutes of walking closes it.": "You're at {0} of {1}. About {2} minutes of walking closes it. Go.", + "You're in good shape today. Your usual plans should feel fine.": "You're in good shape today. Ugh, fine. Your usual plans should feel fine.", + "You're well recovered. A good day to take on something demanding.": "You're well recovered. No excuses today. Go do something hard.", + "You're {0} g short of today's protein, so this leans on protein.": "You're {0} g short of today's protein, so this leans on protein. Eat your damn protein.", + "You're {0} step{1} away from Developer options.": "You're {0} step{1} away from Developer options. Keep tapping, nerd.", + "Your HRV dipped this week. Lighter days and consistent sleep help it recover.": "Your HRV tanked this week. Lighter days and consistent sleep help it recover. Try it.", + "Your average sleep over the last two weeks compared with your goal. It shows whether sleep debt is building up.": "Your average sleep over two weeks vs. your goal. Shows whether sleep debt is piling up like dirty dishes.", + "Your body is asking for rest. Make recovery today's priority.": "Your body is begging for rest. Make recovery today's priority, damn it.", + "Your body is asking for rest. Make recovery today's priority: your {0} is furthest from your usual.": "Your body is begging for rest. Make recovery today's priority: your {0} is way off your usual.", + "Your body is still recovering. Go a little easier today and watch your {0}.": "Your body is still recovering. Go a little easier today and keep an eye on your {0}.", + "Your body is still recovering. Go a little easier today.": "Your body is still recovering. Ease the hell up a little today.", + "Your data has been restored from the backup.": "Your data is back from the backup. You're welcome.", + "Your health, on your terms — no subscription, no cloud.": "Your health, on your terms. No subscription, no cloud, no bullsh*t.", + "Your heart rate variability over the last few nights, weighted toward last night, compared with your usual. Higher than usual generally means you're well recovered; a drop suggests strain.": "Your heart rate variability over the last few nights, weighted toward last night, vs. your usual. Higher generally means you're well recovered; a drop means something's grinding you down.", + "Your long-term sleep trend": "Your long-term sleep saga", + "Your lowest sustained heart rate last night, compared with your usual over recent nights. A resting heart rate a few beats above normal can mean your body is working on recovery, stress, or an oncoming illness.": "Your lowest sustained heart rate last night, vs. your usual over recent nights. A few beats above normal can mean your body is busy with recovery, stress, or an oncoming illness.", + "Your month in sleep": "Your month in sleep. Brace yourself.", + "Your monthly average is {0} across {1}. The biggest lever is consistency — a few short nights move this number more than any single great one.": "Your monthly average is {0} across {1}. The biggest lever is consistency — a few crappy short nights move this number more than any single great one.", + "Your monthly average is {0}, but coverage is low ({1}), so I'd treat that number cautiously. More nights tracked will sharpen the trend.": "Your monthly average is {0}, but coverage is lousy ({1}), so don't trust that number much. Wear the ring more nights and the trend sharpens.", + "Your nights against your own normal, kept as a log": "Your nights vs. your own normal, kept as a log of shame", + "Your nights look like your usual. That's an answer too.": "Your nights look like your usual. Boring. That's an answer too.", + "Your personalized baseline unlocks": "Your personalized baseline unlocks. Eventually.", + "Your preference: ": "Your preference, apparently: ", + "Your resting heart rate is up on last week. Prioritise recovery and sleep.": "Your resting heart rate is up on last week. WTF? Prioritise recovery and sleep.", + "Your ring and phone agree within 5% ({0} days).": "Your ring and phone agree within 5% ({0} days). A miracle.", + "Your ring counts about {0}% fewer steps than your phone ({1} days).": "Your ring counts about {0}% fewer steps than your phone ({1} days). Stingy little thing.", + "Your ring counts about {0}% more steps than your phone ({1} days).": "Your ring counts about {0}% more steps than your phone ({1} days). Generous, huh?", + "Your sleep duration and stage balance were strong. Deep sleep looked supportive, which helped keep the overall score high.": "Your sleep duration and stage balance were strong. Deep sleep actually showed up for once, which kept the score high. Don't get cocky.", + "Your sleep was in a workable range, with the score shaped mostly by duration and stage balance. Deep and light sleep were readable enough to give a useful recovery snapshot.": "Your sleep was… workable. Meh. The score came mostly from duration and stage balance, and deep and light sleep were readable enough for a useful recovery snapshot.", + "Your week at a glance": "Your week at a glance. Brace yourself.", + "Your workout is still recording. Finish it now, or keep recording?": "Your workout is still recording. Done, or are you just slacking? Finish it now, or keep recording?", + "{0} awake during the night": "{0} awake during the night. Party?", + "{0} bpm lower over two weeks than the four before. Often a sign of improving fitness or recovery.": "{0} bpm lower over two weeks than the four before. Often a sign of improving fitness or recovery. Ugh, fine, good job.", + "{0} bpm over the last 3 nights against your usual {1}. Illness, alcohol, stress, heat or hard training can all raise it.": "{0} bpm over the last 3 nights against your usual {1}. Illness, alcohol, stress, heat or hard training can all crank it up.", + "{0} complete": "{0} complete. Finally.", + "{0} days left": "{0} days left. Tick tock.", + "{0} drinks this week": "{0} drinks this week. Hmm.", + "{0} dry days in a row": "{0} dry days in a row. Damn, look at you.", + "{0} dry day{1} so far": "{0} dry day{1} so far. Keep it up.", + "{0} inactive {1} since {2}:00": "{0} lazy {1} since {2}:00", + "{0} left this week": "{0} left this week. Don't blow it.", + "{0} min a night less than your usual over the last 7 nights.": "{0} min a night less than your usual over the last 7 nights. Where the hell is your sleep going?", + "{0} min a night more than your usual over the last 7 nights.": "{0} min a night more than your usual over the last 7 nights. Sleeping beauty over here.", + "{0} more dry day{1} to reach {2}": "{0} more dry day{1} to reach {2}. You can do it, probably.", + "{0} ms over the last 3 nights against your usual {1} ({2}%). Your body may be under extra load.": "{0} ms over the last 3 nights against your usual {1} ({2}%). Your body is hauling some extra sh*t right now.", + "{0} of {1} dry days; a fresh week starts Monday": "{0} of {1} dry days. A fresh week starts Monday, thank god.", + "{0} over your limit": "{0} over your limit. Seriously?", + "{0} steps at {1}.": "{0} steps at {1}. That's it?", + "{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.json b/app/src/main/assets/i18n/pt-BR.json index 741cb93c..9be81242 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -217,7 +217,6 @@ "Battery healthy": "Bateria saudável", "Battery history": "Histórico da bateria", "Battery low": "Bateria baixa", - "Be realistic about portion sizes; state your assumptions (portion sizes, preparation) briefly. Use confidence \"high\" only for clearly identifiable, standard portions. Return only JSON matching the schema.": "Seja realista quanto ao tamanho das porções; informe brevemente suas suposições (tamanho das porções, preparo). Use a confiança \"high\" apenas para porções padrão claramente identificáveis. Retorne apenas JSON de acordo com o schema.", "Bedtime": "Hora de dormir", "Bedtimes within about 30 minutes help sleep quality": "Horários de dormir com variação de até uns 30 minutos ajudam a qualidade do sono", "Beer": "Cerveja", 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 6d34ace3..e4b83b5a 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt @@ -659,7 +659,9 @@ object MealAnalysisLogic { val systemPrompt: String = "You are a nutrition estimator. Given a meal description and/or photo, " + "identify the food and estimate total calories and macros for the portion shown or described. " + - tr("Be realistic about portion sizes; state your assumptions (portion sizes, preparation) briefly. Use confidence \"high\" only for clearly identifiable, standard portions. Return only JSON matching the schema.") + "Be realistic about portion sizes; state your assumptions (portion sizes, preparation) briefly. " + + "Use confidence \"high\" only for clearly identifiable, standard portions. " + + "Return only JSON matching the schema." /** * The verbatim strict meal_estimate json_schema (MealAnalysisSheet.swift:344-362), built From 556f09231be855bcc7b51059d9420b848b98842a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 11:38:22 +0000 Subject: [PATCH 6/6] Fix a KDoc path that opened a nested comment Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- app/src/main/java/com/pulseloop/ui/i18n/L10n.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/pulseloop/ui/i18n/L10n.kt b/app/src/main/java/com/pulseloop/ui/i18n/L10n.kt index 1c80c4ac..302a4dfe 100644 --- a/app/src/main/java/com/pulseloop/ui/i18n/L10n.kt +++ b/app/src/main/java/com/pulseloop/ui/i18n/L10n.kt @@ -40,7 +40,7 @@ enum class AppLanguage( /** * The app's language (Settings → Language). The UI is written in English, and every displayed * literal goes through [tr], which looks the English text up in the language's catalogs - * (`assets/i18n/*.json`) and falls back to the English when a string has no entry yet. The + * (`assets/i18n/.json`) and falls back to the English when a string has no entry yet. The * English text *is* the key, so a reworded string simply shows in English until it is translated * again. *