diff --git a/app/src/androidTest/assets/fixtures/locations_office.json b/app/src/androidTest/assets/fixtures/locations_office.json new file mode 100644 index 0000000..879f86f --- /dev/null +++ b/app/src/androidTest/assets/fixtures/locations_office.json @@ -0,0 +1 @@ +{"data":[{"id":20,"name":"Kelder","type":"pantry"}]} diff --git a/app/src/androidTest/java/dev/scuttle/inventory/flow/DashboardHouseholdAttributionFlowTest.kt b/app/src/androidTest/java/dev/scuttle/inventory/flow/DashboardHouseholdAttributionFlowTest.kt new file mode 100644 index 0000000..ad48ae9 --- /dev/null +++ b/app/src/androidTest/java/dev/scuttle/inventory/flow/DashboardHouseholdAttributionFlowTest.kt @@ -0,0 +1,81 @@ +@file:OptIn(androidx.compose.ui.test.ExperimentalTestApi::class) + +package dev.scuttle.inventory.flow + +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.filterToOne +import androidx.compose.ui.test.hasClickAction +import androidx.compose.ui.test.hasTestTag +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.waitUntilAtLeastOneExists +import dagger.hilt.android.testing.HiltAndroidTest +import dev.scuttle.inventory.FlowTestBase +import dev.scuttle.inventory.ui.dashboard.DASHBOARD_TITLE_TEST_TAG +import org.junit.Test + +/** + * Issue #33: with two households the dashboard aggregated everything into one flat + * list, so a location gave no clue which household it lived in. It must now name the + * household each location belongs to — and stay quiet when there's only one. + */ +@HiltAndroidTest +class DashboardHouseholdAttributionFlowTest : FlowTestBase() { + private fun signIn() { + composeRule.apply { + onNodeWithText("Email").performTextInput("test@example.com") + onNodeWithText("Password").performTextInput("password123") + onAllNodesWithText("Sign in").filterToOne(hasClickAction()).performClick() + + Thread.sleep(3_000) + waitUntilAtLeastOneExists(hasTestTag(DASHBOARD_TITLE_TEST_TAG), timeoutMillis = 5_000) + } + } + + @Test + fun two_households_each_head_their_own_locations() { + mockServer.enqueue(fixture("auth_login.json")) + mockServer.route("/households", fixture("households_two.json")) + mockServer.route("/households/1/locations", fixture("locations_one.json")) + mockServer.route("/households/1/locations/10/shelves", fixture("shelves_empty.json")) + mockServer.route("/households/2/locations", fixture("locations_office.json")) + mockServer.route("/households/2/locations/20/shelves", fixture("shelves_empty.json")) + + signIn() + + composeRule.apply { + waitUntilAtLeastOneExists(hasText("Fridge"), timeoutMillis = 8_000) + + // Both households are named, and each one's location is on screen. Without + // the headers "Fridge" and "Kelder" were indistinguishable neighbours. + onNodeWithText("Home").assertIsDisplayed() + onNodeWithText("Office").assertIsDisplayed() + onNodeWithText("Fridge").assertIsDisplayed() + onNodeWithText("Kelder").assertIsDisplayed() + + // The stat cards sum both households, and now say so. + onNodeWithText("across 2 households").assertIsDisplayed() + } + } + + @Test + fun a_single_household_is_not_labelled() { + mockServer.enqueue(fixture("auth_login.json")) + mockServer.route("/households", fixture("households_one.json")) + mockServer.route("/households/1/locations", fixture("locations_one.json")) + mockServer.route("/households/1/locations/10/shelves", fixture("shelves_empty.json")) + + signIn() + + composeRule.apply { + waitUntilAtLeastOneExists(hasText("Fridge"), timeoutMillis = 8_000) + + // Nothing to disambiguate: no household header, no "across N" caption. + onNodeWithText("Home").assertDoesNotExist() + onNodeWithText("across 1 households").assertDoesNotExist() + } + } +} diff --git a/app/src/main/java/dev/scuttle/inventory/ui/dashboard/DashboardLocationChart.kt b/app/src/main/java/dev/scuttle/inventory/ui/dashboard/DashboardLocationChart.kt new file mode 100644 index 0000000..0efa8dd --- /dev/null +++ b/app/src/main/java/dev/scuttle/inventory/ui/dashboard/DashboardLocationChart.kt @@ -0,0 +1,174 @@ +package dev.scuttle.inventory.ui.dashboard + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import dev.scuttle.inventory.data.LocationStats +import dev.scuttle.inventory.ui.theme.FrostCard +import dev.scuttle.inventory.ui.theme.HouseholdAvatar +import dev.scuttle.inventory.ui.theme.householdBarAccent + +/** + * "Products by location", grouped into one card per household (#33). + * + * With a single household this collapses to exactly what it was before: one card, + * no header, bars in the theme accent. + */ +@Composable +fun DashboardLocationChart( + groups: List, + maxProductCount: Int, + showHouseholdHeaders: Boolean, + onOpenLocation: (householdId: Long, locationId: Long) -> Unit, + modifier: Modifier = Modifier, +) { + Column( + modifier = modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + groups.forEach { group -> + val barColor = householdBarAccent(group.household.id, group.household.color) + FrostCard(modifier = Modifier.fillMaxWidth()) { + Column( + modifier = Modifier.padding(16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + if (showHouseholdHeaders) { + HouseholdHeader(group, barColor) + } + group.stats.forEach { stat -> + LocationBar( + stat = stat, + maxProductCount = maxProductCount, + barColor = if (showHouseholdHeaders) barColor else MaterialTheme.colorScheme.primary, + onClick = { onOpenLocation(stat.householdId, stat.location.id) }, + ) + } + } + } + } + } +} + +/** + * The household's avatar and name. The name is what actually identifies the group — + * the accent only reinforces it, so the card still reads for a colour-blind user. + */ +@Composable +private fun HouseholdHeader( + group: HouseholdLocationGroup, + accent: Color, +) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + HouseholdAvatar( + householdId = group.household.id, + colorKey = group.household.color, + iconKey = group.household.icon, + size = 28.dp, + ) + Text( + group.household.name, + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + Box( + modifier = + Modifier + .width(28.dp) + .height(4.dp) + .background(accent, MaterialTheme.shapes.extraSmall), + ) + } +} + +@Composable +private fun LocationBar( + stat: LocationStats, + maxProductCount: Int, + barColor: Color, + onClick: () -> Unit, +) { + Column( + verticalArrangement = Arrangement.spacedBy(4.dp), + modifier = + Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .padding(vertical = 2.dp), + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + stat.location.name, + style = MaterialTheme.typography.bodySmall, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + Icon( + Icons.AutoMirrored.Filled.KeyboardArrowRight, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(16.dp), + ) + } + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Box( + modifier = + Modifier + .weight(1f) + .height(12.dp) + .background(MaterialTheme.colorScheme.surfaceVariant, MaterialTheme.shapes.extraSmall), + ) { + // Scaled against the global max, so bars stay comparable across households. + val fraction = + if (maxProductCount > 0) stat.productCount.toFloat() / maxProductCount else 0f + Box( + modifier = + Modifier + .fillMaxWidth(fraction.coerceIn(0f, 1f)) + .height(12.dp) + .background(barColor, MaterialTheme.shapes.extraSmall), + ) + } + Text( + stat.productCount.toString(), + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.width(24.dp), + ) + } + } +} diff --git a/app/src/main/java/dev/scuttle/inventory/ui/dashboard/DashboardScreen.kt b/app/src/main/java/dev/scuttle/inventory/ui/dashboard/DashboardScreen.kt index 43cdad1..fb9f45b 100644 --- a/app/src/main/java/dev/scuttle/inventory/ui/dashboard/DashboardScreen.kt +++ b/app/src/main/java/dev/scuttle/inventory/ui/dashboard/DashboardScreen.kt @@ -1,9 +1,7 @@ package dev.scuttle.inventory.ui.dashboard -import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer @@ -15,11 +13,9 @@ import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBars -import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.Star @@ -52,6 +48,7 @@ import dev.scuttle.inventory.R import dev.scuttle.inventory.data.LowStockItem import dev.scuttle.inventory.ui.common.LiveStatusText import dev.scuttle.inventory.ui.theme.FrostCard +import dev.scuttle.inventory.ui.theme.HouseholdAvatar /** * Distinct from the plain text "Dashboard", which also appears as the bottom-nav @@ -73,7 +70,12 @@ fun DashboardScreen( viewModel: DashboardViewModel = hiltViewModel(), ) { val state by viewModel.state.collectAsState() - val primaryColor = MaterialTheme.colorScheme.primary + + // The household a row belongs to, or null when there's only one household and + // saying so would just be noise (#33). + val badgeFor: (Long) -> DashboardHousehold? = { householdId -> + if (state.showHouseholdAttribution) state.householdFor(householdId) else null + } if (state.hasNoHouseholds && !state.loading) { AlertDialog( @@ -132,29 +134,43 @@ fun DashboardScreen( ) { state.error?.let { LiveStatusText(it) } - // Stat cards - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - StatCard( - label = stringResource(R.string.dashboard_stat_locations), - value = state.totalLocations.toString(), - modifier = Modifier.weight(1f), - onClick = onOpenAllStorage, - ) - StatCard( - label = stringResource(R.string.dashboard_stat_shelves), - value = state.totalShelves.toString(), - modifier = Modifier.weight(1f), - onClick = onOpenAllStorage, - ) - StatCard( - label = stringResource(R.string.dashboard_stat_products), - value = state.totalProducts.toString(), - modifier = Modifier.weight(1f), - onClick = { state.firstHouseholdId?.let(onOpenSearch) }, - ) + // Stat cards. The caption belongs to the row, so they're grouped in + // their own Column rather than taking the page's 16dp rhythm. + Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + StatCard( + label = stringResource(R.string.dashboard_stat_locations), + value = state.totalLocations.toString(), + modifier = Modifier.weight(1f), + onClick = onOpenAllStorage, + ) + StatCard( + label = stringResource(R.string.dashboard_stat_shelves), + value = state.totalShelves.toString(), + modifier = Modifier.weight(1f), + onClick = onOpenAllStorage, + ) + StatCard( + label = stringResource(R.string.dashboard_stat_products), + value = state.totalProducts.toString(), + modifier = Modifier.weight(1f), + onClick = { state.firstHouseholdId?.let(onOpenSearch) }, + ) + } + + // These numbers sum every household; say so rather than let them + // read as one household's (#33). + if (state.showHouseholdAttribution) { + Text( + stringResource(R.string.dashboard_across_households, state.households.size), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.align(Alignment.CenterHorizontally), + ) + } } if (state.mandatoryWarnings > 0) { @@ -165,82 +181,25 @@ fun DashboardScreen( // excluded — they're already in the red card above). if (state.lowStockItems.isNotEmpty()) { Text(stringResource(R.string.dashboard_running_low), style = MaterialTheme.typography.titleMedium) - RunningLowCard(state.lowStockItems, onOpenLocation = onOpenLocation) + RunningLowCard( + items = state.lowStockItems, + badgeFor = badgeFor, + onOpenLocation = onOpenLocation, + ) } - // Bar chart + // Bar chart, grouped per household when there's more than one (#33) if (state.locationStats.isNotEmpty()) { Text( stringResource(R.string.dashboard_products_by_location), style = MaterialTheme.typography.titleMedium, ) - FrostCard(modifier = Modifier.fillMaxWidth()) { - Column( - modifier = Modifier.padding(16.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - val maxVal = state.locationStats.maxOfOrNull { it.productCount } ?: 1 - state.locationStats.forEach { stat -> - Column( - verticalArrangement = Arrangement.spacedBy(4.dp), - modifier = - Modifier - .fillMaxWidth() - .clickable { onOpenLocation(stat.householdId, stat.location.id) } - .padding(vertical = 2.dp), - ) { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - stat.location.name, - style = MaterialTheme.typography.bodySmall, - maxLines = 1, - overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), - ) - Icon( - Icons.AutoMirrored.Filled.KeyboardArrowRight, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(16.dp), - ) - } - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - Box( - modifier = - Modifier - .weight(1f) - .height(12.dp) - .background( - MaterialTheme.colorScheme.surfaceVariant, - MaterialTheme.shapes.extraSmall, - ), - ) { - val fraction = if (maxVal > 0) stat.productCount.toFloat() / maxVal else 0f - Box( - modifier = - Modifier - .fillMaxWidth(fraction.coerceIn(0f, 1f)) - .height(12.dp) - .background(primaryColor, MaterialTheme.shapes.extraSmall), - ) - } - Text( - stat.productCount.toString(), - style = MaterialTheme.typography.bodySmall, - modifier = Modifier.width(24.dp), - ) - } - } - } - } - } + DashboardLocationChart( + groups = state.groupedLocationStats, + maxProductCount = state.maxLocationProductCount, + showHouseholdHeaders = state.showHouseholdAttribution, + onOpenLocation = onOpenLocation, + ) } // Favorite locations @@ -252,26 +211,11 @@ fun DashboardScreen( state.locationStats .filter { it.location.id in state.favoriteLocationIds } .forEach { stat -> - FrostCard( + FavoriteRow( + name = stat.location.name, + household = badgeFor(stat.householdId), onClick = { onOpenLocation(stat.householdId, stat.location.id) }, - modifier = Modifier.fillMaxWidth(), - ) { - Row( - modifier = - Modifier - .padding(16.dp) - .fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically, - ) { - Text(stat.location.name, style = MaterialTheme.typography.bodyLarge) - Icon( - Icons.Default.Star, - contentDescription = null, - tint = MaterialTheme.colorScheme.primary, - ) - } - } + ) } } @@ -282,26 +226,11 @@ fun DashboardScreen( style = MaterialTheme.typography.titleMedium, ) state.favoriteShelves.forEach { entry -> - FrostCard( + FavoriteRow( + name = entry.shelf.name, + household = badgeFor(entry.householdId), onClick = { onOpenLocation(entry.householdId, entry.shelf.location_id) }, - modifier = Modifier.fillMaxWidth(), - ) { - Row( - modifier = - Modifier - .padding(16.dp) - .fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically, - ) { - Text(entry.shelf.name, style = MaterialTheme.typography.bodyLarge) - Icon( - Icons.Default.Star, - contentDescription = null, - tint = MaterialTheme.colorScheme.primary, - ) - } - } + ) } } @@ -329,9 +258,59 @@ private fun StatCard( } } +/** + * The household badge for a row, sized for a list item. Carries the household name + * as its content description — on these flat lists the avatar is the only thing + * saying which household the row belongs to, so it must not be silent to TalkBack. + */ +@Composable +private fun HouseholdBadge(household: DashboardHousehold) { + HouseholdAvatar( + householdId = household.id, + colorKey = household.color, + iconKey = household.icon, + size = 24.dp, + contentDescription = household.name, + ) +} + +/** A favorited location or shelf. [household] is null when there's nothing to disambiguate. */ +@Composable +private fun FavoriteRow( + name: String, + household: DashboardHousehold?, + onClick: () -> Unit, +) { + FrostCard(onClick = onClick, modifier = Modifier.fillMaxWidth()) { + Row( + modifier = + Modifier + .padding(16.dp) + .fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + household?.let { HouseholdBadge(it) } + Text( + name, + style = MaterialTheme.typography.bodyLarge, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + Icon( + Icons.Default.Star, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + ) + } + } +} + @Composable private fun RunningLowCard( items: List, + badgeFor: (Long) -> DashboardHousehold?, onOpenLocation: (householdId: Long, locationId: Long) -> Unit, ) { FrostCard(modifier = Modifier.fillMaxWidth()) { @@ -346,8 +325,9 @@ private fun RunningLowCard( .fillMaxWidth() .clickable { onOpenLocation(item.householdId, item.locationId) }, verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween, + horizontalArrangement = Arrangement.spacedBy(12.dp), ) { + badgeFor(item.householdId)?.let { HouseholdBadge(it) } Column(modifier = Modifier.weight(1f)) { Text( item.productName, diff --git a/app/src/main/java/dev/scuttle/inventory/ui/dashboard/DashboardViewModel.kt b/app/src/main/java/dev/scuttle/inventory/ui/dashboard/DashboardViewModel.kt index a9ce132..caedaa3 100644 --- a/app/src/main/java/dev/scuttle/inventory/ui/dashboard/DashboardViewModel.kt +++ b/app/src/main/java/dev/scuttle/inventory/ui/dashboard/DashboardViewModel.kt @@ -16,11 +16,26 @@ import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import javax.inject.Inject +/** Identity of a household, as the dashboard needs it: enough to name and theme it. */ +data class DashboardHousehold( + val id: Long, + val name: String, + val color: String?, + val icon: String?, +) + +/** A household and the locations belonging to it, for the grouped chart. */ +data class HouseholdLocationGroup( + val household: DashboardHousehold, + val stats: List, +) + data class DashboardUiState( val loading: Boolean = false, val refreshing: Boolean = false, val hasNoHouseholds: Boolean = false, val firstHouseholdId: Long? = null, + val households: List = emptyList(), val totalLocations: Int = 0, val totalShelves: Int = 0, val totalProducts: Int = 0, @@ -31,7 +46,32 @@ data class DashboardUiState( val favoriteShelfIds: Set = emptySet(), val favoriteShelves: List = emptyList(), val error: String? = null, -) +) { + /** + * The dashboard is the one screen that aggregates across households (#33), so it + * is the one screen that has to say which household a row belongs to. With a + * single household there is nothing to disambiguate — stay silent rather than + * decorate every row with the same badge. + */ + val showHouseholdAttribution: Boolean get() = households.size > 1 + + /** Locations grouped under their household, in the order the store lists them. */ + val groupedLocationStats: List get() = + households.mapNotNull { household -> + locationStats + .filter { it.householdId == household.id } + .takeIf { it.isNotEmpty() } + ?.let { HouseholdLocationGroup(household, it) } + } + + /** + * Bar scale for the chart, taken across **all** households. Scaling each group to + * its own max would draw a 2-product household's bar as full as a 9-product one's. + */ + val maxLocationProductCount: Int get() = locationStats.maxOfOrNull { it.productCount } ?: 0 + + fun householdFor(id: Long): DashboardHousehold? = households.firstOrNull { it.id == id } +} @HiltViewModel class DashboardViewModel @@ -52,6 +92,10 @@ class DashboardViewModel refreshing = s.refreshing, hasNoHouseholds = s.entries.isEmpty() && !s.loading, firstHouseholdId = s.entries.firstOrNull()?.id, + households = + s.entries.map { + DashboardHousehold(id = it.id, name = it.name, color = it.color, icon = it.icon) + }, totalLocations = s.locationStats.size, totalShelves = s.totalShelves, totalProducts = s.totalProducts, diff --git a/app/src/main/java/dev/scuttle/inventory/ui/theme/Color.kt b/app/src/main/java/dev/scuttle/inventory/ui/theme/Color.kt index 13a941b..08a6b8d 100644 --- a/app/src/main/java/dev/scuttle/inventory/ui/theme/Color.kt +++ b/app/src/main/java/dev/scuttle/inventory/ui/theme/Color.kt @@ -10,7 +10,7 @@ val FrostOnAccent = Color(0xFF06283B) val FrostDarkBackground = Color(0xFF0C1822) val FrostDarkSurface = Color(0xFF10212E) -val FrostDarkSurfaceVariant = Color(0xFF182C3A) +val FrostDarkSurfaceVariant = Color(FROST_DARK_SURFACE_VARIANT_ARGB) val FrostDarkOnSurface = Color(0xFFEAF6FF) val FrostDarkOnSurfaceVariant = Color(0xFFB0CCE0) @@ -19,6 +19,9 @@ val FrostLightPrimary = Color(0xFF2298BA) // medium teal-blue, ~4.5:1 on white val FrostLightOnPrimary = Color(0xFFFFFFFF) val FrostLightBackground = Color(0xFFC2D5E3) // muted steel-blue (matches ref bg) val FrostLightSurface = Color(0xFFF5FAFD) // near-white card surface -val FrostLightSurfaceVariant = Color(0xFFDCECF6) // slightly tinted for chart bg / chips + +// Built from the ARGB constants in HouseholdPalette.kt (not a duplicate literal) so the +// household-accent contrast test measures against the track the bars actually sit on. +val FrostLightSurfaceVariant = Color(FROST_LIGHT_SURFACE_VARIANT_ARGB) // chart bg / chips val FrostLightOnSurface = Color(0xFF0D2436) val FrostLightOnSurfaceVariant = Color(0xFF3D5A6E) diff --git a/app/src/main/java/dev/scuttle/inventory/ui/theme/HouseholdPalette.kt b/app/src/main/java/dev/scuttle/inventory/ui/theme/HouseholdPalette.kt new file mode 100644 index 0000000..d9d6634 --- /dev/null +++ b/app/src/main/java/dev/scuttle/inventory/ui/theme/HouseholdPalette.kt @@ -0,0 +1,53 @@ +package dev.scuttle.inventory.ui.theme + +/** + * Raw household accent data, as ARGB longs. Deliberately free of Compose types — + * same reason as HouseholdThemeIndex.kt: unit tests run on a plain JVM with no + * Compose on the classpath, and the contrast of these hues is exactly the thing + * worth testing (see HouseholdPaletteTest). HouseholdTheme.kt lifts them to `Color`. + * + * Two palettes, because the accents serve two roles with different contrast needs: + * + * - **Avatar wash** — the accent at 28% alpha under an `onSurface`-tinted icon. + * The icon carries the contrast, so the pastels work on either theme. + * - **Bar fill** (dashboard chart) — a solid graphical object, so WCAG 2.1 SC + * 1.4.11 wants >= 3:1 against the `surfaceVariant` track. The pastels are tuned + * for dark navy and wash out on the light track (amber #FCD34D on #DCECF6 is + * ~1.5:1), so the light theme uses a darker tone of each hue. + * + * This mirrors what Frost already does for its own accent: FrostAccent #7DD3FC on + * dark becomes FrostLightPrimary #2298BA on light. + * + * Key order doubles as the id-derived fallback palette (HouseholdThemeIndex) and is + * shared with the server's HouseholdColor enum — **don't reorder, and keep the two + * maps keyed identically.** + */ +internal val householdAccentDarkArgb = + linkedMapOf( + "sky" to 0xFF7DD3FC, // Frost accent + "teal" to 0xFF5EEAD4, + "indigo" to 0xFFA5B4FC, + "pink" to 0xFFF9A8D4, + "amber" to 0xFFFCD34D, + "green" to 0xFF86EFAC, + "violet" to 0xFFC4B5FD, + "orange" to 0xFFFDBA74, + ) + +/** The same hues, darkened for the light theme so a solid bar stays readable. */ +internal val householdAccentLightArgb = + linkedMapOf( + "sky" to 0xFF0284C7, + "teal" to 0xFF0D9488, + "indigo" to 0xFF4F46E5, + "pink" to 0xFFDB2777, + "amber" to 0xFFB45309, + "green" to 0xFF15803D, + "violet" to 0xFF7C3AED, + "orange" to 0xFFC2410C, + ) + +// The chart track the bars sit on. Color.kt builds its surfaceVariant tokens from +// these, so the contrast test and the theme can't drift apart. +internal const val FROST_LIGHT_SURFACE_VARIANT_ARGB = 0xFFDCECF6 +internal const val FROST_DARK_SURFACE_VARIANT_ARGB = 0xFF182C3A diff --git a/app/src/main/java/dev/scuttle/inventory/ui/theme/HouseholdTheme.kt b/app/src/main/java/dev/scuttle/inventory/ui/theme/HouseholdTheme.kt index c712281..e7fe829 100644 --- a/app/src/main/java/dev/scuttle/inventory/ui/theme/HouseholdTheme.kt +++ b/app/src/main/java/dev/scuttle/inventory/ui/theme/HouseholdTheme.kt @@ -43,18 +43,14 @@ data class HouseholdTheme( * Keyed palette shared with the server (HouseholdColor/HouseholdIcon enums in * inventory-laravel): the API stores KEYS, each client renders them. Order * doubles as the derived-fallback palette, so don't reorder. + * + * These are the pastels used for the avatar wash. For a solid fill (the dashboard + * bars) use [householdBarAccent] instead — see HouseholdPalette.kt for why. */ -val householdAccentsByKey = - linkedMapOf( - "sky" to Color(0xFF7DD3FC), // Frost accent - "teal" to Color(0xFF5EEAD4), - "indigo" to Color(0xFFA5B4FC), - "pink" to Color(0xFFF9A8D4), - "amber" to Color(0xFFFCD34D), - "green" to Color(0xFF86EFAC), - "violet" to Color(0xFFC4B5FD), - "orange" to Color(0xFFFDBA74), - ) +val householdAccentsByKey = householdAccentDarkArgb.mapValuesTo(linkedMapOf()) { Color(it.value) } + +/** Light-theme counterparts, dark enough to survive as a solid bar. */ +private val householdAccentsLightByKey = householdAccentLightArgb.mapValuesTo(linkedMapOf()) { Color(it.value) } val householdIconsByKey = linkedMapOf( @@ -86,10 +82,29 @@ fun householdTheme( icon = householdIconsByKey[iconKey] ?: householdIcons[householdIconIndex(id)], ) +/** + * The household's accent as a **solid fill** (dashboard bars), picked for the + * active theme so it keeps >= 3:1 against the surfaceVariant track it sits on. + * The pastel in [HouseholdTheme.accent] is for the translucent avatar wash and is + * not readable as a light-theme bar — see HouseholdPalette.kt. + */ +@Composable +fun householdBarAccent( + id: Long, + colorKey: String? = null, +): Color { + val palette = if (LocalFrostIsDark.current) householdAccentsByKey else householdAccentsLightByKey + return palette[colorKey] ?: palette.values.toList()[householdAccentIndex(id)] +} + /** * Round, accent-tinted badge with the household's icon. The hue distinguishes * households; the icon is tinted with `onSurface` so it stays legible on the * translucent wash in either theme. + * + * Pass [contentDescription] (the household name) wherever the avatar is the only + * thing saying which household a row belongs to — on the dashboard it carries + * that meaning, so it must not be silent to TalkBack. */ @Composable fun HouseholdAvatar( @@ -98,6 +113,7 @@ fun HouseholdAvatar( size: Dp = 36.dp, colorKey: String? = null, iconKey: String? = null, + contentDescription: String? = null, ) { val theme = householdTheme(householdId, colorKey, iconKey) Box( @@ -110,7 +126,7 @@ fun HouseholdAvatar( ) { Icon( imageVector = theme.icon, - contentDescription = null, + contentDescription = contentDescription, tint = MaterialTheme.colorScheme.onSurface, modifier = Modifier.size(size * 0.55f), ) diff --git a/app/src/main/java/dev/scuttle/inventory/ui/theme/Theme.kt b/app/src/main/java/dev/scuttle/inventory/ui/theme/Theme.kt index e80ce53..e77f275 100644 --- a/app/src/main/java/dev/scuttle/inventory/ui/theme/Theme.kt +++ b/app/src/main/java/dev/scuttle/inventory/ui/theme/Theme.kt @@ -6,6 +6,7 @@ import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.graphics.Color private val DarkColors = @@ -45,6 +46,14 @@ private val LightFrostCardColors = border = FrostLightPrimary.copy(alpha = 0.18f), ) +/** + * The theme's *resolved* dark flag. `isSystemInDarkTheme()` is not a substitute: + * the app has its own System/Light/Dark setting, so the caller of [InventoryTheme] + * decides, and a composable picking a theme-dependent colour (e.g. + * `householdBarAccent`) has to read the same answer the scheme was built from. + */ +val LocalFrostIsDark = staticCompositionLocalOf { false } + @Composable fun InventoryTheme( darkTheme: Boolean = isSystemInDarkTheme(), @@ -52,6 +61,7 @@ fun InventoryTheme( ) { CompositionLocalProvider( LocalFrostCardColors provides if (darkTheme) DarkFrostCardColors else LightFrostCardColors, + LocalFrostIsDark provides darkTheme, ) { MaterialTheme( colorScheme = if (darkTheme) DarkColors else LightColors, diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index bc1e58f..fe3f3d4 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -27,6 +27,7 @@ Tik om te zien wat aangevuld moet worden Producten per locatie Bijna op + in %d huishoudens Dashboard Opslag Zoeken diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 5d87f06..68f92a0 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -27,6 +27,7 @@ Tap to see what needs restocking Products by location Running low + across %d households Dashboard Storage Search diff --git a/app/src/test/java/dev/scuttle/inventory/DashboardViewModelTest.kt b/app/src/test/java/dev/scuttle/inventory/DashboardViewModelTest.kt index 24be10d..bf6fe36 100644 --- a/app/src/test/java/dev/scuttle/inventory/DashboardViewModelTest.kt +++ b/app/src/test/java/dev/scuttle/inventory/DashboardViewModelTest.kt @@ -281,6 +281,117 @@ class DashboardViewModelTest { assertFalse(100L in vm.state.value.favoriteShelfIds) } + @Test + fun a_single_household_gets_no_attribution_ui() = + runTest { + val vm = viewModel(locationsByHousehold = mapOf(1L to listOf(LocationDto(10, "Fridge", "fridge")))) + + // Issue #33 is a multi-household problem; a one-household user should see + // the dashboard exactly as before — no headers, no badges, no caption. + assertFalse(vm.state.value.showHouseholdAttribution) + assertEquals(1, vm.state.value.households.size) + } + + @Test + fun two_households_are_exposed_with_their_theme_keys() = + runTest { + val vm = + viewModel( + households = + listOf( + HouseholdDto(1, "Home", "AAAA", color = "teal", icon = "home"), + HouseholdDto(2, "Beach house", "BBBB"), + ), + ) + + assertTrue(vm.state.value.showHouseholdAttribution) + val (home, beach) = vm.state.value.households + assertEquals("Home", home.name) + assertEquals("teal", home.color) + assertEquals("home", home.icon) + // Null keys are legal: the client derives a stable default from the id. + assertEquals("Beach house", beach.name) + assertEquals(null, beach.color) + } + + @Test + fun location_stats_are_grouped_per_household_in_store_order() = + runTest { + val vm = + viewModel( + households = + listOf( + HouseholdDto(1, "Home", "AAAA"), + HouseholdDto(2, "Beach house", "BBBB"), + ), + locationsByHousehold = + mapOf( + 1L to listOf(LocationDto(10, "Bijkeuken", "pantry"), LocationDto(11, "Kelder", "cellar")), + 2L to listOf(LocationDto(20, "Freezer Downstairs", "freezer")), + ), + ) + + val groups = vm.state.value.groupedLocationStats + + assertEquals(2, groups.size) + assertEquals("Home", groups[0].household.name) + assertEquals(listOf("Bijkeuken", "Kelder"), groups[0].stats.map { it.location.name }) + assertEquals("Beach house", groups[1].household.name) + assertEquals(listOf("Freezer Downstairs"), groups[1].stats.map { it.location.name }) + } + + @Test + fun a_household_with_no_locations_gets_no_group() = + runTest { + val vm = + viewModel( + households = + listOf( + HouseholdDto(1, "Home", "AAAA"), + HouseholdDto(2, "Empty", "BBBB"), + ), + locationsByHousehold = mapOf(1L to listOf(LocationDto(10, "Bijkeuken", "pantry"))), + ) + + assertEquals( + listOf("Home"), + vm.state.value.groupedLocationStats + .map { it.household.name }, + ) + } + + @Test + fun the_bar_scale_is_global_so_households_stay_comparable() = + runTest { + val vm = + viewModel( + households = + listOf( + HouseholdDto(1, "Home", "AAAA"), + HouseholdDto(2, "Beach house", "BBBB"), + ), + locationsByHousehold = + mapOf( + 1L to listOf(LocationDto(10, "Bijkeuken", "pantry")), + 2L to listOf(LocationDto(20, "Freezer", "freezer")), + ), + shelvesByLocation = + mapOf( + 10L to listOf(ShelfDto(100, "Top", 0, 10)), + 20L to listOf(ShelfDto(200, "Top", 0, 20)), + ), + productsByShelf = + mapOf( + 100L to (1..9).map { ProductDto(it.toLong(), "P$it", 1, 100) }, + 200L to listOf(ProductDto(50, "Peas", 1, 200), ProductDto(51, "Fish", 1, 200)), + ), + ) + + // Scaled per-card, Beach house's 2 products would fill its bar as completely + // as Home's 9 fill theirs, and the chart would lie about the comparison. + assertEquals(9, vm.state.value.maxLocationProductCount) + } + @Test fun favorite_shelves_list_reflects_favorited_ids() = runTest { diff --git a/app/src/test/java/dev/scuttle/inventory/HouseholdPaletteTest.kt b/app/src/test/java/dev/scuttle/inventory/HouseholdPaletteTest.kt new file mode 100644 index 0000000..e0938c3 --- /dev/null +++ b/app/src/test/java/dev/scuttle/inventory/HouseholdPaletteTest.kt @@ -0,0 +1,102 @@ +package dev.scuttle.inventory + +import dev.scuttle.inventory.ui.theme.FROST_DARK_SURFACE_VARIANT_ARGB +import dev.scuttle.inventory.ui.theme.FROST_LIGHT_SURFACE_VARIANT_ARGB +import dev.scuttle.inventory.ui.theme.HOUSEHOLD_ACCENT_COUNT +import dev.scuttle.inventory.ui.theme.householdAccentDarkArgb +import dev.scuttle.inventory.ui.theme.householdAccentLightArgb +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The household accents are used two ways, and only one of them is a contrast + * problem: + * + * - behind an avatar, as a 28%-alpha wash under an `onSurface` icon — the icon + * carries the contrast, so any hue works; + * - as a **solid bar fill** on the dashboard chart, which is a graphical object + * and needs >= 3:1 against the `surfaceVariant` track it sits on (WCAG 2.1 + * non-text contrast). + * + * The dark palette is a set of pastels chosen to sit on dark navy; on the light + * theme those same pastels wash out (amber #FCD34D on the #DCECF6 track is ~1.5:1). + * Hence the parallel light palette. These tests pin that down so a hue added or + * retuned later can't silently ship an unreadable bar. + * + * Compose-free on purpose: unit tests have no Compose on the classpath, so the + * palette is stored as ARGB longs and lifted to `Color` in HouseholdTheme.kt. + */ +class HouseholdPaletteTest { + /** WCAG 2.1 relative luminance. */ + private fun luminance(argb: Long): Double { + fun channel(c: Long): Double { + val s = c / 255.0 + return if (s <= 0.03928) s / 12.92 else Math.pow((s + 0.055) / 1.055, 2.4) + } + + val r = channel((argb shr 16) and 0xFF) + val g = channel((argb shr 8) and 0xFF) + val b = channel(argb and 0xFF) + return 0.2126 * r + 0.7152 * g + 0.0722 * b + } + + private fun contrast( + a: Long, + b: Long, + ): Double { + val (hi, lo) = listOf(luminance(a), luminance(b)).sorted().reversed() + return (hi + 0.05) / (lo + 0.05) + } + + /** WCAG 2.1 SC 1.4.11 — non-text (graphical) contrast. */ + private val minGraphicalContrast = 3.0 + + @Test + fun light_and_dark_palettes_describe_the_same_households() { + assertEquals(householdAccentDarkArgb.keys, householdAccentLightArgb.keys) + assertEquals(HOUSEHOLD_ACCENT_COUNT, householdAccentDarkArgb.size) + assertEquals(HOUSEHOLD_ACCENT_COUNT, householdAccentLightArgb.size) + } + + @Test + fun every_light_accent_is_readable_as_a_bar_on_the_light_track() { + householdAccentLightArgb.forEach { (key, argb) -> + val ratio = contrast(argb, FROST_LIGHT_SURFACE_VARIANT_ARGB) + assertTrue( + "light accent '$key' is ${"%.2f".format(ratio)}:1 on the light track, " + + "needs >= $minGraphicalContrast:1", + ratio >= minGraphicalContrast, + ) + } + } + + @Test + fun every_dark_accent_is_readable_as_a_bar_on_the_dark_track() { + householdAccentDarkArgb.forEach { (key, argb) -> + val ratio = contrast(argb, FROST_DARK_SURFACE_VARIANT_ARGB) + assertTrue( + "dark accent '$key' is ${"%.2f".format(ratio)}:1 on the dark track, " + + "needs >= $minGraphicalContrast:1", + ratio >= minGraphicalContrast, + ) + } + } + + /** + * The pastels are kept for the avatar wash but must NOT be used as light-theme + * bars. If someone "simplifies" the two palettes back into one, this fails. + */ + @Test + fun the_dark_pastels_would_fail_as_light_theme_bars() { + val washedOut = + householdAccentDarkArgb.count { (_, argb) -> + contrast(argb, FROST_LIGHT_SURFACE_VARIANT_ARGB) < minGraphicalContrast + } + assertTrue( + "expected the dark pastels to be unusable as light bars (that's why the " + + "light palette exists), but $washedOut of ${householdAccentDarkArgb.size} failed", + washedOut >= householdAccentDarkArgb.size / 2, + ) + } +} diff --git a/docs/design/dashboard-household-grouping.png b/docs/design/dashboard-household-grouping.png new file mode 100644 index 0000000..ba98cbd Binary files /dev/null and b/docs/design/dashboard-household-grouping.png differ diff --git a/docs/superpowers/specs/2026-07-12-dashboard-household-differentiation-design.md b/docs/superpowers/specs/2026-07-12-dashboard-household-differentiation-design.md new file mode 100644 index 0000000..3261580 --- /dev/null +++ b/docs/superpowers/specs/2026-07-12-dashboard-household-differentiation-design.md @@ -0,0 +1,122 @@ +# Dashboard household differentiation — design + +**Issue:** [#33](https://github.com/spdotdev/inventory-android/issues/33) — "Two households, two different colours on Dashboard to differentiate?" +**Date:** 2026-07-12 +**Status:** approved + +## Problem + +The Dashboard is the only screen that aggregates *across* households, and it drops the +attribution while doing so. On a two-household account the tester sees: + +- **Stat cards** (`4 Locations / 14 Shelves / 11 Products`) that silently sum both households. +- **Products by location** — `Freezer Downstairs`, `Freezer upstares`, `Bijkeuken`, `Kelder` in + one flat list. Two households each with a "Freezer" are indistinguishable. +- **Running low** and **Favorites** — same flat treatment. + +The issue title asks for "two different colours". Colour alone is the fix for *telling two rows +apart*; it is not a fix for *knowing which household a row belongs to* — for that the household +has to be named. So the design groups and names first, and uses colour to reinforce. + +## What already exists (and is not being rebuilt) + +`ui/theme/HouseholdTheme.kt` already provides a per-household accent + icon: + +- 8 accents and 8 icons, keyed (`sky`, `teal`, … / `home`, `kitchen`, …), user-choosable via + `HouseholdThemeDialog`, persisted server-side as keys, with a stable id-derived fallback. +- `HouseholdAvatar` — a round accent-tinted badge with the household's icon, already used by + `HouseholdsScreen`. + +The data layer already carries what the Dashboard needs: `HouseholdWithLocations` has +`name`/`color`/`icon`, and `LocationStats`, `LowStockItem` and `ShelfEntry` each carry a +`householdId`. **No API, DTO, or repository change is required.** This is a presentation fix. + +## Design + +### 1. Gate everything on more than one household + +`DashboardUiState` gains `households: List` (`id`, `name`, `color`, `icon`), +mapped from `store.state.entries`, and a derived `showHouseholdAttribution = households.size > 1`. + +When the user has a single household, the Dashboard renders exactly as it does today — no +headers, no badges, no caption. Most testers have one household and should not pay for a +two-household problem. + +### 2. Group "Products by location" by household + +One `FrostCard` per household (in `entries` order) instead of a single flat card. Each card +leads with a header row: `HouseholdAvatar` (24dp) + household name (`titleSmall`, medium +weight). Households with no locations get no card. + +**The bar scale stays global.** `maxVal` is computed across *all* `locationStats`, not per card. +A per-card max would scale each household independently, so a household whose best location +holds 2 products would render a full-width bar next to another household's full-width bar +holding 9 — the chart would misrepresent the data it exists to show. + +### 3. Badge the flat lists + +Running-low rows and favorite location/shelf rows get a leading `HouseholdAvatar` (20dp). +`HouseholdAvatar` currently hardcodes `contentDescription = null`; it gains an optional +`contentDescription` parameter so these rows announce their household to TalkBack. + +### 4. Stat cards stay aggregate, but say so + +The numbers are unchanged. A caption below the row — "across 2 households" — is shown only when +`showHouseholdAttribution`. The sum stops being a silent one. + +### 5. Colour: bars need a light-theme variant + +The accent palette is a set of Tailwind-300 pastels (`#7DD3FC`, `#FCD34D`, …). Two different +uses with two different contrast requirements: + +- **Avatar wash** — the accent at `alpha = 0.28` behind an `onSurface`-tinted icon. Legible in + both themes today. **Unchanged.** +- **Bar fill** — a solid graphical object, which needs ≥3:1 against its `surfaceVariant` track. + The pastels fail this on the light theme (amber `#FCD34D` on the light track `#DCECF6` is + nowhere near 3:1). + +Frost already solved exactly this for its own accent: `FrostAccent #7DD3FC` (dark) → +`FrostLightPrimary #2298BA` (light, commented "~4.5:1 on white"). Mirror that pattern with a +parallel light palette — the Tailwind-600 tone of each hue: + +| key | dark (existing) | light (new) | +|--------|-----------|-----------| +| sky | `#7DD3FC` | `#0284C7` | +| teal | `#5EEAD4` | `#0D9488` | +| indigo | `#A5B4FC` | `#4F46E5` | +| pink | `#F9A8D4` | `#DB2777` | +| amber | `#FCD34D` | `#D97706` | +| green | `#86EFAC` | `#16A34A` | +| violet | `#C4B5FD` | `#7C3AED` | +| orange | `#FDBA74` | `#EA580C` | + +Selecting between them needs the app's *resolved* dark flag — `isSystemInDarkTheme()` is wrong +here, because the app has its own System/Light/Dark setting and `InventoryTheme(darkTheme=…)` is +resolved by the caller. Add a `LocalFrostIsDark` CompositionLocal, provided in `InventoryTheme` +alongside the existing `LocalFrostCardColors`. + +Colour is never the sole signal: every grouped card is headed by the household's **name**, and +every badged row carries the household's **icon**. A colour-blind user loses nothing. + +### 6. Split the screen file + +`DashboardScreen.kt` is 410 lines and this change adds to its densest section. Lift the +location chart into `ui/dashboard/DashboardLocationChart.kt` as part of the change. This is +scoped to the code being touched, not a general refactor. + +## Testing + +- **Unit (`DashboardViewModelTest`)** — `entries` map to `households`; `showHouseholdAttribution` + is false for one household and true for two; grouping preserves store order. +- **Unit (palette guard)** — the light and dark accent tables have identical keys and sizes. + `HouseholdThemeIndex` derives fallbacks by `id % HOUSEHOLD_ACCENT_COUNT`, so a table that + drifts out of sync would silently mis-key or crash. Mirrors the existing count guard in + `HouseholdThemeIndexTest`. +- **Instrumented (`DashboardFlowTest`)** — with two households, both names render as headers and + each location appears under its own household; with one household, no header renders. + +## Out of scope + +- Changing the household theme picker, palette contents, or the server contract. +- The `Households` bottom-nav label truncating to "Household s" (visible in the issue + screenshot) — a separate nav-bar bug, tracked separately.