import { createSignal, onMount, onCleanup, For, Show } from 'solid-js'; /** * Searchable multi-select backed by an async lookup. * * Selections are kept as opaque string values; the labels come from the * `search` callback, which is also asked to resolve already-saved values on * mount so a reload shows names rather than bare ids. * * Props: * value string[] selected values * search (q, include) => Promise<[{value,label,meta}]> * onChange (next: string[]) => void * placeholder, emptyText */ export default function MultiSelect(props) { const [open, setOpen] = createSignal(false); const [query, setQuery] = createSignal(''); const [results, setResults] = createSignal([]); const [labels, setLabels] = createSignal({}); const [busy, setBusy] = createSignal(false); let containerRef; let inputRef; let searchToken = 0; const selected = () => props.value || []; const remember = (items) => { const next = { ...labels() }; for (const item of items) { next[item.value] = item; } setLabels(next); }; // Nothing is fetched until the user actually types. On a site with // thousands of posts, opening the box should not pull a list nobody asked // for - and the first thing anyone does here is search by name anyway. const MIN_QUERY = 2; // Debounced so typing doesn't fire a request per keystroke. The token // guards against an earlier, slower response overwriting a later one. let debounce; const runSearch = (q) => { clearTimeout(debounce); if (!q || q.trim().length < MIN_QUERY) { setResults([]); setBusy(false); return; } debounce = setTimeout(async () => { const token = ++searchToken; setBusy(true); try { const items = await props.search(q, []); if (token !== searchToken) return; setResults(items); remember(items); } catch (e) { if (token === searchToken) setResults([]); } finally { if (token === searchToken) setBusy(false); } }, 250); }; onMount(async () => { const onDocClick = (e) => { if (containerRef && !containerRef.contains(e.target)) setOpen(false); }; document.addEventListener('click', onDocClick); onCleanup(() => { document.removeEventListener('click', onDocClick); clearTimeout(debounce); }); // Resolve saved ids to labels. if (selected().length) { try { remember(await props.search('', selected())); } catch (e) { /* labels stay as raw values */ } } }); const add = (item) => { remember([item]); if (!selected().includes(item.value)) { props.onChange?.([...selected(), item.value]); } setQuery(''); setResults([]); inputRef?.focus(); }; const remove = (value) => { props.onChange?.(selected().filter((v) => v !== value)); }; const labelFor = (value) => labels()[value]?.label || value; const metaFor = (value) => labels()[value]?.meta || ''; const available = () => results().filter((r) => !selected().includes(r.value)); return (