Files
TREK/client/src/store/placeVisitsStore.ts
T
Maurice d008331e5f feat(places): notes, visits, tours, history, tags and location in the place sheet, saved lists on the trip map
Both the desktop sheet and the phone sheet of All places show the place's
location as a badge, its notes per list, its visits from trips (hidden without
any), linked tours and bookings, its change history and the reader's own tags
with a tag filter. A trip map can show the places of linked lists and add one
to the trip. All places reloads after a list is added or removed.
2026-11-29 21:16:51 +01:00

125 lines
4.4 KiB
TypeScript

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<string, TripVisitedEntry>;
/** 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<TripVisitedEntry>;
bump: () => void;
}
function keyOf(tripId: number): string {
return `${useAuthStore.getState().user?.id ?? 'anon'}:${tripId}`;
}
export const usePlaceVisitsStore = create<PlaceVisitsState>((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<string> = 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<typeof setTimeout> | null = null;
const onEvent = (event: Record<string, unknown>) => {
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);
};
}