Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / maps / src / main / java / com / vayunmathur / maps / ui / RouteSheet.kt

RouteSheet.kt332 lines · 16.4 KiBRaw
1package com.vayunmathur.maps.ui
2import com.vayunmathur.maps.data.string
3import com.vayunmathur.maps.platform.formatDistance
4import com.vayunmathur.maps.platform.formatDuration
5import com.vayunmathur.maps.service.formatEta
6
7import android.content.Intent
8import androidx.compose.foundation.layout.Arrangement
9import androidx.compose.foundation.layout.Column
10import androidx.compose.foundation.layout.Row
11import androidx.compose.foundation.layout.Spacer
12import androidx.compose.foundation.layout.fillMaxWidth
13import androidx.compose.foundation.layout.height
14import androidx.compose.foundation.layout.padding
15import androidx.compose.foundation.lazy.LazyColumn
16import androidx.compose.foundation.lazy.itemsIndexed
17import androidx.compose.runtime.Composable
18import androidx.compose.runtime.setValue
19import androidx.compose.runtime.getValue
20import androidx.compose.runtime.remember
21import androidx.compose.ui.Alignment
22import androidx.compose.ui.Modifier
23import androidx.compose.ui.platform.LocalContext
24import androidx.compose.ui.res.stringResource
25import androidx.compose.ui.unit.dp
26import com.vayunmathur.library.map.GeoPoint
27import com.vayunmathur.library.ui.Button
28import com.vayunmathur.library.ui.ButtonDefaults
29import com.vayunmathur.library.ui.Card
30import com.vayunmathur.library.ui.ListItem
31import com.vayunmathur.library.ui.LocalContentColor
32import com.vayunmathur.library.ui.MaterialTheme
33import com.vayunmathur.library.ui.PrimaryTabRow
34import com.vayunmathur.library.ui.Spacing
35import com.vayunmathur.library.ui.Tab
36import com.vayunmathur.library.ui.Text
37import com.vayunmathur.library.ui.verticalShape
38import com.vayunmathur.maps.R
39import com.vayunmathur.maps.data.SpecificFeature
40import com.vayunmathur.maps.intents.RideEstimateClient
41import com.vayunmathur.maps.intents.rememberRideEstimate
42import com.vayunmathur.maps.service.NavigationService
43import com.vayunmathur.maps.platform.NavigationSessionManager
44import com.vayunmathur.maps.domain.RouteService
45import androidx.compose.foundation.layout.size
46
47/**
48 * The directions panel: one segment per travel mode, then the turn-by-turn step list.
49 *
50 * Each segment carries its own time and distance, so there is no separate summary row —
51 * comparing modes is the point of the control, and that only works if the numbers are on
52 * it. Rideshare appears as a fifth segment when the taxi app is installed, showing
53 * arrival and price instead, and is a UI-level pseudo-mode rather than a
54 * [RouteService.TravelMode].
55 *
56 * Stateless (no ViewModel) so the store-listing previews can render it - the map it
57 * normally sits over is a native surface a preview cannot draw.
58 */
59@Composable
60fun RouteSheet(
61 selectedFeature: SpecificFeature.Route,
62 route: Map<RouteService.TravelMode, RouteService.RouteType?>,
63 selectedRouteType: RouteService.TravelMode,
64 setSelectedRouteType: (RouteService.TravelMode) -> Unit,
65 modifier: Modifier = Modifier,
66 navState: NavigationSessionManager.NavState = NavigationSessionManager.NavState.Idle,
67 userPosition: GeoPoint? = null,
68 onStartNavigation: ((String, RouteService.TravelMode) -> Unit)? = null,
69 alternatives: List<RouteService.Route> = emptyList(),
70 selectedAlternative: RouteService.Route? = null,
71 onSelectAlternative: (RouteService.Route?) -> Unit = {},
72) {
73 val context = LocalContext.current
74
75 // Rideshare endpoints. Origin may be "from here" (a null waypoint) → the user's live
76 // position; the destination must be a real waypoint, so it never falls back to it.
77 val rideOrigin = selectedFeature.waypoints.firstOrNull()
78 val rideDest = selectedFeature.waypoints.lastOrNull()
79 val rideOriginPos = rideOrigin?.position ?: userPosition
80 val rideDestPos = rideDest?.position
81 val driveRoute = route[RouteService.TravelMode.DRIVE]
82
83 val taxiInstalled = remember { RideEstimateClient.isInstalled(context) }
84 val rideEstimate =
85 if (taxiInstalled && rideOriginPos != null && rideDestPos != null) {
86 rememberRideEstimate(
87 context,
88 rideOriginPos.latitude, rideOriginPos.longitude,
89 rideDestPos.latitude, rideDestPos.longitude,
90 rideOrigin?.name, rideDest.name,
91 ).value?.takeIf { it.available }
92 } else null
93
94 // A ride substitutes for driving, so it needs the drive route to borrow a duration
95 // and a polyline from. No taxi app, no segment — same as the card this replaced.
96 val rideshareOffered = taxiInstalled &&
97 rideOriginPos != null &&
98 rideDestPos != null &&
99 selectedFeature.waypoints.size >= 2 &&
100 driveRoute != null
101
102 // Rideshare is a segment in this selector but deliberately **not** a
103 // [RouteService.TravelMode]: it has no routing profile of its own, and a new variant
104 // would make every `when` across TravelMode's thirteen consumers non-exhaustive. So
105 // its selection lives here, and picking it leaves the mode on DRIVE — a ride follows
106 // the driving route, which is what the map is already drawing.
107 var rideshareSelected by remember { androidx.compose.runtime.mutableStateOf(false) }
108 val showRideshare = rideshareSelected && rideshareOffered
109
110 Column(modifier) {
111 // A tab row rather than the ButtonGroup this replaced: each segment now carries
112 // three stacked lines (mode, time, distance), and `toggleableItem` takes a label
113 // string with no content slot. Tab's content overload is the only primitive in
114 // library/ui that holds a column.
115 val modes = route.keys.toList()
116 val selectedIndex =
117 if (showRideshare) modes.size else modes.indexOf(selectedRouteType).coerceAtLeast(0)
118 PrimaryTabRow(selectedTabIndex = selectedIndex, modifier = Modifier.fillMaxWidth()) {
119 modes.forEach { mode ->
120 val modeRoute = route[mode]?.takeIf { it !is RouteService.EmptyRoute }
121 Tab(
122 selected = !showRideshare && selectedRouteType == mode,
123 onClick = {
124 rideshareSelected = false
125 setSelectedRouteType(mode)
126 },
127 ) {
128 ModeTab(
129 label = stringResource(
130 when (mode) {
131 RouteService.TravelMode.WALK -> R.string.travel_mode_walk
132 RouteService.TravelMode.BICYCLE -> R.string.travel_mode_bicycle
133 RouteService.TravelMode.DRIVE -> R.string.travel_mode_drive
134 RouteService.TravelMode.TRANSIT -> R.string.layer_transit
135 }
136 ),
137 primary = modeRoute?.let { formatDuration(context, it.duration) },
138 secondary = modeRoute?.let { formatDistance(it.distanceMeters) },
139 )
140 }
141 }
142 if (rideshareOffered) {
143 Tab(
144 selected = showRideshare,
145 onClick = {
146 rideshareSelected = true
147 setSelectedRouteType(RouteService.TravelMode.DRIVE)
148 },
149 ) {
150 ModeTab(
151 label = stringResource(R.string.route_taxi_title),
152 // Dropoff, which the provider does not give us: `etaMinutes` is
153 // the pickup wait. Device-local wall clock, unlike a transit
154 // itinerary's feed-local times, because a ride is happening now.
155 primary = rideEstimate?.etaMinutes?.let { wait ->
156 formatEta(
157 System.currentTimeMillis() +
158 wait * 60_000L +
159 driveRoute.duration.inWholeMilliseconds
160 )
161 },
162 secondary = rideEstimate?.fareEstimate,
163 )
164 }
165 }
166 }
167
168 if (showRideshare) {
169 // No step list and no Start Navigation: the ride is driven for the user, so
170 // booking it is the only action.
171 RideshareBooking(
172 originLat = rideOriginPos.latitude,
173 originLng = rideOriginPos.longitude,
174 originLabel = rideOrigin?.name,
175 destLat = rideDestPos.latitude,
176 destLng = rideDestPos.longitude,
177 destLabel = rideDest.name,
178 )
179 return@Column
180 }
181
182 if (alternatives.isNotEmpty()) {
183 AlternativesSection(
184 alternatives = alternatives,
185 selected = selectedAlternative,
186 onSelect = onSelectAlternative,
187 )
188 }
189
190 val routeForMode = route[selectedRouteType]
191 if (routeForMode != null) {
192 if (routeForMode is RouteService.Route) {
193 RouteOptionCard(
194 route = routeForMode,
195 selected = selectedAlternative == null,
196 onClick = { onSelectAlternative(null) },
197 modifier = Modifier.padding(horizontal = Spacing.lg, vertical = Spacing.sm),
198 )
199 }
200 if (routeForMode !is RouteService.EmptyRoute) {
201 // Time and distance live in the selector now, so the summary row that
202 // used to sit here would only repeat the selected tab.
203 //
204 // "Start Navigation" needs a concrete Route (steps + polyline), no active
205 // session, and a real destination. TRANSIT is excluded: the navigation
206 // engine snaps GPS to the polyline and computes ETA from progress along
207 // it, which doesn't model trains/buses, and a mid-trip recalc would
208 // replace transit steps with walking ones. The step list still shows.
209 val lastWaypoint = selectedFeature.waypoints.lastOrNull()
210 if (routeForMode is RouteService.Route &&
211 navState is NavigationSessionManager.NavState.Idle &&
212 selectedRouteType != RouteService.TravelMode.TRANSIT &&
213 lastWaypoint != null
214 ) {
215 Button(
216 onClick = {
217 val intent = Intent(context, NavigationService::class.java)
218 context.startForegroundService(intent)
219 NavigationSessionManager.init(context)
220 NavigationSessionManager.start(
221 route = routeForMode,
222 mode = selectedRouteType,
223 destination = lastWaypoint.position,
224 destinationLabel = lastWaypoint.name,
225 )
226 onStartNavigation?.invoke(lastWaypoint.name, selectedRouteType)
227 },
228 modifier = Modifier
229 .fillMaxWidth()
230 .padding(horizontal = Spacing.lg, vertical = Spacing.sm),
231 colors = ButtonDefaults.buttonColors(
232 containerColor = MaterialTheme.colorScheme.primary,
233 contentColor = MaterialTheme.colorScheme.onPrimary,
234 ),
235 ) {
236 Text(stringResource(R.string.nav_action_start))
237 }
238 }
239 Spacer(Modifier.height(Spacing.sm))
240 }
241 LazyColumn(verticalArrangement = Arrangement.spacedBy(2.dp)) {
242 when (routeForMode) {
243 is RouteService.Route -> {
244 // "Leave at" and "Arrive at" bracket the leg list as ordinary rows, so
245 // the card rounding has to be indexed across all three groups rather
246 // than over the legs alone.
247 val leave = listOfNotNull(routeForMode.departureTime)
248 val arrive = listOfNotNull(routeForMode.arrivalTime)
249 val total = leave.size + routeForMode.step.size + arrive.size
250 itemsIndexed(leave) { idx, time ->
251 Card(shape = verticalShape(idx, total)) {
252 ListItem({ Text(stringResource(R.string.leave_at, time)) })
253 }
254 }
255 itemsIndexed(routeForMode.step) { idx, step ->
256 Card(shape = verticalShape(leave.size + idx, total)) {
257 val transit = step.transitDetails
258 ListItem({
259 Text(step.navInstruction.instructions)
260 }, leadingContent = {
261 step.navInstruction.maneuver.iconContent()?.let { icon ->
262 icon(Modifier, LocalContentColor.current)
263 }
264 }, supportingContent = transit?.let { t ->
265 {
266 Row(
267 verticalAlignment = Alignment.CenterVertically,
268 horizontalArrangement = Arrangement.spacedBy(8.dp),
269 ) {
270 LineBadge(
271 t.transitLine.nameShort ?: t.transitLine.name,
272 t.transitLine.color,
273 )
274 Text(
275 transitSupportingText(t),
276 style = MaterialTheme.typography.bodySmall,
277 color = MaterialTheme.colorScheme.onSurfaceVariant,
278 )
279 }
280 }
281 }, trailingContent = transit
282 ?.stopDetails
283 ?.takeIf { d -> d.departureTime.isNotBlank() }
284 ?.let { d ->
285 {
286 Column(horizontalAlignment = Alignment.End) {
287 Text(
288 d.departureTime,
289 style = MaterialTheme.typography.labelLarge,
290 )
291 if (d.arrivalTime.isNotBlank()) {
292 Text(
293 d.arrivalTime,
294 style = MaterialTheme.typography.bodySmall,
295 color = MaterialTheme.colorScheme
296 .onSurfaceVariant,
297 )
298 }
299 }
300 }
301 })
302 }
303 }
304 itemsIndexed(arrive) { idx, time ->
305 Card(
306 shape = verticalShape(
307 leave.size + routeForMode.step.size + idx,
308 total,
309 )
310 ) {
311 ListItem({ Text(stringResource(R.string.arrive_at, time)) })
312 }
313 }
314 }
315
316 is RouteService.EmptyRoute -> {
317 item {
318 ListItem({
319 Text(stringResource(R.string.no_route_found))
320 })
321 }
322 }
323 }
324 }
325 } else {
326 ListItem({
327 Text(stringResource(R.string.generating_route))
328 })
329 }
330 }
331}
332