Download web/src/sheet/SheetSearch.tsx from fsanyoto/loopable: direct link, hf CLI and curl.
- Browser
- Download file 12.1 kB
-
https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/sheet/SheetSearch.tsx
- Command line
-
hf download hf://spaces/fsanyoto/loopable/web/src/sheet/SheetSearch.tsx
-
curl -L -o SheetSearch.tsx https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/sheet/SheetSearch.tsx
12.1 kB
| 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<HTMLInputElement>(null); | |
| const listId = useId(); | |
| const [open, setOpen] = useState(false); | |
| const [query, setQuery] = useState(""); | |
| const [selected, setSelected] = useState<string | null>(null); | |
| const [notice, setNotice] = useState(""); | |
| const [commands, setCommands] = useState<SheetSearchCommand[]>([]); | |
| const [indexer, setIndexer] = useState<ReactNode>(null); | |
| const [tabs, setTabs] = useState<Map<string, SheetTab>>(new Map()); | |
| const [reading, setReading] = useState(false); | |
| const [readErrors, setReadErrors] = useState<string[]>([]); | |
| // 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<string>()); | |
| 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<HTMLTextAreaElement>(".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 <div className="sheet-search"> | |
| <svg className="sheet-search-icon" viewBox="0 0 16 16" aria-hidden="true"> | |
| <circle cx="7" cy="7" r="4.5" /><path d="m10.5 10.5 3 3" /> | |
| </svg> | |
| <input | |
| ref={inputRef} className="sheet-search-input" type="text" data-kt="Q" | |
| placeholder="Search (Alt+Q)" aria-label="Search commands, functions and cells" | |
| role="combobox" aria-expanded={open} aria-controls={open ? listId : undefined} | |
| aria-autocomplete="list" aria-activedescendant={open && activeIndex >= 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(); | |
| }} | |
| /> | |
| <div hidden>{indexer}</div> | |
| {(searching || (open && notice)) && <AnchoredOverlay | |
| anchor={inputRef.current} className="sheet-ribbon-pop sheet-ribbon-pop-portal sheet-search-pop" | |
| onDismiss={close} initialFocus="none" restoreFocus={false} dataKind="sheet-search" | |
| > | |
| <div id={listId} role="listbox" aria-label="Search results" className="sheet-search-results"> | |
| {(["Commands", "Functions", "Cells"] as const).map(group => { | |
| const rows = results.filter(result => result.group === group); | |
| return rows.length > 0 && <div key={group} role="group" aria-label={group}> | |
| <div className="sheet-search-caption" aria-hidden="true">{group}</div> | |
| {rows.map(result => <button | |
| key={result.id} id={`${listId}-${results.indexOf(result)}`} type="button" role="option" | |
| aria-selected={result.id === active?.id} aria-disabled={result.disabled || undefined} | |
| disabled={result.disabled} tabIndex={-1} | |
| className={"sheet-search-result" + (result.id === active?.id ? " is-active" : "")} | |
| onMouseDown={event => event.preventDefault()} onClick={result.run} | |
| onMouseEnter={() => { if (!result.disabled) setSelected(result.id); }} | |
| > | |
| <span className="sheet-search-result-text"><span>{result.label}</span><span className="sheet-search-detail">{result.detail}</span></span> | |
| {result.disabled ? <span className="sheet-search-detail">Unavailable</span> | |
| : result.shortcut && <kbd className="sheet-search-shortcut">{result.shortcut}</kbd>} | |
| </button>)} | |
| </div>; | |
| })} | |
| </div> | |
| {!results.length && !reading && !readErrors.length && <p className="sheet-search-status">No match</p>} | |
| {reading && <p className="sheet-search-status" role="status">Reading other tabs</p>} | |
| {cellMatches.length > CELL_LIMIT && <p className="sheet-search-status">Showing {CELL_LIMIT} of {cellMatches.length} cells. Keep typing to narrow it.</p>} | |
| {readErrors.map((error, index) => <p key={index} className="sheet-search-status" role="status">{error.replace(/[\u2013\u2014]/g, ", ")}</p>)} | |
| {notice && <p className="sheet-search-status" role="status">{notice}</p>} | |
| </AnchoredOverlay>} | |
| </div>; | |
| } | |