// sheet/FormulaAssist.tsx — the assist UI, wave 52 (W52-T06, contract C3, instructions 5 and 7). // // T05 built the PURE engine (`formulaAssist.ts`, `functionCatalog.ts`, `refColors.ts`) and shipped // no UI at all. This file is that UI: the suggestion dropdown (FA-1..FA-26), the ScreenTip // (ST-1..ST-16) and the coloured-reference text (CR-1..CR-10). It is mounted from BOTH // `FormulaBar.tsx` and `SheetGrid.tsx`'s own cell editor, driven off the SAME local engine in both // places, so the behaviour is identical wherever a formula is typed. // // ⛔⛔ THE ENGINE PROPS BELOW ARE REQUIRED. An optional prop degrades to "the feature does not // exist" with nobody told, which is indistinguishable from never having built it (the ticket's own // words). `verify_wiring.py`'s row for this component matches the declaration WITH NO `?`, so `tsc` // itself fails a call site that forgets one. // W61-T10's caretOffset is positioning only: omitting it preserves the formula bar's placement. // // ⛔ POINT MODE (PM-1..PM-18) IS NOT HERE. It is grid interaction (arrow keys picking a cell, // scrolling to it, a coloured border on the CANVAS) with no meaning for a component that draws only // a dropdown and a tooltip; `SheetGrid.tsx` owns it, the same way T05's header note left it to T06. // // ⚠ DESIGN CONTRACT: this is a TRANSIENT OVERLAY over a dense grid. No layout shift, dismiss on // Escape (owned by the caller, see `dismissed` below), never traps focus (no call site here ever // calls `.focus()`), and no animation on a keystroke-driven state change. Navy/gold tokens only, no // em dash or en dash in any string (FA-15's row summary is the one new copy surface). import { useLayoutEffect, useMemo, useRef } from "react"; import type { ReactNode } from "react"; import { activeArg, refsIn, suggest } from "./formulaAssist"; import type { SuggestItem } from "./formulaAssist"; import { findFunction } from "./functionCatalog"; import { colorForSlot } from "./refColors"; /** * The identifier run immediately before `caret`, as a START INDEX rather than the matched text * (`formulaAssist.ts::suggest` already returns the matched functions; a caller only ever needs to * know where to splice). Same grammar as `suggest`'s own private `IDENT_TAIL` -- letters, digits, * underscore, dot -- duplicated here rather than exported from a PURE, gated T05 module (contract * C3 leaves that file to T05's own gate; this is a UI-layer splicing concern, not an engine rule). */ const IDENT_TAIL = /[A-Za-z_][A-Za-z0-9_.]*$/; export function tokenStartAt(text: string, caret: number): number { const upto = text.slice(0, Math.max(0, Math.min(caret, text.length))); const m = IDENT_TAIL.exec(upto); return m ? caret - m[0].length : caret; } export interface FormulaAssistProps { /** The full formula buffer text being edited. Only ever consulted while it starts with "=". */ text: string; /** Caret position inside `text`. */ caret: number; /** Bottom of the caret's line, relative to the input wrapper. Omit for bar placement. */ caretOffset?: { x: number; y: number }; /** Which suggestion row is highlighted. The CALLER owns Up/Down cycling (FA-16). */ activeIndex: number; /** * FA-23's first Escape: the caller sets this true to close the list WITHOUT touching the * buffer, and clears it the moment the buffer or caret changes (FA-24, "typing again reopens * it"). A missing flag here would leave the dropdown unable to ever stay closed, since * `suggest()` is a pure function of `text`/`caret` and both are unchanged by Escape alone. */ dismissed: boolean; /** Tab (FA-18) or a double click (FA-22) accepted this row. NEVER wired to Enter (FA-19). */ onAccept: (item: SuggestItem) => void; /** The mouse entered a row: it becomes the highlighted one, without accepting (FA-22). */ onHoverIndex: (index: number) => void; } /** ST-4/ST-6: the signature with its active argument (bracketed or bare) rendered bold. */ function renderSignature(signature: string, boldArgName: string | null): ReactNode { if (!boldArgName) return signature; const bracketed = `[${boldArgName}]`; const bracketedAt = signature.indexOf(bracketed); if (bracketedAt >= 0) { return ( <> {signature.slice(0, bracketedAt)} {bracketed} {signature.slice(bracketedAt + bracketed.length)} ); } const plainAt = signature.indexOf(boldArgName); if (plainAt < 0) return signature; return ( <> {signature.slice(0, plainAt)} {boldArgName} {signature.slice(plainAt + boldArgName.length)} ); } /** * ⭐⭐ THE DROPDOWN AND THE SCREENTIP, IN THE HOUSE OVERLAY VOCABULARY. `cg-pop` / * `cg-type-list` / `cg-type-row` are declared UNSCOPED at top level in `index.css`; * `FormulaBar.tsx`'s OWN prior dropdown used exactly this trio, which is the reference pattern * this reuses rather than forks (C7). * * ⛔ NOT `AnchoredOverlay`. That component focus-traps and steals initial focus by default, which * is fatal for a live-typing autocomplete: the caret has to stay in the input on every keystroke. * This positions itself with plain CSS instead (`.formula-assist-tip` / `.formula-assist-list` are * `position: absolute` inside the caller's own `position: relative` wrapper), the same way * `FormulaBar.tsx`'s prior `.sheet-fx-pop` positioned itself under `.cg-pop-wrap`. */ export default function FormulaAssist({ text, caret, caretOffset, activeIndex, dismissed, onAccept, onHoverIndex, }: FormulaAssistProps) { const suggestions = useMemo(() => suggest(text, caret), [text, caret]); const active = useMemo(() => activeArg(text, caret), [text, caret]); const spec = active ? findFunction(active.functionName) : null; const open = !dismissed && suggestions.length > 0; const assistRef = useRef(null); const listRef = useRef(null); const tipRef = useRef(null); useLayoutEffect(() => { if (!caretOffset) return; const place = () => { const parent = assistRef.current?.parentElement; if (!parent) return; const origin = parent.getBoundingClientRect(); const lineHeight = Number.parseFloat(getComputedStyle(parent).lineHeight); const below = origin.top + caretOffset.y + 4; const above = origin.top + caretOffset.y - lineHeight - 4; const roomBelow = Math.max(0, window.innerHeight - 4 - below); const roomAbove = Math.max(0, above - 4); const measure = (panel: HTMLDivElement | null) => { if (!panel) return null; // Measure the natural panel afresh before clipping; reusing yesterday's clipped // height would leave the list permanently short after a viewport resize. panel.style.maxHeight = ""; return panel.getBoundingClientRect(); }; const listRect = measure(listRef.current); const tipRect = measure(tipRef.current); const listAbove = !!listRect && roomBelow < listRect.height && roomAbove > roomBelow; let tipAbove = open ? !listAbove : !!tipRect && roomBelow < tipRect.height && roomAbove > roomBelow; // Near a viewport edge the opposite side may have no room for the tip. Reserve // its height on the list's side instead; independently flipping both makes them overlap. const shareSide = !!listRect && !!tipRect && (tipAbove ? roomAbove : roomBelow) < tipRect.height; if (shareSide) tipAbove = listAbove; const tipHeight = Math.min(tipRect?.height ?? 0, tipAbove ? roomAbove : roomBelow); const listHeight = Math.min(listRect?.height ?? 0, Math.max(0, (listAbove ? roomAbove : roomBelow) - (shareSide ? tipHeight + 4 : 0))); const position = (panel: HTMLDivElement, rect: DOMRect, height: number, desiredTop: number) => { const left = Math.max(4, Math.min(origin.left + caretOffset.x, window.innerWidth - rect.width - 4)); const top = Math.max(4, Math.min(desiredTop, window.innerHeight - height - 4)); panel.style.left = `${left - origin.left}px`; panel.style.top = `${top - origin.top}px`; panel.style.maxHeight = `${height}px`; }; if (listRef.current && listRect) { position(listRef.current, listRect, listHeight, listAbove ? above - listHeight : below); } if (tipRef.current && tipRect) { const gap = shareSide ? listHeight + 4 : 0; position(tipRef.current, tipRect, tipHeight, tipAbove ? above - gap - tipHeight : below + gap); } }; place(); window.addEventListener("resize", place); window.addEventListener("scroll", place, true); return () => { window.removeEventListener("resize", place); window.removeEventListener("scroll", place, true); }; }, [caretOffset, open, spec, text]); if (!open && !spec) return null; const index = open ? Math.min(Math.max(activeIndex, 0), suggestions.length - 1) : 0; return (
{/* ST-12/ST-15: below and left aligned normally; if the dropdown ALSO owns the space below, the tooltip moves above instead so the two never overlap. */} {spec && (
{renderSignature(spec.signature, active?.boldArgName ?? null)}
)} {open && (
{suggestions.map((item, i) => ( ))}
)}
); } export interface ColoredFormulaTextProps { text: string; theme?: "light" | "dark"; } /** * ⭐⭐ CR-1/CR-3/CR-5: every distinct reference OCCURRENCE gets the colour `refsIn` assigned it, * applied to its own substring. `refsIn` already walks `text` left to right and returns one entry * PER OCCURRENCE (a repeated `A1` yields two entries sharing one colour, not one entry), so the * offsets are reconstructed by consuming the string in that same order rather than re-parsing it. * * Used from BOTH mount sites: `FormulaBar.tsx`'s single-line input and `SheetGrid.tsx`'s floating * cell editor, each as the coloured BACKDROP under a transparent-text input (a plain `` * cannot render multiple text colours itself). */ export function ColoredFormulaText({ text, theme = "light" }: ColoredFormulaTextProps) { const refs = useMemo(() => refsIn(text), [text]); if (refs.length === 0) return <>{text}; const nodes: ReactNode[] = []; let cursor = 0; refs.forEach((ref, i) => { const at = text.indexOf(ref.text, cursor); if (at < 0) return; if (at > cursor) nodes.push(text.slice(cursor, at)); nodes.push( {ref.text} , ); cursor = at + ref.text.length; }); if (cursor < text.length) nodes.push(text.slice(cursor)); return <>{nodes}; }