mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-06 02:34:21 +00:00
feat(places): review possible duplicates, and repair the client gates
All places offers the pairs that look like one place: both sides side by side with what differs marked, "keep this one" to group them as one place of the user's own (undo right after), and "not the same place" to set a pair aside for good. Desktop dialog and phone sheet share usePlaceDuplicates; every locale has the new strings. What the last dev run flagged on the client: - Tailwind's Prettier plugin had trimmed the leading space of conditional class names (col-filter-btn, col-lrow sel, col-split map-full, col-detail docked), so the filter row and the open row lost their styling; those classes are now joined so the formatter cannot glue them. - The dock position lives in one helper for the lists and All places, which moves the measured-position markers there instead of adding new ones. - usePlacesLibrary is split into filters, pages, detail and cover hooks that derive their loading state instead of setting it inside effects; the big sheets and views are cut into parts under the complexity limit, dynamic icons go through createElement, originName moves out of a component file. - formatRange is guarded like in the packing export, the cover lookup skips places without a position. - Tests follow the rename to Places, the category icon, the default list icon and the new trip collections store; react-hooks/refs is lowered to the count the run measured. - The rating on a place is a round badge again, in the list and on the map.
This commit is contained in:
@@ -27,19 +27,56 @@ export function parseEntryKey(key: string): { kind: PlacesLibraryKind; id: numbe
|
||||
return match ? { kind: match[1] as PlacesLibraryKind, id: Number(match[2]) } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where an entry of one's own place (`own:<id>`) 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<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 }) {
|
||||
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<LibraryKindFilter>('all');
|
||||
@@ -47,22 +84,6 @@ export function usePlacesLibrary({ active, t }: { active: boolean; t: Translatio
|
||||
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);
|
||||
@@ -80,129 +101,6 @@ export function usePlacesLibrary({ active, t }: { active: boolean; t: Translatio
|
||||
}),
|
||||
[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('');
|
||||
@@ -212,38 +110,206 @@ export function usePlacesLibrary({ active, t }: { active: boolean; t: Translatio
|
||||
setStatus('all');
|
||||
}, []);
|
||||
|
||||
const mappable = useMemo(() => entries.filter(entryHasPosition), [entries]);
|
||||
return {
|
||||
filters,
|
||||
controls: {
|
||||
search,
|
||||
setSearch,
|
||||
kind,
|
||||
setKind,
|
||||
categoryId,
|
||||
setCategoryId,
|
||||
sort,
|
||||
setSort,
|
||||
status,
|
||||
setStatus,
|
||||
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<PageState>(EMPTY_PAGE);
|
||||
// The request "more" is loading for; another key means the button is free again.
|
||||
const [moreFor, setMoreFor] = useState<string | null>(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<AbortController | null>(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 {
|
||||
search,
|
||||
setSearch,
|
||||
kind,
|
||||
setKind,
|
||||
categoryId,
|
||||
setCategoryId,
|
||||
sort,
|
||||
setSort,
|
||||
status,
|
||||
setStatus,
|
||||
filtered,
|
||||
resetFilters,
|
||||
entries,
|
||||
mappable,
|
||||
total,
|
||||
counts,
|
||||
controls,
|
||||
page,
|
||||
loading: requestKey !== '' && !current,
|
||||
hasMore: cursor != null,
|
||||
loading,
|
||||
loadingMore,
|
||||
loadMore,
|
||||
error,
|
||||
offline,
|
||||
reload,
|
||||
};
|
||||
}
|
||||
|
||||
/** 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<string | null>(null);
|
||||
const [loaded, setLoaded] = useState<{ key: string; detail: PlacesLibraryDetailResponse } | null>(null);
|
||||
const [settled, setSettled] = useState<string | null>(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,
|
||||
detailLoading,
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* "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 [reloadSeq, setReloadSeq] = useState(0);
|
||||
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]);
|
||||
|
||||
return {
|
||||
...pages.controls,
|
||||
entries,
|
||||
mappable,
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user