Modern Apps git

← Modern-Apps.git

health: fix line charts for rest of values

Commit
6380fa0819530668f0378613278a5e0f1e0a0c46
Author
Vayun Mathur <[email protected]>
When
2026-02-11 20:41 UTC (9 months ago)
Parents
7019c85

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 5fa9d5cf5d..9d679874ad 100644--- a/health/src/main/java/com/vayunmathur/health/HealthAPI.kt+++ b/health/src/main/java/com/vayunmathur/health/HealthAPI.kt@@ -69,9 +69,9 @@ object HealthAPI {         startTime: Instant,         endTime: Instant,         period: PeriodType-    ): List<Double?> {+    ): List<Pair<Double?, Double?>> {         val tz = TimeZone.currentSystemDefault()-        val avgs = mutableListOf<Double?>()+        val avgs = mutableListOf<Pair<Double?, Double?>>()          var currentStart = startTime @@ -97,8 +97,9 @@ object HealthAPI {             val currentEnd = if (nextStart > endTime) endTime else nextStart              // Fetch sum from DAO-            val avg = db.healthDao().avgInRangeGet(recordType, currentStart, currentEnd)-            avgs.add(avg)+            val avg1 = db.healthDao().avgInRangeGet1(recordType, currentStart, currentEnd)+            val avg2 = db.healthDao().avgInRangeGet2(recordType, currentStart, currentEnd)+            avgs.add(Pair(avg1, avg2))              currentStart = nextStart         }@@ -111,9 +112,9 @@ object HealthAPI {         startTime: Instant,         endTime: Instant,         period: PeriodType-    ): List<Double> {+    ): List<Pair<Double, Double>> {         val tz = TimeZone.currentSystemDefault()-        val sums = mutableListOf<Double>()+        val sums = mutableListOf<Pair<Double, Double>>()          var currentStart = startTime @@ -139,8 +140,9 @@ object HealthAPI {             val currentEnd = if (nextStart > endTime) endTime else nextStart              // Fetch sum from DAO-            val sum = db.healthDao().sumInRangeGet(recordType, currentStart, currentEnd)-            sums.add(sum)+            val sum1 = db.healthDao().sumInRangeGet1(recordType, currentStart, currentEnd)+            val sum2 = db.healthDao().sumInRangeGet2(recordType, currentStart, currentEnd)+            sums.add(Pair(sum1, sum2))              currentStart = nextStart         }
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 d2a8dfef74..a5015bb980 100644--- a/health/src/main/java/com/vayunmathur/health/database/StepsRecordEntity.kt+++ b/health/src/main/java/com/vayunmathur/health/database/StepsRecordEntity.kt@@ -46,9 +46,13 @@ interface HealthDao {     @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 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+    suspend fun sumInRangeGet1(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Double+    @Query("SELECT COALESCE(SUM(secondaryValue), 0.0) FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")+    suspend fun sumInRangeGet2(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?+    suspend fun avgInRangeGet1(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Double?+    @Query("SELECT AVG(secondaryValue) FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")+    suspend fun avgInRangeGet2(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?>     @Query("SELECT MAX(value) FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")
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 29524b5289..177935a0ac 100644--- a/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt@@ -38,37 +38,53 @@ import kotlinx.datetime.todayIn import kotlin.time.Clock  /**- * Configuration for different health metrics.- * Biological markers (HRV, Breathing, etc) use Line Charts and Average-based aggregation.+ * Configuration for health metrics.  */ enum class HealthMetricConfig(     val title: String,     val recordType: RecordType,     val unit: String,     val dailyGoal: Double,+    val secondaryGoal: Double? = null,     val isLineChart: Boolean = false,-    val useDecimals: Boolean = false+    val useDecimals: Boolean = false,+    val isDualSeries: Boolean = false ) {     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)+    DISTANCE("Distance", RecordType.Distance, "km", 5.0, isLineChart = false, useDecimals = true),+    ELEVATION("Elevation Gained", RecordType.Elevation, "m", 50.0, isLineChart = false, useDecimals = true),+    FLOORS("Floors Climbed", RecordType.Floors, "floors", 10.0, isLineChart = false, useDecimals = true),+    HYDRATION("Hydration", RecordType.Hydration, "L", 2.5, isLineChart = false, useDecimals = true),++    // Biological & Medical (Line Charts)+    BLOOD_PRESSURE("Blood Pressure", RecordType.BloodPressure, "mmHg", 120.0, secondaryGoal = 80.0, isLineChart = true, isDualSeries = true),+    GLUCOSE("Blood Glucose", RecordType.BloodGlucose, "mg/dL", 100.0, isLineChart = true, useDecimals = true),+    VO2_MAX("VO2 Max", RecordType.Vo2Max, "ml/kg/min", 45.0, isLineChart = true, useDecimals = true),+    SKIN_TEMP("Skin Temp Variation", RecordType.SkinTemperature, "°C", 0.0, isLineChart = true, useDecimals = true),     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)+    HRV("Heart Rate Variability", RecordType.HeartRateVariabilityRmssd, "ms", 50.0, isLineChart = true, useDecimals = true),++    // Physical Measurements+    HEIGHT("Height", RecordType.Height, "cm", 175.0, isLineChart = true, useDecimals = true),+    WEIGHT("Weight", RecordType.Weight, "kg", 75.0, isLineChart = true, useDecimals = true),+    BODY_FAT("Body Fat", RecordType.BodyFat, "%", 20.0, isLineChart = true, useDecimals = true),+    LEAN_BODY_MASS("Lean Body Mass", RecordType.LeanBodyMass, "kg", 60.0, isLineChart = true, useDecimals = true),+    BONE_MASS("Bone Mass", RecordType.BoneMass, "kg", 3.0, isLineChart = true, useDecimals = true),+    BODY_WATER_MASS("Body Water Mass", RecordType.BodyWaterMass, "kg", 45.0, isLineChart = true, useDecimals = true) }  data class MetricDashboardData(     val totalValue: Double = 0.0,     val dailyAverage: Double = 0.0,+    val secondaryAverage: Double? = null,     val chartData: List<Pair<String, Double?>> = emptyList(),+    val secondaryChartData: List<Pair<String, Double?>>? = null,     val historyItems: List<HistoryItem> = emptyList(),     val totalBarCount: Int = 0 )@@ -76,6 +92,7 @@ data class MetricDashboardData( data class HistoryItem(     val label: String,     val value: Double?,+    val secondaryValue: Double? = null,     val unit: String,     val isGoalMet: Boolean,     val useDecimals: Boolean@@ -97,11 +114,7 @@ fun BarChartDetails(      LaunchedEffect(selectedTab, anchorDate, config) {         val (startTime, endTime, periodType) = when (selectedTab) {-            0 -> Triple(-                anchorDate.atStartOfDayIn(tz),-                anchorDate.atTime(23, 59, 59).toInstant(tz),-                HealthAPI.PeriodType.Hourly-            )+            0 -> Triple(anchorDate.atStartOfDayIn(tz), anchorDate.atTime(23, 59, 59).toInstant(tz), HealthAPI.PeriodType.Hourly)             1 -> {                 val start = anchorDate.minus(anchorDate.dayOfWeek.ordinal, DateTimeUnit.DAY)                 Triple(start.atStartOfDayIn(tz), start.plus(7, DateTimeUnit.DAY).atStartOfDayIn(tz), HealthAPI.PeriodType.Daily)@@ -118,22 +131,19 @@ fun BarChartDetails(             }         } -        val rawValues: List<Double?> = if (config.isLineChart) {+        // Both functions now return List<Pair<Double?, Double?>>+        val rawPairs = if (config.isLineChart) {             HealthAPI.getListOfAverages(config.recordType, startTime, endTime, periodType)         } else {             HealthAPI.getListOfSums(config.recordType, startTime, endTime, periodType)         } -        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-        }+        val mappedChart = rawPairs.mapIndexed { i, p -> i.toString() to p.first }+        val mappedSecondaryChart = if (config.isDualSeries) {+            rawPairs.mapIndexed { i, p -> i.toString() to p.second }+        } else null -        val history = rawValues.mapIndexed { index, value ->+        val history = rawPairs.mapIndexed { index, pair ->             val label = when (selectedTab) {                 0 -> "Hour $index"                 1 -> startTime.plus(index.toLong(), DateTimeUnit.DAY, tz).toLocalDateTime(tz).dayOfWeek.name.lowercase().replaceFirstChar { it.uppercase() }@@ -142,28 +152,25 @@ fun BarChartDetails(             }             HistoryItem(                 label = label,-                value = value,+                value = pair.first,+                secondaryValue = if (config.isDualSeries) pair.second else null,                 unit = config.unit,-                isGoalMet = (value ?: 0.0) >= config.dailyGoal,+                isGoalMet = (pair.first ?: 0.0) >= config.dailyGoal,                 useDecimals = config.useDecimals             )-        }.filter { it.value != null }.reversed() // Remove "No data" cards by filtering nulls+        }.filter { it.value != null }.reversed() -        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-        }+        val nonNullPrimary = rawPairs.mapNotNull { it.first }+        val nonNullSecondary = if (config.isDualSeries) rawPairs.mapNotNull { it.second } else emptyList()          dataState = MetricDashboardData(-            totalValue = totalValue,-            dailyAverage = dailyAvg,+            totalValue = nonNullPrimary.sum(),+            dailyAverage = if (nonNullPrimary.isEmpty()) 0.0 else nonNullPrimary.average(),+            secondaryAverage = if (nonNullSecondary.isEmpty()) null else nonNullSecondary.average(),             chartData = mappedChart,+            secondaryChartData = mappedSecondaryChart,             historyItems = history,-            totalBarCount = rawValues.size+            totalBarCount = rawPairs.size         )     } @@ -231,10 +238,11 @@ fun BarChartDetails(                     Spacer(Modifier.height(16.dp))                      Row(verticalAlignment = Alignment.Bottom) {-                        val avgString = if (config.useDecimals) {-                            String.format("%.1f", dataState.dailyAverage)+                        val formatVal = { v: Double -> if (config.useDecimals) String.format("%.1f", v) else String.format("%,d", v.toLong()) }+                        val avgString = if (dataState.secondaryAverage != null && config.isDualSeries) {+                            "${formatVal(dataState.dailyAverage)}/${formatVal(dataState.secondaryAverage!!)}"                         } else {-                            String.format("%,d", dataState.dailyAverage.toLong())+                            formatVal(dataState.dailyAverage)                         }                          Text(@@ -256,8 +264,11 @@ fun BarChartDetails(                     if (config.isLineChart) {                         GenericLineChart(                             data = dataState.chartData,+                            secondaryData = dataState.secondaryChartData,                             goalValue = config.dailyGoal,+                            secondaryGoal = config.secondaryGoal,                             lineColor = MaterialTheme.colorScheme.primary,+                            secondaryLineColor = MaterialTheme.colorScheme.tertiary,                             goalColor = MaterialTheme.colorScheme.secondary                         )                     } else {@@ -283,13 +294,17 @@ fun BarChartDetails( @Composable fun GenericLineChart(     data: List<Pair<String, Double?>>,+    secondaryData: List<Pair<String, Double?>>? = null,     goalValue: Double,+    secondaryGoal: Double? = null,     lineColor: Color,+    secondaryLineColor: Color,     goalColor: Color ) {     if (data.all { it.second == null }) return -    val maxChartValue = (goalValue * 1.5f).coerceAtLeast(100.0)+    val allValues = (data.mapNotNull { it.second } + (secondaryData?.mapNotNull { it.second } ?: emptyList()))+    val maxChartValue = (allValues.maxOrNull() ?: goalValue).coerceAtLeast(goalValue * 1.2).coerceAtLeast(10.0)     val labelColor = LocalContentColor.current.copy(alpha = 0.6f)      Box(modifier = Modifier.fillMaxWidth().height(220.dp)) {@@ -298,34 +313,34 @@ fun GenericLineChart(             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()-                        )+            val drawSeries = { series: List<Pair<String, Double?>>, color: Color ->+                var lastValidPoint: Offset? = null+                series.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 = color, start = lastValidPoint!!, end = currentPoint, strokeWidth = 3.dp.toPx())+                        }+                        drawCircle(color = color, radius = 3.dp.toPx(), center = currentPoint)+                        lastValidPoint = currentPoint                     }--                    drawCircle(color = lineColor, radius = 3.dp.toPx(), center = currentPoint)-                    lastValidPoint = currentPoint                 }             }++            // Goal lines+            val drawGoal = { goal: Double, color: Color ->+                val gy = height - (goal.toFloat() / maxChartValue.toFloat() * height).coerceIn(0f, height)+                drawLine(color = color, start = Offset(0f, gy), end = Offset(width, gy), strokeWidth = 1.dp.toPx())+            }++            drawGoal(goalValue, goalColor)+            secondaryGoal?.let { drawGoal(it, goalColor.copy(alpha = 0.5f)) }++            drawSeries(data, lineColor)+            secondaryData?.let { drawSeries(it, secondaryLineColor) }         }          Text(text = String.format("%,d", maxChartValue.toLong()), color = labelColor, fontSize = 10.sp, modifier = Modifier.align(Alignment.TopEnd))@@ -342,7 +357,8 @@ fun GenericBarChart(     barColor: Color,     goalColor: Color ) {-    val maxChartValue = (goalValue * 2f).coerceAtLeast(100f)+    val maxValueFound = data.maxOfOrNull { it.second } ?: 0L+    val maxChartValue = (maxValueFound.toFloat() * 1.2f).coerceAtLeast(goalValue * 1.2f).coerceAtLeast(10f)     val labelColor = LocalContentColor.current.copy(alpha = 0.6f)      Box(modifier = Modifier.fillMaxWidth().height(220.dp)) {@@ -396,11 +412,8 @@ fun HistoryCard(item: HistoryItem) {                         Spacer(Modifier.width(8.dp))                     } -                    val valueString = if (item.useDecimals) {-                        String.format("%.1f", item.value)-                    } else {-                        String.format("%,d", item.value.toLong())-                    }+                    val format = { v: Double -> if (item.useDecimals) String.format("%.1f", v) else String.format("%,d", v.toLong()) }+                    val valueString = if (item.secondaryValue != null) "${format(item.value)}/${format(item.secondaryValue)}" else format(item.value)                      Text(                         text = "$valueString ${item.unit}",
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 92a0ccee8f..c2e80657e0 100644--- a/health/src/main/java/com/vayunmathur/health/ui/MainPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/MainPage.kt@@ -197,11 +197,11 @@ fun MainPage(backStack: NavBackStack<Route>) {             Text("Nutrition (Today)", style = MaterialTheme.typography.labelLarge)             // TODO: add this back             //NutritionSummaryCard(aggregates)-            Hydration(hydrationToday)+            Hydration(backStack, hydrationToday)              // 3. Body Composition             Text("Body Composition", style = MaterialTheme.typography.labelLarge)-            BodyCompositionDashboard(height, weight, bodyFat, leanBodyMass, boneMass, bodyWaterMass)+            BodyCompositionDashboard(backStack, height, weight, bodyFat, leanBodyMass, boneMass, bodyWaterMass)              Spacer(modifier = Modifier.height(24.dp))         }@@ -241,8 +241,12 @@ fun NutritionMacro(label: String, value: Double?, unit: String) { 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(0, items, "Blood Pressure", bp?.let { "${it.first.toInt()}/${it.second.toInt()}" }, "mmHg", onClick = {+            backStack.add(Route.BarChartDetails(HealthMetricConfig.BLOOD_PRESSURE))+        })+        MetricSegmentCard(1, items, "Blood Glucose", bg, "mg/dL", onClick = {+            backStack.add(Route.BarChartDetails(HealthMetricConfig.GLUCOSE))+        })         MetricSegmentCard(2, items, "Oxygen Saturation", spo2, "%", onClick = {             backStack.add(Route.BarChartDetails(HealthMetricConfig.OXYGEN_SATURATION))         })@@ -255,21 +259,37 @@ fun VitalsDashboard(backStack: NavBackStack<Route>, br: Double?, spo2: Double?,         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)+        MetricSegmentCard(6, items, "VO2 Max", vo2, "mL/kg/min", onClick = {+            backStack.add(Route.BarChartDetails(HealthMetricConfig.VO2_MAX))+        })+        MetricSegmentCard(7, items, "Skin Temp Var", temp, "°C", showSign = true, onClick = {+            backStack.add(Route.BarChartDetails(HealthMetricConfig.SKIN_TEMP))+        })     } }  @Composable-fun BodyCompositionDashboard(h: Double?, w: Double?, bf: Double?, lbm: Double?, bm: Double?, bw: Double?) {+fun BodyCompositionDashboard(backStack: NavBackStack<Route>, h: Double?, w: Double?, bf: Double?, lbm: Double?, bm: Double?, bw: Double?) {     val items = 6     Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {-        MetricSegmentCard(0, items, "Height", h?.let { it * 100 }, "cm")-        MetricSegmentCard(1, items, "Weight", w, "kg")-        MetricSegmentCard(2, items, "Body Fat", bf, "%")-        MetricSegmentCard(3, items, "Lean Body Mass", lbm, "kg")-        MetricSegmentCard(4, items, "Bone Mass", bm, "kg")-        MetricSegmentCard(5, items, "Body Water Mass", bw, "kg")+        MetricSegmentCard(0, items, "Height", h?.let { it * 100 }, "cm", onClick = {+            backStack.add(Route.BarChartDetails(HealthMetricConfig.HEIGHT))+        })+        MetricSegmentCard(1, items, "Weight", w, "kg", onClick = {+            backStack.add(Route.BarChartDetails(HealthMetricConfig.WEIGHT))+        })+        MetricSegmentCard(2, items, "Body Fat", bf, "%", onClick = {+            backStack.add(Route.BarChartDetails(HealthMetricConfig.BODY_FAT))+        })+        MetricSegmentCard(3, items, "Lean Body Mass", lbm, "kg", onClick = {+            backStack.add(Route.BarChartDetails(HealthMetricConfig.LEAN_BODY_MASS))+        })+        MetricSegmentCard(4, items, "Bone Mass", bm, "kg", onClick = {+            backStack.add(Route.BarChartDetails(HealthMetricConfig.BONE_MASS))+        })+        MetricSegmentCard(5, items, "Body Water Mass", bw, "kg", onClick = {+            backStack.add(Route.BarChartDetails(HealthMetricConfig.BODY_WATER_MASS))+        })     } } @@ -322,8 +342,10 @@ fun verticalSegmentedCardShape(index: Int, total: Int): Shape { }  @Composable-fun Hydration(ml: Double) {-    GenericCard("Hydration", null, "mL", ml.toInt().toString(), "Today") {+fun Hydration(backStack: NavBackStack<Route>, ml: Double) {+    GenericCard("Hydration", null, "mL", ml.toInt().toString(), "Today", onClick = {+        backStack.add(Route.BarChartDetails(HealthMetricConfig.HYDRATION))+    }) {         ProgressBarGraphic(R.drawable.baseline_local_fire_department_24, ml.toFloat(), 3000f, Color(0xFF2196F3))     } }
maps/src/main/java/com/vayunmathur/maps/data/Tag.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/Tag.kt b/maps/src/main/java/com/vayunmathur/maps/data/Tag.ktindex 371f5f1798..279fbc8e7f 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/Tag.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/Tag.kt@@ -61,65 +61,36 @@ data class AmenitySearchResult( @Dao interface AmenityDao { -    /**-     * The High-Speed Search.-     * 1. Joins with the FTS5 table for instant text matching.-     * 2. Uses the 'knn' virtual table to utilize the R-Tree index.-     * * @param searchQuery The text to match (e.g., "Starbucks")-     * @param userLat Current user latitude-     * @param userLng Current user longitude-     * @param limit Maximum number of results to return-     */-    @SkipQueryVerification     @Query("""-        SELECT -            a.id, -            a.name, -            a.lat, -            a.lon, -            ST_Distance(a.geom, MakePoint(:userLng, :userLat, 4326), 1) AS distanceInMeters-        FROM knn k-        JOIN Amenities a ON k.fid = a.id-        JOIN Amenities_fts f ON a.id = f.rowid+    SELECT +        a.id, +        a.name, +        a.lat, +        a.lon, +        ST_Distance(a.geom, MakePoint(:userLng, :userLat, 4326), 1) AS distanceInMeters+    FROM Amenities a+    -- Filter 1: Full Text Search (Fast)+    JOIN Amenities_fts f ON a.id = f.rowid+    WHERE f.name MATCH :searchQuery+      -- Filter 2: Spatial Index (Fastest way to prune 32M rows)+      AND a.id IN (+        SELECT rowid +        FROM SpatialIndex          WHERE f_table_name = 'Amenities'            AND f_geometry_column = 'geom'-          AND ref_geometry = MakePoint(:userLng, :userLat, 4326)-          AND max_items = 100-          AND f.name MATCH :searchQuery-        ORDER BY distanceInMeters ASC-        LIMIT :limit-    """)-    suspend fun findNearestAmenities(-        searchQuery: String,-        userLat: Double,-        userLng: Double,-        limit: Int = 15-    ): List<AmenitySearchResult>--    /**-     * Fallback search for when the user hasn't typed anything yet (Browsing mode).-     * This skips FTS and purely uses the R-Tree KNN search.-     */+          AND search_frame = BuildCircleMbr(:userLng, :userLat, :radiusInDegrees, 4326)+      )+    ORDER BY distanceInMeters ASC+    LIMIT :limit+""")     @SkipQueryVerification-    @Query("""-        SELECT -            a.id, -            a.name, -            a.lat, -            a.lon, -            ST_Distance(a.geom, MakePoint(:userLng, :userLat, 4326), 1) AS distanceInMeters-        FROM knn k-        JOIN Amenities a ON k.fid = a.id-        WHERE f_table_name = 'Amenities' -          AND f_geometry_column = 'geom'-          AND ref_geometry = MakePoint(:userLng, :userLat, 4326)-          AND max_items = :limit-    """)-    suspend fun getNearest(+    suspend fun searchNearby(         userLat: Double,         userLng: Double,-        limit: Int = 15-    ): List<AmenitySearchResult>+        searchQuery: String,+        radiusInDegrees: Double = 0.5,+        limit: Int = 100+    ): List<AmenityEntity>      @Query("SELECT * FROM Amenities WHERE id = :id")     suspend fun getById(id: Long): AmenityEntity?
maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.ktindex 5c402b6dd2..01269a7d3b 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -60,6 +60,8 @@ import com.vayunmathur.maps.ensurePmtilesReady import com.vayunmathur.maps.ui.components.BottomSheetContent import com.vayunmathur.maps.ui.components.MyMapLayers import com.vayunmathur.maps.ui.components.UserIcon+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.serialization.json.Json import kotlinx.serialization.json.buildJsonArray@@ -196,6 +198,13 @@ fun MapPage(backStack: NavBackStack<Route>, ds: DataStoreUtils, db: AmenityDatab         inactiveNavigation = null     } +    LaunchedEffect(Unit) {+        CoroutineScope(Dispatchers.IO).launch {+            val res = db.amenityDao().searchNearby(34.0248435,-118.2867097, "Subway")+            println("CLOSEST RESULTS: $res")+        }+    }+     var selectedRouteType by remember { mutableStateOf(RouteService.TravelMode.DRIVE) }      // --- RENDER ---