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
@@ -1074,6 +1074,50 @@ describe('MapView bounds fitting', () => {
rerender(<MapView places={places} fitKey={2} />)
expect(mapMock.fitBounds).not.toHaveBeenCalled()
})
it('FE-COMP-MAPVIEW-078: a caller padding frames the focus points instead of the phone margin, and the day fit keeps its own', () => {
// A phone shell lays a chip rail over the top of the map and a bar plus the dock over
// the bottom. The flat margin put the ends of a framed leg under either of them.
Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 420 })
const leg: [number, number][] = [[48.1, 2.1], [48.3, 2.4]]
const chrome = { top: 120, right: 16, bottom: 290, left: 16 }
const { rerender } = render(<MapView places={[]} fitKey={1} />)
expect(mapMock.fitBounds).not.toHaveBeenCalled()
rerender(<MapView places={[]} fitKey={1} focusPoints={leg} fitPadding={chrome} />)
expect(mapMock.fitBounds).toHaveBeenCalledTimes(1)
expect(mapMock.fitBounds.mock.calls[0][1]).toMatchObject({ paddingTopLeft: [16, 120], paddingBottomRight: [16, 290] })
// Picking a day is not the caller's frame, so that fit keeps the phone margin.
const places = [buildMapPlace({ id: 1, lat: 48, lng: 2 }), buildMapPlace({ id: 2, lat: 48.2, lng: 2.2 })]
rerender(<MapView places={places} fitKey={2} focusPoints={leg} fitPadding={chrome} />)
expect(mapMock.fitBounds).toHaveBeenCalledTimes(2)
expect(mapMock.fitBounds.mock.calls[1][1]).toMatchObject({ paddingTopLeft: [40, 20], paddingBottomRight: [40, 20] })
// And without one, the focus fit falls back to that margin too.
const stage: [number, number][] = [[47, 1], [47.5, 1.5]]
rerender(<MapView places={places} fitKey={2} focusPoints={stage} />)
expect(mapMock.fitBounds).toHaveBeenCalledTimes(3)
expect(mapMock.fitBounds.mock.calls[2][1]).toMatchObject({ paddingTopLeft: [40, 20], paddingBottomRight: [40, 20] })
})
it('FE-COMP-MAPVIEW-079: the caller padding is read by value, so only new numbers refit the points on screen', () => {
const leg: [number, number][] = [[48.1, 2.1], [48.3, 2.4]]
const { rerender } = render(
<MapView places={[]} fitKey={1} focusPoints={leg} fitPadding={{ top: 120, right: 16, bottom: 290, left: 16 }} />,
)
expect(mapMock.fitBounds).toHaveBeenCalledTimes(1)
// A parent that builds the object inline hands a new one on every render. The camera
// belongs to the traveller between fits, so that alone must not take it back.
rerender(<MapView places={[]} fitKey={1} focusPoints={leg} fitPadding={{ top: 120, right: 16, bottom: 290, left: 16 }} />)
expect(mapMock.fitBounds).toHaveBeenCalledTimes(1)
// New numbers mean the chrome moved, so the same points are framed again around it.
rerender(<MapView places={[]} fitKey={1} focusPoints={leg} fitPadding={{ top: 120, right: 16, bottom: 98, left: 16 }} />)
expect(mapMock.fitBounds).toHaveBeenCalledTimes(2)
expect(mapMock.fitBounds.mock.calls[1][1]).toMatchObject({ paddingTopLeft: [16, 120], paddingBottomRight: [16, 98] })
})
})
describe('MapView photo thumbnails', () => {
+30 -10
View File
@@ -401,15 +401,33 @@ interface BoundsControllerProps {
* needs that leg on screen, which is neither the day nor the trip.
*/
focusPoints?: [number, number][]
/**
* What the caller's own chrome covers while `focusPoints` is framed, in pixels per edge.
*
* `paddingOpts` knows the planner's panels and nothing else, and on a phone it is a flat
* margin. A shell that lays its own bars over the map passes what they cover, so the
* frame lands in the part still visible. Only the fit on `focusPoints` reads it.
* Compared by value: the same numbers in a new object do not refit, while new numbers
* refit the points already handed over, because the chrome they must clear has moved.
*/
fitPadding?: ViewportPadding
}
function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMount = false, focusPoints }: BoundsControllerProps) {
/** A padding box as Leaflet's fit options spell it, corner pairs rather than edges. */
function leafletPadding(box: ViewportPadding): L.FitBoundsOptions {
return {
paddingTopLeft: [box.left, box.top],
paddingBottomRight: [box.right, box.bottom],
}
}
function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMount = false, focusPoints, fitPadding }: BoundsControllerProps) {
const map = useMap()
const prevFitKey = useRef(-1)
const awaitingRoute = useRef(false)
const fitRan = useRef(false)
const fitTo = useCallback((coords: [number, number][]) => {
const fitTo = useCallback((coords: [number, number][], padding: L.FitBoundsOptions = paddingOpts) => {
if (coords.length === 0) return
try {
const bounds = L.latLngBounds(coords)
@@ -428,7 +446,7 @@ function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMo
* (#1982). MapViewGL never had the nudge, so this also brings the two
* renderers back into agreement.
*/
map.fitBounds(bounds, { ...paddingOpts, maxZoom: 16, animate: true })
map.fitBounds(bounds, { ...padding, maxZoom: 16, animate: true })
}
} catch {}
}, [map, paddingOpts])
@@ -460,14 +478,18 @@ function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMo
fitTo([...places.map(p => [p.lat, p.lng] as [number, number]), ...routeCoords])
}, [routeCoords]) // eslint-disable-line react-hooks/exhaustive-deps
// The caller's padding as a value, so a parent that builds the object inline on every
// render does not move the camera each time it renders.
const fitPaddingKey = fitPadding ? [fitPadding.top, fitPadding.right, fitPadding.bottom, fitPadding.left].join(' ') : ''
// Frame whatever was handed over. Nothing happens when it empties, so closing the
// picker leaves the map where the user left it rather than snapping back.
useEffect(() => {
if (!focusPoints?.length) return
// A day fit that has not run yet must not overwrite this a moment later.
awaitingRoute.current = false
fitTo(focusPoints)
}, [focusPoints]) // eslint-disable-line react-hooks/exhaustive-deps
fitTo(focusPoints, fitPadding ? leafletPadding(fitPadding) : paddingOpts)
}, [focusPoints, fitPaddingKey]) // eslint-disable-line react-hooks/exhaustive-deps
return null
}
@@ -687,6 +709,7 @@ export const MapView = memo(function MapView({
onRemoveVia,
alternativeRoutes,
focusPoints,
fitPadding,
clusterLoosely = false,
activeAlternative,
onChooseAlternative,
@@ -748,10 +771,7 @@ export const MapView = memo(function MapView({
}
}, [leftWidth, rightWidth, hasInspector, hasDayDetail])
const paddingOpts = useMemo((): L.FitBoundsOptions => ({
paddingTopLeft: [paddingBox.left, paddingBox.top],
paddingBottomRight: [paddingBox.right, paddingBox.bottom],
}), [paddingBox])
const paddingOpts = useMemo(() => leafletPadding(paddingBox), [paddingBox])
// Open framed on the places rather than on the caller's default, so a trip in Japan shows
// Japan straight away instead of the world view followed by a flight across the planet.
@@ -1070,7 +1090,7 @@ export const MapView = memo(function MapView({
)}
<MapController center={center} zoom={zoom} />
<BoundsController places={dayPlaces.length > 0 ? dayPlaces : places} routeCoords={dayPlaces.length > 0 ? routeCoords : []} fitKey={fitKey} paddingOpts={paddingOpts} framedOnMount={initialView.framed} focusPoints={focusPoints} />
<BoundsController places={dayPlaces.length > 0 ? dayPlaces : places} routeCoords={dayPlaces.length > 0 ? routeCoords : []} fitKey={fitKey} paddingOpts={paddingOpts} framedOnMount={initialView.framed} focusPoints={focusPoints} fitPadding={fitPadding} />
<SelectionController places={places} selectedPlaceId={selectedPlaceId} dayPlaces={dayPlaces} paddingOpts={paddingOpts} />
<MapClickHandler onClick={onMapClick} />
<MapContextMenuHandler onContextMenu={onMapContextMenu} />
@@ -2196,6 +2196,62 @@ describe('MapViewGL', () => {
)
expect(glMap.addSource).not.toHaveBeenCalledWith('trip-satellite', expect.anything())
})
it('FE-COMP-MAPVIEWGL-085: a caller padding frames the focus points instead of the phone margin, and the day fit keeps its own', async () => {
// A phone shell lays a chip rail over the top of the map and a bar plus the dock over
// the bottom. The flat 40px margin put the ends of a framed leg under either of them.
const original = window.innerWidth
Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 420 })
try {
const leg: [number, number][] = [[48.1, 2.1], [48.3, 2.4]]
const chrome = { top: 120, right: 16, bottom: 290, left: 16 }
const { rerender } = render(<MapViewGL places={[]} fitKey={1} />)
await act(async () => {})
expect(glMap.fitBounds).not.toHaveBeenCalled()
rerender(<MapViewGL places={[]} fitKey={1} focusPoints={leg} fitPadding={chrome} />)
await act(async () => {})
expect(glMap.fitBounds).toHaveBeenCalledTimes(1)
expect(glMap.fitBounds.mock.calls[0][1]).toMatchObject({ padding: chrome, maxZoom: 15 })
// Picking a day is not the caller's frame, so that fit keeps the phone margin.
const places = [buildMapPlace({ id: 88, lat: 48.1, lng: 2.1 }), buildMapPlace({ id: 89, lat: 48.2, lng: 2.2 })]
rerender(<MapViewGL places={places} fitKey={2} focusPoints={leg} fitPadding={chrome} />)
await act(async () => {})
expect(glMap.fitBounds).toHaveBeenCalledTimes(2)
expect(glMap.fitBounds.mock.calls[1][1]).toMatchObject({ padding: { top: 40, right: 20, bottom: 40, left: 20 } })
// And without one, the focus fit falls back to that margin too.
const stage: [number, number][] = [[47, 1], [47.5, 1.5]]
rerender(<MapViewGL places={places} fitKey={2} focusPoints={stage} />)
await act(async () => {})
expect(glMap.fitBounds).toHaveBeenCalledTimes(3)
expect(glMap.fitBounds.mock.calls[2][1]).toMatchObject({ padding: { top: 40, right: 20, bottom: 40, left: 20 } })
} finally {
Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: original })
}
})
it('FE-COMP-MAPVIEWGL-086: the caller padding is read by value, so only new numbers refit the points on screen', async () => {
const leg: [number, number][] = [[48.1, 2.1], [48.3, 2.4]]
const { rerender } = render(
<MapViewGL places={[]} fitKey={1} focusPoints={leg} fitPadding={{ top: 120, right: 16, bottom: 290, left: 16 }} />,
)
await act(async () => {})
expect(glMap.fitBounds).toHaveBeenCalledTimes(1)
// A parent that builds the object inline hands a new one on every render. The camera
// belongs to the traveller between fits, so that alone must not take it back.
rerender(<MapViewGL places={[]} fitKey={1} focusPoints={leg} fitPadding={{ top: 120, right: 16, bottom: 290, left: 16 }} />)
await act(async () => {})
expect(glMap.fitBounds).toHaveBeenCalledTimes(1)
// New numbers mean the chrome moved, so the same points are framed again around it.
rerender(<MapViewGL places={[]} fitKey={1} focusPoints={leg} fitPadding={{ top: 120, right: 16, bottom: 98, left: 16 }} />)
await act(async () => {})
expect(glMap.fitBounds).toHaveBeenCalledTimes(2)
expect(glMap.fitBounds.mock.calls[1][1]).toMatchObject({ padding: { top: 120, right: 16, bottom: 98, left: 16 } })
})
})
describe('MapViewGL attribution', () => {
const flushFrames = () => act(async () => { await new Promise(resolve => setTimeout(resolve, 40)) })
+18 -3
View File
@@ -40,7 +40,7 @@ import { resolveTrackColor, hasManualTrackColor } from './trackColors'
import { buildPoiPopupHtml } from './placePopup'
import { pluginsApi, type PluginMapMarker, type PluginMapLayer } from '../../api/client'
import { DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM, SATELLITE_TILE_URL, SATELLITE_TILE_ATTRIBUTION, SATELLITE_TILE_MAXZOOM } from '../../constants/mapDefaults'
import { computeMapViewport, TILE_SIZE_GL } from '../../utils/mapViewport'
import { computeMapViewport, TILE_SIZE_GL, type ViewportPadding } from '../../utils/mapViewport'
function categoryIconSvg(iconName: string | null | undefined, size: number): string {
const IconComponent = (iconName && CATEGORY_ICON_MAP[iconName]) || CATEGORY_ICON_MAP['MapPin']
@@ -185,6 +185,16 @@ interface Props {
* needs that leg on screen, which is neither the day nor the trip.
*/
focusPoints?: [number, number][]
/**
* What the caller's own chrome covers while `focusPoints` is framed, in pixels per edge.
*
* The default padding knows this component's panels and nothing else, and on a phone it
* is a flat margin. A shell that lays its own bars over the map passes what they cover,
* so the frame lands in the part still visible. Only the fit on `focusPoints` reads it.
* Compared by value: the same numbers in a new object do not refit, while new numbers
* refit the points already handed over, because the chrome they must clear has moved.
*/
fitPadding?: ViewportPadding
/**
* Let markers stay apart longer than usual.
*
@@ -656,6 +666,7 @@ export function MapViewGL({
zoom = DEFAULT_MAP_ZOOM,
fitKey = 0,
focusPoints,
fitPadding,
clusterLoosely = false,
hazards,
dawarichTrack = null,
@@ -2206,6 +2217,10 @@ export function MapViewGL({
if (routeArrivedForPendingFit) pendingRouteFitRef.current = null
}, [fitKey, routeFitKey]) // eslint-disable-line react-hooks/exhaustive-deps
// The caller's padding as a value, so a parent that builds the object inline on every
// render does not move the camera each time it renders.
const fitPaddingKey = fitPadding ? [fitPadding.top, fitPadding.right, fitPadding.bottom, fitPadding.left].join(' ') : ''
// Frame whatever was handed over. Nothing happens when it empties, so closing the
// picker leaves the map where the user left it rather than snapping back.
useEffect(() => {
@@ -2217,13 +2232,13 @@ export function MapViewGL({
pendingRouteFitRef.current = null
try {
map.fitBounds(bounds, {
padding: paddingOpts,
padding: fitPadding ?? paddingOpts,
maxZoom: 15,
pitch: enableMapbox3d ? 45 : 0,
duration: 400,
})
} catch { /* noop */ }
}, [focusPoints]) // eslint-disable-line react-hooks/exhaustive-deps
}, [focusPoints, fitPaddingKey]) // eslint-disable-line react-hooks/exhaustive-deps
// flyTo selected place
useEffect(() => {
@@ -4,9 +4,8 @@ import { useTranslation } from '../../i18n/TranslationContext'
import { Tooltip } from '../shared/Tooltip'
import { useSettingsStore } from '../../store/settingsStore'
import { formatDistance } from '../../utils/units'
import { formatDurationShort } from './roadtripModel'
import type { LegAlternatives } from './useRouteAlternatives'
import type { AlternativeOverlay } from './alternativeOverlays'
import { alternativesPhase, alternativeSubline, type AlternativeOverlay } from './alternativeOverlays'
interface RoadtripAlternativesBarProps {
open: LegAlternatives | null
@@ -35,6 +34,7 @@ export default function RoadtripAlternativesBar({
const { t } = useTranslation()
const distanceUnit = useSettingsStore(s => s.settings.distance_unit)
if (!open) return null
const phase = alternativesPhase(open, overlays)
return (
<div className="pointer-events-auto flex max-w-[min(92vw,640px)] flex-col gap-2 rounded-2xl border border-edge-faint bg-surface-elevated px-3 py-2.5 shadow-modal backdrop-blur">
@@ -53,14 +53,14 @@ export default function RoadtripAlternativesBar({
</button>
</div>
{open.loading ? (
{phase === 'loading' ? (
<p className="text-caption text-content-muted">{t('roadtrip.alt.loading')}</p>
) : open.error ? (
) : phase === 'failed' ? (
<p className="flex items-start gap-1.5 text-caption text-warning">
<AlertTriangle size={12} className="mt-0.5 shrink-0" aria-hidden />
{t('roadtrip.alt.failed')}
</p>
) : overlays.length < 2 ? (
) : phase === 'onlyOne' ? (
// One route back means there is genuinely only one sensible way to drive it.
<p className="text-caption text-content-muted">{t('roadtrip.alt.onlyOne')}</p>
) : (
@@ -88,9 +88,7 @@ export default function RoadtripAlternativesBar({
{formatDistance(alt.distance / 1000, distanceUnit)}
</span>
<span className="text-caption tabular-nums text-content-muted">
{alt.note
? alt.note
: t('roadtrip.alt.slower', { time: formatDurationShort(alt.slowerThanQuickest) })}
{alternativeSubline(alt, time => t('roadtrip.alt.slower', { time }))}
</span>
</span>
{/* Only where the drive time on the map came from the other engine. The
@@ -17,6 +17,7 @@ import { formatDistance } from '../../utils/units'
import { formatDate, formatClockTime } from '../../utils/formatters'
import { formatDurationShort, isServiceStopType, serviceColor, type ScheduleEntry, type ScheduleWarning, refuelsRange } from './roadtripModel'
import { STOP_KIND_BY_KEY } from './stopKinds'
import { legReroutable } from './roadtripRowModel'
import { spurWorthLabelling } from './accessSpur'
import StopKindPicker from './StopKindPicker'
import StopFillPicker from './StopFillPicker'
@@ -1416,7 +1417,7 @@ function DaySection({ day, selectedAssignmentId, onSelectStop, onReorderStop, on
{i < last && (!day.stops[i + 1].automaticNight || day.legs[i]?.distance !== 0) ? (
<DriveBand
leg={day.legs[i]}
onAskAlternatives={onAskAlternatives && !day.stops[i + 1].automaticNight ? () => onAskAlternatives(day.dayId, i) : undefined}
onAskAlternatives={onAskAlternatives && legReroutable(day, i) ? () => onAskAlternatives(day.dayId, i) : undefined}
alternativesOpen={openAlternatives?.dayId === day.dayId && openAlternatives.index === i}
/>
) : null}
@@ -1,10 +1,11 @@
import { describe, it, expect } from 'vitest'
import { buildAlternativeOverlays } from './alternativeOverlays'
import { alternativeSubline, alternativesPhase, buildAlternativeOverlays, type AlternativeOverlay } from './alternativeOverlays'
import { formatDurationShort } from './roadtripModel'
import { ALT_PRIMARY, ALT_SECONDARY, ALT_LABEL_PRIMARY_BG, ALT_LABEL_SECONDARY_BG } from './alternativeColors'
import type { RouteAlternative } from '../Map/RouteCalculator'
/**
* FE-ALTOVL-001..010 — turning the router's answers into something drawable.
* FE-ALTOVL-001..017: turning the router's answers into something drawable.
*
* Two decisions live here and neither is cosmetic: which of the offered roads is
* drawn as the one you are on, and where each label hangs. A label anchored on a
@@ -221,3 +222,36 @@ describe('buildAlternativeOverlays', () => {
expect(out[1].color).toBe(ALT_SECONDARY)
})
})
describe('alternativesPhase', () => {
const two = buildAlternativeOverlays([alt({ coordinates: line(20, 0) }), alt({ coordinates: line(20, 1) })], LABELS)
it('FE-ALTOVL-016: asking beats a failure, a failure beats an empty list, and only two roads are a choice', () => {
// A new question replaces the old answer and its error with it.
expect(alternativesPhase({ loading: true, error: true }, two)).toBe('loading')
expect(alternativesPhase({ loading: true, error: false }, [])).toBe('loading')
// A router that will not answer is not a leg with one sensible way.
expect(alternativesPhase({ loading: false, error: true }, [])).toBe('failed')
expect(alternativesPhase({ loading: false, error: true }, two)).toBe('failed')
expect(alternativesPhase({ loading: false, error: false }, [])).toBe('onlyOne')
expect(alternativesPhase({ loading: false, error: false }, two.slice(0, 1))).toBe('onlyOne')
expect(alternativesPhase({ loading: false, error: false }, two)).toBe('choose')
})
})
describe('alternativeSubline', () => {
const overlay = (over: Partial<AlternativeOverlay>): AlternativeOverlay => ({
...buildAlternativeOverlays([alt({ coordinates: line(20, 0) }), alt({ coordinates: line(20, 1) })], LABELS)[1],
...over,
})
it('FE-ALTOVL-017: an offer is named by what it is, and only a plain one by how much slower it is', () => {
const slower = (time: string) => `${time} slower`
for (const note of ['No motorway', 'Current', 'Fastest']) {
expect(alternativeSubline(overlay({ note, slowerThanQuickest: 1800 }), slower)).toBe(note)
}
// The caller words the difference; the figure is the same short duration the map prints.
expect(alternativeSubline(overlay({ note: '', slowerThanQuickest: 1800 }), slower))
.toBe(`${formatDurationShort(1800)} slower`)
})
})
@@ -1,6 +1,7 @@
import { formatDurationShort } from './roadtripModel'
import { ALT_PRIMARY, ALT_SECONDARY, ALT_LABEL_PRIMARY_BG, ALT_LABEL_SECONDARY_BG } from './alternativeColors'
import type { RouteAlternative } from '../Map/RouteCalculator'
import type { LegAlternatives } from './useRouteAlternatives'
/** One offered route, ready to draw: the line, its colour, and where its label sits. */
export interface AlternativeOverlay {
@@ -154,3 +155,39 @@ export function buildAlternativeOverlays(
}
})
}
/** What a picker has to say about one leg, whichever shell draws it. */
export type AlternativesPhase = 'loading' | 'failed' | 'onlyOne' | 'choose'
/**
* Which of its four states a picker is in.
*
* Both bars branch on this, so the desk and the phone cannot disagree about when a leg has
* a choice. Asking wins over a failure, because a new question replaces the old answer
* and its error with it. A failure wins over an empty list, so a router that will not
* answer is never read as a leg with only one sensible way. Fewer than two overlays is
* that single way: `buildAlternativeOverlays` draws nothing for one answer, and one road
* is not a choice.
*/
export function alternativesPhase(
open: Pick<LegAlternatives, 'loading' | 'error'>,
overlays: readonly AlternativeOverlay[],
): AlternativesPhase {
if (open.loading) return 'loading'
if (open.error) return 'failed'
return overlays.length < 2 ? 'onlyOne' : 'choose'
}
/**
* The second line an offer is listed with: what this way is, or else how much slower.
*
* Its own note wins, for the reason the note exists: a road offered because the motorway
* was left out of it is taken for that, not for its minutes. Without one the line is the
* difference to the quickest, worded by the caller (a translation this module stays free
* of). The desk bar's docstring tells what two copies of one figure once did, the driven
* road called "Fastest" beside an offer called quicker, so both bars read this line here
* instead of each keeping its own.
*/
export function alternativeSubline(alt: AlternativeOverlay, slower: (time: string) => string): string {
return alt.note || slower(formatDurationShort(alt.slowerThanQuickest))
}
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'
import {
destinationCount,
firstStopOfPlace,
legReroutable,
pickWarning,
roadtripRows,
stageClocks,
@@ -14,7 +15,7 @@ import {
import type { ScheduleEntry, ScheduleWarning } from './roadtripModel'
import type { RoadtripDay, RoadtripStop, RouteSegment } from '@trek/shared/roadtrip'
// FE-RTROW-001 to FE-RTROW-037
// FE-RTROW-001 to FE-RTROW-039
function stop(name: string, over: Partial<RoadtripStop> = {}): RoadtripStop {
return {
@@ -443,3 +444,31 @@ describe('firstStopOfPlace', () => {
expect(firstStopOfPlace([day([stop('Nacht', { placeId: 303, automaticNight: { phase: 'end', fromDayNumber: 1 } })])], 303)).toBeNull()
})
})
describe('legReroutable', () => {
it('FE-RTROW-038: a routed leg between two stops anybody chose can be offered other ways, a service stop included', () => {
const d = day([stop('Bremen'), stop('Aral', { stopType: 'fuel' }), stop('Kassel')])
expect(legReroutable(d, 0)).toBe(true)
expect(legReroutable(d, 1)).toBe(true)
})
it('FE-RTROW-039: no leg into or out of an automatic night, none without a route, none past either end', () => {
// Bremen, Kassel, automatic night, Fulda: the rail offers the first leg only.
const withNight = day([stop('Bremen'), stop('Kassel'), night(), stop('Fulda')])
expect(legReroutable(withNight, 0)).toBe(true)
// Into the marker where the window closed, and out of it again the morning after.
expect(legReroutable(withNight, 1)).toBe(false)
expect(legReroutable(withNight, 2)).toBe(false)
expect(legReroutable(day([night('start'), stop('Fulda')]), 0)).toBe(false)
// A leg the router has not answered for yet has nothing to weigh an offer against.
const unrouted = day([stop('A'), stop('B'), stop('C')], { legs: [seg(0)] })
expect(legReroutable(unrouted, 0)).toBe(true)
expect(legReroutable(unrouted, 1)).toBe(false)
// The last stop has no leg after it, whatever the legs array happens to hold.
const extra = day([stop('A'), stop('B')], { legs: [seg(0), seg(1)] })
expect(legReroutable(extra, 1)).toBe(false)
expect(legReroutable(extra, -1)).toBe(false)
})
})
@@ -152,6 +152,26 @@ export function roadtripRows(day: RoadtripDay): RoadtripRow[] {
return rows
}
/**
* Whether the leg leaving stop `index` can be offered other ways of driving it.
*
* The desktop rail's rule, kept here so the phone chain offers the button on exactly the
* legs the rail does. A leg needs a route, because an unrouted one has nothing to weigh an
* offer against. And neither of its ends may be an automatic night: that point is the
* shell's own marker for where the daily window closed, a spot somewhere along the road
* rather than a stop anyone chose. The router's offers from or to it would reshape a
* stretch of a longer drive, and the via a choice writes is filed by the position of a
* stored stop, which the marker is not. The rail draws the band out of that marker
* without the control for the same reason.
*/
export function legReroutable(day: RoadtripDay, index: number): boolean {
return index >= 0
&& index < day.stops.length - 1
&& !!day.legs[index]
&& !day.stops[index].automaticNight
&& !day.stops[index + 1].automaticNight
}
/** Stops that carry a number, for a count that agrees with the numbering above. */
export function destinationCount(day: RoadtripDay): number {
return day.stops.filter(s => !s.automaticNight && !isServiceStopType(s.stopType)).length
@@ -12,7 +12,7 @@ import type { RoadtripStop } from './useRoadtripRoutes'
import type { RoadtripVia } from '@trek/shared'
/**
* FE-ALTHOOK-001..009 — asking for other ways of driving one leg.
* FE-ALTHOOK-001..010: asking for other ways of driving one leg.
*
* The case that carries the feature: when the leg already carries vias, the road
* actually being driven is NOT among what the router offers for the two bare
@@ -147,4 +147,25 @@ describe('useRouteAlternatives', () => {
expect(signals[1].aborted).toBe(true)
expect(result.current.open).toBeNull()
})
it('FE-ALTHOOK-010: the state keeps its identity until the picker itself changes', async () => {
// The planner keys its close gate on this object. A new one per render ran that
// effect on every render, so any render at all was a chance to close the picker.
const { result, rerender } = renderHook(() => useRouteAlternatives())
const idle = result.current
rerender()
expect(result.current).toBe(idle)
act(() => { result.current.ask(4, 1, from, to, 'driving', []) })
const asking = result.current
expect(asking).not.toBe(idle)
// The functions themselves never change, only the object carrying the new `open`.
expect(asking.ask).toBe(idle.ask)
expect(asking.close).toBe(idle.close)
await waitFor(() => expect(result.current.open?.loading).toBe(false))
const answered = result.current
rerender()
expect(result.current).toBe(answered)
})
})
@@ -1,4 +1,4 @@
import { useCallback, useRef, useState } from 'react'
import { useCallback, useMemo, useRef, useState } from 'react'
import { calculateAlternatives, calculateRoute, type RouteAlternative } from '../Map/RouteCalculator'
import type { RoadtripStop } from './useRoadtripRoutes'
import type { RoadtripVia } from '@trek/shared'
@@ -108,5 +108,11 @@ export function useRouteAlternatives(): RouteAlternativesState {
})
}, [])
return { open, ask, close }
// One object for as long as nothing in it changes. The planner keys its close gate and
// the callbacks that ask, choose and focus on this state as a whole, so a fresh object
// per render re-ran that gate and rebuilt those callbacks on every render of the
// planner, whatever had caused it. Whether the picker stays open is still the gate's own
// condition to decide (a new `open` runs it either way); the memo only stops that work
// from repeating on renders that changed nothing about the picker.
return useMemo(() => ({ open, ask, close }), [open, ask, close])
}