runloopable / web /src /sheet /formulaAssist.ts
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
82cdb59 verified
Raw History Blame Contribute Delete
13.9 kB
// The formula assist module, wave 52 (W52-T05, contract C3, instructions 5 and 7).
//
// PURE functions only. No React, no DOM. That is what makes this module gateable without a
// browser (`verify_formula_engine.py`'s new leg compiles it and drives it under plain `node`), and
// it is what leaves the KEY HANDLING decisions -- what Tab does, what Enter does, when a click
// commits a point-mode proposal -- to the UI layer T06 builds next. This module answers "what is
// the list right now" and "what does this text mean right now"; it never mutates anything and it
// never remembers anything between calls.
//
// Rules implemented here are from `AutoWiki/waves/wave52/proto/excel-behaviour-spec.md`, Part
// A: FA-1..FA-26 (the suggestion dropdown), ST-1..ST-16 (the ScreenTip), CR-1..CR-10 (coloured
// references). Point mode (PM-1..PM-18) is NOT built here -- this ticket ships no UI, and PM's
// rules describe grid interaction (arrow keys, click-drag, scrolling to a proposed cell) that has
// no meaning without one. T06 owns PM.
import { FUNCTIONS, findFunction, type FunctionSpec } from "./functionCatalog";
import { parseRef, type CellRef } from "./a1";
// ── FA-19/FA-18/FA-22: which keys accept a suggestion. Enter is deliberately NOT in this list. ──
//
// β›”β›” THE CRITICAL NEGATIVE RULE (FA-19). Every implementer's instinct from VS Code, IntelliJ and
// every browser autocomplete is that Enter accepts a highlighted item. In Excel it does not: Enter
// commits the LITERAL text typed, and Tab is the only key that accepts (FA-18). Double-click also
// accepts (FA-22), but a mouse click is not a "key" -- the UI layer calls the accept path directly
// on double-click, it never asks this list. `suggest()` itself never decides what a key does; it
// only returns the ranked list. This constant is what the CALLER consults, and it is what the
// gate's negative control mutates to prove a caller that wired Enter here would be caught.
export const ACCEPT_KEYS: readonly string[] = ["Tab"];
/** True only for a key that accepts a highlighted suggestion. FA-18/FA-19/FA-22. */
export function acceptsSuggestion(key: string): boolean {
return ACCEPT_KEYS.includes(key);
}
// ── Part A section 1: the suggestion dropdown ───────────────────────────────────────────────────
export type SuggestKind = "function";
export interface SuggestItem {
kind: SuggestKind;
name: string;
signature: string;
summary: string;
}
/** The identifier run a token match is built from. Letters, digits, underscore, dot. */
const IDENT_TAIL = /[A-Za-z_][A-Za-z0-9_.]*$/;
/**
* FA-1..FA-10: the ranked suggestion list for the token under `caret` in `text`.
*
* Returns `[]` (closes the dropdown, per FA-2/FA-24/FA-25) whenever:
* - `text` does not start with `=` (not a formula at all),
* - there is no identifier character run immediately before `caret` (bare `=`, right after `(`,
* `,`, an operator, or inside a string -- the caller passes the caret position, this function
* does not know about quoting, so a caller inside a string literal should not call this at all;
* T06 owns that decision),
* - the token matches nothing in the catalog (prefix, case insensitive -- FA-5/FA-6).
*
* Ordering (FA-8): exact case-insensitive match on the whole token first, then every remaining
* match A-Z ascending, case insensitive. No fuzzy match, no frequency ranking (FA-5, FA-8). The
* first item in a non-empty result is always the one to preselect (FA-10) -- there is no separate
* "selected index" concept here because there is nothing to select from an empty list.
*/
export function suggest(text: string, caret: number): SuggestItem[] {
const src = String(text || "");
if (!src.startsWith("=")) return [];
const upto = src.slice(0, Math.max(0, Math.min(caret, src.length)));
const m = IDENT_TAIL.exec(upto);
if (!m || m[0].length < 1) return [];
const token = m[0].toLowerCase();
const matches = FUNCTIONS.filter((f) => f.name.toLowerCase().startsWith(token));
const exact = matches.filter((f) => f.name.toLowerCase() === token);
const exactNames = new Set(exact.map((f) => f.name));
const rest = matches
.filter((f) => !exactNames.has(f.name))
.sort((a, b) => a.name.localeCompare(b.name, "en", { sensitivity: "base" }));
return [...exact, ...rest].map((f) => toSuggestItem(f));
}
function toSuggestItem(f: FunctionSpec): SuggestItem {
return { kind: "function", name: f.name, signature: f.signature, summary: f.summary };
}
/**
* FA-20/FA-21: what accepting a suggestion inserts. A function gets its name (already upper
* case, FA-7) and the opening parenthesis, caret placed after it. This is pure text -- the caller
* still owns splicing it into the buffer and moving the real caret.
*/
export function acceptedText(item: SuggestItem): string {
return `${item.name}(`;
}
// ── Part A section 2: the ScreenTip (signature tooltip) ─────────────────────────────────────────
export interface ActiveArg {
functionName: string;
/** 0-based count of top-level commas before `caret`, inside that function's own parens. ST-5. */
argIndex: number;
/** The argument name to render bold, or null when there is nothing to bold (ST-6). */
boldArgName: string | null;
}
/**
* ST-1..ST-8: which function's signature to show, and which argument is bold, for the caret
* position in `text`. Returns `null` when the caret is not inside any open call's parentheses
* (ST-15 -- that is the caller's cue to hide the tooltip).
*
* ST-5, the exact rule: count TOP-LEVEL commas between the innermost enclosing function's own `(`
* and the caret. A comma inside a nested call's parens, inside a quoted string, or inside a
* bracketed `[...]` table specifier does not count -- each of those is tracked separately so a
* nested call's commas are attributed to ITS OWN frame, never to the frame around it.
*
* ST-6: once the caret passes the last named argument, a signature ending in `...` keeps its
* repeating argument bold; one that does not keeps NO argument bold (the tooltip itself stays up,
* per ST-6 -- this function still returns a result, just with `boldArgName: null`).
*/
export function activeArg(text: string, caret: number): ActiveArg | null {
const src = String(text || "");
if (!src.startsWith("=")) return null;
const end = Math.max(0, Math.min(caret, src.length));
interface Frame {
fnName: string;
commaCount: number;
}
const stack: Frame[] = [];
let quote: string | null = null;
let bracketDepth = 0;
let i = 0;
while (i < end) {
const c = src[i];
if (quote) {
if (c === quote) quote = null;
i += 1;
continue;
}
if (c === '"' || c === "'") {
quote = c;
i += 1;
continue;
}
if (c === "[") {
bracketDepth += 1;
i += 1;
continue;
}
if (c === "]") {
bracketDepth = Math.max(0, bracketDepth - 1);
i += 1;
continue;
}
if (c === "(") {
const preceding = IDENT_TAIL.exec(src.slice(0, i));
stack.push({ fnName: preceding ? preceding[0].toUpperCase() : "", commaCount: 0 });
i += 1;
continue;
}
if (c === ")") {
stack.pop();
i += 1;
continue;
}
if (c === "," && bracketDepth === 0 && stack.length > 0) {
stack[stack.length - 1].commaCount += 1;
i += 1;
continue;
}
i += 1;
}
if (stack.length === 0) return null;
const top = stack[stack.length - 1];
const spec = findFunction(top.fnName);
const boldArgName = spec ? boldArgumentName(spec, top.commaCount) : null;
return { functionName: top.fnName, argIndex: top.commaCount, boldArgName };
}
/** ST-6's capping rule, isolated so it is one small pure function instead of inline branching. */
function boldArgumentName(spec: FunctionSpec, argIndex: number): string | null {
const names = spec.argNames;
if (names.length === 0) return null;
if (argIndex < names.length) return names[argIndex];
const repeats = spec.signature.trimEnd().endsWith("...)");
return repeats ? names[names.length - 1] : null;
}
// ── Part A section 4: coloured references ───────────────────────────────────────────────────────
export interface CellReference {
/** The reference exactly as it appears in the formula text, e.g. "A1" or "B2:B4". */
text: string;
isRange: boolean;
start: CellRef;
end: CellRef;
/** 0-5, a slot into the fixed six colour rotation in refColors.ts (CR-4). */
colorIndex: number;
/** W57-T01: a whole column or row. Endpoints carry only its axis position; a painter
* must bound the other axis against the sheet it is painting on. */
band?: "column" | "row";
}
/** One reference candidate, matched but not yet range-joined. */
const REF_TOKEN =
"(?:(?:'([^']{1,64})'|([A-Za-z_][A-Za-z0-9_]{0,63}))!)?(\\$?)([A-Za-z]{1,3})(\\$?)([1-9][0-9]{0,6})";
// W57-T01: only identical axes form a band; matchBandAt checks equality after matching.
// The trailing boundary prevents A:A1 or 1:10 from being accepted as a shorter band.
const BAND_TOKEN =
"(?:(?:'([^']{1,64})'|([A-Za-z_][A-Za-z0-9_]{0,63}))!)?(\\$?)"
+ "([A-Za-z]{1,3}|[1-9][0-9]{0,6}):(\\$?)([A-Za-z]{1,3}|[1-9][0-9]{0,6})"
+ "(?![A-Za-z0-9_$!])";
/**
* CR-1..CR-5, CR-9: every distinct cell or range reference in `text`, in order of FIRST
* appearance, each carrying a colour slot from the fixed six colour rotation (CR-4) -- the same
* slot for every later occurrence of an identical reference (CR-3), cycling after the sixth.
*
* A range (`B2:B4`) is ONE reference distinct from either endpoint alone (CR-3). Quoted text is
* never scanned (`="A1 is nice"` yields no references) and a token immediately followed by `(` is
* a function name, not a reference (the same collision `a1.ts::rewriteRefs` guards, e.g. `LOG10(`).
*
* β›” THIS DOES NOT REUSE `a1.ts::rewriteRefs`'s scanner because that scanner's job is different:
* it REWRITES text byte for byte and treats `B4:B8` as two independent references either side of a
* literal `:`. This function instead needs to RECOGNISE a range as one unit for colouring (CR-3),
* so it does its own scan -- but it reuses `a1.ts::parseRef` to turn a matched substring into a
* `CellRef` rather than re-deriving the `$`/sheet-name grammar a second time.
*/
export function refsIn(text: string): CellReference[] {
const src = String(text || "");
const scan = new RegExp(REF_TOKEN, "gy");
const bandScan = new RegExp(BAND_TOKEN, "gy");
const out: CellReference[] = [];
const slotByKey = new Map<string, number>();
let nextSlot = 0;
let quote: string | null = null;
let i = 0;
const matchAt = (pos: number): { token: string; ref: CellRef } | null => {
scan.lastIndex = pos;
const m = scan.exec(src);
if (!m || m.index !== pos) return null;
const after = src.slice(pos + m[0].length);
if (/^\s*\(/.test(after)) return null; // a function name, e.g. LOG10(
const ref = parseRef(m[0]);
if (!ref) return null;
return { token: m[0], ref };
};
const matchBandAt = (pos: number): {
token: string; ref: CellRef; end: CellRef; band: "column" | "row";
} | null => {
bandScan.lastIndex = pos;
const m = bandScan.exec(src);
if (!m || m.index !== pos) return null;
if (m[4].toUpperCase() !== m[6].toUpperCase()) return null;
const after = src.slice(pos + m[0].length);
if (/^\s*\(/.test(after)) return null;
const isColumn = /^[A-Za-z]/.test(m[4]);
// parseRef stays cell-only: widening it would also change fill and structural rewrites.
const ref: CellRef = {
sheet: m[1] || m[2] || "",
colAbs: isColumn && m[3] === "$",
col: isColumn ? m[4].toUpperCase() : "A",
rowAbs: !isColumn && m[3] === "$",
row: isColumn ? 1 : Number(m[4]),
};
return {
token: m[0],
ref,
end: {
...ref,
colAbs: isColumn && m[5] === "$",
rowAbs: !isColumn && m[5] === "$",
},
band: isColumn ? "column" : "row",
};
};
while (i < src.length) {
const c = src[i];
if (quote) {
if (c === quote) quote = null;
i += 1;
continue;
}
if (c === '"') {
quote = c;
i += 1;
continue;
}
if (c === "'") {
const close = src.indexOf("'", i + 1);
const isSheetName = close > i && src[close + 1] === "!";
if (!isSheetName) {
quote = c;
i += 1;
continue;
}
}
const prev = i ? src[i - 1] : "";
const boundary = !/[A-Za-z0-9_$]/.test(prev);
if (boundary && /[A-Za-z0-9$']/.test(c)) {
const band = matchBandAt(i);
const first = matchAt(i) ?? band;
if (first) {
let fullText = first.token;
let end = band?.end ?? first.ref;
let cursor = i + first.token.length;
if (!band && src[cursor] === ":") {
const second = matchAt(cursor + 1);
if (second) {
fullText = `${first.token}:${second.token}`;
end = second.ref;
cursor = cursor + 1 + second.token.length;
}
}
const key = fullText.toUpperCase();
let slot = slotByKey.get(key);
if (slot === undefined) {
slot = nextSlot % 6;
nextSlot += 1;
slotByKey.set(key, slot);
}
out.push({
text: fullText,
isRange: fullText.includes(":"),
start: first.ref,
end,
colorIndex: slot,
...(band ? { band: band.band } : {}),
});
i = cursor;
continue;
}
}
i += 1;
}
return out;
}