Files
TREK/client/src/components/Collections/usePlacesLibrary.ts
T
Maurice 01d327b502 feat(places): Places replaces Collections, with All places, place sheets and a calmer list
- Collections is Places now: /places opens "All places", every place of the
  trips and lists with where it comes from, the same filter row (where from,
  status, category, order), map bar (search, lock, list toggle) and place sheet
  as a list; /places/saved and /places/:id are the lists, and the old
  /collections links still land there. On the phone the same, with its own
  sheet. A place sheet shows each trip (planned day or trip dates, stay,
  booking, notes) and each list (status, labels, rating, notes) as one row
  that opens it.
- The rail: a calm "New list" with its plus tile, All places and All saved as
  views, a "My lists" heading, every name on one edge. Lists can carry one of
  24 symbols, shown in their colour in the rail and the editor.
- A saved place's row keeps to two lines: its category as an icon before the
  name, its average vote as a star on the picture. Map pins wear the same star.
- The place forms put the category in front of the name as a tile that opens
  the category list, instead of a row of chips.
- All saved gets a subtitle; the import dialog opens centred.
- Fixes: a pasted coordinate pair splits from either field of the place form;
  "more" in All places frees itself when a filter changes mid-load; place
  names on the trip map and the rating badge follow the reading direction.
2026-11-29 15:49:35 +01:00

250 lines
7.9 KiB
TypeScript

