diff --git a/client/src/pages/tripPlanner/useRoadtripAlternatives.test.ts b/client/src/pages/tripPlanner/useRoadtripAlternatives.test.ts new file mode 100644 index 000000000..e8da14546 --- /dev/null +++ b/client/src/pages/tripPlanner/useRoadtripAlternatives.test.ts @@ -0,0 +1,396 @@ +// FE-TP-ALTERNATIVES-001 to FE-TP-ALTERNATIVES-015 +// +// The other ways of driving one leg and what the road trip map frames, driven straight +// through useRoadtripAlternatives. The picker's own state and the pin search are +// fixtures with suites of their own; the drive helpers beside them stay real, since +// which leg a choice lands on is what these cases are about. +import { act, renderHook } from '@testing-library/react' +import type { PinProof } from '../../components/Roadtrip/alternativePins' +import type { LegAlternatives, OfferedRoute } from '../../components/Roadtrip/useRouteAlternatives' +import { openLeg } from '../../../tests/helpers/legAlternatives' +import type { Translate } from './plannerTypes' +import type { RoadtripFeed } from './useRoadtripFeed' +import { useRoadtripAlternatives } from './useRoadtripAlternatives' + +const fx = vi.hoisted(() => ({ + alt: { + open: null as unknown, + ask: vi.fn(), + close: vi.fn(), + prove: vi.fn(), + settle: vi.fn(), + }, + pin: vi.fn(), +})) + +vi.mock('../../components/Roadtrip/useRouteAlternatives', async importOriginal => ({ + ...(await importOriginal()), + useRouteAlternatives: () => fx.alt, +})) +vi.mock('../../components/Roadtrip/alternativePins', async importOriginal => ({ + ...(await importOriginal()), + pinAlternative: (...args: unknown[]) => fx.pin(...args), +})) + +type Options = Parameters[0] +type Via = { id: number; day_id: number; after_order_index: number; sequence: number; lat: number; lng: number } + +const toast = { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() } +const t: Translate = (key, params) => (params ? `${key} ${JSON.stringify(params)}` : key) + +const stopAt = (assignmentId: number, ownerDayId: number, ownerIndex: number, lng: number, extra: object = {}) => ( + { assignmentId, ownerDayId, ownerIndex, placeId: assignmentId, name: `Stop ${assignmentId}`, lat: 50, lng, ...extra } +) +const seg = { distance: 70000, duration: 3600, mode: 'driving' } + +// Day 2 drives three stops, and arrives from the last stop of day 1. Day 3 has a single +// stop: it draws no card, but the drive into it leaves from day 2's last stop. +const dayOneEnd = stopAt(13, 1, 2, 9) +const dayTwo = { + dayId: 2, dayNumber: 2, + stops: [stopAt(21, 2, 0, 10), stopAt(22, 2, 1, 11), stopAt(23, 2, 2, 12)], + legs: [seg, seg], + legLines: [[[50, 10], [50, 11]]], + arrivingFrom: dayOneEnd, arrivingLeg: seg, arrivingLine: [[50, 9], [50, 10]], + schedule: { entries: [] }, + geometry: [[50, 10], [50, 11], [50, 12]], +} +const quietDay = { dayId: 3, dayNumber: 3, stops: [stopAt(31, 3, 0, 13)] } + +const offers: OfferedRoute[] = [ + { coordinates: [[50, 10], [50.2, 10.5], [50, 11]], distance: 70000, duration: 3600, divergence: null, current: true }, + { coordinates: [[50, 10], [49.6, 10.5], [50, 11]], distance: 90000, duration: 4200, divergence: null, hasFerry: true }, + { coordinates: [[50, 10], [49.8, 10.5], [50, 11]], distance: 80000, duration: 3900, divergence: null, direct: true }, +] + +let router: { mode: string; avoid: string[]; engine: string; route: ReturnType } +let routes: Record & { days: unknown[]; quietDays: unknown[]; legRouter: ReturnType; reroute: ReturnType } +let vias: { byDay: Record; editable: boolean; addMany: ReturnType } +let refuel: { offered: Array<{ lat: number; lng: number }>; close: ReturnType } +let signal: AbortController + +function baseOptions(over: Partial = {}): Options { + return { + t, toast, isMobile: false, activeTab: 'plan', roadtripActive: true, roadtripFeedActive: true, + roadtripRoutes: routes as unknown as RoadtripFeed['roadtripRoutes'], + roadtripVias: vias as unknown as RoadtripFeed['roadtripVias'], + refuel: refuel as unknown as RoadtripFeed['refuel'], + collapsedRoadtripDays: new Set(), + ...over, + } +} + +function renderAlternatives(over: Partial = {}) { + return renderHook((props: Options) => useRoadtripAlternatives(props), { initialProps: baseOptions(over) }) +} + +/** The picker open on day 2's first leg, as the rail asked about it. */ +function openFirstLeg(over: Partial = {}) { + fx.alt.open = openLeg({ routes: offers, ends: { from: 21, to: 22 }, ...over }) +} + +const proof = (over: Partial = {}): PinProof => ({ + held: true, pins: [{ lat: 49.6, lng: 10.5 }], fellBack: false, + last: { coordinates: [], distance: 0, duration: 0 } as unknown as PinProof['last'], ...over, +}) + +beforeEach(() => { + vi.clearAllMocks() + fx.alt.open = null + signal = new AbortController() + fx.alt.prove.mockImplementation(() => signal.signal) + fx.pin.mockReset().mockResolvedValue(proof()) + router = { mode: 'driving', avoid: [], engine: 'osrm', route: vi.fn() } + routes = { + days: [dayTwo], quietDays: [quietDay], lines: [], lineDays: [], vias: [{ lat: 1, lng: 2 }], + legRouter: vi.fn(() => router), reroute: vi.fn(), + } + vias = { byDay: {}, editable: true, addMany: vi.fn(async () => undefined) } + refuel = { offered: [], close: vi.fn() } +}) + +describe('useRoadtripAlternatives', () => { + it('FE-TP-ALTERNATIVES-001: with the picker closed nothing is offered, highlighted or framed', () => { + const { result } = renderAlternatives() + + expect(result.current.routeAlternatives).toBe(fx.alt) + expect(result.current.highlightedAlternative).toBeNull() + expect(result.current.alternativeOverlays).toEqual([]) + expect(result.current.alternativeFocusPoints).toEqual([]) + expect(result.current.mapFocusPoints).toEqual([]) + expect(result.current.roadtripMapVias).toEqual([{ lat: 1, lng: 2 }]) + expect(fx.alt.close).not.toHaveBeenCalled() + }) + + it('FE-TP-ALTERNATIVES-002: the highlighted road is forgotten once the picker closes', () => { + openFirstLeg() + const { result, rerender } = renderAlternatives() + + act(() => { result.current.setHighlightedAlternative(1) }) + expect(result.current.highlightedAlternative).toBe(1) + + fx.alt.open = null + rerender(baseOptions()) + expect(result.current.highlightedAlternative).toBeNull() + }) + + it('FE-TP-ALTERNATIVES-003: the picker closes wherever it can no longer be seen', () => { + // At the desk it lives in road trip mode. + const desk = renderAlternatives({ roadtripActive: false }) + expect(fx.alt.close).toHaveBeenCalledTimes(1) + desk.unmount() + + // On the phone it lives on the drive tab, and leaving the tab closes it. + fx.alt.close.mockClear() + const phone = { isMobile: true, roadtripActive: false } + const { rerender } = renderAlternatives({ ...phone, activeTab: 'roadtrip' }) + expect(fx.alt.close).not.toHaveBeenCalled() + rerender(baseOptions({ ...phone, activeTab: 'plan' })) + expect(fx.alt.close).toHaveBeenCalledTimes(1) + rerender(baseOptions({ ...phone, activeTab: 'roadtrip' })) + expect(fx.alt.close).toHaveBeenCalledTimes(1) + // Without the feed there is no drive to offer other ways of. + rerender(baseOptions({ ...phone, activeTab: 'roadtrip', roadtripFeedActive: false })) + expect(fx.alt.close).toHaveBeenCalledTimes(2) + }) + + it('FE-TP-ALTERNATIVES-004: the offers are drawn, framed, and give way to refuel offers on the map', () => { + openFirstLeg() + const { result, rerender } = renderAlternatives() + + expect(result.current.alternativeOverlays.map(o => o.note)).toEqual(['roadtrip.alt.current', '', '']) + expect(result.current.alternativeFocusPoints).toEqual(offers.flatMap(o => o.coordinates)) + expect(result.current.mapFocusPoints).toBe(result.current.alternativeFocusPoints) + + refuel.offered = [{ lat: 48, lng: 9 }, { lat: 48.5, lng: 9.5 }] + rerender(baseOptions()) + expect(result.current.mapFocusPoints).toEqual([[48, 9], [48.5, 9.5]]) + }) + + it('FE-TP-ALTERNATIVES-005: focusing a point on the drive closes both pickers and frames that point', () => { + const { result, rerender } = renderAlternatives() + + act(() => { result.current.focusRoadtripPoint(50.5, 10.5) }) + expect(refuel.close).toHaveBeenCalled() + expect(fx.alt.close).toHaveBeenCalled() + expect(result.current.mapFocusPoints).toEqual([[50.5, 10.5]]) + + // A rail rebuilt since is a different drive: the point no longer stands. + routes.days = [{ ...dayTwo }] + rerender(baseOptions()) + expect(result.current.mapFocusPoints).toEqual([]) + }) + + it('FE-TP-ALTERNATIVES-006: asking about a leg hands the picker the leg as the rail drives it', () => { + const { result } = renderAlternatives() + + act(() => { result.current.askRouteAlternatives(2, { kind: 'leg', index: 0 }) }) + expect(routes.legRouter).toHaveBeenCalledWith(dayTwo.stops[0], dayTwo.stops[1], 2) + expect(fx.alt.ask).toHaveBeenCalledWith({ + dayId: 2, + drive: { kind: 'leg', index: 0 }, + from: { lat: 50, lng: 10 }, + to: { lat: 50, lng: 11 }, + driven: { coordinates: [[50, 10], [50, 11]], distance: 70000, duration: 3600 }, + anchor: { dayId: 2, afterIndex: 0 }, + ends: { from: 21, to: 22 }, + router, + }) + + // A leg the rail drew no line for is asked about with an empty one. + act(() => { result.current.askRouteAlternatives(2, { kind: 'leg', index: 1 }) }) + expect(fx.alt.ask).toHaveBeenLastCalledWith(expect.objectContaining({ + driven: { coordinates: [], distance: 70000, duration: 3600 }, + anchor: { dayId: 2, afterIndex: 1 }, + })) + + // The drive arriving at the head of the card is filed behind yesterday's last stop. + act(() => { result.current.askRouteAlternatives(2, { kind: 'arriving' }) }) + expect(fx.alt.ask).toHaveBeenLastCalledWith(expect.objectContaining({ + from: { lat: 50, lng: 9 }, + anchor: { dayId: 1, afterIndex: 2 }, + ends: { from: 13, to: 21 }, + })) + }) + + it('FE-TP-ALTERNATIVES-007: a second ask about the open leg closes it, and an unknown leg asks nothing', () => { + openFirstLeg() + const { result } = renderAlternatives() + + act(() => { result.current.askRouteAlternatives(2, { kind: 'leg', index: 0 }) }) + expect(fx.alt.close).toHaveBeenCalledTimes(1) + expect(fx.alt.ask).not.toHaveBeenCalled() + + act(() => { + result.current.askRouteAlternatives(9, { kind: 'leg', index: 0 }) + result.current.askRouteAlternatives(2, { kind: 'leg', index: 5 }) + }) + routes.legRouter.mockReturnValueOnce(undefined) + act(() => { result.current.askRouteAlternatives(2, { kind: 'leg', index: 1 }) }) + expect(fx.alt.ask).not.toHaveBeenCalled() + }) + + it('FE-TP-ALTERNATIVES-008: a choice that cannot be checked is not tried', async () => { + const { result, rerender } = renderAlternatives() + await act(async () => { await result.current.chooseRouteAlternative(1) }) + expect(fx.alt.prove).not.toHaveBeenCalled() + + openFirstLeg() + rerender(baseOptions()) + await act(async () => { await result.current.chooseRouteAlternative(7) }) + expect(fx.alt.prove).not.toHaveBeenCalled() + + // The road already driven changes nothing and just closes the picker. + await act(async () => { await result.current.chooseRouteAlternative(0) }) + expect(fx.alt.close).toHaveBeenCalledTimes(1) + + openFirstLeg({ proving: 2 }) + rerender(baseOptions()) + await act(async () => { await result.current.chooseRouteAlternative(1) }) + expect(fx.alt.prove).not.toHaveBeenCalled() + + openFirstLeg() + vias.editable = false + rerender(baseOptions()) + await act(async () => { await result.current.chooseRouteAlternative(1) }) + expect(toast.error).toHaveBeenCalledWith('roadtrip.alt.offline') + expect(fx.alt.prove).not.toHaveBeenCalled() + }) + + it('FE-TP-ALTERNATIVES-009: a check the router could not answer is said in the bar, and on the phone as a toast', async () => { + openFirstLeg() + fx.pin.mockRejectedValue(new Error('429')) + const { result, rerender } = renderAlternatives() + + await act(async () => { await result.current.chooseRouteAlternative(1) }) + expect(fx.alt.prove).toHaveBeenCalledWith(1) + expect(fx.pin).toHaveBeenCalledWith({ offer: offers[1], current: offers[0], route: (fx.alt.open as LegAlternatives).route, signal: signal.signal }) + expect(fx.alt.settle).toHaveBeenCalledWith('roadtrip.alt.failed') + expect(toast.error).not.toHaveBeenCalled() + + rerender(baseOptions({ isMobile: true })) + await act(async () => { await result.current.chooseRouteAlternative(1) }) + expect(toast.error).toHaveBeenCalledWith('roadtrip.alt.failed') + + // Abandoned on the way: nobody is waiting for the answer any more. + fx.alt.settle.mockClear() + signal.abort() + await act(async () => { await result.current.chooseRouteAlternative(1) }) + expect(fx.alt.settle).not.toHaveBeenCalled() + }) + + it('FE-TP-ALTERNATIVES-010: a way the router will not hold is refused with the way out, where there is one', async () => { + openFirstLeg() + const { result, rerender } = renderAlternatives() + + fx.pin.mockResolvedValueOnce(proof({ held: false, pins: [], last: { hasFerry: false } as unknown as PinProof['last'] })) + await act(async () => { await result.current.chooseRouteAlternative(1) }) + expect(fx.alt.settle).toHaveBeenLastCalledWith('roadtrip.alt.notHeld roadtrip.alt.ferryNotHeld') + expect(toast.error).not.toHaveBeenCalled() + + fx.pin.mockResolvedValueOnce(proof({ held: false, pins: [] })) + await act(async () => { await result.current.chooseRouteAlternative(2) }) + expect(fx.alt.settle).toHaveBeenLastCalledWith('roadtrip.alt.notHeld') + + fx.pin.mockResolvedValueOnce(proof({ held: false, pins: [], fellBack: true })) + await act(async () => { await result.current.chooseRouteAlternative(1) }) + expect(fx.alt.settle).toHaveBeenLastCalledWith('roadtrip.alt.failed') + + rerender(baseOptions({ isMobile: true })) + fx.pin.mockResolvedValueOnce(proof({ held: false, pins: [], last: { hasFerry: false } as unknown as PinProof['last'] })) + await act(async () => { await result.current.chooseRouteAlternative(1) }) + expect(toast.error).toHaveBeenLastCalledWith('roadtrip.alt.notHeld', 6000) + expect(toast.info).toHaveBeenLastCalledWith('roadtrip.alt.ferryNotHeld', 8000) + + fx.pin.mockResolvedValueOnce(proof({ held: false, pins: [] })) + await act(async () => { await result.current.chooseRouteAlternative(2) }) + expect(toast.error).toHaveBeenLastCalledWith('roadtrip.alt.notHeld', 6000) + expect(toast.info).toHaveBeenCalledTimes(1) + }) + + it('FE-TP-ALTERNATIVES-011: an answer that comes back after the picker moved on writes nothing', async () => { + openFirstLeg() + fx.pin.mockImplementation(async () => { signal.abort(); return proof() }) + const { result } = renderAlternatives() + + await act(async () => { await result.current.chooseRouteAlternative(1) }) + expect(vias.addMany).not.toHaveBeenCalled() + expect(fx.alt.settle).not.toHaveBeenCalled() + expect(fx.alt.close).not.toHaveBeenCalled() + }) + + it('FE-TP-ALTERNATIVES-012: a leg that changed under the check is not written', async () => { + openFirstLeg({ ends: { from: 21, to: 23 } }) + const { result, rerender } = renderAlternatives() + + await act(async () => { await result.current.chooseRouteAlternative(1) }) + expect(toast.error).toHaveBeenCalledWith('roadtrip.alt.legChanged', 6000) + expect(fx.alt.close).toHaveBeenCalledTimes(1) + expect(vias.addMany).not.toHaveBeenCalled() + + // Nor one whose stop is gone from the rail altogether. + openFirstLeg({ anchor: { dayId: 2, afterIndex: 9 } }) + rerender(baseOptions()) + await act(async () => { await result.current.chooseRouteAlternative(1) }) + expect(fx.alt.close).toHaveBeenCalledTimes(2) + expect(vias.addMany).not.toHaveBeenCalled() + }) + + it('FE-TP-ALTERNATIVES-013: a held way replaces the leg\'s vias in one write, the drive into a quiet day included', async () => { + openFirstLeg() + const { result, rerender } = renderAlternatives() + + await act(async () => { await result.current.chooseRouteAlternative(1) }) + expect(vias.addMany).toHaveBeenCalledWith(2, [{ after_order_index: 0, lat: 49.6, lng: 10.5 }], [0]) + expect(fx.alt.close).toHaveBeenCalledTimes(1) + expect(toast.info).not.toHaveBeenCalled() + + // The drive from day 2's last stop into the day with one stop, which draws no card. + openFirstLeg({ drive: { kind: 'leg', index: 2 }, anchor: { dayId: 2, afterIndex: 2 }, ends: { from: 23, to: 31 }, standIn: true }) + rerender(baseOptions()) + await act(async () => { await result.current.chooseRouteAlternative(1) }) + expect(vias.addMany).toHaveBeenLastCalledWith(2, [{ after_order_index: 2, lat: 49.6, lng: 10.5 }], [2]) + expect(toast.info).toHaveBeenCalledWith('roadtrip.alt.standIn', 8000) + expect(routes.reroute).not.toHaveBeenCalled() + }) + + it('FE-TP-ALTERNATIVES-014: without pins the leg is cleared when bent, re-routed when drawn by a stand-in, and left alone otherwise', async () => { + openFirstLeg() + fx.pin.mockResolvedValue(proof({ pins: [] })) + const { result, rerender } = renderAlternatives() + + await act(async () => { await result.current.chooseRouteAlternative(2) }) + expect(vias.addMany).not.toHaveBeenCalled() + expect(routes.reroute).not.toHaveBeenCalled() + expect(fx.alt.close).toHaveBeenCalledTimes(1) + + vias.byDay = { 2: [{ id: 5, day_id: 2, after_order_index: 0, sequence: 0, lat: 50.3, lng: 10.4 }] } + rerender(baseOptions()) + await act(async () => { await result.current.chooseRouteAlternative(2) }) + expect(vias.addMany).toHaveBeenCalledWith(2, [], [0]) + + vias.byDay = {} + openFirstLeg({ standIn: true }) + rerender(baseOptions()) + await act(async () => { await result.current.chooseRouteAlternative(2) }) + expect(routes.reroute).toHaveBeenCalledTimes(1) + expect(toast.info).toHaveBeenCalledWith('roadtrip.alt.standIn', 8000) + }) + + it('FE-TP-ALTERNATIVES-015: a write that fails is said in the bar and as a toast, the bar only while it is still that leg\'s', async () => { + openFirstLeg() + const { result } = renderAlternatives() + + vias.addMany.mockRejectedValueOnce(new Error('offline')) + await act(async () => { await result.current.chooseRouteAlternative(1) }) + expect(fx.alt.settle).toHaveBeenCalledWith('offline') + expect(toast.error).toHaveBeenCalledWith('offline') + expect(fx.alt.close).not.toHaveBeenCalled() + + fx.alt.settle.mockClear() + vias.addMany.mockImplementationOnce(async () => { signal.abort(); throw 'gone' }) + await act(async () => { await result.current.chooseRouteAlternative(1) }) + expect(fx.alt.settle).not.toHaveBeenCalled() + expect(toast.error).toHaveBeenLastCalledWith('common.unknownError') + }) +}) diff --git a/client/src/pages/tripPlanner/useRoadtripAlternatives.ts b/client/src/pages/tripPlanner/useRoadtripAlternatives.ts new file mode 100644 index 000000000..bbf053e9e --- /dev/null +++ b/client/src/pages/tripPlanner/useRoadtripAlternatives.ts @@ -0,0 +1,263 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { viasLeaving } from '@trek/shared/roadtrip' +import { alternativesBusy, buildAlternativeOverlays } from '../../components/Roadtrip/alternativeOverlays' +import { pinAlternative, railDriveOn, railLegAt, refusalHint, type PinProof } from '../../components/Roadtrip/alternativePins' +import { useAutomaticDayPoints } from '../../components/Roadtrip/useAutomaticDayPoints' +import { openOn, useRouteAlternatives, type RailDrive } from '../../components/Roadtrip/useRouteAlternatives' +import type { PlannerBase } from './plannerTypes' +import type { RoadtripFeed } from './useRoadtripFeed' + +interface RoadtripAlternativesOptions + extends Pick, + Pick { + isMobile: boolean + activeTab: string +} + +/** + * The other ways of driving one leg and what the road trip map frames: the routes on + * offer and the one the pointer is on, their overlays and the stretch they cover, the + * automatic day points and their markers, and asking for and choosing an alternative. + * + * Its effects run where useTripPlanner calls it, after the road trip feed's, in the + * order they always had. + */ +export function useRoadtripAlternatives(options: RoadtripAlternativesOptions) { + const { + t, toast, isMobile, activeTab, roadtripActive, roadtripFeedActive, roadtripRoutes, roadtripVias, refuel, + collapsedRoadtripDays, + } = options + const routeAlternatives = useRouteAlternatives() + /** + * Which offered route the pointer is on, so the map can light that one up. + * + * Lives here rather than in the bar because the map draws it and the bar reports it: + * neither owns it, and passing it through the page would put state in a wiring + * container the Page pattern keeps stateless. + */ + const [highlightedAlternative, setHighlightedAlternative] = useState(null) + // Closing the picker has to clear it, or the next one opens with a road already lit. + useEffect(() => { + if (!routeAlternatives.open) setHighlightedAlternative(null) + }, [routeAlternatives.open]) + + // Leaving road trip mode closes it too. The switch sits in the left sidebar and + // is reachable while the bar is open over the map, and the overlay depends only + // on the picker, so flipping the mode off left pale blue alternatives, their + // casings and their drive-time pills drawn on an ordinary planner map, with no + // road trip UI left to dismiss them from. + // + // The gate is where the picker can be seen, not the mode. `roadtripActive` is false + // on a phone by design (see `roadtripMode` in useTripPlanner), so gating on it alone + // closed a picker the phone had just opened, on the very next render. On the phone the + // picker lives on the drive tab, so it stays open there and closes once the tab is + // left. At desk width `isMobile` is false and this is exactly `roadtripActive`, as it + // always was. + const alternativesShown = roadtripActive || (isMobile && roadtripFeedActive && activeTab === 'roadtrip') + useEffect(() => { + if (!alternativesShown) routeAlternatives.close() + }, [alternativesShown, routeAlternatives]) + + /** + * The offered routes as the map draws them: line, colour, and the label that sits on + * the road. Built here rather than in the page so the page stays a wiring container + * and both renderers get the identical shape. + */ + const alternativeOverlays = useMemo( + () => buildAlternativeOverlays(routeAlternatives.open?.routes, { + fastest: t('roadtrip.alt.fastest'), + current: t('roadtrip.alt.current'), + noMotorway: t('roadtrip.alt.noMotorway'), + noToll: t('roadtrip.alt.noToll'), + noFerry: t('roadtrip.alt.noFerry'), + }, routeAlternatives.open?.engine), + [routeAlternatives.open, t], + ) + + /** + * The stretch of map the offered routes cover, handed to whichever renderer is up. + * + * Opening the picker without moving the camera means weighing three roads you cannot + * see. Derived from the overlays rather than from the two endpoints so the frame holds + * the whole of every alternative, including one that swings far off the direct line. + * Empty while nothing is open, and the map is told to do nothing with an empty list, + * so closing the picker leaves the view where the user put it. + */ + const alternativeFocusPoints = useMemo( + () => alternativeOverlays.flatMap(o => o.coordinates), + [alternativeOverlays], + ) + + const automaticPoints = useAutomaticDayPoints(roadtripRoutes, collapsedRoadtripDays) + const focusRoadtripPoint = useCallback((lat: number, lng: number) => { + refuel.close() + routeAlternatives.close() + automaticPoints.focusPoint(lat, lng) + }, [refuel, routeAlternatives, automaticPoints]) + const roadtripMapVias = automaticPoints.markers + /** + * What the map should bring into view. + * + * Refuel offers win while they are open, and for the reason they exist at all: somebody + * is being asked to accept a stop, and a stop off the edge of the map cannot be judged. + * They are the newer, smaller and more specific answer, so they take the view from the + * alternatives rather than being averaged with them into a frame that shows neither. + */ + const mapFocusPoints = useMemo<[number, number][]>( + () => (refuel.offered.length + ? refuel.offered.map(p => [p.lat, p.lng] as [number, number]) + : alternativeFocusPoints.length ? alternativeFocusPoints : automaticPoints.focusPoints ?? alternativeFocusPoints), + [refuel.offered, alternativeFocusPoints, automaticPoints.focusPoints], + ) + + /** + * The rail as it stands now, for a choice that is written several router answers after + * the render that started it. Checked against before anything is written. + */ + const railDaysRef = useRef[0]>(roadtripRoutes.days) + // The days with a single stop as well, in day order: they draw no card, but a drive + // into the day after one leaves from its stop, and a choice for that drive is filed there. + useEffect(() => { + railDaysRef.current = [...roadtripRoutes.days, ...roadtripRoutes.quietDays].sort((a, b) => a.dayNumber - b.dayNumber) + }, [roadtripRoutes.days, roadtripRoutes.quietDays]) + + /** + * Asks the rail's own router for other ways of one drive on a card. + * + * The picker is handed everything about the leg as the rail has it: the road it is on + * now, which heads the list as the current one; where a choice would be written; and + * the router with the leg's own mode and avoided classes, not the trip-wide profile. + * + * The drive arriving at the head of a connected card is asked about the same way, as + * the pair from the last stop of the day before to the card's first. Its router is the + * one the rail drives that seam with, under the card it arrives on, and a choice is + * filed behind the stop it leaves, where the map already files a point dropped on it. + * It used to be the one drive on the rail that could not be offered another way. + */ + const askRouteAlternatives = useCallback((dayId: number, drive: RailDrive) => { + const day = roadtripRoutes.days.find(d => d.dayId === dayId) + const found = day ? railDriveOn(day, drive) : null + const router = found ? roadtripRoutes.legRouter?.(found.from, found.to, dayId) : undefined + if (!found || !router) return + if (openOn(routeAlternatives.open, dayId, drive)) { + routeAlternatives.close() + return + } + const { from, to, seg, line } = found + routeAlternatives.ask({ + dayId, + drive, + from: { lat: from.lat, lng: from.lng }, + to: { lat: to.lat, lng: to.lng }, + driven: { coordinates: line ?? [], distance: seg.distance, duration: seg.duration }, + // The vias of a leg are filed behind the stop it leaves, on the day that stop is + // stored on, which on a card holding a night drive or a drive in from yesterday is + // not the card's own day. + anchor: { dayId: from.ownerDayId, afterIndex: from.ownerIndex }, + ends: { from: from.assignmentId, to: to.assignmentId }, + router, + }) + }, [roadtripRoutes, routeAlternatives]) + + /** + * Taking one of the offered routes: pinned, proven, and only then written. + * + * Saved as vias, not as a stored polyline: a polyline goes stale with the next OSM update + * and with every stop that moves, while a via keeps forcing the router back onto this + * road for as long as the road exists. But a via only holds a road the router is willing + * to drive through it, and nothing used to check that: a point on a ferry was pulled to + * the pier and the day went the long way round, and a way weighed away from motorways + * kept the motorway after its one pinned point. So the rail's own router is asked first + * (`pinAlternative`), and a way it will not follow is not saved and says why. + * + * The pins replace the leg's vias in one write rather than joining them. Appending put a + * new point behind the old one and routed out to each in turn, a zigzag matching neither + * the preview nor the distance printed on it; and one delete per via meant a full re-route + * between each of them. A write that fails is reported and leaves the picker open: + * swallowed, it closed on a leg that still carried its via, and not even the reload ran + * to contradict the traveller. + * + * A refusal is said twice: as a toast, and to the bar (`settle`), which keeps it beside + * the offers and announces it. A leg the rail drew with OSRM standing in for an engine + * that did not answer is asked for again once a choice holds, since the road the router + * chose is not the one on the map: taking the router's own road there wrote nothing and + * left the stand-in line in place, which read as a click that did nothing. + */ + const chooseRouteAlternative = useCallback(async (index: number) => { + const open = routeAlternatives.open + const offer = open?.routes[index] + if (!open || !offer) return + // Choosing the road already being driven changes nothing. + if (offer.current) { routeAlternatives.close(); return } + // One choice at a time: the map line can be clicked while a chip's choice is checked. + if (alternativesBusy(open)) return + // Vias are written online only, so a choice that could not be kept is not checked. + if (!roadtripVias.editable) { toast.error(t('roadtrip.alt.offline')); return } + + const signal = routeAlternatives.prove(index) + let proof: PinProof + try { + proof = await pinAlternative({ offer, current: open.routes.find(r => r.current), route: open.route, signal }) + } catch { + if (signal.aborted) return + routeAlternatives.settle(t('roadtrip.alt.failed')) + // The desk's bar says it in its own status line; a toast on top covered that line + // and printed the same sentence twice. The phone's bar has no room for a sentence. + if (isMobile) toast.error(t('roadtrip.alt.failed')) + return + } + if (signal.aborted) return + if (!proof.held) { + const refusal = t(proof.fellBack ? 'roadtrip.alt.failed' : 'roadtrip.alt.notHeld') + const hint = proof.fellBack ? null : refusalHint(offer, proof.last, t) + routeAlternatives.settle(hint ? `${refusal} ${hint}` : refusal) + if (isMobile) { + toast.error(refusal, 6000) + if (hint) toast.info(hint, 8000) + } + return + } + + // The chain may have moved while the router was asked: a stop dragged, a collaborator's + // edit arriving. Pins worked out for this leg are only written where it still runs. + const { anchor, ends } = open + const leg = railLegAt(railDaysRef.current, anchor) + if (!leg || leg.from.assignmentId !== ends.from || leg.to.assignmentId !== ends.to) { + toast.error(t('roadtrip.alt.legChanged'), 6000) + routeAlternatives.close() + return + } + // The router's own road on a leg nothing bends is already what is driven, unless OSRM + // drew the leg in its engine's place. A write routes the leg again by itself; without + // one the rail is asked to, and either way the picker says why the map may still hold + // the stand-in line for a moment, or for as long as that engine does not answer. + const bent = viasLeaving(leg.from, roadtripVias.byDay[anchor.dayId] ?? []).length > 0 + if (proof.pins.length || bent) { + try { + await roadtripVias.addMany( + anchor.dayId, + proof.pins.map(pin => ({ after_order_index: anchor.afterIndex, lat: pin.lat, lng: pin.lng })), + [anchor.afterIndex], + ) + } catch (err: unknown) { + // Said even when the picker has moved on in the meantime: the write was asked for. + const message = err instanceof Error ? err.message : t('common.unknownError') + if (!signal.aborted) routeAlternatives.settle(message) + toast.error(message) + return + } + } else if (open.standIn) { + roadtripRoutes.reroute?.() + } + if (open.standIn) toast.info(t('roadtrip.alt.standIn'), 8000) + // A picker opened on another leg while this was written belongs to that leg now. + if (!signal.aborted) routeAlternatives.close() + }, [routeAlternatives, roadtripVias, roadtripRoutes, toast, t, isMobile]) + + return { + routeAlternatives, highlightedAlternative, setHighlightedAlternative, alternativeOverlays, alternativeFocusPoints, + focusRoadtripPoint, roadtripMapVias, mapFocusPoints, askRouteAlternatives, chooseRouteAlternative, + } +} + +export type RoadtripAlternatives = ReturnType diff --git a/client/src/pages/tripPlanner/useTripPlanner.ts b/client/src/pages/tripPlanner/useTripPlanner.ts index 50f537bef..9dc6cbbdf 100644 --- a/client/src/pages/tripPlanner/useTripPlanner.ts +++ b/client/src/pages/tripPlanner/useTripPlanner.ts @@ -25,15 +25,11 @@ import { useAuthStore } from '../../store/authStore' import { useResizablePanels } from '../../hooks/useResizablePanels' import { useTripWebSocket } from '../../hooks/useTripWebSocket' import { useRouteCalculation } from '../../hooks/useRouteCalculation' -import { useAutomaticDayPoints } from '../../components/Roadtrip/useAutomaticDayPoints' import { roadtripInsertion } from '../../components/Roadtrip/dayWindow' -import { isStoredStop, viasLeaving, type CarrierTerminal } from '@trek/shared/roadtrip' +import { isStoredStop, type CarrierTerminal } from '@trek/shared/roadtrip' import { useTripRouteOverview } from '../../components/Map/useTripRouteOverview' import { useDayClear } from './useDayClear' import type { RefuelCandidate } from '../../components/Roadtrip/refuelSuggestion' -import { openOn, useRouteAlternatives, type RailDrive } from '../../components/Roadtrip/useRouteAlternatives' -import { alternativesBusy, buildAlternativeOverlays } from '../../components/Roadtrip/alternativeOverlays' -import { pinAlternative, railDriveOn, railLegAt, refusalHint, type PinProof } from '../../components/Roadtrip/alternativePins' import { stopArrival } from '../../components/Roadtrip/stopArrival' import type { CorridorPoi } from '../../components/Roadtrip/useCorridorPois' import { projectOntoRoute, sliceAtMeters, type CorridorHit, type LatLng } from '../../components/Roadtrip/corridor' @@ -72,6 +68,7 @@ import { usePlannerMapView } from './usePlannerMapView' import { useMapPlaces } from './useMapPlaces' import { useRoadtripFeed } from './useRoadtripFeed' import { useRoadtripStopEdits } from './useRoadtripStopEdits' +import { useRoadtripAlternatives } from './useRoadtripAlternatives' import { useIsPhone } from '../../mobile/useIsPhone' /** @@ -703,231 +700,14 @@ export function useTripPlanner() { roadtripVias, roadtripStopsOf, viaLiesBefore, dayBoundaries, dailyTimesActive, }) - const routeAlternatives = useRouteAlternatives() - /** - * Which offered route the pointer is on, so the map can light that one up. - * - * Lives here rather than in the bar because the map draws it and the bar reports it — - * neither owns it, and passing it through the page would put state in a wiring - * container the Page pattern keeps stateless. - */ - const [highlightedAlternative, setHighlightedAlternative] = useState(null) - // Closing the picker has to clear it, or the next one opens with a road already lit. - useEffect(() => { - if (!routeAlternatives.open) setHighlightedAlternative(null) - }, [routeAlternatives.open]) - - // Leaving road trip mode closes it too. The switch sits in the left sidebar and - // is reachable while the bar is open over the map, and the overlay depends only - // on the picker — so flipping the mode off left pale blue alternatives, their - // casings and their drive-time pills drawn on an ordinary planner map, with no - // road trip UI left to dismiss them from. - // - // The gate is where the picker can be seen, not the mode. `roadtripActive` is false - // on a phone by design (see `roadtripMode`), so gating on it alone closed a picker - // the phone had just opened, on the very next render. On the phone the picker lives - // on the drive tab, so it stays open there and closes once the tab is left. At desk - // width `isMobile` is false and this is exactly `roadtripActive`, as it always was. - const alternativesShown = roadtripActive || (isMobile && roadtripFeedActive && activeTab === 'roadtrip') - useEffect(() => { - if (!alternativesShown) routeAlternatives.close() - }, [alternativesShown, routeAlternatives]) - - /** - * The offered routes as the map draws them: line, colour, and the label that sits on - * the road. Built here rather than in the page so the page stays a wiring container - * and both renderers get the identical shape. - */ - const alternativeOverlays = useMemo( - () => buildAlternativeOverlays(routeAlternatives.open?.routes, { - fastest: t('roadtrip.alt.fastest'), - current: t('roadtrip.alt.current'), - noMotorway: t('roadtrip.alt.noMotorway'), - noToll: t('roadtrip.alt.noToll'), - noFerry: t('roadtrip.alt.noFerry'), - }, routeAlternatives.open?.engine), - [routeAlternatives.open, t], - ) - - /** - * The stretch of map the offered routes cover, handed to whichever renderer is up. - * - * Opening the picker without moving the camera means weighing three roads you cannot - * see. Derived from the overlays rather than from the two endpoints so the frame holds - * the whole of every alternative, including one that swings far off the direct line. - * Empty while nothing is open, and the map is told to do nothing with an empty list — - * so closing the picker leaves the view where the user put it. - */ - const alternativeFocusPoints = useMemo( - () => alternativeOverlays.flatMap(o => o.coordinates), - [alternativeOverlays], - ) - - /** - * What the map should bring into view. - * - * Refuel offers win while they are open, and for the reason they exist at all: somebody - * is being asked to accept a stop, and a stop off the edge of the map cannot be judged. - * They are the newer, smaller and more specific answer, so they take the view from the - * alternatives rather than being averaged with them into a frame that shows neither. - */ - const automaticPoints = useAutomaticDayPoints(roadtripRoutes, collapsedRoadtripDays) - const focusRoadtripPoint = useCallback((lat: number, lng: number) => { - refuel.close() - routeAlternatives.close() - automaticPoints.focusPoint(lat, lng) - }, [refuel, routeAlternatives, automaticPoints]) - const roadtripMapVias = automaticPoints.markers - const mapFocusPoints = useMemo<[number, number][]>( - () => (refuel.offered.length - ? refuel.offered.map(p => [p.lat, p.lng] as [number, number]) - : alternativeFocusPoints.length ? alternativeFocusPoints : automaticPoints.focusPoints ?? alternativeFocusPoints), - [refuel.offered, alternativeFocusPoints, automaticPoints.focusPoints], - ) - - /** - * The rail as it stands now, for a choice that is written several router answers after - * the render that started it. Checked against before anything is written. - */ - const railDaysRef = useRef[0]>(roadtripRoutes.days) - // The days with a single stop as well, in day order: they draw no card, but a drive - // into the day after one leaves from its stop, and a choice for that drive is filed there. - useEffect(() => { - railDaysRef.current = [...roadtripRoutes.days, ...roadtripRoutes.quietDays].sort((a, b) => a.dayNumber - b.dayNumber) - }, [roadtripRoutes.days, roadtripRoutes.quietDays]) - - /** - * Asks the rail's own router for other ways of one drive on a card. - * - * The picker is handed everything about the leg as the rail has it: the road it is on - * now, which heads the list as the current one; where a choice would be written; and - * the router with the leg's own mode and avoided classes, not the trip-wide profile. - * - * The drive arriving at the head of a connected card is asked about the same way, as - * the pair from the last stop of the day before to the card's first. Its router is the - * one the rail drives that seam with, under the card it arrives on, and a choice is - * filed behind the stop it leaves, where the map already files a point dropped on it. - * It used to be the one drive on the rail that could not be offered another way. - */ - const askRouteAlternatives = useCallback((dayId: number, drive: RailDrive) => { - const day = roadtripRoutes.days.find(d => d.dayId === dayId) - const found = day ? railDriveOn(day, drive) : null - const router = found ? roadtripRoutes.legRouter?.(found.from, found.to, dayId) : undefined - if (!found || !router) return - if (openOn(routeAlternatives.open, dayId, drive)) { - routeAlternatives.close() - return - } - const { from, to, seg, line } = found - routeAlternatives.ask({ - dayId, - drive, - from: { lat: from.lat, lng: from.lng }, - to: { lat: to.lat, lng: to.lng }, - driven: { coordinates: line ?? [], distance: seg.distance, duration: seg.duration }, - // The vias of a leg are filed behind the stop it leaves, on the day that stop is - // stored on, which on a card holding a night drive or a drive in from yesterday is - // not the card's own day. - anchor: { dayId: from.ownerDayId, afterIndex: from.ownerIndex }, - ends: { from: from.assignmentId, to: to.assignmentId }, - router, - }) - }, [roadtripRoutes, routeAlternatives]) - - /** - * Taking one of the offered routes: pinned, proven, and only then written. - * - * Saved as vias, not as a stored polyline: a polyline goes stale with the next OSM update - * and with every stop that moves, while a via keeps forcing the router back onto this - * road for as long as the road exists. But a via only holds a road the router is willing - * to drive through it, and nothing used to check that: a point on a ferry was pulled to - * the pier and the day went the long way round, and a way weighed away from motorways - * kept the motorway after its one pinned point. So the rail's own router is asked first - * (`pinAlternative`), and a way it will not follow is not saved and says why. - * - * The pins replace the leg's vias in one write rather than joining them. Appending put a - * new point behind the old one and routed out to each in turn, a zigzag matching neither - * the preview nor the distance printed on it; and one delete per via meant a full re-route - * between each of them. A write that fails is reported and leaves the picker open: - * swallowed, it closed on a leg that still carried its via, and not even the reload ran - * to contradict the traveller. - * - * A refusal is said twice: as a toast, and to the bar (`settle`), which keeps it beside - * the offers and announces it. A leg the rail drew with OSRM standing in for an engine - * that did not answer is asked for again once a choice holds, since the road the router - * chose is not the one on the map: taking the router's own road there wrote nothing and - * left the stand-in line in place, which read as a click that did nothing. - */ - const chooseRouteAlternative = useCallback(async (index: number) => { - const open = routeAlternatives.open - const offer = open?.routes[index] - if (!open || !offer) return - // Choosing the road already being driven changes nothing. - if (offer.current) { routeAlternatives.close(); return } - // One choice at a time: the map line can be clicked while a chip's choice is checked. - if (alternativesBusy(open)) return - // Vias are written online only, so a choice that could not be kept is not checked. - if (!roadtripVias.editable) { toast.error(t('roadtrip.alt.offline')); return } - - const signal = routeAlternatives.prove(index) - let proof: PinProof - try { - proof = await pinAlternative({ offer, current: open.routes.find(r => r.current), route: open.route, signal }) - } catch { - if (signal.aborted) return - routeAlternatives.settle(t('roadtrip.alt.failed')) - // The desk's bar says it in its own status line; a toast on top covered that line - // and printed the same sentence twice. The phone's bar has no room for a sentence. - if (isMobile) toast.error(t('roadtrip.alt.failed')) - return - } - if (signal.aborted) return - if (!proof.held) { - const refusal = t(proof.fellBack ? 'roadtrip.alt.failed' : 'roadtrip.alt.notHeld') - const hint = proof.fellBack ? null : refusalHint(offer, proof.last, t) - routeAlternatives.settle(hint ? `${refusal} ${hint}` : refusal) - if (isMobile) { - toast.error(refusal, 6000) - if (hint) toast.info(hint, 8000) - } - return - } - - // The chain may have moved while the router was asked: a stop dragged, a collaborator's - // edit arriving. Pins worked out for this leg are only written where it still runs. - const { anchor, ends } = open - const leg = railLegAt(railDaysRef.current, anchor) - if (!leg || leg.from.assignmentId !== ends.from || leg.to.assignmentId !== ends.to) { - toast.error(t('roadtrip.alt.legChanged'), 6000) - routeAlternatives.close() - return - } - // The router's own road on a leg nothing bends is already what is driven, unless OSRM - // drew the leg in its engine's place. A write routes the leg again by itself; without - // one the rail is asked to, and either way the picker says why the map may still hold - // the stand-in line for a moment, or for as long as that engine does not answer. - const bent = viasLeaving(leg.from, roadtripVias.byDay[anchor.dayId] ?? []).length > 0 - if (proof.pins.length || bent) { - try { - await roadtripVias.addMany( - anchor.dayId, - proof.pins.map(pin => ({ after_order_index: anchor.afterIndex, lat: pin.lat, lng: pin.lng })), - [anchor.afterIndex], - ) - } catch (err: unknown) { - // Said even when the picker has moved on in the meantime: the write was asked for. - const message = err instanceof Error ? err.message : t('common.unknownError') - if (!signal.aborted) routeAlternatives.settle(message) - toast.error(message) - return - } - } else if (open.standIn) { - roadtripRoutes.reroute?.() - } - if (open.standIn) toast.info(t('roadtrip.alt.standIn'), 8000) - // A picker opened on another leg while this was written belongs to that leg now. - if (!signal.aborted) routeAlternatives.close() - }, [routeAlternatives, roadtripVias, roadtripRoutes, toast, t, isMobile]) + // Called here so the picker's effects keep their place after the road trip's own. + const { + highlightedAlternative, setHighlightedAlternative, routeAlternatives, alternativeOverlays, alternativeFocusPoints, + mapFocusPoints, roadtripMapVias, focusRoadtripPoint, askRouteAlternatives, chooseRouteAlternative, + } = useRoadtripAlternatives({ + t, toast, isMobile, activeTab, roadtripActive, roadtripFeedActive, roadtripRoutes, roadtripVias, refuel, + collapsedRoadtripDays, + }) /** * A click on the drawn route puts a via there, and the drive is redrawn through it.