import { listChats } from "$lib/api/endpoints"; import type { Chat } from "$lib/api/types"; const DEBOUNCE_MS = 250; const LIMIT = 40; export function createChatPicker() { let results = $state([]); let timer: ReturnType | null = null; let seq = 0; async function run(query: string, current: number) { try { const found = await listChats({ limit: LIMIT, search: query || undefined, }); if (current === seq) { results = found; } } catch { if (current === seq) { results = []; } } } return { get results(): Chat[] { return results; }, search(query: string) { seq += 1; const current = seq; if (timer !== null) { clearTimeout(timer); } timer = setTimeout(() => { run(query.trim(), current).catch(() => undefined); }, DEBOUNCE_MS); }, }; }