import { PLACES_LIBRARY_PAGE_MAX, type CollectionStatus, type PlacesLibraryEntry } from '@trek/shared'; import { useEffect, useState } from 'react'; import { placesLibraryRepo } from '../../repo/placesLibraryRepo'; /** At most this many pages are read, so a huge archive cannot keep the dialog busy. */ const MAX_PAGES = 10; /** A place of All places as the saved-place picker shows and hands it on. */ export interface PickerLibraryPlace { key: string; /** A use of the place to name its picture by: its trip place or its saved place. */ id: number; name: string; address: string | null; lat: number | null; lng: number | null; image_url: string | null; category: PlacesLibraryEntry['category']; /** The statuses its lists give it, for the picker's status filter. */ statuses: CollectionStatus[]; } /** An entry of All places as a row of the picker. */ export function pickerPlaceOf(entry: PlacesLibraryEntry): PickerLibraryPlace { const first = entry.origins[0]; return { key: entry.key, id: first.kind === 'trip' ? first.place_id : first.collection_place_id, name: entry.name, address: entry.address, lat: entry.lat, lng: entry.lng, image_url: entry.image_url, category: entry.category, statuses: entry.origins.flatMap((o) => (o.kind === 'list' ? [o.status] : [])), }; } /** * What a pick from All places fills the place form with: the facts the entry * carries, its category where the trip has the same one, and no provider id, * so the details column looks the place up by its position. */ export function pickedFromLibrary(place: PickerLibraryPlace): Record { return { name: place.name, address: place.address, lat: place.lat, lng: place.lng, category_id: place.category?.id ?? null, }; } async function readPages(signal: AbortSignal, cursor: string | undefined, read: number): Promise { const res = await placesLibraryRepo.list({ limit: PLACES_LIBRARY_PAGE_MAX, cursor }, signal); if (!res.next_cursor || read + 1 >= MAX_PAGES) return res.entries; return [...res.entries, ...(await readPages(signal, res.next_cursor, read + 1))]; } /** * Every place of All places for the saved-place picker of the place dialog: * the trips' places beside the lists', each place once. Read only once the * picker asks for them, and read whole, so the picker searches, filters and * sorts them by distance the same way it does the lists' places. */ export function usePickerLibrary(enabled: boolean) { const [places, setPlaces] = useState(null); // Asked for and not read yet: that is the whole of loading, a failed read leaves an empty list. const loading = enabled && places === null; useEffect(() => { if (!loading) return; const ctrl = new AbortController(); readPages(ctrl.signal, undefined, 0) .then((entries) => setPlaces(entries.map(pickerPlaceOf))) .catch(() => { if (!ctrl.signal.aborted) setPlaces([]); }); return () => ctrl.abort(); }, [loading]); return { places: places ?? [], loading, loaded: places !== null }; }