Files
TREK/client/src/components/Roadtrip/useRouteAlternatives.ts
T
Maurice 53a422d22d fix(roadtrip): other ways come from the router that draws the leg, and a choice is saved once it holds
The picker of other ways asked OSRM with nothing avoided while the rail drives a trip
that avoids a road class through Valhalla, so the list had no current road, called a road
the rail was not on the fastest, and choosing it changed nothing. A choice was stored as
one via where the offer strayed furthest, without asking whether the router then drove
it: a point on a ferry was pulled to the pier and the drive went overland, and a way
weighed away from motorways kept the motorway after its one point. An OSRM answer standing
in for a Valhalla that did not respond was cached as the avoided road, unmarked.

The rail now hands out a router per leg with the leg's own mode, avoided classes and
engine, and its days carry the line of every leg. Offers come from that engine, and the
rail's own leg always heads the list as Current. A choice is pinned and proven against
that router with at most three pins before anything is written; a way it will not follow
is not saved and says why, with a hint when it crosses by ferry, and a leg that changed
meanwhile or a device offline writes nothing. The OSRM stand-in is filed under the plain
key only and flags the day as not avoided.
2026-09-23 11:28:24 +02:00

178 lines
7.4 KiB
TypeScript

import { useCallback, useMemo, useRef, useState } from 'react'
import { calculateAlternatives, sameRoad, type RouteAlternative, type RouteEngine } from '../Map/RouteCalculator'
import type { RailLegRoute, RailLegRouter } from './useRoadtripRoutes'
/** One offered way of driving a leg, with what it means for this trip. */
export interface OfferedRoute extends RouteAlternative {
/** True for the road the rail drives on this leg now, whatever shaped it. */
current?: boolean
/** True for the router's own preference with no vias at all. */
direct?: boolean
}
/**
* Which drive on a card a picker is asked about: the leg from stop `index` to the next one.
*
* A tagged union rather than a bare index, so the drive arriving at the head of a
* connected card can join it as a target of its own instead of borrowing an index no
* stop has.
*/
export type RailDrive = { kind: 'leg'; index: number }
/** Where the vias that shape a leg are stored: after stop `afterIndex` of day `dayId`. */
export interface ViaAnchor {
dayId: number
afterIndex: number
}
/** Which leg is being reconsidered, and what was offered for it. */
export interface LegAlternatives {
dayId: number
/** Index of the leg within the day: the drive from stop `index` to `index + 1`. */
index: number
/** Where a choice is written. Read off the stop the leg leaves, when it was asked about. */
anchor: ViaAnchor
/**
* The two stops the leg ran between when it was asked about, by assignment. A choice is
* only written while the rail still has this leg at `anchor`, so a chain that re-flowed
* in between cannot receive a road that was worked out for another one.
*/
ends: { from: number; to: number }
/** The engine the rail drives this leg with. Offers from another cannot be read against it. */
engine: RouteEngine
/** Routes the leg through pins exactly as the rail does, to check a choice before saving it. */
route: RailLegRouter['route']
routes: OfferedRoute[]
loading: boolean
error: boolean
/** The offer being checked against the rail's router and saved, or null while none is. */
proving: number | null
}
/** Everything a picker needs to know about the leg it is opened on. */
export interface AlternativesRequest {
dayId: number
index: number
from: { lat: number; lng: number }
to: { lat: number; lng: number }
/** The leg as the rail drives it now: its line, its figures, and the engine behind them. */
driven: Pick<RailLegRoute, 'coordinates' | 'distance' | 'duration'>
anchor: ViaAnchor
ends: { from: number; to: number }
/** How the rail routes this leg: mode, avoided classes, engine, and the call itself. */
router: RailLegRouter
}
export interface RouteAlternativesState {
open: LegAlternatives | null
/** Asks the rail's own router for the ways of driving this one leg. */
ask: (request: AlternativesRequest) => void
close: () => void
/**
* Marks offer `index` as being checked and saved. The signal aborts when the picker
* closes, moves to another leg, or another check starts.
*/
prove: (index: number) => AbortSignal
/** Ends a check that led to no save, leaving the picker open for another choice. */
settle: () => void
}
/**
* Other ways of driving one leg.
*
* One leg at a time, on demand, and never for the whole trip: the routers answer with
* alternatives only between exactly two coordinates, so asking for a day would mean
* breaking up the single request `splitIntoRuns` bundles it into, the optimisation that
* makes a road trip appear at once rather than trickle in.
*
* The offers come from the engine that drives the leg on the rail, with the same mode and
* the same avoided classes, and the road the rail is on heads the list as `current`,
* always, taken from the rail itself rather than asked for again. Asked for again it came
* from OSRM with nothing avoided while the rail drove Valhalla, so the list had no current
* road at all, called a road the rail was not on the fastest, and choosing it did nothing.
* An offer that is the current road is not listed a second time; if it was the router's
* own preference, the current road says so.
*/
export function useRouteAlternatives(): RouteAlternativesState {
const [open, setOpen] = useState<LegAlternatives | null>(null)
const abortRef = useRef<AbortController | null>(null)
const provingRef = useRef<AbortController | null>(null)
const stopProving = useCallback(() => {
provingRef.current?.abort()
provingRef.current = null
}, [])
const close = useCallback(() => {
abortRef.current?.abort()
abortRef.current = null
stopProving()
setOpen(null)
}, [stopProving])
const ask = useCallback((request: AlternativesRequest) => {
abortRef.current?.abort()
stopProving()
const controller = new AbortController()
abortRef.current = controller
const { dayId, index, from, to, driven, anchor, ends, router } = request
const leg = { dayId, index, anchor, ends, engine: router.engine, route: router.route, proving: null }
setOpen({ ...leg, routes: [], loading: true, error: false })
const current: OfferedRoute = {
coordinates: driven.coordinates,
distance: driven.distance,
duration: driven.duration,
divergence: null,
engine: router.engine,
current: true,
}
// A plugin's mode means nothing to the routers asked here, so its leg is offered the
// ways a car would take; the offers then carry OSRM's times, and the list says so.
const profile: 'driving' | 'walking' | 'cycling' =
router.mode === 'walking' ? 'walking' : router.mode === 'cycling' ? 'cycling' : 'driving'
void calculateAlternatives(from, to, profile, { signal: controller.signal, avoid: router.avoid })
.then(alternatives => {
if (controller.signal.aborted) return
const routes: OfferedRoute[] = [current]
alternatives.forEach((offer, i) => {
if (sameRoad(offer, current)) {
// The rail is already on the router's own preference: one entry, and it says so.
if (i === 0) current.direct = true
return
}
routes.push({ ...offer, direct: i === 0 })
})
setOpen({ ...leg, routes, loading: false, error: false })
})
.catch(() => {
if (controller.signal.aborted) return
// A router that will not answer is not worth a dialog; the leg keeps the route it
// already has and the panel says so.
setOpen({ ...leg, routes: [], loading: false, error: true })
})
}, [stopProving])
const prove = useCallback((index: number) => {
stopProving()
const controller = new AbortController()
provingRef.current = controller
setOpen(o => (o ? { ...o, proving: index } : o))
return controller.signal
}, [stopProving])
const settle = useCallback(() => {
provingRef.current = null
setOpen(o => (o ? { ...o, proving: null } : o))
}, [])
// 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, prove, settle }), [open, ask, close, prove, settle])
}