Modern Apps git

← Modern-Apps.git

maps: word walk legs by duration, add Leave at and Arrive at

Commit
cf169b8f0ca0a350c34a5b9e8af7b33d96edebdd
Author
vayun-mathur <[email protected]>
When
2026-08-24 19:41 UTC (3 months ago)
Parents
e651f51

Diff

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 1094e0f17e..ebbd71c7a2 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt@@ -283,8 +283,19 @@ fun RouteSheet(             LazyColumn(verticalArrangement = Arrangement.spacedBy(2.dp)) {                 when (routeForMode) {                     is RouteService.Route -> {+                        // "Leave at" and "Arrive at" bracket the leg list as ordinary rows, so+                        // the card rounding has to be indexed across all three groups rather+                        // than over the legs alone.+                        val leave = listOfNotNull(routeForMode.departureTime)+                        val arrive = listOfNotNull(routeForMode.arrivalTime)+                        val total = leave.size + routeForMode.step.size + arrive.size+                        itemsIndexed(leave) { idx, time ->+                            Card(shape = verticalShape(idx, total)) {+                                ListItem({ Text(stringResource(R.string.leave_at, time)) })+                            }+                        }                         itemsIndexed(routeForMode.step) { idx, it ->-                            Card(shape = verticalShape(idx, routeForMode.step.size)) {+                            Card(shape = verticalShape(leave.size + idx, total)) {                                 val transit = it.transitDetails                                 ListItem({                                     Text(it.navInstruction.instructions)@@ -332,6 +343,16 @@ fun RouteSheet(                                     })                             }                         }+                        itemsIndexed(arrive) { idx, time ->+                            Card(+                                shape = verticalShape(+                                    leave.size + routeForMode.step.size + idx,+                                    total,+                                )+                            ) {+                                ListItem({ Text(stringResource(R.string.arrive_at, time)) })+                            }+                        }                     }                      is RouteService.EmptyRoute -> {
maps/src/main/java/com/vayunmathur/maps/util/ItineraryWording.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/ItineraryWording.kt b/maps/src/main/java/com/vayunmathur/maps/util/ItineraryWording.ktnew file mode 100644index 0000000000..3e7259c382--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/ItineraryWording.kt@@ -0,0 +1,81 @@+package com.vayunmathur.maps.util++import kotlin.math.ceil+import kotlin.time.Duration++/**+ * How a transit itinerary is worded: a walk leg's duration, and the "Leave at" /+ * "Arrive at" bookends.+ *+ * Split out of [OfflineRouter] because that object's initializer loads the native+ * routing library, which puts everything on it out of reach of a JVM unit test.+ * None of this needs the router — it reads the legs the router already produced.+ */++/**+ * Stand-in instruction text for an itinerary's walk leg, replaced by+ * [phraseWalkLegs] once coalescing has settled the leg's duration. Never shown: it+ * exists so adjacent walk legs still compare equal and merge.+ */+internal const val WALK_LEG_PLACEHOLDER = "\u0000walk"++/**+ * Replace each walk leg's placeholder instruction with its duration, via [label].+ *+ * Done after coalescing, not while the step is built: the merge groups steps by+ * identical instruction text, so a duration embedded earlier would stop two adjacent+ * walk legs merging and split them into two rows. By this point the duration is the+ * merged one, which is what the row should show.+ *+ * [label] rather than a `Context` so the rule about *which* steps get rephrased —+ * the part that interacts with coalescing — is testable off-device.+ */+internal fun phraseWalkLegs(+    steps: List<RouteService.Step>,+    mode: RouteService.TravelMode,+    label: (minutes: Int) -> String,+): List<RouteService.Step> {+    if (mode != RouteService.TravelMode.TRANSIT) return steps+    return steps.map { step ->+        if (step.navInstruction.instructions != WALK_LEG_PLACEHOLDER) step+        else step.copy(+            navInstruction = step.navInstruction.copy(+                instructions = label(walkLegMinutes(step.staticDuration))+            )+        )+    }+}++/**+ * A walk leg's duration in whole minutes, rounded up and floored at one: every other+ * time the route sheet shows drops seconds, and "0 min" reads as no walk at all.+ */+internal fun walkLegMinutes(duration: Duration): Int =+    ceil(duration.inWholeSeconds / 60.0).toInt().coerceAtLeast(1)++/**+ * When to set off: the first ride's departure less the walk that leads to it.+ *+ * Not the itinerary's own start time. A wait leg between the walk and the ride is+ * slack the user does not need to spend at the stop, so only the walk is subtracted —+ * that is the number that answers "when do I leave?". Null when there is no+ * timetabled ride, i.e. a walk-only itinerary.+ */+internal fun leaveAt(rawSteps: Array<OfflineRouter.RawStep>): String? {+    val firstRide = rawSteps.indexOfFirst { it.isTransit && it.depSecs > 0 }+    if (firstRide < 0) return null+    return formatServiceTime(rawSteps[firstRide].depSecs - walkSecs(rawSteps.take(firstRide)))+}++/** When the itinerary lands: the last ride's arrival plus the walk off the end. */+internal fun arriveAt(rawSteps: Array<OfflineRouter.RawStep>): String? {+    val lastRide = rawSteps.indexOfLast { it.isTransit && it.arrSecs > 0 }+    if (lastRide < 0) return null+    return formatServiceTime(rawSteps[lastRide].arrSecs + walkSecs(rawSteps.drop(lastRide + 1)))+}++/** Walking seconds across [legs], counting neither rides nor waiting at a stop. */+private fun walkSecs(legs: List<OfflineRouter.RawStep>): Int =+    legs.filter { !it.isTransit && it.maneuverId != RouteService.API.Maneuver.WAIT.ordinal }+        .sumOf { it.duration10ms / 100 }+        .toInt()
maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.ktindex 8e5ccef4cf..4addb9de6b 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt@@ -949,6 +949,15 @@ object OfflineRouter {                                         else ->                                             if (raw.isTransit && raw.stopCode != null && raw.endStopCode != null)                                                 context.getString(R.string.maneuver_ride_transit, raw.roadName, raw.stopCode, raw.endStopCode, raw.stopCount)+                                            else if (mode == RouteService.TravelMode.TRANSIT)+                                                // A walk leg of an itinerary. The planner names+                                                // every one of them "Walk", which the road-name+                                                // templates below turn into "Continue onto Walk".+                                                // Phrased for real after coalescing, from the+                                                // merged duration; this placeholder only has to+                                                // compare equal between adjacent walk legs so+                                                // they still merge.+                                                WALK_LEG_PLACEHOLDER                                             else if (hasName)                                                 context.getString(                                                         R.string.maneuver_unspecified,@@ -1039,7 +1048,15 @@ object OfflineRouter {                                 coalescedSteps.sumOf { it.staticDuration.inWholeSeconds }.seconds,                         distanceMeters = coalescedSteps.sumOf { it.distanceMeters },                         polyline = fullPolyline,-                        step = coalescedSteps+                        step = phraseWalkLegs(coalescedSteps, mode) { minutes ->+                            context.resources.getQuantityString(+                                    R.plurals.maneuver_walk_minutes,+                                    minutes,+                                    minutes,+                            )+                        },+                        departureTime = leaveAt(rawSteps),+                        arrivalTime = arriveAt(rawSteps),                 )     } 
maps/src/main/java/com/vayunmathur/maps/util/RouteService.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/RouteService.kt b/maps/src/main/java/com/vayunmathur/maps/util/RouteService.ktindex 0200f9b784..dd90c04651 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/RouteService.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/RouteService.kt@@ -24,7 +24,21 @@ object RouteService {          */         @Serializable data class Lane(val directions: List<Maneuver>, val active: Boolean)     }-    data class Route(override val duration: Duration, override val distanceMeters: Double, val polyline: List<Position>, val step: List<Step>): RouteType+    /**+     * [departureTime] and [arrivalTime] are wall-clock `HH:mm` in the **feed's**+     * timezone, matching the per-leg times in [API.StopDetails] — a transit+     * itinerary's legs are timetabled in that zone, so a device-local rendering+     * would disagree with the rows beneath. Null on any route without a ride leg,+     * which includes every non-transit mode and a walk-only itinerary.+     */+    data class Route(+        override val duration: Duration,+        override val distanceMeters: Double,+        val polyline: List<Position>,+        val step: List<Step>,+        val departureTime: String? = null,+        val arrivalTime: String? = null,+    ): RouteType     data class Step(val distanceMeters: Double, val staticDuration: Duration, val polyline: List<Position>, val navInstruction: API.NavInstruction, val travelMode: TravelMode, val transitDetails: API.TransitDetails? = null, val speedRatio: Double = 1.0, val lanes: List<API.Lane> = emptyList())     interface RouteType { val duration: Duration; val distanceMeters: Double }     class EmptyRoute: RouteType { override val duration: Duration = 0.seconds; override val distanceMeters: Double = 0.0 }
maps/src/main/res/values/strings.xml
diff --git a/maps/src/main/res/values/strings.xml b/maps/src/main/res/values/strings.xmlindex 6376975a36..c3c57762fd 100644--- a/maps/src/main/res/values/strings.xml+++ b/maps/src/main/res/values/strings.xml@@ -338,6 +338,15 @@     </plurals>     <!-- Transit directions: joins the headsign and the stop count, e.g. "Towards Ocean Beach · 4 stops" -->     <string name="transit_detail_separator">%1$s \u00b7 %2$s</string>+    <!-- Transit directions: a walk leg of an itinerary, phrased from its duration. %1$d = whole minutes -->+    <plurals name="maneuver_walk_minutes">+        <item quantity="one">Walk %1$d min</item>+        <item quantity="other">Walk %1$d min</item>+    </plurals>+    <!-- Transit directions: when to set off, so the first ride is caught. %1$s = time e.g. "08:42" -->+    <string name="leave_at">Leave at <xliff:g id="time" example="08:42">%1$s</xliff:g></string>+    <!-- Transit directions: when the itinerary reaches the destination. %1$s = time e.g. "09:15" -->+    <string name="arrive_at">Arrive at <xliff:g id="time" example="09:15">%1$s</xliff:g></string>      <!-- Settings: screen title. Noun. -->     <string name="settings_title">Settings</string>
maps/src/test/java/com/vayunmathur/maps/util/ItineraryWordingTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/ItineraryWordingTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/ItineraryWordingTest.ktnew file mode 100644index 0000000000..e59c4ef48c--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/ItineraryWordingTest.kt@@ -0,0 +1,212 @@+package com.vayunmathur.maps.util++import org.maplibre.spatialk.geojson.Position+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.time.Duration.Companion.minutes+import kotlin.time.Duration.Companion.seconds++/**+ * How a transit itinerary is worded: a walk leg's duration, and the "Leave at" /+ * "Arrive at" bookends.+ *+ * All four are derived from the raw native legs, so none of them needs a device.+ * The walk phrasing takes its plural lookup as a lambda for exactly that reason —+ * what is worth pinning is *which* steps get rephrased and off *which* duration,+ * not the wording of the resource.+ */+class ItineraryWordingTest {++    /** A native leg. Only the fields these functions read are meaningful. */+    private fun leg(+        isTransit: Boolean,+        depSecs: Int = 0,+        arrSecs: Int = 0,+        seconds: Long = 0,+        maneuverId: Int = 0,+    ) = OfflineRouter.RawStep(+        maneuverId = maneuverId,+        roadName = if (isTransit) "N" else "Walk",+        distanceMm = 0,+        duration10ms = seconds * 100,+        geometry = DoubleArray(0),+        speedRatio = 1.0,+        isTransit = isTransit,+        gtfsFeed = null,+        stopCode = null,+        endStopCode = null,+        stopCount = 0,+        lanePacked = IntArray(0),+        headsign = null,+        routeColor = 0,+        depSecs = depSecs,+        arrSecs = arrSecs,+        boardStopId = null,+        alightStopId = null,+    )++    private val wait = RouteService.API.Maneuver.WAIT.ordinal++    private fun walkStep(duration: kotlin.time.Duration) = RouteService.Step(+        distanceMeters = 100.0,+        staticDuration = duration,+        polyline = listOf(Position(0.0, 0.0)),+        navInstruction = RouteService.API.NavInstruction(+            RouteService.API.Maneuver.MANEUVER_UNSPECIFIED,+            WALK_LEG_PLACEHOLDER,+        ),+        travelMode = RouteService.TravelMode.WALK,+    )++    private fun label(minutes: Int) = "Walk $minutes min"++    // --- Walk-leg wording ---++    @Test+    fun `a walk leg is phrased from its duration, not its road name`() {+        val phrased = phraseWalkLegs(+            listOf(walkStep(8.minutes)),+            RouteService.TravelMode.TRANSIT,+            ::label,+        )+        assertEquals("Walk 8 min", phrased.single().navInstruction.instructions)+    }++    /**+     * The placeholder is what lets coalescing merge adjacent walk legs, so it must+     * never survive to the UI — the whole point of rephrasing after the merge.+     */+    @Test+    fun `no walk placeholder survives phrasing`() {+        val phrased = phraseWalkLegs(+            listOf(walkStep(3.minutes), walkStep(5.minutes)),+            RouteService.TravelMode.TRANSIT,+            ::label,+        )+        assertEquals(+            listOf("Walk 3 min", "Walk 5 min"),+            phrased.map { it.navInstruction.instructions },+        )+    }++    /**+     * Two adjacent walk legs are merged before phrasing, so the row shows the summed+     * duration. Pinned as the merged step's own duration, since embedding the text+     * earlier is precisely what would have stopped the merge happening.+     */+    @Test+    fun `a merged pair of walk legs is phrased from the summed duration`() {+        val merged = walkStep(3.minutes + 5.minutes)+        val phrased = phraseWalkLegs(+            listOf(merged),+            RouteService.TravelMode.TRANSIT,+            ::label,+        )+        assertEquals("Walk 8 min", phrased.single().navInstruction.instructions)+    }++    @Test+    fun `a ride leg is left alone`() {+        val ride = walkStep(4.minutes).copy(+            travelMode = RouteService.TravelMode.TRANSIT,+            navInstruction = RouteService.API.NavInstruction(+                RouteService.API.Maneuver.RIDE,+                "Ride N from Alpha to Gamma",+            ),+        )+        val phrased = phraseWalkLegs(+            listOf(ride),+            RouteService.TravelMode.TRANSIT,+            ::label,+        )+        assertEquals("Ride N from Alpha to Gamma", phrased.single().navInstruction.instructions)+    }++    @Test+    fun `driving steps are untouched even if they carry the placeholder`() {+        val steps = listOf(walkStep(4.minutes))+        assertEquals(+            steps,+            phraseWalkLegs(steps, RouteService.TravelMode.DRIVE, ::label),+        )+    }++    /** Never "0 min": a sub-minute walk is still a walk. */+    @Test+    fun `a sub-minute walk rounds up to one minute`() {+        assertEquals(1, walkLegMinutes(1.seconds))+        assertEquals(1, walkLegMinutes(59.seconds))+        assertEquals(1, walkLegMinutes(60.seconds))+    }++    @Test+    fun `walk minutes round up rather than truncating`() {+        assertEquals(2, walkLegMinutes(61.seconds))+        assertEquals(5, walkLegMinutes(4.minutes + 1.seconds))+    }++    // --- Leave at / Arrive at ---++    @Test+    fun `leave at is the first ride departure minus the leading walk`() {+        val steps = arrayOf(+            leg(isTransit = false, seconds = 300), // 5 min walk to the stop+            leg(isTransit = true, depSecs = 32_400, arrSecs = 34_200), // 09:00 -> 09:30+        )+        assertEquals("08:55", leaveAt(steps))+    }++    /**+     * A wait leg is slack at the stop, not travel: subtracting it too would tell the+     * user to leave earlier than they need to.+     */+    @Test+    fun `a wait before the ride does not move leave at any earlier`() {+        val steps = arrayOf(+            leg(isTransit = false, seconds = 300),+            leg(isTransit = false, seconds = 600, maneuverId = wait),+            leg(isTransit = true, depSecs = 32_400, arrSecs = 34_200),+        )+        assertEquals("08:55", leaveAt(steps))+    }++    @Test+    fun `arrive at is the last ride arrival plus the trailing walk`() {+        val steps = arrayOf(+            leg(isTransit = true, depSecs = 32_400, arrSecs = 34_200), // lands 09:30+            leg(isTransit = false, seconds = 420), // 7 min walk off the end+        )+        assertEquals("09:37", arriveAt(steps))+    }++    @Test+    fun `both bookends span the outermost rides of a two-ride itinerary`() {+        val steps = arrayOf(+            leg(isTransit = false, seconds = 300),+            leg(isTransit = true, depSecs = 32_400, arrSecs = 33_000),+            leg(isTransit = false, seconds = 120),+            leg(isTransit = true, depSecs = 33_600, arrSecs = 34_800), // lands 09:40+            leg(isTransit = false, seconds = 300),+        )+        assertEquals("08:55", leaveAt(steps))+        assertEquals("09:45", arriveAt(steps))+    }++    /** Nothing to bracket: a walk-only itinerary omits both rows. */+    @Test+    fun `a walk-only itinerary has neither bookend`() {+        val steps = arrayOf(leg(isTransit = false, seconds = 900))+        assertNull(leaveAt(steps))+        assertNull(arriveAt(steps))+    }++    /** A ride with no timetable (`0 secs`) cannot anchor a wall-clock row. */+    @Test+    fun `a ride without times has neither bookend`() {+        val steps = arrayOf(leg(isTransit = true, depSecs = 0, arrSecs = 0))+        assertNull(leaveAt(steps))+        assertNull(arriveAt(steps))+    }+}+