import type { CollectionPlace } from '@trek/shared'; import { collectionsApi } from '../api/collections'; /** Detail requests fired at once while building the union. A user with many * lists would otherwise open "All saved" (or the trip's saved-places picker) * with one full list read per list, all in parallel (#2559). */ const DETAIL_BATCH = 4; /** Union of every list's places, in list order, without duplicates. A list * that cannot be read is skipped. */ export async function loadUnionPlaces(ids: number[]): Promise { const merged: CollectionPlace[] = []; const seen = new Set(); for (let i = 0; i < ids.length; i += DETAIL_BATCH) { const batch = await Promise.all( ids.slice(i, i + DETAIL_BATCH).map((id) => collectionsApi.get(id).catch(() => { // A list that cannot be read (left, deleted, unreachable) is skipped, so // the union still holds the places of every list that can be. return null; }) ) ); for (const d of batch) { if (!d) continue; for (const p of d.places) { if (seen.has(p.id)) continue; seen.add(p.id); merged.push(p); } } } return merged; } /** * The places of several lists with each place once, for the views over all of * them (All saved, the picker's All lists): copies saved from the same trip * place are one place, the way All places groups them, and the first one read * stands for it. Every other saved place stays, even with the same name. */ export function distinctPlaces(places: CollectionPlace[]): CollectionPlace[] { const seen = new Set(); return places.filter((p) => { const key = copyKey(p); if (seen.has(key)) return false; seen.add(key); return true; }); } /** Which place a saved place is a copy of: its trip place, or itself when it came from none. */ export function copyKey(p: CollectionPlace): string { return p.source_place_id != null ? `trip:${p.source_place_id}` : `list:${p.id}`; } /** * Every saved place's id with the ids of all copies of the same place, so an * action on the one row All saved shows (delete, a status, tags) reaches each * list that keeps the place. */ export function copiesOf(places: CollectionPlace[]): Map { const byKey = new Map(); for (const p of places) byKey.set(copyKey(p), [...(byKey.get(copyKey(p)) ?? []), p.id]); return new Map(places.map((p) => [p.id, byKey.get(copyKey(p)) ?? [p.id]])); }