runloopable / web /src /sheet /FormulaBar.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
8133df9 verified
Raw History Blame Contribute Delete
22.9 kB
// ---------------------------------------------------------------------------
// sheet/FormulaBar.tsx β€” the bar above the grid (wave 50 Β· W50-T21, contract C2, rulings R5/R17;
// wave 52 Β· W52-T06, contract C3, instructions 5 and 7).
//
// ⭐⭐ WHAT THIS IS: Excel's formula bar. A name box on the left naming ONE cell, the cell's own
// editable text in the middle, and a function autocomplete driven by the SAME local pure engine
// `SheetGrid.tsx`'s own cell editor uses (`formulaAssist.ts` / `functionCatalog.ts`), rendered by
// the shared `FormulaAssist` component, so the behaviour is identical wherever a formula is typed.
//
// β›”β›” W52-T06 REPLACED THE SERVER CATALOGUE (`/query/formula-catalogue`, wave-50 C2) HERE, ON
// PURPOSE, AND IT IS A NAMED TRADE-OFF NOT AN OVERSIGHT. The server catalogue carried 101
// functions with richer metadata; the local one T05 shipped carries 26. Discoverability of the
// other ~75 sheet-scoped functions through THIS autocomplete is lost -- they remain fully typeable
// and evaluable, only unsuggested. The reasons this file took that trade anyway: (1) the ticket's
// own letter says "mount from BOTH FormulaBar.tsx and the SheetGrid.tsx cell editor overlay so the
// behaviour is identical wherever a formula is typed" -- two engines driving two dropdowns from
// two different name lists is not identical, it is two features that happen to look similar; (2)
// FA-19 (Enter must never accept a suggestion) has exactly ONE source of truth,
// `formulaAssist.ts::acceptsSuggestion`, and a second hand-rolled accept-key check beside it is
// exactly the kind of drift that let the old bug ship in the first place; (3) the exact spacing
// `SUM(number1, [number2], ...)` the owner's own instruction 5 names is only GUARANTEED by
// `functionCatalog.ts::buildSignature` -- the server's string happens to match it today for SUM,
// which is not the same as it being pinned to match for every function forever.
// See this ticket's HANDOFF (`LEARNINGS`) for the PENDING row this trade-off opens: whether the
// other ~75 functions belong in `functionCatalog.ts` too, which is a product call for the root.
//
// β›”β›” THE MIRROR IS HALF WIRED, AND SAYING SO IS THE POINT. "Mirrors the SELECTED cell" needs the
// grid's selection, and glide's selection lives inside `SheetGrid.tsx::selected` (line ~247) which
// this ticket may not edit. So the bar takes `addr` as a PROP and the page feeds it from the name
// box today. The handover is two lines in a file W50-T20 owns:
//
// SheetGridProps gains onSelect?: (sel: { addr: string; cell: Cell | null } | null) => void
// fired from an effect on the existing `selected` memo,
// and SheetPage passes onSelect={(s) => setBarAddr(s?.addr ?? barAddr)}.
//
// Nothing in this file changes when that lands: `addr` simply starts arriving from the grid
// instead of from the name box. The name box is NOT a stand-in that will be deleted either - it
// is Excel's own control and it is what makes the bar usable from the keyboard alone.
//
// β›” THE TEXT RULES ARE `sheetState.ts`'s, NEVER THIS FILE'S. `editableText` is what F2 opens with
// and `commitTyped` is the one door that decides literal or formula. Re-deriving either here would
// let the bar show different text than the cell opens with, and let a formula typed in the bar
// become a different cell than the same formula typed in the grid.
//
// β›” R20: A BOUND CELL IS NOT EDITED HERE. Typing over a bound cell is a CONFIRMED conversion and
// the page owns that confirmation, so the bar shows a bound cell read only and names why. A bar
// that silently converted would be a second, unconfirmed door onto the same act.
//
// ⭐⭐ S67-T03 / CONTRACT C1 (R28, QI27, 2026-09-28) β€” THE BAR MIRRORS THE CELL'S DRAFT LIVE AND
// EXPANDS LIKE EXCEL'S. `SheetGrid` reports its in-cell draft through `onDraftChange`, the page
// passes it here as `draft`, and while it is a string the bar shows it character for character
// (read only: one edit has one home, the cell's editor). `null` hands the bar back its own text,
// which after a commit is the stored formula. The chevron at the bar's right end and Ctrl+Shift+U
// toggle the expanded height; both live in THIS file, never in `shortcuts.ts` (lane B's), and the
// chevron stays live on a read-only sheet, because reading a long formula is not an edit.
//
// ⚠ DESIGN CONTRACT: sentence case, quiet buttons, token only colour and type, no emoji, and no
// em dash or en dash in any string that reaches a screen (aria labels included).
// ---------------------------------------------------------------------------
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { KeyboardEvent as ReactKeyboardEvent } from "react";
import { colToIndex, parseRef } from "./a1";
import FormulaAssist, { ColoredFormulaText, tokenStartAt } from "./FormulaAssistPanel";
import { acceptedText, acceptsSuggestion, refsIn, suggest } from "./formulaAssist";
import type { SuggestItem } from "./formulaAssist";
import { boundToCurrency, commitTyped, displayText, editableText, isFormulaText } from "./sheetState";
import type { Cell } from "./types";
import { formatCellText } from "./types";
import "../styles/wave52/sheet-grid.css";
import "../styles/wave61/sheet-grid.css";
/**
* ⚠ THE GRID'S SHAPE, RESTATED, BECAUSE `SheetGrid.tsx`'s `COLS`/`ROWS` ARE MODULE PRIVATE and
* that file is outside this ticket's fence. They are only used to REFUSE an address the grid
* could not show; nothing here paints a cell. Exporting them from `SheetGrid.tsx` is the tidy
* follow up and is named in this ticket's handoff.
*/
const LAST_COL = 26;
const LAST_ROW = 200;
/** A1 the grid could actually show, or "". `parseRef` owns the grammar; this owns the bounds. */
const withinGrid = (text: string): string => {
const ref = parseRef(text);
if (!ref) return "";
const col = colToIndex(ref.col);
if (col < 1 || col > LAST_COL || ref.row < 1 || ref.row > LAST_ROW) return "";
return `${ref.col}${ref.row}`;
};
export interface FormulaBarProps {
/** The ONE cell the bar is showing. See the header: the grid's selection feeds this next. */
addr: string;
/** That cell, or null for an empty one. The page reads it from the open tab. */
cell: Cell | null;
disabled?: boolean;
onAddrChange: (addr: string) => void;
/** The page's one commit door, so a bar edit takes one history step and one save. */
onCommit: (edits: Record<string, Cell | null>) => void;
/**
* C1: the in-cell editor's live draft, or null when no cell editor is open. While it is a
* string the bar shows it instead of its own text and does not take typing.
*/
draft?: string | null;
}
/** C1: the lines the expanded bar opens to at least, and grows to at most, before it scrolls. */
const EXPANDED_MIN_LINES = 6;
const EXPANDED_MAX_LINES = 12;
/** DESIGN.md Β§4 motion: 100-200 ms ease-out for the expand and collapse. */
const EXPAND_MS = 150;
export default function FormulaBar({
addr, cell, disabled = false, onAddrChange, onCommit, draft: cellDraft = null,
}: FormulaBarProps) {
const [draft, setDraft] = useState<string>("");
/** C1: the expanded height is this bar's own state, toggled by the chevron and Ctrl+Shift+U. */
const [expanded, setExpanded] = useState(false);
/** True for the one measure that follows a toggle, so only that change is animated. */
const animateNext = useRef(false);
/** C1: a cell editor is open and its draft is what the bar shows. */
const mirroring = typeof cellDraft === "string";
const shown = mirroring ? cellDraft : draft;
const [addrDraft, setAddrDraft] = useState<string>(addr);
/** FA-16's highlighted row. The caller (this file) owns cycling it; `FormulaAssist` only reads it. */
const [activeIndex, setActiveIndex] = useState(0);
/**
* FA-23's first Escape: true closes the list WITHOUT touching the buffer. `suggest()` is a pure
* function of `draft`/`caret`, so without this flag the very next render would recompute the
* SAME list and the dropdown could never actually close on Escape alone (FA-24: only typing
* another character reopens it, which is exactly the one place this resets to false).
*/
const [dismissed, setDismissed] = useState(false);
const [caret, setCaret] = useState(0);
const inputRef = useRef<HTMLTextAreaElement | null>(null);
const backdropRef = useRef<HTMLDivElement | null>(null);
const bound = cell?.kind === "bound";
const text = boundToCurrency(cell) ? formatCellText(cell, displayText(cell)) : editableText(cell);
// ⭐ THE MIRROR. A new address, or a cell whose text changed under us (a refresh, an undo, a
// paste), replaces the draft. Keyed on the TEXT rather than on the cell object, because
// `withCells` rebuilds the whole workbook on every commit and an object identity dependency
// would wipe the reader's half typed formula on every neighbouring keystroke.
useEffect(() => {
setDraft(text);
setDismissed(false);
}, [addr, text]);
useEffect(() => { setAddrDraft(addr); }, [addr]);
// ⭐⭐ W52-T06 / CONTRACT C3 β€” THE SUGGESTION LIST, DRIVEN BY `formulaAssist.ts` ALONE. Neither
// this file nor `FormulaAssist.tsx` re-derives what matches or how it is ordered (FA-5/FA-8);
// this is read only to decide what Tab and the arrow keys do, `FormulaAssist` renders the same
// call's result.
const suggestions = useMemo(
() => (!mirroring && isFormulaText(draft) ? suggest(draft, caret) : []),
[draft, caret, mirroring],
);
const dropdownOpen = !dismissed && suggestions.length > 0;
/** CR-1: at least one live reference, which is what turns the input's own text transparent so
* the coloured backdrop underneath is what is actually seen (a plain input cannot itself paint
* more than one colour). */
const refCount = useMemo(
() => (isFormulaText(shown) ? refsIn(shown).length : 0),
[shown],
);
const syncBackdropScroll = useCallback(() => {
const input = inputRef.current;
const backdrop = backdropRef.current;
if (input && backdrop) {
backdrop.scrollTop = input.scrollTop;
backdrop.scrollLeft = input.scrollLeft;
}
}, []);
// W61-T10 / R12: grow with the wrapped draft, up to five lines. Beyond that, both the
// real text and its coloured mirror scroll together instead of pushing the grid away.
// S67-T03 / C1: expanded, the bar opens to at least six lines and grows to twelve; the toggle
// animates from the old height to the new one (Web Animations, because the auto-height measure
// below would defeat a CSS height transition), and not at all under reduced motion.
useLayoutEffect(() => {
const input = inputRef.current;
if (!input) return;
const measure = () => {
const metrics = getComputedStyle(input);
const lineHeight = Number.parseFloat(metrics.lineHeight);
const padding = Number.parseFloat(metrics.paddingTop) + Number.parseFloat(metrics.paddingBottom);
const border = Number.parseFloat(metrics.borderTopWidth) + Number.parseFloat(metrics.borderBottomWidth);
const before = input.getBoundingClientRect().height;
input.style.height = "auto";
const natural = input.scrollHeight + border;
const lines = (n: number) => lineHeight * n + padding + border;
const next = expanded
? Math.max(lines(EXPANDED_MIN_LINES), Math.min(natural, lines(EXPANDED_MAX_LINES)))
: Math.min(natural, lineHeight * 5 + padding + border);
input.style.height = `${next}px`;
if (backdropRef.current) backdropRef.current.style.height = input.style.height;
if (animateNext.current) {
animateNext.current = false;
const still = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
if (!still && Math.abs(before - next) > 1 && typeof input.animate === "function") {
const frames = [{ height: `${before}px` }, { height: `${next}px` }];
const timing = { duration: EXPAND_MS, easing: "ease-out" };
input.animate(frames, timing);
backdropRef.current?.animate(frames, timing);
}
}
syncBackdropScroll();
};
measure();
const observer = new ResizeObserver(measure);
if (input.parentElement) observer.observe(input.parentElement);
return () => observer.disconnect();
}, [expanded, shown, syncBackdropScroll]);
/** C1: the chevron and Ctrl+Shift+U share this one toggle. */
const toggleExpanded = useCallback(() => {
animateNext.current = true;
setExpanded((open) => !open);
}, []);
// β›” C1: Ctrl+Shift+U IS THIS FILE'S, NEVER `shortcuts.ts`'s (whose Ctrl+Shift branch has no
// "u", so plain Ctrl+U stays underline). Capture phase, so the grid and the cell editor, which
// hold focus while a formula is typed, never see the chord.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (!(e.ctrlKey || e.metaKey) || !e.shiftKey || e.altKey) return;
if (e.key.toLowerCase() !== "u") return;
e.preventDefault();
e.stopPropagation();
toggleExpanded();
};
window.addEventListener("keydown", onKey, true);
return () => window.removeEventListener("keydown", onKey, true);
}, [toggleExpanded]);
const sync = useCallback((el: HTMLTextAreaElement) => {
setCaret(el.selectionStart ?? el.value.length);
}, []);
/** FA-18/FA-20/FA-22: Tab or a double click. NEVER Enter (FA-19) -- see `onKeyDown` below. */
const accept = useCallback((item: SuggestItem) => {
const start = tokenStartAt(draft, caret);
const inserted = acceptedText(item);
const next = `${draft.slice(0, start)}${inserted}${draft.slice(caret)}`;
const at = start + inserted.length;
setDraft(next);
setDismissed(false);
setActiveIndex(0);
setCaret(at);
// The caret has to land INSIDE the parentheses, which React does not do for us: setting
// `value` puts it at the end. One frame later the new value is on the element.
window.requestAnimationFrame(() => {
const el = inputRef.current;
if (el) { el.focus(); el.setSelectionRange(at, at); }
});
}, [caret, draft]);
const commit = useCallback(() => {
if (bound || !addr) return;
onCommit({ [addr]: commitTyped(cell, draft) });
setDismissed(false);
}, [addr, bound, cell, draft, onCommit]);
const onKeyDown = useCallback((e: ReactKeyboardEvent<HTMLTextAreaElement>) => {
if (dropdownOpen) {
if (e.key === "ArrowDown") {
e.preventDefault();
setActiveIndex((i) => (i + 1) % suggestions.length);
return;
}
if (e.key === "ArrowUp") {
e.preventDefault();
setActiveIndex((i) => (i - 1 + suggestions.length) % suggestions.length);
return;
}
// β›”β›” FA-19, THE TICKET'S NAMESAKE BUG. `acceptsSuggestion` is the ONE place a key is asked
// whether it accepts (Tab, and only Tab -- FA-18); Enter is deliberately never asked here,
// which is what lets it fall through to the plain commit below instead.
if (acceptsSuggestion(e.key)) {
e.preventDefault();
accept(suggestions[Math.min(activeIndex, suggestions.length - 1)]);
return;
}
// FA-23 #1: closes the list only. The buffer is untouched; a second Escape (below) reverts.
if (e.key === "Escape") {
e.preventDefault();
setDismissed(true);
return;
}
}
if (e.key === "Enter") {
e.preventDefault();
commit();
return;
}
if (e.key === "Escape") {
e.preventDefault();
setDraft(text);
setDismissed(false);
}
}, [accept, activeIndex, commit, dropdownOpen, suggestions, text]);
/**
* ⭐ W51-T08 β€” CANCEL IS THE ESCAPE KEY, CONFIRM IS THE ENTER KEY, AND NEITHER IS NEW BEHAVIOUR.
* The two controls drive the handlers `onKeyDown` already runs, so the bar keeps exactly one
* notion of "revert" and one notion of "commit". A second code path here is how a button and a
* keystroke end up disagreeing about what a half typed formula meant.
*/
const cancel = useCallback(() => {
setDraft(text);
setDismissed(false);
}, [text]);
/** True while there is nothing to confirm or revert, so both controls read as unavailable. A
* mirrored draft belongs to the cell's editor, whose own Enter and Escape commit or revert it. */
const idle = disabled || !addr || bound || mirroring;
const goToAddr = useCallback(() => {
const next = withinGrid(addrDraft);
if (!next) {
setAddrDraft(addr);
return;
}
onAddrChange(next);
}, [addr, addrDraft, onAddrChange]);
return (
<div className="sheet-fx" role="group" aria-label="Formula bar"
// S67-T03: expanded, the name box and the controls stay on the first line, as in Excel.
style={expanded ? { alignItems: "flex-start" } : undefined}>
<label className="sheet-fx-addr">
<span className="sheet-fx-addr-label">Cell</span>
<input
type="text"
value={addrDraft}
aria-label="Cell address"
onChange={(e) => setAddrDraft(e.currentTarget.value)}
onBlur={goToAddr}
onKeyDown={(e) => {
if (e.key === "Enter") { e.preventDefault(); goToAddr(); }
if (e.key === "Escape") { e.preventDefault(); setAddrDraft(addr); }
}}
/>
</label>
{/* ⭐⭐ W51-T08 β€” CANCEL AND CONFIRM, IN EXCEL'S OWN PLACE: after the name box and before the
`fx` mark. `onMouseDown` preventing default is the same reason the suggestion rows do it,
the input's blur fires FIRST and would move the caret out from under the click.
⚠ CANCEL IS NOT DESTRUCTIVE INK. It reverts an edit in progress; it deletes nothing, so
it carries the same quiet muted ink as every other glyph in this row (DESIGN.md Β§3). */}
<button
type="button"
className="sheet-fx-btn"
aria-label="Cancel this edit"
title="Cancel this edit"
disabled={idle}
onMouseDown={(e) => e.preventDefault()}
onClick={cancel}
>
<svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden>
<path
d="M4.6 4.6l6.8 6.8M11.4 4.6l-6.8 6.8"
stroke="currentColor"
strokeWidth="1.3"
strokeLinecap="round"
/>
</svg>
</button>
<button
type="button"
className="sheet-fx-btn sheet-fx-btn--ok"
aria-label="Confirm this edit"
title="Confirm this edit"
disabled={idle}
onMouseDown={(e) => e.preventDefault()}
onClick={commit}
>
<svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden>
<path
d="M3.4 8.4l3.2 3.2L12.6 5"
stroke="currentColor"
strokeWidth="1.3"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</button>
<span className="sheet-fx-mark" aria-hidden>
<svg width="13" height="13" viewBox="0 0 16 16" fill="none">
<path
d="M4 13V5.2C4 3.98 4.98 3 6.2 3H8M2.8 7.6h5.6M9.6 7.6l3.6 5.4M13.2 7.6l-3.6 5.4"
stroke="currentColor"
strokeWidth="1.3"
strokeLinecap="round"
/>
</svg>
</span>
<div className="cg-pop-wrap sheet-fx-field formula-assist-input-wrap">
{/* CR-1/CR-5: the coloured backdrop under a transparent-text input. Only mounted once a
reference actually exists, so a formula with none yet paints exactly as it always did. */}
{refCount > 0 && (
<div ref={backdropRef} className="formula-assist-backdrop-bar" aria-hidden="true">
<ColoredFormulaText text={shown} theme="light" />
</div>
)}
{/* W61-T10: wrapping needs a textarea; onKeyDown already prevents Enter before commit. */}
<textarea
ref={inputRef}
rows={1}
className={"sheet-fx-input" + (refCount > 0 ? " formula-assist-input-bar--colored" : "")}
value={shown}
readOnly={bound || mirroring}
disabled={disabled || !addr}
aria-label={bound ? "This cell reads from a database" : "Formula or value"}
placeholder={bound ? "" : "Type a value, or = to start a formula"}
role="combobox"
aria-expanded={dropdownOpen}
aria-autocomplete="list"
onChange={(e) => {
setDraft(e.currentTarget.value);
sync(e.currentTarget);
setActiveIndex(0);
// FA-24: typing reopens a dismissed list.
setDismissed(false);
}}
onKeyUp={(e) => sync(e.currentTarget)}
onClick={(e) => sync(e.currentTarget)}
onBlur={() => setDismissed(true)}
onKeyDown={onKeyDown}
onScroll={syncBackdropScroll}
/>
{/* ⭐⭐ CONTRACT C3 / CROSS-FEATURE WIRING #1 β€” THE SHARED ASSIST, MOUNTED HERE. Same
component, same `formulaAssist.ts` engine `SheetGrid.tsx`'s own cell editor drives, so
the dropdown and the ScreenTip read identically wherever a formula is typed. */}
<FormulaAssist
text={draft}
caret={caret}
activeIndex={activeIndex}
dismissed={dismissed || mirroring}
onAccept={accept}
onHoverIndex={setActiveIndex}
/>
</div>
{/* ⭐⭐ S67-T03 / C1 β€” EXCEL'S EXPAND CHEVRON, AT THE BAR'S RIGHT END. Never disabled: a
read-only sheet still expands, because reading a long formula is not an edit. */}
<button
type="button"
className="sheet-fx-btn sheet-fx-expand"
aria-label={expanded ? "Collapse formula bar" : "Expand formula bar"}
title={expanded ? "Collapse formula bar (Ctrl+Shift+U)" : "Expand formula bar (Ctrl+Shift+U)"}
aria-expanded={expanded}
onMouseDown={(e) => e.preventDefault()}
onClick={toggleExpanded}
>
<svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden
style={{ transform: expanded ? "rotate(180deg)" : undefined,
transition: `transform ${EXPAND_MS}ms ease-out` }}>
<path
d="M4 6.2l4 4 4-4"
stroke="currentColor"
strokeWidth="1.3"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</button>
{/* β›” R20 SAID IN THE BAR, NOT ENFORCED TWICE. The input is already read only; this states
WHY, because a field that refuses a keystroke without a reason reads as broken. */}
{bound && (
<span className="sheet-fx-note">
This cell reads from a database. Open it in the grid to change what it points at.
</span>
)}
</div>
);
}