import { useEffect, useId, useMemo, useRef, useState } from "react"; import type { ReactNode } from "react"; import { AnchoredOverlay } from "../customer-grid/OverlaySurface"; import { FUNCTIONS } from "./functionCatalog"; import { writeSheetAddress } from "./index"; import { readTab } from "./sheetApi"; import { ribbonCommandShortcut } from "./shortcuts"; import type { Cell, SheetTab, Workbook } from "./types"; import "../styles/wave66/sheet-search.css"; export interface SheetSearchCommand { id: string; key: string; label: string; location: string; disabled: boolean; run: () => void; } interface Props { storagePrefix?: string; book: Workbook | null; activeSheetId?: string; disabled?: boolean; buildCommands: (publish: (commands: SheetSearchCommand[]) => void) => ReactNode; } interface SearchResult { id: string; group: "Commands" | "Functions" | "Cells"; label: string; detail: string; shortcut?: string; disabled?: boolean; rank: number; run: () => void; } /** Prefix, word start, then substring. A miss sorts outside the result set. */ function matchRank(text: string, query: string): number { const value = text.toLocaleLowerCase(); if (value.startsWith(query)) return 0; if (value.split(/[^\p{L}\p{N}_]+/u).some(word => word.startsWith(query))) return 1; return value.includes(query) ? 2 : 3; } function cellTexts(cell: Cell): string[] { if (cell.kind === "empty") return []; return [cell.display, cell.value, cell.kind === "literal" ? cell.text : undefined] .filter(value => value !== undefined && value !== null && typeof value !== "object") .map(String).filter(Boolean); } function cellLabel(tab: string, address: string): string { const name = /^[\p{L}_][\p{L}\p{N}_]*$/u.test(tab) ? tab : `'${tab.replace(/'/g, "''")}'`; return `${name}!${address}`; } const CELL_LIMIT = 50; export default function SheetSearch({ book, activeSheetId, buildCommands, disabled = false, storagePrefix = "" }: Props) { const inputRef = useRef(null); const listId = useId(); const [open, setOpen] = useState(false); const [query, setQuery] = useState(""); const [selected, setSelected] = useState(null); const [notice, setNotice] = useState(""); const [commands, setCommands] = useState([]); const [indexer, setIndexer] = useState(null); const [tabs, setTabs] = useState>(new Map()); const [reading, setReading] = useState(false); const [readErrors, setReadErrors] = useState([]); // The component is keyed by workbook id. A tab counts as loaded once the page holds ANY cell // map for it, empty included, so clearing the last local value never resurrects its saved value // in search results. ⛔ A tab the page has not opened carries NO `cells` key at all // (`sheets.py::workbook_meta` drops it for C3's `?tabs=meta`), so it is unread, never empty. const loaded = useRef(new Set()); if (activeSheetId) loaded.current.add(activeSheetId); book?.sheets.forEach(tab => { if (tab.cells) loaded.current.add(tab.id); }); const start = () => { if (open) return; setNotice(""); setSelected(null); setIndexer(buildCommands(setCommands)); setOpen(true); }; const close = () => { setOpen(false); setIndexer(null); }; const normalizedQuery = query.trim().toLocaleLowerCase(); const searching = open && normalizedQuery !== ""; useEffect(() => { if (!searching || !book) return; let cancelled = false; const missing = book.sheets.filter(tab => (tab.visibility ?? "visible") === "visible" && !loaded.current.has(tab.id) && !tabs.has(tab.id)); setReadErrors([]); if (!missing.length) return; setReading(true); // One read per unread tab, the first time a query needs it; what was read is kept for this // workbook's search, so typing never refetches. Reads never adopt into the workbook, save, // recompute, or replace fresher local cells. void (async () => { for (const tab of missing) { try { const result = await readTab(book.id, tab.id); if (cancelled) return; if (result.ok && result.value) { const value = result.value; setTabs(held => new Map(held).set(tab.id, value)); } else { const message = result.ok ? "This tab could not be read." : result.message; setReadErrors(held => [...held, `${tab.name}: ${message}`]); } } catch (error) { if (cancelled) return; setReadErrors(held => [...held, `${tab.name}: ${error instanceof Error ? error.message : "This tab could not be read."}`]); } } if (!cancelled) setReading(false); })(); return () => { cancelled = true; setReading(false); }; // The first query chooses reads; the live book below always supplies local results. // eslint-disable-next-line react-hooks/exhaustive-deps }, [searching, book?.id]); const insertFunction = (name: string) => { const editor = inputRef.current?.closest(".sheet-grid-wrap") ?.querySelector(".sheet-fx textarea.sheet-fx-input"); if (!editor || editor.disabled) { setNotice("Select a cell to insert a function."); return; } if (editor.readOnly) { setNotice("This cell reads from a database and cannot accept a formula."); return; } close(); const draft = `=${name}(`; editor.focus(); Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(editor, draft); editor.setSelectionRange(draft.length, draft.length); editor.dispatchEvent(new Event("input", { bubbles: true })); editor.setSelectionRange(draft.length, draft.length); }; const cellMatches = useMemo(() => { if (!open || !book || !normalizedQuery) return []; const matches: { id: string; label: string; detail: string; rank: number; tab: string; cell: string }[] = []; for (const tab of book.sheets) { if ((tab.visibility ?? "visible") !== "visible") continue; const source = loaded.current.has(tab.id) ? tab : tabs.get(tab.id); if (source && (source.visibility ?? "visible") !== "visible") continue; for (const [address, cell] of Object.entries(source?.cells ?? {})) { const texts = cellTexts(cell); const rank = Math.min(3, ...texts.map(text => matchRank(text, normalizedQuery))); if (rank < 3) matches.push({ id: `cell:${tab.id}:${address}`, label: texts[0], detail: cellLabel(tab.name, address), rank, tab: tab.id, cell: address, }); } } return matches.sort((a, b) => a.rank - b.rank || a.detail.localeCompare(b.detail)); }, [open, book, normalizedQuery, tabs]); const results: SearchResult[] = !open || !normalizedQuery ? [] : [ ...commands.map(command => ({ ...command, group: "Commands" as const, detail: command.location, disabled: disabled || command.disabled, shortcut: ribbonCommandShortcut(command.key, command.label, storagePrefix), rank: matchRank(command.label, normalizedQuery), run: () => { close(); command.run(); }, })).filter(result => result.rank < 3).sort((a, b) => a.rank - b.rank || a.label.localeCompare(b.label)), ...FUNCTIONS.map(fn => ({ id: `function:${fn.name}`, group: "Functions" as const, label: fn.name, detail: fn.signature, rank: matchRank(fn.name, normalizedQuery), run: () => insertFunction(fn.name), })).filter(result => result.rank < 3).sort((a, b) => a.rank - b.rank || a.label.localeCompare(b.label)), ...cellMatches.slice(0, CELL_LIMIT).map(cell => ({ ...cell, group: "Cells" as const, run: () => { close(); if (book) writeSheetAddress({ wb: book.id, tab: cell.tab, cell: cell.cell }); }, })), ]; const enabled = results.filter(result => !result.disabled); const active = enabled.find(result => result.id === selected) ?? enabled[0]; const activeIndex = results.findIndex(result => result.id === active?.id); useEffect(() => { if (activeIndex >= 0) document.getElementById(`${listId}-${activeIndex}`)?.scrollIntoView({ block: "nearest" }); }, [activeIndex, listId, query]); return
= 0 ? `${listId}-${activeIndex}` : undefined} value={query} onFocus={start} onClick={start} onChange={event => { setQuery(event.currentTarget.value); setSelected(null); setNotice(""); start(); }} onKeyDown={event => { if (event.nativeEvent.isComposing) return; if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); event.stopPropagation(); if (!open) { start(); return; } if (enabled.length) { const at = enabled.findIndex(result => result.id === active?.id); const next = (at + (event.key === "ArrowDown" ? 1 : -1) + enabled.length) % enabled.length; setSelected(enabled[next].id); } } else if (event.key === "Enter") { event.preventDefault(); event.stopPropagation(); if (!open) start(); else active?.run(); } else if (event.key === "Tab") close(); }} /> {(searching || (open && notice)) &&
{(["Commands", "Functions", "Cells"] as const).map(group => { const rows = results.filter(result => result.group === group); return rows.length > 0 &&
{rows.map(result => )}
; })}
{!results.length && !reading && !readErrors.length &&

No match

} {reading &&

Reading other tabs

} {cellMatches.length > CELL_LIMIT &&

Showing {CELL_LIMIT} of {cellMatches.length} cells. Keep typing to narrow it.

} {readErrors.map((error, index) =>

{error.replace(/[\u2013\u2014]/g, ", ")}

)} {notice &&

{notice}

}
}
; }