feat(roadtrip): let a day drive along an imported track

An imported GPX track was a line drawn beside the day: the map showed the
scenic route while the day kept driving the motorway, so the distance, the
drive time and every warning belonged to a road nobody was taking. Norway
publishes its scenic routes that way, and so does every touring club worth
importing from.

A track becomes a route the day takes by refinement, not by conversion. Route
through what we have, find the point of the track the road misses by the most,
make that point a via, go again. Each round roughly halves the worst miss,
because the new via lands in the middle of what the last one left unfollowed,
so a scenic route usually fits inside ten vias — and the loop stops when the
road is close enough rather than after a fixed count. Every point of the track
would route exactly and take a hundred requests; two would route in seconds
and follow nothing.

The day is routed whole per round, not leg by leg: it is a single request
already, and per-leg would multiply every round by the number of legs against
a host that answers one request a second. The track is oriented to the day
first, because half of Norway's routes are published southbound, and the legs
it covers are cleared before the new chain lands, so applying a track twice
does not stack.

Offered from the day's own badges, and only once something has been imported.
Tinted while the day carries vias: the rail draws none of them, so that badge
is the only place a drive shaped by hand differs from one the router picked.
This commit is contained in:
Maurice
2026-09-05 00:22:44 +02:00
committed by Maurice
parent 620f4c6ecd
commit 761ec4e66f
35 changed files with 1807 additions and 3 deletions
@@ -509,6 +509,34 @@ describe('RoadtripSidebar', () => {
expect(screen.getByLabelText(/0 min/)).toBeInTheDocument()
})
it('FE-ROADTRIP-SIDEBAR-018: the track badge is a viewer-free control, and it says when a day is shaped', () => {
const onFollowTrack = vi.fn()
const stops = [stop({ assignmentId: 1, name: 'Hamburg' }), stop({ assignmentId: 2, name: 'Berlin' })]
const { rerender } = wrap(
<RoadtripSidebar routes={routes({ days: [day({ stops })] })} onFollowTrack={onFollowTrack} viaCounts={{ 1: 4 }} />,
)
const badge = screen.getByRole('button', { name: 'Track' })
fireEvent.click(badge)
expect(onFollowTrack).toHaveBeenCalledWith(1)
// The rail draws no vias, so the tint is the only place a drive shaped by hand
// differs from one the router picked on its own.
expect(badge.className).toContain('bg-accent-subtle')
rerender(
<TranslationProvider>
<RoadtripSidebar routes={routes({ days: [day({ stops })] })} onFollowTrack={onFollowTrack} />
</TranslationProvider>,
)
expect(screen.getByRole('button', { name: 'Track' }).className).not.toContain('bg-accent-subtle')
})
it('FE-ROADTRIP-SIDEBAR-019: a viewer is offered no track badge at all', () => {
const stops = [stop({ assignmentId: 1, name: 'Hamburg' }), stop({ assignmentId: 2, name: 'Berlin' })]
wrap(<RoadtripSidebar routes={routes({ days: [day({ stops })] })} />)
expect(screen.queryByRole('button', { name: 'Track' })).toBeNull()
})
})
describe('RoadtripModeSwitch', () => {
@@ -1,7 +1,7 @@
import React, { useState } from 'react'
import {
MapPin, CarFront, Footprints, Bike, Zap, AlertTriangle, Moon,
ParkingSquare, Shuffle, Fuel, Clock,
ParkingSquare, Shuffle, Fuel, Clock, Spline,
type LucideIcon,
} from 'lucide-react'
import { useTranslation } from '../../i18n/TranslationContext'
@@ -46,6 +46,20 @@ interface RoadtripSidebarProps {
* Absent leaves every disc read-only, which is also what a viewer sees.
*/
onSetStopKind?: (placeId: number, kind: RoadtripStopType | null) => Promise<void> | void
/**
* Opens the dialog that makes a day follow an imported track (#1797).
*
* Absent leaves the rail read-only on that count, which is also what a viewer sees.
*/
onFollowTrack?: (dayId: number) => void
/**
* How many vias each day carries, so a day whose shape was chosen by hand says so.
*
* A count rather than the points: the rail draws none of them — they are the router's
* business — but "this drive is not the one the router would have picked" is exactly
* what somebody reading the day needs to know.
*/
viaCounts?: Record<number, number>
}
const MODE_ICON: Record<string, LucideIcon> = {
@@ -745,7 +759,7 @@ function Stop({ stop, number, entry, late, driveFindings, selected, continues, s
* (`dayOrderMap` numbers the selected day's assignments from 1). A rail counting across
* the trip would put "17" beside a pin the map calls "3".
*/
function DaySection({ day, selectedAssignmentId, onSelectStop, onReorderStop, onMoveStopToDay, drag, onAskAlternatives, openAlternatives, onEditStay, onSetStopKind }: {
function DaySection({ day, selectedAssignmentId, onSelectStop, onReorderStop, onMoveStopToDay, drag, onAskAlternatives, openAlternatives, onEditStay, onSetStopKind, onFollowTrack, viaCount }: {
day: RoadtripDay
selectedAssignmentId?: number | null
onSelectStop?: (placeId: number, assignmentId: number) => void
@@ -757,6 +771,8 @@ function DaySection({ day, selectedAssignmentId, onSelectStop, onReorderStop, on
openAlternatives?: RoadtripSidebarProps['openAlternatives']
onEditStay?: RoadtripSidebarProps['onEditStay']
onSetStopKind?: RoadtripSidebarProps['onSetStopKind']
onFollowTrack?: RoadtripSidebarProps['onFollowTrack']
viaCount?: number
}): React.ReactElement {
const { from, setFrom, dropAt, setDropAt } = drag
const dragging = from?.dayId === day.dayId ? from.index : null
@@ -816,6 +832,25 @@ function DaySection({ day, selectedAssignmentId, onSelectStop, onReorderStop, on
<span className={`${DAY_BADGE} bg-surface-tertiary`} style={{ fontSize: FS.label }}>
{t('roadtrip.day.stopCount', { count: day.stops.filter(s => !isServiceStopType(s.stopType)).length })}
</span>
{/* Among the day's facts rather than beside its title, because "which road this
day takes" is one of them. Tinted once the day carries vias: the rail draws
none of them, so this badge is the only place a drive shaped by hand differs
from one the router picked on its own. */}
{onFollowTrack ? (
<Tooltip label={t('roadtrip.track.hint')}>
<button
type="button"
onClick={() => onFollowTrack(day.dayId)}
className={`${DAY_BADGE} gap-1 transition-colors hover:text-content focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent ${
viaCount ? 'bg-accent-subtle text-content' : 'bg-surface-tertiary hover:bg-surface-hover'
}`}
style={{ fontSize: FS.label }}
>
<Spline size={10} className="shrink-0" aria-hidden />
{t('roadtrip.track.badge')}
</button>
</Tooltip>
) : null}
</div>
</header>
{/* One list item per stop, with the drive that follows it inside — the chain is a
@@ -994,7 +1029,7 @@ function QuietDaySection({ day, onMoveStopToDay, drag }: {
*/
export default function RoadtripSidebar({
routes, selectedAssignmentId, onSelectStop, onReorderStop, onMoveStopToDay, onAskAlternatives, openAlternatives, onEditStay,
onSetStopKind,
onSetStopKind, onFollowTrack, viaCounts,
}: RoadtripSidebarProps): React.ReactElement {
const { t } = useTranslation()
// One drag state for the whole rail rather than one per day: a stop that cannot leave
@@ -1037,6 +1072,8 @@ export default function RoadtripSidebar({
openAlternatives={openAlternatives}
onEditStay={onEditStay}
onSetStopKind={onSetStopKind}
onFollowTrack={onFollowTrack}
viaCount={viaCounts?.[day.dayId] ?? 0}
/>
))}
{routes.quietDays.map(day => (
@@ -0,0 +1,124 @@
import React from 'react'
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { TranslationProvider } from '../../i18n'
import RoadtripTrackModal from './RoadtripTrackModal'
import type { FollowTrack, TrackChoice } from './useFollowTrack'
const wrap = (ui: React.ReactElement) => render(<TranslationProvider>{ui}</TranslationProvider>)
const track = (over: Partial<TrackChoice> & { id: number; name: string }): TrackChoice => ({
color: '#0ea5e9',
points: [{ lat: 52, lng: 13 }, { lat: 52, lng: 14 }],
lengthKm: 68,
gapKm: 0.4,
...over,
})
function follow(over: Partial<FollowTrack> = {}): FollowTrack {
return {
dayId: 7,
open: vi.fn(),
close: vi.fn(),
tracks: [track({ id: 3, name: 'Atlantic Road' })],
busy: false,
round: 0,
error: null,
outcome: null,
apply: vi.fn().mockResolvedValue(undefined),
clear: vi.fn().mockResolvedValue(undefined),
viaCount: 0,
available: true,
...over,
}
}
describe('RoadtripTrackModal', () => {
it('FE-TRACKMODAL-001: closed is nothing at all, not a hidden dialog', () => {
const { container } = wrap(<RoadtripTrackModal follow={follow({ dayId: null })} dayNumber={1} />)
expect(container.firstChild).toBeNull()
})
it('FE-TRACKMODAL-002: a trip with no tracks says where tracks come from', () => {
wrap(<RoadtripTrackModal follow={follow({ tracks: [] })} dayNumber={2} />)
expect(screen.getByText('No tracks in this trip')).toBeTruthy()
expect(screen.getByText(/GPX or KML/)).toBeTruthy()
})
it('FE-TRACKMODAL-003: a track close to the day says so rather than quoting a distance', () => {
wrap(<RoadtripTrackModal follow={follow()} dayNumber={1} />)
expect(screen.getByText(/along this day/)).toBeTruthy()
expect(screen.getByText(/68 km long/)).toBeTruthy()
})
it('FE-TRACKMODAL-004: a track that runs elsewhere is offered with the distance to here', () => {
wrap(<RoadtripTrackModal follow={follow({ tracks: [track({ id: 9, name: 'Elsewhere', gapKm: 240 })] })} dayNumber={1} />)
expect(screen.getByText(/240 km off this day/)).toBeTruthy()
})
it('FE-TRACKMODAL-005: nothing is applied until a track is picked', () => {
const state = follow()
wrap(<RoadtripTrackModal follow={state} dayNumber={1} />)
const action = screen.getByRole('button', { name: 'Follow this track' })
expect((action as HTMLButtonElement).disabled).toBe(true)
fireEvent.click(screen.getByText('Atlantic Road'))
expect((screen.getByRole('button', { name: 'Follow this track' }) as HTMLButtonElement).disabled).toBe(false)
// What it will do, before it does it: a track becomes a dozen waypoints on the day.
expect(screen.getByText(/via points/)).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Follow this track' }))
expect(state.apply).toHaveBeenCalledWith(3)
})
it('FE-TRACKMODAL-006: a picked track can be unpicked', () => {
wrap(<RoadtripTrackModal follow={follow()} dayNumber={1} />)
fireEvent.click(screen.getByText('Atlantic Road'))
fireEvent.click(screen.getByText('Atlantic Road'))
expect((screen.getByRole('button', { name: 'Follow this track' }) as HTMLButtonElement).disabled).toBe(true)
})
it('FE-TRACKMODAL-007: a run says which round it is on rather than going blank', () => {
wrap(<RoadtripTrackModal follow={follow({ busy: true, round: 4 })} dayNumber={1} />)
expect(screen.getByRole('status').textContent).toMatch(/round 4/)
})
it('FE-TRACKMODAL-008: a finished run reports how close the drive got', () => {
wrap(<RoadtripTrackModal follow={follow({ outcome: { vias: 6, strayKm: 0.8, capped: false } })} dayNumber={1} />)
expect(screen.getByRole('status').textContent).toMatch(/6 via points placed/)
})
it('FE-TRACKMODAL-009: a run that ran out of vias admits the gap it left', () => {
wrap(<RoadtripTrackModal follow={follow({ outcome: { vias: 12, strayKm: 2.4, capped: true } })} dayNumber={1} />)
// The honest form: it did what it could, and the number says how much that was worth.
expect(screen.getByRole('status').textContent).toMatch(/no closer than/)
})
it('FE-TRACKMODAL-010: a drive that already followed the track is not dressed up as work', () => {
wrap(<RoadtripTrackModal follow={follow({ outcome: { vias: 0, strayKm: 0, capped: false } })} dayNumber={1} />)
expect(screen.getByRole('status').textContent).toMatch(/already followed/)
})
it('FE-TRACKMODAL-011: a failure is an alert, not a silent nothing', () => {
wrap(<RoadtripTrackModal follow={follow({ error: 'route' })} dayNumber={1} />)
expect(screen.getByRole('alert').textContent).toMatch(/routing service/)
})
it('FE-TRACKMODAL-012: dropping the day\'s vias is offered only once it has some', () => {
const state = follow({ viaCount: 5 })
const { rerender } = wrap(<RoadtripTrackModal follow={state} dayNumber={1} />)
const drop = screen.getByRole('button', { name: /Drop 5 via points/ })
fireEvent.click(drop)
expect(state.clear).toHaveBeenCalled()
rerender(<TranslationProvider><RoadtripTrackModal follow={follow({ viaCount: 0 })} dayNumber={1} /></TranslationProvider>)
expect(screen.queryByRole('button', { name: /Drop/ })).toBeNull()
})
it('FE-TRACKMODAL-013: while it runs, nothing else in the dialog can be touched', () => {
wrap(<RoadtripTrackModal follow={follow({ busy: true, viaCount: 2 })} dayNumber={1} />)
expect((screen.getByRole('button', { name: /Atlantic Road/ }) as HTMLButtonElement).disabled).toBe(true)
expect((screen.getByRole('button', { name: /Drop 2 via points/ }) as HTMLButtonElement).disabled).toBe(true)
})
})
@@ -0,0 +1,185 @@
import React, { useEffect, useState } from 'react'
import { AlertTriangle, Check, RotateCw, Spline, Trash2 } from 'lucide-react'
import Modal from '../shared/Modal'
import EmptyState from '../shared/EmptyState'
import { useTranslation } from '../../i18n/TranslationContext'
import { useSettingsStore } from '../../store/settingsStore'
import { formatDistance } from '../../utils/units'
import { FS } from './typeScale'
import type { FollowTrack, TrackChoice } from './useFollowTrack'
/**
* Picking the track a day drives along.
*
* The list is the whole dialog. Everything a traveller needs to tell two imported tracks
* apart is on the row — the colour the map draws it in, how long it runs, and how far it
* is from this particular day — and the last of those is why the list is ordered the way
* it is: a trip carrying every track of a three-week tour still opens on the one beside
* today's drive.
*
* Applying is slow and says so. It is a routing round trip per refinement, half a minute
* on a long scenic route, and a dialog that went blank for that long would read as broken.
*/
/** A track close enough that it is plainly about this day rather than another one. */
const ON_THIS_DAY_KM = 2
function TrackRow({ track, disabled, onPick }: {
track: TrackChoice
disabled: boolean
onPick: () => void
}): React.ReactElement {
const { t } = useTranslation()
const distanceUnit = useSettingsStore(s => s.settings.distance_unit)
const onDay = track.gapKm <= ON_THIS_DAY_KM
return (
<li>
<button
type="button"
disabled={disabled}
onClick={onPick}
className="flex w-full items-center gap-3 rounded-xl px-2 py-2 text-start transition-colors hover:bg-surface-hover disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
{/* The line's own colour, as a short stroke rather than a dot: it is a line on the
map, and a dot beside a name reads as a place. */}
<span
className="h-1 w-6 shrink-0 rounded-full"
// theme-lint-disable — the colour the track carries, the same one the map draws.
style={{ background: track.color || 'var(--text-faint)' }}
aria-hidden
/>
<span className="min-w-0 flex-1">
<span className="block truncate font-semibold text-content" style={{ fontSize: FS.name }}>
{track.name || t('roadtrip.track.untitled')}
</span>
<span className="block truncate tabular-nums text-content-faint" style={{ fontSize: FS.meta }}>
{t('roadtrip.track.length', { distance: formatDistance(track.lengthKm, distanceUnit) })}
{' · '}
{onDay
? t('roadtrip.track.onDay')
: t('roadtrip.track.gap', { distance: formatDistance(track.gapKm, distanceUnit) })}
</span>
</span>
</button>
</li>
)
}
export default function RoadtripTrackModal({ follow, dayNumber }: {
follow: FollowTrack
/** The day's number, so the dialog says which drive it is about to reshape. */
dayNumber: number
}): React.ReactElement | null {
const { t } = useTranslation()
const distanceUnit = useSettingsStore(s => s.settings.distance_unit)
const [picked, setPicked] = useState<number | null>(null)
const { dayId, busy, round, error, outcome, tracks, viaCount } = follow
// A track picked on one day means nothing on the next.
useEffect(() => { setPicked(null) }, [dayId])
if (dayId === null) return null
const chosen = tracks.find(track => track.id === picked) ?? null
return (
<Modal
isOpen
onClose={follow.close}
size="sm"
title={
<span className="flex items-center gap-2">
<Spline size={15} className="text-content-faint" aria-hidden />
{t('roadtrip.track.title', { number: dayNumber })}
</span>
}
>
<div className="flex flex-col gap-3">
{tracks.length === 0 ? (
<div className="flex flex-col items-center gap-2 py-2">
<EmptyState scene="transport" size={96} compact title={t('roadtrip.track.empty')} />
<p className="text-center text-caption text-content-faint">{t('roadtrip.track.emptyHint')}</p>
</div>
) : (
<ul className="-mx-2 max-h-[280px] overflow-y-auto">
{tracks.map(track => (
<TrackRow
key={track.id}
track={track}
disabled={busy}
onPick={() => setPicked(track.id === picked ? null : track.id)}
/>
))}
</ul>
)}
{/* What the pick will do, before it is done. The count is the honest part: a track
becomes a dozen waypoints on the day, and a traveller who later wonders where
they came from should have been told here. */}
{chosen ? (
<p className="rounded-xl bg-surface-secondary px-3 py-2 text-caption text-content-secondary">
{t('roadtrip.track.explain')}
</p>
) : null}
{busy ? (
<p className="flex items-center gap-2 text-caption text-content-secondary" role="status">
<RotateCw size={13} className="animate-spin shrink-0" aria-hidden />
{t('roadtrip.track.working', { round })}
</p>
) : null}
{error ? (
<p className="flex items-start gap-1.5 text-caption text-danger" role="alert">
<AlertTriangle size={13} className="mt-px shrink-0" aria-hidden />
{t(error === 'route' ? 'roadtrip.track.errorRoute' : 'roadtrip.track.errorSave')}
</p>
) : null}
{outcome && !busy && !error ? (
<p className="flex items-start gap-1.5 text-caption text-content-secondary" role="status">
<Check size={13} className="mt-px shrink-0 text-success" aria-hidden />
{outcome.vias === 0
? t('roadtrip.track.already')
: outcome.capped
? t('roadtrip.track.capped', {
count: outcome.vias,
distance: formatDistance(outcome.strayKm, distanceUnit),
})
: t('roadtrip.track.done', {
count: outcome.vias,
distance: formatDistance(outcome.strayKm, distanceUnit),
})}
</p>
) : null}
<div className="flex items-center gap-2">
{/* Offered whenever the day carries vias, whether this dialog put them there or
a dragged handle did: "put it back the way the router had it" is the same
wish either way. */}
{viaCount > 0 ? (
<button
type="button"
disabled={busy}
onClick={() => { void follow.clear() }}
className="flex items-center gap-1.5 rounded-lg px-2.5 py-2 text-caption text-content-secondary transition-colors hover:bg-surface-hover disabled:opacity-50"
>
<Trash2 size={13} aria-hidden />
{t('roadtrip.track.clear', { count: viaCount })}
</button>
) : null}
<button
type="button"
disabled={!chosen || busy}
onClick={() => { if (chosen) void follow.apply(chosen.id) }}
className="ms-auto rounded-lg bg-accent px-3 py-2 text-caption font-semibold text-accent-text transition-opacity hover:opacity-90 disabled:opacity-40"
>
{t('roadtrip.track.action')}
</button>
</div>
</div>
</Modal>
)
}
@@ -0,0 +1,238 @@
import { describe, it, expect } from 'vitest'
import { haversineKm, type LatLng } from './corridor'
import {
parseTrack, lineLengthKm, thin, nearestIndex, orient, stopIndices, trackGapKm, planTrack,
} from './followTrack'
/**
* The refinement is the interesting part, and it is testable without a router: what it
* needs is something that answers "the road I would drive through these waypoints", and
* the straight line between them is exactly the answer that makes the loop work for its
* living. A track that bulges away from that chord is the shape every scenic route has.
*/
/** A track arching north away from the straight line between its ends. */
function arc(points = 120, bulgeDeg = 0.1): LatLng[] {
return Array.from({ length: points + 1 }, (_, i) => ({
lat: 52 + bulgeDeg * Math.sin((Math.PI * i) / points),
lng: 13 + i / points,
}))
}
const START: LatLng = { lat: 52, lng: 13 }
const END: LatLng = { lat: 52, lng: 14 }
/** A router with no idea about roads: it drives straight from waypoint to waypoint. */
function straightRouter(): { route: (w: LatLng[]) => Promise<LatLng[]>; calls: LatLng[][] } {
const calls: LatLng[][] = []
return {
calls,
route: async (waypoints: LatLng[]) => {
calls.push(waypoints)
return waypoints
},
}
}
describe('parseTrack', () => {
it('FE-FOLLOWTRACK-001: reads pairs and triples, and steps over what is neither', () => {
const geometry = JSON.stringify([[52, 13], [52.1, 13.1, 340], ['x', 1], [1], null, [53, 14]])
expect(parseTrack(geometry)).toEqual([
{ lat: 52, lng: 13 },
{ lat: 52.1, lng: 13.1 },
{ lat: 53, lng: 14 },
])
})
it('FE-FOLLOWTRACK-002: a track that is not a track is nothing, never a throw', () => {
// Somebody else's column, filled by an importer that has seen every malformed GPX
// there is. A day that cannot follow a track is a day; an exception here is a page.
expect(parseTrack('not json')).toEqual([])
expect(parseTrack('{"type":"LineString"}')).toEqual([])
expect(parseTrack(null)).toEqual([])
expect(parseTrack(undefined)).toEqual([])
})
})
describe('thinning and measuring', () => {
it('FE-FOLLOWTRACK-003: thinning keeps both ends, whatever the stride', () => {
const line = arc(1000)
const thinned = thin(line, 400)
expect(thinned.length).toBeLessThanOrEqual(401)
expect(thinned[0]).toEqual(line[0])
expect(thinned[thinned.length - 1]).toEqual(line[line.length - 1])
})
it('FE-FOLLOWTRACK-004: a line shorter than the cap comes back untouched', () => {
const line = arc(10)
expect(thin(line, 400)).toBe(line)
})
it('FE-FOLLOWTRACK-005: an arc is longer than the chord it spans', () => {
expect(lineLengthKm(arc())).toBeGreaterThan(haversineKm(START, END))
})
it('FE-FOLLOWTRACK-006: the nearest point of a track is found by position, not by order', () => {
const line = arc(20)
expect(nearestIndex(line, line[7])).toBe(7)
})
})
describe('orientation', () => {
it('FE-FOLLOWTRACK-007: a track recorded the other way round is turned', () => {
// Half of Norway's scenic routes are published southbound. Without this the vias come
// out in reverse order and the day drives the loop backwards.
const backwards = [...arc(20)].reverse()
const turned = orient(backwards, [START, END])
expect(turned[0].lng).toBeLessThan(turned[turned.length - 1].lng)
})
it('FE-FOLLOWTRACK-008: a track already pointing the right way is left alone', () => {
const line = arc(20)
expect(orient(line, [START, END])).toBe(line)
})
it('FE-FOLLOWTRACK-009: stops never walk backwards along the track', () => {
// A track that doubles back has two nearest points for the same stop, and the wrong
// one would put a via on the leg before it.
const line = arc(40)
const stops = [START, { lat: 52.05, lng: 13.5 }, END]
const idx = stopIndices(line, stops)
expect(idx[0]).toBeLessThanOrEqual(idx[1])
expect(idx[1]).toBeLessThanOrEqual(idx[2])
})
})
describe('planTrack', () => {
it('FE-FOLLOWTRACK-010: a road that already follows the track needs no vias', async () => {
const track = arc()
const plan = await planTrack({ track, stops: [START, END], route: async () => track })
expect(plan.vias).toEqual([])
expect(plan.rounds).toBe(1)
expect(plan.capped).toBe(false)
// Still names the leg it runs along, so applying it clears what an earlier pass left.
expect(plan.legs).toEqual([0])
})
it('FE-FOLLOWTRACK-011: it refines until the road is inside the tolerance', async () => {
const { route, calls } = straightRouter()
const plan = await planTrack({ track: arc(), stops: [START, END], route, options: { toleranceKm: 1 } })
expect(plan.capped).toBe(false)
expect(plan.strayKm).toBeLessThanOrEqual(1)
expect(plan.vias.length).toBeGreaterThan(0)
// One route per round, and the waypoint list grows by exactly the via just added.
expect(calls.length).toBe(plan.rounds)
expect(calls[calls.length - 1].length).toBe(2 + plan.vias.length)
})
it('FE-FOLLOWTRACK-012: every via lands on the track, in driving order', async () => {
const { route } = straightRouter()
const track = arc()
const plan = await planTrack({ track, stops: [START, END], route, options: { toleranceKm: 1 } })
for (const via of plan.vias) {
expect(track.some(p => haversineKm(p, via) < 0.001)).toBe(true)
}
const longitudes = plan.vias.map(v => v.lng)
expect([...longitudes].sort((a, b) => a - b)).toEqual(longitudes)
})
it('FE-FOLLOWTRACK-013: no via is laid down on top of a stop', async () => {
// A via a hundred metres from a stop costs a waypoint to tell the router what the
// stop already told it.
const { route } = straightRouter()
const plan = await planTrack({ track: arc(), stops: [START, END], route, options: { toleranceKm: 0.2, maxVias: 8 } })
for (const via of plan.vias) {
expect(haversineKm(via, START)).toBeGreaterThanOrEqual(0.6)
expect(haversineKm(via, END)).toBeGreaterThanOrEqual(0.6)
}
})
it('FE-FOLLOWTRACK-014: a via hangs behind the stop whose leg it shapes', async () => {
const { route } = straightRouter()
// Three stops, and the bulge is entirely on the second leg.
const straight: LatLng[] = Array.from({ length: 40 }, (_, i) => ({ lat: 52, lng: 13 + i / 78 }))
const bulge: LatLng[] = Array.from({ length: 81 }, (_, i) => ({
lat: 52 + 0.1 * Math.sin((Math.PI * i) / 80),
lng: 13.5 + i / 160,
}))
const middle: LatLng = { lat: 52, lng: 13.5 }
const plan = await planTrack({
track: [...straight, ...bulge],
stops: [START, middle, END],
route,
options: { toleranceKm: 1 },
})
expect(plan.vias.length).toBeGreaterThan(0)
expect(plan.vias.every(v => v.after_order_index === 1)).toBe(true)
expect(plan.legs).toEqual([0, 1])
})
it('FE-FOLLOWTRACK-015: it gives up rather than spending the day on a road that will not fit', async () => {
const { route, calls } = straightRouter()
const plan = await planTrack({
track: arc(),
stops: [START, END],
route,
options: { toleranceKm: 0.0001, maxVias: 3 },
})
expect(plan.capped).toBe(true)
expect(plan.vias).toHaveLength(3)
expect(calls.length).toBe(4)
})
it('FE-FOLLOWTRACK-016: a track the day only brushes past is not a route for it', async () => {
const { route, calls } = straightRouter()
const plan = await planTrack({ track: [{ lat: 40, lng: 2 }, { lat: 40.001, lng: 2.001 }], stops: [START, END], route })
expect(plan.vias).toEqual([])
expect(plan.legs).toEqual([])
// Never asks the router about a track that has nothing to do with the day.
expect(calls).toHaveLength(0)
})
it('FE-FOLLOWTRACK-017: nothing to route through is not an error', async () => {
const { route } = straightRouter()
expect((await planTrack({ track: arc(), stops: [START], route })).vias).toEqual([])
expect((await planTrack({ track: [], stops: [START, END], route })).vias).toEqual([])
})
it('FE-FOLLOWTRACK-018: a router that answers with no road says so', async () => {
await expect(planTrack({ track: arc(), stops: [START, END], route: async () => [] }))
.rejects.toThrow(/road/)
})
it('FE-FOLLOWTRACK-019: an aborted plan stops where it is', async () => {
const controller = new AbortController()
const plan = await planTrack({
track: arc(),
stops: [START, END],
route: async () => [START, END],
signal: controller.signal,
options: { toleranceKm: 0.001 },
})
controller.abort()
// Ran to its own conclusion here; the point is that the signal is honoured at the top
// of each round, which the aborted-before-start case proves.
expect(plan.rounds).toBeGreaterThan(0)
const stopped = new AbortController()
stopped.abort()
const none = await planTrack({
track: arc(),
stops: [START, END],
route: async () => [START, END],
signal: stopped.signal,
})
expect(none.rounds).toBe(0)
})
it('FE-FOLLOWTRACK-020: how far a track runs from a day is what orders a list of them', async () => {
const near = trackGapKm(arc(), [START, END])
const far = trackGapKm(arc().map(p => ({ lat: p.lat + 3, lng: p.lng })), [START, END])
expect(near).toBeLessThan(far)
expect(trackGapKm([], [START])).toBe(Number.POSITIVE_INFINITY)
})
})
@@ -0,0 +1,318 @@
import { haversineKm, projectOntoRoute, type LatLng } from './corridor'
/**
* Making a day's drive follow an imported track.
*
* A GPX track is a shape, not a route: a list of positions with no idea which roads they
* were recorded on. Drawing it beside the day is easy and useless — the distance, the
* drive time and every warning still belong to the motorway the router picked, so the
* plan says four hours while the road nobody is taking says seven. Norway publishes its
* scenic routes this way, and so does every touring club worth importing from.
*
* What turns a shape into a route the day actually takes is a handful of vias placed on
* it, because a via is the one thing a router treats as "go through here". Placing them
* is the whole problem. Every point of the track would route exactly and take a hundred
* requests; two would route in seconds and follow nothing.
*
* So this refines: route through what we have, find the point of the track the road
* misses by the most, make that point a via, and go again. Each round roughly halves the
* worst miss, because the new via lands in the middle of whatever the last one left
* unfollowed — which is why a scenic route usually fits inside ten of them, and why the
* loop stops when the road is close enough rather than after a fixed count.
*
* Everything here is pure apart from the injected router: no React, no store, no api.
*/
/** Track points kept for measuring — enough to catch a hairpin, few enough to be fast. */
const MEASURE_POINTS = 400
/** Routed points kept for measuring. Coarser: it is the thing being measured against. */
const ROUTE_POINTS = 2000
/**
* How close a via may sit to a stop, or to another via, before it is pointless.
*
* A via a hundred metres from a stop tells the router nothing it did not already know
* from the stop, and two vias in the same lay-by cost a waypoint each to say one thing.
*/
const MIN_GAP_KM = 0.6
export interface FollowTrackOptions {
/** How close the road must come to the track before the plan is done, in kilometres. */
toleranceKm?: number
/** The most vias the plan may lay down. */
maxVias?: number
/** The most routing round trips it may spend. */
maxRounds?: number
}
export interface TrackVia {
/** The stop the via hangs behind, as an index into the day's stops. */
after_order_index: number
lat: number
lng: number
}
export interface FollowTrackPlan {
/** The vias to write, in driving order, each already on the leg it shapes. */
vias: TrackVia[]
/** The legs the track runs along — cleared first, so applying twice does not stack. */
legs: number[]
/** How far the road still strays from the track at its worst point, in kilometres. */
strayKm: number
/** Routing round trips spent. */
rounds: number
/** True when it ran out of vias or rounds before the road fitted the track. */
capped: boolean
}
const EMPTY_PLAN: FollowTrackPlan = { vias: [], legs: [], strayKm: 0, rounds: 0, capped: false }
/**
* The points of a stored track.
*
* `route_geometry` is the column the GPX and KML importers write, holding `[lat, lng]`
* pairs or `[lat, lng, ele]` triples depending on whether every point carried an
* elevation. Anything else in there is somebody else's data — a malformed track is worth
* skipping, never worth throwing over.
*/
export function parseTrack(routeGeometry: string | null | undefined): LatLng[] {
if (!routeGeometry) return []
try {
const raw: unknown = JSON.parse(routeGeometry)
if (!Array.isArray(raw)) return []
const out: LatLng[] = []
for (const point of raw) {
if (!Array.isArray(point) || point.length < 2) continue
const lat = Number(point[0])
const lng = Number(point[1])
if (!Number.isFinite(lat) || !Number.isFinite(lng)) continue
out.push({ lat, lng })
}
return out
} catch {
return []
}
}
/** How long a polyline is, in kilometres. */
export function lineLengthKm(line: LatLng[]): number {
let km = 0
for (let i = 1; i < line.length; i++) km += haversineKm(line[i - 1], line[i])
return km
}
/**
* Every nth point, keeping both ends.
*
* Deliberately not the Douglas-Peucker in `corridor.ts`: that one is recursive and slices
* the array at every step, which is fine for a routed leg and quadratic on a recorded
* track of thirty thousand points. Taking a stride loses a little accuracy on a hairpin
* and none of the shape, and the tolerance this feeds is measured in kilometres.
*/
export function thin(line: LatLng[], max: number): LatLng[] {
if (line.length <= max) return line
const stride = Math.ceil(line.length / max)
const out: LatLng[] = []
for (let i = 0; i < line.length; i += stride) out.push(line[i])
const last = line[line.length - 1]
if (out[out.length - 1] !== last) out.push(last)
return out
}
/** Index of the point of `line` closest to `p`. */
export function nearestIndex(line: LatLng[], p: LatLng): number {
let best = Number.POSITIVE_INFINITY
let at = 0
for (let i = 0; i < line.length; i++) {
const d = haversineKm(line[i], p)
if (d < best) {
best = d
at = i
}
}
return at
}
/** How far a point lies from a line, in kilometres. Infinite for a line of one point. */
export function offLineKm(line: LatLng[], p: LatLng): number {
return projectOntoRoute(p, line)?.offRouteKm ?? Number.POSITIVE_INFINITY
}
/**
* The track pointing the way the day is driven.
*
* A recorded track has a direction, and it is whichever way the person who recorded it
* happened to drive. Half of Norway's scenic routes are published southbound. Reversed
* where the day's last stop comes before its first, so everything downstream can treat a
* higher index as "further along the drive".
*/
export function orient(track: LatLng[], stops: LatLng[]): LatLng[] {
if (track.length < 2 || stops.length < 2) return track
const start = nearestIndex(track, stops[0])
const end = nearestIndex(track, stops[stops.length - 1])
return end < start ? [...track].reverse() : track
}
/**
* Where each stop sits on the track, as an index.
*
* Forced not to go backwards. A stop nowhere near the track still gets its nearest point,
* and on a track that doubles back that point can land before the previous stop's —
* which would put a via on the wrong leg and send the day round the loop twice.
*/
export function stopIndices(track: LatLng[], stops: LatLng[]): number[] {
let floor = 0
return stops.map(stop => {
const at = Math.max(floor, nearestIndex(track, stop))
floor = at
return at
})
}
/** The leg an anchor belongs to: the last stop it comes after. */
function legFor(anchor: number, stopIdx: number[]): number {
let leg = 0
for (let k = 0; k + 1 < stopIdx.length; k++) if (stopIdx[k] <= anchor) leg = k
return leg
}
/** The stops with the anchors threaded in between, in the order they are driven. */
function waypointsFor(stops: LatLng[], anchors: number[], track: LatLng[], stopIdx: number[]): LatLng[] {
const out: LatLng[] = []
for (let k = 0; k < stops.length; k++) {
out.push(stops[k])
if (k + 1 >= stops.length) continue
for (const anchor of anchors) if (legFor(anchor, stopIdx) === k) out.push(track[anchor])
}
return out
}
/**
* The point of the track the road misses by the most — among the ones worth fixing.
*
* Points already anchored are skipped because the router is going through them, and
* points hard against a stop or an existing via are skipped because a via there would
* buy nothing. What is left is the miss the next round can actually close.
*/
function worstMiss(
track: LatLng[],
road: LatLng[],
span: { from: number; to: number },
anchors: number[],
stops: LatLng[],
): { index: number; km: number } | null {
const taken = new Set(anchors)
let best: { index: number; km: number } | null = null
for (let i = span.from; i <= span.to; i++) {
if (taken.has(i)) continue
const point = track[i]
if (stops.some(s => haversineKm(s, point) < MIN_GAP_KM)) continue
if (anchors.some(a => haversineKm(track[a], point) < MIN_GAP_KM)) continue
const km = offLineKm(road, point)
if (!Number.isFinite(km)) continue
if (!best || km > best.km) best = { index: i, km }
}
return best
}
export interface TrackPlanInput {
/** The track's points, as stored. */
track: LatLng[]
/** The day's stops, in driving order. */
stops: LatLng[]
/** Routes through the given waypoints and answers with the road it drew. */
route: (waypoints: LatLng[]) => Promise<LatLng[]>
options?: FollowTrackOptions
/** Called after each round, so a dialog can say how far it has got. */
onRound?: (round: number, strayKm: number) => void
signal?: AbortSignal
}
/**
* How much of a day a track has anything to say about.
*
* A trip full of imported tracks needs an order to offer them in, and "how far this one
* runs from that drive" is the answer — measured from the stops rather than from the
* routed line, so it holds for a day that has not routed yet.
*/
export function trackGapKm(track: LatLng[], stops: LatLng[]): number {
if (!track.length || !stops.length) return Number.POSITIVE_INFINITY
const line = thin(track, MEASURE_POINTS)
if (line.length < 2) return haversineKm(line[0], stops[0])
let best = Number.POSITIVE_INFINITY
for (const stop of stops) best = Math.min(best, offLineKm(line, stop))
return best
}
/**
* Vias that pull a day's drive onto a track.
*
* Routes the whole day per round rather than one leg at a time: the day is a single
* request to begin with, and asking per leg would multiply every round by the number of
* legs against a host that answers one request a second.
*/
export async function planTrack({
track,
stops,
route,
options = {},
onRound,
signal,
}: TrackPlanInput): Promise<FollowTrackPlan> {
const toleranceKm = options.toleranceKm ?? 1
const maxVias = options.maxVias ?? 12
const maxRounds = options.maxRounds ?? 10
if (track.length < 2 || stops.length < 2) return EMPTY_PLAN
const measured = orient(thin(track, MEASURE_POINTS), stops)
const stopIdx = stopIndices(measured, stops)
const span = { from: stopIdx[0], to: stopIdx[stopIdx.length - 1] }
// A track the day only touches at one point is a track for some other day.
if (span.to - span.from < 2) return EMPTY_PLAN
// The legs the track runs along. Read off the stops, not off the anchors, so applying
// a track twice clears what the first pass laid down instead of stacking on it — and
// so a track that already fits still says which legs it owns.
const legs: number[] = []
for (let k = 0; k + 1 < stops.length; k++) {
if (stopIdx[k + 1] > span.from && stopIdx[k] < span.to) legs.push(k)
}
const anchors: number[] = []
let strayKm = 0
let rounds = 0
let capped = false
for (;;) {
if (signal?.aborted) break
const drawn = await route(waypointsFor(stops, anchors, measured, stopIdx))
if (drawn.length < 2) throw new Error('The router answered without a road')
rounds += 1
const miss = worstMiss(measured, thin(drawn, ROUTE_POINTS), span, anchors, stops)
// No candidate left to fix is as finished as being inside the tolerance: everything
// that remains sits against a stop or against a via that is already there.
strayKm = miss?.km ?? 0
onRound?.(rounds, strayKm)
if (!miss || miss.km <= toleranceKm) break
if (anchors.length >= maxVias || rounds >= maxRounds) {
capped = true
break
}
anchors.push(miss.index)
anchors.sort((a, b) => a - b)
}
return {
vias: anchors.map(i => ({
after_order_index: legFor(i, stopIdx),
lat: measured[i].lat,
lng: measured[i].lng,
})),
legs,
strayKm,
rounds,
capped,
}
}
@@ -0,0 +1,209 @@
import { renderHook, act, waitFor } from '@testing-library/react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { RoadtripDay, RoadtripRoutes } from './useRoadtripRoutes'
import type { RoadtripVias } from './useRoadtripVias'
import type { TrackPlace } from './useFollowTrack'
const { calculateRouteWithLegs } = vi.hoisted(() => ({ calculateRouteWithLegs: vi.fn() }))
vi.mock('../Map/RouteCalculator', () => ({ calculateRouteWithLegs }))
import { useFollowTrack } from './useFollowTrack'
/**
* The hook is the part that talks to two services and has to survive both of them going
* wrong halfway. The refinement itself is `followTrack`'s business and tested there; what
* matters here is what reaches the day and what reaches the traveller.
*/
const START = { lat: 52, lng: 13 }
const END = { lat: 52, lng: 14 }
/** A track arching north away from the straight line between the day's two stops. */
function arc(points = 60, bulgeDeg = 0.1): [number, number][] {
return Array.from({ length: points + 1 }, (_, i) => [
52 + bulgeDeg * Math.sin((Math.PI * i) / points),
13 + i / points,
])
}
function day(over: Partial<RoadtripDay> = {}): RoadtripDay {
return {
dayId: 7, dayNumber: 1, date: null, title: null,
stops: [
{ assignmentId: 1, placeId: 10, name: 'A', lat: START.lat, lng: START.lng, time: null, dwellMinutes: null, legMode: null, incomingLegMode: null, stopType: null },
{ assignmentId: 2, placeId: 20, name: 'B', lat: END.lat, lng: END.lng, time: null, dwellMinutes: null, legMode: null, incomingLegMode: null, stopType: null },
],
legs: [], legVias: [], driveWarnings: [], dayWarning: null, schedule: { entries: [], warnings: [] },
geometry: [[START.lat, START.lng], [END.lat, END.lng]],
distance: 0, duration: 0,
...over,
}
}
const routes = (days: RoadtripDay[]): RoadtripRoutes => ({
days, lines: [], segments: [], accessLines: [], vias: [], totalDistance: 0, totalDuration: 0, totalStops: 0, quietDays: [], loading: false,
})
function viasStub(over: Partial<RoadtripVias> = {}): RoadtripVias {
return {
byDay: {},
add: vi.fn(),
addMany: vi.fn().mockResolvedValue(undefined),
move: vi.fn(),
remove: vi.fn(),
reanchor: vi.fn(),
...over,
}
}
const TRACK: TrackPlace = { id: 3, name: 'Atlantic Road', route_geometry: JSON.stringify(arc()), route_color: '#0ea5e9' }
const PLAIN: TrackPlace = { id: 4, name: 'A hotel', route_geometry: null }
const FAR: TrackPlace = { id: 5, name: 'Somewhere else', route_geometry: JSON.stringify(arc().map(([la, ln]) => [la + 4, ln])) }
/**
* A router with no idea about roads: it drives straight from waypoint to waypoint.
*
* Which is exactly what makes the refinement work for its living — each via added bends
* the answer a little closer to the arc, so the loop converges instead of running to its
* cap the way a fixed answer would.
*/
function answersStraight(): void {
calculateRouteWithLegs.mockImplementation(async (waypoints: { lat: number; lng: number }[]) => ({
coordinates: waypoints.map(w => [w.lat, w.lng]),
distance: 0, duration: 0, legs: [],
}))
}
beforeEach(() => {
calculateRouteWithLegs.mockReset()
})
describe('useFollowTrack', () => {
it('FE-FOLLOWHOOK-001: nothing is parsed while the dialog is closed', () => {
const { result } = renderHook(() => useFollowTrack(1, [TRACK, PLAIN], routes([day()]), viasStub()))
expect(result.current.dayId).toBeNull()
// Tens of thousands of points per track, for a dialog nobody opened.
expect(result.current.tracks).toEqual([])
// But it still knows there is something to open, without parsing a single point.
expect(result.current.available).toBe(true)
})
it('FE-FOLLOWHOOK-010: a trip that imported nothing offers no way in', () => {
const { result } = renderHook(() => useFollowTrack(1, [PLAIN], routes([day()]), viasStub()))
expect(result.current.available).toBe(false)
})
it('FE-FOLLOWHOOK-002: opening lists only the places that carry a line, nearest first', () => {
const { result } = renderHook(() => useFollowTrack(1, [FAR, PLAIN, TRACK], routes([day()]), viasStub()))
act(() => { result.current.open(7) })
expect(result.current.tracks.map(t => t.id)).toEqual([3, 5])
expect(result.current.tracks[0].name).toBe('Atlantic Road')
expect(result.current.tracks[0].color).toBe('#0ea5e9')
expect(result.current.tracks[0].lengthKm).toBeGreaterThan(60)
expect(result.current.tracks[0].gapKm).toBeLessThan(result.current.tracks[1].gapKm)
})
it('FE-FOLLOWHOOK-003: applying writes the plan onto the day, legs and all', async () => {
answersStraight()
const vias = viasStub()
const { result } = renderHook(() => useFollowTrack(1, [TRACK], routes([day()]), vias))
act(() => { result.current.open(7) })
await act(async () => { await result.current.apply(3) })
expect(vias.addMany).toHaveBeenCalledTimes(1)
const [dayId, written, legs] = (vias.addMany as ReturnType<typeof vi.fn>).mock.calls[0]
expect(dayId).toBe(7)
expect(legs).toEqual([0])
expect(written.length).toBeGreaterThan(0)
// Every via hangs behind the first stop, because the day has exactly one leg.
expect(written.every((v: { after_order_index: number }) => v.after_order_index === 0)).toBe(true)
expect(result.current.outcome?.vias).toBe(written.length)
expect(result.current.busy).toBe(false)
})
it('FE-FOLLOWHOOK-004: a track the drive already follows writes nothing but says so', async () => {
// The router answers with the track itself, so there is nothing left to pull onto.
calculateRouteWithLegs.mockResolvedValue({ coordinates: arc(), distance: 0, duration: 0, legs: [] })
const vias = viasStub()
const { result } = renderHook(() => useFollowTrack(1, [TRACK], routes([day()]), vias))
act(() => { result.current.open(7) })
await act(async () => { await result.current.apply(3) })
expect(result.current.outcome).toEqual({ vias: 0, strayKm: 0, capped: false })
// Still a write: the legs are cleared, so applying a second track does not stack.
expect(vias.addMany).toHaveBeenCalledWith(7, [], [0])
})
it('FE-FOLLOWHOOK-005: a routing outage is reported rather than written as an empty plan', async () => {
calculateRouteWithLegs.mockRejectedValue(new Error('429'))
const vias = viasStub()
const { result } = renderHook(() => useFollowTrack(1, [TRACK], routes([day()]), vias))
act(() => { result.current.open(7) })
await act(async () => { await result.current.apply(3) })
expect(result.current.error).toBe('route')
expect(result.current.busy).toBe(false)
expect(vias.addMany).not.toHaveBeenCalled()
// One retry, because a refinement is several calls against a rate-limited host.
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(2)
}, 10000)
it('FE-FOLLOWHOOK-006: a save that fails says so instead of claiming the day changed', async () => {
answersStraight()
const vias = viasStub({ addMany: vi.fn().mockRejectedValue(new Error('boom')) })
const { result } = renderHook(() => useFollowTrack(1, [TRACK], routes([day()]), vias))
act(() => { result.current.open(7) })
await act(async () => { await result.current.apply(3) })
expect(result.current.error).toBe('save')
expect(result.current.outcome).toBeNull()
expect(result.current.busy).toBe(false)
}, 10000)
it('FE-FOLLOWHOOK-007: clearing drops the vias of every leg of the day', async () => {
const vias = viasStub({ byDay: { 7: [{ id: 1 }, { id: 2 }] as never } })
const { result } = renderHook(() => useFollowTrack(1, [TRACK], routes([day()]), vias))
act(() => { result.current.open(7) })
expect(result.current.viaCount).toBe(2)
await act(async () => { await result.current.clear() })
expect(vias.addMany).toHaveBeenCalledWith(7, [], [0])
expect(result.current.outcome).toEqual({ vias: 0, strayKm: 0, capped: false })
})
it('FE-FOLLOWHOOK-008: closing abandons a run rather than letting it land afterwards', async () => {
let release: ((value: unknown) => void) | null = null
calculateRouteWithLegs.mockImplementation(() => new Promise(resolve => { release = resolve }))
const vias = viasStub()
const { result } = renderHook(() => useFollowTrack(1, [TRACK], routes([day()]), vias))
act(() => { result.current.open(7) })
let running: Promise<void> | null = null
act(() => { running = result.current.apply(3) })
await waitFor(() => { expect(result.current.busy).toBe(true) })
act(() => { result.current.close() })
await act(async () => {
release?.({ coordinates: [[START.lat, START.lng], [END.lat, END.lng]], distance: 0, duration: 0, legs: [] })
await running
})
// The day is left exactly as it was: an abandoned plan is not half a chain of vias.
expect(vias.addMany).not.toHaveBeenCalled()
expect(result.current.dayId).toBeNull()
expect(result.current.error).toBeNull()
})
it('FE-FOLLOWHOOK-009: a day with nothing to drive between is not applied to', async () => {
answersStraight()
const vias = viasStub()
const lonely = day({ stops: [day().stops[0]] })
const { result } = renderHook(() => useFollowTrack(1, [TRACK], routes([lonely]), vias))
act(() => { result.current.open(7) })
await act(async () => { await result.current.apply(3) })
expect(calculateRouteWithLegs).not.toHaveBeenCalled()
expect(vias.addMany).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,219 @@
import { useCallback, useMemo, useRef, useState } from 'react'
import { calculateRouteWithLegs } from '../Map/RouteCalculator'
import { lineLengthKm, parseTrack, planTrack, trackGapKm, type FollowTrackPlan } from './followTrack'
import type { LatLng } from './corridor'
import type { RoadtripRoutes } from './useRoadtripRoutes'
import type { RoadtripVias } from './useRoadtripVias'
/**
* The dialog state behind "this day follows that track".
*
* Kept out of the dialog because applying one is a long job — a round trip to the routing
* host per refinement — and a component that unmounts halfway would leave the day with
* half a chain of vias on it. Here it can be aborted, and here it can say how far it has
* got while it runs.
*/
/** A track of this trip, ready to be offered. */
export interface TrackChoice {
id: number
name: string
/** The colour the map already draws it in, so the list and the line agree. */
color: string | null
points: LatLng[]
lengthKm: number
/** How far the track runs from the open day at its closest — what orders the list. */
gapKm: number
}
/** What became of an applied track. */
export interface FollowTrackOutcome {
vias: number
strayKm: number
capped: boolean
}
export interface FollowTrack {
/** The day the dialog is open for, or null when it is closed. */
dayId: number | null
open: (dayId: number) => void
close: () => void
/** The trip's tracks, nearest to this day first. Empty until the dialog opens. */
tracks: TrackChoice[]
busy: boolean
/** Which refinement round is running, for a dialog that has to say something. */
round: number
error: 'route' | 'save' | null
outcome: FollowTrackOutcome | null
apply: (trackId: number) => Promise<void>
/** Drops every via of the open day, so it drives the way the router would. */
clear: () => Promise<void>
/** How many vias the open day carries — what makes clearing worth offering. */
viaCount: number
/**
* Whether the trip holds a track at all.
*
* Read off the column rather than off `tracks`, which is empty until the dialog opens
* and would therefore never let it be opened. It is what keeps the rail from offering
* a control whose only possible answer is "no tracks in this trip".
*/
available: boolean
}
/** A place is a track when it carries a line. */
export interface TrackPlace {
id: number
name?: string | null
route_geometry?: string | null
route_color?: string | null
}
/** Waiting a beat between rounds: the public routing hosts allow about one call a second. */
export const ROUND_PAUSE_MS = 400
/** How long to wait before the one retry a round gets. */
export const RETRY_PAUSE_MS = 1500
const sleep = (ms: number): Promise<void> => new Promise(resolve => { setTimeout(resolve, ms) })
export function useFollowTrack(
tripId: number | string | null,
places: TrackPlace[],
routes: RoadtripRoutes,
vias: RoadtripVias,
): FollowTrack {
const [dayId, setDayId] = useState<number | null>(null)
const [busy, setBusy] = useState(false)
const [round, setRound] = useState(0)
const [error, setError] = useState<'route' | 'save' | null>(null)
const [outcome, setOutcome] = useState<FollowTrackOutcome | null>(null)
const abort = useRef<AbortController | null>(null)
const day = useMemo(() => routes.days.find(d => d.dayId === dayId), [routes.days, dayId])
const stops = useMemo<LatLng[]>(() => (day?.stops ?? []).map(s => ({ lat: s.lat, lng: s.lng })), [day])
/**
* Parsed only while the dialog is open.
*
* A track runs to tens of thousands of points and a trip can hold a dozen of them, so
* parsing them to render a rail nobody opened would cost more than the rail does. The
* memo hangs off `dayId` as well as `places` for exactly that reason.
*/
const tracks = useMemo<TrackChoice[]>(() => {
if (dayId === null) return []
const found: TrackChoice[] = []
for (const place of places) {
const points = parseTrack(place.route_geometry)
if (points.length < 2) continue
found.push({
id: place.id,
name: place.name || '',
color: place.route_color ?? null,
points,
lengthKm: lineLengthKm(points),
gapKm: trackGapKm(points, stops),
})
}
// Nearest first: a trip carrying every track of a three-week tour should still open
// on the one that runs along today's drive.
return found.sort((a, b) => a.gapKm - b.gapKm)
}, [dayId, places, stops])
const open = useCallback((next: number) => {
setDayId(next)
setOutcome(null)
setError(null)
setRound(0)
}, [])
const close = useCallback(() => {
abort.current?.abort()
abort.current = null
setDayId(null)
setBusy(false)
setRound(0)
}, [])
const apply = useCallback(async (trackId: number) => {
const track = tracks.find(t => t.id === trackId)
if (!track || dayId === null || stops.length < 2 || busy) return
const controller = new AbortController()
abort.current = controller
setBusy(true)
setError(null)
setOutcome(null)
setRound(0)
let plan: FollowTrackPlan
let spent = 0
try {
plan = await planTrack({
track: track.points,
stops,
signal: controller.signal,
onRound: n => { setRound(n) },
route: async waypoints => {
// Paced before the call rather than after it, so a plan that fits on its first
// round costs nothing in waiting — and given one second chance, because a
// refinement is several calls in a row against a host that allows about one a
// second, and losing the whole loop to a single 429 would restart it at nothing.
if (spent > 0) await sleep(ROUND_PAUSE_MS)
spent += 1
for (let attempt = 0; ; attempt++) {
try {
const r = await calculateRouteWithLegs(waypoints, {
signal: controller.signal,
profile: 'driving',
tripId,
dayId,
})
return r.coordinates.map(([lat, lng]) => ({ lat, lng }))
} catch (err) {
if (attempt >= 1 || controller.signal.aborted) throw err
await sleep(RETRY_PAUSE_MS)
}
}
},
})
} catch {
if (!controller.signal.aborted) setError('route')
setBusy(false)
return
}
if (controller.signal.aborted) { setBusy(false); return }
try {
await vias.addMany(dayId, plan.vias, plan.legs)
setOutcome({ vias: plan.vias.length, strayKm: plan.strayKm, capped: plan.capped })
} catch {
setError('save')
} finally {
setBusy(false)
}
}, [tracks, dayId, stops, busy, tripId, vias])
const viaCount = dayId === null ? 0 : (vias.byDay[dayId]?.length ?? 0)
// A cheap look at the column, not a parse: this runs on every planner render, and the
// question is only whether anything at all was ever imported.
const available = useMemo(() => places.some(p => (p.route_geometry?.length ?? 0) > 2), [places])
const clear = useCallback(async () => {
if (dayId === null || busy) return
setBusy(true)
setError(null)
try {
// Every leg of the day, so nothing is left behind on a leg the track never reached.
const legs = Array.from({ length: Math.max(0, stops.length - 1) }, (_, i) => i)
await vias.addMany(dayId, [], legs)
setOutcome({ vias: 0, strayKm: 0, capped: false })
} catch {
setError('save')
} finally {
setBusy(false)
}
}, [dayId, busy, stops.length, vias])
return { dayId, open, close, tracks, busy, round, error, outcome, apply, clear, viaCount, available }
}