File size: 22,944 Bytes
ce4ad7b
e88a3a3
 
ce4ad7b
 
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a93637f
 
 
 
 
 
 
 
ce4ad7b
 
 
 
bdac669
ce4ad7b
 
e88a3a3
 
 
b2aa446
ce4ad7b
b2aa446
e88a3a3
bdac669
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a93637f
 
 
 
 
ce4ad7b
 
a93637f
 
 
 
 
 
ce4ad7b
a93637f
ce4ad7b
 
a93637f
 
 
 
 
 
 
ce4ad7b
e88a3a3
 
 
 
 
 
 
 
 
ce4ad7b
bdac669
 
ce4ad7b
 
b2aa446
ce4ad7b
 
 
 
 
 
 
e88a3a3
ce4ad7b
 
 
 
e88a3a3
 
 
 
 
a93637f
 
ce4ad7b
e88a3a3
 
 
 
 
a93637f
 
e88a3a3
ce4ad7b
bdac669
 
 
 
 
 
 
 
 
 
 
a93637f
 
 
bdac669
 
 
 
 
 
 
 
a93637f
bdac669
a93637f
 
 
 
 
 
bdac669
a93637f
 
 
 
 
 
 
 
 
 
bdac669
 
 
 
 
 
a93637f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdac669
 
ce4ad7b
 
 
e88a3a3
 
 
 
 
 
ce4ad7b
e88a3a3
 
ce4ad7b
 
 
 
 
 
 
e88a3a3
ce4ad7b
 
 
 
e88a3a3
ce4ad7b
 
bdac669
e88a3a3
ce4ad7b
 
e88a3a3
ce4ad7b
 
 
 
e88a3a3
ce4ad7b
 
e88a3a3
 
 
 
ce4ad7b
e88a3a3
ce4ad7b
 
e88a3a3
ce4ad7b
 
e88a3a3
ce4ad7b
 
 
 
 
 
 
 
 
 
 
e88a3a3
ce4ad7b
e88a3a3
ce4ad7b
39a9177
 
 
 
 
 
 
 
e88a3a3
39a9177
 
a93637f
 
 
39a9177
ce4ad7b
 
 
 
 
 
 
 
 
 
a93637f
 
 
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce4ad7b
 
 
 
 
 
 
 
 
 
 
e88a3a3
 
 
 
bdac669
a93637f
e88a3a3
 
bdac669
 
ce4ad7b
bdac669
e88a3a3
a93637f
 
ce4ad7b
 
 
 
e88a3a3
ce4ad7b
 
 
 
e88a3a3
 
 
ce4ad7b
 
 
e88a3a3
ce4ad7b
bdac669
ce4ad7b
 
e88a3a3
 
 
 
 
 
 
a93637f
e88a3a3
 
 
ce4ad7b
 
a93637f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce4ad7b
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
// ---------------------------------------------------------------------------
// 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>
  );
}