File size: 12,676 Bytes
e88a3a3
 
 
 
 
 
 
 
bdac669
e88a3a3
 
 
bdac669
e88a3a3
 
 
 
 
 
 
 
 
bdac669
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdac669
 
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdac669
e88a3a3
 
 
 
 
bdac669
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e88a3a3
 
 
 
 
 
bdac669
e88a3a3
 
 
 
bdac669
e88a3a3
bdac669
e88a3a3
 
 
 
 
 
 
 
 
bdac669
 
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// 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)}
        <strong className="formula-assist-tip-bold">{bracketed}</strong>
        {signature.slice(bracketedAt + bracketed.length)}
      </>
    );
  }
  const plainAt = signature.indexOf(boldArgName);
  if (plainAt < 0) return signature;
  return (
    <>
      {signature.slice(0, plainAt)}
      <strong className="formula-assist-tip-bold">{boldArgName}</strong>
      {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<HTMLDivElement | null>(null);
  const listRef = useRef<HTMLDivElement | null>(null);
  const tipRef = useRef<HTMLDivElement | null>(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 (
    <div ref={assistRef} className={"formula-assist" + (caretOffset ? " formula-assist--caret" : "")}>
      {/* 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 && (
        <div
          ref={tipRef}
          className={"cg-pop formula-assist-tip" + (open ? " formula-assist-tip--above" : "")}
          style={caretOffset ? { left: caretOffset.x, top: caretOffset.y + 4, bottom: "auto" } : undefined}
          role="status"
          aria-live="polite"
        >
          <span className="formula-assist-tip-sig">
            {renderSignature(spec.signature, active?.boldArgName ?? null)}
          </span>
        </div>
      )}
      {open && (
        <div ref={listRef} className="cg-pop formula-assist-list" role="listbox" aria-label="Functions"
          style={caretOffset ? { left: caretOffset.x, top: caretOffset.y + 4, bottom: "auto" } : undefined}>
          <div className="cg-type-list">
            {suggestions.map((item, i) => (
              <button
                key={item.name}
                type="button"
                role="option"
                aria-selected={i === index}
                className={"cg-type-row" + (i === index ? " is-on" : "")}
                // ⭐ `onMouseDown` with `preventDefault`, not `onClick`: the input's own blur
                // fires first on a click and would close the list before it could land, exactly
                // the reason `FormulaBar.tsx`'s prior dropdown did the same (FA-22: a click
                // accepts, and it must not lose the edit's focus to do it).
                onMouseDown={(event) => { event.preventDefault(); onAccept(item); }}
                onDoubleClick={() => onAccept(item)}
                onMouseEnter={() => onHoverIndex(i)}
              >
                <span className="cg-type-label">{item.name}</span>
                <span className="formula-assist-summary">{item.summary}</span>
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

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 `<input>`
 * 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(
      <span
        key={`${i}-${at}`}
        className="formula-assist-ref"
        style={{ color: colorForSlot(ref.colorIndex, theme) }}
      >
        {ref.text}
      </span>,
    );
    cursor = at + ref.text.length;
  });
  if (cursor < text.length) nodes.push(text.slice(cursor));
  return <>{nodes}</>;
}