mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-06 18:54:17 +00:00
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.
This commit is contained in:
@@ -20,7 +20,8 @@ import type {
|
||||
export type IncomingCollectionInvite = CollectionListResponse['incomingInvites'][number]
|
||||
|
||||
/** What a copy into a trip takes along besides the places (D9): left out, neither notes nor tags. */
|
||||
type CopyToTripCarry = Pick<CollectionCopyToTripRequest, 'include_notes' | 'tag_ids'>
|
||||
/** What comes along into the trip: the notes, the list's tags, and (PLC-21) the personal tags chosen to share. */
|
||||
type CopyToTripCarry = Pick<CollectionCopyToTripRequest, 'include_notes' | 'tag_ids' | 'personal_tag_ids'>
|
||||
|
||||
/** Sentinel id for the client-side "All saved" union pseudo-list. */
|
||||
export const ALL_SAVED = 'all' as const
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
import type {
|
||||
PlaceActivity,
|
||||
PlaceActivitySource,
|
||||
PlaceLibraryActivitySource,
|
||||
PlacesLibraryKind,
|
||||
TripPlaceActivityLinkRequest,
|
||||
} from '@trek/shared';
|
||||
import { create } from 'zustand';
|
||||
|
||||
import { addListener, removeListener } from '../api/websocket';
|
||||
import { placeActivitiesRepo } from '../repo/placeActivitiesRepo';
|
||||
import { useAuthStore } from './authStore';
|
||||
|
||||
/**
|
||||
* The bookings and tours a place is about (PLC-18), as the server answered
|
||||
* for the signed-in account: per trip place, per saved place and per entry of
|
||||
* All places. Keyed by account, because what each person sees follows their
|
||||
* own rights. A `placeActivities:changed` push reads again what the store
|
||||
* holds for that trip place (and the entries it is an origin of); a
|
||||
* `collections:updated` push does the same for the saved places of that list.
|
||||
*/
|
||||
|
||||
export interface PlaceActivitiesEntry {
|
||||
activities: PlaceActivity[];
|
||||
/** Whether the reader may link more: on this place, or for an entry on any of its origins. */
|
||||
canLink: boolean;
|
||||
/** For an entry of All places: its origins and whether each takes links. Empty otherwise. */
|
||||
sources: PlaceLibraryActivitySource[];
|
||||
}
|
||||
|
||||
/** Which place an entry of the store belongs to. */
|
||||
export type PlaceActivitiesTarget =
|
||||
| { kind: 'trip'; tripId: number; placeId: number }
|
||||
| { kind: 'list'; collectionPlaceId: number }
|
||||
| { kind: 'entry'; entryKind: PlacesLibraryKind; id: number };
|
||||
|
||||
interface PlaceActivitiesState {
|
||||
entries: Record<string, PlaceActivitiesEntry>;
|
||||
/** Reads the activities of a trip place, a saved place or an entry. Online only; throws when refused or offline. */
|
||||
load: (target: PlaceActivitiesTarget) => Promise<PlaceActivitiesEntry>;
|
||||
/** Links a booking or tour of the trip to the trip place. */
|
||||
linkTrip: (tripId: number, placeId: number, body: TripPlaceActivityLinkRequest) => Promise<void>;
|
||||
/** Links a tour kept in the list to the saved place. */
|
||||
linkSaved: (collectionPlaceId: number, collectionTourId: number) => Promise<void>;
|
||||
/** Takes the link of an activity off the place it was linked to; the booking or tour stays. */
|
||||
unlink: (activity: Pick<PlaceActivity, 'source' | 'target'>) => Promise<void>;
|
||||
}
|
||||
|
||||
function targetKey(target: PlaceActivitiesTarget): string {
|
||||
const user = useAuthStore.getState().user?.id ?? 'anon';
|
||||
if (target.kind === 'trip') return `${user}:trip:${target.tripId}:${target.placeId}`;
|
||||
if (target.kind === 'list') return `${user}:list:${target.collectionPlaceId}`;
|
||||
return `${user}:entry:${target.entryKind}:${target.id}`;
|
||||
}
|
||||
|
||||
/** The store entry of the place a source names. */
|
||||
function sourceTarget(source: PlaceActivitySource): PlaceActivitiesTarget {
|
||||
return source.kind === 'trip'
|
||||
? { kind: 'trip', tripId: source.trip_id, placeId: source.place_id }
|
||||
: { kind: 'list', collectionPlaceId: source.collection_place_id };
|
||||
}
|
||||
|
||||
/** The targets the store holds, read back from their keys, for the signed-in account. */
|
||||
function heldTargets(entries: Record<string, PlaceActivitiesEntry>): PlaceActivitiesTarget[] {
|
||||
const prefix = `${useAuthStore.getState().user?.id ?? 'anon'}:`;
|
||||
return Object.keys(entries).flatMap((key): PlaceActivitiesTarget[] => {
|
||||
if (!key.startsWith(prefix)) return [];
|
||||
const [kind, a, b] = key.slice(prefix.length).split(':');
|
||||
if (kind === 'trip') return [{ kind: 'trip', tripId: Number(a), placeId: Number(b) }];
|
||||
if (kind === 'list') return [{ kind: 'list', collectionPlaceId: Number(a) }];
|
||||
if (kind === 'entry' && (a === 'trip' || a === 'list')) return [{ kind: 'entry', entryKind: a, id: Number(b) }];
|
||||
return [];
|
||||
});
|
||||
}
|
||||
|
||||
export const usePlaceActivitiesStore = create<PlaceActivitiesState>((set, get) => {
|
||||
const put = (target: PlaceActivitiesTarget, entry: PlaceActivitiesEntry): PlaceActivitiesEntry => {
|
||||
set((state) => ({ entries: { ...state.entries, [targetKey(target)]: entry } }));
|
||||
return entry;
|
||||
};
|
||||
/** After a write: the place it changed, and every entry of All places held that has it as an origin. */
|
||||
const refreshAround = async (place: PlaceActivitiesTarget) => {
|
||||
const entries = get().entries;
|
||||
const around = heldTargets(entries).filter(
|
||||
(target) =>
|
||||
target.kind === 'entry' &&
|
||||
(entries[targetKey(target)]?.sources.some((origin) => isPlace(origin.source, place)) ?? false)
|
||||
);
|
||||
await Promise.all(around.map((target) => get().load(target)));
|
||||
};
|
||||
|
||||
return {
|
||||
entries: {},
|
||||
|
||||
load: async (target) => {
|
||||
if (target.kind === 'trip') {
|
||||
const { activities, can_link } = await placeActivitiesRepo.tripPlace(target.tripId, target.placeId);
|
||||
return put(target, { activities, canLink: can_link, sources: [] });
|
||||
}
|
||||
if (target.kind === 'list') {
|
||||
const { activities, can_link } = await placeActivitiesRepo.savedPlace(target.collectionPlaceId);
|
||||
return put(target, { activities, canLink: can_link, sources: [] });
|
||||
}
|
||||
const { activities, sources } = await placeActivitiesRepo.libraryEntry(target.entryKind, target.id);
|
||||
return put(target, { activities, canLink: sources.some((origin) => origin.can_link), sources });
|
||||
},
|
||||
|
||||
linkTrip: async (tripId, placeId, body) => {
|
||||
const { activities, can_link } = await placeActivitiesRepo.linkTrip(tripId, placeId, body);
|
||||
const place = { kind: 'trip', tripId, placeId } as const;
|
||||
put(place, { activities, canLink: can_link, sources: [] });
|
||||
await refreshAround(place);
|
||||
},
|
||||
|
||||
linkSaved: async (collectionPlaceId, collectionTourId) => {
|
||||
const { activities, can_link } = await placeActivitiesRepo.linkSaved(collectionPlaceId, collectionTourId);
|
||||
const place = { kind: 'list', collectionPlaceId } as const;
|
||||
put(place, { activities, canLink: can_link, sources: [] });
|
||||
await refreshAround(place);
|
||||
},
|
||||
|
||||
unlink: async (activity) => {
|
||||
const { activities, can_link } = await placeActivitiesRepo.unlink(activity);
|
||||
const place = sourceTarget(activity.source);
|
||||
put(place, { activities, canLink: can_link, sources: [] });
|
||||
await refreshAround(place);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
/** Whether an origin of an entry is the trip place or saved place `place`. */
|
||||
function isPlace(source: PlaceActivitySource, place: PlaceActivitiesTarget): boolean {
|
||||
if (source.kind === 'trip') return place.kind === 'trip' && place.placeId === source.place_id;
|
||||
return place.kind === 'list' && place.collectionPlaceId === source.collection_place_id;
|
||||
}
|
||||
|
||||
/** The store's entry for the signed-in account, if it holds one. */
|
||||
export function placeActivitiesEntry(
|
||||
state: Pick<PlaceActivitiesState, 'entries'>,
|
||||
target: PlaceActivitiesTarget
|
||||
): PlaceActivitiesEntry | undefined {
|
||||
return state.entries[targetKey(target)];
|
||||
}
|
||||
|
||||
/** Whether a held target is touched by a push: the trip place `placeId`, or the list `collectionId`. */
|
||||
function touched(
|
||||
target: PlaceActivitiesTarget,
|
||||
entry: PlaceActivitiesEntry | undefined,
|
||||
push: { placeId?: number; collectionId?: number }
|
||||
): boolean {
|
||||
if (target.kind === 'trip') return target.placeId === push.placeId;
|
||||
if (target.kind === 'list') {
|
||||
return (
|
||||
entry?.activities.some(
|
||||
(activity) => activity.source.kind === 'list' && activity.source.collection_id === push.collectionId
|
||||
) ?? false
|
||||
);
|
||||
}
|
||||
return (
|
||||
entry?.sources.some(({ source }) =>
|
||||
source.kind === 'trip' ? source.place_id === push.placeId : source.collection_id === push.collectionId
|
||||
) ?? false
|
||||
);
|
||||
}
|
||||
|
||||
const positiveId = (value: unknown): number | undefined => {
|
||||
const id = Number(value);
|
||||
return Number.isSafeInteger(id) && id > 0 ? id : undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* Applies `placeActivities:changed` (a trip place's links changed) and
|
||||
* `collections:updated` (something in a list changed, its saved places'
|
||||
* links among it): reads again every held trip place, saved place and entry
|
||||
* the push touches. A saved place the store holds without any activity is
|
||||
* read again on every push of any list, since nothing says which list it is on.
|
||||
* Returns the function that stops listening.
|
||||
*/
|
||||
export function watchPlaceActivities(): () => void {
|
||||
const onEvent = (event: Record<string, unknown>) => {
|
||||
if (event?.type !== 'placeActivities:changed' && event?.type !== 'collections:updated') return;
|
||||
const push: { placeId?: number; collectionId?: number } =
|
||||
event.type === 'placeActivities:changed'
|
||||
? { placeId: positiveId(event.placeId) }
|
||||
: { collectionId: positiveId(event.collectionId) };
|
||||
if (push.placeId === undefined && push.collectionId === undefined) return;
|
||||
const store = usePlaceActivitiesStore.getState();
|
||||
for (const target of heldTargets(store.entries)) {
|
||||
const entry = placeActivitiesEntry(store, target);
|
||||
const unknownList = target.kind === 'list' && push.collectionId !== undefined && !entry?.activities.length;
|
||||
if (!unknownList && !touched(target, entry, push)) continue;
|
||||
void store.load(target).catch(() => {
|
||||
// Offline or refused: the store keeps the last answer until the next read.
|
||||
return undefined;
|
||||
});
|
||||
}
|
||||
};
|
||||
addListener(onEvent);
|
||||
return () => removeListener(onEvent);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { PlacesLibraryBulkTagsRequest, PlacesLibraryEntry, Tag } from '@trek/shared';
|
||||
import { create } from 'zustand';
|
||||
|
||||
import { addListener, removeListener } from '../api/websocket';
|
||||
import { placeTagsRepo } from '../repo/placeTagsRepo';
|
||||
|
||||
/**
|
||||
* PLC-21: the signed-in user's personal tags, as the tag picker and the tag
|
||||
* filter of All places offer them, by name. Online only, like the repo. The
|
||||
* assignments themselves are not kept here: an entry carries its own tags,
|
||||
* and a change answers the entries as they are now, for the caller to put
|
||||
* where it shows them. A `tags:changed` push (another tab or device changed
|
||||
* the tags) reads the list again.
|
||||
*/
|
||||
interface PlaceTagsState {
|
||||
tags: Tag[];
|
||||
loaded: boolean;
|
||||
/** Reads the tags again. Online only; throws when offline or refused. */
|
||||
load: () => Promise<Tag[]>;
|
||||
/** The user's tag of that name (case ignored), made now when there is none yet. */
|
||||
create: (name: string, color?: string) => Promise<Tag>;
|
||||
update: (id: number, changes: { name?: string; color?: string }) => Promise<Tag>;
|
||||
/** Deletes the tag; it comes off every place that carried it. */
|
||||
remove: (id: number) => Promise<void>;
|
||||
/** The entry carries exactly these tags from now on; answers the entry, null once out of reach. */
|
||||
setForEntry: (key: string, tagIds: number[]) => Promise<PlacesLibraryEntry | null>;
|
||||
/** Puts tags on several entries and takes others off; answers the entries. */
|
||||
bulk: (body: PlacesLibraryBulkTagsRequest) => Promise<PlacesLibraryEntry[]>;
|
||||
}
|
||||
|
||||
const byName = (a: Tag, b: Tag) => String(a.name).localeCompare(String(b.name)) || a.id - b.id;
|
||||
|
||||
/** The list with `tag` in it, once, in name order. */
|
||||
function withTag(tags: Tag[], tag: Tag): Tag[] {
|
||||
return [...tags.filter((other) => other.id !== tag.id), tag].sort(byName);
|
||||
}
|
||||
|
||||
export const usePlaceTagsStore = create<PlaceTagsState>((set) => ({
|
||||
tags: [],
|
||||
loaded: false,
|
||||
|
||||
async load() {
|
||||
const tags = [...(await placeTagsRepo.list())].sort(byName);
|
||||
set({ tags, loaded: true });
|
||||
return tags;
|
||||
},
|
||||
|
||||
async create(name, color) {
|
||||
const tag = await placeTagsRepo.create(name, color);
|
||||
set((state) => ({ tags: withTag(state.tags, tag) }));
|
||||
return tag;
|
||||
},
|
||||
|
||||
async update(id, changes) {
|
||||
const tag = await placeTagsRepo.update(id, changes);
|
||||
set((state) => ({ tags: withTag(state.tags, tag) }));
|
||||
return tag;
|
||||
},
|
||||
|
||||
async remove(id) {
|
||||
await placeTagsRepo.remove(id);
|
||||
set((state) => ({ tags: state.tags.filter((tag) => tag.id !== id) }));
|
||||
},
|
||||
|
||||
async setForEntry(key, tagIds) {
|
||||
return await placeTagsRepo.setForEntry(key, tagIds);
|
||||
},
|
||||
|
||||
async bulk(body) {
|
||||
return await placeTagsRepo.bulk(body);
|
||||
},
|
||||
}));
|
||||
|
||||
/**
|
||||
* Reads the tags again on a `tags:changed` push while the store has been
|
||||
* loaded once. Returns the unsubscribe.
|
||||
*/
|
||||
export function subscribePlaceTags(): () => void {
|
||||
const onEvent = (event: Record<string, unknown>) => {
|
||||
if (event?.type !== 'tags:changed') return;
|
||||
const store = usePlaceTagsStore.getState();
|
||||
if (!store.loaded) return;
|
||||
void store.load().catch(() => {
|
||||
// Offline or refused: the last list stays until the next read.
|
||||
return undefined;
|
||||
});
|
||||
};
|
||||
addListener(onEvent);
|
||||
return () => removeListener(onEvent);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
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);
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user