Modern Apps git

← Modern-Apps.git

health: fix sleep page layout

Commit
a86f12f810ded9f1c3f0e5e4f6d3b8205eeaab9d
Author
Vayun Mathur <[email protected]>
When
2026-05-08 20:47 UTC (7 months ago)
Parents
af28cc0

Diff

health/src/main/java/com/vayunmathur/health/MainActivity.kt
diff --git a/health/src/main/java/com/vayunmathur/health/MainActivity.kt b/health/src/main/java/com/vayunmathur/health/MainActivity.ktindex 232dfa13d9..f9a0228a9f 100644--- a/health/src/main/java/com/vayunmathur/health/MainActivity.kt+++ b/health/src/main/java/com/vayunmathur/health/MainActivity.kt@@ -46,6 +46,7 @@ import androidx.health.connect.client.records.OxygenSaturationRecord import androidx.health.connect.client.records.RespiratoryRateRecord import androidx.health.connect.client.records.RestingHeartRateRecord import androidx.health.connect.client.records.SkinTemperatureRecord+import androidx.health.connect.client.records.SleepSessionRecord import androidx.health.connect.client.records.StepsRecord import androidx.health.connect.client.records.TotalCaloriesBurnedRecord import androidx.health.connect.client.records.Vo2MaxRecord@@ -82,7 +83,7 @@ val CLASSES = setOf(     WeightRecord::class, HeightRecord::class, BodyFatRecord::class, LeanBodyMassRecord::class, BoneMassRecord::class, BodyWaterMassRecord::class,      // Lifestyle & Nutrition-    MindfulnessSessionRecord::class, HydrationRecord::class, NutritionRecord::class, // TODO: readd these: SleepSessionRecord::class+    MindfulnessSessionRecord::class, HydrationRecord::class, NutritionRecord::class, SleepSessionRecord::class )  val PERMISSIONS = CLASSES.map { HealthPermission.getReadPermission(it) }.toSet() + @@ -173,6 +174,9 @@ sealed interface Route: NavKey {      @Serializable     data class BarChartDetails(val healthMetric: HealthMetricConfig): Route++    @Serializable+    data object SleepDetails: Route }  @Composable@@ -212,5 +216,8 @@ fun Navigation() {         entry<Route.BarChartDetails> {             BarChartDetails(backStack, it.healthMetric)         }+        entry<Route.SleepDetails> {+            com.vayunmathur.health.ui.SleepDetailsPage(backStack)+        }     } }
health/src/main/java/com/vayunmathur/health/data/Record.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/Record.kt b/health/src/main/java/com/vayunmathur/health/data/Record.ktindex d50adc0208..2219ce9fc1 100644--- a/health/src/main/java/com/vayunmathur/health/data/Record.kt+++ b/health/src/main/java/com/vayunmathur/health/data/Record.kt@@ -70,6 +70,23 @@ data class NutritionData(     val calories: Double = 0.0 ) +@Serializable+data class SleepStage(+    val startTimeMillis: Long,+    val endTimeMillis: Long,+    val stage: Int+)++@Serializable+data class SleepData(+    val awakeDurationMillis: Long = 0,+    val remDurationMillis: Long = 0,+    val lightDurationMillis: Long = 0,+    val deepDurationMillis: Long = 0,+    val unknownDurationMillis: Long = 0,+    val stagesJson: String? = null+)+ @Entity(indices = [Index(value = ["type", "startTime", "endTime"])]) data class Record(     val id: String,@@ -80,6 +97,7 @@ data class Record(     val value: Double,     val secondaryValue: Double = 0.0,     @Embedded(prefix = "nutrition_") val nutritionData: NutritionData? = null,+    @Embedded(prefix = "sleep_") val sleepData: SleepData? = null,     val metadata: String? = null,     @PrimaryKey val primaryKey: String = "$id-$index", )@@ -390,7 +408,7 @@ interface HealthDao {  @Database(     entities = [Record::class, Ingredient::class, Recipe::class, ServingUnit::class, RecipeIngredient::class],-    version = 3,+    version = 4,     exportSchema = false ) @TypeConverters(Converters::class)
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 c1a4c6c101..200e28915d 100644--- a/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt@@ -120,7 +120,8 @@ enum class HealthMetricConfig(     BODY_FAT(R.string.metric_body_fat, RecordType.BodyFat, "%", 20.0, isLineChart = true, useDecimals = true),     LEAN_BODY_MASS(R.string.metric_lean_body_mass, RecordType.LeanBodyMass, "kg", 60.0, isLineChart = true, useDecimals = true),     BONE_MASS(R.string.metric_bone_mass, RecordType.BoneMass, "kg", 3.0, isLineChart = true, useDecimals = true),-    BODY_WATER_MASS(R.string.metric_body_water_mass, RecordType.BodyWaterMass, "kg", 45.0, isLineChart = true, useDecimals = true)+    BODY_WATER_MASS(R.string.metric_body_water_mass, RecordType.BodyWaterMass, "kg", 45.0, isLineChart = true, useDecimals = true),+    SLEEP(R.string.metric_sleep, RecordType.Sleep, "hr", 8.0, isLineChart = false, useDecimals = true) }  data class MetricDashboardData(
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 45079a3b7c..525b85ea82 100644--- a/health/src/main/java/com/vayunmathur/health/ui/MainPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/MainPage.kt@@ -83,6 +83,7 @@ fun MainPage(backStack: NavBackStack<Route>) {     var vo2Max by remember { mutableStateOf<Double?>(null) }     var bloodGlucose by remember { mutableStateOf<Double?>(null) }     var bloodPressure by remember { mutableStateOf<Pair<Double, Double>?>(null) }+    var sleepMinutes by remember { mutableStateOf<Long?>(null) }      // Body Measurement States     var height by remember { mutableStateOf<Double?>(null) }@@ -128,6 +129,11 @@ fun MainPage(backStack: NavBackStack<Route>) {                         it.value to it.secondaryValue                     }                 }+                val sleepD = async {+                    HealthAPI.lastRecord(RecordType.Sleep)?.let {+                        (it.value * 60).toLong()+                    }+                }                 val heightD = async { HealthAPI.lastRecord(RecordType.Height)?.value }                 val weightD = async { HealthAPI.lastRecord(RecordType.Weight)?.value }                 val bodyFatD = async { HealthAPI.lastRecord(RecordType.BodyFat)?.value }@@ -143,6 +149,7 @@ fun MainPage(backStack: NavBackStack<Route>) {                 vo2Max = vo2MaxD.await()                 bloodGlucose = bloodGlucoseD.await()                 bloodPressure = bloodPressureD.await()+                sleepMinutes = sleepD.await()                 height = heightD.await()                 weight = weightD.await()                 bodyFat = bodyFatD.await()@@ -212,8 +219,9 @@ fun MainPage(backStack: NavBackStack<Route>) {              item { Distance(backStack,distanceToday) }             item { HeartRate(backStack, heartRateMaxToday, heartRateMinToday) }-            // TODO: add this back-            //Sleep(aggregates?.get(SleepSessionRecord.SLEEP_DURATION_TOTAL)?.toKotlinDuration()?.inWholeMinutes ?: 0)+            item { +                SleepCard(backStack, sleepMinutes ?: 0L)+            }               // 1. Vitals & Clinical Metrics@@ -441,9 +449,11 @@ fun HeartRate(backStack: NavBackStack<Route>, max: Long, min: Long) { }  @Composable-fun Sleep(min: Long) {+fun SleepCard(backStack: NavBackStack<Route>, min: Long) {     val context = LocalContext.current-    GenericCard(stringResource(R.string.label_sleep), null, stringResource(R.string.unit_hr), hoursMinutesString(context, min), stringResource(R.string.label_last_night)) {+    GenericCard(stringResource(R.string.label_sleep), null, "", hoursMinutesString(context, min), stringResource(R.string.label_last_night), onClick = {+        backStack.add(Route.SleepDetails)+    }) {         ProgressBarGraphic(R.drawable.baseline_bedtime_24, min.toFloat(), 480f, Color(0xFF9C27B0))     } }
health/src/main/java/com/vayunmathur/health/ui/SleepDetailsPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/SleepDetailsPage.kt b/health/src/main/java/com/vayunmathur/health/ui/SleepDetailsPage.ktnew file mode 100644index 0000000000..df9bfc6d26--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/ui/SleepDetailsPage.kt@@ -0,0 +1,368 @@+package com.vayunmathur.health.ui++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.layout.*+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.pager.HorizontalPager+import androidx.compose.foundation.pager.rememberPagerState+import androidx.compose.material3.*+import androidx.compose.runtime.*+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+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.platform.LocalContext+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.health.connect.client.records.SleepSessionRecord+import com.vayunmathur.health.R+import com.vayunmathur.health.Route+import com.vayunmathur.health.data.Record+import com.vayunmathur.health.data.RecordType+import com.vayunmathur.health.data.SleepData+import com.vayunmathur.health.data.SleepStage+import com.vayunmathur.health.util.HealthAPI+import com.vayunmathur.health.util.displayString+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.util.NavBackStack+import kotlin.time.Clock+import kotlin.time.Duration.Companion.hours+import kotlinx.coroutines.launch+import kotlinx.datetime.*+import kotlinx.serialization.json.Json++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun SleepDetailsPage(backStack: NavBackStack<Route>) {+    val initialPage = 999+    val pagerState = rememberPagerState(initialPage = initialPage) { 1000 }+    val scope = rememberCoroutineScope()+    val tz = TimeZone.currentSystemDefault()+    val today = Clock.System.todayIn(tz)++    Scaffold(+            topBar = {+                TopAppBar(+                        title = { Text(stringResource(R.string.label_sleep)) },+                        navigationIcon = { IconNavigation(backStack) }+                )+            }+    ) { padding ->+        Column(modifier = Modifier.padding(padding).fillMaxSize()) {+            // Navigation Row (Same as BarChartDetails)+            val selectedDay =+                    remember(pagerState.currentPage) {+                        today.minus(initialPage - pagerState.currentPage, DateTimeUnit.DAY)+                    }+            val headerLabel =+                    if (selectedDay == today) stringResource(R.string.label_today)+                    else selectedDay.displayString()++            Row(+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),+                    verticalAlignment = Alignment.CenterVertically,+                    horizontalArrangement = Arrangement.Center+            ) {+                IconButton(+                        onClick = {+                            scope.launch {+                                pagerState.animateScrollToPage(pagerState.currentPage - 1)+                            }+                        }+                ) {+                    Icon(+                            painterResource(R.drawable.baseline_arrow_back_24),+                            stringResource(R.string.nav_prev)+                    )+                }++                Text(+                        text = headerLabel,+                        style = MaterialTheme.typography.titleMedium,+                        modifier = Modifier.widthIn(min = 140.dp),+                        textAlign = TextAlign.Center+                )++                IconButton(+                        onClick = {+                            scope.launch {+                                pagerState.animateScrollToPage(pagerState.currentPage + 1)+                            }+                        },+                        enabled =+                                pagerState.currentPage < pagerState.pageCount - 1 &&+                                        selectedDay < today+                ) {+                    Icon(+                            painterResource(R.drawable.outline_arrow_forward_24),+                            stringResource(R.string.nav_next)+                    )+                }+            }++            HorizontalPager(state = pagerState, modifier = Modifier.weight(1f).fillMaxSize()) { page+                ->+                val day = today.minus(initialPage - page, DateTimeUnit.DAY)+                val dayStart = day.atStartOfDayIn(tz)+                val dayEnd = dayStart.plus(24.hours)++                // Fetch records that ended during this day (most likely the sleep that ended this+                // morning)+                val records by+                        HealthAPI.getAllRecordsInRange(RecordType.Sleep, dayStart, dayEnd)+                                .collectAsState(emptyList())+                val record = records.maxByOrNull { it.endTime }++                LazyColumn(+                        modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp),+                        verticalArrangement = Arrangement.spacedBy(24.dp),+                        contentPadding = PaddingValues(bottom = 24.dp)+                ) {+                    record?.let { r ->+                        val sleepData = r.sleepData+                        if (sleepData != null) {+                            item { SleepSummaryHeader(r) }+                            item { SleepStageGraph(r) }+                            item { SleepStageBreakdown(sleepData) }+                        }+                    }+                            ?: item {+                                Box(+                                        Modifier.fillParentMaxSize(),+                                        contentAlignment = Alignment.Center+                                ) {+                                    Text(+                                            stringResource(R.string.no_data_available),+                                            color = MaterialTheme.colorScheme.outline+                                    )+                                }+                            }+                }+            }+        }+    }+}++@Composable+fun SleepSummaryHeader(record: Record) {+    val context = LocalContext.current+    val totalMinutes = (record.value * 60).toLong()+    val startTime =+            kotlinx.datetime.Instant.fromEpochMilliseconds(record.startTime.toEpochMilli())+                    .toLocalDateTime(TimeZone.currentSystemDefault())+    val endTime =+            kotlinx.datetime.Instant.fromEpochMilliseconds(record.endTime.toEpochMilli())+                    .toLocalDateTime(TimeZone.currentSystemDefault())++    Column {+        Text(+                text = hoursMinutesString(context, totalMinutes),+                style = MaterialTheme.typography.displayMedium,+                fontWeight = FontWeight.Light+        )+        Text(+                text =+                        "${startTime.hour}:${startTime.minute.toString().padStart(2, '0')} - ${endTime.hour}:${endTime.minute.toString().padStart(2, '0')}",+                style = MaterialTheme.typography.bodyMedium,+                color = MaterialTheme.colorScheme.outline+        )+    }+}++@Composable+fun SleepStageGraph(record: Record) {+    val stages =+            remember(record) {+                record.sleepData?.stagesJson?.let { Json.decodeFromString<List<SleepStage>>(it) }+                        ?: emptyList()+            }++    if (stages.isEmpty()) return++    val startTime = record.startTime.toEpochMilli()+    val endTime = record.endTime.toEpochMilli()+    val duration = (endTime - startTime).coerceAtLeast(1)++    val awakeColor = Color(0xFFFF9500)+    val remColor = Color(0xFF5AC8FA)+    val coreColor = Color(0xFF007AFF)+    val deepColor = Color(0xFF5856D6)++    Column {+        Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {+            Column(+                    horizontalAlignment = Alignment.Start,+                    verticalArrangement = Arrangement.SpaceBetween,+                    modifier = Modifier.height(160.dp)+            ) {+                Text(+                        stringResource(R.string.label_awake),+                        style = MaterialTheme.typography.labelSmall,+                        color = MaterialTheme.colorScheme.outline+                )+                Text(+                        stringResource(R.string.label_rem),+                        style = MaterialTheme.typography.labelSmall,+                        color = MaterialTheme.colorScheme.outline+                )+                Text(+                        stringResource(R.string.label_core),+                        style = MaterialTheme.typography.labelSmall,+                        color = MaterialTheme.colorScheme.outline+                )+                Text(+                        stringResource(R.string.label_deep),+                        style = MaterialTheme.typography.labelSmall,+                        color = MaterialTheme.colorScheme.outline+                )+            }++            Canvas(modifier = Modifier.weight(1f).height(160.dp).padding(start = 8.dp)) {+                val canvasWidth = size.width+                val canvasHeight = size.height+                val levelHeight = canvasHeight / 4++                // Draw background lines+                for (i in 0..4) {+                    val y = i * levelHeight+                    drawLine(+                            Color.LightGray.copy(alpha = 0.3f),+                            Offset(0f, y),+                            Offset(canvasWidth, y),+                            strokeWidth = 1.dp.toPx()+                    )+                }++                stages.forEach { stage ->+                    val startX =+                            ((stage.startTimeMillis - startTime).toFloat() / duration) * canvasWidth+                    val endX =+                            ((stage.endTimeMillis - startTime).toFloat() / duration) * canvasWidth++                    val yPos =+                            when (stage.stage) {+                                SleepSessionRecord.STAGE_TYPE_AWAKE,+                                SleepSessionRecord.STAGE_TYPE_OUT_OF_BED -> 0f+                                SleepSessionRecord.STAGE_TYPE_REM -> levelHeight+                                SleepSessionRecord.STAGE_TYPE_LIGHT -> levelHeight * 2+                                SleepSessionRecord.STAGE_TYPE_DEEP -> levelHeight * 3+                                else -> levelHeight * 2+                            }++                    val color =+                            when (stage.stage) {+                                SleepSessionRecord.STAGE_TYPE_AWAKE,+                                SleepSessionRecord.STAGE_TYPE_OUT_OF_BED -> awakeColor+                                SleepSessionRecord.STAGE_TYPE_REM -> remColor+                                SleepSessionRecord.STAGE_TYPE_LIGHT -> coreColor+                                SleepSessionRecord.STAGE_TYPE_DEEP -> deepColor+                                else -> coreColor+                            }++                    drawRoundRect(+                            color = color,+                            topLeft = Offset(startX, yPos + 4.dp.toPx()),+                            size =+                                    Size(+                                            (endX - startX).coerceAtLeast(2.dp.toPx()),+                                            levelHeight - 8.dp.toPx()+                                    ),+                            cornerRadius = CornerRadius(4.dp.toPx(), 4.dp.toPx())+                    )+                }+            }+        }++        Spacer(Modifier.height(8.dp))++        // Time labels+        Row(+                Modifier.fillMaxWidth().padding(start = 48.dp),+                horizontalArrangement = Arrangement.SpaceBetween+        ) {+            val startT =+                    kotlinx.datetime.Instant.fromEpochMilliseconds(record.startTime.toEpochMilli())+                            .toLocalDateTime(TimeZone.currentSystemDefault())+            val endT =+                    kotlinx.datetime.Instant.fromEpochMilliseconds(record.endTime.toEpochMilli())+                            .toLocalDateTime(TimeZone.currentSystemDefault())++            fun formatHour(hour: Int): String {+                val h = if (hour % 12 == 0) 12 else hour % 12+                val ampm = if (hour < 12) "AM" else "PM"+                return "$h $ampm"+            }++            Text(+                    formatHour(startT.hour),+                    style = MaterialTheme.typography.labelSmall,+                    color = MaterialTheme.colorScheme.outline+            )+            Text(+                    formatHour(endT.hour),+                    style = MaterialTheme.typography.labelSmall,+                    color = MaterialTheme.colorScheme.outline+            )+        }+    }+}++@Composable+fun SleepStageBreakdown(data: SleepData) {+    val context = LocalContext.current+    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {+        Text("Stages", style = MaterialTheme.typography.labelLarge)+        Card(+                modifier = Modifier.fillMaxWidth(),+                colors =+                        CardDefaults.cardColors(+                                containerColor =+                                        MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)+                        )+        ) {+            Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {+                StageRow(+                        stringResource(R.string.label_awake),+                        hoursMinutesString(context, data.awakeDurationMillis / 60000),+                        Color(0xFFFF9500)+                )+                StageRow(+                        stringResource(R.string.label_rem),+                        hoursMinutesString(context, data.remDurationMillis / 60000),+                        Color(0xFF5AC8FA)+                )+                StageRow(+                        stringResource(R.string.label_core),+                        hoursMinutesString(context, data.lightDurationMillis / 60000),+                        Color(0xFF007AFF)+                )+                StageRow(+                        stringResource(R.string.label_deep),+                        hoursMinutesString(context, data.deepDurationMillis / 60000),+                        Color(0xFF5856D6)+                )+            }+        }+    }+}++@Composable+fun StageRow(label: String, duration: String, color: Color) {+    Row(+            Modifier.fillMaxWidth(),+            verticalAlignment = Alignment.CenterVertically,+            horizontalArrangement = Arrangement.SpaceBetween+    ) {+        Row(verticalAlignment = Alignment.CenterVertically) {+            Surface(Modifier.size(12.dp), shape = MaterialTheme.shapes.extraSmall, color = color) {}+            Spacer(Modifier.width(12.dp))+            Text(label, style = MaterialTheme.typography.bodyLarge)+        }+        Text(duration, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Bold)+    }+}
health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.kt
diff --git a/health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.kt b/health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.ktindex a01d13f12a..b745ebf07a 100644--- a/health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.kt+++ b/health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.kt@@ -24,6 +24,7 @@ import androidx.health.connect.client.records.OxygenSaturationRecord import androidx.health.connect.client.records.RespiratoryRateRecord import androidx.health.connect.client.records.RestingHeartRateRecord import androidx.health.connect.client.records.SkinTemperatureRecord+import androidx.health.connect.client.records.SleepSessionRecord import androidx.health.connect.client.records.StepsRecord import androidx.health.connect.client.records.TotalCaloriesBurnedRecord import androidx.health.connect.client.records.Vo2MaxRecord@@ -50,6 +51,9 @@ import com.vayunmathur.library.util.buildDatabase import java.time.Duration import java.time.Instant import java.util.concurrent.TimeUnit+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json+import com.vayunmathur.health.data.SleepStage  /**  * Worker that ensures local Room DB is in sync with Health Connect.@@ -164,7 +168,30 @@ fun androidx.health.connect.client.records.Record.toRecord(): List<Record> =         is BodyWaterMassRecord -> listOf(Record(this.metadata.id, 0, RecordType.BodyWaterMass, this.time, this.time, this.mass.inKilograms, metadata = "Body Water Mass"))          // --- Lifestyle ----//                    is SleepSessionRecord -> listOf(Record(this.metadata.id, 0, "Sleep", this.startTime, this.endTime, this))+        is SleepSessionRecord -> {+            val stages = this.stages.map { stage ->+                SleepStage(stage.startTime.toEpochMilli(), stage.endTime.toEpochMilli(), stage.stage)+            }+            val awake = this.stages.filter { it.stage == SleepSessionRecord.STAGE_TYPE_AWAKE || it.stage == SleepSessionRecord.STAGE_TYPE_OUT_OF_BED }.sumOf { Duration.between(it.startTime, it.endTime).toMillis() }+            val rem = this.stages.filter { it.stage == SleepSessionRecord.STAGE_TYPE_REM }.sumOf { Duration.between(it.startTime, it.endTime).toMillis() }+            val light = this.stages.filter { it.stage == SleepSessionRecord.STAGE_TYPE_LIGHT }.sumOf { Duration.between(it.startTime, it.endTime).toMillis() }+            val deep = this.stages.filter { it.stage == SleepSessionRecord.STAGE_TYPE_DEEP }.sumOf { Duration.between(it.startTime, it.endTime).toMillis() }+            val unknown = this.stages.filter { it.stage == SleepSessionRecord.STAGE_TYPE_UNKNOWN }.sumOf { Duration.between(it.startTime, it.endTime).toMillis() }++            listOf(Record(+                this.metadata.id, 0, RecordType.Sleep, this.startTime, this.endTime,+                Duration.between(this.startTime, this.endTime).toMillis().toDouble() / 1000.0 / 60.0 / 60.0, // Hours+                sleepData = com.vayunmathur.health.data.SleepData(+                    awakeDurationMillis = awake,+                    remDurationMillis = rem,+                    lightDurationMillis = light,+                    deepDurationMillis = deep,+                    unknownDurationMillis = unknown,+                    stagesJson = Json.encodeToString(stages)+                ),+                metadata = "Sleep Session"+            ))+        }         is MindfulnessSessionRecord -> listOf(Record(this.metadata.id, 0, RecordType.Mindfulness, this.startTime, this.endTime, Duration.between(this.startTime, this.endTime).toMillis().toDouble() / 1000.0 / 60.0, metadata = "Mindfulness"))         is HydrationRecord -> listOf(Record(this.metadata.id, 0, RecordType.Hydration, this.startTime, this.endTime, this.volume.inMilliliters, metadata = "Hydration"))         is NutritionRecord -> {
health/src/main/res/values/strings.xml
diff --git a/health/src/main/res/values/strings.xml b/health/src/main/res/values/strings.xmlindex c630f9ba7d..05373b1603 100644--- a/health/src/main/res/values/strings.xml+++ b/health/src/main/res/values/strings.xml@@ -56,6 +56,13 @@     <string name="metric_lean_body_mass">Lean Body Mass</string>     <string name="metric_bone_mass">Bone Mass</string>     <string name="metric_body_water_mass">Body Water Mass</string>+    <string name="metric_sleep">Sleep</string>++    <!-- Sleep Stages -->+    <string name="label_awake">Awake</string>+    <string name="label_rem">REM</string>+    <string name="label_core">Core</string>+    <string name="label_deep">Deep</string>      <!-- MainPage – section headers -->     <string name="section_medical_records">Medical Records</string>