feat(roadtrip): other ways to drive a leg, on the phone

The desk offers alternative routes from the drive band between two stops;
the phone had nothing. A leg in the phone chain now carries one round
button that asks the router for other ways and switches to the map, where a
bar takes the stage bar's place: the ways as chips with their colour, time,
distance and what sets them apart, and a confirm button. On glass there is
no hover, so a tap on a chip or on a line only previews that road; confirm
writes it. The button shows only where the desk offers it (a routed leg
between chosen stops), for someone who may edit the day, and not offline,
since vias are written online only.

The picker could not have stayed open on a phone at all: the planner closed
it whenever road trip mode was off, and that mode is off on a phone by
design, so the next render shut it. The close now follows where the picker
can be seen (road trip mode on the desk, the road trip tab on a phone), and
useRouteAlternatives returns a memoised object.

The rules both shells need are shared: legReroutable in the row model,
alternativesPhase and alternativeSubline next to the overlays, and the desk
bar and sidebar read them too with no visible change. Both map engines take
an optional fitPadding, so the phone frames the leg between the day chips
and the bar instead of under them.
This commit is contained in:
Maurice
2026-09-17 00:10:51 +00:00
parent 9b415c8ab9
commit 6a6c7f1882
25 changed files with 1572 additions and 57 deletions
+106 -3
View File
@@ -1,4 +1,4 @@
import { useCallback, useMemo, useRef, useState } from 'react'
import { useCallback, useLayoutEffect, useMemo, useRef, useState, type RefObject } from 'react'
import { MapViewAuto } from '../../../../components/Map/MapViewAuto'
import { MapCompassPill, type CompassMap } from '../../../../components/Map/MapCompassPill'
import { MAP_LAYER_SWITCHER_INSET, MAP_ROUND_CONTROL_SIZE } from '../../../../components/Map/MapLayerSwitcher'
@@ -12,8 +12,10 @@ import { stageMapData } from '../../../../components/Roadtrip/stageMap'
import { useRoadtripSettings } from '../../../../hooks/useRoadtripSettings'
import { useSettingsStore } from '../../../../store/settingsStore'
import { useTripStore } from '../../../../store/tripStore'
import { RT_ALT_BAR_LIFT } from '../roadtrip/useMRtAlternatives'
import type { MMapAreaProps } from '../MTripShell'
import type { Poi } from '../../../../components/Map/poiCategories'
import type { ViewportPadding } from '../../../../utils/mapViewport'
/** One array, so an explore set switched off does not move every pin on the stage. */
const NO_POIS: Poi[] = []
@@ -25,6 +27,71 @@ const NO_POIS: Poi[] = []
*/
const COMPASS_LEFT = MAP_LAYER_SWITCHER_INSET + MAP_ROUND_CONTROL_SIZE + 8
/** The safe-area insets at the top and the bottom of the screen, in pixels. */
interface SafeInsets {
top: number
bottom: number
}
const NO_INSETS: SafeInsets = { top: 0, bottom: 0 }
/**
* The safe-area insets as numbers, read off a probe that is padded by them.
*
* The frame handed to the map engine is pixels, and `env()` only resolves inside CSS. On a
* phone with a notch the chrome sits a status bar lower (and a home indicator higher) than
* its classes spell out, so a frame worked out without the insets would put the far end of
* a leg under the day chips. A computed padding is where the browser hands the resolved
* inset back. Read on mount and again on a resize, which is what turning the phone does.
*/
function useSafeInsets(probe: RefObject<HTMLElement | null>): SafeInsets {
const [insets, setInsets] = useState<SafeInsets>(NO_INSETS)
useLayoutEffect(() => {
const read = () => {
const el = probe.current
if (!el) return
const style = window.getComputedStyle(el)
const top = Number.parseFloat(style.paddingTop) || 0
const bottom = Number.parseFloat(style.paddingBottom) || 0
setInsets(prev => (prev.top === top && prev.bottom === bottom ? prev : { top, bottom }))
}
read()
window.addEventListener('resize', read)
return () => window.removeEventListener('resize', read)
}, [probe])
return insets
}
/**
* Where the roads offered for a leg are framed: in the strip of map between the day chips
* and the alternatives bar, rather than behind either of them.
*
* Both engines fit a phone with a flat margin that knows nothing of this shell's bars, and
* with the picker open those cover most of the screen: that margin would leave the leg's
* ends and their time pills under the chips and under a 174px bar. The numbers are the
* ones the classes on this screen are built from, so a change there has to be carried here.
*
* Top: the safe area, then `--m-safe-top`'s own 12px, the chip rail's 50px offset under it
* and its 42px height, then a 12px gap so a time pill at the far end is not flush against
* the rail. The search bar that sits below the rail on the stage steps away while the
* picker is open, so the rail is the lowest chrome up there.
*
* Bottom: the safe area, the dock's 74px (62px tall, 12px off the bottom), the bar's lift
* (its height and the 15px gap between the dock and its foot) and the 38px credit row
* over that. That is the very line `--bottom-nav-h` puts the round controls' band on, so
* the frame ends where they begin, and they only take the two corners of it.
*
* The sides keep the 20px both engines already give a phone: nothing floats there.
*/
function alternativesFitPadding(insets: SafeInsets): ViewportPadding {
return {
top: insets.top + 12 + 50 + 42 + 12,
right: 20,
bottom: insets.bottom + 74 + RT_ALT_BAR_LIFT + 38,
left: 20,
}
}
/** A camera focus the planner is holding, and the day that was on screen when it arrived. */
interface HeldFocus {
points: readonly [number, number][]
@@ -133,6 +200,20 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
if (focus !== heldFocus) setHeldFocus(focus)
const focusPending = focus.live && planner.mapFocusPoints.length > 0
// Handed over only once there are roads to frame, not as soon as the picker opens: the
// engines refit whatever they hold when this padding changes, and while the router is
// still thinking that is the stage, which would be flown out to a smaller frame just
// before the answer flies it to the leg. So the padding and the roads arrive in one
// render and the camera moves once, and on close both go in one render as well.
// Memoised for the reason the stage data is, the shell re-rendering on every store write.
const insetProbe = useRef<HTMLSpanElement>(null)
const insets = useSafeInsets(insetProbe)
const framingOffers = onStage && planner.alternativeOverlays.length > 0
const fitPadding = useMemo(
() => (framingOffers ? alternativesFitPadding(insets) : undefined),
[framingOffers, insets],
)
/**
* A pin on the road trip tab opens its stop: the sheet the chain row opens, not the
* place inspector.
@@ -201,9 +282,21 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
className="m-credit-corner absolute inset-0 isolate overflow-hidden bg-[color:var(--m-mapb)] [--m-map-floor:calc(env(safe-area-inset-bottom,0px)+74px+var(--m-stage-lift,0px))] [--bottom-nav-h:calc(var(--m-map-floor)+38px)]"
// 76px is the stage bar's own height plus the gap it keeps on both sides, so the
// credit lands one gap above the bar instead of on its top edge, and the round
// controls one credit row above that.
style={{ ['--m-stage-lift' as string]: onStage && mapActive ? '76px' : '0px' }}
// controls one credit row above that. While other ways of driving a leg are on offer
// their bar stands in that slot instead, taller, and the floor clears it the same way.
style={{
['--m-stage-lift' as string]: onStage && mapActive
? (planner.routeAlternatives.open ? `${RT_ALT_BAR_LIFT}px` : '76px')
: '0px',
}}
>
{/* Measures the safe area for the alternatives frame, see useSafeInsets. Out of the
flow and invisible, so it takes no room and catches no tap. */}
<span
ref={insetProbe}
aria-hidden="true"
className="pointer-events-none invisible absolute left-0 top-0 pb-[env(safe-area-inset-bottom,0px)] pt-[env(safe-area-inset-top,0px)]"
/>
<MapViewAuto
tripId={planner.tripId}
dawarichTrack={planner.dawarichTrail.track}
@@ -253,6 +346,16 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
: marker => planner.openAddPlaceFromPoi(marker, planner.selectedDayId)}
onViewportChange={poi.onViewportChange}
onMapReady={setGlMap}
// Other ways of driving the leg the stage asked about, and the one lit up.
alternativeRoutes={onStage ? planner.alternativeOverlays : undefined}
activeAlternative={onStage ? planner.highlightedAlternative : undefined}
// A tap on a road or its time pill only lights it; the bar's confirm takes it. The
// desk hands `chooseRouteAlternative` in here and previews on hover, but glass has
// no hover, so the same wiring would save a via on the very first touch of a line.
// No highlight handler either: a touch fires emulated mouse enter and leave events,
// and the leave would put out the road the tap has just lit.
onChooseAlternative={onStage ? planner.setHighlightedAlternative : undefined}
fitPadding={fitPadding}
/>
{/* Floating map chrome — only while the map view is front-most. The POI bar
@@ -1,4 +1,4 @@
import { AlertTriangle, Bike, CarFront, Footprints, Fuel, Hourglass, Moon, Pin, Plus, RotateCcw, Sunrise, X, Zap } from 'lucide-react'
import { AlertTriangle, Bike, CarFront, Footprints, Fuel, Hourglass, Moon, Pin, Plus, RotateCcw, Shuffle, Sunrise, X, Zap } from 'lucide-react'
import type { CSSProperties, ReactNode } from 'react'
import MDancingTrek from '../../../components/MDancingTrek'
import MIconBtn from '../../../components/MIconBtn'
@@ -19,9 +19,11 @@ import type { TranslationFn } from '../../../../types'
* than no badge. The rest of a stop's findings live in its sheet, written out as full
* sentences. Which mark survives is decided in `roadtripRowModel.pickWarning`, not here.
*
* Nothing in this file except a destination row reacts to a tap. Drive bands, discs,
* marks, the night block and the day-end point carry no role and no chevron, so
* nothing looks like a button that isn't one.
* Few things in the chain react to a tap, and each looks like the control it is. A
* destination row is its own tap target, a leg has one round button that asks for other
* ways of driving it, and the dry band has its reserve lamp and the offers it brings
* back. The drive pill, discs, marks, the night block and the day-end point carry no role
* and no chevron, so nothing looks like a button that isn't one.
*/
export interface RowChrome {
@@ -140,13 +142,32 @@ const LEG_ICONS: Record<string, typeof CarFront> = {
cycling: Bike,
}
/** The drive between two stops. 12px rather than the desktop's 10: a four-hour leg
* deserves the space it takes. A div, never a button: tapping a leg to pick another
* route is a desktop affordance and costs up to five routing requests. */
export function RtLegRow({ seg, mode, chrome }: {
/**
* The drive between two stops. 12px rather than the desktop's 10: a four-hour leg
* deserves the space it takes.
*
* Other ways of driving it are asked for with one 40px round button at the end of the
* row, never with the whole band as on the desktop rail. The chain scrolls under a thumb,
* and with a band-wide target the tap that only meant to stop that scroll, landing on a
* leg, would cost up to five routing requests and a jump to the map. So the pill stays a
* line of text, and the button is the one thing on the row that acts: a small, separate
* target that keeps that cost behind a gesture nobody makes by accident.
*
* Open, the button takes the inner surface and the full ink rather than filling with the
* action colour, for the reason the rail gives: a filled chip in a column of quiet rows
* reads as a button that was pressed and stuck. Offline it keeps its place but dims,
* because a choice is saved as a via and vias are online only. Without `onAlternatives`
* (no permission, or a leg that cannot be rerouted) the column stays empty.
*/
export function RtLegRow({ seg, mode, chrome, onAlternatives, alternativesOpen = false, alternativesDisabled = false }: {
seg: RouteSegment | undefined
mode: string | null
chrome: RowChrome
/** Asks for other ways of driving this leg. Absent means the leg offers none. */
onAlternatives?: () => void
/** True while the picker is open on this leg. */
alternativesOpen?: boolean
alternativesDisabled?: boolean
}) {
const { t } = chrome
const Icon = mode && LEG_ICONS[mode] ? LEG_ICONS[mode] : mode?.startsWith('plugin:') ? Zap : CarFront
@@ -161,11 +182,28 @@ export function RtLegRow({ seg, mode, chrome }: {
<span className="flex min-h-[40px] flex-col items-center" aria-hidden="true">
<span className="w-[2px] flex-1" style={{ backgroundImage: 'repeating-linear-gradient(var(--m-conn) 0 4px, transparent 4px 8px)' }} />
</span>
<span className="my-1.5 flex items-center gap-[7px] rounded-[13px] bg-[color:var(--m-ic)] px-[11px] py-[7px]">
<span className="my-1.5 flex min-w-0 items-center gap-[7px] rounded-[13px] bg-[color:var(--m-ic)] px-[11px] py-[7px]">
<Icon size={14} strokeWidth={2} className="flex-none text-m-muted" aria-hidden="true" />
<span className="truncate text-[0.75rem] font-semibold tabular-nums text-m-ink">{text}</span>
</span>
<span />
{onAlternatives ? (
<button
type="button"
onClick={onAlternatives}
disabled={alternativesDisabled}
aria-pressed={alternativesOpen}
aria-label={t('roadtrip.alt.ask')}
className={`grid h-10 w-10 flex-none place-items-center rounded-full border disabled:opacity-35 ${
alternativesOpen
? 'border-[color:var(--m-inbr)] bg-[color:var(--m-inner)] text-m-ink'
: 'border-transparent bg-[color:var(--m-ic)] text-m-muted'
}`}
>
<Shuffle size={16} strokeWidth={2} aria-hidden="true" />
</button>
) : (
<span />
)}
</div>
)
}
@@ -246,8 +284,9 @@ export function RtDryRow({ intoLegKm, chrome, electric, onSearch, offline, refue
>
<div className="flex min-h-[44px] items-center gap-2.5">
{/* Renamed on this span only, never on the band: the offers below are drawn in
--m-ink too, and they have to stay ink. Not a tap target either, because
nothing in the chain but a destination row reacts to a tap. */}
--m-ink too, and they have to stay ink. Not a tap target either: the lamp at
the end of this line is its one control, and a mascot that reacted too would
be a second one that looks like none. */}
<span
className="pointer-events-none flex flex-none"
style={{ '--m-ink': 'var(--m-st-danger)', '--m-bg': DRY_GROUND } as CSSProperties}
@@ -3,7 +3,9 @@ import { AlertTriangle, MapPin, Navigation } from 'lucide-react'
import { useMPlanDaySwipe } from '../plan/useMPlanDaySwipe'
import { showStopOnMap, useMRoadtrip } from './useMRoadtrip'
import { useMRtCorridor } from './useMRtCorridor'
import { useMRtAlternatives } from './useMRtAlternatives'
import MRtCorridorBar from './MRtCorridorBar'
import MRtAlternativesBar from './MRtAlternativesBar'
import { RtAutoRow, RtDryRow, RtLegRow, RtSpillRow, RtStopRow, type RowChrome } from './MRoadtripRows'
import { badgeLabel, distanceBadge } from './stageBadges'
import MBadge from '../../../components/MBadge'
@@ -17,7 +19,7 @@ import { useSettingsStore } from '../../../../store/settingsStore'
import { formatDistance } from '../../../../utils/units'
import { isRtlLanguage } from '../../../../i18n'
import type { MTripTabPanelProps } from '../MTripShell'
import type { StopRow } from '../../../../components/Roadtrip/roadtripRowModel'
import { legReroutable, type StopRow } from '../../../../components/Roadtrip/roadtripRowModel'
/**
* The road trip tab: one day of the drive, as a chain or on the map.
@@ -38,6 +40,9 @@ export default function MRoadtripTab({ planner, shell }: MTripTabPanelProps) {
const cardRef = useRef<HTMLDivElement>(null)
const rt = useMRoadtrip(planner)
const corridor = useMRtCorridor(planner, shell)
// Called once here and handed down, like `rt`: the chain's leg buttons and the bar over
// the map read one controller, so a leg shows pressed for exactly the picker on the map.
const alts = useMRtAlternatives(planner, shell)
const unit = useSettingsStore(s => s.settings.distance_unit)
const chrome: RowChrome = { t, unit }
@@ -81,10 +86,15 @@ export default function MRoadtripTab({ planner, shell }: MTripTabPanelProps) {
// ── Map half: the two bars, and nothing else. Everything between them belongs to the
// map instance the shell keeps mounted, so this layer must not swallow taps.
//
// While other ways of driving a leg are on offer, their bar takes the stage bar's slot
// and the search bar steps away. The picker is modal on the map: its lines are the
// question on screen, a corridor search started under it would draw its pins over
// them, and the band it frees at the top is room the leg is framed into.
if (shell.rtView === 'map') {
return (
<div className="pointer-events-none absolute inset-0 z-20">
{searchBar}
{!alts.open && searchBar}
{/* Just above the dock, the same gap everything else on this shell keeps from
it. Twenty pixels higher left a band of map between the two that read as a
gap rather than as breathing room, and pushed the map's own buttons into
@@ -93,7 +103,9 @@ export default function MRoadtripTab({ planner, shell }: MTripTabPanelProps) {
{/* `rt` is handed down rather than looked up again: useMRoadtrip owns a
30s interval and a network subscription, and a second call would run a
second pair of them for the same screen. */}
<StageBar planner={planner} rt={rt} onOpen={openStop} />
{alts.open
? <MRtAlternativesBar planner={planner} alts={alts} />
: <StageBar planner={planner} rt={rt} onOpen={openStop} />}
</div>
</div>
)
@@ -197,7 +209,22 @@ export default function MRoadtripTab({ planner, shell }: MTripTabPanelProps) {
<section className="mt-2.5 overflow-hidden rounded-[22px] border border-[color:var(--m-cbr)] bg-[color:var(--m-card)] px-3.5 pb-3 pt-1">
{rt.rows.map((row, i) => {
if (row.kind === 'stop') return <RtStopRow key={`s${i}`} row={row} chrome={chrome} onOpen={() => openStop(row)} />
if (row.kind === 'leg') return <RtLegRow key={`l${i}`} seg={row.seg} mode={row.mode} chrome={chrome} />
if (row.kind === 'leg') {
// Only where the desk rail offers it too (legReroutable), and with the
// card's day id, the one the desk passes: the planner finds the day each
// stop is stored on by itself.
return (
<RtLegRow
key={`l${i}`}
seg={row.seg}
mode={row.mode}
chrome={chrome}
onAlternatives={alts.canAsk && legReroutable(stage, row.index) ? () => alts.ask(stage.dayId, row.index) : undefined}
alternativesOpen={alts.isOpenFor(stage.dayId, row.index)}
alternativesDisabled={!alts.editable}
/>
)
}
if (row.kind === 'auto') return <RtAutoRow key={`a${i}`} phase={row.phase} time={row.time} chrome={chrome} />
if (row.kind === 'spill') {
return <RtSpillRow key={`p${i}`} fromDayNumber={row.fromDayNumber} departs={row.departs} chrome={chrome} />
@@ -0,0 +1,178 @@
import { AlertTriangle, Check, Loader2, Shuffle, X } from 'lucide-react'
import MBadge from '../../../components/MBadge'
import MIconBtn from '../../../components/MIconBtn'
import { alternativeSubline, type AlternativeOverlay } from '../../../../components/Roadtrip/alternativeOverlays'
import { useSettingsStore } from '../../../../store/settingsStore'
import { formatDistance } from '../../../../utils/units'
import { badgeLabel } from './stageBadges'
import { RT_ALT_BAR_HEIGHT, type MRtAlternativesController } from './useMRtAlternatives'
import type { TripPlanner } from '../MTripShell'
export interface MRtAlternativesBarProps {
planner: TripPlanner
alts: MRtAlternativesController
}
/**
* The ways of driving one leg, over the map that draws them.
*
* It takes the stage bar's slot rather than a sheet: the answer is the lines on the map,
* and a sheet big enough for three offers would cover the very roads it asks about.
*
* Three rows at fixed heights, because the map lifts its credit and its round controls by
* this bar's height (RT_ALT_BAR_LIFT), and a bar that grew with its text would slide under
* them. So every line truncates or clamps instead of wrapping into another row.
*
* A chip previews and the button takes. The chip lights its road on the map, and so does
* a tap on the line itself; nothing is written until the confirm, which stays off until a
* road other than the one already driven is picked. The chips go quiet while the choice
* is being saved, so a second tap cannot pick another road under a write in flight.
*/
export default function MRtAlternativesBar({ planner, alts }: MRtAlternativesBarProps) {
const { t } = planner
const title = t('roadtrip.alt.title')
return (
<section
aria-label={title}
className="flex flex-col gap-2 rounded-[22px] border border-[color:var(--m-cbr)] bg-[color:var(--m-card)] px-[14px] py-[11px] shadow-[0_16px_44px_-14px_rgba(0,0,0,.35)] backdrop-blur-[24px] backdrop-saturate-[1.6]"
style={{ height: RT_ALT_BAR_HEIGHT }}
>
<div className="flex h-8 flex-none items-center gap-2">
<Shuffle size={14} strokeWidth={2} className="flex-none text-m-muted" aria-hidden="true" />
<span className="min-w-0 flex-1 truncate font-geist text-[0.625rem] font-bold uppercase tracking-[.09em] text-m-muted">
{title}
</span>
<MIconBtn variant="neutral" size={32} ariaLabel={t('common.close')} onClick={alts.cancel}>
<X size={15} strokeWidth={2.2} aria-hidden="true" />
</MIconBtn>
</div>
<div className="h-[58px] flex-none">
<AlternativesBody planner={planner} alts={alts} />
</div>
<div className="flex h-11 flex-none items-center gap-2.5">
{/* The desk hides this sentence in a tooltip on the chip. There is no hover here,
so it stands beside the button whose choice it qualifies. */}
{alts.picked?.otherEngine && (
<span className="line-clamp-2 min-w-0 flex-1 font-geist text-[0.65625rem] leading-[1.35] text-m-muted">
{t('roadtrip.alt.otherEngine')}
</span>
)}
<button
type="button"
onClick={alts.confirm}
disabled={!alts.canConfirm}
aria-busy={alts.saving}
// Saving keeps the fill: the button is busy with the choice, not unavailable.
className={`flex h-11 min-w-0 items-center justify-center gap-[7px] rounded-full bg-m-act px-5 text-[0.8125rem] font-semibold text-m-actfg ${
alts.saving ? '' : 'disabled:bg-[color:var(--m-ic)] disabled:text-m-faint'
} ${alts.picked?.otherEngine ? 'flex-none' : 'flex-1'}`}
>
{alts.saving
? <Loader2 size={15} strokeWidth={2.2} className="flex-none animate-spin" aria-hidden="true" />
: <Check size={15} strokeWidth={2.2} className="flex-none" aria-hidden="true" />}
<span className="truncate">{t('common.confirm')}</span>
</button>
</div>
</section>
)
}
/** The middle row: what the router said, or the roads to pick from. */
function AlternativesBody({ planner, alts }: MRtAlternativesBarProps) {
const { t } = planner
const unit = useSettingsStore(s => s.settings.distance_unit)
if (alts.phase === 'loading') {
return (
<p role="status" className="flex h-full items-center gap-2 text-[0.8125rem] font-medium text-m-muted">
<Loader2 size={15} strokeWidth={2.2} className="flex-none animate-spin" aria-hidden="true" />
<span className="truncate">{t('roadtrip.alt.loading')}</span>
</p>
)
}
if (alts.phase === 'failed') {
return (
<p role="status" className="flex h-full items-center gap-2 text-[0.8125rem] font-medium text-m-ink">
<AlertTriangle size={15} strokeWidth={2.2} className="flex-none text-[color:var(--m-st-pending)]" aria-hidden="true" />
<span className="line-clamp-2">{t('roadtrip.alt.failed')}</span>
</p>
)
}
if (alts.phase === 'onlyOne') {
// One road back is genuinely one sensible way to drive the leg, not a failure.
return (
<p role="status" className="flex h-full items-center text-[0.8125rem] font-medium text-m-muted">
<span className="line-clamp-2">{t('roadtrip.alt.onlyOne')}</span>
</p>
)
}
// No phase means no open picker. The tab mounts the bar only while one is open, so this
// is at most the render it closes in, and "only one way" there would describe no leg.
if (alts.phase !== 'choose') return null
// Scrolls sideways rather than wrapping, because the row has a fixed height. The negative
// margin lets a chip slide under the bar's own edge instead of stopping short of it.
return (
<div className="-mx-[14px] flex h-full snap-x gap-2 overflow-x-auto px-[14px]">
{alts.overlays.map(alt => (
<AlternativeChip
key={alt.index}
alt={alt}
picked={alts.picked?.index === alt.index}
disabled={alts.saving}
distance={formatDistance(alt.distance / 1000, unit)}
subline={alternativeSubline(alt, time => t('roadtrip.alt.slower', { time }))}
onPick={() => alts.pick(alt.index)}
/>
))}
</div>
)
}
/**
* One offered road: its colour, its drive time, its length and what sets it apart.
*
* The drive time comes first because it is the exact text of the pill on the map, and it
* is that text rather than the swatch that ties a chip to its line: every offer is drawn
* in the same pale blue. The distance is a badge, a figure on its own the way the stage
* bar sets its figures, and the chip spells its parts out in its name for the reason the
* stage bar does.
*/
function AlternativeChip({ alt, picked, disabled, distance, subline, onPick }: {
alt: AlternativeOverlay
picked: boolean
disabled: boolean
distance: string
subline: string
onPick: () => void
}) {
return (
<button
type="button"
onClick={onPick}
disabled={disabled}
aria-pressed={picked}
aria-label={badgeLabel([alt.label, distance, subline])}
className={`flex h-full min-w-[128px] max-w-[232px] flex-none snap-start items-center gap-2.5 rounded-[16px] border px-3 text-start disabled:opacity-60 ${
picked ? 'border-[color:var(--m-act)] bg-[color:var(--m-inner)]' : 'border-[color:var(--m-cbr)] bg-[color:var(--m-ic)]'
}`}
>
<span
aria-hidden="true"
className="h-3 w-3 flex-none rounded-full"
// theme-lint-disable: the very colour this road is drawn in on the map, see alternativeColors.ts.
style={{ background: alt.color }}
/>
<span className="min-w-0 flex-1">
<span className="flex min-w-0 items-center gap-1.5">
<span className="truncate text-[0.8125rem] font-semibold tabular-nums text-m-ink">{alt.label}</span>
<MBadge caps={false}>{distance}</MBadge>
</span>
<span className="mt-[3px] block truncate font-geist text-[0.6875rem] text-m-muted">{subline}</span>
</span>
</button>
)
}
@@ -0,0 +1,136 @@
import { useEffect, useTransition } from 'react'
import { alternativesPhase, type AlternativeOverlay, type AlternativesPhase } from '../../../../components/Roadtrip/alternativeOverlays'
import type { LegAlternatives } from '../../../../components/Roadtrip/useRouteAlternatives'
import type { MTripShellApi, TripPlanner } from '../MTripShell'
/**
* The alternatives bar's fixed height, in pixels. MRtAlternativesBar is drawn at exactly
* this, and the map floor below is worked out from it, so the two cannot drift apart.
*/
export const RT_ALT_BAR_HEIGHT = 174
/**
* How far the map floor rises while the alternatives bar stands over the dock, in pixels.
*
* The bar's height plus the same 15px the 76px stage lift adds to the 61px stage bar: the
* gap between the top of the dock and the foot of a bar standing over it. So the floor
* lands on this bar's top edge as it lands on that one's, and the credit and the round
* controls clear this bar the way they clear that one.
*
* A number rather than a CSS length because the map's fit padding is added up from it.
* Kept in this module rather than in the bar's, so the map area reads it without pulling
* a component in.
*/
export const RT_ALT_BAR_LIFT = RT_ALT_BAR_HEIGHT + 15
export interface MRtAlternativesController {
/** The leg being reconsidered and what came back for it. Null while no picker is open. */
open: LegAlternatives | null
/** The very overlays the map draws, so a chip and its line can never disagree. */
overlays: AlternativeOverlay[]
/** Which of its four states the open picker is in. Null while none is open. */
phase: AlternativesPhase | null
/** The road a tap is previewing, lit on the map and waiting for confirm. */
picked: AlternativeOverlay | null
/** May this person reshape the drive at all. Without it no leg offers the question. */
canAsk: boolean
/** False offline: a choice is written as a via, and vias are online only. */
editable: boolean
canConfirm: boolean
/** True while the chosen road is being written. */
saving: boolean
isOpenFor: (dayId: number, legIndex: number) => boolean
ask: (dayId: number, legIndex: number) => void
pick: (index: number) => void
confirm: () => void
cancel: () => void
}
/**
* Other ways of driving a leg, as a phone asks for them and takes one.
*
* Holds no picker state of its own. The road trip tab is mounted in two places, one per
* half of the list and map switch, so it remounts on every toggle, and a picker living
* here would be gone the moment somebody looked back at the chain. Everything stays in
* the planner, where the desk keeps it too: the open leg, the offers, the overlays and
* the road lit on the map. What this adds is what a desk does not need.
*
* A tap previews and a confirm takes. On the desk a pointer hovers to preview and a
* click writes; glass has no hover, so the first touch on a chip or a line would already
* be the write. Here that touch only lights the road (`pick`), and the bar's button
* commits it (`confirm`).
*
* The question is always about the leg on screen. Asking goes to the map, where the
* answer is drawn, and a stage change closes the picker, because offers drawn for a leg
* of another day are lines nobody on this stage asked about.
*/
export function useMRtAlternatives(planner: TripPlanner, shell: MTripShellApi): MRtAlternativesController {
const { open, close } = planner.routeAlternatives
const overlays = planner.alternativeOverlays
const editable = planner.roadtripVias.editable
const [saving, startSaving] = useTransition()
const phase = open ? alternativesPhase(open, overlays) : null
const highlighted = planner.highlightedAlternative
const picked = highlighted == null ? null : overlays.find(o => o.index === highlighted) ?? null
// The road already driven is no choice: taking it writes nothing and only closes the
// picker, which the close button already does without pretending to save.
const canConfirm = !!picked && phase === 'choose' && !open?.routes[picked.index]?.current && editable && !saving
const isOpenFor = (dayId: number, legIndex: number) => open?.dayId === dayId && open.index === legIndex
// The day chips, a swipe and the all days switch all move the stage under an open
// picker. `close` is the planner's stable callback, so this runs when the leg or the
// stage changes and not on every render.
const selectedDayId = planner.selectedDayId
useEffect(() => {
if (open && open.dayId !== selectedDayId) close()
}, [open, selectedDayId, close])
const ask = (dayId: number, legIndex: number) => {
// The planner's own ask toggles a leg that is already open, which is the desk
// button's second click. Here the pressed button on the chain is the way back to the
// answer on the map, so it must not close what it is pointing at.
if (!isOpenFor(dayId, legIndex)) {
// A pick belongs to the leg it was made on. Carried over, it would light a road
// on the next leg by its position in a list that leg never offered.
planner.setHighlightedAlternative(null)
// An open fuel search keeps the camera on its stations (see mapFocusPoints), so the
// leg would be asked about and never framed. The picker is modal on the map anyway.
planner.refuel.close()
// The card's day, as the desk passes it: the planner looks the stops up on that
// card and works out the day each one is stored on by itself.
planner.askRouteAlternatives(dayId, legIndex)
}
if (shell.rtView === 'list') shell.toggleRtView()
}
const pick = (index: number) => planner.setHighlightedAlternative(index)
const confirm = () => {
if (!canConfirm || !picked) return
const index = picked.index
// A transition rather than a flag of our own, so the pending state ends when the
// write does. The planner reports a failure itself and leaves the picker open for
// another go, and closes it once the via is saved.
startSaving(async () => {
await planner.chooseRouteAlternative(index)
})
}
return {
open,
overlays,
phase,
picked,
canAsk: planner.can('day_edit', planner.trip),
editable,
canConfirm,
saving,
isOpenFor,
ask,
pick,
confirm,
cancel: close,
}
}