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 { useSaveToCollectionStore } from '../../store/saveToCollectionStore'; 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; } /** * Where an entry of one's own place (`own:`) is opened from: its first use, since * the detail route reads a trip place or a saved place and lists every use either way. */ export function firstOrigin( entries: readonly PlacesLibraryEntry[], key: string ): { kind: PlacesLibraryKind; id: number } | null { const origin = entries.find((e) => e.key === key)?.origins[0]; if (!origin) return null; return origin.kind === 'trip' ? { kind: 'trip', id: origin.place_id } : { kind: 'list', id: origin.collection_place_id }; } /** 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); } interface PageState { /** The request this state answers; the first page is loading while it is not the current one. */ key: string; entries: PlacesLibraryEntry[]; total: number; counts: PlacesLibraryCounts; cursor: string | null; error: string | null; offline: boolean; } const EMPTY_PAGE: PageState = { key: '', entries: [], total: 0, counts: NO_COUNTS, cursor: null, error: null, offline: false, }; /** A failure as the screen shows it: offline says so, anything else names the error. */ function failureOf(err: unknown, t: TranslationFn): { error: string | null; offline: boolean } { return err instanceof OnlineOnlyError ? { error: null, offline: true } : { error: getApiErrorMessage(err, t('common.error')), offline: false }; } /** The filters of "All places". */ function useLibraryFilters() { 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'); // At least this many stars on the average of the votes, as the lists filter; unrated places drop out. const [minRating, setMinRating] = useState('all'); // PLC-21: tag names of the lists and trips, any of which an entry must carry, whatever their case. const [tagNames, setTagNames] = useState([]); const toggleTagName = useCallback( (name: string) => setTagNames((names) => { const key = name.trim().toLowerCase(); const kept = names.filter((n) => n.trim().toLowerCase() !== key); return kept.length < names.length || key === '' ? kept : [...names, name.trim()]; }), [] ); // 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 } : {}), ...(tagNames.length > 0 ? { tags: tagNames } : {}), ...(minRating !== 'all' ? { min_rating: minRating } : {}), sort, limit: PAGE, }), [query, kind, categoryId, status, tagNames, minRating, sort] ); const filtered = query !== '' || kind !== 'all' || categoryId !== 'all' || status !== 'all' || tagNames.length > 0 || minRating !== 'all'; const resetFilters = useCallback(() => { setSearch(''); setQuery(''); setKind('all'); setCategoryId('all'); setStatus('all'); setTagNames([]); setMinRating('all'); }, []); return { filters, controls: { search, setSearch, kind, setKind, categoryId, setCategoryId, sort, setSort, status, setStatus, tagNames, toggleTagName, minRating, setMinRating, filtered, resetFilters, }, }; } /** The first page for the filters and the pages "more" appends. */ function useLibraryPages(active: boolean, reloadSeq: number, t: TranslationFn) { const { filters, controls } = useLibraryFilters(); const [page, setPage] = useState(EMPTY_PAGE); // The request "more" is loading for; another key means the button is free again. const [moreFor, setMoreFor] = useState(null); const requestKey = active ? `${JSON.stringify(filters)}#${reloadSeq}` : ''; // The first page, again for every filter change and every reload. What was shown // stays until the answer comes, so a reload does not blank the list. useEffect(() => { if (!requestKey) return; const ctrl = new AbortController(); placesLibraryRepo .list(filters, ctrl.signal) .then((res) => { if (ctrl.signal.aborted) return; setPage({ key: requestKey, entries: res.entries, total: res.total, counts: res.counts, cursor: res.next_cursor, error: null, offline: false, }); }) .catch((err: unknown) => { if (!ctrl.signal.aborted) setPage((prev) => ({ ...prev, key: requestKey, ...failureOf(err, t) })); }); return () => ctrl.abort(); }, [requestKey, filters, t]); const current = page.key === requestKey; const cursor = current ? page.cursor : null; const loadingMore = moreFor !== null && moreFor === requestKey; const moreRef = useRef(null); const loadMore = useCallback(async () => { if (!cursor || loadingMore) return; moreRef.current?.abort(); const ctrl = new AbortController(); moreRef.current = ctrl; const forKey = requestKey; setMoreFor(forKey); try { const res = await placesLibraryRepo.list({ ...filters, cursor }, ctrl.signal); if (ctrl.signal.aborted) return; setPage((prev) => { if (prev.key !== forKey) return prev; const fresh = res.entries.filter((e) => !prev.entries.some((p) => p.key === e.key)); return { ...prev, entries: [...prev.entries, ...fresh], cursor: res.next_cursor }; }); } catch (err) { if (!ctrl.signal.aborted) setPage((prev) => (prev.key === forKey ? { ...prev, ...failureOf(err, t) } : prev)); } finally { if (moreRef.current === ctrl) setMoreFor(null); } }, [cursor, loadingMore, filters, requestKey, t]); // A filter change starts over, so a page still on its way is dropped. useEffect(() => () => moreRef.current?.abort(), [filters]); return { controls, page, loading: requestKey !== '' && !current, hasMore: cursor != null, loadingMore, loadMore, }; } /** The entry that is open and what its origins keep. */ function useLibraryDetail(entries: readonly PlacesLibraryEntry[], reloadSeq: number, onError: (err: unknown) => void) { const [selectedKey, setSelectedKey] = useState(null); const [loaded, setLoaded] = useState<{ key: string; detail: PlacesLibraryDetailResponse } | null>(null); const [settled, setSettled] = useState(null); // Where the open entry is read from, as text so a page arriving later does not ask again. const origin = selectedKey ? (parseEntryKey(selectedKey) ?? firstOrigin(entries, selectedKey)) : null; const originKey = origin ? `${origin.kind}:${origin.id}` : null; const requestKey = selectedKey && originKey ? `${selectedKey}|${originKey}#${reloadSeq}` : null; useEffect(() => { if (!selectedKey || !originKey || !requestKey) return; const [kind, id] = originKey.split(':'); const ctrl = new AbortController(); placesLibraryRepo .detail(kind as PlacesLibraryKind, Number(id), ctrl.signal) .then((res) => { if (!ctrl.signal.aborted) setLoaded({ key: selectedKey, detail: res }); }) .catch((err: unknown) => { if (ctrl.signal.aborted) return; setSelectedKey(null); onError(err); }) .finally(() => { if (!ctrl.signal.aborted) setSettled(requestKey); }); return () => ctrl.abort(); }, [selectedKey, originKey, requestKey, onError]); const open = useCallback((key: string | null) => setSelectedKey((cur) => (cur === key ? null : key)), []); const show = useCallback((key: string) => setSelectedKey(key), []); const close = useCallback(() => setSelectedKey(null), []); return { selectedKey, open, show, close, detail: loaded && loaded.key === selectedKey ? loaded.detail : null, detailLoading: requestKey !== null && settled !== requestKey, }; } /** The open place's picture: its own, a list's, or else the provider's photo for it. */ function useLibraryCover(detail: PlacesLibraryDetailResponse | null): string | null { const [photo, setPhoto] = useState<{ key: string; url: string | null } | null>(null); const entry = detail?.entry ?? null; const ownImage = entry ? (entry.image_url ?? detail?.details.map((d) => d.info.image_url).find(Boolean) ?? null) : null; useEffect(() => { if (!entry || ownImage || entry.lat == null || entry.lng == null) return; let cancelled = false; const key = entry.key; placesLibraryRepo .coverPhoto({ ...entry, lat: entry.lat, lng: entry.lng }) .then((url) => { if (!cancelled) setPhoto({ key, url }); }) // No photo is the gradient, which is what a failed lookup should look like too. .catch(() => { if (!cancelled) setPhoto({ key, url: null }); }); return () => { cancelled = true; }; }, [entry, ownImage]); if (ownImage) return ownImage; return entry && photo?.key === entry.key ? photo.url : null; } type TagOption = { name: string; color: string | null }; /** The tag names seen so far with those of these entries added, by case-folded name; the same map when none is new. */ function withTagsOf( seen: ReadonlyMap, entries: readonly PlacesLibraryEntry[] ): ReadonlyMap { let next: Map | null = null; for (const entry of entries) for (const tag of entry.tags ?? []) { const key = tag.name.toLowerCase(); if (seen.has(key) || next?.has(key)) continue; next ??= new Map(seen); next.set(key, { name: tag.name, color: tag.color ?? null }); } return next ?? seen; } /** * The tag names the filter offers: every tag seen on a place since the page * opened (a filter that narrows the list does not take its own options away), * and every picked one, sorted by name. */ export function useTagOptions(entries: readonly PlacesLibraryEntry[], picked: readonly string[]) { // What was seen is kept beside the entries it was read from, so new entries add to it while rendering. const [held, setHeld] = useState(() => ({ entries, seen: withTagsOf(new Map(), entries) })); let seen = held.seen; if (held.entries !== entries) { seen = withTagsOf(held.seen, entries); setHeld({ entries, seen }); } return useMemo(() => { const all = new Map(seen); for (const name of picked) if (!all.has(name.toLowerCase())) all.set(name.toLowerCase(), { name, color: null }); return [...all.values()].sort((x, y) => x.name.localeCompare(y.name)); }, [seen, picked]); } /** * "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 [ownSeq, setReloadSeq] = useState(0); // A place saved to a list from here or anywhere else adds an origin: read again then too. const savedVersion = useSaveToCollectionStore((st) => st.version); const reloadSeq = ownSeq + savedVersion; const [detailError, setDetailError] = useState<{ error: string | null; offline: boolean } | null>(null); const pages = useLibraryPages(active, reloadSeq, t); const onDetailError = useCallback((err: unknown) => setDetailError(failureOf(err, t)), [t]); const sel = useLibraryDetail(pages.page.entries, reloadSeq, onDetailError); const cover = useLibraryCover(sel.detail); const reload = useCallback(() => { setDetailError(null); setReloadSeq((n) => n + 1); }, []); const { entries, total, counts, error, offline } = pages.page; const mappable = useMemo(() => entries.filter(entryHasPosition), [entries]); const tagOptions = useTagOptions(entries, pages.controls.tagNames); return { ...pages.controls, entries, mappable, tagOptions, total, counts, hasMore: pages.hasMore, loading: pages.loading, loadingMore: pages.loadingMore, loadMore: pages.loadMore, error: error ?? detailError?.error ?? null, offline: offline || (detailError?.offline ?? false), reload, ...sel, cover, }; }