import type { PlaceVisitTripVisitedResponse } from '@trek/shared'; import { create } from 'zustand'; import { addListener, removeListener } from '../api/websocket'; import { placeVisitsRepo } from '../repo/placeVisitsRepo'; import { useAuthStore } from './authStore'; /** * Which places of a trip the signed-in account visited (PLC-23), for the * filter of the trip's place list and map, and a revision that moves whenever * a trip change may have changed them, so an open visit history or place * detail knows to read again. A visit is never entered: the server reads it * from the trips' day plans (a dated day up to today, the stop naming no one * or the reader), so the store follows the plan's own events. Keyed by * account and trip, because visits are per person. Online only. */ interface TripVisitedEntry { placeIds: number[]; places: PlaceVisitTripVisitedResponse['places']; } interface PlaceVisitsState { visited: Record; /** Grows by one whenever a pushed trip change may have changed the visits. */ revision: number; /** Reads which of the trip's places the account visited. Throws when offline or refused. */ loadTripVisited: (tripId: number) => Promise; bump: () => void; } function keyOf(tripId: number): string { return `${useAuthStore.getState().user?.id ?? 'anon'}:${tripId}`; } export const usePlaceVisitsStore = create((set) => ({ visited: {}, revision: 0, loadTripVisited: async (tripId) => { const { place_ids, places } = await placeVisitsRepo.tripVisited(tripId); const entry = { placeIds: place_ids, places }; set((state) => ({ visited: { ...state.visited, [keyOf(tripId)]: entry } })); return entry; }, bump: () => set((state) => ({ revision: state.revision + 1 })), })); /** The trip's visited places for the signed-in account, if the store holds them. */ export function tripVisitedEntry( state: PlaceVisitsState, tripId: number | null | undefined ): TripVisitedEntry | undefined { return tripId == null ? undefined : state.visited[keyOf(tripId)]; } /** * Reads again every trip whose visited places the store holds for this account, * after a visit changed here or reached it from elsewhere. */ export function refreshTripVisited(): void { const store = usePlaceVisitsStore.getState(); store.bump(); const prefix = `${useAuthStore.getState().user?.id ?? 'anon'}:`; const tripIds = Object.keys(store.visited) .filter((key) => key.startsWith(prefix)) .map((key) => Number(key.slice(prefix.length))) .filter((id) => Number.isSafeInteger(id) && id > 0); void Promise.all(tripIds.map((tripId) => store.loadTripVisited(tripId))).catch(() => { // Offline or refused: the store keeps the last answer until the next read. return undefined; }); } /** * The pushed changes that can change what the account visited: a place * planned on or taken off a day or given other participants, a day's date, a * place gone, someone joining or leaving a trip, a trip's dates, a trip gone * or the account's trips changing. A place in one trip can be the same place * as one in another (All places), so every held trip is read again. */ const VISIT_EVENTS: ReadonlySet = new Set([ 'assignment:created', 'assignment:updated', 'assignment:deleted', 'assignment:moved', 'assignment:participants', 'day:created', 'day:updated', 'day:deleted', 'day:reordered', 'place:deleted', 'member:added', 'member:removed', 'trip:updated', 'trip:deleted', 'trips:changed', ]); /** How long a burst of plan changes (a drag across days, an undo) is gathered before reading again. */ const REFRESH_DELAY_MS = 400; /** * Follows the trip events that can change the visits: moves the revision and * reads again every trip whose visited places the store holds for this * account, once per burst. Returns the function that stops listening. */ export function watchPlaceVisits(): () => void { let timer: ReturnType | null = null; const onEvent = (event: Record) => { if (typeof event?.type !== 'string' || !VISIT_EVENTS.has(event.type)) return; if (timer !== null) clearTimeout(timer); timer = setTimeout(() => { timer = null; refreshTripVisited(); }, REFRESH_DELAY_MS); }; addListener(onEvent); return () => { if (timer !== null) clearTimeout(timer); removeListener(onEvent); }; }