mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-27 15:17:30 +00:00
fix(roadtrip): keep the shaping a traveller did, through every path that moves a stop
A via records which stop it follows by POSITION, so anything that renumbers a day's stops moves the ground under it. The road-trip rail corrects for that; almost nothing else did. reanchor() never renumbered `sequence`. It is allocated per leg and starts at 0 in each, and re-anchoring MERGES two legs whenever the stop between them goes away — so leg A's 0,1 ended up beside leg B's 0,1, and everything that draws the route orders by sequence. The drive ran A0, B0, A1, B1: forward, back, and forward again. Persisted, surviving a reload, and unrepairable except by deleting the vias. The old anchor is read before the updates and used as the primary sort key, so the vias of the earlier leg stay ahead of the ones that merged into it. Reordering the only two stops of a day deleted every via on it. A reorder is modelled as remove-then-insert, and the removal half refuses to treat a two-stop day as still having a drive — right when a stop really goes away, catastrophic when nothing was removed. Two stops is exactly the shape "follow this track" produces, up to nine vias on that one leg, gone to a single drag with no prompt and no undo. Removing a stop, reordering within a day, and assigning a place mid-day never re-anchored at all, though the helpers exist and three other paths use them. The detour then sat on a leg the traveller never chose, or on a leg that no longer existed and vanished — until a later stop brought it back bending a road nobody asked for. Reordering hands a whole new ordering rather than one move, so the anchors there follow the stop they were pinned behind instead of arithmetic on the index, which is correct for any permutation. Duplicating a trip dropped all of it: `stop_type` was missing from the place insert, and neither via nor day-track table was copied. The duplicate looked complete and quietly drove somewhere else. A failed read of the via list emptied it. That read runs after every write and feeds the routing key, so a 502, a dropped connection or a tab going offline re-routed the whole trip along the roads the traveller had steered away from, with nothing said and nothing retried — indistinguishable from having deleted them. Only a 404 or 403 empties now; anything else keeps the last known list and says it may be stale.
This commit is contained in:
@@ -234,6 +234,38 @@ describe('RoadtripStopPopup', () => {
|
||||
expect(onSave).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-STOPPOPUP-026: a scheme-less OSM website still leaves the app', () => {
|
||||
// OSM `website` tags are routinely written without a scheme. As a raw href
|
||||
// `www.hotel.de` is a RELATIVE url, so the click navigated the planner to
|
||||
// /trips/<id>/www.hotel.de and the user lost the page they were on.
|
||||
wrap(
|
||||
<RoadtripStopPopup
|
||||
draft={draft({ poi: poi({ category: 'hotel', website: 'www.hotel-adlon.de' }), overnight })}
|
||||
{...noop}
|
||||
onSaveNight={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByRole('link', { name: 'Website' })).toHaveAttribute('href', 'https://www.hotel-adlon.de')
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-STOPPOPUP-027: a website that is not a link is not rendered as one', () => {
|
||||
// Anything that is not http(s) loses the link rather than being handed to
|
||||
// the browser. The CSP stops a javascript: navigation on a stock deployment,
|
||||
// but this is defended everywhere else in the app and belongs here too.
|
||||
for (const bad of ['javascript:alert(1)', 'data:text/html,<script>', 'tel:+49301234']) {
|
||||
const { unmount } = wrap(
|
||||
<RoadtripStopPopup
|
||||
draft={draft({ poi: poi({ category: 'hotel', website: bad }), overnight })}
|
||||
{...noop}
|
||||
onSaveNight={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
expect(screen.queryByRole('link', { name: 'Website' }), bad).not.toBeInTheDocument()
|
||||
unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-STOPPOPUP-025: without a way to book a night the switch stays away', () => {
|
||||
// An onSaveNight-less caller gets the dialog it always had, rather than a mode that
|
||||
// leads nowhere.
|
||||
|
||||
@@ -3,6 +3,7 @@ import { ParkingSquare, Hourglass, AlertTriangle, BedDouble } from 'lucide-react
|
||||
import Modal from '../shared/Modal'
|
||||
import CustomSelect from '../shared/CustomSelect'
|
||||
import { useTranslation } from '../../i18n/TranslationContext'
|
||||
import { safeExternalHref } from '../../utils/safeUrl'
|
||||
import { formatDurationShort, SERVICE_COLORS } from './roadtripModel'
|
||||
import { STOP_KINDS, STOP_KIND_BY_KEY } from './stopKinds'
|
||||
import type { CorridorPoi } from './useCorridorPois'
|
||||
@@ -71,6 +72,13 @@ export default function RoadtripStopPopup({
|
||||
draft, duplicateName, onClose, onSave, onSaveNight, onMoreDetails,
|
||||
}: RoadtripStopPopupProps): React.ReactElement | null {
|
||||
const { t } = useTranslation()
|
||||
// Through the same guard every other external link in the app goes through.
|
||||
// This value is an unvalidated OpenStreetMap tag, and OSM `website` tags are
|
||||
// routinely written without a scheme — `www.hotel.de` as a raw href is a
|
||||
// RELATIVE url, so the click navigated the planner to
|
||||
// /trips/<id>/www.hotel.de instead of leaving the app. The helper adds the
|
||||
// scheme for a bare host and drops anything that is not http(s).
|
||||
const websiteHref = safeExternalHref(draft?.poi.website)
|
||||
const suggested = STOP_KINDS.find(k => k.key === draft?.poi.category)
|
||||
const [stopType, setStopType] = useState<RoadtripStopType | null>(suggested?.key ?? null)
|
||||
const [dwell, setDwell] = useState<number>(suggested?.defaultMinutes ?? 30)
|
||||
@@ -210,16 +218,16 @@ export default function RoadtripStopPopup({
|
||||
{/* What OSM knows about the house, which is the whole of what we offer: no
|
||||
price, no availability, no link into a booking portal. TREK links to maps
|
||||
and to the place's own site, never to a vendor. */}
|
||||
{draft.poi.website || draft.poi.phone ? (
|
||||
{websiteHref || draft.poi.phone ? (
|
||||
<div className="flex flex-wrap gap-x-3 gap-y-1 text-caption">
|
||||
{draft.poi.website ? (
|
||||
{websiteHref ? (
|
||||
<a
|
||||
href={draft.poi.website}
|
||||
href={websiteHref}
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
className="text-accent hover:underline"
|
||||
>
|
||||
{t('places.website')}
|
||||
{t('places.formWebsite')}
|
||||
</a>
|
||||
) : null}
|
||||
{draft.poi.phone ? (
|
||||
|
||||
@@ -167,9 +167,21 @@ export function corridorTiles(line: LatLng[], widthKm: number, maxSpanDeg = 0.45
|
||||
}
|
||||
}
|
||||
|
||||
// The point the open box last swallowed. When a box closes, the next one starts
|
||||
// from it rather than from `p` alone, so the two overlap by exactly one step of
|
||||
// the walk. Starting at `p` left the stretch between them covered only by the
|
||||
// padding on either side — and the walk steps in up to maxSpanDeg/2 while the
|
||||
// padding is widthKm, so at the offered widths a band of several kilometres of
|
||||
// route fell into no box at all. Nothing downstream noticed: the panel counts
|
||||
// tiles asked and tiles answered, so it reported a finished, uncapped,
|
||||
// error-free search of a drive it had never fully looked at. "Find fuel along
|
||||
// the route" is the whole feature.
|
||||
let previous: LatLng | null = null
|
||||
|
||||
for (const p of densify(line, maxSpanDeg / 2)) {
|
||||
if (!current) {
|
||||
current = { south: p.lat, north: p.lat, west: p.lng, east: p.lng }
|
||||
previous = p
|
||||
continue
|
||||
}
|
||||
const next: Bbox = {
|
||||
@@ -181,10 +193,17 @@ export function corridorTiles(line: LatLng[], widthKm: number, maxSpanDeg = 0.45
|
||||
const grown = padded(next)
|
||||
if (grown.north - grown.south > maxSpanDeg || grown.east - grown.west > maxSpanDeg) {
|
||||
tiles.push(padded(current))
|
||||
current = { south: p.lat, north: p.lat, west: p.lng, east: p.lng }
|
||||
const from = previous ?? p
|
||||
current = {
|
||||
south: Math.min(from.lat, p.lat),
|
||||
north: Math.max(from.lat, p.lat),
|
||||
west: Math.min(from.lng, p.lng),
|
||||
east: Math.max(from.lng, p.lng),
|
||||
}
|
||||
} else {
|
||||
current = next
|
||||
}
|
||||
previous = p
|
||||
}
|
||||
if (current) tiles.push(padded(current))
|
||||
return tiles
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
reanchorAfterInsert,
|
||||
reanchorAfterRemove,
|
||||
reanchorByStopOrder,
|
||||
reanchorAfterReorder,
|
||||
isEmptyReanchoring,
|
||||
type AnchoredVia,
|
||||
@@ -123,4 +124,54 @@ describe('reanchorAfterReorder', () => {
|
||||
it('FE-REANCHOR-016: no vias means no request', () => {
|
||||
expect(isEmptyReanchoring(reanchorAfterReorder([], 0, 2, 4))).toBe(true)
|
||||
})
|
||||
|
||||
it('FE-REANCHOR-017: swapping the only two stops keeps every via', () => {
|
||||
// A reorder removes nothing. Leg 0 is still leg 0 after the swap, merely
|
||||
// driven the other way round, so the anchors are already right. Routing this
|
||||
// through the removal half asked the server to delete every via of the day —
|
||||
// and two stops is exactly the shape "follow this track" produces, up to
|
||||
// nine vias on that one leg, gone to a single drag with no prompt and no
|
||||
// undo.
|
||||
const vias = [via(11, 0), via(12, 0), via(13, 0)]
|
||||
|
||||
for (const [from, to] of [[0, 1], [1, 0]] as const) {
|
||||
const plan = reanchorAfterReorder(vias, from, to, 2)
|
||||
expect(plan.remove, `${from}->${to}`).toEqual([])
|
||||
expect(isEmptyReanchoring(plan), `${from}->${to}`).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-REANCHOR-019: a wholesale reorder follows the stop, not the number', () => {
|
||||
// The plan-mode drag hands a whole new ordering rather than one move, so the
|
||||
// anchors are mapped by the stop they were pinned behind. Stops A,B,C,D with
|
||||
// a via on the C->D leg (anchor 2): move A to the end and C is now at index
|
||||
// 1, so the via belongs on leg 1.
|
||||
const plan = reanchorByStopOrder([via(1, 2)], [10, 20, 30, 40], [20, 30, 40, 10])
|
||||
expect(plan.vias).toEqual([{ id: 1, after_order_index: 1 }])
|
||||
expect(plan.remove).toEqual([])
|
||||
})
|
||||
|
||||
it('FE-REANCHOR-020: a via whose stop became the last one has no leg left', () => {
|
||||
// Nothing follows the final stop, so there is no drive for the via to bend.
|
||||
const plan = reanchorByStopOrder([via(1, 0)], [10, 20, 30], [20, 30, 10])
|
||||
expect(plan.remove).toEqual([1])
|
||||
})
|
||||
|
||||
it('FE-REANCHOR-021: a stop that is gone takes its vias with it', () => {
|
||||
const plan = reanchorByStopOrder([via(1, 1)], [10, 20, 30], [10, 30])
|
||||
expect(plan.remove).toEqual([1])
|
||||
})
|
||||
|
||||
it('FE-REANCHOR-022: an ordering that did not actually change asks for nothing', () => {
|
||||
expect(isEmptyReanchoring(reanchorByStopOrder([via(1, 0)], [10, 20, 30], [10, 20, 30]))).toBe(true)
|
||||
})
|
||||
|
||||
it('FE-REANCHOR-018: removing a stop from a two-stop day still clears the leg', () => {
|
||||
// The other half of the same rule, and the reason the short-circuit exists:
|
||||
// take a stop away from a two-stop day and there is no drive left, so a via
|
||||
// has nowhere to sit.
|
||||
const plan = reanchorAfterRemove([via(11, 0), via(12, 0)], 1, 2)
|
||||
expect(plan.remove).toEqual([11, 12])
|
||||
expect(plan.vias).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -116,6 +116,55 @@ describe('computeSchedule', () => {
|
||||
expect(entries[2].arrival).toBe('13:00')
|
||||
})
|
||||
|
||||
it('ROADTRIP-MODEL-082: a night drive onto a pinned time after midnight is on time', () => {
|
||||
// Leave at 20:00, drive six hours, check in at 02:00. The anchor used to be
|
||||
// placed on the day the cascade had reached so far — and that only advances
|
||||
// once a computed arrival crosses midnight, which is read before this stop's
|
||||
// arrival is known. So the stop that does the crossing had its own pin put a
|
||||
// whole day early: the rail drew a warning-coloured "+24 h" on a plan that
|
||||
// was exactly on time, and dropped the overnight marker with it.
|
||||
const { entries, warnings } = computeSchedule(
|
||||
[
|
||||
{ anchor: '20:00', dwellMinutes: 0 },
|
||||
{ anchor: '02:00', dwellMinutes: 0 },
|
||||
],
|
||||
[hours(6)],
|
||||
)
|
||||
|
||||
expect(warnings.filter(w => w.code === 'late')).toEqual([])
|
||||
expect(entries[1]).toMatchObject({ arrival: '02:00', dayOffset: 1, anchored: true })
|
||||
// The day still turned over, so the rail keeps its carry badge.
|
||||
expect(warnings.some(w => w.code === 'overnight' && w.index === 1)).toBe(true)
|
||||
})
|
||||
|
||||
it('ROADTRIP-MODEL-083: a ferry that really is missed is still reported late', () => {
|
||||
// The other half: picking the nearest occurrence must not swallow a genuine
|
||||
// delay. Leaving at 21:00 and driving five hours arrives at 02:00, half an
|
||||
// hour after the 01:30 ferry, and that is what it says.
|
||||
const { warnings } = computeSchedule(
|
||||
[
|
||||
{ anchor: '21:00', dwellMinutes: 0 },
|
||||
{ anchor: '01:30', dwellMinutes: 0 },
|
||||
],
|
||||
[hours(5)],
|
||||
)
|
||||
expect(warnings.find(w => w.code === 'late')).toMatchObject({ index: 1, minutes: 30 })
|
||||
})
|
||||
|
||||
it('ROADTRIP-MODEL-084: a pinned stop after an untimed leg keeps the day it is on', () => {
|
||||
// Nothing to be late against, but the day carried so far still applies —
|
||||
// otherwise the stop prints under a day-1 stop as though it happened first.
|
||||
const { entries } = computeSchedule(
|
||||
[
|
||||
{ anchor: '20:00', dwellMinutes: 0 },
|
||||
{ anchor: '02:00', dwellMinutes: 0 },
|
||||
{ anchor: '09:00', dwellMinutes: 0 },
|
||||
],
|
||||
[hours(6), undefined],
|
||||
)
|
||||
expect(entries[2]).toMatchObject({ arrival: '09:00', dayOffset: 1 })
|
||||
})
|
||||
|
||||
it('reports a stop the drive cannot reach in time', () => {
|
||||
const { warnings } = computeSchedule(
|
||||
[
|
||||
|
||||
@@ -184,17 +184,30 @@ export interface Schedule {
|
||||
* cascade from there. When it sits before the arrival the drive implies, the plan does
|
||||
* not fit: the caller is told by how much rather than the pinned time being moved.
|
||||
*/
|
||||
const DAY_MINUTES = 24 * 60
|
||||
|
||||
function resolveArrival(
|
||||
anchor: number | null,
|
||||
cursor: number | null,
|
||||
dayOffset: number,
|
||||
): { arrival: number | null; lateBy: number | null } {
|
||||
if (anchor === null) return { arrival: cursor, lateBy: null }
|
||||
if (cursor === null) return { arrival: anchor, lateBy: null }
|
||||
const anchorToday = anchor + dayOffset * 24 * 60
|
||||
// No drive has been timed yet, so there is nothing to be late against — but the
|
||||
// day carried so far still applies, or a pinned stop after an untimed leg
|
||||
// prints under a day-1 stop as though it happened first.
|
||||
if (cursor === null) return { arrival: anchor + dayOffset * DAY_MINUTES, lateBy: null }
|
||||
// The occurrence of that wall-clock time nearest the cursor, not the one on the
|
||||
// day the cascade has reached so far. `dayOffset` only advances once a computed
|
||||
// arrival crosses midnight, and it is read before this stop's arrival is known —
|
||||
// so when the stop that crosses midnight is the pinned one, its anchor was
|
||||
// placed a whole day early and the plan was reported as 24 hours late while
|
||||
// being exactly on time. Rounding also keeps the ordinary case: 08:00, a three
|
||||
// hour leg, a 09:00 pin still picks the same day and is two hours late.
|
||||
const k = Math.round((cursor - anchor) / DAY_MINUTES)
|
||||
const anchorAt = anchor + k * DAY_MINUTES
|
||||
return {
|
||||
arrival: anchorToday,
|
||||
lateBy: cursor > anchorToday + 1 ? Math.round(cursor - anchorToday) : null,
|
||||
arrival: anchorAt,
|
||||
lateBy: cursor > anchorAt + 1 ? Math.round(cursor - anchorAt) : null,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -535,6 +548,40 @@ export function reanchorAfterRemove(vias: AnchoredVia[], position: number, stopC
|
||||
* `stopCount` is the number of stops BEFORE the move. `to` is the index in the list as
|
||||
* it looks AFTER the stop has been taken out.
|
||||
*/
|
||||
/**
|
||||
* Re-pin a day's vias after its stops were reordered wholesale.
|
||||
*
|
||||
* The single-move helpers above take a from/to pair, which is what the rail
|
||||
* hands them. The plan-mode drag hands a whole new ordering instead, and any
|
||||
* permutation is possible — so this maps by the stop each anchor refers to
|
||||
* rather than by arithmetic on the index. A via anchored after a stop stays
|
||||
* anchored after that same stop, wherever it ended up.
|
||||
*
|
||||
* Both lists are in the rail's index space, i.e. only stops that can be routed.
|
||||
* A via whose stop is gone, or which lands on the last stop and so has no leg
|
||||
* left to bend, is reported for removal.
|
||||
*/
|
||||
export function reanchorByStopOrder(
|
||||
vias: AnchoredVia[],
|
||||
previousIds: number[],
|
||||
nextIds: number[],
|
||||
): Reanchoring {
|
||||
if (!vias.length) return EMPTY_REANCHORING
|
||||
const moved: ReanchoredVia[] = []
|
||||
const remove: number[] = []
|
||||
for (const via of vias) {
|
||||
const stopId = previousIds[via.after_order_index]
|
||||
const next = stopId === undefined ? -1 : nextIds.indexOf(stopId)
|
||||
// Gone, or now the last stop of the day: either way there is no leg for it.
|
||||
if (next === -1 || next >= nextIds.length - 1) {
|
||||
remove.push(via.id)
|
||||
continue
|
||||
}
|
||||
if (next !== via.after_order_index) moved.push({ id: via.id, after_order_index: next })
|
||||
}
|
||||
return { vias: moved, remove }
|
||||
}
|
||||
|
||||
export function reanchorAfterReorder(
|
||||
vias: AnchoredVia[],
|
||||
from: number,
|
||||
@@ -542,6 +589,17 @@ export function reanchorAfterReorder(
|
||||
stopCount: number,
|
||||
): Reanchoring {
|
||||
if (!vias.length || from === to) return EMPTY_REANCHORING
|
||||
// A reorder is modelled as remove-then-insert, and the removal half refuses to
|
||||
// treat a two-stop day as still having a drive: below three stops it reports
|
||||
// every via for deletion, which is right when a stop really goes away and
|
||||
// catastrophic here. Nothing is removed by a reorder — swapping the only two
|
||||
// stops leaves leg 0 exactly where it was, merely driven the other way round —
|
||||
// so the anchors are already correct and there is nothing to re-pin.
|
||||
//
|
||||
// Two stops is the shape "follow this track" produces: it lays up to nine vias
|
||||
// on the single leg between one pair, and one drag in the rail deleted all of
|
||||
// them, with no prompt and no undo.
|
||||
if (stopCount <= 2) return EMPTY_REANCHORING
|
||||
const afterRemove = reanchorAfterRemove(vias, from, stopCount)
|
||||
const dropped = new Set(afterRemove.remove)
|
||||
const movedTo = new Map(afterRemove.vias.map(v => [v.id, v.after_order_index] as const))
|
||||
|
||||
@@ -48,6 +48,7 @@ function viasStub(over: Partial<RoadtripVias> = {}): RoadtripVias {
|
||||
return {
|
||||
byDay: {},
|
||||
trackByDay: {},
|
||||
stale: false,
|
||||
add: vi.fn(),
|
||||
addMany: vi.fn().mockResolvedValue(undefined),
|
||||
move: vi.fn(),
|
||||
|
||||
@@ -43,12 +43,37 @@ describe('useRoadtripVias', () => {
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-VIAS-003: an addon that is switched off means no vias, not an error', async () => {
|
||||
roadtripApi.listVias.mockRejectedValue(new Error('404'))
|
||||
// Shaped like the rejection axios actually produces, so the branch that
|
||||
// reads the status is the one under test.
|
||||
roadtripApi.listVias.mockRejectedValue({ response: { status: 404 } })
|
||||
|
||||
const { result } = renderHook(() => useRoadtripVias(7, true))
|
||||
|
||||
await waitFor(() => expect(roadtripApi.listVias).toHaveBeenCalled())
|
||||
expect(result.current.byDay).toEqual({})
|
||||
expect(result.current.stale).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-VIAS-007: a read that fails for another reason keeps the vias it has', async () => {
|
||||
// This read runs after every write, and the via list feeds the routing key.
|
||||
// Emptying on a 502, a dropped connection or a tab that just went offline
|
||||
// re-routed the whole trip along the roads the traveller had steered away
|
||||
// from — with no toast, nothing retrying, and no way to tell it apart from
|
||||
// having deleted them.
|
||||
roadtripApi.listVias.mockResolvedValue({ vias: [via({ id: 1, day_id: 1 })] })
|
||||
const { result } = renderHook(() => useRoadtripVias(7, true))
|
||||
await waitFor(() => expect(result.current.byDay[1]).toHaveLength(1))
|
||||
|
||||
roadtripApi.listVias.mockRejectedValue({ response: { status: 502 } })
|
||||
await act(async () => { await result.current.move(1, 1, 54, 11) })
|
||||
|
||||
expect(result.current.byDay[1]).toHaveLength(1)
|
||||
expect(result.current.stale).toBe(true)
|
||||
|
||||
// And a read that works again clears the doubt.
|
||||
roadtripApi.listVias.mockResolvedValue({ vias: [via({ id: 1, day_id: 1 })] })
|
||||
await act(async () => { await result.current.move(1, 1, 54, 11) })
|
||||
expect(result.current.stale).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-VIAS-004: adding one re-reads the list rather than guessing its id', async () => {
|
||||
|
||||
@@ -14,6 +14,16 @@ export interface RoadtripVias {
|
||||
* with the place, so nothing here can name a line that no longer exists.
|
||||
*/
|
||||
trackByDay: Record<number, RoadtripDayTrack>
|
||||
/**
|
||||
* True when the last read failed for a reason other than "there is nothing
|
||||
* here", so what is drawn may be older than what the server holds.
|
||||
*
|
||||
* The read runs after every write, and the via list feeds the routing key, so
|
||||
* emptying on a transient failure re-routed the whole trip along the roads the
|
||||
* traveller had steered away from — indistinguishable from having deleted
|
||||
* them. The list is kept and the staleness is said instead.
|
||||
*/
|
||||
stale: boolean
|
||||
add: (dayId: number, afterOrderIndex: number, lat: number, lng: number) => Promise<void>
|
||||
/**
|
||||
* Lay a chain of vias on one day, optionally clearing the legs it fills first.
|
||||
@@ -58,6 +68,14 @@ const EMPTY_TRACKS: Record<number, RoadtripDayTrack> = {}
|
||||
export function useRoadtripVias(tripId: number | string | null, active: boolean): RoadtripVias {
|
||||
const [byDay, setByDay] = useState<Record<number, RoadtripVia[]>>(EMPTY)
|
||||
const [trackByDay, setTrackByDay] = useState<Record<number, RoadtripDayTrack>>(EMPTY_TRACKS)
|
||||
/**
|
||||
* The list on screen may be older than the server's.
|
||||
*
|
||||
* Set when a read fails for a reason that is not "there is nothing here", so
|
||||
* the rail can say the shaping it is drawing might be out of date rather than
|
||||
* quietly showing a trip that has lost its detours.
|
||||
*/
|
||||
const [stale, setStale] = useState(false)
|
||||
|
||||
const group = useCallback((vias: RoadtripVia[]) => {
|
||||
const next: Record<number, RoadtripVia[]> = {}
|
||||
@@ -73,11 +91,26 @@ export function useRoadtripVias(tripId: number | string | null, active: boolean)
|
||||
const byId: Record<number, RoadtripDayTrack> = {}
|
||||
for (const track of tracks ?? []) byId[track.day_id] = track
|
||||
setTrackByDay(byId)
|
||||
} catch {
|
||||
// An instance with the addon off answers 404 here, which is not an error worth
|
||||
// reporting — it just means there are no vias to draw.
|
||||
setByDay(EMPTY)
|
||||
setTrackByDay(EMPTY_TRACKS)
|
||||
setStale(false)
|
||||
} catch (err) {
|
||||
// An instance with the addon off answers 404 here, and a caller without
|
||||
// the permission 403. Neither is worth reporting: it just means there are
|
||||
// no vias to draw, and emptying is the truthful answer.
|
||||
//
|
||||
// Anything else is not. This read runs after every write, so a 502 from a
|
||||
// proxy, a dropped connection or a tab that has just gone offline used to
|
||||
// empty the map — and because the via list feeds the routing key, the whole
|
||||
// trip was then re-routed along the roads the traveller had steered away
|
||||
// from. Nothing said so, nothing retried, and it looked exactly like
|
||||
// having deleted them. The last known list is kept instead.
|
||||
const status = (err as { response?: { status?: number } } | null)?.response?.status
|
||||
if (status === 404 || status === 403) {
|
||||
setByDay(EMPTY)
|
||||
setTrackByDay(EMPTY_TRACKS)
|
||||
setStale(false)
|
||||
return
|
||||
}
|
||||
setStale(true)
|
||||
}
|
||||
}, [tripId, active, group])
|
||||
|
||||
@@ -126,5 +159,5 @@ export function useRoadtripVias(tripId: number | string | null, active: boolean)
|
||||
await reload()
|
||||
}, [tripId, reload])
|
||||
|
||||
return { byDay, trackByDay, add, addMany, move, remove, reanchor }
|
||||
return { byDay, trackByDay, stale, add, addMany, move, remove, reanchor }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user