Modern Apps git

← Modern-Apps.git

maps: put the UI on explicit Material 3 Expressive tokens

Commit
e912e05710a5963ba7ed7d0e854d3c8bccf9ff80
Author
vayun-mathur <[email protected]>
When
2026-08-21 16:21 UTC (3 months ago)
Parents
8f12de8

Diff

library/ui/src/main/java/com/vayunmathur/library/ui/DynamicTheme.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/DynamicTheme.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/DynamicTheme.ktindex fa3e41ea9e..59db072870 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/DynamicTheme.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/DynamicTheme.kt@@ -1,19 +1,34 @@+@file:OptIn(androidx.compose.material3.ExperimentalMaterial3ExpressiveApi::class)+ package com.vayunmathur.library.ui  import androidx.compose.foundation.isSystemInDarkTheme-import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.MaterialExpressiveTheme import androidx.compose.material3.Typography import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext +/**+ * The app theme: Material You colour extraction on a Material 3 Expressive foundation.+ *+ * [MaterialExpressiveTheme] rather than `MaterialTheme` because it is what populates+ * `MaterialTheme.shapes` (the full `extraSmall`..`extraExtraLarge` scale, including the+ * `*Increased` roles) and `MaterialTheme.motionScheme`, and what flips the flag components+ * read to pick their Expressive defaults. Without it `MaterialTheme.shapes` carries only the+ * classic five roles, which is why corner radii ended up as call-site literals.+ *+ * Shapes, typography and motion are deliberately not overridden here: Material's own+ * defaults are the token set, so there is nothing for us to restate and nothing to drift+ * from it on a dependency bump.+ */ @Composable fun DynamicTheme(darkTheme: Boolean? = null, content: @Composable () -> Unit) {     val isDark = darkTheme ?: isSystemInDarkTheme()     val colorScheme = if (isDark) dynamicDarkColorScheme(LocalContext.current) else dynamicLightColorScheme(LocalContext.current) -    MaterialTheme(+    MaterialExpressiveTheme(         colorScheme = colorScheme,         typography = Typography(),         content = content
library/ui/src/main/java/com/vayunmathur/library/ui/VerticalShape.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/VerticalShape.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/VerticalShape.ktnew file mode 100644index 0000000000..a816b680ac--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/VerticalShape.kt@@ -0,0 +1,31 @@+package com.vayunmathur.library.ui++import androidx.compose.foundation.shape.CornerSize+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.ReadOnlyComposable+import androidx.compose.ui.unit.dp++/**+ * The shape for one row of a grouped list, so a run of cards reads as a single block.+ *+ * The outer corners of the group are rounded and the inner joins are square, which is how+ * Material 3 Expressive draws grouped lists: the group is the object, and the rows are+ * divisions inside it rather than separate cards that happen to be adjacent.+ *+ * Radius comes from `MaterialTheme.shapes` rather than a literal, so a theme change moves the+ * whole app's list grouping at once. A single-row group ([count] == 1) is rounded on all four+ * corners, which is the same thing said consistently.+ */+@Composable+@ReadOnlyComposable+fun verticalShape(index: Int, count: Int): RoundedCornerShape {+    val outer = MaterialTheme.shapes.medium.topStart+    val inner = CornerSize(0.dp)+    return RoundedCornerShape(+        topStart = if (index == 0) outer else inner,+        topEnd = if (index == 0) outer else inner,+        bottomEnd = if (index == count - 1) outer else inner,+        bottomStart = if (index == count - 1) outer else inner,+    )+}
maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt b/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.ktindex 3a771c5f03..2c1a925cca 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt@@ -20,6 +20,7 @@ import com.vayunmathur.library.ui.PrimaryTabRow import com.vayunmathur.library.ui.Tab import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.verticalShape import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue
maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.ktindex eec9ce8879..005ebf975b 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt@@ -11,6 +11,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable+import androidx.compose.runtime.ReadOnlyComposable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.remember@@ -173,7 +174,7 @@ private fun DepartureRow(dep: Departure, now: Long) {                     stringResource(R.string.transit_cancelled),                     style = MaterialTheme.typography.labelMedium,                     fontWeight = FontWeight.Bold,-                    color = DELAY_LATE,+                    color = MaterialTheme.colorScheme.error,                 )             } else {                 Text(@@ -202,15 +203,19 @@ private fun countdownText(target: Long, now: Long): String {     else stringResource(R.string.transit_minutes, minutes) } -private val DELAY_ON_TIME = Color(0xFF2E7D32)-private val DELAY_SLIGHT = Color(0xFFF9A825)-private val DELAY_LATE = Color(0xFFC62828)--/** On-time/early → green, 1–4 min late → amber, ≥5 late → red. */+/**+ * On-time/early → muted, 1–4 min late → tertiary, ≥5 late → error.+ *+ * Scheme-derived, not fixed: these sit on the sheet's own surface rather than on the tiles,+ * so they are ordinary UI text and should follow the theme. "On time" is deliberately the+ * quiet one — it is the expected case, and colouring it green made every board look alarming.+ */+@Composable+@ReadOnlyComposable private fun delayColor(delayMinutes: Int): Color = when {-    delayMinutes <= 0 -> DELAY_ON_TIME-    delayMinutes < 5 -> DELAY_SLIGHT-    else -> DELAY_LATE+    delayMinutes <= 0 -> MaterialTheme.colorScheme.onSurfaceVariant+    delayMinutes < 5 -> MaterialTheme.colorScheme.tertiary+    else -> MaterialTheme.colorScheme.error }  /** A once-per-15s ticker that reports the current epoch millis to [onTick]. */
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 3d0580abef..503ef27d7d 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -31,6 +31,7 @@ import com.vayunmathur.library.ui.FreeHeightBottomSheetScaffold import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.CardDefaults+import com.vayunmathur.library.ui.verticalShape import com.vayunmathur.library.ui.CompassCalibrationBanner import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.FloatingActionButton@@ -77,6 +78,7 @@ import com.vayunmathur.maps.util.GooglePoiMapViewModel import com.vayunmathur.maps.util.MapSettingsViewModel import com.vayunmathur.maps.util.MapsSearchViewModel import com.vayunmathur.maps.util.PoiIndex+import com.vayunmathur.maps.ui.theme.BasemapPalette import com.vayunmathur.maps.util.SelectedFeatureViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch@@ -555,7 +557,7 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                             ClickResult.Pass                         }                 ) {-                        MyMapLayers(selectedFeature, route?.get(selectedRouteType), json, userPosition, userBearing, navProgress, searchResults, savedPins, parkingSpot, familyMembers, trafficEnabled, satelliteEnabled, safetyEnabled, transitEnabled, poiFilterTypes = selectedCategory?.types)+                        MyMapLayers(selectedFeature, route?.get(selectedRouteType), json, userPosition, userBearing, navProgress, searchResults, savedPins, parkingSpot, familyMembers, trafficEnabled, satelliteEnabled, safetyEnabled, transitEnabled, poiFilterTypes = selectedCategory?.types, darkBasemap = darkMap)                     }                 } @@ -887,8 +889,8 @@ fun patchStyleForHybrid(  */ private fun darkenPaint(id: String, paint: JsonObject?): JsonObject? {     if (paint == null) return null-    val base = darkBaseColor(id)-    val (text, halo) = darkTextColors(id)+    val base = BasemapPalette.darkFillHex(id)+    val (text, halo) = BasemapPalette.darkLabelHex(id)     return buildJsonObject {         paint.forEach { (k, v) ->             when (k) {@@ -900,54 +902,3 @@ private fun darkenPaint(id: String, paint: JsonObject?): JsonObject? {         }     } }--/**- * Dark fill/line/background colour for a base Protomaps layer. Keyed by layer id- * (the style's ids are stable), falling through prefix/substring rules for the- * many road variants. Casing colours must be matched before the highway/major- * rules because e.g. `roads_highway_casing_early` contains both tokens.- */-private fun darkBaseColor(id: String): String = when {-    id == "background" || id == "earth" -> "#1b1d22"-    id == "water" -> "#0d1b2a"-    id == "water_stream" || id == "water_river" -> "#24455f"-    id == "landcover" -> "#1f2a22"-    id == "landuse_park" -> "#1e2b20"-    id == "landuse_urban_green" -> "#23362a"-    id == "landuse_hospital" -> "#2b2528"-    id == "landuse_industrial" -> "#20262b"-    id == "landuse_school" -> "#282520"-    id == "landuse_beach" -> "#2c2a22"-    id == "landuse_zoo" -> "#213030"-    id == "landuse_aerodrome" -> "#212228"-    id == "landuse_runway" -> "#2b2d33"-    id == "landuse_pedestrian" -> "#242229"-    id == "landuse_pier" -> "#202225"-    id.startsWith("landuse") -> "#1f2126"-    id == "buildings" -> "#22262c"-    id.startsWith("boundaries") -> "#4a4f57"-    id == "roads_rail" -> "#3a3e45"-    id.startsWith("roads_runway") || id.startsWith("roads_taxiway") -> "#2b2d33"-    id.contains("casing") -> "#111318"-    id.startsWith("roads_tunnels") -> "#2b2e35"-    id.contains("highway") || id.contains("major") || id.contains("link") -> "#464b54"-    id.startsWith("roads") -> "#34383f"-    else -> "#26282e"-}--/**- * Dark (text-color, text-halo-color) for a label/POI symbol layer: light text on- * a near-black halo so labels stay legible over the dark basemap. Water labels- * keep a blue tint over the dark-navy water.- */-private fun darkTextColors(id: String): Pair<String, String> = when (id) {-    "places_locality" -> "#e4e8ee" to "#101216"-    "places_country" -> "#9aa0aa" to "#101216"-    "places_region" -> "#80868f" to "#101216"-    "places_subplace" -> "#b0b6c0" to "#101216"-    "earth_label_islands" -> "#9aa0aa" to "#101216"-    "water_waterway_label", "water_label_ocean", "water_label_lakes" -> "#6f8fce" to "#0d1b2a"-    "roads_shields" -> "#c8ccd4" to "#101216"-    "roads_labels_major", "roads_labels_minor", "address_label" -> "#b8bdc6" to "#101216"-    else -> "#c9ced6" to "#101216"-}
maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.ktindex 70046c2f3c..e339cec1ba 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt@@ -10,9 +10,13 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.maps.data.Feature1 import com.vayunmathur.maps.data.SpecificFeature import com.vayunmathur.maps.data.google.GoogleTrafficSource+import com.vayunmathur.maps.ui.theme.MapTokens+import com.vayunmathur.maps.ui.theme.mapTokens+import com.vayunmathur.maps.ui.theme.toStyleHex import com.vayunmathur.maps.util.MapTileCache import com.vayunmathur.maps.util.OfflineRouter import com.vayunmathur.maps.util.RouteService@@ -65,8 +69,12 @@ fun MyMapLayers(     safetyEnabled: Boolean = false,     transitEnabled: Boolean = false,     poiFilterTypes: Set<Int>? = null,+    // Which basemap palette is in play. Not derivable from [styleJson]: the recolour has+    // already been baked into it by the time it arrives here.+    darkBasemap: Boolean = false, ) {     val context = LocalContext.current+    val tokens = remember(darkBasemap) { mapTokens(darkBasemap) }      LaunchedEffect(Unit) {         // OfflineRouter.initialize does asset-listing I/O — push to IO. The@@ -140,7 +148,7 @@ fun MyMapLayers(         // stops). Harmless no-op while the layer is absent (until v5 is         // regenerated with it).         if (transitEnabled) {-            TransitLinesLayer(adminSource)+            TransitLinesLayer(adminSource, tokens)         }          // Ambient POI overlay (P29): rendered NATIVELY from the baked `ma_pois`@@ -195,8 +203,11 @@ fun MyMapLayers(             org.maplibre.compose.layers.CircleLayer(                 "user-location-dot",                 src,-                color = const(Color(0xFF0E35F1)),+                color = const(MaterialTheme.colorScheme.primary),                 radius = const(8.dp),+                // The casing ring stays white on purpose. It is what keeps the puck+                // findable when the wallpaper accent happens to land near the basemap's+                // own colours, or over satellite imagery, which has no palette at all.                 strokeColor = const(Color.White),                 strokeWidth = const(2.dp)             )@@ -208,7 +219,7 @@ fun MyMapLayers(                 iconRotate = feature["bearing"].cast(),                 iconRotationAlignment = const(org.maplibre.compose.expressions.value.IconRotationAlignment.Map),                 iconSize = const(0.6f),-                iconColor = const(Color(0xFF0E35F1))+                iconColor = const(MaterialTheme.colorScheme.primary)             )         } @@ -235,7 +246,7 @@ fun MyMapLayers(                         ) {                             if (route is RouteService.Route) {                                 val features: List<Feature1> = buildRouteFeatures(-                                    route, navProgress+                                    route, navProgress, tokens                                 )                                 routeSource.setData(                                     GeoJsonData.Features(FeatureCollection(features))@@ -268,16 +279,16 @@ fun MyMapLayers(  */ @Composable @MaplibreComposable-private fun TransitLinesLayer(source: VectorSource) {+private fun TransitLinesLayer(source: VectorSource, tokens: MapTokens) {     // Fallback palette keyed on `kind` when the feature has no `colour`.     val byKind = switch(         feature["kind"].cast<StringValue>(),-        case("subway", const(Color(0xFF0055A4))),      // metro blue-        case("light_rail", const(Color(0xFF00843D))),  // green-        case("tram", const(Color(0xFFE4002B))),        // red-        case("monorail", const(Color(0xFF6A1B9A))),    // purple-        case("train", const(Color(0xFF455A64))),       // slate-        fallback = const(Color(0xFF616161)),           // rail / unknown grey+        case("subway", const(tokens.transitMode.subway)),+        case("light_rail", const(tokens.transitMode.lightRail)),+        case("tram", const(tokens.transitMode.tram)),+        case("monorail", const(tokens.transitMode.monorail)),+        case("train", const(tokens.transitMode.train)),+        fallback = const(tokens.transitMode.rail),     )     // Prefer the baked `colour` attribute; coalesce falls back to [byKind] when     // it's missing/unparseable.@@ -323,37 +334,35 @@ private fun AdminHighlight(     value: String, ) {     val match = feature[key].cast<StringValue>() eq const(value)+    val highlight = MaterialTheme.colorScheme.secondary     FillLayer(         "admin-highlight-fill",         source,         sourceLayer = sourceLayer,         filter = match,-        color = const(Color.Red.copy(alpha = 0.12f)),+        color = const(highlight.copy(alpha = 0.12f)),     )     LineLayer(         "admin-highlight-outline",         source,         sourceLayer = sourceLayer,         filter = match,-        color = const(Color.Red),+        color = const(highlight),         width = const(3.dp),     ) } -/** Fallback when a transit line reports no colour of its own. */-private const val TRANSIT_FALLBACK = "#FF0000"- /**  * Compute the per-step `route-color` for the static (non-navigating) case.  * Driving uses traffic-aware red/amber/green, transit uses the line's own colour,  * walk/bike fall through to a single blue.  */-private fun staticColorFor(step: RouteService.Step): String {+private fun staticColorFor(step: RouteService.Step, tokens: MapTokens): String {     return when (step.travelMode) {         RouteService.TravelMode.DRIVE -> when {-            step.speedRatio < 0.5 -> "#F44336" // Red-            step.speedRatio < 0.9 -> "#FFC107" // Amber/Yellow-            else -> "#4CAF50"                  // Green+            step.speedRatio < 0.5 -> tokens.traffic.jam.toStyleHex()+            step.speedRatio < 0.9 -> tokens.traffic.slow.toStyleHex()+            else -> tokens.traffic.free.toStyleHex()         }         // The colour the pack (or MOTIS) reported for this route, which is what         // the step-list badge already shows. This used to re-derive the colour@@ -361,14 +370,12 @@ private fun staticColorFor(step: RouteService.Step): String {         // in the APK — so every downloaded pack fell through to the fallback and         // the whole map drew red while the badges were correct.         RouteService.TravelMode.TRANSIT ->-            step.transitDetails?.transitLine?.color?.ifBlank { null } ?: TRANSIT_FALLBACK-        else -> "#1710F1"+            step.transitDetails?.transitLine?.color?.ifBlank { null }+                ?: tokens.routeTransitFallback.toStyleHex()+        else -> tokens.routeInert.toStyleHex()     } } -/** Color shown for the portion of the route the user has already traveled. */-private const val TRAVELED_GRAY = "#9E9E9E"- /**  * Build the GeoJSON `Feature` list for the route polyline.  *@@ -391,12 +398,14 @@ private const val TRAVELED_GRAY = "#9E9E9E" private fun buildRouteFeatures(     route: RouteService.Route,     navProgress: com.vayunmathur.maps.util.NavigationProgress?,+    tokens: MapTokens, ): List<Feature1> {+    val traveledGray = tokens.traffic.traveled.toStyleHex()     if (navProgress == null) {         return route.step.filter { it.polyline.size >= 2 }.map { step ->             Feature1(                 LineString(step.polyline),-                JsonObject(mapOf("route-color" to JsonPrimitive(staticColorFor(step))))+                JsonObject(mapOf("route-color" to JsonPrimitive(staticColorFor(step, tokens))))             )         }     }@@ -419,14 +428,14 @@ private fun buildRouteFeatures(         }         val first = cursor         val last = (first + stepLen - 1).coerceAtMost(route.polyline.size - 1)-        val color = staticColorFor(step)+        val color = staticColorFor(step, tokens)          when {             stepIdx < currentStepIdx -> {                 // Entirely behind: gray.                 out += Feature1(                     LineString(step.polyline),-                    JsonObject(mapOf("route-color" to JsonPrimitive(TRAVELED_GRAY)))+                    JsonObject(mapOf("route-color" to JsonPrimitive(traveledGray)))                 )             }             stepIdx > currentStepIdx -> {@@ -451,7 +460,7 @@ private fun buildRouteFeatures(                 // Snap fell on a later step. Treat the whole step as behind.                 out += Feature1(                     LineString(step.polyline),-                    JsonObject(mapOf("route-color" to JsonPrimitive(TRAVELED_GRAY)))+                    JsonObject(mapOf("route-color" to JsonPrimitive(traveledGray)))                 )             }             else -> {@@ -466,7 +475,7 @@ private fun buildRouteFeatures(                 if (behindVertices.size >= 2) {                     out += Feature1(                         LineString(behindVertices),-                        JsonObject(mapOf("route-color" to JsonPrimitive(TRAVELED_GRAY)))+                        JsonObject(mapOf("route-color" to JsonPrimitive(traveledGray)))                     )                 }                 // Ahead portion: snapped position, then remaining vertices.
maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.ktindex d87c29e2d5..5d95a6eda6 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt@@ -19,6 +19,7 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.CardDefaults+import com.vayunmathur.library.ui.verticalShape import com.vayunmathur.library.ui.IconCall import com.vayunmathur.library.ui.IconDirections import com.vayunmathur.library.ui.IconDirectionsWalk@@ -379,12 +380,6 @@ private fun OsmHours(openingHours: OpeningHours) {     } } -fun verticalShape(index: Int, count: Int): RoundedCornerShape {-    val top = if (index == 0) 12.dp else 0.dp-    val bottom = if (index == count - 1) 12.dp else 0.dp-    return RoundedCornerShape(top, top, bottom, bottom)-}- @Composable fun RestaurantItem(icon: @Composable () -> Unit, text: String, shape: Shape = CardDefaults.shape, onClick: () -> Unit) {     RestaurantItem(icon, AnnotatedString(text), shape, onClick)
maps/src/main/java/com/vayunmathur/maps/ui/SearchResultLayer.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/SearchResultLayer.kt b/maps/src/main/java/com/vayunmathur/maps/ui/SearchResultLayer.ktindex ba2a85825d..74445ef1de 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/SearchResultLayer.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/SearchResultLayer.kt@@ -10,6 +10,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.maps.data.Feature1 import com.vayunmathur.maps.data.SpecificFeature import com.vayunmathur.maps.data.string@@ -69,7 +70,7 @@ fun SearchResultLayer(results: List<SearchResult>) {         CircleLayer(             SEARCH_RESULT_DOT_LAYER_ID,             src,-            color = const(Color(0xFFEA4335)),+            color = const(MaterialTheme.colorScheme.primary),             radius = interpolate(                 linear(), zoom(),                 11 to const(5.dp),
maps/src/main/java/com/vayunmathur/maps/ui/nav/SpeedWidget.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/nav/SpeedWidget.kt b/maps/src/main/java/com/vayunmathur/maps/ui/nav/SpeedWidget.ktindex 3486e9147a..09e306a3b2 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/nav/SpeedWidget.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/nav/SpeedWidget.kt@@ -20,6 +20,7 @@ import androidx.compose.ui.unit.sp import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text import com.vayunmathur.maps.data.PostedLimit+import com.vayunmathur.maps.ui.theme.SpeedSign import com.vayunmathur.maps.util.isImperialUnits import kotlin.math.roundToInt @@ -58,7 +59,7 @@ fun SpeedWidget(             Modifier                 .shadow(4.dp, CircleShape)                 .background(-                    if (over) Color(0xFFD32F2F) else MaterialTheme.colorScheme.surface,+                    if (over) SpeedSign.ring else MaterialTheme.colorScheme.surface,                     CircleShape,                 )                 .size(64.dp),@@ -79,13 +80,15 @@ fun SpeedWidget(             }         } -        // Posted-limit sign (only when we have a limit).+        // Posted-limit sign (only when we have a limit). White disc, red ring, near-black+        // numerals in BOTH themes: this is a reproduction of a legal road sign, and there is+        // no dark-mode variant of one. The speed pill beside it does follow the theme.         if (limitValue != null) {             Box(                 Modifier                     .shadow(4.dp, CircleShape)-                    .background(Color.White, CircleShape)-                    .border(4.dp, Color(0xFFD32F2F), CircleShape)+                    .background(SpeedSign.disc, CircleShape)+                    .border(4.dp, SpeedSign.ring, CircleShape)                     .size(56.dp),                 contentAlignment = Alignment.Center,             ) {@@ -93,7 +96,7 @@ fun SpeedWidget(                     limitValue.toString(),                     fontSize = 20.sp,                     fontWeight = FontWeight.Bold,-                    color = Color(0xFF111111),+                    color = SpeedSign.ink,                 )             }         }
maps/src/main/java/com/vayunmathur/maps/ui/theme/BasemapPalette.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/theme/BasemapPalette.kt b/maps/src/main/java/com/vayunmathur/maps/ui/theme/BasemapPalette.ktnew file mode 100644index 0000000000..4c01bfe367--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/theme/BasemapPalette.kt@@ -0,0 +1,170 @@+package com.vayunmathur.maps.ui.theme++import androidx.compose.runtime.Immutable+import androidx.compose.ui.graphics.Color++/**+ * Colours for things drawn on the *tiles* rather than on the app's surfaces.+ *+ * These were hardcoded for a reason, even if an unstated one: `colorScheme.onSurface` is the+ * wrong reference for a road label, because a road label does not sit on a surface — it sits+ * on the basemap, whose colours this file also owns. Deriving them from the wallpaper would+ * let an unlucky accent produce grey-on-grey terrain, and nothing in the scheme expresses+ * "legible against whatever the terrain happens to be".+ *+ * So the basemap gets its own closed palette, contrast-checked against itself. Only the dark+ * palette exists: light mode uses the Protomaps style's own paint verbatim, and the runtime+ * recolour is what dark mode is.+ *+ * Values are `Color`, not hex strings, so they can be contrast-tested. They cross into the+ * style JSON through [toStyleHex] at a single boundary.+ */+object BasemapPalette {++    /** What a basemap layer *is*, independent of what the style happens to call it. */+    enum class Fill {+        Background,+        Water,+        Waterway,+        Landcover,+        Park,+        UrbanGreen,+        Hospital,+        Industrial,+        School,+        Beach,+        Zoo,+        Aerodrome,+        Airstrip,+        Pedestrian,+        Pier,+        LanduseOther,+        Buildings,+        Boundaries,+        Rail,+        RoadCasing,+        RoadTunnel,+        RoadMajor,+        RoadMinor,+        Other,+    }++    /** What a label layer is. Each carries a text colour and its halo. */+    enum class Label {+        Locality,+        Country,+        Region,+        Subplace,+        Islands,+        Water,+        Shields,+        Road,+        Other,+    }++    @Immutable+    data class LabelColors(val text: Color, val halo: Color)++    private val darkFill: Map<Fill, Color> = mapOf(+        Fill.Background to Color(0xFF1B1D22),+        Fill.Water to Color(0xFF0D1B2A),+        Fill.Waterway to Color(0xFF24455F),+        Fill.Landcover to Color(0xFF1F2A22),+        Fill.Park to Color(0xFF1E2B20),+        Fill.UrbanGreen to Color(0xFF23362A),+        Fill.Hospital to Color(0xFF2B2528),+        Fill.Industrial to Color(0xFF20262B),+        Fill.School to Color(0xFF282520),+        Fill.Beach to Color(0xFF2C2A22),+        Fill.Zoo to Color(0xFF213030),+        Fill.Aerodrome to Color(0xFF212228),+        Fill.Airstrip to Color(0xFF2B2D33),+        Fill.Pedestrian to Color(0xFF242229),+        Fill.Pier to Color(0xFF202225),+        Fill.LanduseOther to Color(0xFF1F2126),+        Fill.Buildings to Color(0xFF22262C),+        Fill.Boundaries to Color(0xFF4A4F57),+        Fill.Rail to Color(0xFF3A3E45),+        Fill.RoadCasing to Color(0xFF111318),+        Fill.RoadTunnel to Color(0xFF2B2E35),+        Fill.RoadMajor to Color(0xFF464B54),+        Fill.RoadMinor to Color(0xFF34383F),+        Fill.Other to Color(0xFF26282E),+    )++    private val darkHalo = Color(0xFF101216)++    private val darkLabel: Map<Label, LabelColors> = mapOf(+        Label.Locality to LabelColors(Color(0xFFE4E8EE), darkHalo),+        Label.Country to LabelColors(Color(0xFF9AA0AA), darkHalo),+        Label.Region to LabelColors(Color(0xFF80868F), darkHalo),+        Label.Subplace to LabelColors(Color(0xFFB0B6C0), darkHalo),+        Label.Islands to LabelColors(Color(0xFF9AA0AA), darkHalo),+        // Blue-tinted so a lake name reads as belonging to the water it sits on.+        Label.Water to LabelColors(Color(0xFF6F8FCE), Color(0xFF0D1B2A)),+        Label.Shields to LabelColors(Color(0xFFC8CCD4), darkHalo),+        Label.Road to LabelColors(Color(0xFFB8BDC6), darkHalo),+        Label.Other to LabelColors(Color(0xFFC9CED6), darkHalo),+    )++    fun fill(role: Fill): Color = darkFill.getValue(role)++    fun label(role: Label): LabelColors = darkLabel.getValue(role)++    /**+     * Which [Fill] a style layer id denotes.+     *+     * Prefix and substring matching, carried over unchanged from the code this replaced.+     * It is fragile — a renamed layer silently falls through to [Fill.Other] rather than+     * failing — and gets replaced by an explicit id map in the basemap-correctness pass.+     * Casing has to be tested before highway/major because `roads_highway_casing_early`+     * contains both tokens.+     */+    fun fillRole(id: String): Fill = when {+        id == "background" || id == "earth" -> Fill.Background+        id == "water" -> Fill.Water+        id == "water_stream" || id == "water_river" -> Fill.Waterway+        id == "landcover" -> Fill.Landcover+        id == "landuse_park" -> Fill.Park+        id == "landuse_urban_green" -> Fill.UrbanGreen+        id == "landuse_hospital" -> Fill.Hospital+        id == "landuse_industrial" -> Fill.Industrial+        id == "landuse_school" -> Fill.School+        id == "landuse_beach" -> Fill.Beach+        id == "landuse_zoo" -> Fill.Zoo+        id == "landuse_aerodrome" -> Fill.Aerodrome+        id == "landuse_runway" -> Fill.Airstrip+        id == "landuse_pedestrian" -> Fill.Pedestrian+        id == "landuse_pier" -> Fill.Pier+        id.startsWith("landuse") -> Fill.LanduseOther+        id == "buildings" -> Fill.Buildings+        id.startsWith("boundaries") -> Fill.Boundaries+        id == "roads_rail" -> Fill.Rail+        id.startsWith("roads_runway") || id.startsWith("roads_taxiway") -> Fill.Airstrip+        id.contains("casing") -> Fill.RoadCasing+        id.startsWith("roads_tunnels") -> Fill.RoadTunnel+        id.contains("highway") || id.contains("major") || id.contains("link") -> Fill.RoadMajor+        id.startsWith("roads") -> Fill.RoadMinor+        else -> Fill.Other+    }++    /** Which [Label] a style layer id denotes. Same caveat as [fillRole]. */+    fun labelRole(id: String): Label = when (id) {+        "places_locality" -> Label.Locality+        "places_country" -> Label.Country+        "places_region" -> Label.Region+        "places_subplace" -> Label.Subplace+        "earth_label_islands" -> Label.Islands+        "water_waterway_label", "water_label_ocean", "water_label_lakes" -> Label.Water+        "roads_shields" -> Label.Shields+        "roads_labels_major", "roads_labels_minor", "address_label" -> Label.Road+        else -> Label.Other+    }++    /** Dark fill/line/background colour for a base style layer, as a style string. */+    fun darkFillHex(id: String): String = fill(fillRole(id)).toStyleHex()++    /** Dark `(text-color, text-halo-color)` for a label layer, as style strings. */+    fun darkLabelHex(id: String): Pair<String, String> =+        label(labelRole(id)).let { it.text.toStyleHex() to it.halo.toStyleHex() }+}
maps/src/main/java/com/vayunmathur/maps/ui/theme/MapChromeMetrics.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/theme/MapChromeMetrics.kt b/maps/src/main/java/com/vayunmathur/maps/ui/theme/MapChromeMetrics.ktnew file mode 100644index 0000000000..19694f54c0--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/theme/MapChromeMetrics.kt@@ -0,0 +1,59 @@+package com.vayunmathur.maps.ui.theme++import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp++/**+ * Map geometry that two or more call sites have to agree on.+ *+ * This is NOT a dimens file. Ordinary padding belongs to+ * [com.vayunmathur.library.ui.Spacing], and a genuinely one-off size is better as a literal+ * where it is used — `Spacing`'s own KDoc says so. What lives here is the narrower set where+ * a number appearing in one file is only correct because of a number in another: get them+ * out of sync and the UI overlaps, which is exactly what happened to the two overlay insets+ * below.+ */+object MapChromeMetrics {++    /**+     * How much of the bottom sheet shows when it is peeking.+     *+     * Fixed rather than content-driven, which is a known limitation: a sheet whose content is+     * shorter than this renders padding below it.+     */+    val sheetPeekHeight: Dp = 170.dp++    /**+     * Height of the navigation ETA strip, measured from its own layout: 12 dp vertical+     * padding either side of a 20 sp line over a 14 sp line, with the "End trip" button+     * setting the real floor at a 40 dp minimum touch target.+     *+     * An estimate, and the reason the two insets below are derived from it rather than from+     * each other. If the strip's typography changes this number has to change with it —+     * which is still strictly better than the two independent magic numbers it replaces+     * (`96.dp` and `84.dp`, 12 dp apart for no stated reason, so one of them was wrong).+     */+    val etaStripHeight: Dp = 72.dp++    /** Clearance for chrome sitting directly above the ETA strip. */+    val aboveEtaStrip: Dp = etaStripHeight + 12.dp++    /** Clearance for the full-width step list, which tucks closer than free-floating chrome. */+    val aboveEtaStripTight: Dp = etaStripHeight + 4.dp++    /**+     * Radius of the tolerance box around a tap used to hit-test map pins.+     *+     * Coupled to the marker `iconSize` ramps in the pin layers, not to any spacing value: it+     * exists so tapping *near* a small glyph still selects it. 22 dp gives a 44 dp box, just+     * under Material's 48 dp minimum touch target. Revisit it whenever those ramps change —+     * the marker sizes were halved once already without this being looked at.+     */+    val hitSlop: Dp = 22.dp++    /** Outer margin of the floating map chrome (FAB stacks, scale bar). */+    val chromeMargin: Dp = 16.dp++    /** Gap between stacked floating action buttons. */+    val fabSpacing: Dp = 12.dp+}
maps/src/main/java/com/vayunmathur/maps/ui/theme/MapTokens.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/theme/MapTokens.kt b/maps/src/main/java/com/vayunmathur/maps/ui/theme/MapTokens.ktnew file mode 100644index 0000000000..23dc23dd16--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/theme/MapTokens.kt@@ -0,0 +1,153 @@+package com.vayunmathur.maps.ui.theme++import androidx.compose.runtime.Immutable+import androidx.compose.ui.graphics.Color++/**+ * Map colours that must NOT follow the wallpaper.+ *+ * Everything drawn on the app's own surfaces belongs to `MaterialTheme.colorScheme`. These+ * do not: each one encodes a convention the user already knows from outside the app, and+ * re-hueing it from an arbitrary accent would change what it means. A green traffic jam and+ * a blue speed-limit sign are not restyled UI, they are wrong.+ *+ * They still come in light and dark variants — a fixed hue is not the same as a fixed+ * lightness, and the light-mode values are chosen against a light basemap.+ *+ * Resolve with [mapTokens], passing the map's own dark flag. Plain data rather than a+ * composition local because the map's light/dark state is a setting threaded explicitly (it+ * overrides the system one), and because the route-colour producers that need these are+ * ordinary functions building GeoJSON, not composables.+ */+@Immutable+data class MapTokens(+    val traffic: TrafficColors,+    val transitMode: TransitModeColors,+    val speedSign: SpeedSignColors,+    /** Walking and cycling routes, which carry no congestion data to colour by. */+    val routeInert: Color,+    /** A transit line that reported no colour of its own. */+    val routeTransitFallback: Color,+)++/**+ * The driving-route congestion ramp.+ *+ * Red/amber/green is the convention every traffic map uses; the mapping to `speedRatio`+ * lives in the caller. [traveled] greys out the part of the route already driven, so it has+ * to read as "spent" against both basemaps rather than as a fourth congestion level.+ */+@Immutable+data class TrafficColors(+    val jam: Color,+    val slow: Color,+    val free: Color,+    val traveled: Color,+)++/**+ * Rail-like transit modes, used only as the fallback when a line reports no `colour` of its+ * own. Riders read these off system maps, so the hues are conventional rather than derived.+ */+@Immutable+data class TransitModeColors(+    val rail: Color,+    val subway: Color,+    val lightRail: Color,+    val tram: Color,+    val monorail: Color,+    val train: Color,+)++/**+ * The posted-speed-limit sign: white disc, red ring, near-black numerals.+ *+ * There is deliberately only ONE of these, shared by both palettes. It is a reproduction of a+ * legal road sign, and a dark-mode speed limit sign does not exist — having a single value is+ * how that is stated so nobody adds a variant later. The dark-mode complaint this addresses+ * was never these colours; it was that the card behind them was white too. Theme containers,+ * leave the sign alone.+ */+val SpeedSign = SpeedSignColors(+    disc = Color(0xFFFFFFFF),+    ring = Color(0xFFD32F2F),+    ink = Color(0xFF111111),+)++@Immutable+data class SpeedSignColors(+    val disc: Color,+    val ring: Color,+    val ink: Color,+)++private val LightMapTokens = MapTokens(+    traffic = TrafficColors(+        jam = Color(0xFFF44336),+        slow = Color(0xFFFFC107),+        free = Color(0xFF4CAF50),+        traveled = Color(0xFF9E9E9E),+    ),+    transitMode = TransitModeColors(+        rail = Color(0xFF616161),+        subway = Color(0xFF0055A4),+        lightRail = Color(0xFF00843D),+        tram = Color(0xFFE4002B),+        monorail = Color(0xFF6A1B9A),+        train = Color(0xFF455A64),+    ),+    speedSign = SpeedSign,+    routeInert = Color(0xFF1710F1),+    routeTransitFallback = Color(0xFFFF0000),+)++/**+ * Same hues, lifted for a dark basemap.+ *+ * The light values are mid-tone Material 500s, which sit close to the dark basemap's own+ * lightness and lose their edges on it. These are the 300/400 steps of the same hues, so+ * the convention survives while the contrast does.+ */+private val DarkMapTokens = MapTokens(+    traffic = TrafficColors(+        jam = Color(0xFFEF5350),+        slow = Color(0xFFFFCA28),+        free = Color(0xFF66BB6A),+        traveled = Color(0xFF757575),+    ),+    transitMode = TransitModeColors(+        rail = Color(0xFF9E9E9E),+        subway = Color(0xFF5B8DEF),+        lightRail = Color(0xFF4CAF50),+        tram = Color(0xFFFF6B6B),+        monorail = Color(0xFFBA68C8),+        train = Color(0xFF90A4AE),+    ),+    // Unchanged: a road sign does not have a dark variant.+    speedSign = SpeedSign,+    routeInert = Color(0xFF7C8CFF),+    routeTransitFallback = Color(0xFFFF6E6E),+)++/** The token set for [isDark]. Safe to call off the main thread. */+fun mapTokens(isDark: Boolean): MapTokens = if (isDark) DarkMapTokens else LightMapTokens++/**+ * Render as a MapLibre style colour string.+ *+ * MapLibre parses CSS colour syntax, so this emits `#rrggbb`, or `rgba()` when there is+ * alpha — `#aarrggbb` is an Android convention and is **not** valid CSS, which is the trap+ * this exists to close. Needed wherever a colour has to survive a round-trip through a+ * GeoJSON feature property or the style JSON rather than staying a typed expression.+ */+fun Color.toStyleHex(): String {+    val r = (red * 255f + 0.5f).toInt()+    val g = (green * 255f + 0.5f).toInt()+    val b = (blue * 255f + 0.5f).toInt()+    if (alpha >= 1f) return "#%02x%02x%02x".format(r, g, b)+    // Two decimals, and locale-independent: alpha is stored quantized to 8 bits, so asking+    // for more precision just surfaces the quantization (0.5f comes back as 0.502). Trailing+    // zeros trimmed so the output is stable enough to assert on.+    val a = String.format(java.util.Locale.ROOT, "%.2f", alpha).trimEnd('0').trimEnd('.')+    return "rgba($r,$g,$b,$a)"+}
maps/src/test/java/com/vayunmathur/maps/ui/theme/BasemapPaletteTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/theme/BasemapPaletteTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/theme/BasemapPaletteTest.ktnew file mode 100644index 0000000000..b15848b727--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/theme/BasemapPaletteTest.kt@@ -0,0 +1,126 @@+package com.vayunmathur.maps.ui.theme++import androidx.compose.ui.graphics.Color+import kotlin.math.max+import kotlin.math.min+import kotlin.math.pow+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * "Legible against the basemap" is the whole reason these colours are hardcoded rather than+ * derived from the scheme, but it was only ever an assertion in a comment. These make it an+ * assertion the build checks.+ *+ * Contrast is WCAG relative luminance, the same ratio the accessibility guidelines use. Text+ * has to clear 4.5:1 against the surface it sits on; large fills only have to be+ * distinguishable from their neighbours, which is a much weaker claim and is checked as such.+ */+class BasemapPaletteTest {++    /** WCAG 2.x relative luminance. */+    private fun luminance(c: Color): Double {+        fun channel(v: Float): Double {+            val d = v.toDouble()+            return if (d <= 0.03928) d / 12.92 else ((d + 0.055) / 1.055).pow(2.4)+        }+        return 0.2126 * channel(c.red) + 0.7152 * channel(c.green) + 0.0722 * channel(c.blue)+    }++    private fun contrast(a: Color, b: Color): Double {+        val la = luminance(a)+        val lb = luminance(b)+        return (max(la, lb) + 0.05) / (min(la, lb) + 0.05)+    }++    @Test+    fun `every label clears 4_5 to 1 against its own halo`() {+        for (role in BasemapPalette.Label.entries) {+            val colors = BasemapPalette.label(role)+            val ratio = contrast(colors.text, colors.halo)+            assertTrue(+                ratio >= 4.5,+                "label $role text/halo contrast is $ratio, below 4.5:1",+            )+        }+    }++    /**+     * A label's halo only covers the glyph outline, so the text also has to survive against+     * the terrain it crosses. Background is the worst case: it is the largest area and the+     * one a label is most likely to sit on.+     */+    @Test+    fun `every label clears 4_5 to 1 against the background fill`() {+        val background = BasemapPalette.fill(BasemapPalette.Fill.Background)+        for (role in BasemapPalette.Label.entries) {+            val ratio = contrast(BasemapPalette.label(role).text, background)+            assertTrue(+                ratio >= 4.5,+                "label $role does not clear 4.5:1 against the basemap background (got $ratio)",+            )+        }+    }++    /** Roads have to be findable against the terrain they run over. */+    @Test+    fun `roads are distinguishable from the background`() {+        val background = BasemapPalette.fill(BasemapPalette.Fill.Background)+        for (role in listOf(+            BasemapPalette.Fill.RoadMajor,+            BasemapPalette.Fill.RoadMinor,+            BasemapPalette.Fill.Boundaries,+        )) {+            val ratio = contrast(BasemapPalette.fill(role), background)+            assertTrue(ratio >= 1.3, "fill $role is indistinguishable from background ($ratio)")+        }+    }++    @Test+    fun `every role resolves and every fill is opaque`() {+        for (role in BasemapPalette.Fill.entries) {+            assertEquals(1f, BasemapPalette.fill(role).alpha, "fill $role is translucent")+        }+    }++    /**+     * The prefix rules are order-dependent — `roads_highway_casing_early` contains both+     * "casing" and "highway", and casing has to win. Every id here is a real one from+     * `assets/style.json`.+     */+    @Test+    fun `layer ids resolve to the role they look like`() {+        val expected = mapOf(+            "background" to BasemapPalette.Fill.Background,+            "earth" to BasemapPalette.Fill.Background,+            "water" to BasemapPalette.Fill.Water,+            "water_river" to BasemapPalette.Fill.Waterway,+            "landuse_park" to BasemapPalette.Fill.Park,+            "landuse_runway" to BasemapPalette.Fill.Airstrip,+            "roads_taxiway" to BasemapPalette.Fill.Airstrip,+            "buildings" to BasemapPalette.Fill.Buildings,+            "boundaries_country" to BasemapPalette.Fill.Boundaries,+            "roads_rail" to BasemapPalette.Fill.Rail,+            // Casing before highway/major/link, or these three land on RoadMajor.+            "roads_highway_casing_early" to BasemapPalette.Fill.RoadCasing,+            "roads_major_casing_late" to BasemapPalette.Fill.RoadCasing,+            "roads_tunnels_link_casing" to BasemapPalette.Fill.RoadCasing,+            "roads_tunnels_highway" to BasemapPalette.Fill.RoadTunnel,+            "roads_highway" to BasemapPalette.Fill.RoadMajor,+            "roads_minor" to BasemapPalette.Fill.RoadMinor,+            "pois" to BasemapPalette.Fill.Other,+        )+        for ((id, role) in expected) {+            assertEquals(role, BasemapPalette.fillRole(id), "wrong fill role for '$id'")+        }+    }++    @Test+    fun `label ids resolve to the role they look like`() {+        assertEquals(BasemapPalette.Label.Locality, BasemapPalette.labelRole("places_locality"))+        assertEquals(BasemapPalette.Label.Water, BasemapPalette.labelRole("water_label_lakes"))+        assertEquals(BasemapPalette.Label.Road, BasemapPalette.labelRole("roads_labels_major"))+        assertEquals(BasemapPalette.Label.Other, BasemapPalette.labelRole("roads_oneway"))+    }+}
maps/src/test/java/com/vayunmathur/maps/ui/theme/MapTokensTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/theme/MapTokensTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/theme/MapTokensTest.ktnew file mode 100644index 0000000000..5f75a02c32--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/theme/MapTokensTest.kt@@ -0,0 +1,78 @@+package com.vayunmathur.maps.ui.theme++import androidx.compose.ui.graphics.Color+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * [toStyleHex] feeds colours into MapLibre, which parses CSS colour syntax. The trap it+ * exists to close is that `#aarrggbb` — the form Android's own `Color.parseColor` accepts —+ * is not valid CSS, so an alpha colour serialized the obvious way is silently mis-parsed.+ */+class MapTokensTest {++    @Test+    fun `opaque colours render as six-digit hex`() {+        assertEquals("#ff0000", Color(0xFFFF0000).toStyleHex())+        assertEquals("#000000", Color(0xFF000000).toStyleHex())+        assertEquals("#ffffff", Color(0xFFFFFFFF).toStyleHex())+        assertEquals("#1b1d22", Color(0xFF1B1D22).toStyleHex())+    }++    @Test+    fun `translucent colours render as rgba, never as eight-digit hex`() {+        // 0.5f is stored as 128/255, so the emitted value is the quantized one rounded to+        // two places — that is the whole reason precision is capped there.+        val hex = Color(0xFFFF0000).copy(alpha = 0.5f).toStyleHex()+        assertEquals("rgba(255,0,0,0.5)", hex)+        assertTrue(!hex.startsWith("#"), "alpha must not be emitted as hex: $hex")+    }++    /** The admin highlight fill is the real caller of the alpha path. */+    @Test+    fun `a low alpha keeps two decimals`() {+        assertEquals("rgba(255,0,0,0.12)", Color(0xFFFF0000).copy(alpha = 0.12f).toStyleHex())+    }++    @Test+    fun `formatting does not depend on the default locale`() {+        val original = java.util.Locale.getDefault()+        try {+            // A comma-decimal locale would otherwise emit "rgba(255,0,0,0,5)", which MapLibre+            // parses as a four-argument rgba and rejects.+            java.util.Locale.setDefault(java.util.Locale.GERMANY)+            assertEquals("rgba(255,0,0,0.5)", Color(0xFFFF0000).copy(alpha = 0.5f).toStyleHex())+        } finally {+            java.util.Locale.setDefault(original)+        }+    }++    @Test+    fun `a fully transparent colour still round-trips as rgba`() {+        assertEquals("rgba(0,0,0,0)", Color.Transparent.toStyleHex())+    }++    /** Rounding, not truncation — 0.5/255 must not fall a channel short. */+    @Test+    fun `channels round to nearest`() {+        assertEquals("#808080", Color(0xFF808080).toStyleHex())+    }++    @Test+    fun `the two palettes differ everywhere it matters`() {+        val light = mapTokens(isDark = false)+        val dark = mapTokens(isDark = true)+        assertTrue(light.traffic.jam != dark.traffic.jam, "traffic ramp must adapt to the basemap")+        assertTrue(light.traffic.free != dark.traffic.free)+        assertTrue(light.transitMode.subway != dark.transitMode.subway)+        assertTrue(light.routeInert != dark.routeInert)+    }++    /** A road sign has no dark variant, and this is where that stops being a comment. */+    @Test+    fun `the speed limit sign is identical in both palettes`() {+        assertEquals(mapTokens(isDark = false).speedSign, mapTokens(isDark = true).speedSign)+        assertEquals(SpeedSign, mapTokens(isDark = true).speedSign)+    }+}