Modern Apps git

← Modern-Apps.git

health: redesign bar/line chart layout for readability

Commit
60f04516c92e2dbef2a88876ed96de2c4254262c
Author
Vayun Mathur <[email protected]>
When
2026-05-29 19:05 UTC (6 months ago)
Parents
83a268e

Diff

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 4e8cf807c5..b0f4ca64d7 100644--- a/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt@@ -1,6 +1,8 @@ package com.vayunmathur.health.ui  import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column@@ -13,6 +15,7 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton@@ -37,14 +40,17 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip 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.annotation.StringRes import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding+import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.res.painterResource import androidx.compose.ui.layout.layout import androidx.compose.ui.platform.LocalDensity@@ -434,45 +440,33 @@ fun BarChartDetails(                     }                  if (hasData) {-                    Row(verticalAlignment = Alignment.Bottom) {-                        val formatVal = { v: Double ->-                            if (config.useDecimals) v.round(1).toString() else v.toLong()-                                .toStringCommas()-                        }-                        val avgString = if (config == HealthMetricConfig.HEART_RATE) {-                            stringResource(-                                R.string.dash_value_format,-                                formatVal(dataState.primaryRange?.start ?: 0.0),-                                formatVal(dataState.primaryRange?.endInclusive ?: 0.0)-                            )-                        } else if (dataState.secondaryAverage != null && config.isDualSeries) {-                            stringResource(-                                R.string.slash_value_format,-                                formatVal(dataState.dailyAverage),-                                formatVal(dataState.secondaryAverage!!)-                            )-                        } else {-                            formatVal(dataState.dailyAverage)-                        }--                        Text(-                            text = avgString,-                            style = MaterialTheme.typography.displayMedium,-                            fontWeight = FontWeight.Light,-                            color = colorFor(config),-                        )-                        Text(-                            text = if (selectedTab != 0 && !config.isLineChart) stringResource(-                                R.string.unit_per_day_avg_format, config.unit-                            ) else stringResource(R.string.unit_only_format, config.unit),-                            style = MaterialTheme.typography.bodyLarge,-                            modifier = Modifier.padding(bottom = 12.dp, start = 4.dp),-                            color = LocalContentColor.current.copy(alpha = 0.6f)-                        )-                    }+                    ChartHeader(+                        config = config,+                        avgString = run {+                            val formatVal = { v: Double ->+                                if (config.useDecimals) v.round(1).toString() else v.toLong().toStringCommas()+                            }+                            when {+                                config == HealthMetricConfig.HEART_RATE -> stringResource(+                                    R.string.dash_value_format,+                                    formatVal(dataState.primaryRange?.start ?: 0.0),+                                    formatVal(dataState.primaryRange?.endInclusive ?: 0.0)+                                )+                                dataState.secondaryAverage != null && config.isDualSeries -> stringResource(+                                    R.string.slash_value_format,+                                    formatVal(dataState.dailyAverage),+                                    formatVal(dataState.secondaryAverage!!)+                                )+                                else -> formatVal(dataState.dailyAverage)+                            }+                        },+                        unitLabel = if (selectedTab != 0 && !config.isLineChart) stringResource(+                            R.string.unit_per_day_avg_format, config.unit+                        ) else stringResource(R.string.unit_only_format, config.unit),+                    )                 } -                Spacer(Modifier.height(24.dp))+                Spacer(Modifier.height(16.dp))                  if (!hasData) {                     Box(@@ -554,6 +548,59 @@ fun BarChartDetails(     } } +@Composable+private fun ChartHeader(+    config: HealthMetricConfig,+    avgString: String,+    unitLabel: String,+) {+    val accent = colorFor(config)+    val iconRes = iconResFor(config)+    Row(verticalAlignment = Alignment.Bottom) {+        Box(+            modifier = Modifier+                .padding(end = 12.dp, bottom = 10.dp)+                .size(36.dp)+                .clip(CircleShape)+                .background(accent.copy(alpha = 0.15f)),+            contentAlignment = Alignment.Center,+        ) {+            Icon(+                painter = painterResource(iconRes),+                contentDescription = null,+                tint = accent,+                modifier = Modifier.size(20.dp),+            )+        }+        Text(+            text = avgString,+            style = MaterialTheme.typography.displayMedium,+            fontWeight = FontWeight.Light,+            color = accent,+        )+        Text(+            text = unitLabel,+            style = MaterialTheme.typography.bodyLarge,+            modifier = Modifier.padding(bottom = 12.dp, start = 4.dp),+            color = LocalContentColor.current.copy(alpha = 0.6f)+        )+    }+}++private fun iconResFor(config: HealthMetricConfig): Int = when (config.recordType) {+    RecordType.Steps, RecordType.Distance, RecordType.Floors, RecordType.Elevation,+    RecordType.Wheelchair -> R.drawable.outline_directions_walk_24+    RecordType.CaloriesActive, RecordType.CaloriesTotal, RecordType.CaloriesBasal -> R.drawable.baseline_local_fire_department_24+    RecordType.HeartRate, RecordType.RestingHeartRate, RecordType.HeartRateVariabilityRmssd,+    RecordType.RespiratoryRate, RecordType.OxygenSaturation, RecordType.BloodPressure,+    RecordType.BloodGlucose, RecordType.Vo2Max, RecordType.SkinTemperature -> R.drawable.baseline_favorite_24+    RecordType.Weight, RecordType.Height, RecordType.BodyFat, RecordType.LeanBodyMass,+    RecordType.BoneMass, RecordType.BodyWaterMass -> R.drawable.body_24px+    RecordType.Sleep, RecordType.Mindfulness -> R.drawable.baseline_bedtime_24+    RecordType.Hydration -> R.drawable.baseline_bedtime_24+    RecordType.Nutrition -> R.drawable.baseline_local_fire_department_24+}+ @Composable fun GenericLineChart(     data: List<Pair<String, Double?>>,@@ -570,11 +617,13 @@ fun GenericLineChart(         (data.mapNotNull { it.second } + (secondaryData?.mapNotNull { it.second } ?: emptyList()))     val maxChartValue =         (allValues.maxOrNull() ?: goalValue).coerceAtLeast(goalValue * 1.2).coerceAtLeast(10.0)+    val minSeriesValue = allValues.minOrNull() ?: 0.0+    val avgSeriesValue = if (allValues.isNotEmpty()) allValues.average() else 0.0     val labelColor = LocalContentColor.current.copy(alpha = 0.6f) -    val chartHeight = 180.dp+    val chartHeight = 200.dp     val xAxisHeight = 24.dp-    val sideLabelWidth = 40.dp+    val sideLabelWidth = 44.dp      val context = LocalContext.current     val resources = context.resources@@ -599,21 +648,42 @@ fun GenericLineChart(             val height = size.height             val width = size.width -            // Axis lines-            drawLine(-                color = labelColor.copy(alpha = 0.15f),-                start = Offset(0f, height),-                end = Offset(width, height),-                strokeWidth = 1.dp.toPx()-            )-            drawLine(-                color = labelColor.copy(alpha = 0.15f),-                start = Offset(width, 0f),-                end = Offset(width, height),-                strokeWidth = 1.dp.toPx()-            )+            // Subtle horizontal grid lines at 25/50/75/100%+            listOf(0.25f, 0.5f, 0.75f, 1f).forEach { frac ->+                drawLine(+                    color = labelColor.copy(alpha = 0.10f),+                    start = Offset(0f, height * (1f - frac)),+                    end = Offset(width, height * (1f - frac)),+                    strokeWidth = 1.dp.toPx()+                )+            } -            val drawSeries = { series: List<Pair<String, Double?>>, color: Color ->+            val drawSeries = { series: List<Pair<String, Double?>>, color: Color, isPrimary: Boolean ->+                // Filled area under the primary line+                if (isPrimary) {+                    val path = Path()+                    var started = false+                    var lastX = 0f+                    series.forEachIndexed { index, pair ->+                        val value = pair.second ?: return@forEachIndexed+                        val x = index * spacing+                        val y = height - (value.toFloat() / maxChartValue.toFloat() * height)+                            .coerceIn(0f, height)+                        if (!started) {+                            path.moveTo(x, height)+                            path.lineTo(x, y)+                            started = true+                        } else {+                            path.lineTo(x, y)+                        }+                        lastX = x+                    }+                    if (started) {+                        path.lineTo(lastX, height)+                        path.close()+                        drawPath(path, color = color.copy(alpha = 0.15f))+                    }+                }                 var lastValidPoint: Offset? = null                 series.forEachIndexed { index, pair ->                     val value = pair.second@@ -629,16 +699,15 @@ fun GenericLineChart(                                 color = color,                                 start = lastValidPoint,                                 end = currentPoint,-                                strokeWidth = 3.dp.toPx()+                                strokeWidth = 2.dp.toPx()                             )                         }-                        drawCircle(color = color, radius = 3.dp.toPx(), center = currentPoint)+                        drawCircle(color = color, radius = 2.5.dp.toPx(), center = currentPoint)                         lastValidPoint = currentPoint                     }                 }             } -            // Goal lines             val drawGoal = { goal: Double, color: Color, isSecondary: Boolean ->                 val gy = height - (goal.toFloat() / maxChartValue.toFloat() * height).coerceIn(                     0f, height@@ -650,20 +719,21 @@ fun GenericLineChart(                     strokeWidth = 1.dp.toPx(),                     pathEffect = if (isSecondary) PathEffect.dashPathEffect(                         floatArrayOf(10f, 10f), 0f-                    ) else null+                    ) else PathEffect.dashPathEffect(floatArrayOf(8f, 6f), 0f)                 )             }              drawGoal(goalValue, goalColor, false)             secondaryGoal?.let { drawGoal(it, goalColor.copy(alpha = 0.5f), true) } -            drawSeries(data, lineColor)-            secondaryData?.let { drawSeries(it, secondaryLineColor) }+            drawSeries(data, lineColor, true)+            secondaryData?.let { drawSeries(it, secondaryLineColor, false) }         } -        // X-axis labels+        // Decimated X-axis labels+        val labelStep = decimationStep(data.size)         data.forEachIndexed { index, pair ->-            if (pair.first.isNotEmpty()) {+            if (pair.first.isNotEmpty() && index % labelStep == 0) {                 val x = index * spacing                 Text(                     text = pair.first,@@ -681,55 +751,21 @@ fun GenericLineChart(             }         } -        // Y-axis labels+        // Y-axis labels: max, avg, min, 0         val format = { v: Double ->             if (v >= 10000) resources.getString(                 R.string.k_format, (v / 1000).round(0).toString()             ) else v.toLong().toStringCommas()         } -        Text(-            text = format(maxChartValue),-            color = labelColor,-            fontSize = 10.sp,-            modifier = Modifier-                .align(Alignment.TopEnd)-                .width(sideLabelWidth)-                .padding(start = 4.dp)-        )--        val goalY = (1f - (goalValue.toFloat() / maxChartValue.toFloat())) * actualChartHeightPx-        Text(-            text = format(goalValue),-            color = goalColor,-            fontSize = 10.sp,-            modifier = Modifier-                .align(Alignment.TopEnd)-                .width(sideLabelWidth)-                .offset(y = with(density) { goalY.toDp() })-                .layout { measurable, constraints ->-                    val placeable = measurable.measure(constraints)-                    layout(placeable.width, placeable.height) {-                        placeable.placeRelative(0, -(placeable.height / 2))-                    }-                }-                .padding(start = 4.dp))--        Text(-            text = "0",-            color = labelColor,-            fontSize = 10.sp,-            modifier = Modifier-                .align(Alignment.TopEnd)-                .width(sideLabelWidth)-                .offset(y = with(density) { actualChartHeightPx.toDp() })-                .layout { measurable, constraints ->-                    val placeable = measurable.measure(constraints)-                    layout(placeable.width, placeable.height) {-                        placeable.placeRelative(0, -(placeable.height / 2))-                    }-                }-                .padding(start = 4.dp))+        YAxisLabel(format(maxChartValue), labelColor, sideLabelWidth, 0f, density)+        if (allValues.isNotEmpty()) {+            val avgY = (1f - (avgSeriesValue.toFloat() / maxChartValue.toFloat())) * actualChartHeightPx+            YAxisLabel("avg ${format(avgSeriesValue)}", lineColor, sideLabelWidth, avgY, density)+            val minY = (1f - (minSeriesValue.toFloat() / maxChartValue.toFloat())) * actualChartHeightPx+            YAxisLabel("min ${format(minSeriesValue)}", labelColor, sideLabelWidth, minY, density)+        }+        YAxisLabel("0", labelColor, sideLabelWidth, actualChartHeightPx, density)     } } @@ -742,69 +778,109 @@ fun GenericBarChart(     goalColor: Color ) {     val maxValueFound = data.maxOfOrNull { it.second } ?: 0.0+    val avgValueFound = if (data.isNotEmpty()) data.map { it.second }.average() else 0.0     val maxChartValue = (maxValueFound.toFloat() * 1.2f).coerceAtLeast(goalValue.toFloat() * 1.2f)         .coerceAtLeast(10f)     val labelColor = LocalContentColor.current.copy(alpha = 0.6f)+    var selectedIndex by remember(data) { mutableIntStateOf(-1) } -    val chartHeight = 180.dp+    val chartHeight = 200.dp     val xAxisHeight = 24.dp-    val sideLabelWidth = 40.dp+    val sideLabelWidth = 44.dp+    val tooltipHeight = 20.dp      val context = LocalContext.current     val resources = context.resources     BoxWithConstraints(         modifier = Modifier             .fillMaxWidth()-            .height(chartHeight)+            .height(chartHeight + tooltipHeight)     ) {         val density = LocalDensity.current         val fullWidthPx = with(density) { maxWidth.toPx() }         val sideLabelWidthPx = with(density) { sideLabelWidth.toPx() }         val chartWidthPx = fullWidthPx - sideLabelWidthPx-        val actualChartHeightPx = with(density) { (chartHeight - xAxisHeight).toPx() }          val barWidth = with(density) { 6.dp.toPx() }         val spacing =             (chartWidthPx - (totalBarCount * barWidth)) / (totalBarCount + 1).coerceAtLeast(1)+        val format = { v: Double ->+            if (v >= 10000) resources.getString(+                R.string.k_format, (v / 1000).round(0).toString()+            ) else v.toLong().toStringCommas()+        }++        // Tooltip above selected bar+        if (selectedIndex in data.indices) {+            val pair = data[selectedIndex]+            val barCenterX = spacing + selectedIndex * (barWidth + spacing) + barWidth / 2+            Text(+                text = format(pair.second),+                color = barColor,+                fontSize = 11.sp,+                fontWeight = FontWeight.SemiBold,+                modifier = Modifier+                    .align(Alignment.TopStart)+                    .offset(x = with(density) { barCenterX.toDp() })+                    .layout { measurable, constraints ->+                        val placeable = measurable.measure(constraints)+                        layout(placeable.width, placeable.height) {+                            placeable.placeRelative(-(placeable.width / 2), 0)+                        }+                    }+            )+        }          Canvas(             modifier = Modifier-                .fillMaxSize()+                .fillMaxWidth()+                .height(chartHeight)+                .align(Alignment.BottomStart)                 .padding(end = sideLabelWidth, bottom = xAxisHeight)+                .pointerInput(data, totalBarCount) {+                    detectTapGestures { offset ->+                        val tapX = offset.x+                        val matched = data.indices.firstOrNull { idx ->+                            val left = spacing + idx * (barWidth + spacing)+                            tapX >= left - spacing / 2 && tapX <= left + barWidth + spacing / 2+                        } ?: -1+                        selectedIndex = if (matched == selectedIndex) -1 else matched+                    }+                }         ) {             val height = size.height             val width = size.width -            // Axis lines-            drawLine(-                color = labelColor.copy(alpha = 0.15f),-                start = Offset(0f, height),-                end = Offset(width, height),-                strokeWidth = 1.dp.toPx()-            )-            drawLine(-                color = labelColor.copy(alpha = 0.15f),-                start = Offset(width, 0f),-                end = Offset(width, height),-                strokeWidth = 1.dp.toPx()-            )+            // Subtle horizontal grid lines at 25/50/75/100%+            listOf(0.25f, 0.5f, 0.75f, 1f).forEach { frac ->+                drawLine(+                    color = labelColor.copy(alpha = 0.10f),+                    start = Offset(0f, height * (1f - frac)),+                    end = Offset(width, height * (1f - frac)),+                    strokeWidth = 1.dp.toPx()+                )+            }              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()+                strokeWidth = 1.dp.toPx(),+                pathEffect = PathEffect.dashPathEffect(floatArrayOf(8f, 6f), 0f)             )              data.forEachIndexed { index, pair ->                 val barHeight =-                    (pair.second.toFloat() / maxChartValue * height).coerceIn(4f, height)+                    (pair.second.toFloat() / maxChartValue * height).coerceIn(+                        if (pair.second > 0) 4f else 0f, height+                    )                 val x = spacing + index * (barWidth + spacing)                 val y = height - barHeight-+                val drawColor = if (selectedIndex < 0 || selectedIndex == index) barColor+                else barColor.copy(alpha = 0.6f)                 drawRoundRect(-                    color = barColor,+                    color = drawColor,                     topLeft = Offset(x, y),                     size = Size(barWidth, barHeight),                     cornerRadius = CornerRadius(2.dp.toPx(), 2.dp.toPx())@@ -812,9 +888,10 @@ fun GenericBarChart(             }         } -        // X-axis labels+        // Decimated X-axis labels+        val labelStep = decimationStep(totalBarCount)         data.forEachIndexed { index, pair ->-            if (pair.first.isNotEmpty()) {+            if (pair.first.isNotEmpty() && index % labelStep == 0) {                 val x = spacing + index * (barWidth + spacing) + barWidth / 2                 Text(                     text = pair.first,@@ -832,54 +909,47 @@ fun GenericBarChart(             }         } -        // Y-axis labels-        val format = { v: Double ->-            if (v >= 10000) resources.getString(-                R.string.k_format, (v / 1000).round(0).toString()-            ) else v.toLong().toStringCommas()+        // Y-axis labels: max, avg, 0+        val actualChartHeightPx = with(density) { (chartHeight - xAxisHeight).toPx() }+        val topOffsetPx = with(density) { tooltipHeight.toPx() }+        YAxisLabel(format(maxChartValue.toDouble()), labelColor, sideLabelWidth, topOffsetPx, density)+        if (data.isNotEmpty()) {+            val avgY = topOffsetPx + (1f - (avgValueFound.toFloat() / maxChartValue)) * actualChartHeightPx+            YAxisLabel("avg ${format(avgValueFound)}", barColor, sideLabelWidth, avgY, density)         }+        YAxisLabel("0", labelColor, sideLabelWidth, topOffsetPx + actualChartHeightPx, density)+    }+} -        Text(-            text = format(maxChartValue.toDouble()),-            color = labelColor,-            fontSize = 10.sp,-            modifier = Modifier-                .align(Alignment.TopEnd)-                .width(sideLabelWidth)-                .padding(start = 4.dp)-        )--        val goalY = (1f - (goalValue.toFloat() / maxChartValue)) * actualChartHeightPx-        Text(-            text = format(goalValue),-            color = goalColor,-            fontSize = 10.sp,-            modifier = Modifier-                .align(Alignment.TopEnd)-                .width(sideLabelWidth)-                .offset(y = with(density) { goalY.toDp() })-                .layout { measurable, constraints ->-                    val placeable = measurable.measure(constraints)-                    layout(placeable.width, placeable.height) {-                        placeable.placeRelative(0, -(placeable.height / 2))-                    }-                }-                .padding(start = 4.dp))+private fun decimationStep(count: Int): Int = when {+    count <= 8 -> 1+    count <= 16 -> 2+    count <= 24 -> 3+    else -> 5+} -        Text(-            text = "0",-            color = labelColor,-            fontSize = 10.sp,-            modifier = Modifier-                .align(Alignment.TopEnd)-                .width(sideLabelWidth)-                .offset(y = with(density) { actualChartHeightPx.toDp() })-                .layout { measurable, constraints ->-                    val placeable = measurable.measure(constraints)-                    layout(placeable.width, placeable.height) {-                        placeable.placeRelative(0, -(placeable.height / 2))-                    }+@Composable+private fun androidx.compose.foundation.layout.BoxScope.YAxisLabel(+    text: String,+    color: Color,+    sideLabelWidth: Dp,+    yPx: Float,+    density: androidx.compose.ui.unit.Density,+) {+    Text(+        text = text,+        color = color,+        fontSize = 10.sp,+        modifier = Modifier+            .align(Alignment.TopEnd)+            .width(sideLabelWidth)+            .offset(y = with(density) { yPx.toDp() })+            .layout { measurable, constraints ->+                val placeable = measurable.measure(constraints)+                layout(placeable.width, placeable.height) {+                    placeable.placeRelative(0, -(placeable.height / 2))                 }-                .padding(start = 4.dp))-    }+            }+            .padding(start = 4.dp)+    ) }