import type {
CollectionStatus,
PlacesLibraryCounts,
PlacesLibraryDetailResponse,
PlacesLibraryEntry,
PlacesLibraryKind,
PlacesLibrarySort,
} from '@trek/shared';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { OnlineOnlyError } from '../../repo/onlineOnly';
import { placesLibraryRepo } from '../../repo/placesLibraryRepo';
import type { TranslationFn } from '../../types';
import { getApiErrorMessage } from '../../utils/apiError';
/** Which origins the overview shows: all, only trip places, only saved ones. */
export type LibraryKindFilter = 'all' | PlacesLibraryKind;
const PAGE = 60;
/** How long typing settles before the search asks the server. */
const SEARCH_SETTLE_MS = 250;
const NO_COUNTS: PlacesLibraryCounts = { all: 0, trip: 0, list: 0 };
/** The origin an entry is opened from: its key, `trip:<place id>` or `list:<saved place id>`. */
export function parseEntryKey(key: string): { kind: PlacesLibraryKind; id: number } | null {
const match = /^(trip|list):(\d+)$/.exec(key);
return match ? { kind: match[1] as PlacesLibraryKind, id: Number(match[2]) } : null;
}
/** An entry with coordinates, as a point for the map. */
export function entryHasPosition(entry: Pick<PlacesLibraryEntry, 'lat' | 'lng'>): boolean {
return entry.lat != null && entry.lng != null && Number.isFinite(entry.lat) && Number.isFinite(entry.lng);
}
/**
* "All places" (PLC-07, PLC-08): every place of the user's trips and lists in one
* overview, behind the desktop view and the phone screen, which render their own
* markup over it. Online only like the lists themselves; a filter change starts a
* fresh first page, "more" appends the next one, and opening an entry loads what
* each of its origins keeps.
*/
export function usePlacesLibrary({ active, t }: { active: boolean; t: TranslationFn }) {
const [search, setSearch] = useState('');
const [query, setQuery] = useState('');
const [kind, setKind] = useState<LibraryKindFilter>('all');
const [categoryId, setCategoryId] = useState<number | 'all'>('all');
const [sort, setSort] = useState<PlacesLibrarySort>('name');
const [status, setStatus] = useState<CollectionStatus | 'all'>('all');
const [entries, setEntries] = useState<PlacesLibraryEntry[]>([]);
const [total, setTotal] = useState(0);
const [counts, setCounts] = useState<PlacesLibraryCounts>(NO_COUNTS);
const [cursor, setCursor] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [loadingMore, setLoadingMore] = useState(false);
const [error, setError] = useState<string | null>(null);
const [offline, setOffline] = useState(false);
const [reloadSeq, setReloadSeq] = useState(0);
const [selectedKey, setSelectedKey] = useState<string | null>(null);
const [detail, setDetail] = useState<PlacesLibraryDetailResponse | null>(null);
const [detailLoading, setDetailLoading] = useState(false);
// The provider's photo for a place without its own, as a list's place sheet shows it.
const [cover, setCover] = useState<string | null>(null);
// Typing settles before it asks.
useEffect(() => {
const timer = setTimeout(() => setQuery(search.trim()), SEARCH_SETTLE_MS);
return () => clearTimeout(timer);
}, [search]);
const filters = useMemo(
() => ({
...(query ? { q: query } : {}),
...(kind !== 'all' ? { kind } : {}),
...(categoryId !== 'all' ? { category_id: categoryId } : {}),
...(status !== 'all' ? { status } : {}),
sort,
limit: PAGE,
}),
[query, kind, categoryId, status, sort]
);
const fail = useCallback(
(err: unknown) => {
if (err instanceof OnlineOnlyError) setOffline(true);
else setError(getApiErrorMessage(err, t('common.error')));
},
[t]
);
// The first page, again for every filter change and every reload.
useEffect(() => {
if (!active) return;
const ctrl = new AbortController();
setLoading(true);
setError(null);
setOffline(false);
placesLibraryRepo
.list(filters, ctrl.signal)
.then((page) => {
if (ctrl.signal.aborted) return;
setEntries(page.entries);
setTotal(page.total);
setCounts(page.counts);
setCursor(page.next_cursor);
})
.catch((err: unknown) => {
if (!ctrl.signal.aborted) fail(err);
})
.finally(() => {
if (!ctrl.signal.aborted) setLoading(false);
});
return () => ctrl.abort();
}, [active, filters, reloadSeq, fail]);
const moreRef = useRef<AbortController | null>(null);
const loadMore = useCallback(async () => {
if (!cursor || loadingMore) return;
moreRef.current?.abort();
const ctrl = new AbortController();
moreRef.current = ctrl;
setLoadingMore(true);
try {
const page = await placesLibraryRepo.list({ ...filters, cursor }, ctrl.signal);
if (ctrl.signal.aborted) return;
setEntries((prev) => [...prev, ...page.entries.filter((e) => !prev.some((p) => p.key === e.key))]);
setCursor(page.next_cursor);
} catch (err) {
if (!ctrl.signal.aborted) fail(err);
} finally {
// Only the latest request lets go of the button: an aborted one was replaced or
// dropped by a filter change, which lets go of it itself.
if (moreRef.current === ctrl) setLoadingMore(false);
}
}, [cursor, loadingMore, filters, fail]);
// A filter change starts over, so a page still on its way is dropped and "more" is free again.
useEffect(
() => () => {
moreRef.current?.abort();
moreRef.current = null;
setLoadingMore(false);
},
[filters]
);
// The entry that is open, and what its origins keep.
useEffect(() => {
const ref = selectedKey ? parseEntryKey(selectedKey) : null;
if (!ref) {
setDetail(null);
return;
}
const ctrl = new AbortController();
setDetailLoading(true);
placesLibraryRepo
.detail(ref.kind, ref.id, ctrl.signal)
.then((res) => {
if (!ctrl.signal.aborted) setDetail(res);
})
.catch((err: unknown) => {
if (ctrl.signal.aborted) return;
setDetail(null);
setSelectedKey(null);
fail(err);
})
.finally(() => {
if (!ctrl.signal.aborted) setDetailLoading(false);
});
return () => {
ctrl.abort();
setDetailLoading(false);
};
}, [selectedKey, reloadSeq, fail]);
useEffect(() => {
setCover(null);
const entry = detail?.entry;
if (!entry) return;
const own = entry.image_url ?? detail.details.map((d) => d.info.image_url).find(Boolean) ?? null;
if (own) {
setCover(own);
return;
}
let cancelled = false;
placesLibraryRepo
.coverPhoto(entry)
.then((url) => {
if (!cancelled) setCover(url);
})
// No photo is the gradient, which is what a failed lookup should look like too.
.catch(() => {
if (!cancelled) setCover(null);
});
return () => {
cancelled = true;
};
}, [detail]);
const reload = useCallback(() => setReloadSeq((n) => n + 1), []);
const open = useCallback((key: string | null) => setSelectedKey((cur) => (cur === key ? null : key)), []);
const show = useCallback((key: string) => setSelectedKey(key), []);
const close = useCallback(() => setSelectedKey(null), []);
const filtered = query !== '' || kind !== 'all' || categoryId !== 'all' || status !== 'all';
const resetFilters = useCallback(() => {
setSearch('');
setQuery('');
setKind('all');
setCategoryId('all');
setStatus('all');
}, []);
const mappable = useMemo(() => entries.filter(entryHasPosition), [entries]);
return {
search,
setSearch,
kind,
setKind,
categoryId,
setCategoryId,
sort,
setSort,
status,
setStatus,
filtered,
resetFilters,
entries,
mappable,
total,
counts,
hasMore: cursor != null,
loading,
loadingMore,
loadMore,
error,
offline,
reload,
selectedKey,
open,
show,
close,
detail,
detailLoading,
cover,
};
}