Modern Apps git

← Modern-Apps.git

health: feat: line charts for several numerical values that don't accumulate

Commit
7019c8590f13102d034eb011d056eb49b3598a7b
Author
Vayun Mathur <[email protected]>
When
2026-02-11 08:25 UTC (9 months ago)
Parents
74d5097

Diff

health/src/main/java/com/vayunmathur/health/HealthAPI.kt
diff --git a/health/src/main/java/com/vayunmathur/health/HealthAPI.kt b/health/src/main/java/com/vayunmathur/health/HealthAPI.ktindex 490493a634..5fa9d5cf5d 100644--- a/health/src/main/java/com/vayunmathur/health/HealthAPI.kt+++ b/health/src/main/java/com/vayunmathur/health/HealthAPI.kt@@ -47,12 +47,12 @@ object HealthAPI {     }      @Composable-    fun maxInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {+    fun maxInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double?> {         return remember { db.healthDao().maxInRange(recordType, startTime, endTime) }     }      @Composable-    fun minInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {+    fun minInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double?> {         return remember { db.healthDao().minInRange(recordType, startTime, endTime) }     } @@ -64,6 +64,48 @@ object HealthAPI {         Hourly, Daily, Weekly     } +    suspend fun getListOfAverages(+        recordType: RecordType,+        startTime: Instant,+        endTime: Instant,+        period: PeriodType+    ): List<Double?> {+        val tz = TimeZone.currentSystemDefault()+        val avgs = mutableListOf<Double?>()++        var currentStart = startTime++        while (currentStart < endTime) {+            val nextStart = when (period) {+                PeriodType.Hourly -> {+                    currentStart.plus(1.hours)+                }+                PeriodType.Daily -> {+                    // Shift to local time, add a day, shift back to Instant+                    val localDateTime = currentStart.toLocalDateTime(tz)+                    val nextLocalDate = localDateTime.date.plus(1, DateTimeUnit.DAY)+                    nextLocalDate.atTime(localDateTime.hour, localDateTime.minute).toInstant(tz)+                }+                PeriodType.Weekly -> {+                    val localDateTime = currentStart.toLocalDateTime(tz)+                    val nextLocalDate = localDateTime.date.plus(1, DateTimeUnit.WEEK)+                    nextLocalDate.atTime(localDateTime.hour, localDateTime.minute).toInstant(tz)+                }+            }++            // Clamp the end range to the requested endTime+            val currentEnd = if (nextStart > endTime) endTime else nextStart++            // Fetch sum from DAO+            val avg = db.healthDao().avgInRangeGet(recordType, currentStart, currentEnd)+            avgs.add(avg)++            currentStart = nextStart+        }++        return avgs+    }+     suspend fun getListOfSums(         recordType: RecordType,         startTime: Instant,
health/src/main/java/com/vayunmathur/health/database/StepsRecordEntity.kt
diff --git a/health/src/main/java/com/vayunmathur/health/database/StepsRecordEntity.kt b/health/src/main/java/com/vayunmathur/health/database/StepsRecordEntity.ktindex 3192fef073..d2a8dfef74 100644--- a/health/src/main/java/com/vayunmathur/health/database/StepsRecordEntity.kt+++ b/health/src/main/java/com/vayunmathur/health/database/StepsRecordEntity.kt@@ -43,14 +43,18 @@ interface HealthDao {     @Query("SELECT * FROM Record WHERE type = :type ORDER BY startTime DESC LIMIT 1")     suspend fun getLastRecord(type: RecordType): Record? -    @Query("SELECT SUM(value) FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")+    @Query("SELECT COALESCE(SUM(value), 0.0) FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")     fun sumInRange(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Flow<Double>-    @Query("SELECT SUM(value) FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")+    @Query("SELECT COALESCE(SUM(value), 0.0) FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")     suspend fun sumInRangeGet(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Double+    @Query("SELECT AVG(value) FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")+    suspend fun avgInRangeGet(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Double?     @Query("SELECT MIN(value) FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")-    fun minInRange(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Flow<Double>+    fun minInRange(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Flow<Double?>     @Query("SELECT MAX(value) FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")-    fun maxInRange(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Flow<Double>+    fun maxInRange(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Flow<Double?>+    @Query("SELECT * FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")+    fun getAllInRange(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Flow<List<Record>> }  @Database(
health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt b/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.ktindex ff81d2fd16..29524b5289 100644--- a/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt@@ -1,7 +1,6 @@ package com.vayunmathur.health.ui  import androidx.compose.foundation.Canvas-import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items@@ -13,14 +12,13 @@ import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp-import androidx.health.connect.client.aggregate.AggregateMetric-import androidx.health.connect.client.aggregate.AggregationResult-import androidx.health.connect.client.records.* import androidx.navigation3.runtime.NavBackStack import com.vayunmathur.health.HealthAPI import com.vayunmathur.health.Route@@ -40,38 +38,47 @@ import kotlinx.datetime.todayIn import kotlin.time.Clock  /**- * Configuration for different health metrics to make the UI reusable.- * Converted to an enum class for easier serialization/navigation.+ * Configuration for different health metrics.+ * Biological markers (HRV, Breathing, etc) use Line Charts and Average-based aggregation.  */ enum class HealthMetricConfig(     val title: String,     val recordType: RecordType,     val unit: String,-    val dailyGoal: Long+    val dailyGoal: Double,+    val isLineChart: Boolean = false,+    val useDecimals: Boolean = false ) {-    ENERGY("Energy Burned", RecordType.CaloriesTotal, "cal", 2470),-    ACTIVE_CALORIES("Active Calories", RecordType.CaloriesActive, "cal", 500),-    BASAL_METABOLIC_RATE("Basal Metabolic Rate", RecordType.CaloriesBasal, "cal", 1800),-    STEPS("Steps", RecordType.Steps, "steps", 10000),-    WHEELCHAIR_PUSHES("Wheelchair Pushes", RecordType.Wheelchair, "pushes", 3000),-    DISTANCE("Distance", RecordType.Distance, "km", 5),-    ELEVATION("Elevation Gained", RecordType.Elevation, "m", 50),-    FLOORS("Floors Climbed", RecordType.Floors, "floors", 10)+    ENERGY("Energy Burned", RecordType.CaloriesTotal, "cal", 2470.0),+    ACTIVE_CALORIES("Active Calories", RecordType.CaloriesActive, "cal", 500.0),+    BASAL_METABOLIC_RATE("Basal Metabolic Rate", RecordType.CaloriesBasal, "cal", 1800.0),+    STEPS("Steps", RecordType.Steps, "steps", 10000.0),+    WHEELCHAIR_PUSHES("Wheelchair Pushes", RecordType.Wheelchair, "pushes", 3000.0),+    DISTANCE("Distance", RecordType.Distance, "km", 5.0, useDecimals = true),+    ELEVATION("Elevation Gained", RecordType.Elevation, "m", 50.0, useDecimals = true),+    FLOORS("Floors Climbed", RecordType.Floors, "floors", 10.0, useDecimals = true),++    // Biological Metrics (Line Charts + Averages)+    BREATHING_RATE("Breathing Rate", RecordType.RespiratoryRate, "brpm", 16.0, isLineChart = true, useDecimals = true),+    RESTING_HEART_RATE("Resting Heart Rate", RecordType.RestingHeartRate, "bpm", 60.0, isLineChart = true),+    OXYGEN_SATURATION("Oxygen Saturation", RecordType.OxygenSaturation, "%", 95.0, isLineChart = true, useDecimals = true),+    HRV("Heart Rate Variability", RecordType.HeartRateVariabilityRmssd, "ms", 50.0, isLineChart = true, useDecimals = true) }  data class MetricDashboardData(-    val totalValue: Long = 0,-    val dailyAverage: Long = 0,-    val chartData: List<Pair<String, Long>> = emptyList(),+    val totalValue: Double = 0.0,+    val dailyAverage: Double = 0.0,+    val chartData: List<Pair<String, Double?>> = emptyList(),     val historyItems: List<HistoryItem> = emptyList(),     val totalBarCount: Int = 0 )  data class HistoryItem(     val label: String,-    val value: Long,+    val value: Double?,     val unit: String,-    val isGoalMet: Boolean+    val isGoalMet: Boolean,+    val useDecimals: Boolean )  @OptIn(ExperimentalMaterial3Api::class)@@ -83,7 +90,6 @@ fun BarChartDetails(     var selectedTab by remember { mutableIntStateOf(2) }     val tabs = listOf("Day", "Week", "Month", "Year") -    // Switch to kotlinx-datetime     var anchorDate by remember { mutableStateOf(Clock.System.todayIn(TimeZone.currentSystemDefault())) }     var dataState by remember { mutableStateOf(MetricDashboardData()) } @@ -108,41 +114,56 @@ fun BarChartDetails(             else -> {                 val start = LocalDate(anchorDate.year, 1, 1)                 val end = start.plus(1, DateTimeUnit.YEAR)-                Triple(start.atStartOfDayIn(tz), end.atStartOfDayIn(tz), HealthAPI.PeriodType.Weekly) // Or Monthly if you add it+                Triple(start.atStartOfDayIn(tz), end.atStartOfDayIn(tz), HealthAPI.PeriodType.Weekly)             }         } -        val rawSums = HealthAPI.getListOfSums(config.recordType, startTime, endTime, periodType)+        val rawValues: List<Double?> = if (config.isLineChart) {+            HealthAPI.getListOfAverages(config.recordType, startTime, endTime, periodType)+        } else {+            HealthAPI.getListOfSums(config.recordType, startTime, endTime, periodType)+        } -        // Transform the raw sums into Chart and History data-        val mappedChart = rawSums.mapIndexed { index, value ->+        val mappedChart = rawValues.mapIndexed { index, value ->             val label = when (selectedTab) {                 0 -> index.toString()                 1 -> startTime.plus(index.toLong(), DateTimeUnit.DAY, tz).toLocalDateTime(tz).dayOfWeek.name.take(3)                 else -> (index + 1).toString()             }-            label to value.toLong()+            label to value         } -        val history = rawSums.mapIndexed { index, value ->+        val history = rawValues.mapIndexed { index, value ->             val label = when (selectedTab) {                 0 -> "Hour $index"-                1 -> startTime.plus(index.toLong(), DateTimeUnit.DAY, tz).toLocalDateTime(tz).dayOfWeek.name.lowercase().capitalize()+                1 -> startTime.plus(index.toLong(), DateTimeUnit.DAY, tz).toLocalDateTime(tz).dayOfWeek.name.lowercase().replaceFirstChar { it.uppercase() }                 2 -> "Day ${index + 1}"                 else -> "Week ${index + 1}"             }-            HistoryItem(label, value.toLong(), config.unit, value >= config.dailyGoal)-        }.filter { it.value > 0 }.reversed()+            HistoryItem(+                label = label,+                value = value,+                unit = config.unit,+                isGoalMet = (value ?: 0.0) >= config.dailyGoal,+                useDecimals = config.useDecimals+            )+        }.filter { it.value != null }.reversed() // Remove "No data" cards by filtering nulls -        val totalValue = rawSums.sum().toLong()-        val daysInRange = rawSums.size.coerceAtLeast(1)+        val nonNullValues = rawValues.filterNotNull()+        val totalValue = nonNullValues.sum()+        val dailyAvg = if (config.isLineChart) {+            if (nonNullValues.isEmpty()) 0.0 else nonNullValues.average()+        } else {+            val divisor = rawValues.size.coerceAtLeast(1)+            totalValue / divisor+        }          dataState = MetricDashboardData(             totalValue = totalValue,-            dailyAverage = if (selectedTab == 0) totalValue else totalValue / daysInRange,+            dailyAverage = dailyAvg,             chartData = mappedChart,             historyItems = history,-            totalBarCount = rawSums.size+            totalBarCount = rawValues.size         )     } @@ -170,7 +191,6 @@ fun BarChartDetails(                 contentPadding = PaddingValues(top = 16.dp, bottom = 24.dp)             ) {                 item {-                    // Header Date Display                     val headerLabel = when (selectedTab) {                         0 -> "${anchorDate.month.name} ${anchorDate.dayOfMonth}, ${anchorDate.year}"                         1 -> "Week of ${anchorDate.minus(anchorDate.dayOfWeek.ordinal, DateTimeUnit.DAY)}"@@ -211,13 +231,19 @@ fun BarChartDetails(                     Spacer(Modifier.height(16.dp))                      Row(verticalAlignment = Alignment.Bottom) {+                        val avgString = if (config.useDecimals) {+                            String.format("%.1f", dataState.dailyAverage)+                        } else {+                            String.format("%,d", dataState.dailyAverage.toLong())+                        }+                         Text(-                            text = String.format("%,d", dataState.dailyAverage),+                            text = avgString,                             style = MaterialTheme.typography.displayMedium,                             fontWeight = FontWeight.Light                         )                         Text(-                            text = " ${config.unit}${if (selectedTab != 0) " per day (avg)" else ""}",+                            text = " ${config.unit}${if (selectedTab != 0 && !config.isLineChart) " per day (avg)" else ""}",                             style = MaterialTheme.typography.bodyLarge,                             modifier = Modifier.padding(bottom = 12.dp, start = 4.dp),                             color = LocalContentColor.current.copy(alpha = 0.6f)@@ -227,13 +253,22 @@ fun BarChartDetails(                  item {                     Spacer(Modifier.height(32.dp))-                    GenericBarChart(-                        data = dataState.chartData,-                        totalBarCount = dataState.totalBarCount,-                        goalValue = config.dailyGoal,-                        barColor = MaterialTheme.colorScheme.primary,-                        goalColor = MaterialTheme.colorScheme.secondary-                    )+                    if (config.isLineChart) {+                        GenericLineChart(+                            data = dataState.chartData,+                            goalValue = config.dailyGoal,+                            lineColor = MaterialTheme.colorScheme.primary,+                            goalColor = MaterialTheme.colorScheme.secondary+                        )+                    } else {+                        GenericBarChart(+                            data = dataState.chartData.map { it.first to (it.second?.toLong() ?: 0L) },+                            totalBarCount = dataState.totalBarCount,+                            goalValue = config.dailyGoal.toLong(),+                            barColor = MaterialTheme.colorScheme.primary,+                            goalColor = MaterialTheme.colorScheme.secondary+                        )+                    }                 }                  items(dataState.historyItems) { item ->@@ -245,6 +280,60 @@ fun BarChartDetails(     } } +@Composable+fun GenericLineChart(+    data: List<Pair<String, Double?>>,+    goalValue: Double,+    lineColor: Color,+    goalColor: Color+) {+    if (data.all { it.second == null }) return++    val maxChartValue = (goalValue * 1.5f).coerceAtLeast(100.0)+    val labelColor = LocalContentColor.current.copy(alpha = 0.6f)++    Box(modifier = Modifier.fillMaxWidth().height(220.dp)) {+        Canvas(modifier = Modifier.fillMaxSize()) {+            val width = size.width+            val height = size.height+            val spacing = width / (data.size - 1).coerceAtLeast(1)++            // Goal line+            val goalY = height - (goalValue.toFloat() / maxChartValue.toFloat() * height).coerceIn(0f, height)+            drawLine(color = goalColor, start = Offset(0f, goalY), end = Offset(width, goalY), strokeWidth = 1.dp.toPx())++            // Draw line segments+            var lastValidPoint: Offset? = null++            data.forEachIndexed { index, pair ->+                val value = pair.second+                val x = index * spacing++                if (value != null) {+                    val y = height - (value.toFloat() / maxChartValue.toFloat() * height).coerceIn(0f, height)+                    val currentPoint = Offset(x, y)++                    if (lastValidPoint != null) {+                        drawLine(+                            color = lineColor,+                            start = lastValidPoint!!,+                            end = currentPoint,+                            strokeWidth = 3.dp.toPx()+                        )+                    }++                    drawCircle(color = lineColor, radius = 3.dp.toPx(), center = currentPoint)+                    lastValidPoint = currentPoint+                }+            }+        }++        Text(text = String.format("%,d", maxChartValue.toLong()), color = labelColor, fontSize = 10.sp, modifier = Modifier.align(Alignment.TopEnd))+        Text(text = String.format("%,d", goalValue.toLong()), color = lineColor, fontSize = 10.sp, modifier = Modifier.align(Alignment.CenterEnd).padding(top = 40.dp))+        Text(text = "0", color = labelColor, fontSize = 10.sp, modifier = Modifier.align(Alignment.BottomEnd))+    }+}+ @Composable fun GenericBarChart(     data: List<Pair<String, Long>>,@@ -264,12 +353,7 @@ fun GenericBarChart(             val spacing = (width - (totalBarCount * barWidth)) / (totalBarCount + 1).coerceAtLeast(1)              val goalY = height - (goalValue.toFloat() / maxChartValue * height).coerceIn(0f, height)-            drawLine(-                color = goalColor,-                start = Offset(0f, goalY),-                end = Offset(width, goalY),-                strokeWidth = 1.dp.toPx()-            )+            drawLine(color = goalColor, start = Offset(0f, goalY), end = Offset(width, goalY), strokeWidth = 1.dp.toPx())              data.forEachIndexed { index, pair ->                 val barHeight = (pair.second.toFloat() / maxChartValue * height).coerceIn(4f, height)@@ -285,24 +369,9 @@ fun GenericBarChart(             }         } -        Text(-            text = String.format("%,d", maxChartValue.toLong()),-            color = labelColor,-            fontSize = 10.sp,-            modifier = Modifier.align(Alignment.TopEnd)-        )-        Text(-            text = String.format("%,d", goalValue),-            color = barColor,-            fontSize = 10.sp,-            modifier = Modifier.align(Alignment.CenterEnd).padding(top = 40.dp)-        )-        Text(-            text = "0",-            color = labelColor,-            fontSize = 10.sp,-            modifier = Modifier.align(Alignment.BottomEnd)-        )+        Text(text = String.format("%,d", maxChartValue.toLong()), color = labelColor, fontSize = 10.sp, modifier = Modifier.align(Alignment.TopEnd))+        Text(text = String.format("%,d", goalValue), color = barColor, fontSize = 10.sp, modifier = Modifier.align(Alignment.CenterEnd).padding(top = 40.dp))+        Text(text = "0", color = labelColor, fontSize = 10.sp, modifier = Modifier.align(Alignment.BottomEnd))     } } @@ -316,19 +385,28 @@ fun HistoryCard(item: HistoryItem) {         ) {             Text(item.label)             Row(verticalAlignment = Alignment.CenterVertically) {-                if (item.isGoalMet) {-                    Icon(-                        painter = painterResource(R.drawable.baseline_check_24),-                        contentDescription = null,-                        tint = MaterialTheme.colorScheme.primary,-                        modifier = Modifier.size(18.dp)+                if (item.value != null) {+                    if (item.isGoalMet) {+                        Icon(+                            painter = painterResource(R.drawable.baseline_check_24),+                            contentDescription = null,+                            tint = MaterialTheme.colorScheme.primary,+                            modifier = Modifier.size(18.dp)+                        )+                        Spacer(Modifier.width(8.dp))+                    }++                    val valueString = if (item.useDecimals) {+                        String.format("%.1f", item.value)+                    } else {+                        String.format("%,d", item.value.toLong())+                    }++                    Text(+                        text = "$valueString ${item.unit}",+                        fontWeight = FontWeight.Medium                     )-                    Spacer(Modifier.width(8.dp))                 }-                Text(-                    text = "${String.format("%,d", item.value)} ${item.unit}",-                    fontWeight = FontWeight.Medium-                )             }         }     }
health/src/main/java/com/vayunmathur/health/ui/MainPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/MainPage.kt b/health/src/main/java/com/vayunmathur/health/ui/MainPage.ktindex 9fa7a00da4..92a0ccee8f 100644--- a/health/src/main/java/com/vayunmathur/health/ui/MainPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/MainPage.kt@@ -88,7 +88,7 @@ fun MainPage(backStack: NavBackStack<Route>) {     var leanBodyMass by remember { mutableStateOf<Double?>(null) }     var bodyWaterMass by remember { mutableStateOf<Double?>(null) }     -    val dayStart = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date.atStartOfDayIn(TimeZone.currentSystemDefault())+    val dayStart = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date.atStartOfDayIn(TimeZone.currentSystemDefault()).minus(24.hours)     val dayEnd = dayStart.plus(24.hours)      val totalCaloriesBurnedToday by HealthAPI.sumInRange(RecordType.CaloriesTotal, dayStart, dayEnd).map { it.toLong() }.collectAsState(0L)@@ -106,8 +106,8 @@ fun MainPage(backStack: NavBackStack<Route>) { //    val carbsToday by HealthAPI.sumInRange(RecordType.Carbohydrates, dayStart, dayEnd).collectAsState(0.0) //    val fatToday by HealthAPI.sumInRange(RecordType.Fat, dayStart, dayEnd).collectAsState(0.0) -    val heartRateMaxToday by HealthAPI.maxInRange(RecordType.HeartRate, dayStart, dayEnd).map{it.toLong()}.collectAsState(0L)-    val heartRateMinToday by HealthAPI.minInRange(RecordType.HeartRate, dayStart, dayEnd).map{it.toLong()}.collectAsState(0L)+    val heartRateMaxToday by HealthAPI.maxInRange(RecordType.HeartRate, dayStart, dayEnd).map{it?.toLong() ?: 0L}.collectAsState(0L)+    val heartRateMinToday by HealthAPI.minInRange(RecordType.HeartRate, dayStart, dayEnd).map{it?.toLong() ?: 0L}.collectAsState(0L)  //    val sleepDurationToday by HealthAPI.sumInRange(RecordType.Sleep, dayStart, dayEnd).map { it.toLong() }.collectAsState(0L) @@ -191,7 +191,7 @@ fun MainPage(backStack: NavBackStack<Route>) {              // 1. Vitals & Clinical Metrics             Text("Vitals & Clinical", style = MaterialTheme.typography.labelLarge)-            VitalsDashboard(br, spo2, rhr, hrv, skinTemp, vo2Max, bloodGlucose, bloodPressure)+            VitalsDashboard(backStack, br, spo2, rhr, hrv, skinTemp, vo2Max, bloodGlucose, bloodPressure)              // 2. Nutrition Summary             Text("Nutrition (Today)", style = MaterialTheme.typography.labelLarge)@@ -238,15 +238,23 @@ fun NutritionMacro(label: String, value: Double?, unit: String) { }  @Composable-fun VitalsDashboard(br: Double?, spo2: Double?, rhr: Long?, hrv: Double?, temp: Double?, vo2: Double?, bg: Double?, bp: Pair<Double, Double>?) {+fun VitalsDashboard(backStack: NavBackStack<Route>, br: Double?, spo2: Double?, rhr: Long?, hrv: Double?, temp: Double?, vo2: Double?, bg: Double?, bp: Pair<Double, Double>?) {     val items = 8     Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {         MetricSegmentCard(0, items, "Blood Pressure", bp?.let { "${it.first.toInt()}/${it.second.toInt()}" }, "mmHg")         MetricSegmentCard(1, items, "Blood Glucose", bg, "mg/dL")-        MetricSegmentCard(2, items, "Oxygen Saturation", spo2, "%")-        MetricSegmentCard(3, items, "Breathing Rate", br, "brpm")-        MetricSegmentCard(4, items, "Resting Heart Rate", rhr?.toDouble(), "bpm")-        MetricSegmentCard(5, items, "HRV (RMSSD)", hrv, "ms")+        MetricSegmentCard(2, items, "Oxygen Saturation", spo2, "%", onClick = {+            backStack.add(Route.BarChartDetails(HealthMetricConfig.OXYGEN_SATURATION))+        })+        MetricSegmentCard(3, items, "Breathing Rate", br, "brpm", onClick = {+            backStack.add(Route.BarChartDetails(HealthMetricConfig.BREATHING_RATE))+        })+        MetricSegmentCard(4, items, "Resting Heart Rate", rhr?.toDouble(), "bpm", onClick = {+            backStack.add(Route.BarChartDetails(HealthMetricConfig.RESTING_HEART_RATE))+        })+        MetricSegmentCard(5, items, "HRV (RMSSD)", hrv, "ms", onClick = {+            backStack.add(Route.BarChartDetails(HealthMetricConfig.HRV))+        })         MetricSegmentCard(6, items, "VO2 Max", vo2, "mL/kg/min")         MetricSegmentCard(7, items, "Skin Temp Var", temp, "°C", showSign = true)     }@@ -266,10 +274,9 @@ fun BodyCompositionDashboard(h: Double?, w: Double?, bf: Double?, lbm: Double?, }  @Composable-fun MetricSegmentCard(index: Int, total: Int, label: String, value: Any?, unit: String, showSign: Boolean = false) {-    Card(-        shape = verticalSegmentedCardShape(index, total),-        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f))+fun MetricSegmentCard(index: Int, total: Int, label: String, value: Any?, unit: String, showSign: Boolean = false, onClick: (() -> Unit)? = null) {+    val modifier = if (onClick != null) Modifier.clickable { onClick() } else Modifier+    Card(modifier, verticalSegmentedCardShape(index, total), CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f))     ) {         Row(             modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 14.dp),