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:` or `list:`. */ 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): 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('all'); const [categoryId, setCategoryId] = useState('all'); const [sort, setSort] = useState('name'); const [status, setStatus] = useState('all'); const [entries, setEntries] = useState([]); const [total, setTotal] = useState(0); const [counts, setCounts] = useState(NO_COUNTS); const [cursor, setCursor] = useState(null); const [loading, setLoading] = useState(false); const [loadingMore, setLoadingMore] = useState(false); const [error, setError] = useState(null); const [offline, setOffline] = useState(false); const [reloadSeq, setReloadSeq] = useState(0); const [selectedKey, setSelectedKey] = useState(null); const [detail, setDetail] = useState(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(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(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, }; }