health: improved graphs
- Commit
ea9ef51c3e2853a952e5f1458dff5daf18ed05cc- Author
- Vayun Mathur <[email protected]>
- When
- 2026-03-03 23:18 UTC (9 months ago)
- Parents
be01055
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 2d47754ce3..3974045f75 100644--- a/health/src/main/java/com/vayunmathur/health/HealthAPI.kt+++ b/health/src/main/java/com/vayunmathur/health/HealthAPI.kt@@ -12,13 +12,19 @@ import androidx.health.connect.client.request.ReadMedicalResourcesPageRequest import com.vayunmathur.health.database.HealthDatabase import com.vayunmathur.health.database.Record import com.vayunmathur.health.database.RecordType+import com.vayunmathur.library.util.Tuple3 import kotlinx.coroutines.flow.Flow import kotlinx.datetime.DateTimeUnit+import kotlinx.datetime.LocalDate+import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone+import kotlinx.datetime.atStartOfDayIn import kotlinx.datetime.atTime+import kotlinx.datetime.minus import kotlinx.datetime.plus import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime+import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.hours import kotlin.time.Instant @@ -53,7 +59,7 @@ object HealthAPI { } enum class PeriodType {- Hourly, Daily, Weekly+ Hourly, Daily, Weekly, Monthly } suspend fun getListOfAverages(@@ -83,6 +89,11 @@ object HealthAPI { val nextLocalDate = localDateTime.date.plus(1, DateTimeUnit.WEEK) nextLocalDate.atTime(localDateTime.hour, localDateTime.minute).toInstant(tz) }+ PeriodType.Monthly -> {+ val localDateTime = currentStart.toLocalDateTime(tz)+ val nextLocalDate = localDateTime.date.plus(1, DateTimeUnit.MONTH)+ nextLocalDate.atTime(localDateTime.hour, localDateTime.minute).toInstant(tz)+ } } // Clamp the end range to the requested endTime@@ -104,42 +115,43 @@ object HealthAPI { startTime: Instant, endTime: Instant, period: PeriodType- ): List<Pair<Double, Double>> {- val tz = TimeZone.currentSystemDefault()- val sums = mutableListOf<Pair<Double, 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)+ ): List<Tuple3<Long, Double, Double>> {+ when(period) {+ PeriodType.Daily -> {+ // yyyy-mm-dd+ val dailySums = db.healthDao().getDailySums(recordType, startTime, endTime).sortedBy { it.day }+ return dailySums.map { Tuple3(LocalDate.parse(it.day).toEpochDays(), it.totalValue, it.totalValue2) }+ }+ PeriodType.Weekly -> {+ val dailySums = db.healthDao().getDailySums(recordType, startTime, endTime).sortedBy { it.day }+ .groupBy {+ val date = LocalDate.parse(it.day)+ val firstDayOfWeek = date.plus((date.dayOfWeek.ordinal+1)%7, DateTimeUnit.DAY)+ firstDayOfWeek.toEpochDays()+ }+ .mapValues { it.value.map { it.totalValue }.average() to it.value.map { it.totalValue2 }.average() }+ .map { Tuple3(it.key, it.value.first, it.value.second) }+ return dailySums+ }+ PeriodType.Monthly -> {+ val dailySums = db.healthDao().getDailySums(recordType, startTime, endTime).sortedBy { it.day }+ .groupBy {+ val date = LocalDate.parse(it.day)+ val firstDayOfMonth = date.minus(date.day-1, DateTimeUnit.DAY)+ firstDayOfMonth+ }+ .mapValues { it.value.map { it.totalValue }.average() to it.value.map { it.totalValue2 }.average() }+ .map { Tuple3(it.key.toEpochDays(), it.value.first, it.value.second) }+ return dailySums+ }+ else -> {+ val hourlySums = db.healthDao().getHourlySums(recordType, startTime.toEpochMilliseconds(), endTime.toEpochMilliseconds()).sortedBy { it.hourBlock }+ return hourlySums.map {+ val date = LocalDateTime.parse(it.hourBlock)+ Tuple3(date.date.toEpochDays()*24 + date.hour, it.totalValue, it.totalValue2) } }-- // Clamp the end range to the requested endTime- val currentEnd = if (nextStart > endTime) endTime else nextStart-- // Fetch sum from DAO- val sum1 = db.healthDao().sumInRangeGet1(recordType, currentStart, currentEnd)- val sum2 = db.healthDao().sumInRangeGet2(recordType, currentStart, currentEnd)- sums.add(Pair(sum1, sum2))-- currentStart = nextStart }-- return sums } @OptIn(ExperimentalPersonalHealthRecordApi::class)
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 c0ae1b973b..8080ba3a3f 100644--- a/health/src/main/java/com/vayunmathur/health/database/StepsRecordEntity.kt+++ b/health/src/main/java/com/vayunmathur/health/database/StepsRecordEntity.kt@@ -66,6 +66,54 @@ interface HealthDao { 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>>++ @Query("""+ SELECT + date(startTime / 1000, 'unixepoch', 'localtime') as day, + SUM(value) as totalValue,+ SUM(secondaryValue) as totalValue2 + FROM Record + WHERE type = :type + AND startTime >= :startTime + AND endTime <= :endTime+ GROUP BY day+ ORDER BY day ASC+""")+ suspend fun getDailySums(+ type: RecordType,+ startTime: kotlin.time.Instant,+ endTime: kotlin.time.Instant+ ): List<DailySum>++ @Query("""+ SELECT + strftime('%Y-%m-%d %H:00', startTime / 1000, 'unixepoch', 'localtime') AS hourBlock, + SUM(value) AS totalValue,+ SUM(secondaryValue) AS totalValue2+ FROM Record + WHERE type = :type + AND startTime >= :startTime + AND endTime <= :endTime+ GROUP BY hourBlock+ ORDER BY hourBlock ASC+""")+ suspend fun getHourlySums(+ type: RecordType,+ startTime: Long,+ endTime: Long+ ): List<HourlySum>++ // Helper data class to catch the results+ data class DailySum(+ val day: String, // Format: YYYY-MM-DD+ val totalValue: Double,+ val totalValue2: Double+ )+ data class HourlySum(+ val hourBlock: String, // Format: 2026-03-03 15:00+ val totalValue: Double,+ val totalValue2: Double+ ) } @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 53c2699ca0..2325de0579 100644--- a/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/BarChartDetails.kt@@ -16,12 +16,17 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton+import androidx.compose.material3.ListItem+import androidx.compose.material3.ListItemDefaults import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold+import androidx.compose.material3.SecondaryTabRow import androidx.compose.material3.Surface import androidx.compose.material3.Tab import androidx.compose.material3.TabRow@@ -50,7 +55,12 @@ import com.vayunmathur.health.HealthAPI import com.vayunmathur.health.R import com.vayunmathur.health.Route import com.vayunmathur.health.database.RecordType+import com.vayunmathur.library.ui.IconCheck import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.util.Tuple3+import com.vayunmathur.library.util.Tuple4+import com.vayunmathur.library.util.toStringCommas+import com.vayunmathur.library.util.toStringDigits import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone@@ -62,6 +72,8 @@ import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime import kotlinx.datetime.todayIn import kotlin.time.Clock+import kotlin.time.Duration.Companion.days+import kotlin.time.Duration.Companion.hours /** * Configuration for health metrics.@@ -117,7 +129,7 @@ data class MetricDashboardData( data class HistoryItem( val label: String,- val value: Double?,+ val value: Double, val secondaryValue: Double? = null, val unit: String, val isGoalMet: Boolean,@@ -139,55 +151,73 @@ fun BarChartDetails( val tz = TimeZone.currentSystemDefault() 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)+ val (startDate, endDate, periodType, periodType2) = when (selectedTab) {+ 0 -> Tuple4(anchorDate, anchorDate.plus(1, DateTimeUnit.DAY), HealthAPI.PeriodType.Hourly, 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)+ val start = anchorDate.minus((anchorDate.dayOfWeek.ordinal+1)%7, DateTimeUnit.DAY)+ Tuple4(start, start.plus(7, DateTimeUnit.DAY), HealthAPI.PeriodType.Daily, HealthAPI.PeriodType.Daily) } 2 -> { val start = LocalDate(anchorDate.year, anchorDate.month, 1) val end = start.plus(1, DateTimeUnit.MONTH)- Triple(start.atStartOfDayIn(tz), end.atStartOfDayIn(tz), HealthAPI.PeriodType.Daily)+ Tuple4(start, end, HealthAPI.PeriodType.Daily, HealthAPI.PeriodType.Weekly) } 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)+ Tuple4(start, end, HealthAPI.PeriodType.Monthly, HealthAPI.PeriodType.Monthly) } }+ val startTime = startDate.atStartOfDayIn(tz)+ val endTime = endDate.atStartOfDayIn(tz)++ val endTimeNow = if(Clock.System.now() < endTime) Clock.System.now() else endTime // Both functions now return List<Pair<Double?, Double?>> val rawPairs = if (config.isLineChart) {- HealthAPI.getListOfAverages(config.recordType, startTime, endTime, periodType)+ HealthAPI.getListOfAverages(config.recordType, startTime, endTimeNow, periodType).mapIndexed { idx, it ->+ Tuple3(+ idx.toLong(),+ it.first,+ it.second+ )+ }+ } else {+ HealthAPI.getListOfSums(config.recordType, startTime, endTimeNow, periodType)+ }+ val rawPairsHistory = if (config.isLineChart) {+ HealthAPI.getListOfAverages(config.recordType, startTime, endTimeNow, periodType2).mapIndexed { idx, it ->+ Tuple3(idx, it.first, it.second)+ } } else {- HealthAPI.getListOfSums(config.recordType, startTime, endTime, periodType)+ HealthAPI.getListOfSums(config.recordType, startTime, endTimeNow, periodType2) } - val mappedChart = rawPairs.mapIndexed { i, p -> i.toString() to p.first }+ val mappedChart = rawPairs.mapIndexed { i, p -> i.toString() to p.second } val mappedSecondaryChart = if (config.isDualSeries) {- rawPairs.mapIndexed { i, p -> i.toString() to p.second }+ rawPairs.mapIndexed { i, p -> i.toString() to p.third } } else null - val history = rawPairs.mapIndexed { index, pair ->+ val history = if(selectedTab != 0) rawPairsHistory.mapIndexedNotNull { index, triple -> val label = when (selectedTab) {- 0 -> "Hour $index"+ 0 -> "" 1 -> startTime.plus(index.toLong(), DateTimeUnit.DAY, tz).toLocalDateTime(tz).dayOfWeek.name.lowercase().replaceFirstChar { it.uppercase() } 2 -> "Day ${index + 1}"- else -> "Week ${index + 1}"+ else -> "Month ${index + 1}" }+ if(triple.second == null) return@mapIndexedNotNull null HistoryItem( label = label,- value = pair.first,- secondaryValue = if (config.isDualSeries) pair.second else null,+ value = triple.second!!,+ secondaryValue = if (config.isDualSeries) triple.third else null, unit = config.unit,- isGoalMet = (pair.first ?: 0.0) >= config.dailyGoal,+ isGoalMet = (triple.second ?: 0.0) >= config.dailyGoal, useDecimals = config.useDecimals )- }.filter { it.value != null }.reversed()+ }.reversed() else listOf() - val nonNullPrimary = rawPairs.mapNotNull { it.first }- val nonNullSecondary = if (config.isDualSeries) rawPairs.mapNotNull { it.second } else emptyList()+ val nonNullPrimary = history.map { it.value }+ val nonNullSecondary = if (config.isDualSeries) history.mapNotNull { it.secondaryValue } else emptyList() dataState = MetricDashboardData( totalValue = nonNullPrimary.sum(),@@ -209,7 +239,7 @@ fun BarChartDetails( } ) { padding -> Column(modifier = Modifier.padding(padding).fillMaxSize()) {- TabRow(selectedTabIndex = selectedTab, divider = {}) {+ SecondaryTabRow(selectedTabIndex = selectedTab, divider = {}) { tabs.forEachIndexed { index, title -> Tab( selected = selectedTab == index,@@ -226,7 +256,7 @@ fun BarChartDetails( item { val headerLabel = when (selectedTab) { 0 -> "${anchorDate.month.name} ${anchorDate.day}, ${anchorDate.year}"- 1 -> "Week of ${anchorDate.minus(anchorDate.dayOfWeek.ordinal, DateTimeUnit.DAY)}"+ 1 -> "Week of ${anchorDate.minus((anchorDate.dayOfWeek.ordinal+1)%7, DateTimeUnit.DAY)}" 2 -> "${anchorDate.month.name} ${anchorDate.year}" else -> anchorDate.year.toString() }@@ -249,6 +279,13 @@ fun BarChartDetails( Text(headerLabel, style = MaterialTheme.typography.titleMedium, modifier = Modifier.widthIn(min = 140.dp), textAlign = TextAlign.Center) + val nextDate = when(selectedTab) {+ 0 -> anchorDate.plus(1, DateTimeUnit.DAY)+ 1 -> anchorDate.plus(1, DateTimeUnit.WEEK)+ 2 -> anchorDate.plus(1, DateTimeUnit.MONTH)+ else -> anchorDate.plus(1, DateTimeUnit.YEAR)+ }+ IconButton(onClick = { anchorDate = when(selectedTab) { 0 -> anchorDate.plus(1, DateTimeUnit.DAY)@@ -256,7 +293,7 @@ fun BarChartDetails( 2 -> anchorDate.plus(1, DateTimeUnit.MONTH) else -> anchorDate.plus(1, DateTimeUnit.YEAR) }- }) {+ }, enabled = nextDate <= Clock.System.todayIn(TimeZone.currentSystemDefault())) { Icon(painterResource(R.drawable.outline_arrow_forward_24), "Next") } }@@ -306,11 +343,24 @@ fun BarChartDetails( goalColor = MaterialTheme.colorScheme.secondary ) }+ Spacer(Modifier.height(32.dp)) } - items(dataState.historyItems) { item ->- HistoryCard(item)- Spacer(Modifier.height(8.dp))+ itemsIndexed(dataState.historyItems) { idx, item ->+ Card(Modifier.padding(vertical = 2.dp), shape = verticalSegmentedCardShape(idx, dataState.historyItems.size)) {+ ListItem({+ Text(item.label)+ }, trailingContent = {+ Row {+ if(item.isGoalMet) {+ IconCheck()+ }+ val format = { v: Double -> if (item.useDecimals) v.toStringDigits(1) else v.toLong().toStringCommas() }+ val valueString = if (item.secondaryValue != null) "${format(item.value)}/${format(item.secondaryValue)}" else format(item.value)+ Text("$valueString ${item.unit}")+ }+ }, colors = ListItemDefaults.colors(containerColor = Color.Transparent))+ } } } }@@ -415,38 +465,4 @@ fun GenericBarChart( 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)) }-}--@Composable-fun HistoryCard(item: HistoryItem) {- Surface(color = Color.Transparent, modifier = Modifier.fillMaxWidth()) {- Row(- modifier = Modifier.padding(vertical = 12.dp),- verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.SpaceBetween- ) {- Text(item.label)- Row(verticalAlignment = Alignment.CenterVertically) {- 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 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}",- fontWeight = FontWeight.Medium- )- }- }- }- } }\ No newline at end of file
library/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/src/main/java/com/vayunmathur/library/ui/Icons.ktindex c4c5b33b91..73334a9696 100644--- a/library/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -77,4 +77,9 @@ fun IconNavigation(backStack: NavBackStack<out NavKey>) { }) { Icon(painterResource(R.drawable.arrow_back_24px), "Navigation") }+}++@Composable+fun IconCheck(tint: Color = LocalContentColor.current) {+ Icon(painterResource(R.drawable.outline_check_24), "Check", tint = tint) }\ No newline at end of file
library/src/main/java/com/vayunmathur/library/util/Format.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/Format.kt b/library/src/main/java/com/vayunmathur/library/util/Format.ktnew file mode 100644index 0000000000..535d3bf0aa--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/util/Format.kt@@ -0,0 +1,13 @@+package com.vayunmathur.library.util++import java.text.NumberFormat+import java.util.Locale+++fun Double.toStringDigits(digits: Int): String {+ return "%.${digits}f".format(this)+}++fun Long.toStringCommas(): String {+ return NumberFormat.getInstance(Locale.US).format(this)+}\ No newline at end of file
library/src/main/java/com/vayunmathur/library/util/Util.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/Util.kt b/library/src/main/java/com/vayunmathur/library/util/Util.ktindex 47a07eed13..97f1269a9e 100644--- a/library/src/main/java/com/vayunmathur/library/util/Util.kt+++ b/library/src/main/java/com/vayunmathur/library/util/Util.kt@@ -41,4 +41,7 @@ inline fun <reified T: ComponentActivity> Context.findActivity(): T? { context = context.baseContext } return null-}\ No newline at end of file+}++data class Tuple3<A, B, C>(val first: A, val second: B, val third: C)+data class Tuple4<A, B, C, D>(val first: A, val second: B, val third: C, val fourth: D)\ No newline at end of file
library/src/main/res/drawable/outline_check_24.xml
diff --git a/library/src/main/res/drawable/outline_check_24.xml b/library/src/main/res/drawable/outline_check_24.xmlnew file mode 100644index 0000000000..e2cfef7434--- /dev/null+++ b/library/src/main/res/drawable/outline_check_24.xml@@ -0,0 +1,5 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android" android:height="24dp" android:tint="#000000" android:viewportHeight="960" android:viewportWidth="960" android:width="24dp">+ + <path android:fillColor="@android:color/white" android:pathData="M382,720L154,492L211,435L382,606L749,239L806,296L382,720Z"/>+ +</vector>