feat(tours): add non-motorized day tour planning

This commit is contained in:
elmocito
2026-10-04 12:59:55 +02:00
parent c93cf2bce9
commit 9e475f447a
202 changed files with 16129 additions and 383 deletions
+12 -3
View File
@@ -5,14 +5,16 @@ export interface UndoEntry {
undo: () => Promise<void> | void
/** The days the step acts on. Deleting one of them drops the step. */
dayIds?: number[]
/** Place-backed steps become invalid if one of their Tour places is permanently deleted. */
placeIds?: number[]
}
export function usePlannerHistory(maxEntries = 30) {
const historyRef = useRef<UndoEntry[]>([])
const [, forceUpdate] = useReducer((x: number) => x + 1, 0)
const pushUndo = (label: string, undoFn: () => Promise<void> | void, dayIds?: number[]) => {
historyRef.current = [{ label, undo: undoFn, dayIds }, ...historyRef.current].slice(0, maxEntries)
const pushUndo = (label: string, undoFn: () => Promise<void> | void, dayIds?: number[], placeIds?: number[]) => {
historyRef.current = [{ label, undo: undoFn, dayIds, placeIds }, ...historyRef.current].slice(0, maxEntries)
forceUpdate()
}
@@ -45,8 +47,15 @@ export function usePlannerHistory(maxEntries = 30) {
forceUpdate()
}, [])
const forgetPlace = useCallback((placeId: number) => {
const kept = historyRef.current.filter(entry => !entry.placeIds?.includes(placeId))
if (kept.length === historyRef.current.length) return
historyRef.current = kept
forceUpdate()
}, [])
const canUndo = historyRef.current.length > 0
const lastActionLabel = historyRef.current[0]?.label ?? null
return { pushUndo, undo, forgetDay, canUndo, lastActionLabel }
return { pushUndo, undo, forgetDay, forgetPlace, canUndo, lastActionLabel }
}
@@ -0,0 +1,82 @@
import { act, renderHook, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { buildAssignment, buildDay, buildPlace } from '../../tests/helpers/factories'
import { resetAllStores } from '../../tests/helpers/store'
import { useAddonStore } from '../store/addonStore'
import { useSettingsStore } from '../store/settingsStore'
import { useTripStore } from '../store/tripStore'
import { useRouteCalculation } from './useRouteCalculation'
const mocks = vi.hoisted(() => ({ route: vi.fn(), mirrorServiceStops: true }))
vi.mock('../components/Map/RouteCalculator', async importActual => ({
...await importActual<typeof import('../components/Map/RouteCalculator')>(),
calculateRouteWithLegs: mocks.route,
}))
vi.mock('./useRoadtripSettings', () => ({
useRoadtripSettings: (select: (settings: { roadtrip_service_stops_in_days: boolean }) => unknown) =>
select({ roadtrip_service_stops_in_days: mocks.mirrorServiceStops }),
}))
function seed(enabled = true, excluded = false) {
const places = [
buildPlace({ id: 1, lat: 48.1, lng: 11.1 }),
buildPlace({ id: 2, lat: 48.2, lng: 11.2, route_geometry: '[[48.2,11.2],[48.3,11.3]]' }),
buildPlace({ id: 3, lat: 48.4, lng: 11.4 }),
]
const assignments = { '1': places.map((place, order) => buildAssignment({
day_id: 1, order_index: order, place,
...(order === 1 ? { tour_place_id: 2, tour_route_geometry: '[[49,12],[49.1,12.1]]', route_excluded: excluded } : {}),
})) }
useAddonStore.setState({ addons: [{ id: 'tours', name: 'Tours', icon: 'Route', type: 'feature', enabled }] })
useTripStore.setState({ days: [buildDay({ id: 1 })], assignments, places, reservations: [] })
return places
}
beforeEach(() => {
resetAllStores()
mocks.mirrorServiceStops = true
mocks.route.mockReset().mockImplementation(async (points: Array<{ lat: number; lng: number }>) => ({
coordinates: points.map(point => [point.lat, point.lng]), legs: [],
}))
useSettingsStore.setState(state => ({ settings: { ...state.settings, optimize_from_accommodation: false } }))
})
describe('B5 useRouteCalculation', () => {
it.each([
{ enabled: true, excluded: false, expected: [[48.1, 48.2], [48.3, 48.4]] },
{ enabled: true, excluded: true, expected: [[48.1, 48.4]] },
{ enabled: false, excluded: false, expected: [[48.1, 48.2, 48.4]] },
])('routes enabled=$enabled excluded=$excluded using the shared day topology', async ({ enabled, excluded, expected }) => {
seed(enabled, excluded)
const { result } = renderHook(() => useRouteCalculation(useTripStore(), 1, true, 'walking'))
await waitFor(() => expect(result.current.route?.map(run => run.map(point => point[0]))).toEqual(expected))
expect(mocks.route.mock.calls.map(call => call[0].map((point: { lat: number }) => point.lat))).toEqual(expected)
expect(useTripStore.getState().assignments['1']).toHaveLength(3)
})
it('filters hidden service stops before the Tour projection', async () => {
mocks.mirrorServiceStops = false
const places = seed()
const service = buildAssignment({ day_id: 1, order_index: 0.5,
place: buildPlace({ id: 4, lat: 48.15, lng: 11.15, stop_type: 'fuel' }) })
useTripStore.setState(state => ({ assignments: { '1': [...state.assignments['1'], service] }, places }))
const { result } = renderHook(() => useRouteCalculation(useTripStore(), 1, true, 'walking'))
await waitFor(() => expect(result.current.route).toHaveLength(2))
expect(mocks.route.mock.calls.map(call => call[0].map((point: { lat: number }) => point.lat)))
.toEqual([[48.1, 48.2], [48.3, 48.4]])
})
it('aborts an old calculation and prevents its late answer replacing current Place geometry', async () => {
const places = seed()
let release: (answer: { coordinates: number[][]; legs: never[] }) => void = () => {}
mocks.route.mockImplementationOnce(() => new Promise(resolve => { release = resolve }))
const { result } = renderHook(() => useRouteCalculation(useTripStore(), 1, true, 'walking'))
const oldSignal = mocks.route.mock.calls[0][1].signal as AbortSignal
act(() => useTripStore.setState({ places: places.map(place => place.id === 2
? { ...place, route_geometry: '[[48.2,11.2],[48.35,11.35]]' } : place) }))
await waitFor(() => expect(result.current.route?.[1]?.[0]).toEqual([48.35, 11.35]))
expect(oldSignal.aborted).toBe(true)
await act(async () => release({ coordinates: [[49, 12], [49.1, 12.1]], legs: [] }))
expect(result.current.route?.[1]?.[0]).toEqual([48.35, 11.35])
})
})
+7 -2
View File
@@ -3,6 +3,7 @@ import { isServiceStopType } from '../components/Roadtrip/roadtripModel'
import { useState, useCallback, useRef, useEffect, useMemo } from 'react'
import { useTripStore } from '../store/tripStore'
import { useSettingsStore } from '../store/settingsStore'
import { useAddonStore } from '../store/addonStore'
import { calculateRouteWithLegs, type RouteProfileKey } from '../components/Map/RouteCalculator'
import { buildDayRouteRuns, hotelBookendOf, TRANSPORT_TYPES } from '../components/Map/dayRoutePlan'
import { resolveLegMode } from '../components/Planner/legMode'
@@ -26,6 +27,8 @@ export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: nu
// Charging stops / rest areas a plugin route places on the drawn line.
const [routeVias, setRouteVias] = useState<RouteVia[]>([])
const mirrorServiceStops = useRoadtripSettings(s => s.roadtrip_service_stops_in_days !== false)
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
const places = useTripStore(s => s.places)
const routeAbortRef = useRef<AbortController | null>(null)
const reservationsForSignature = useTripStore((s) => s.reservations)
// Recompute when the selected day's whole-day default mode changes (#1281) —
@@ -54,6 +57,8 @@ export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: nu
reservations: state.reservations || [],
accommodations,
optimizeFromAccommodation,
toursEnabled,
places,
})
const day = allDays.find(d => d.id === dayId)
@@ -138,7 +143,7 @@ export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: nu
// Aborted (day changed) — newer call owns the state. Anything else: keep straight lines.
if (!(err instanceof Error) || err.name !== 'AbortError') { setRouteSegments([]); setRouteVias([]) }
}
}, [enabled, profile, accommodations, optimizeFromAccommodation, distanceUnit, selectedDayDefaultMode, mirrorServiceStops])
}, [enabled, profile, accommodations, optimizeFromAccommodation, distanceUnit, selectedDayDefaultMode, mirrorServiceStops, toursEnabled, places])
// Stable signature for transport reservations on the selected day — changes when a transport
// is added, removed, or repositioned, ensuring route recalc fires even on transport-only reorders.
@@ -162,7 +167,7 @@ export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: nu
if (!selectedDayId) { setRoute(null); setRouteWalking([]); setRouteSegments([]); setRouteVias([]); return }
updateRouteForDay(selectedDayId)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedDayId, selectedDayAssignments, transportSignature, enabled, profile, accommodations, optimizeFromAccommodation, distanceUnit, selectedDayDefaultMode, mirrorServiceStops])
}, [selectedDayId, selectedDayAssignments, transportSignature, enabled, profile, accommodations, optimizeFromAccommodation, distanceUnit, selectedDayDefaultMode, mirrorServiceStops, toursEnabled, places])
return { route, routeWalking, routeSegments, routeVias, routeInfo, setRoute, setRouteInfo, updateRouteForDay }
}
+241
View File
@@ -0,0 +1,241 @@
import { act, renderHook, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { TourListItem } from '@trek/shared'
import { toursApi } from '../api/client'
import { useTourPlaceIds } from './useTourPlaceIds'
vi.mock('../api/client', () => ({
toursApi: { list: vi.fn() },
}))
const tour: TourListItem = {
place_id: 42,
name: 'Ridge walk',
tour_type: 'hike',
distance: 4,
elevation_gain: 100,
elevation_loss: 80,
duration: null,
difficulty: null,
wanderer_ref: null,
match_confidence: null,
tour_group_id: null,
max_hiking_difficulty: 2,
planned: false,
caution: false,
}
function deferred<T>() {
let resolve!: (value: T) => void
let reject!: (reason?: unknown) => void
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
resolve = resolvePromise
reject = rejectPromise
})
return { promise, resolve, reject }
}
function tourFor(placeId: number, name: string): TourListItem {
return { ...tour, place_id: placeId, name }
}
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(toursApi.list).mockResolvedValue({ tours: [tour] })
})
describe('useTourPlaceIds', () => {
it('loads one facet list for filtering and selected-tour lookup', async () => {
const { result } = renderHook(() => useTourPlaceIds(7, true))
await waitFor(() => expect(result.current.tourDataReady).toBe(true))
expect(result.current.tours).toEqual([tour])
expect(result.current.tourPlaceIds).toEqual(new Set([42]))
expect(toursApi.list).toHaveBeenCalledWith(7)
})
it('hides facet identity while disabled without fetching or deleting its cached data', async () => {
const { result, rerender } = renderHook(({ enabled }) => useTourPlaceIds(7, enabled), { initialProps: { enabled: true } })
await waitFor(() => expect(result.current.tours).toEqual([tour]))
rerender({ enabled: false })
expect(result.current.tourDataReady).toBe(true)
expect(result.current.tours).toEqual([])
expect(result.current.tourPlaceIds.size).toBe(0)
expect(toursApi.list).toHaveBeenCalledTimes(1)
})
it('inserts a fresh save immediately and replaces it after an edit', async () => {
const { result } = renderHook(() => useTourPlaceIds(7, true))
await waitFor(() => expect(result.current.tours).toEqual([tour]))
const saved = { ...tour, place_id: 43, name: 'Fresh tour' }
act(() => result.current.upsertTour(saved))
expect(result.current.tours).toEqual([saved, tour])
const edited = { ...saved, name: 'Fresh tour edited' }
act(() => result.current.upsertTour(edited))
expect(result.current.tours).toEqual([edited, tour])
})
it('shows only the new trip Tours after a successful trip switch', async () => {
const tripTwoTour = tourFor(84, 'Trip two tour')
vi.mocked(toursApi.list).mockImplementation(async tripId => ({
tours: [tripId === 7 ? tour : tripTwoTour],
}))
const { result, rerender } = renderHook(({ tripId }) => useTourPlaceIds(tripId, true), {
initialProps: { tripId: 7 },
})
await waitFor(() => expect(result.current.tourDataReady).toBe(true))
rerender({ tripId: 8 })
expect(result.current.tours).toEqual([])
expect(result.current.tourPlaceIds.size).toBe(0)
expect(result.current.tourDataReady).toBe(false)
expect(result.current.toursLoading).toBe(true)
await waitFor(() => expect(result.current.tours).toEqual([tripTwoTour]))
expect(result.current.tourPlaceIds).toEqual(new Set([84]))
})
it('keeps previous-trip data hidden when the new trip refresh fails', async () => {
vi.mocked(toursApi.list).mockImplementation(async tripId => {
if (tripId === 8) throw new Error('Trip two unavailable')
return { tours: [tour] }
})
const { result, rerender } = renderHook(({ tripId }) => useTourPlaceIds(tripId, true), {
initialProps: { tripId: 7 },
})
await waitFor(() => expect(result.current.tourDataReady).toBe(true))
rerender({ tripId: 8 })
expect(result.current.tours).toEqual([])
expect(result.current.tourDataReady).toBe(false)
await waitFor(() => expect(result.current.tourLoadError).toBe(true))
expect(result.current.tours).toEqual([])
expect(result.current.tourPlaceIds.size).toBe(0)
expect(result.current.tourDataReady).toBe(false)
expect(result.current.toursLoading).toBe(false)
})
it('ignores a late response from the previous trip', async () => {
const tripOne = deferred<{ tours: TourListItem[] }>()
const tripTwoTour = tourFor(84, 'Trip two tour')
const tripTwo = deferred<{ tours: TourListItem[] }>()
vi.mocked(toursApi.list).mockImplementation(tripId => tripId === 7 ? tripOne.promise : tripTwo.promise)
const { result, rerender } = renderHook(({ tripId }) => useTourPlaceIds(tripId, true), {
initialProps: { tripId: 7 },
})
rerender({ tripId: 8 })
await act(async () => tripTwo.resolve({ tours: [tripTwoTour] }))
await waitFor(() => expect(result.current.tours).toEqual([tripTwoTour]))
await act(async () => tripOne.resolve({ tours: [tour] }))
expect(result.current.tours).toEqual([tripTwoTour])
expect(result.current.tourPlaceIds).toEqual(new Set([84]))
})
it('lets only the latest request commit after rapid trip changes', async () => {
const requests = new Map<string | number, ReturnType<typeof deferred<{ tours: TourListItem[] }>>>()
vi.mocked(toursApi.list).mockImplementation(tripId => {
const request = deferred<{ tours: TourListItem[] }>()
requests.set(tripId, request)
return request.promise
})
const { result, rerender } = renderHook(({ tripId }) => useTourPlaceIds(tripId, true), {
initialProps: { tripId: 1 },
})
rerender({ tripId: 2 })
rerender({ tripId: 3 })
const tripThreeTour = tourFor(93, 'Trip three tour')
await act(async () => requests.get(3)!.resolve({ tours: [tripThreeTour] }))
await waitFor(() => expect(result.current.tours).toEqual([tripThreeTour]))
await act(async () => requests.get(2)!.resolve({ tours: [tourFor(92, 'Trip two tour')] }))
await act(async () => requests.get(1)!.resolve({ tours: [tour] }))
expect(result.current.tours).toEqual([tripThreeTour])
expect(result.current.tourPlaceIds).toEqual(new Set([93]))
})
it('lets only the latest same-trip refresh commit after rapid assignment mutations', async () => {
const { result } = renderHook(() => useTourPlaceIds(7, true))
await waitFor(() => expect(result.current.tours).toEqual([tour]))
const beforeMutation = deferred<{ tours: TourListItem[] }>()
const afterMutation = deferred<{ tours: TourListItem[] }>()
vi.mocked(toursApi.list).mockReset()
.mockReturnValueOnce(beforeMutation.promise)
.mockReturnValueOnce(afterMutation.promise)
let firstRefresh!: Promise<void>
let secondRefresh!: Promise<void>
act(() => {
firstRefresh = result.current.reloadTourPlaceIds()
secondRefresh = result.current.reloadTourPlaceIds()
})
const plannedTour = { ...tour, planned: true }
await act(async () => { afterMutation.resolve({ tours: [plannedTour] }); await secondRefresh })
await waitFor(() => expect(result.current.tours).toEqual([plannedTour]))
await act(async () => { beforeMutation.resolve({ tours: [tour] }); await firstRefresh })
expect(result.current.tours).toEqual([plannedTour])
expect(result.current.tourPlaceIds).toEqual(new Set([42]))
expect(result.current.tourLoadError).toBe(false)
})
it('retains same-trip last-good data and exposes a failed refresh', async () => {
const { result } = renderHook(() => useTourPlaceIds(7, true))
await waitFor(() => expect(result.current.tourDataReady).toBe(true))
vi.mocked(toursApi.list).mockRejectedValueOnce(new Error('Refresh unavailable'))
await act(async () => { await result.current.reloadTourPlaceIds() })
expect(result.current.tours).toEqual([tour])
expect(result.current.tourPlaceIds).toEqual(new Set([42]))
expect(result.current.tourDataReady).toBe(true)
expect(result.current.tourLoadError).toBe(true)
expect(result.current.toursLoading).toBe(false)
})
it('does not let a pending request update state after unmount', async () => {
const request = deferred<{ tours: TourListItem[] }>()
vi.mocked(toursApi.list).mockReturnValue(request.promise)
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
const { unmount } = renderHook(() => useTourPlaceIds(7, true))
unmount()
await act(async () => request.resolve({ tours: [tour] }))
expect(consoleError).not.toHaveBeenCalled()
})
it('distinguishes an empty successful list from a failed refresh', async () => {
vi.mocked(toursApi.list).mockResolvedValueOnce({ tours: [] })
const { result } = renderHook(() => useTourPlaceIds(7, true))
await waitFor(() => expect(result.current.tourDataReady).toBe(true))
expect(result.current.tours).toEqual([])
expect(result.current.tourLoadError).toBe(false)
vi.mocked(toursApi.list).mockRejectedValueOnce(new Error('Refresh unavailable'))
await act(async () => { await result.current.reloadTourPlaceIds() })
expect(result.current.tours).toEqual([])
expect(result.current.tourDataReady).toBe(true)
expect(result.current.tourLoadError).toBe(true)
})
it('does not let an older refresh overwrite a successful Tour upsert', async () => {
const { result } = renderHook(() => useTourPlaceIds(7, true))
await waitFor(() => expect(result.current.tourDataReady).toBe(true))
const refresh = deferred<{ tours: TourListItem[] }>()
vi.mocked(toursApi.list).mockReturnValueOnce(refresh.promise)
act(() => { void result.current.reloadTourPlaceIds() })
await waitFor(() => expect(result.current.toursLoading).toBe(true))
const savedTour = tourFor(43, 'Saved while refreshing')
act(() => result.current.upsertTour(savedTour))
await act(async () => refresh.resolve({ tours: [tour] }))
expect(result.current.tours).toEqual([savedTour, tour])
expect(result.current.tourLoadError).toBe(false)
})
})
+104
View File
@@ -0,0 +1,104 @@
import { useEffect, useState, useCallback, useRef } from 'react'
import type { TourListItem } from '@trek/shared'
import { toursApi } from '../api/client'
export interface ToursInvalidation {
placeIds?: number[]
removedPlaceIds?: number[]
}
/**
* Place ids that are tours (a `tours` facet row exists for them), used to keep
* them out of the Places pool while the Tours addon is on.
* The single discriminator stays the `tours`
* facet row \u2014 this hook just mirrors it into a client-side Set for the
* Places filter, it does not add anything to the `places` table.
*
* Only fetches while `enabled` is true: with the addon off there is nothing to
* exclude, and the Places pool must stay byte-for-byte identical to today.
*/
export function useTourPlaceIds(tripId: number, enabled: boolean) {
const [tourData, setTourData] = useState<{ tripId: number; tours: TourListItem[] } | null>(null)
const [requestState, setRequestState] = useState<{
tripId: number
loading: boolean
error: boolean
} | null>(null)
const [pendingPlaceIds, setPendingPlaceIds] = useState<{ tripId: number; ids: Set<number> } | null>(null)
const requestIdRef = useRef(0)
const mountedRef = useRef(false)
const activeRequestRef = useRef({ tripId, enabled })
activeRequestRef.current = { tripId, enabled }
const reload = useCallback(async () => {
if (!enabled || !mountedRef.current
|| activeRequestRef.current.tripId !== tripId
|| !activeRequestRef.current.enabled) return
const requestId = ++requestIdRef.current
setRequestState({ tripId, loading: true, error: false })
try {
const response = await toursApi.list(tripId)
if (!mountedRef.current || requestId !== requestIdRef.current) return
setTourData({ tripId, tours: response.tours })
setPendingPlaceIds(current => current?.tripId === tripId ? null : current)
setRequestState({ tripId, loading: false, error: false })
} catch {
if (!mountedRef.current || requestId !== requestIdRef.current) return
// Data is keyed by trip, so this retains only a same-trip last-good list.
setRequestState({ tripId, loading: false, error: true })
}
}, [tripId, enabled])
const invalidateTourPlaceIds = useCallback((change?: ToursInvalidation) => {
if (!enabled || !mountedRef.current || activeRequestRef.current.tripId !== tripId
|| !activeRequestRef.current.enabled) return
const added = change?.placeIds ?? []
const removed = change?.removedPlaceIds ?? []
if (added.length || removed.length) {
setPendingPlaceIds(current => {
const ids = new Set(current?.tripId === tripId ? current.ids : [])
for (const id of removed) ids.delete(id)
for (const id of added) ids.add(id)
return ids.size ? { tripId, ids } : null
})
}
void reload()
}, [enabled, tripId, reload])
useEffect(() => {
mountedRef.current = true
void reload()
return () => {
mountedRef.current = false
requestIdRef.current += 1
}
}, [reload])
const upsertTour = useCallback((tour: TourListItem) => {
if (!enabled || !mountedRef.current || activeRequestRef.current.tripId !== tripId
|| !activeRequestRef.current.enabled) return
requestIdRef.current += 1
setTourData(current => ({
tripId,
tours: [tour, ...(current?.tripId === tripId ? current.tours : [])
.filter(item => item.place_id !== tour.place_id)],
}))
setRequestState({ tripId, loading: false, error: false })
}, [enabled, tripId])
const tourDataReady = !enabled || tourData?.tripId === tripId
const visibleTours = enabled && tourData?.tripId === tripId ? tourData.tours : []
const pendingIds = enabled && pendingPlaceIds?.tripId === tripId ? pendingPlaceIds.ids : []
const currentRequest = requestState?.tripId === tripId ? requestState : null
return {
tours: visibleTours,
toursLoading: enabled && (currentRequest?.loading ?? false),
tourLoadError: enabled && (currentRequest?.error ?? false),
tourDataReady,
tourPlaceIds: new Set([...visibleTours.map(tour => tour.place_id), ...pendingIds]),
reloadTourPlaceIds: reload,
invalidateTourPlaceIds,
upsertTour,
}
}
+209
View File
@@ -0,0 +1,209 @@
import { act, renderHook, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { TourListItem } from '@trek/shared'
const mocks = vi.hoisted(() => {
const listeners = new Set<(event: Record<string, unknown>) => void>()
const toursApi = { list: vi.fn() }
const handleRemoteEvent = vi.fn()
const loadFiles = vi.fn()
const useTripStore = Object.assign(vi.fn(() => ({ loadFiles })), {
getState: () => ({ handleRemoteEvent }),
})
return {
listeners,
toursApi,
handleRemoteEvent,
loadFiles,
useTripStore,
joinTrip: vi.fn(),
leaveTrip: vi.fn(),
addListener: vi.fn((listener: (event: Record<string, unknown>) => void) => listeners.add(listener)),
removeListener: vi.fn((listener: (event: Record<string, unknown>) => void) => listeners.delete(listener)),
}
})
vi.mock('../api/client', () => ({ toursApi: mocks.toursApi }))
vi.mock('../api/websocket', () => ({
joinTrip: mocks.joinTrip,
leaveTrip: mocks.leaveTrip,
addListener: mocks.addListener,
removeListener: mocks.removeListener,
}))
vi.mock('../store/tripStore', () => ({ useTripStore: mocks.useTripStore }))
import { useTourPlaceIds } from './useTourPlaceIds'
import { useTripWebSocket } from './useTripWebSocket'
const baseTour: TourListItem = {
place_id: 42,
name: 'Ridge walk',
tour_type: 'hike',
distance: 4,
elevation_gain: 100,
elevation_loss: 80,
duration: null,
difficulty: null,
wanderer_ref: null,
match_confidence: null,
tour_group_id: null,
max_hiking_difficulty: 2,
planned: false,
caution: false,
}
function emit(event: Record<string, unknown>): void {
for (const listener of [...mocks.listeners]) listener(event)
}
function renderTrip(tripId: number, enabled = true) {
return renderHook(() => {
const tours = useTourPlaceIds(tripId, enabled)
useTripWebSocket(tripId, tours.invalidateTourPlaceIds)
return tours
})
}
function deferred<T>() {
let resolve!: (value: T) => void
let reject!: (reason?: unknown) => void
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
resolve = resolvePromise
reject = rejectPromise
})
return { promise, resolve, reject }
}
beforeEach(() => {
mocks.listeners.clear()
mocks.addListener.mockClear()
mocks.removeListener.mockClear()
mocks.joinTrip.mockClear()
mocks.leaveTrip.mockClear()
mocks.handleRemoteEvent.mockClear()
mocks.loadFiles.mockClear()
mocks.toursApi.list.mockReset().mockResolvedValue({ tours: [baseTour] })
})
describe('Tours websocket invalidation', () => {
it('refreshes the active trip read model and Places exclusion after tours:changed', async () => {
const nextTour = { ...baseTour, place_id: 84, name: 'Trip 7 new tour' }
const refresh = deferred<{ tours: TourListItem[] }>()
mocks.toursApi.list.mockResolvedValueOnce({ tours: [baseTour] }).mockReturnValueOnce(refresh.promise)
const { result } = renderTrip(7)
await waitFor(() => expect(result.current.tourDataReady).toBe(true))
expect(result.current.tourPlaceIds).toEqual(new Set([42]))
act(() => emit({ type: 'tours:changed', tripId: 7, placeIds: [84] }))
expect(result.current.tourPlaceIds).toEqual(new Set([42, 84]))
await act(async () => refresh.resolve({ tours: [nextTour] }))
await waitFor(() => expect(result.current.tourPlaceIds).toEqual(new Set([84])))
expect(result.current.tours).toEqual([nextTour])
expect(mocks.toursApi.list).toHaveBeenCalledTimes(2)
})
it('ignores events for another trip and events without an explicit trip id', async () => {
const { result } = renderTrip(7)
await waitFor(() => expect(result.current.tourDataReady).toBe(true))
act(() => {
emit({ type: 'tours:changed', tripId: 8, placeIds: [84] })
emit({ type: 'tours:changed', placeIds: [84] })
})
expect(mocks.toursApi.list).toHaveBeenCalledOnce()
expect(result.current.tourPlaceIds).toEqual(new Set([42]))
})
it.each(['place:deleted', 'assignment:created', 'assignment:deleted', 'day:deleted'])(
'refreshes the matching trip after %s changes Tours membership or planned status', async type => {
const { result } = renderTrip(7)
await waitFor(() => expect(result.current.tourDataReady).toBe(true))
act(() => emit({ type, tripId: 7, placeId: 42 }))
await waitFor(() => expect(mocks.toursApi.list).toHaveBeenCalledTimes(2))
},
)
it.each(['place:deleted', 'assignment:created', 'assignment:deleted', 'day:deleted'])(
'refreshes the matching trip after %s changes Tours membership or planned status', async type => {
const { result } = renderTrip(7)
await waitFor(() => expect(result.current.tourDataReady).toBe(true))
act(() => emit({ type, tripId: 7 }))
await waitFor(() => expect(mocks.toursApi.list).toHaveBeenCalledTimes(2))
},
)
it('lets the latest rapid invalidation refresh win without leaking prior results', async () => {
const first = deferred<{ tours: TourListItem[] }>()
const second = deferred<{ tours: TourListItem[] }>()
const newest = { ...baseTour, place_id: 99, name: 'Newest' }
mocks.toursApi.list.mockResolvedValueOnce({ tours: [baseTour] })
.mockReturnValueOnce(first.promise)
.mockReturnValueOnce(second.promise)
const { result } = renderTrip(7)
await waitFor(() => expect(result.current.tourDataReady).toBe(true))
act(() => {
emit({ type: 'tours:changed', tripId: 7, placeIds: [98] })
emit({ type: 'tours:changed', tripId: 7, placeIds: [99] })
})
expect(result.current.tourPlaceIds).toEqual(new Set([42, 98, 99]))
await act(async () => second.resolve({ tours: [newest] }))
await waitFor(() => expect(result.current.tours).toEqual([newest]))
await act(async () => first.resolve({ tours: [baseTour] }))
expect(result.current.tours).toEqual([newest])
expect(result.current.tourPlaceIds).toEqual(new Set([99]))
expect(mocks.toursApi.list).toHaveBeenCalledTimes(3)
})
it('removes a pending Tour exclusion when its Place is deleted before refresh completes', async () => {
const staleRefresh = deferred<{ tours: TourListItem[] }>()
const deleteRefresh = deferred<{ tours: TourListItem[] }>()
mocks.toursApi.list.mockResolvedValueOnce({ tours: [] })
.mockReturnValueOnce(staleRefresh.promise)
.mockReturnValueOnce(deleteRefresh.promise)
const { result } = renderTrip(7)
await waitFor(() => expect(result.current.tourDataReady).toBe(true))
act(() => emit({ type: 'tours:changed', tripId: 7, placeIds: [84] }))
expect(result.current.tourPlaceIds).toEqual(new Set([84]))
act(() => emit({ type: 'place:deleted', tripId: 7, placeId: 84 }))
expect(result.current.tourPlaceIds).toEqual(new Set())
await act(async () => deleteRefresh.resolve({ tours: [] }))
await act(async () => staleRefresh.resolve({ tours: [{ ...baseTour, place_id: 84 }] }))
expect(result.current.tourPlaceIds).toEqual(new Set())
expect(mocks.toursApi.list).toHaveBeenCalledTimes(3)
})
it('keeps same-trip last-good Tours and exposes error on refresh failure', async () => {
const { result } = renderTrip(7)
await waitFor(() => expect(result.current.tourDataReady).toBe(true))
mocks.toursApi.list.mockRejectedValueOnce(new Error('refresh unavailable'))
act(() => emit({ type: 'tours:changed', tripId: 7, placeIds: [84] }))
await waitFor(() => expect(result.current.tourLoadError).toBe(true))
expect(result.current.tours).toEqual([baseTour])
expect(result.current.tourPlaceIds).toEqual(new Set([42, 84]))
})
it('leaves ordinary Place event handling intact and Tours-off refresh is a no-op', async () => {
const { result } = renderTrip(7, false)
await waitFor(() => expect(result.current.tourDataReady).toBe(true))
act(() => emit({ type: 'place:created', tripId: 7, place: { id: 93, name: 'Ordinary place' } }))
act(() => emit({ type: 'tours:changed', tripId: 7 }))
expect(mocks.handleRemoteEvent).toHaveBeenCalledWith(expect.objectContaining({ type: 'place:created', tripId: 7 }))
expect(mocks.toursApi.list).not.toHaveBeenCalled()
expect(result.current.tours).toEqual([])
expect(result.current.tourPlaceIds.size).toBe(0)
})
})
+20 -2
View File
@@ -2,8 +2,9 @@ import { useEffect } from 'react'
import { useTripStore } from '../store/tripStore'
import { joinTrip, leaveTrip, addListener, removeListener } from '../api/websocket'
import type { WebSocketEvent } from '../types'
import type { ToursInvalidation } from './useTourPlaceIds'
export function useTripWebSocket(tripId: number | string | undefined) {
export function useTripWebSocket(tripId: number | string | undefined, onToursChanged?: (change?: ToursInvalidation) => void) {
const tripStore = useTripStore()
useEffect(() => {
@@ -17,13 +18,30 @@ export function useTripWebSocket(tripId: number | string | undefined) {
}
}
addListener(collabFileSync)
const toursInvalidation = (event: WebSocketEvent) => {
if (String(event?.tripId ?? '') !== String(tripId)) return
if (event?.type === 'tours:changed') {
const placeIds = Array.isArray(event.placeIds)
? event.placeIds.map(Number).filter(Number.isSafeInteger)
: []
onToursChanged?.(placeIds.length ? { placeIds } : undefined)
} else if (event?.type === 'place:deleted') {
const placeId = Number(event.placeId)
onToursChanged?.(Number.isSafeInteger(placeId) ? { removedPlaceIds: [placeId] } : undefined)
} else if (event?.type === 'assignment:created' || event?.type === 'assignment:deleted'
|| event?.type === 'day:deleted') {
onToursChanged?.()
}
}
addListener(toursInvalidation)
const localFileSync = () => tripStore.loadFiles?.(tripId)
window.addEventListener('collab-files-changed', localFileSync)
return () => {
leaveTrip(tripId)
removeListener(handler)
removeListener(collabFileSync)
removeListener(toursInvalidation)
window.removeEventListener('collab-files-changed', localFileSync)
}
}, [tripId])
}, [tripId, onToursChanged])
}