Skip to content

Offline gym log for Android. No account, no ads, no internet.

Add a Health section with Health Connect data

InlitXe9b43a72f3ec
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index cf6126b..9dccee2 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -11,6 +11,18 @@
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.health.READ_STEPS"/>
+ <uses-permission android:name="android.permission.health.READ_RESTING_HEART_RATE"/>
+ <uses-permission android:name="android.permission.health.READ_HEART_RATE"/>
+ <uses-permission android:name="android.permission.health.READ_HEART_RATE_VARIABILITY"/>
+ <uses-permission android:name="android.permission.health.READ_OXYGEN_SATURATION"/>
+ <uses-permission android:name="android.permission.health.READ_RESPIRATORY_RATE"/>
+ <uses-permission android:name="android.permission.health.READ_BLOOD_PRESSURE"/>
+ <uses-permission android:name="android.permission.health.READ_BODY_TEMPERATURE"/>
+ <uses-permission android:name="android.permission.health.READ_SLEEP"/>
+ <uses-permission android:name="android.permission.health.READ_DISTANCE"/>
+ <uses-permission android:name="android.permission.health.READ_FLOORS_CLIMBED"/>
+ <uses-permission android:name="android.permission.health.READ_ELEVATION_GAINED"/>
+ <uses-permission android:name="android.permission.health.READ_ACTIVE_CALORIES_BURNED"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" tools:node="remove"/>
<uses-feature android:name="android.hardware.type.watch" android:required="false"/>
diff --git a/android/app/src/main/kotlin/com/gymmane/app/HealthBridge.kt b/android/app/src/main/kotlin/com/gymmane/app/HealthBridge.kt
index 5ee96c9..7a87877 100644
--- a/android/app/src/main/kotlin/com/gymmane/app/HealthBridge.kt
+++ b/android/app/src/main/kotlin/com/gymmane/app/HealthBridge.kt
@@ -3,18 +3,39 @@ package com.gymmane.app
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
+import android.health.connect.AggregateRecordsGroupedByPeriodResponse
import android.health.connect.AggregateRecordsRequest
import android.health.connect.AggregateRecordsResponse
import android.health.connect.HealthConnectException
import android.health.connect.HealthConnectManager
import android.health.connect.HealthPermissions
+import android.health.connect.LocalTimeRangeFilter
+import android.health.connect.ReadRecordsRequestUsingFilters
+import android.health.connect.ReadRecordsResponse
import android.health.connect.TimeInstantRangeFilter
+import android.health.connect.datatypes.ActiveCaloriesBurnedRecord
+import android.health.connect.datatypes.AggregationType
+import android.health.connect.datatypes.BloodPressureRecord
+import android.health.connect.datatypes.BodyTemperatureRecord
+import android.health.connect.datatypes.DistanceRecord
+import android.health.connect.datatypes.ElevationGainedRecord
+import android.health.connect.datatypes.FloorsClimbedRecord
+import android.health.connect.datatypes.HeartRateRecord
+import android.health.connect.datatypes.HeartRateVariabilityRmssdRecord
+import android.health.connect.datatypes.OxygenSaturationRecord
+import android.health.connect.datatypes.Record
+import android.health.connect.datatypes.RespiratoryRateRecord
+import android.health.connect.datatypes.RestingHeartRateRecord
+import android.health.connect.datatypes.SleepSessionRecord
import android.health.connect.datatypes.StepsRecord
import android.os.Build
import android.os.OutcomeReceiver
import androidx.annotation.RequiresApi
import io.flutter.plugin.common.MethodChannel
import java.time.Instant
+import java.time.LocalDateTime
+import java.time.Period
+import java.time.ZoneId
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
@@ -26,6 +47,23 @@ object HealthBridge {
private val supported get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
+ private const val MAX_ROWS = 20000
+
+ private val metrics = mapOf(
+ "restingHr" to "android.permission.health.READ_RESTING_HEART_RATE",
+ "heartRate" to "android.permission.health.READ_HEART_RATE",
+ "hrv" to "android.permission.health.READ_HEART_RATE_VARIABILITY",
+ "spo2" to "android.permission.health.READ_OXYGEN_SATURATION",
+ "respiration" to "android.permission.health.READ_RESPIRATORY_RATE",
+ "bloodPressure" to "android.permission.health.READ_BLOOD_PRESSURE",
+ "temperature" to "android.permission.health.READ_BODY_TEMPERATURE",
+ "sleep" to "android.permission.health.READ_SLEEP",
+ "distance" to "android.permission.health.READ_DISTANCE",
+ "floors" to "android.permission.health.READ_FLOORS_CLIMBED",
+ "elevation" to "android.permission.health.READ_ELEVATION_GAINED",
+ "activeKcal" to "android.permission.health.READ_ACTIVE_CALORIES_BURNED",
+ )
+
fun attach(activity: Activity, channel: MethodChannel) {
this.channel = channel
channel.setMethodCallHandler { call, result ->
@@ -42,6 +80,15 @@ object HealthBridge {
"request" -> request(activity, result)
"openSettings" -> result.success(openSettings(activity))
"readSteps" -> readSteps(activity, call.argument<List<List<Number>>>("ranges").orEmpty(), result)
+ "metricsGranted" -> result.success(metricsGranted(activity))
+ "requestMetrics" -> requestMetrics(activity, call.argument<List<String>>("metrics").orEmpty(), result)
+ "readMetric" -> readMetric(
+ activity,
+ call.argument<String>("metric").orEmpty(),
+ call.argument<Number>("from")?.toLong() ?: 0L,
+ call.argument<Number>("to")?.toLong() ?: 0L,
+ result,
+ )
else -> result.notImplemented()
}
}
@@ -76,15 +123,157 @@ object HealthBridge {
activity.requestPermissions(arrayOf(HealthPermissions.READ_STEPS), REQUEST_CODE)
}
+ private fun metricsGranted(activity: Activity): List<String> =
+ metrics.filterValues { activity.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED }.keys.toList()
+
+ @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+ private fun requestMetrics(activity: Activity, keys: List<String>, result: MethodChannel.Result) {
+ if (activity.getSystemService(HealthConnectManager::class.java) == null) return result.success(false)
+ val wanted = keys.mapNotNull { metrics[it] }
+ .filter { activity.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
+ if (wanted.isEmpty()) return result.success(keys.all { it in metrics })
+ pending?.success(false)
+ pending = result
+ activity.requestPermissions(wanted.toTypedArray(), REQUEST_CODE)
+ }
+
+ @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+ private fun readMetric(activity: Activity, key: String, from: Long, to: Long, result: MethodChannel.Result) {
+ val manager = activity.getSystemService(HealthConnectManager::class.java)
+ val permission = metrics[key]
+ if (manager == null || permission == null || to <= from ||
+ activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED
+ ) {
+ return result.success(null)
+ }
+ val reader = Reader(activity, manager, from, to, result)
+ when (key) {
+ "restingHr" -> reader.daily(RestingHeartRateRecord.BPM_AVG) { it.toDouble() }
+ "heartRate" -> reader.daily(HeartRateRecord.BPM_AVG) { it.toDouble() }
+ "distance" -> reader.daily(DistanceRecord.DISTANCE_TOTAL) { it.inMeters }
+ "floors" -> reader.daily(FloorsClimbedRecord.FLOORS_CLIMBED_TOTAL) { it }
+ "elevation" -> reader.daily(ElevationGainedRecord.ELEVATION_GAINED_TOTAL) { it.inMeters }
+ "activeKcal" -> reader.daily(ActiveCaloriesBurnedRecord.ACTIVE_CALORIES_TOTAL) { it.inCalories / 1000 }
+ "hrv" -> reader.records(HeartRateVariabilityRmssdRecord::class.java) {
+ listOf(it.time.toEpochMilli().toDouble(), it.heartRateVariabilityMillis)
+ }
+ "spo2" -> reader.records(OxygenSaturationRecord::class.java) {
+ listOf(it.time.toEpochMilli().toDouble(), it.percentage.value)
+ }
+ "respiration" -> reader.records(RespiratoryRateRecord::class.java) {
+ listOf(it.time.toEpochMilli().toDouble(), it.rate)
+ }
+ "bloodPressure" -> reader.records(BloodPressureRecord::class.java) {
+ listOf(
+ it.time.toEpochMilli().toDouble(),
+ it.systolic.inMillimetersOfMercury,
+ it.diastolic.inMillimetersOfMercury,
+ )
+ }
+ "temperature" -> reader.records(BodyTemperatureRecord::class.java) {
+ listOf(it.time.toEpochMilli().toDouble(), it.temperature.inCelsius)
+ }
+ "sleep" -> reader.records(SleepSessionRecord::class.java) {
+ val start = it.startTime.toEpochMilli()
+ val end = it.endTime.toEpochMilli()
+ listOf(end.toDouble(), (end - start) / 60000.0)
+ }
+ else -> result.success(null)
+ }
+ }
+
+ @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+ private class Reader(
+ val activity: Activity,
+ val manager: HealthConnectManager,
+ val from: Long,
+ val to: Long,
+ val result: MethodChannel.Result,
+ ) {
+ fun <T> daily(type: AggregationType<T>, value: (T) -> Double) {
+ val zone = ZoneId.systemDefault()
+ val filter = LocalTimeRangeFilter.Builder()
+ .setStartTime(LocalDateTime.ofInstant(Instant.ofEpochMilli(from), zone))
+ .setEndTime(LocalDateTime.ofInstant(Instant.ofEpochMilli(to), zone))
+ .build()
+ val request = AggregateRecordsRequest.Builder<T>(filter).addAggregationType(type).build()
+ try {
+ manager.aggregateGroupByPeriod(
+ request,
+ Period.ofDays(1),
+ activity.mainExecutor,
+ object : OutcomeReceiver<List<AggregateRecordsGroupedByPeriodResponse<T>>, HealthConnectException> {
+ override fun onResult(groups: List<AggregateRecordsGroupedByPeriodResponse<T>>) {
+ result.success(
+ groups.mapNotNull { g ->
+ val v: T = g.get(type) ?: return@mapNotNull null
+ listOf(g.startTime.atZone(zone).toInstant().toEpochMilli().toDouble(), value(v))
+ },
+ )
+ }
+
+ override fun onError(error: HealthConnectException) {
+ result.success(null)
+ }
+ },
+ )
+ } catch (e: Exception) {
+ result.success(null)
+ }
+ }
+
+ fun <T : Record> records(type: Class<T>, row: (T) -> List<Double>) {
+ val filter = TimeInstantRangeFilter.Builder()
+ .setStartTime(Instant.ofEpochMilli(from))
+ .setEndTime(Instant.ofEpochMilli(to))
+ .build()
+ val rows = mutableListOf<List<Double>>()
+ fun page(token: Long?) {
+ val builder = ReadRecordsRequestUsingFilters.Builder(type)
+ .setTimeRangeFilter(filter)
+ .setPageSize(1000)
+ if (token != null) builder.setPageToken(token)
+ try {
+ manager.readRecords(
+ builder.build(),
+ activity.mainExecutor,
+ object : OutcomeReceiver<ReadRecordsResponse<T>, HealthConnectException> {
+ override fun onResult(response: ReadRecordsResponse<T>) {
+ response.records.forEach { rows.add(row(it)) }
+ val next = response.nextPageToken
+ if (next != -1L && rows.size < MAX_ROWS) page(next) else result.success(rows)
+ }
+
+ override fun onError(error: HealthConnectException) {
+ result.success(if (rows.isEmpty()) null else rows)
+ }
+ },
+ )
+ } catch (e: Exception) {
+ result.success(if (rows.isEmpty()) null else rows)
+ }
+ }
+ page(null)
+ }
+ }
+
@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
- private fun openSettings(activity: Activity): Boolean = try {
- activity.startActivity(
+ private fun openSettings(activity: Activity): Boolean {
+ val tries = listOf(
Intent(HealthConnectManager.ACTION_MANAGE_HEALTH_PERMISSIONS)
.putExtra(Intent.EXTRA_PACKAGE_NAME, activity.packageName),
+ Intent("android.health.connect.action.HEALTH_HOME_SETTINGS"),
+ Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
+ .setData(android.net.Uri.fromParts("package", activity.packageName, null)),
)
- true
- } catch (e: Exception) {
- false
+ for (intent in tries) {
+ try {
+ activity.startActivity(intent)
+ return true
+ } catch (e: Exception) {
+ }
+ }
+ return false
}
@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
diff --git a/lib/services/health_metrics.dart b/lib/services/health_metrics.dart
new file mode 100644
index 0000000..b07ec70
--- /dev/null
+++ b/lib/services/health_metrics.dart
@@ -0,0 +1,113 @@
+import 'dart:io';
+
+import 'package:flutter/services.dart';
+
+enum HealthGroup { heart, vitals, sleep, activity }
+
+enum HealthMetric {
+ restingHr(HealthGroup.heart),
+ heartRate(HealthGroup.heart),
+ hrv(HealthGroup.heart),
+ spo2(HealthGroup.vitals),
+ respiration(HealthGroup.vitals),
+ bloodPressure(HealthGroup.vitals),
+ temperature(HealthGroup.vitals),
+ sleep(HealthGroup.sleep),
+ distance(HealthGroup.activity),
+ floors(HealthGroup.activity),
+ elevation(HealthGroup.activity),
+ activeKcal(HealthGroup.activity);
+
+ const HealthMetric(this.group);
+
+ final HealthGroup group;
+
+ bool get daily => switch (this) {
+ restingHr || heartRate || distance || floors || elevation || activeKcal => true,
+ _ => false,
+ };
+
+ bool get summed => switch (this) {
+ sleep || distance || floors || elevation || activeKcal => true,
+ _ => false,
+ };
+}
+
+class HealthMetrics {
+ const HealthMetrics._();
+
+ static const _channel = MethodChannel('gymmane/health');
+
+ static Future<Set<HealthMetric>> granted() async {
+ if (!Platform.isAndroid) return {};
+ try {
+ final keys = await _channel.invokeListMethod<String>('metricsGranted') ?? const [];
+ final byName = HealthMetric.values.asNameMap();
+ return {for (final k in keys) ?byName[k]};
+ } on PlatformException {
+ return {};
+ } on MissingPluginException {
+ return {};
+ }
+ }
+
+ static Future<bool> request(Iterable<HealthMetric> metrics) async {
+ if (!Platform.isAndroid) return false;
+ try {
+ return await _channel.invokeMethod<bool>('requestMetrics', {
+ 'metrics': [for (final m in metrics) m.name],
+ }) ??
+ false;
+ } on PlatformException {
+ return false;
+ } on MissingPluginException {
+ return false;
+ }
+ }
+
+ static Future<List<List<double>>?> read(HealthMetric metric, DateTime from, DateTime to) async {
+ if (!Platform.isAndroid) return null;
+ try {
+ final rows = await _channel.invokeListMethod<Object?>('readMetric', {
+ 'metric': metric.name,
+ 'from': from.millisecondsSinceEpoch,
+ 'to': to.millisecondsSinceEpoch,
+ });
+ if (rows == null) return null;
+ return [
+ for (final r in rows)
+ if (r is List && r.length >= 2) [for (final v in r) (v as num).toDouble()],
+ ];
+ } on PlatformException {
+ return null;
+ } on MissingPluginException {
+ return null;
+ }
+ }
+
+ static Map<String, List<double>> byDay(HealthMetric metric, List<List<double>> rows) {
+ final sums = <String, List<double>>{};
+ final counts = <String, int>{};
+ for (final r in rows) {
+ final t = DateTime.fromMillisecondsSinceEpoch(r[0].round());
+ final key = dayKey(t);
+ final values = r.sublist(1);
+ final acc = sums[key];
+ if (acc == null) {
+ sums[key] = [...values];
+ } else {
+ for (var i = 0; i < acc.length && i < values.length; i++) {
+ acc[i] += values[i];
+ }
+ }
+ counts[key] = (counts[key] ?? 0) + 1;
+ }
+ if (metric.daily || metric.summed) return sums;
+ return {
+ for (final e in sums.entries) e.key: [for (final v in e.value) v / counts[e.key]!],
+ };
+ }
+
+ static String dayKey(DateTime d) =>
+ '${d.year}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}';
+}
diff --git a/lib/state/health_state.dart b/lib/state/health_state.dart
new file mode 100644
index 0000000..dba815a
--- /dev/null
+++ b/lib/state/health_state.dart
@@ -0,0 +1,152 @@
+part of 'fit_state.dart';
+
+mixin HealthState on FitCore {
+ static const healthDays = 30;
+
+ final Set<HealthMetric> healthShown = {};
+ final List<HealthMetric> healthPinned = [];
+ Set<HealthMetric> healthGranted = {};
+ final Map<HealthMetric, Map<String, List<double>>> healthByDay = {};
+ Future<void>? _healthRunning;
+
+ List<HealthMetric> get healthMetrics => [for (final m in HealthMetric.values) if (healthShown.contains(m)) m];
+
+ List<HealthMetric> get healthTop {
+ final pinned = [for (final m in healthPinned) if (healthShown.contains(m)) m];
+ if (pinned.isNotEmpty) return pinned;
+ const preferred = [HealthMetric.sleep, HealthMetric.restingHr, HealthMetric.activeKcal];
+ return [
+ ...[for (final m in preferred) if (healthShown.contains(m)) m],
+ ...[for (final m in healthMetrics) if (!preferred.contains(m)) m],
+ ].take(3).toList();
+ }
+
+ void toggleHealthPin(HealthMetric m) {
+ final current = healthTop;
+ healthPinned
+ ..clear()
+ ..addAll(current);
+ if (healthPinned.contains(m)) {
+ if (healthPinned.length > 1) healthPinned.remove(m);
+ } else if (healthPinned.length < 3) {
+ healthPinned.add(m);
+ }
+ _persist();
+ notifyListeners();
+ }
+
+ Future<bool> allowAllHealth() async {
+ final missing = [for (final m in HealthMetric.values) if (!healthGranted.contains(m)) m];
+ if (missing.isNotEmpty) {
+ await HealthMetrics.request(missing);
+ healthGranted = await HealthMetrics.granted();
+ }
+ final now = [for (final m in HealthMetric.values) if (healthGranted.contains(m)) m];
+ if (now.isEmpty) {
+ notifyListeners();
+ return false;
+ }
+ healthShown.addAll(now);
+ _persist();
+ notifyListeners();
+ await _healthRunning;
+ await refreshHealth();
+ return now.length == HealthMetric.values.length;
+ }
+
+ void loadHealth(Map<String, dynamic>? j) {
+ final byName = HealthMetric.values.asNameMap();
+ healthShown
+ ..clear()
+ ..addAll([for (final k in (j?['on'] as List?) ?? const []) ?byName[k]]);
+ healthPinned
+ ..clear()
+ ..addAll([for (final k in (j?['pin'] as List?) ?? const []) ?byName[k]]);
+ healthByDay.clear();
+ ((j?['days'] as Map?) ?? const {}).forEach((k, v) {
+ final m = byName[k];
+ if (m == null || v is! Map) return;
+ healthByDay[m] = v.map((d, xs) => MapEntry(d as String, [for (final x in xs as List) (x as num).toDouble()]));
+ });
+ }
+
+ Map<String, dynamic> healthJson() => {
+ if (healthShown.isNotEmpty) 'on': [for (final m in healthMetrics) m.name],
+ if (healthPinned.isNotEmpty) 'pin': [for (final m in healthPinned) m.name],
+ if (healthByDay.isNotEmpty) 'days': {for (final e in healthByDay.entries) e.key.name: e.value},
+ };
+
+ List<double>? healthOnDay(HealthMetric m, DateTime day) => healthByDay[m]?[HealthMetrics.dayKey(day)];
+
+ ({DateTime day, List<double> values})? healthLatest(HealthMetric m) {
+ final days = healthByDay[m];
+ if (days == null || days.isEmpty) return null;
+ final key = days.keys.reduce((a, b) => a.compareTo(b) >= 0 ? a : b);
+ return (day: DateTime.parse(key), values: days[key]!);
+ }
+
+ List<DateTime> healthLastDays(int n) {
+ final now = DateTime.now();
+ return [for (var i = n - 1; i >= 0; i--) DateTime(now.year, now.month, now.day - i)];
+ }
+
+ List<double?> healthSeries(HealthMetric m, int n) =>
+ [for (final d in healthLastDays(n)) healthOnDay(m, d)?.first];
+
+ Future<void> refreshHealth() => _healthRunning ??= _syncHealth().whenComplete(() => _healthRunning = null);
+
+ Future<void> _syncHealth() async {
+ if (healthShown.isEmpty) return;
+ final granted = await HealthMetrics.granted();
+ var dirty = !setEquals(granted, healthGranted);
+ healthGranted = granted;
+ final now = DateTime.now();
+ final from = DateTime(now.year, now.month, now.day - healthDays + 1);
+ final to = DateTime(now.year, now.month, now.day + 1);
+ for (final m in healthMetrics) {
+ if (!granted.contains(m)) continue;
+ final rows = await HealthMetrics.read(m, from, to);
+ if (rows == null) continue;
+ final days = HealthMetrics.byDay(m, rows);
+ if (_sameDays(healthByDay[m], days)) continue;
+ healthByDay[m] = days;
+ dirty = true;
+ }
+ if (!dirty) return;
+ _persist();
+ notifyListeners();
+ }
+
+ static bool _sameDays(Map<String, List<double>>? a, Map<String, List<double>> b) {
+ if (a == null || a.length != b.length) return false;
+ for (final e in b.entries) {
+ final o = a[e.key];
+ if (o == null || !listEquals(o, e.value)) return false;
+ }
+ return true;
+ }
+
+ Future<bool> setHealthMetric(HealthMetric m, bool on) async {
+ if (on && !healthGranted.contains(m)) {
+ final ok = await HealthMetrics.request([m]);
+ healthGranted = await HealthMetrics.granted();
+ if (!ok && !healthGranted.contains(m)) {
+ notifyListeners();
+ return false;
+ }
+ }
+ if (on) {
+ healthShown.add(m);
+ } else {
+ healthShown.remove(m);
+ healthByDay.remove(m);
+ }
+ _persist();
+ notifyListeners();
+ if (on) {
+ await _healthRunning;
+ await refreshHealth();
+ }
+ return true;
+ }
+}
diff --git a/lib/widgets/health_cards.dart b/lib/widgets/health_cards.dart
new file mode 100644
index 0000000..7ada575
--- /dev/null
+++ b/lib/widgets/health_cards.dart
@@ -0,0 +1,682 @@
+import 'dart:math' as math;
+
+import 'package:flutter/material.dart';
+import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';
+
+import '../l10n/l10n.dart';
+import '../services/health_metrics.dart';
+import '../services/health_steps.dart';
+import '../state/fit_state.dart';
+import '../theme/app_colors.dart';
+import '../theme/app_theme.dart';
+import 'charts.dart';
+import 'entrance.dart';
+import 'glass.dart';
+import 'nutrition_art.dart' show ValueLineChart;
+import 'ui_kit.dart';
+
+String healthName(HealthMetric m) => switch (m) {
+ HealthMetric.restingHr => t.healthRestingHr,
+ HealthMetric.heartRate => t.healthHeartRate,
+ HealthMetric.hrv => t.healthHrv,
+ HealthMetric.spo2 => t.healthSpo2,
+ HealthMetric.respiration => t.healthRespiration,
+ HealthMetric.bloodPressure => t.healthBloodPressure,
+ HealthMetric.temperature => t.healthTemperature,
+ HealthMetric.sleep => t.healthSleep,
+ HealthMetric.distance => t.healthDistance,
+ HealthMetric.floors => t.healthFloors,
+ HealthMetric.elevation => t.healthElevation,
+ HealthMetric.activeKcal => t.healthActiveKcal,
+ };
+
+String healthGroupName(HealthGroup g) => switch (g) {
+ HealthGroup.heart => t.healthGroupHeart,
+ HealthGroup.vitals => t.healthGroupVitals,
+ HealthGroup.sleep => t.healthSleep,
+ HealthGroup.activity => t.healthGroupActivity,
+ };
+
+IconData healthIcon(HealthMetric m) => switch (m) {
+ HealthMetric.restingHr => PhosphorIconsFill.heart,
+ HealthMetric.heartRate => PhosphorIconsFill.heartbeat,
+ HealthMetric.hrv => PhosphorIconsFill.waveform,
+ HealthMetric.spo2 => PhosphorIconsFill.drop,
+ HealthMetric.respiration => PhosphorIconsFill.wind,
+ HealthMetric.bloodPressure => PhosphorIconsFill.gauge,
+ HealthMetric.temperature => PhosphorIconsFill.thermometer,
+ HealthMetric.sleep => PhosphorIconsFill.moonStars,
+ HealthMetric.distance => PhosphorIconsFill.path,
+ HealthMetric.floors => PhosphorIconsFill.stairs,
+ HealthMetric.elevation => PhosphorIconsFill.mountains,
+ HealthMetric.activeKcal => PhosphorIconsFill.fire,
+ };
+
+Color healthTone(GymColors gc, HealthGroup g) => switch (g) {
+ HealthGroup.heart => gc.accent,
+ HealthGroup.vitals => gc.info,
+ HealthGroup.sleep => gc.warn,
+ HealthGroup.activity => gc.sage,
+ };
+
+double healthShown(HealthMetric m, double v) => switch (m) {
+ HealthMetric.temperature => fit.isLb ? v * 9 / 5 + 32 : v,
+ HealthMetric.distance => fit.toDisplayKm(v / 1000),
+ HealthMetric.elevation => fit.isLb ? v * 3.28084 : v,
+ HealthMetric.sleep => v / 60,
+ _ => v,
+ };
+
+String healthNumber(HealthMetric m, double v) {
+ final shown = healthShown(m, v);
+ return switch (m) {
+ HealthMetric.sleep => '${v.round() ~/ 60}:${(v.round() % 60).toString().padLeft(2, '0')}',
+ HealthMetric.distance => fmt((shown * 100).round() / 100),
+ HealthMetric.spo2 || HealthMetric.respiration || HealthMetric.temperature => fmt((shown * 10).round() / 10),
+ _ => '${shown.round()}',
+ };
+}
+
+String healthValue(HealthMetric m, List<double> v) => m == HealthMetric.bloodPressure && v.length > 1
+ ? '${v[0].round()}/${v[1].round()}'
+ : healthNumber(m, v.first);
+
+String healthUnit(HealthMetric m) => switch (m) {
+ HealthMetric.restingHr || HealthMetric.heartRate => t.healthBpm,
+ HealthMetric.hrv => 'ms',
+ HealthMetric.spo2 => '%',
+ HealthMetric.respiration => t.healthBreaths,
+ HealthMetric.bloodPressure => 'mmHg',
+ HealthMetric.temperature => fit.isLb ? '°F' : '°C',
+ HealthMetric.sleep => t.unitHours,
+ HealthMetric.distance => fit.distanceUnit,
+ HealthMetric.elevation => fit.isLb ? 'ft' : 'm',
+ HealthMetric.activeKcal => 'kcal',
+ HealthMetric.floors => '',
+ };
+
+String healthWhen(DateTime day) {
+ final now = DateTime.now();
+ final today = DateTime(now.year, now.month, now.day);
+ final d = today.difference(DateTime(day.year, day.month, day.day)).inDays;
+ return d == 0
+ ? t.noteToday
+ : d == 1
+ ? t.noteYesterday
+ : t.shortDate(day);
+}
+
+class HealthCard extends StatelessWidget {
+ const HealthCard({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ final gc = context.gc;
+ final top = fit.healthTop;
+ return Pressable(
+ onTap: () => fit.pushRoute('health'),
+ scale: 0.98,
+ child: Container(
+ padding: const EdgeInsets.fromLTRB(20, 18, 20, 16),
+ decoration: BoxDecoration(color: gc.bgRaised, borderRadius: BorderRadius.circular(26)),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(children: [
+ Icon(PhosphorIconsFill.heartbeat, size: 15, color: gc.accent),
+ const SizedBox(width: 7),
+ Expanded(
+ child: Text(t.healthTitle.toUpperCase(),
+ style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.4)),
+ ),
+ RoundAction(
+ label: t.healthPinTitle,
+ size: 32,
+ onTap: () => showHealthPins(context),
+ child: Icon(PhosphorIconsBold.pencilSimple, size: 14, color: gc.textSecondary),
+ ),
+ ]),
+ const SizedBox(height: 14),
+ IntrinsicHeight(
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ for (var i = 0; i < top.length; i++) ...[
+ if (i > 0)
+ Container(
+ width: 1,
+ margin: const EdgeInsets.symmetric(horizontal: 14),
+ color: gc.border.withValues(alpha: 0.7),
+ ),
+ Expanded(child: _HealthFigure(top[i])),
+ ],
+ ],
+ ),
+ ),
+ const SizedBox(height: 14),
+ Container(height: 1, color: gc.border.withValues(alpha: 0.6)),
+ const SizedBox(height: 12),
+ Row(children: [
+ Expanded(
+ child: Text(t.healthFrom,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppTheme.f(11.5, weight: FontWeight.w500, color: gc.textTertiary)),
+ ),
+ Text('${t.healthSeeAll} · ${fit.healthShown.length}',
+ style: AppTheme.f(12.5, weight: FontWeight.w700, color: gc.text)),
+ const SizedBox(width: 4),
+ Icon(PhosphorIconsBold.caretRight, size: 12, color: gc.text),
+ ]),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class _HealthFigure extends StatelessWidget {
+ const _HealthFigure(this.metric);
+
+ final HealthMetric metric;
+
+ @override
+ Widget build(BuildContext context) {
+ final gc = context.gc;
+ final tone = healthTone(gc, metric.group);
+ final latest = fit.healthLatest(metric);
+ final unit = healthUnit(metric);
+ final series = [for (final v in fit.healthSeries(metric, 14)) if (v != null) healthShown(metric, v)];
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Icon(healthIcon(metric), size: 15, color: tone),
+ const SizedBox(height: 8),
+ FittedBox(
+ fit: BoxFit.scaleDown,
+ alignment: Alignment.centerLeft,
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.baseline,
+ textBaseline: TextBaseline.alphabetic,
+ children: [
+ RollIn(latest == null ? '—' : healthValue(metric, latest.values),
+ style: AppTheme.f(26, weight: FontWeight.w800, color: gc.text)),
+ if (latest != null && unit.isNotEmpty) ...[
+ const SizedBox(width: 3),
+ Text(unit, style: AppTheme.f(11, weight: FontWeight.w600, color: gc.textSecondary)),
+ ],
+ ],
+ ),
+ ),
+ const SizedBox(height: 2),
+ Text(healthName(metric),
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: AppTheme.f(11.5, weight: FontWeight.w600, color: gc.textTertiary, height: 1.2)),
+ const Spacer(),
+ const SizedBox(height: 10),
+ series.length < 2 ? const SizedBox(height: 22) : Sparkline(values: series, height: 22, color: tone),
+ ],
+ );
+ }
+}
+
+class HealthScreen extends StatelessWidget {
+ const HealthScreen({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ final gc = context.gc;
+ final shown = fit.healthMetrics;
+ return RiseScope(
+ id: 'health',
+ child: SafeArea(
+ bottom: false,
+ child: SingleChildScrollView(
+ clipBehavior: Clip.none,
+ padding: const EdgeInsets.fromLTRB(20, 12, 20, 120),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: riseAll([
+ Row(children: [
+ RoundAction(
+ label: t.back,
+ onTap: fit.popRoute,
+ child: Icon(PhosphorIconsBold.caretLeft, size: 16, color: gc.text),
+ ),
+ const Spacer(),
+ RoundAction(
+ label: t.healthPickTitle,
+ onTap: () => showHealthPicker(context),
+ child: Icon(PhosphorIconsBold.slidersHorizontal, size: 16, color: gc.text),
+ ),
+ ]),
+ const SizedBox(height: 18),
+ Text(t.healthTitle,
+ style: AppTheme.f(32, weight: FontWeight.w800, color: gc.text, letterSpacing: -0.9, height: 1.05)),
+ const SizedBox(height: 4),
+ Text(t.healthFrom, style: AppTheme.f(13, weight: FontWeight.w500, color: gc.textSecondary)),
+ for (final g in HealthGroup.values)
+ if (shown.any((m) => m.group == g))
+ Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(4, 24, 0, 10),
+ child: Text(healthGroupName(g).toUpperCase(),
+ style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.4)),
+ ),
+ ..._rows([for (final m in shown) if (m.group == g) m]),
+ ],
+ ),
+ ]),
+ ),
+ ),
+ ),
+ );
+ }
+
+ List<Widget> _rows(List<HealthMetric> metrics) => [
+ for (var i = 0; i < metrics.length; i += 2) ...[
+ if (i > 0) const SizedBox(height: 12),
+ IntrinsicHeight(
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Expanded(child: HealthTile(metrics[i])),
+ if (i + 1 < metrics.length) ...[
+ const SizedBox(width: 12),
+ Expanded(child: HealthTile(metrics[i + 1])),
+ ],
+ ],
+ ),
+ ),
+ ],
+ ];
+}
+
+void showHealthPins(BuildContext context) {
+ final gc = context.gc;
+ showAppSheet<void>(
+ context: context,
+ isScrollControlled: true,
+ backgroundColor: Colors.transparent,
+ builder: (sheet) => ListenableBuilder(
+ listenable: fit,
+ builder: (sheet, _) {
+ final top = fit.healthTop;
+ return ConstrainedBox(
+ constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(sheet).height * 0.85),
+ child: Container(
+ padding: sheetPad(sheet),
+ decoration: BoxDecoration(
+ color: gc.bgRaised,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ const SheetHandle(),
+ const SizedBox(height: 20),
+ Text(t.healthPinTitle, textAlign: TextAlign.center, style: AppTheme.f(19, color: gc.text)),
+ const SizedBox(height: 6),
+ Text(t.healthPinHint,
+ textAlign: TextAlign.center,
+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textSecondary, height: 1.4)),
+ const SizedBox(height: 16),
+ Flexible(
+ child: SingleChildScrollView(
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 14),
+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(18)),
+ child: Column(children: [
+ for (final (i, m) in fit.healthMetrics.indexed) ...[
+ if (i > 0) Divider(height: 1, thickness: 1, color: gc.border),
+ GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () => fit.toggleHealthPin(m),
+ child: SizedBox(
+ height: 52,
+ child: Row(children: [
+ Icon(healthIcon(m), size: 17, color: healthTone(gc, m.group)),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Text(healthName(m),
+ style: AppTheme.f(14.5, weight: FontWeight.w500, color: gc.text)),
+ ),
+ AnimatedScale(
+ scale: top.contains(m) ? 1 : 0.7,
+ duration: const Duration(milliseconds: 240),
+ curve: Curves.easeOutBack,
+ child: Icon(
+ top.contains(m) ? PhosphorIconsFill.checkCircle : PhosphorIconsRegular.circle,
+ size: 22,
+ color: top.contains(m) ? gc.accent : gc.textTertiary,
+ ),
+ ),
+ ]),
+ ),
+ ),
+ ],
+ ]),
+ ),
+ ),
+ ),
+ const SizedBox(height: 16),
+ PrimaryButton(label: t.done, onTap: () => Navigator.of(sheet).pop()),
+ ],
+ ),
+ ),
+ );
+ },
+ ),
+ );
+}
+
+class HealthTile extends StatelessWidget {
+ const HealthTile(this.metric, {super.key});
+
+ final HealthMetric metric;
+
+ @override
+ Widget build(BuildContext context) {
+ final gc = context.gc;
+ final tone = healthTone(gc, metric.group);
+ final latest = fit.healthLatest(metric);
+ final granted = fit.healthGranted.contains(metric);
+ final series = [for (final v in fit.healthSeries(metric, 14)) if (v != null) healthShown(metric, v)];
+ final unit = healthUnit(metric);
+ return Pressable(
+ onTap: granted ? () => showHealthDetail(context, metric) : () => _allow(metric),
+ child: Container(
+ padding: const EdgeInsets.fromLTRB(16, 15, 16, 15),
+ decoration: BoxDecoration(color: gc.bgRaised, borderRadius: BorderRadius.circular(22)),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(children: [
+ Icon(healthIcon(metric), size: 13, color: tone),
+ const SizedBox(width: 6),
+ Expanded(
+ child: FitText(healthName(metric).toUpperCase(),
+ style: AppTheme.f(9.5, weight: FontWeight.w600, color: gc.textTertiary, letterSpacing: 0.8)),
+ ),
+ ]),
+ const SizedBox(height: 10),
+ FittedBox(
+ fit: BoxFit.scaleDown,
+ alignment: Alignment.centerLeft,
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.baseline,
+ textBaseline: TextBaseline.alphabetic,
+ children: [
+ RollIn(latest == null ? '—' : healthValue(metric, latest.values),
+ style: AppTheme.f(25, weight: FontWeight.w800, color: gc.text)),
+ if (latest != null && unit.isNotEmpty) ...[
+ const SizedBox(width: 4),
+ Text(unit, style: AppTheme.f(12, weight: FontWeight.w500, color: gc.textSecondary)),
+ ],
+ ],
+ ),
+ ),
+ const SizedBox(height: 3),
+ Text(
+ !granted
+ ? t.healthAllow
+ : latest == null
+ ? t.healthNoData
+ : healthWhen(latest.day),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppTheme.f(11.5, weight: FontWeight.w500, color: granted ? gc.textTertiary : tone),
+ ),
+ const Spacer(),
+ const SizedBox(height: 10),
+ series.length < 2
+ ? const SizedBox(height: 26)
+ : Sparkline(values: series, height: 26, color: tone),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+Future<void> _allow(HealthMetric m) async {
+ if (!await fit.setHealthMetric(m, true)) await HealthSteps.openSettings();
+}
+
+void showHealthPicker(BuildContext context) {
+ final gc = context.gc;
+ showAppSheet<void>(
+ context: context,
+ isScrollControlled: true,
+ backgroundColor: Colors.transparent,
+ builder: (sheet) => ListenableBuilder(
+ listenable: fit,
+ builder: (sheet, _) => ConstrainedBox(
+ constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(sheet).height * 0.9),
+ child: Container(
+ padding: sheetPad(sheet),
+ decoration: BoxDecoration(
+ color: gc.bgRaised,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ const SheetHandle(),
+ const SizedBox(height: 20),
+ Text(t.healthPickTitle, textAlign: TextAlign.center, style: AppTheme.f(19, color: gc.text)),
+ const SizedBox(height: 6),
+ Text(t.healthPickHint,
+ textAlign: TextAlign.center,
+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textSecondary, height: 1.4)),
+ const SizedBox(height: 16),
+ if (fit.healthShown.length < HealthMetric.values.length)
+ Center(
+ child: Pressable(
+ onTap: () async {
+ if (!await fit.allowAllHealth()) await HealthSteps.openSettings();
+ },
+ child: Container(
+ height: 42,
+ padding: const EdgeInsets.symmetric(horizontal: 20),
+ decoration: BoxDecoration(color: gc.text, borderRadius: BorderRadius.circular(100)),
+ child: Row(mainAxisSize: MainAxisSize.min, children: [
+ Icon(PhosphorIconsBold.checks, size: 16, color: gc.bg),
+ const SizedBox(width: 8),
+ Text(t.healthAllowAll, style: AppTheme.f(14, weight: FontWeight.w800, color: gc.bg)),
+ ]),
+ ),
+ ),
+ ),
+ const SizedBox(height: 6),
+ Flexible(
+ child: SingleChildScrollView(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ for (final g in HealthGroup.values) ...[
+ Padding(
+ padding: const EdgeInsets.fromLTRB(4, 10, 4, 6),
+ child: Text(healthGroupName(g).toUpperCase(),
+ style: AppTheme.f(10,
+ weight: FontWeight.w600, color: gc.textTertiary, letterSpacing: 0.9)),
+ ),
+ Container(
+ padding: const EdgeInsets.symmetric(horizontal: 14),
+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(18)),
+ child: Column(children: [
+ for (final (i, m) in HealthMetric.values.where((m) => m.group == g).indexed) ...[
+ if (i > 0) Divider(height: 1, thickness: 1, color: gc.border),
+ _pickRow(gc, m),
+ ],
+ ]),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(height: 18),
+ Center(
+ child: GhostButton(
+ label: t.stepsManage,
+ icon: PhosphorIconsRegular.shieldCheck,
+ onTap: HealthSteps.openSettings,
+ ),
+ ),
+ const SizedBox(height: 12),
+ PrimaryButton(label: t.done, onTap: () => Navigator.of(sheet).pop()),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+}
+
+Widget _pickRow(GymColors gc, HealthMetric m) {
+ final on = fit.healthShown.contains(m);
+ return GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () async {
+ if (!await fit.setHealthMetric(m, !on)) await HealthSteps.openSettings();
+ },
+ child: SizedBox(
+ height: 52,
+ child: Row(children: [
+ Icon(healthIcon(m), size: 17, color: healthTone(gc, m.group)),
+ const SizedBox(width: 12),
+ Expanded(child: Text(healthName(m), style: AppTheme.f(14.5, weight: FontWeight.w500, color: gc.text))),
+ TinySwitch(on: on),
+ ]),
+ ),
+ );
+}
+
+void showHealthDetail(BuildContext context, HealthMetric metric) {
+ final gc = context.gc;
+ final tone = healthTone(gc, metric.group);
+ final latest = fit.healthLatest(metric);
+ final week = fit.healthLastDays(7);
+ final month = [for (final v in fit.healthSeries(metric, HealthState.healthDays)) ?v];
+ final unit = healthUnit(metric);
+ final pressure = metric == HealthMetric.bloodPressure;
+ final lows = pressure
+ ? [for (final d in fit.healthLastDays(HealthState.healthDays)) if ((fit.healthOnDay(metric, d)?.length ?? 0) > 1) fit.healthOnDay(metric, d)![1]]
+ : const <double>[];
+ String avg(List<double> xs) => xs.isEmpty ? '—' : healthNumber(metric, xs.reduce((a, b) => a + b) / xs.length);
+ String one(List<double> xs, double Function(double, double) pick) =>
+ xs.isEmpty ? '—' : healthNumber(metric, xs.reduce(pick));
+ String pair(String a, String b) => pressure ? '$a/$b' : a;
+ final stats = [
+ (t.healthAvg30, pair(avg(month), avg(lows))),
+ (t.healthLow, pair(one(month, math.min), one(lows, math.min))),
+ (t.healthHigh, pair(one(month, math.max), one(lows, math.max))),
+ ];
+ showAppSheet<void>(
+ context: context,
+ isScrollControlled: true,
+ backgroundColor: Colors.transparent,
+ builder: (sheet) => Container(
+ padding: sheetPad(sheet),
+ decoration: BoxDecoration(
+ color: gc.bgRaised,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ const SheetHandle(),
+ const SizedBox(height: 20),
+ Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ Icon(healthIcon(metric), size: 16, color: tone),
+ const SizedBox(width: 8),
+ Flexible(child: Text(healthName(metric), style: AppTheme.f(19, color: gc.text))),
+ ]),
+ const SizedBox(height: 14),
+ Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ crossAxisAlignment: CrossAxisAlignment.baseline,
+ textBaseline: TextBaseline.alphabetic,
+ children: [
+ Text(latest == null ? '—' : healthValue(metric, latest.values),
+ style: AppTheme.f(40, weight: FontWeight.w800, color: gc.text, height: 1.05)),
+ if (latest != null && unit.isNotEmpty) ...[
+ const SizedBox(width: 6),
+ Text(unit, style: AppTheme.f(15, weight: FontWeight.w600, color: gc.textSecondary)),
+ ],
+ ],
+ ),
+ const SizedBox(height: 4),
+ Text(latest == null ? t.healthNoData : healthWhen(latest.day),
+ textAlign: TextAlign.center,
+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textTertiary)),
+ const SizedBox(height: 20),
+ Padding(
+ padding: const EdgeInsets.only(left: 4, bottom: 8),
+ child: Text(t.healthLast7.toUpperCase(),
+ style: AppTheme.f(10, weight: FontWeight.w600, color: gc.textTertiary, letterSpacing: 0.9)),
+ ),
+ SoftCard(
+ radius: 22,
+ padding: const EdgeInsets.fromLTRB(12, 16, 12, 10),
+ child: ValueLineChart(
+ values: [
+ for (final d in week)
+ if (fit.healthOnDay(metric, d)?.first case final v?) healthShown(metric, v) else null,
+ ],
+ labels: [for (final d in week) t.weekdayInitial(d.weekday)],
+ format: (v) => switch (metric) {
+ HealthMetric.sleep => healthNumber(metric, v * 60),
+ HealthMetric.spo2 ||
+ HealthMetric.respiration ||
+ HealthMetric.temperature ||
+ HealthMetric.distance =>
+ fmt((v * 10).round() / 10),
+ _ => '${v.round()}',
+ },
+ color: tone,
+ highlight: 6,
+ fromZero: metric.summed,
+ height: 150,
+ ),
+ ),
+ const SizedBox(height: 12),
+ Row(children: [
+ for (final (i, (label, value)) in stats.indexed) ...[
+ if (i > 0) const SizedBox(width: 10),
+ Expanded(
+ child: Container(
+ padding: const EdgeInsets.fromLTRB(12, 12, 12, 12),
+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(16)),
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ FitText(label.toUpperCase(),
+ style: AppTheme.f(9, weight: FontWeight.w600, color: gc.textTertiary, letterSpacing: 0.8)),
+ const SizedBox(height: 6),
+ FittedBox(
+ fit: BoxFit.scaleDown,
+ alignment: Alignment.centerLeft,
+ child: Text(value, style: AppTheme.f(17, weight: FontWeight.w800, color: gc.text)),
+ ),
+ ]),
+ ),
+ ),
+ ],
+ ]),
+ const SizedBox(height: 10),
+ Text(t.healthFrom,
+ textAlign: TextAlign.center,
+ style: AppTheme.f(11.5, weight: FontWeight.w500, color: gc.textTertiary)),
+ const SizedBox(height: 16),
+ PrimaryButton(label: t.done, onTap: () => Navigator.of(sheet).pop()),
+ ],
+ ),
+ ),
+ );
+}
diff --git a/test/health_test.dart b/test/health_test.dart
new file mode 100644
index 0000000..7ce036a
--- /dev/null
+++ b/test/health_test.dart
@@ -0,0 +1,123 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:gymmane/l10n/l10n.dart';
+import 'package:gymmane/services/health_metrics.dart';
+import 'package:gymmane/services/local_store.dart';
+import 'package:gymmane/state/fit_state.dart';
+import 'package:gymmane/widgets/health_cards.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ setUp(() async {
+ SharedPreferences.setMockInitialValues({});
+ await Store.instance.init();
+ fit.resetAllData();
+ fit.onboarded = true;
+ setAppLanguage('en');
+ });
+
+ double at(int daysAgo, int hour) {
+ final n = DateTime.now();
+ return DateTime(n.year, n.month, n.day - daysAgo, hour).millisecondsSinceEpoch.toDouble();
+ }
+
+ String key(int daysAgo) {
+ final n = DateTime.now();
+ return HealthMetrics.dayKey(DateTime(n.year, n.month, n.day - daysAgo));
+ }
+
+ group('#281 datos de salud por día', () {
+ test('las medidas sueltas se promedian por día', () {
+ final days = HealthMetrics.byDay(HealthMetric.spo2, [
+ [at(0, 8), 96],
+ [at(0, 20), 98],
+ [at(1, 9), 95],
+ ]);
+ expect(days[key(0)], [97]);
+ expect(days[key(1)], [95]);
+ });
+
+ test('la tensión promedia la alta y la baja por separado', () {
+ final days = HealthMetrics.byDay(HealthMetric.bloodPressure, [
+ [at(0, 8), 120, 80],
+ [at(0, 21), 130, 84],
+ ]);
+ expect(days[key(0)], [125, 82]);
+ });
+
+ test('el sueño de un día se suma y cuenta en el día en que acaba', () {
+ final days = HealthMetrics.byDay(HealthMetric.sleep, [
+ [at(0, 7), 420],
+ [at(0, 16), 30],
+ ]);
+ expect(days[key(0)], [450]);
+ expect(days.containsKey(key(1)), isFalse);
+ });
+
+ test('los totales diarios se quedan tal cual', () {
+ final days = HealthMetrics.byDay(HealthMetric.floors, [
+ [at(1, 0), 12],
+ [at(0, 0), 4],
+ ]);
+ expect(days[key(1)], [12]);
+ expect(days[key(0)], [4]);
+ });
+ });
+
+ group('#281 estado de salud', () {
+ test('lo elegido y los datos se guardan y vuelven al reabrir', () {
+ fit.healthShown.addAll({HealthMetric.sleep, HealthMetric.restingHr});
+ fit.healthByDay[HealthMetric.restingHr] = {key(0): [58], key(2): [61]};
+ fit.persistNow();
+ fit.healthShown.clear();
+ fit.healthByDay.clear();
+ fit.loadFromStore();
+
+ expect(fit.healthMetrics, [HealthMetric.restingHr, HealthMetric.sleep]);
+ expect(fit.healthOnDay(HealthMetric.restingHr, DateTime.now()), [58]);
+ expect(fit.healthLatest(HealthMetric.restingHr)!.values, [58]);
+ final week = fit.healthSeries(HealthMetric.restingHr, 7);
+ expect(week.length, 7);
+ expect(week.last, 58);
+ expect(week[4], 61);
+ expect(week[5], isNull);
+ });
+
+ test('borrar todo deja la salud vacía', () {
+ fit.healthShown.add(HealthMetric.hrv);
+ fit.healthByDay[HealthMetric.hrv] = {key(0): [42]};
+ fit.resetAllData();
+ expect(fit.healthShown, isEmpty);
+ expect(fit.healthByDay, isEmpty);
+ });
+
+ test('lo último es el día más reciente con datos', () {
+ fit.healthByDay[HealthMetric.spo2] = {key(5): [95], key(1): [97], key(3): [96]};
+ final last = fit.healthLatest(HealthMetric.spo2)!;
+ expect(last.values, [97]);
+ expect(HealthMetrics.dayKey(last.day), key(1));
+ });
+ });
+
+ group('#281 cómo se enseñan', () {
+ test('sueño en horas y minutos, tensión alta/baja', () {
+ expect(healthValue(HealthMetric.sleep, [452]), '7:32');
+ expect(healthValue(HealthMetric.bloodPressure, [121.4, 79.6]), '121/80');
+ expect(healthValue(HealthMetric.restingHr, [57.6]), '58');
+ });
+
+ test('distancia, desnivel y temperatura siguen las unidades', () {
+ fit.setUnits('kg');
+ expect(healthValue(HealthMetric.distance, [5230]), '5.23');
+ expect(healthUnit(HealthMetric.distance), 'km');
+ expect(healthValue(HealthMetric.temperature, [36.64]), '36.6');
+ expect(healthUnit(HealthMetric.temperature), '°C');
+ fit.setUnits('lb');
+ expect(healthUnit(HealthMetric.distance), 'mi');
+ expect(healthValue(HealthMetric.temperature, [37]), '98.6');
+ expect(healthUnit(HealthMetric.elevation), 'ft');
+ expect(healthValue(HealthMetric.elevation, [100]), '328');
+ });
+ });
+}