import { useCallback, useMemo } from "react"; import { useSearchParams } from "react-router-dom"; const haystacks = new WeakMap(); /** Every readable value in a row — text and numbers, however deep — as one lowercase string to search in. */ function haystackOf(row: unknown): string { if (row !== null && typeof row === "object") { const cached = haystacks.get(row); if (cached !== undefined) return cached; } const parts: string[] = []; const walk = (value: unknown, depth: number) => { if (typeof value === "string") parts.push(value); else if (typeof value === "number") parts.push(String(value)); else if (depth < 3 && Array.isArray(value)) for (const v of value) walk(v, depth + 1); else if (depth < 3 && value !== null && typeof value === "object") for (const v of Object.values(value)) walk(v, depth + 1); }; walk(row, 0); const text = parts.join(" \n").toLowerCase(); if (row !== null && typeof row === "object") haystacks.set(row, text); return text; } /** * Text search over a table's rows. Several words must all appear (in any column, in any order), so "elsa running" finds a running * container on elsa. Returns the rows unchanged while the box is empty, and `null`/`undefined` as they came while loading. * * The words live in the address (`?q=elsa running`), so a search survives a reload, can be bookmarked or sent on, and can be pinned as * a saved view. A page has one searchable table, so one `q`; other things in the address are left alone. */ export function useTableSearch(items: T[] | null | undefined) { const [params, setParams] = useSearchParams(); const query = params.get("q") ?? ""; const setQuery = useCallback( (value: string) => setParams( (prev) => { const next = new URLSearchParams(prev); if (value) next.set("q", value); else next.delete("q"); return next; }, { replace: true }, ), [setParams], ); const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean); const key = terms.join(" "); const filtered = useMemo(() => { if (!items || key === "") return items; const wanted = key.split(" "); return items.filter((row) => { const hay = haystackOf(row); return wanted.every((t) => hay.includes(t)); }); }, [items, key]); return { query, setQuery, filtered, active: key !== "" }; }