// sheet/SheetGrid.tsx — the free-form workbook grid (wave 49, W49-T05, rulings R3, R11, R18, R19; // wave 50, W50-T18, amendment A2). // // ⭐ R3: FREE FORM, NOT PEGGED TO A COLUMN AXIS. The columns here are spreadsheet columns (A, B, // C…), not fields of a database, so nothing about a table's schema reaches this component. A cell // knows its own address and nothing about its neighbours. // // ⛔ THIS MOUNTS ITS OWN `DataEditor` RATHER THAN REUSING `CustomerGrid`. That file is a different // product surface with its own store, its own field contract and ~10,000 lines of behaviour; lane A // may touch it for exactly ONE line (W49-T07's `export` of `LinkGridModal`). The glide-data-grid // mounting PATTERN is copied — theme object, `getCellContent`, `customRenderers` — and nothing else. // // ⚠ `getCellContent` IS THE ONLY THING GLIDE WATCHES, so its dependency array must be exhaustive. // The same note is written above `useGetCellContent` in `customer-grid/`: a stale closure here does // not throw, it paints yesterday's values. // // ⚠ DESIGN CONTRACT: token-only colour and type, sentence case, no emoji, inline SVG icons, motion // 100-200 ms ease-out on opacity and transform only, and no em dash or en dash in any string that // reaches a screen. // // ═════════════════════════════════════════════════════════════════════════════════════════════ // ⛔⛔ W50-T18 — WHY THIS GRID OPENED AT COLUMN H, AND WHAT FIXED IT. // // Nothing in this file ever scrolled the grid, which is exactly why the cause was hard to see: it // was never a scroll at all, it was a SIZE. // // 1. `` was mounted with NO `width` prop. // 2. glide answers that with its own ideal size, not with the box it was given: // `data-editor.js` renders ``, and // `idealWidth` is `mangledCols.reduce((acc, x) => x.width + acc, 0) + scrollbarWidth` — for // 26 columns at 120 px plus the row marker that is about 3,170 px, as a HARD PIXEL WIDTH. // 3. `styles/wave49/sheet.css`'s `.sheet-body` is `display:flex; justify-content:center; // overflow:auto`. A flex container that CENTRES an item wider than itself puts half the // overflow before its own scroll origin, where `scrollLeft: 0` starts and no scrollbar can // reach. Half of (3,170 minus a roughly 1,500 px viewport) is about 835 px, which is seven // columns of 120 px: the grid opens at about H and column A cannot be scrolled back to. // // ⭐ `width="100%"` IS THE FIX AND IT BELONGS HERE, not in the stylesheet: it makes glide's own // wrapper exactly as wide as the box it was handed, so there is no overflow left for // `justify-content: center` to push out of reach, and glide's internal scroller (which starts at // A1) becomes the horizontal scroller again. // // ═════════════════════════════════════════════════════════════════════════════════════════════ // ⛔⛔ W50-T19 — WHY NO CANVAS EVER PAINTED. TWO CAUSES, AND THE SECOND IS THE REAL ONE. // // MEASURED, twice, against a real build: `.sheet-grid-canvas` had height 0 and // `document.querySelectorAll(".sheet-grid-canvas canvas").length` was 0. // // ⛔ CAUSE 1, THE BOX. `styles/wave49/sheet.css`'s `.sheet-body` was `display: flex` with NO // `flex-direction`, so it was a ROW: the toolbar, the notice and this grid were laid out SIDE BY // SIDE, and `align-items: flex-start` then gave `.sheet-grid-wrap` its CONTENT height, which is // `.sheet-grid-head` at 28 px plus a canvas box of 0. `flex-direction: column` fixed that half, // and the canvas box measured a real 744 px afterwards. // // ⛔⛔ CAUSE 2, AND IT SURVIVED THE FIRST FIX: GLIDE'S STYLESHEET WAS NOT IN THIS CHUNK. // `customer-grid/CustomerGrid.tsx:25` was the ONLY file in the tree importing // `@glideapps/glide-data-grid/dist/index.css`, so every structural rule the library needs was // bundled into the CustomerGrid chunk alone. The Sheet is its own lazily loaded chunk and never // loaded it, so on this page `.gdg-wmyidgi` had NO RULES AT ALL: // // .gdg-wmyidgi{min-width:10px;max-width:100%;min-height:10px;max-height:100%; // width:var(--wmyidgi-0);height:var(--wmyidgi-1);position:relative;overflow:clip} // // none of it applied. glide's wrapper was therefore a PLAIN BLOCK DIV: it filled its parent's // width the way any block does, and took its CONTENT height, which was 0. It measured 864 x 0 // with `--wmyidgi-0` and `--wmyidgi-1` both set to `100%` on the element and nothing reading // them, and `min-height: 10px` did not hold because that rule was not loaded either. // // ⚠ AND THAT IS ALSO WHY W50-T18's `width="100%"` APPEARED TO WORK. It was never glide's CSS // honouring the prop; it was a block div doing what a block div does. The horizontal fix was a // coincidence with the right outcome, which is why the vertical one had nothing to stand on. // // ⛔ A ZERO-SIZED BOX DOES NOT MEAN A CLIPPED GRID, IT MEANS NO GRID. glide's // `internal/scrolling-data-grid/infinite-scroller.js` ends its render with // // if ((width ?? 0) === 0 || (height ?? 0) === 0) return React.createElement("div", { ref }); // // so at a measured zero it renders an EMPTY div and its children, the two `` elements, // are never created. That is why the count was 0 rather than "a canvas 0 px tall". // // ⭐ THE FIX IS THREE THINGS, and each covers a different level. The stylesheet import above is // the one that matters. `.sheet-body` is a column. And `.sheet-grid-canvas` is now a flex column // whose child stretches, so glide's wrapper takes its height as a FLEX ITEM rather than by // resolving `100%` against a parent whose own height came from `flex: 1 1 auto`. `width` and // `height` stay at `100%`: with the stylesheet loaded they are read, `min-height: 10px` is a real // floor, and glide sizes its internal scroller from the box instead of from `idealHeight`, which // for 200 rows at 34 px would be about 6,836 px. // // ⚠ THE CANVAS COMES BACK ONE FRAME LATER, NOT SYNCHRONOUSLY. `common/resize-detector.js` is a // live `ResizeObserver` writing React state, and the zero-size early return carries the SAME // `ref` at the same tree position, so React keeps the node and the observer survives. Measuring // the canvas count in the same tick as a style change therefore reads 0 whatever the fix. // ═════════════════════════════════════════════════════════════════════════════════════════════ import { cloneElement, isValidElement, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import type { ChangeEvent as ReactChangeEvent, KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent, ReactNode } from "react"; import { createPortal } from "react-dom"; import type { DataEditorRef, DrawCellCallback, DrawHeaderCallback, EditableGridCell, GridColumn, GridKeyEventArgs, GridMouseEventArgs, GridSelection, Item, GridCell, Rectangle, } from "@glideapps/glide-data-grid"; import { CompactSelection, GridCellKind } from "@glideapps/glide-data-grid"; // ⭐ glide's editor with a row marker that paints the SHEET's row. See `sheetDataEditor.tsx`. import { DataEditor } from "./sheetDataEditor"; // ⛔⛔ THIS IMPORT IS THE GRID. Without it glide's STRUCTURAL stylesheet is not in this chunk and // no canvas is ever created; the block comment at the head of this file has the measurement. It // is one line and it looks like housekeeping, which is exactly why it went missing. import "@glideapps/glide-data-grid/dist/index.css"; import { lightTheme } from "../customer-grid/theme"; import { AnchoredOverlay } from "../customer-grid/OverlaySurface"; import type { AnchorRect } from "../customer-grid/OverlaySurface"; import { fetchWorkspace } from "../customer-grid/apiBridge"; import type { SurfaceScope } from "../customer-grid/apiBridge"; import type { Field, FilterTree } from "../customer-grid/types"; import { filterTreeConj, filterTreeNodes } from "../customer-grid/types"; import { FilterBuilderPanel as SharedFilterBuilderPanel, type FilterBuilderPanelProps } from "../filter-kit/FilterBuilderPanel"; // ⭐ INSTRUCTION 15 — clicking a sheet cell folds the nav rail exactly as a Data-module cell // click already does (`customer-grid/CustomerGrid.tsx::selectView`). One shared signal, one // shared listener (`shell/Shell.tsx::onNavMinimize`); this file never dispatched it before. import { NAV_MINIMIZE_EVENT, signal } from "../apiContract"; // ⭐⭐ W52-T06 / CONTRACT C3 / CROSS-FEATURE WIRING #1 — THE SAME SHARED ASSIST FormulaBar.tsx // MOUNTS, driven by the SAME pure engine, so the dropdown, the ScreenTip and the coloured // reference text read identically wherever a formula is typed. This file additionally owns POINT // MODE (PM-1..PM-18): FormulaAssist ships no grid interaction of its own. import FormulaAssist, { ColoredFormulaText, tokenStartAt } from "./FormulaAssistPanel"; import { acceptedText, acceptsSuggestion, refsIn, suggest, } from "./formulaAssist"; import type { SuggestItem } from "./formulaAssist"; // ⭐⭐ W54-T25 / RULING R9(i) — FORMULA ENTRY'S TWO PURE RULES, FROM THE PURE ENGINE. Closing an // unfinished formula and walking one reference through Excel's four anchor states are both string // arithmetic, so they live in `formulaEval.ts` where `verify_formula_engine.py` compiles them and // EXECUTES the claim under node. This file owns only the keystroke and the commit that call them. import { ERROR_REF, ERROR_VALUE, autoCloseFormula, cycleAnchorAtCaret, workbookFormulaGetter, } from "./formulaEval"; import { colorForSlot } from "./refColors"; import { useCellRefFocus, useHighlightedCellRefs } from "./refHighlight"; import "../styles/wave52/sheet-grid.css"; import "../styles/wave61/sheet-grid.css"; // ⛔⛔ CONTRACT C8: ONE ESCAPE ARBITER FOR THE WHOLE APP, topmost wins. Nothing in this tree adds // a second `keydown` listener for it, and amendment A2 says the two-press rule is OPT IN: the // shortcuts PANEL opts in, this file's find box keeps the one press close every picker has. import { useEscapeClose } from "../ui/useEscapeClose"; import CellActionBar from "./CellActionBar"; import { paintCellLimitMark } from "./cellLimits"; import Ribbon from "./Ribbon"; // ⭐ W54-T10 (lane B) — `RibbonInsertDoor` is the Insert tab's document door, declared beside the // act union it deliberately is not part of. See its own doc comment in `Ribbon.tsx`. import type { RibbonAction, RibbonInsertDoor } from "./Ribbon"; import type { SheetFilterDoor } from "./ribbonData"; import { RulesDialog, ValidationDialog } from "./RulesDialog"; import ChartDialog from "./ChartDialog"; import SheetChartLayer from "./SheetChartLayer"; import SheetViewLayer from "./SheetViewLayer"; import { IconRowGroup } from "./ribbonIcons"; import "./rowOutline.css"; import { copyChartImage } from "./sheetExport"; import { sheetPageGrid } from "./pageViews"; import ShortcutsPanel from "./ShortcutsPanel"; import SheetStatusBar from "./SheetStatusBar"; import { holdsTwoOrMore, selectionRects, selectionStatsSteps } from "./sheetSelectionStats"; import type { SelectionStats } from "./sheetSelectionStats"; import { colToIndex, columnRangeA1, indexToCol, rowRangeA1, shiftForStructure } from "./a1"; import { createViewRowsReader, fetchViewRows, viewBlockGeometry, viewChromeRefusal, viewHeaderAt, viewReadKey, viewRefreshOp, writeViewCell, } from "./viewPlacement"; import type { FormulaBarProps } from "./FormulaBar"; // ⛔⛔ W51-T18 — THE RULE ENGINE AND THE VALIDATION CHECKER ARE PURE AND SHEET LOCAL, and that is // what lets `verify_api.py` compile them beside `sheetState.js` and EXECUTE the ten operators // rather than grep for their names. This component is the only place their answers meet a canvas. // ⭐ W54-T05 adds `ruleBarAt` and the two rule FACTORIES beside them, for the reason that // module's own head note gives: a proportional width cannot be said as a style, so a data // bar has a second door, and both doors walk one shared first-match list. import { addRule, barRule, numericBounds, overlayRuleStyle, ruleBarAt, ruleStyleAt, ruleSubject, scaleRule, } from "./rules"; // ⭐ WAVE 54 BASE KIT — three seams split out of this hub file so four lanes can work at once. // `cellBorders.ts` owns the per-cell border paint AND the palette-token resolver that its stroke // setup needs; `clipboardOps.ts` owns what a copy is made of; `sparkline.ts` is an empty seam that // answers `false` today. All three were moved or wired without changing a pixel. import { paintCellBorders, tokenColour } from "./cellBorders"; import { buildCopyPayload, MENU_PASTE_OPTIONS, parseClipboardPayload, pasteOptionsFrom, readClipboardPayload, runCopySelection } from "./clipboardOps"; import type { ClipboardPayload, CopyPayload, PasteMode, PasteOptions } from "./clipboardOps"; import { drawSparkline } from "./sparkline"; // ⭐ W54-T14 / LANE B — A CELL'S ATTACHMENTS: the canvas marks, the hover bubble and the door that // follows a link. `LinkDialog.tsx` owns all three beside the surface that authors them; this file // owns only the wiring, which is one call in the paint and one in each grid's click and hover. import LinkDialog, { NoteBubble, followLink, paintCellMarks } from "./LinkDialog"; import type { CellLink } from "./LinkDialog"; import CellContextMenu, { FONT_SIZE_LADDER } from "./CellContextMenu"; import type { CellMenuAct } from "./CellContextMenu"; import { PasteSpecialDialog } from "./PasteSpecialDialog"; import type { FollowContext } from "./LinkDialog"; import { canonicalEntry, checkEntry, filterList, refusalLabel, screenEdits, validationEdits, validationOf, } from "./validation"; import { fontPt, fontPx, fontStack, formatCellText, stylePaints, sheetExtent, CELL_FONTS, DEFAULT_CELL_FONT, DEFAULT_COL_WIDTH, DEFAULT_FONT_PT, DEFAULT_SHEET_COLS, DEFAULT_SHEET_ROWS, MAX_CELL_INDENT, MAX_COL_WIDTH, MIN_COL_WIDTH, } from "./types"; import type { Cell, CellStyle, CellStylePatch, CellValign, SheetChartSpec, SheetRule, SheetTab, SheetViewDoor, SheetRowGroup, ViewBinding, ViewRowsAnswer, Workbook, } from "./types"; import { addressOf, appendLineBreak, applyStructureWorkbook, autoSumFormula, boundDragLabel, cellAt, cellShiftLabel, cellToValue, clearAll, recalcDependents, recalculateWorkbook, WorkbookCalculationSession, clearCells, clearFormats, commitTyped, cycleAnchors, dateStamp, displayText, drillAffordance, editableText, fillCells, fillDown, fillRight, findMatches, isFilled, markOf, noMatchLabel, nothingHiddenLabel, paintPatch, pasteCells, pasteOptionsOf, chartPaneProjections, frozenBandSize, hideColumnByWidth, lastVisibleWidth, lockstepScrollX, copyCells, recallCopy, rememberCut, withClipboardScope, setFormula, shiftCells, splitAddress, styleCells, styleOf, usedExtent, structureRefusal, viewIndexOf, rowHeightsPatch, visibleIndices, withHidden, outlineHiddenRows, rowGroupRefusal, rowOutlineItems, } from "./sheetState"; import type { CellRange, DragContext, FillEdit, MovedBlock, OptionCatalogue, StructureOp, TabViewPatch, } from "./sheetState"; import type { SavedViewShadow } from "./bindingRefs"; // ⛔⛔ W51-T17 — ONE TABLE, TWO CONSUMERS. `shortcuts.ts` is the key map AND the panel's rows, and // it imports NOTHING: see its head note on tsc's emitted root. This file matches against it and // `ShortcutsPanel.tsx` renders it, so the two cannot advertise different keys. import { arrowStep, axisBand, commitDirection, commitTarget, currentRegion, edgeIndex, edgeStart, extendEdgeRect, crossesProjectedFocus, isArrowKey, KEY_TIP_GRID_ARROW_EVENT, keyTipGridArrow, matchShortcut as matchShortcutDefault, matchShortcutInGrid as matchShortcutInGridDefault, projectedFocusOwner, selectAllTarget, shortcutOwner, structureAxis, tabRunOrigin, wholeAxisAnchor } from "./shortcuts"; import type { CommitDirection, SelectionAxis, SelectionRect, ShortcutId, WholeAxis } from "./shortcuts"; type SheetFilter = { scope: string; headerRow: number; col0: number; col1: number; lastRow: number; values: Record>; }; /** Match the canvas's formatted values, including formula results and real blanks. */ const sheetFilterValue = (cell: Cell | null | undefined): string => !cell || cell.kind === "empty" ? "" : formatCellText(cell, displayText(cell)); /** A single cell expands across its header; an explicit range keeps its chosen columns. */ function sheetFilterRegion(tab: SheetTab, range: CellRange): Omit | null { const headerRow = Math.min(range.row0, range.row1); let col0 = Math.min(range.col0, range.col1); let col1 = Math.max(range.col0, range.col1); const hasHeader = (col: number) => sheetFilterValue(cellAt(tab, addressOf(col, headerRow))) !== ""; if (col0 === col1 && range.row0 === range.row1) { if (!hasHeader(col0)) return null; while (col0 > 0 && hasHeader(col0 - 1)) col0--; while (col1 + 1 < sheetExtent(tab).cols && hasHeader(col1 + 1)) col1++; } let headerFound = false; for (let col = col0; col <= col1; col++) headerFound ||= hasHeader(col); if (!headerFound) return null; const populatedRows = new Set(); let lastUsedRow = headerRow; for (const [addr, cell] of Object.entries(tab.cells ?? {})) { const at = splitAddress(addr); if (!at || at.col - 1 < col0 || at.col - 1 > col1 || at.row - 1 <= headerRow || sheetFilterValue(cell) === "") continue; populatedRows.add(at.row - 1); lastUsedRow = Math.max(lastUsedRow, at.row - 1); } let lastRow = headerRow; if (range.row0 !== range.row1) { // Keep internal blank rows in an explicit range, but never filter an empty sheet tail. lastRow = Math.min(Math.max(range.row0, range.row1), lastUsedRow); if (![...populatedRows].some(row => row <= lastRow)) return null; } else { while (populatedRows.has(lastRow + 1)) lastRow++; } return lastRow > headerRow ? { headerRow, col0, col1, lastRow } : null; } /** This projection never writes the tab's manual hiddenRows or any persistence door. */ function sheetFilterHiddenRows(tab: SheetTab, filter: SheetFilter | null): number[] { if (!filter) return []; const criteria = Object.entries(filter.values); if (!criteria.length) return []; // `row` walks zero-based grid rows; hiddenRows speak the SHEET's one-based rows (types.ts). const hidden: number[] = []; for (let row = filter.headerRow + 1; row <= filter.lastRow; row++) { if (criteria.some(([col, values]) => !values.has(sheetFilterValue(cellAt(tab, addressOf(Number(col), row)))))) hidden.push(row + 1); } return hidden; } // W61-T09: match the paste engine's clipboard key. CRLF and stripped trailing blank rows // must not make the same copied block lose its axis on a browser clipboard round trip. const wholeAxisClipboardKey = (text: string): string => String(text).replace(/\r\n?/g, "\n").replace(/\n+$/, ""); /** * ⭐⭐ W50-T20 — THE EXTENT IS THE SHEET'S NOW, AND THESE ARE ONLY ITS DEFAULTS. * * `COLS` and `ROWS` were module constants, which is precisely why no sheet could grow past them * and nothing else in the module could agree with them: `FormulaBar.tsx` had to RESTATE them as * `LAST_COL` / `LAST_ROW` because they were not exported. They are exported now, and they are * the DEFAULTS a new sheet is created with rather than a bound anything should check against. * * ⚠ THE FOLLOW UP IS A REAL CHANGE, NOT AN IMPORT SWAP. A consumer that wants to know whether an * address fits must read the OPEN SHEET's `cols` / `rows` (`types.ts::sheetExtent`), because a * grown sheet legitimately holds `AB300`. Swapping `FormulaBar`'s two constants for these would * keep refusing that address, so the tidy is named here and left to that file's owner. */ export const COLS = DEFAULT_SHEET_COLS; export const ROWS = DEFAULT_SHEET_ROWS; /** Geometry shared by the grid and by any chart positioned over it, so the two cannot disagree. */ const COL_WIDTH = DEFAULT_COL_WIDTH; const ROW_HEIGHT = 22; const SHEET_ROW_MARKER_WIDTH = 44; /** Glide's `internal/data-grid/data-grid.js::edgeDetectionBuffer` straddles each border. */ export const COLUMN_RESIZE_ZONE = 5; /** Both sides of a row's bottom border remain grabbable without changing the gutter. */ export const ROW_RESIZE_ZONE = 5; /** Hover can be stale over a resize zone, so check both edges of its last header rectangle. */ export function borderHit(x: number, rect: Pick, zone = COLUMN_RESIZE_ZONE): boolean { return Math.abs(x - rect.x) <= zone || Math.abs(x - rect.x - rect.width) <= zone; } /** Select-all can arrive as a range rather than a column set, including the frozen-row seam. */ export function columnsForResize(selection: GridSelection | undefined, colIndex: number, bounds: { columns: number; minRow: number; maxRow: number }): number[] { if (selection?.columns.hasIndex(colIndex)) return selection.columns.toArray(); const range = selection?.current?.range; if (range && range.x === 0 && range.width >= bounds.columns && (range.y <= bounds.minRow || range.y === 0) && range.y + range.height > bounds.maxRow) { return Array.from({ length: bounds.columns }, (_, index) => index); } return [colIndex]; } /** A whole-row range, including Ctrl+A and negative frozen-band rows, keeps its selection. */ export function rowsForResize(selection: GridSelection | undefined, row: number, bounds: { columns: number; minRow: number; maxRow: number }): number[] { if (selection?.rows.hasIndex(row)) return selection.rows.toArray(); const range = selection?.current?.range; if (range && range.x === 0 && range.width >= bounds.columns && row >= range.y && row < range.y + range.height) { const first = Math.max(bounds.minRow, range.y); const last = Math.min(bounds.maxRow, range.y + range.height - 1); return Array.from({ length: Math.max(0, last - first + 1) }, (_, index) => first + index); } return [row]; } /** * ⭐ W51-T34: glide's own default header height, DECLARED so it can be depended on. The frozen * band's grid carries the column letters and the main grid below it is given `headerHeight={0}`, * so the letters appear once rather than twice, and the band's box has to be exactly this plus * its rows. glide guards the zero itself (`drawGridHeaders` returns early at a total of zero), so * a headerless grid is a supported shape rather than a shape that happens to work. */ const SHEET_HEADER_HEIGHT = 36; const MIN_ROW_HEIGHT = 18; const MAX_ROW_HEIGHT = 200; /** S67-T02: the narrowest the in-cell formula editor wraps at when a cell sits by the pane's * right edge (about 50 characters), and the room kept under it, inside the window, for the * Enter/Point label. */ const FORMULA_EDITOR_READABLE_WIDTH = 360; const FORMULA_MODE_RESERVE = 22; /** S67-T11 / C2: one border side exactly as lane B's contract shapes it, `{style, color}`. */ interface BorderPenLine { style: string; color: string } /** S67-T11: Excel's three Draw Border pens, raised by `aios:sheet-border-draw`. */ type BorderPen = BorderPenLine & { mode: "draw" | "grid" | "erase" }; type BorderPenSide = "top" | "right" | "bottom" | "left"; const BORDER_PEN_STYLES = ["thin", "medium", "thick", "dashed", "dotted", "double", "hair"]; /** * Whether one visible row/column heading belongs to the document selection's paint projection. * The selection itself stays untouched: feeding these axes back through `GridSelection.rows` or * `.columns` would turn an ordinary cell range into a whole-axis copy/delete command. */ export function selectionProjectsHeader( selection: GridSelection | undefined, axis: "column" | "row", index: number, bounds: { columns: number; minRow: number; maxRow: number }, ): boolean { if (!selection) return false; const heldColumns = selection.columns.length > 0; const heldRows = selection.rows.length > 0; if (heldColumns || heldRows) { return axis === "column" ? heldColumns && selection.columns.hasIndex(index) : heldRows && selection.rows.hasIndex(index); } const range = selection.current?.range; if (!range || range.width <= 0 || range.height <= 0) return false; const col0 = range.x; const col1 = range.x + range.width - 1; const row0 = range.y; const row1 = range.y + range.height - 1; const wholeRows = col0 <= 0 && col1 >= bounds.columns - 1; // Before T25 gives a column click its explicit axis set, its legacy body projection begins at // zero even with frozen rows above it. Recognise both that shape and the complete C6 range. const wholeColumns = (row0 <= bounds.minRow || row0 === 0) && row1 >= bounds.maxRow; if (wholeRows && !wholeColumns) return axis === "row" && index >= row0 && index <= row1; if (wholeColumns && !wholeRows) return axis === "column" && index >= col0 && index <= col1; return axis === "column" ? index >= col0 && index <= col1 : index >= row0 && index <= row1; } /** * ⭐⭐ W54-T06 — ONE OFFSCREEN 2D CONTEXT, BECAUSE A ROW'S HEIGHT IS ASKED OUTSIDE PAINT TIME. * * glide asks how tall a row is BEFORE it paints anything, and a wrapped value's line count is a * measurement in a font, not a guess from a character count: `measureText` is the only honest * answer and it needs a canvas context. The one glide paints into is not ours to borrow between * frames, so this is a canvas of our own, created once, never mounted, never drawn. * * ⚠ IT ANSWERS `null` WHERE THERE IS NO DOCUMENT (a node proof, a test runner), and every caller * treats that as "no wrapped row is taller than the base", which is exactly what the grid did * before this ticket. A measurement that cannot be taken must not become a guess. */ let measureCtx: CanvasRenderingContext2D | null | undefined; const measureContext = (): CanvasRenderingContext2D | null => { if (measureCtx === undefined) { measureCtx = typeof document === "undefined" ? null : document.createElement("canvas").getContext("2d"); } return measureCtx; }; /** * ⭐ THE WRAP ITSELF, SHARED BY THE MEASUREMENT AND THE PAINT so the two cannot disagree. Words * are added to a line until the next one would cross the cell's inner width, in whatever font * `ctx` is ALREADY set to; a single word wider than the column stays on its own line and is * clipped, because breaking inside a word would hyphenate an account code. */ const wrapIntoLines = ( ctx: CanvasRenderingContext2D, text: string, inner: number, ): string[] => { const out: string[] = []; let line = ""; for (const word of text.split(/\s+/)) { const next = line ? `${line} ${word}` : word; if (line && ctx.measureText(next).width > inner) { out.push(line); line = word; } else { line = next; } } if (line) out.push(line); return out; }; /** * ⭐⭐ W54-T19 (instruction 13) — THE ONE SURFACE THE KEYBOARD RESCUE STANDS DOWN FOR. * * A modal owns the keyboard for as long as it is open, so a focus that goes nowhere INSIDE one is * the modal's own business to answer, not the sheet's. Pulling the keyboard back to the grid * underneath it would be the sheet reaching through a dialog, which is worse than the scroll the * rescue exists to prevent. */ const MODAL_SELECTOR = '[role="dialog"], [role="alertdialog"]'; /** * ⭐ W51-T16 — R8's FOUR SIZE STEPS, IN THE ONE UNIT A CANVAS UNDERSTANDS. * * `--lp-fs-*` is a CSS custom property and glide's grid is a CANVAS, which cannot read one * (DESIGN.md 5 says this in full: `theme.ts` exists because a painted cell cannot resolve a * variable). `lightTheme.baseFontStyle` is `13px`, so `m` IS the grid's own body size and the * other three step around it rather than inventing a second scale. */ const SIZE_PX: Record = { s: 11, m: 13, l: 16, xl: 20 }; // ⭐ W54-T03 / R11 — THIS TABLE IS NOW THE NAMED HALF OF A TWO SHAPE SLOT, and it is unchanged // on purpose. `types.ts::SIZE_STEP_PT` maps the same four names to 8, 10, 12 and 15 POINTS, and // `types.ts::fontPx` rounds a point size to four thirds of itself, which reproduces these four // numbers exactly. So a document written before the size box existed paints identically, and the // only cells that take the other branch are the ones somebody set a point size on. const BINDING_REFUSAL_COPY: Readonly> = { database_unreadable: { display: "#NO ACCESS", message: "You do not have access to this database." }, field_unknown: { display: "#FIELD?", message: "This field is no longer in the database." }, scope_not_applicable: { display: "#ERROR!", message: "The database cannot apply this cell's row restrictions." }, // HOTFIX 2026-09-24: a cell with no answer computed for this reader yet is not a failed // calculation, and painting it `#ERROR!` is what made a working binding look broken. sheet_refresh_required: { display: "#REFRESH", message: "Press Refresh to calculate this cell for your access." }, store_catching_up: { display: "#UPDATING", message: "This database is updating. Refresh when it finishes." }, source_unavailable: { display: "#UPDATING", message: "The database was busy. This cell updates after the next sync." }, store_not_ready: { display: "#UPDATING", message: "The database was busy. This cell updates after the next sync." }, mirror_not_ready: { display: "#UPDATING", message: "The database was busy. This cell updates after the next sync." }, amazon_mirror_not_loaded: { display: "#UPDATING", message: "The database was busy. This cell updates after the next sync." }, }; /** A bound cell still waiting for an answer. A stale cell with a server reason keeps its value and does not shimmer. */ function boundWaiting(cell: Cell | null | undefined): cell is Cell { return !!cell && cell.kind === "bound" && cell.state === "stale" && !(cell as Cell & { staleReason?: string }).staleReason; } const BINDING_REFUSAL_FALLBACK = { display: "#ERROR!", message: "This cell's database binding could not be calculated." }; /** R48: old documents may have a blank display, but the grid always owns its refusal copy. */ function bindingRefusal(cell: Cell | null | undefined) { if (cell?.kind !== "bound" || cell.state !== "refused" || cell.binding?.mode === "view") return null; return BINDING_REFUSAL_COPY[cell.refusal?.code ?? ""] ?? BINDING_REFUSAL_FALLBACK; } /** * Lay out a run in its owner's box. The caller clips to the cell being repainted. * An unstyled owner uses {}: SIZE_PX.m (13 px), lightTheme.fontFamily (Inter), * and left alignment, matching glide's baseFontStyle and its default alignment. * This file never sets contentAlign. */ function drawCellTextRun( ctx: CanvasRenderingContext2D, box: Rectangle, cell: Cell | null, style: CellStyle, zoom: number, ): void { const refusal = bindingRefusal(cell); const text = refusal?.display ?? formatCellText(cell, displayText(cell)); // ⭐ W51-T16: THE SIZE STEP AND THE INDENT ARE PART OF THE FONT AND THE BOX, so they // are settled BEFORE anything is measured. A canvas measures text in the font that is // set at the time, so choosing the size after `measureText` would centre a heading // using the body size's width. // ⭐⭐ W54-T03 / R11 — TWO SHAPES, ONE SLOT, AND THE PIXELS DO NOT MOVE. A `size` that is one // of C2's four step NAMES is still read out of the table above, byte for byte as it was; a // size that is a NUMBER is a POINT size and goes through `fontPx`. The two agree by // construction: 8, 10, 12 and 15 points round to 11, 13, 16 and 20 px, which is exactly what // that table holds, so every cell styled before this ticket paints at the size it always did. // ⭐ W54-T03 / R10 — AND THE FACE IS THE CELL'S OWN. `fontStack` resolves the stored NAME to // a stack ending in a generic family, falling back to the grid's own Inter when the cell // names none. The app's chrome is unaffected: this is one canvas string, on cell text only. const documentSize = typeof style.size === "number" ? fontPx(style.size) : SIZE_PX[style.size ?? "m"] ?? SIZE_PX.m; const size = documentSize * zoom; const weight = style.bold ? "600 " : ""; const slant = style.italic ? "italic " : ""; ctx.font = `${slant}${weight}${size}px ${fontStack(style.font, lightTheme.fontFamily)}`; ctx.fillStyle = tokenColour(refusal ? "--lp-red-deep" : style.color ?? "", lightTheme.textDark ?? "#202433"); ctx.textBaseline = "middle"; const pad = (8 + Math.max(0, Math.min(MAX_CELL_INDENT, style.indent ?? 0)) * 8) * zoom; const lineHeight = Math.round(documentSize * 1.35) * zoom; /** * ⭐⭐ WRAP IS THE ONE THAT CHANGES THE SHAPE OF THE PAINT, so it is measured rather * than guessed: words are added to a line until the next one would cross the cell's * inner width. A single word wider than the column stays on its own line and is * clipped, exactly as glide clips an unwrapped value, because breaking inside a word * would hyphenate an account code. */ const inner = box.width - pad - 8 * zoom; const lines: string[] = []; if (style.wrap && text) { // ⭐ W54-T06 MOVED THE LOOP ITSELF to `wrapIntoLines` at the top of this file, unchanged, // and called it from BOTH here and `wrapHeights` below. The row's height and the row's // paint are now one measurement asked twice rather than two measurements that agree by // inspection: a wrapped value that needs three lines is given three lines of room. lines.push(...wrapIntoLines(ctx, text, inner)); } else { lines.push(text); } // ⭐ THE VERTICAL ALIGN. `middle` is glide's own behaviour and stays the default, so // a cell that never asked for one paints exactly where it always did. const block = lines.length * lineHeight; const valign = style.valign ?? "middle"; let top = box.y + box.height / 2 - block / 2 + lineHeight / 2; if (valign === "top") top = box.y + 4 * zoom + lineHeight / 2; else if (valign === "bottom") top = box.y + box.height - 4 * zoom - block + lineHeight / 2; // ═══════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W54-T06 — THE TURN, AND THE SIGN IS THE WHOLE OF IT. // // `CellStyle.textRotation` is Excel's own signed degree: POSITIVE is counterclockwise, the // way a protractor reads and the way `core/sheets.py::_clean_style` clamps it. A canvas y // grows DOWNWARD, so the same visual turn is a NEGATIVE `rotate`, and the negation happens // once, here, rather than in the gallery that writes the number: what the document stores // stays the number a person asked for. // // ⛔ THE CONTEXT IS TURNED ABOUT THE CELL'S OWN CENTRE, INSIDE THE TEXT CLIP that was set a // few lines above, so a turned value still stops at its own cell edge instead of writing // over its neighbour. It is also inside the one `ctx.save()` this branch already opened, so // the transform is undone by the `ctx.restore()` that was always there and the borders, // marks and marquees below are painted in untouched device space. // // ⚠ A TURNED RUN IS CENTRED IN BOTH AXES, whatever the cell's align and valign say. Those // two describe where a HORIZONTAL run sits against the cell's corners, and a run leaving its // corner at an angle simply leaves the box: left-aligned at 90 degrees the whole value would // be clipped away and the control would read as broken. Excel makes the same trade. // ═══════════════════════════════════════════════════════════════════════════════ const turn = typeof style.textRotation === "number" ? style.textRotation : 0; if (turn !== 0) { const cx = box.x + box.width / 2; const cy = box.y + box.height / 2; ctx.translate(cx, cy); ctx.rotate((-turn * Math.PI) / 180); ctx.translate(-cx, -cy); top = cy - block / 2 + lineHeight / 2; } lines.forEach((line, index) => { const width = ctx.measureText(line).width; let x = box.x + pad; if (style.align === "center") x = box.x + (box.width - width) / 2; else if (style.align === "right") x = box.x + box.width - 8 * zoom - width; if (turn !== 0) x = box.x + (box.width - width) / 2; const y = top + index * lineHeight; ctx.fillText(line, x, y); // 3. THE UNDERLINE is drawn, not requested: a canvas has no text decoration, so the // rule is a 1 px fill under the measured run and nothing else. if (style.underline && line) { ctx.fillRect(x, Math.round(y + size / 2 + 1), width, 1); } }); } type SpillMeasure = (text: string, cell: Cell, col: number) => number; type SpillOwner = { ownerCol: number; ownerText: string; ownerCell: Cell }; type SpillBlocker = (col: number, row: number) => boolean; /** The narrow vertical band a one-line run occupies; separator masking never leaves this band. */ function spillTextBand(box: Rectangle, style: CellStyle, zoom: number) { const documentSize = typeof style.size === "number" ? fontPx(style.size) : SIZE_PX[style.size ?? "m"] ?? SIZE_PX.m; const lineHeight = Math.round(documentSize * 1.35) * zoom; const valign = style.valign ?? "middle"; let centre = box.y + box.height / 2; if (valign === "top") centre = box.y + 4 * zoom + lineHeight / 2; else if (valign === "bottom") centre = box.y + box.height - 4 * zoom - lineHeight / 2; return { top: Math.max(box.y + 1, Math.floor(centre - lineHeight / 2)), bottom: Math.min(box.y + box.height - 1, Math.ceil(centre + lineHeight / 2)), }; } /** Distances beyond the owner's edges, in document pixels, matching the run's layout. */ function spillReach(cell: Cell, width: number, col: number, measure: SpillMeasure) { const style = cell.style ?? {}; // An error belongs to its own cell, even when the column is too narrow for its code. if (cell.state === "refused") return null; if (style.wrap || style.textRotation || displayText(cell) === "") return null; const text = formatCellText(cell, displayText(cell)); const runWidth = measure(text, cell, col); const pad = 8 + Math.max(0, Math.min(MAX_CELL_INDENT, style.indent ?? 0)) * 8; const x = style.align === "center" ? (width - runWidth) / 2 : style.align === "right" ? width - 8 - runWidth : pad; return { left: style.align === "right" || style.align === "center" ? Math.max(0, -x) : 0, right: style.align !== "right" ? Math.max(0, x + runWidth - width) : 0, text, }; } /** * Find the nearest non-empty neighbour whose run reaches this empty cell. * Widths and measure use document pixels; addrAt maps visible columns and rows. * A filled neighbour blocks the walk even if its own text cannot spill. */ export function spillOwnerAt( cells: Readonly>, addrAt: (col: number, row: number) => string, widths: readonly number[], frozenCols: number, col: number, row: number, measure: SpillMeasure, blocks: SpillBlocker = () => false, ): SpillOwner | null { if (col < 0 || col >= widths.length || blocks(col, row) || displayText(cells[addrAt(col, row)]) !== "") return null; const first = col < frozenCols ? 0 : frozenCols; const last = col < frozenCols ? frozenCols : widths.length; for (const step of [-1, 1]) { let gap = 0; for (let ownerCol = col + step; ownerCol >= first && ownerCol < last; ownerCol += step) { if (blocks(ownerCol, row)) break; const ownerCell = cells[addrAt(ownerCol, row)]; if (displayText(ownerCell) !== "") { const reach = spillReach(ownerCell, widths[ownerCol], ownerCol, measure); if (reach && (step < 0 ? reach.right : reach.left) > gap) { return { ownerCol, ownerText: reach.text, ownerCell }; } break; } gap += widths[ownerCol]; } } return null; } /** Whether this owner's run reaches an empty adjacent cell in the same frozen pane. */ export function cellSpillsAt( cells: Readonly>, addrAt: (col: number, row: number) => string, widths: readonly number[], frozenCols: number, col: number, row: number, measure: SpillMeasure, blocks: SpillBlocker = () => false, ): boolean { if (col < 0 || col >= widths.length || blocks(col, row)) return false; const cell = cells[addrAt(col, row)]; if (!cell) return false; const reach = spillReach(cell, widths[col], col, measure); if (!reach) return false; const first = col < frozenCols ? 0 : frozenCols; const last = col < frozenCols ? frozenCols : widths.length; return (reach.left > 0 && col > first && !blocks(col - 1, row) && displayText(cells[addrAt(col - 1, row)]) === "") || (reach.right > 0 && col + 1 < last && !blocks(col + 1, row) && displayText(cells[addrAt(col + 1, row)]) === ""); } /** R8's size menu emits a step NAME; C2 stores a letter. One table, so the two cannot drift. */ const SIZE_OF_STEP: Record = { small: "s", normal: "m", large: "l", heading: "xl", }; /** * ⛔ THE ONE ACT THIS COMPONENT STILL DEFERS, AND IT SAYS SO RATHER THAN DOING NOTHING. A custom * format code needs W51-T20's parser (contract C7's `formatWithCode`), which is not in this tree. * A control that is present, labelled and SILENT is the defect instruction 17 reported; a control * that names the reason is the honest half while its owner lands. * * ⭐ W51-T18 CLOSED THE OTHER ONE. `NOT_YET_RULES` is gone: Conditional formatting opens the real * editor now, which is why the ribbon's Styles group is a door rather than a notice (R8). */ const NOT_YET_FORMAT_CODE = "A custom number format is not available yet. It arrives with the format code reader."; /** * ⭐ EXCEL'S KEYS, SAID ONCE. glide already carries the four accept keys and the escape * (`acceptOverlayDown: Enter`, `acceptOverlayUp: shift+Enter`, `acceptOverlayRight: Tab`, * `acceptOverlayLeft: shift+Tab`, `closeOverlay: any+Escape`), so the ONLY thing this override * adds is F2. Its matcher compares `event.key` for any token longer than one character * (`common/is-hotkey.js::checkKey`), so `F2` is the literal name of the key. * * ⛔ `delete` IS NOT LISTED, ON PURPOSE. Delete and Backspace are intercepted in `onKeyDown` * below and cancelled, so clearing a cell (R5: value AND binding, for a bound one) is in code a * reader can see rather than resting on glide's internal `isReadWriteCell` filter. */ const KEYBINDINGS = { activateCell: " |Enter|shift+Enter|F2" } as const; // The document paste event reaches the ribbon's writer even after a panel leaves focus outside // the canvas. Disable Glide's window-capture paste handler before it can read or land a second time. const GRID_KEYBINDINGS = { ...KEYBINDINGS, paste: false } as const; export interface SheetGridProps { /** C3: an embedded grid scopes rail and focus events to its page. */ eventScope?: string; workbook: Workbook; tab: SheetTab; busy?: boolean; /** Hotfix 2026-09-24: the binding panel or the drill is open over this grid. The cell action * bar is the door to both, so it is hidden while either one is showing; it stayed painted * over the grid after Edit was clicked. */ panelOpen?: boolean; onEdit: (addr: string, cell: Cell | null) => void; onViewRows: (addr: string, cell: Cell | null) => void; // ── W51-T15, CONTRACT C1 ─────────────────────────────────────────────────────────────────── /** * ⭐⭐ THE FORMULA BAR'S SLOT, AND IT IS A SLOT RATHER THAN A MOUNT ON PURPOSE. Instruction 10 * puts the formula rail BELOW the Home tab, and the ribbon lives inside this component, so the * bar has to arrive here to sit under it. Passing the ELEMENT rather than importing * `FormulaBar` keeps every piece of its state (the name box, the draft, the commit door) in * `SheetPage.tsx` where it already is: this file renders a child it knows nothing about. * * ⛔ ALL FOUR OF THESE ARE OPTIONAL, AND THAT IS A MERGE FACT, NOT A STYLE ONE. Lane C keeps * rendering `` ABOVE `` until the wave's handover ticket lands, so a * required prop would break its tree at the merge. When `formulaBar` is undefined this renders * NOTHING: no placeholder and no empty box, because anything above the grid competes for * vertical space and glide renders no canvas at all at a measured height of zero. */ formulaBar?: ReactNode; /** The ribbon's Refresh button, on the same row as Bold, Italic and Underline. */ onRefresh?: () => void; /** Ctrl+S, caught in this component because the grid canvas owns the keyboard. */ onSaveNow?: () => void; /** The page's import door. The ribbon offers Import only where this is given. */ onOpenImport?: () => void; /** * One or many cells, committed and SAVED AS ONE STEP. `null` clears a cell. A paste, a fill and * a range delete each arrive here once, so they take one history step and one PUT. */ /** * S67-T09: `move` rides along when these edits MOVE a block (a completed cut), so the page can * re-anchor every reference to it on every tab in the SAME history step. */ onCommit: (edits: Record, move?: MovedBlock) => void; /** The one cell selected when this workbook and tab are adopted. */ openAt: { workbookId: string; tabId: string; addr: string; request?: number }; onUndo: () => void; onRedo: () => void; onNotice: (message: string) => void; /** * C5's post-commit evaluator. Each entry is the exact bound cell object just landed, so the * page can flush the save, compute through Save's one-cell door, and ignore an answer whose * binding identity no longer matches. */ onEvaluateBindings?: (request: BoundEvaluationRequest) => void; // ── W50-T20 ──────────────────────────────────────────────────────────────────────────────── /** * ⭐⭐ THE HANDOVER W50-T21 DEFERRED TO THIS TICKET. glide's selection lives in this component * and nowhere else, so the formula bar could not mirror the SELECTED cell; it was driven by its * own name box. This fires the `{addr, cell}` the `selected` memo already computes, and * `SheetPage.tsx` feeds it to `setBarAddr`. NOTHING IN `FormulaBar.tsx` CHANGED. */ onSelect?: (selection: { addr: string; cell: Cell | null; /** True only when the reader moved to this cell, never for a restore or library default. */ readerCaused: boolean; } | null) => void; /** * Insert or delete rows and columns. The GRID raises the intent and the PAGE decides: the * refusal wall (R18) and the bound-cell confirmation both need the whole workbook, which is * where the one commit door already lives. */ onStructure: (op: StructureOp) => void; /** Grow the sheet on demand, past 26 columns and 200 rows. */ onGrow: (dCols: number, dRows: number) => void; /** Freeze or unfreeze the leading columns of this sheet. */ onFreeze: (patch: { cols?: number; rows?: number }) => void; /** * ⭐⭐ W51-T16 / C2 — THE PERSISTENCE DOOR FOR A HIDDEN BAND, AND IT IS OPTIONAL FOR THE SAME * MERGE REASON THE FOUR W51-T15 PROPS ARE. `SheetPage.tsx` owns `commitSheets`, the one path * that takes a history step and queues one PUT against the document's `rev`, and that file is * NOT in this ticket's fence. So hiding works on the screen the moment it is pressed (the band * is local state below), and it is WRITTEN to the document only where the page has wired this. * The wiring is the wave's own handover row; until it lands, a hidden band lasts as long as the * sheet stays open, which is stated in the notice rather than left to be discovered. */ onHideBands?: (patch: { hiddenRows?: number[]; hiddenCols?: number[] }) => void; /** No local fallback: only an editor with the document save door can change an outline. */ onRowGroups?: (groups: SheetRowGroup[]) => void; // ── W51-T18, contract C2 ─────────────────────────────────────────────────────────────────── /** * ⭐⭐ THE PERSISTENCE DOOR FOR THIS TAB'S CONDITIONAL FORMATTING RULES, optional for exactly * the reason `onHideBands` is: `SheetPage.tsx` owns `commitSheets`, the one path that takes a * history step and queues one PUT against the document's `rev`, and that file is NOT in this * ticket's fence. So a rule paints the moment it is saved (the list is local state below), and * it is WRITTEN to the document only where the page has wired this. The wiring is the wave's * own handover row; until it lands, a rule lasts as long as the sheet stays open, which the * dialog's own notice says rather than leaving it to be discovered. */ onRules?: (rules: SheetRule[]) => void; // ── W54-T10, LANE B'S WIRING (one contiguous addition, so a merge can see it whole) ───────── /** * ⭐⭐ THE PERSISTENCE DOOR FOR THIS TAB'S CHARTS, and it is the SAME optional-persistence-door * pattern `onHideBands` and `onRules` above are, for the same reason stated there: `commitSheets` * lives in `SheetPage.tsx`, and a REQUIRED prop would break another lane's tree at the merge. * So an inserted chart appears the moment it is inserted (the list is local state below), and it * is WRITTEN to the document only where the page has wired this. * ⛔ AND THE TWO-WRITERS RULE APPLIES UNCHANGED: with this wired the DOCUMENT is the single * answer, or a local copy outlives the state it mirrored and an undo repaints from a stale list. */ onCharts?: (charts: SheetChartSpec[]) => void; onCreatePivot?: () => void; /** A dragged column width, once the drag has ENDED. See the note on `dragWidth` below. */ onColumnWidth: (colIndex: number, width: number) => void; /** * Wave 60 base kit: merge display settings into the OPEN tab's `view`, through `commitSheets` * like `onFreeze`. Handed to the ribbon on `insert` (see `insertDoor`, `SheetViewDoor`). */ onTabView: (patch: TabViewPatch) => void; /** Wave 60 base kit: hide or show a tab by id; hiding the last visible tab is refused. */ onTabVisibility: (tabId: string, visibility: "visible" | "hidden") => void; /** Persist the sheet-wide base height; wrap still raises individual rows. */ onRowHeight?: (height: number) => void; // ── W51-T17, ruling R7 ───────────────────────────────────────────────────────────────────── /** * ⭐⭐ Ctrl+PgUp AND Ctrl+PgDn's DOOR, AND IT IS OPTIONAL FOR THE SAME MERGE REASON THE FOUR * W51-T15 props and `onHideBands` are. The open tab is `SheetPage.tsx::tabId` and that file is * NOT in this ticket's fence, so a required prop would break lane C's tree at the merge. * * ⚠ AND THE KEY WORKS WITHOUT IT. Where the page has not wired this, the handler presses the * TAB BUTTON a person would press, in the workbook's own tab bar. That is a real press of a * real control rather than a second copy of the page's state, and it is stated here so the one * line that wires this prop is a tidy rather than a rescue. */ onSelectTab?: (tabId: string) => void; // ── W51-T19, contract C2, rulings R9 and R10 ─────────────────────────────────────────────── /** * ⭐⭐ THE OPTION ORDER A NON-METRIC COPY WALKS, AND IT IS A SEAM RATHER THAN A FETCH. * R13 applies the chosen driver's option order in every signed direction, which is schema, and * THIS COMPONENT IS * DELIBERATELY SCHEMA FREE: its own head note says so, and reaching for `fetchWorkspace` here * would make the grid know about databases so that one drag could work. * * The page loads this alongside `viewShadows`; absence is an explicit incomplete copy reported * by {@link boundDragLabel}, never a reason to guess an option or wrap to the beginning. */ options?: OptionCatalogue; /** Canonical saved-View filters loaded before a copy, for R5's local shadow materialisation. */ viewShadows?: readonly SavedViewShadow[]; // ── S67-T02, contract C1 ─────────────────────────────────────────────────────────────────── /** * The in-cell formula draft, for the formula bar to mirror while it is typed. Called with the * draft whenever this component's own editor opens or its draft changes (typing, a pointed * reference, an accepted suggestion, F4), and with `null` whenever that editor closes (commit, * Escape, unmount). Optional so a page that has not wired it compiles unchanged. */ onDraftChange?: (draft: string | null) => void; /** * S67-T07: the reader may view this workbook but not change it, so the cell menu SHOWS its edit * items disabled rather than hiding them. Absent reads as editable (the server still refuses). */ readOnly?: boolean; } /** The copied cells that must take the same save-then-compute path as Binding editor Save. */ export interface BoundEvaluationRequest { tabId: string; cells: Readonly>; } /** The corner mark each of R19's three states wears, plus the refusal. Colour rides a token; the * SHAPE carries the meaning too, so the three are told apart without relying on hue. */ const MARK_STYLE: Record = { "bound-fresh": { fill: "--lp-blue", corner: "tri" }, "bound-stale": { fill: "--lp-yellow-deep", corner: "tri" }, typed: { fill: "--lp-muted", corner: "dot" }, refused: { fill: "--lp-red-deep", corner: "bar" }, }; /** * ⭐ WAVE 54 BASE KIT — `tokenColour` (and its `TOKEN_CACHE`) NOW LIVE IN `cellBorders.ts`, which * is where the border paint went and is the only home this split's editing fence could reach. * Nothing about it changed: same memoised `getComputedStyle` read, same ink fallback, one cache. * `sheet/colors.ts` is the tidier home when a fence allows it; see that file's own note. */ /** glide hands back a union; every kind this grid offers carries its value in `data`. */ const typedText = (value: EditableGridCell): string => { const data = (value as { data?: unknown }).data; return data == null ? "" : String(data); }; /** An `AnchoredOverlay` anchor from one of glide's own cell or header rectangles. */ const rectAnchor = (bounds: Rectangle) => ({ left: bounds.x, top: bounds.y, right: bounds.x + bounds.width, bottom: bounds.y + bounds.height, width: bounds.width, height: bounds.height, }); // ── W52-T06 — point mode's pure geometry (PM-1..PM-18). No hooks, no closures over component // state: every one of these takes what it needs as an argument, which is what lets them sit // beside `rectAnchor` at module scope instead of being re-created on every render. ──────────── /** The four arrow keys' effect on a REAL, 1-based cell coordinate. */ const ARROW_DELTA: Record = { ArrowUp: { dCol: 0, dRow: -1 }, ArrowDown: { dCol: 0, dRow: 1 }, ArrowLeft: { dCol: -1, dRow: 0 }, ArrowRight: { dCol: 1, dRow: 0 }, }; /** PM-4: a reference is legal immediately after `=`, `(`, `,`, or an operator. */ const REF_POSITION_CHARS = new Set(["=", "(", ",", "+", "-", "*", "/", "^", "&", "<", ">"]); function isRefPosition(text: string, caret: number): boolean { if (caret <= 0) return false; return REF_POSITION_CHARS.has(text[caret - 1]); } /** `{col:2,row:5}` (1-based, `splitAddress`'s own shape) as the A1 text `"B5"`. */ function pointAddr(cell: { col: number; row: number }): string { return `${indexToCol(cell.col)}${cell.row}`; } /** PM-7: a Shift-extended proposal's text, one cell or a `"B4:B6"` range as the corners require. */ function pointRangeText(a: { col: number; row: number }, b: { col: number; row: number }): string { const col0 = Math.min(a.col, b.col); const col1 = Math.max(a.col, b.col); const row0 = Math.min(a.row, b.row); const row1 = Math.max(a.row, b.row); if (col0 === col1 && row0 === row1) return pointAddr({ col: col0, row: row0 }); return `${pointAddr({ col: col0, row: row0 })}:${pointAddr({ col: col1, row: row1 })}`; } /** * W57-T01: how far a whole-column or whole-row reference highlight paints, in one-based inclusive * coordinates on both axes. * * ⛔ A CONSTANT RATHER THAN THE SHEET'S OWN EXTENT, AND THAT IS A DELIBERATE TRADE. The two memos * that paint this band are pinned by `verify_formula_engine.py`'s RO-3 and RO-4 to close over the * edit state and the selection and nothing else, so a bound read off `tab` would add a third input * to both and cost the guarantee those legs exist to hold: that no outline can outlive the * reference or the editor that made it. A fixed span costs nothing anybody can see instead. It is * past `MAX_SHEET_COLS` (702), so a whole-ROW band is always complete; a whole-COLUMN band paints * its first thousand rows, which is roughly thirty screenfuls at the contract 1440x900 viewport, so * the column reads as highlighted at every scroll position a person reaches while editing one * formula. And it stays under the 4000-cell paint cap below, so the band always paints rather than * being skipped as pathological. */ const BAND_HIGHLIGHT_SPAN = 1000; /** What the right-click menu is open ON: a whole column, or the row and column of one cell. */ interface SheetMenu { anchor: ReturnType; /** 1 based, as `StructureOp.at` is. */ col: number; /** 1 based, or 0 when the menu was opened on a column header and no row is implied. */ row: number; /** * ⭐ W51-T17 / R14 — WHICH OF THE THREE SURFACES WAS RIGHT CLICKED. The column header, the row * header and a cell offer overlapping but different acts, and `row === 0` alone could only ever * say two of the three apart. The grid library reports a row marker as a CELL at column `-1`, * which is what makes the third one reachable at all. */ on: "cell" | "column" | "row"; } interface ViewHeaderMenu { anchor: AnchorRect; origin: string; field: string; item: Item; binding: ViewBinding; } // Accept the optional database prop while the shared panel arrives from its owning shard. const FilterBuilderPanel: (props: FilterBuilderPanelProps & { database?: string }) => ReturnType = SharedFilterBuilderPanel; /** A field's own filter vocabulary, in the same overlay and builder as the rest of the app. */ function ViewHeaderDropdown({ menu, onApply, onClose }: { menu: ViewHeaderMenu; onApply: (patch: Pick | Pick) => Promise; onClose: () => void; }) { const [fields, setFields] = useState(null); const [users, setUsers] = useState([]); const [error, setError] = useState(""); const [applying, setApplying] = useState(false); const pending = useRef(false); const initial = menu.binding.filter as FilterTree | undefined; const [filter, setFilter] = useState(() => ({ conj: filterTreeConj(initial), nodes: filterTreeNodes(initial), })); useEffect(() => { let live = true; const database = menu.binding.database; const scope = database === "customer_data" ? "customer" : database === "product_data" ? "product" : database.startsWith("ut_") ? database as SurfaceScope : null; void (async () => { const workspace = scope ? await fetchWorkspace(scope, { allowCached: true }) : null; if (!live) return; const catalogue = workspace?.fields; if (!catalogue?.some(field => field.key === menu.field)) { setError("The filter fields could not be loaded."); return; } // Keep other conditions' labels and types, while Add condition targets this header. setFields(catalogue.map(field => ({ ...field, filterable: field.key === menu.field && field.filterable !== false }))); setUsers(workspace?.userOptions ?? []); })().catch(() => { if (live) setError("The filter fields could not be loaded."); }); return () => { live = false; }; }, [menu.binding.database, menu.field]); const apply = async (patch: Pick | Pick) => { if (pending.current) return; pending.current = true; setApplying(true); try { if (await onApply(patch)) onClose(); } finally { pending.current = false; setApplying(false); } }; return (
{fields ? void apply({ filter })}>Apply filter } /> :
{error || "Loading filter…"}
}
); } /** What the find box is looking for and which match it is standing on. */ interface FindState { query: string; at: number; /** * ⭐ W54-T07 — WHAT REPLACE WOULD WRITE IN PLACE OF THE MATCH, and an empty string is a real * answer rather than a missing one: replacing a word with nothing is how a person deletes it * everywhere at once. */ replace?: string; /** * ⭐ W54-T07 — WHETHER THE PANEL WAS OPENED BY REPLACE RATHER THAN BY FIND. One box, two * shapes: Ctrl+F and the ribbon's Find item leave this absent and the panel shows what it * always showed, and the ribbon's Replace item sets it and the same panel grows a second * input plus its two buttons. A person who asked to FIND is never shown a field they did not * ask for, which is the whole reason this flag exists rather than the row always being there. */ replacing?: boolean; } /** What the row height or column width dialog is asking for, and what it opened with. */ interface NumberAsk { kind: "row-height" | "column-width"; value: number; } /** A REAL, 1-based cell coordinate -- `splitAddress`'s own shape, reused throughout point mode * because every reference `a1.ts::indexToCol`/`colToIndex` speaks is 1-based too. */ interface RealCell { col: number; row: number; } /** * ⭐⭐ W52-T06 — THE FLOATING FORMULA EDITOR'S WHOLE STATE (PM-1..PM-18, CR-1..CR-10). One record * rather than five booleans, so a stale combination (`mode: "point"` with no `pointCell`) cannot be * represented instead of merely being unlikely. */ interface FormulaEditState { /** The cell being edited. */ addr: string; /** W51-T34's frozen band is a SECOND `DataEditor`; `bandGridRef` owns its own screen space. */ inBand: boolean; /** The view `[col, row]` `getBounds()` is called with -- band-local when `inBand`. */ viewCell: readonly [number, number]; draft: string; caret: number; dropdownIndex: number; /** FA-23 #1: the dropdown is closed without touching `draft` (see `FormulaAssist`'s own note). */ dismissed: boolean; mode: "enter" | "point"; /** W57-T04: F2 toggles native caret arrows; explicit Ctrl reference gestures still work. */ caretOnly: boolean; /** PM-4's anchor: the EDITING cell, real 1-based coordinates. Never the selection. */ anchor: RealCell; /** Where in `draft` the live point-mode reference text starts, for PM-5's replace-not-append. */ insertStart: number | null; /** The single proposed cell while no Shift range is open. */ pointCell: RealCell | null; /** W57-T01: set when the live proposal is a whole column or row rather than a cell or * rectangle, so the dashed overlay can cover the band the same way the colour map does. */ pointBand: "column" | "row" | null; /** PM-7's range anchor once Shift extends the proposal; null outside a range. */ rangeAnchor: RealCell | null; } /** The gutter belongs to the grid, while the collapse state belongs to the document. */ export function RowOutline({ items, levels, onToggle }: { items: { group: SheetRowGroup; level: number; top: number; bottom: number }[]; levels: number; onToggle?: (id: string) => void; }) { if (levels === 0) return null; return
{items.map(({ group, level, top, bottom }) =>
{!group.collapsed && bottom - top > 24 && } {onToggle ? : }
)}
; } export default function SheetGrid({ eventScope = "", workbook: storedWorkbook, tab: storedTab, busy = false, panelOpen = false, onEdit, onViewRows, formulaBar, onRefresh, onSaveNow, onOpenImport, onCommit, openAt, onUndo, onRedo, onNotice, onEvaluateBindings, onSelect, onStructure, onGrow, onFreeze, onColumnWidth, onRowHeight, onHideBands, onRules, onCharts, onTabView, onTabVisibility, onRowGroups, onCreatePivot, onSelectTab, options, viewShadows, onDraftChange, readOnly = false, }: SheetGridProps) { const embedded = eventScope.startsWith("embed:"); const minimizeEvent = embedded ? `${NAV_MINIMIZE_EVENT}:${eventScope}` : NAV_MINIMIZE_EVENT; const panelEvent = embedded ? `aios:nav-panel:${eventScope}` : "aios:nav-panel"; const focusEvent = embedded ? `aios:sheet-focus-grid:${eventScope}` : "aios:sheet-focus-grid"; const storagePrefix = embedded ? eventScope : ""; const matchShortcut = useCallback((chord: Parameters[0]) => matchShortcutDefault(chord, storagePrefix), [storagePrefix]); const matchShortcutInGrid = useCallback((chord: Parameters[0], context: Parameters[1]) => matchShortcutInGridDefault(chord, context, storagePrefix), [storagePrefix]); /** * ⭐ THE CLIENT VIEW IS RECALCULATED FROM THE WHOLE WORKBOOK. This is a projection, not an * effect and not a write: opening a workbook creates no undo step, while a formula on Sheet1 * can paint from a changed Sheet2 cell as soon as the workbook object changes. */ const calculationSession = useRef(new WorkbookCalculationSession()); const workbook = useMemo( () => recalculateWorkbook(storedWorkbook, storedTab.id, calculationSession.current), [storedWorkbook, storedTab.id], ); const tab = workbook.sheets.find((sheet) => sheet.id === storedTab.id) ?? storedTab; // C3/R29: the existing structure door owns history and persistence. Serialize views so a // growing first view moves the next anchor before that next view resolves. No cell PATCH or // floating spill renderer participates in this path. const viewRefresh = useRef({ generation: 0, scope: "", key: "", busy: false, seen: new WeakSet() }); const viewContext = useRef({ storedWorkbook, storedTab, onStructure, onNotice }); viewContext.current = { storedWorkbook, storedTab, onStructure, onNotice }; const viewWritePending = useRef(false); const readViewRows = useRef(createViewRowsReader()); const [viewWriteRefresh, setViewWriteRefresh] = useState(0); useEffect(() => { const state = viewRefresh.current; return () => { state.generation++; state.key = ""; state.seen = new WeakSet(); }; }, []); useEffect(() => { const state = viewRefresh.current; const scope = `${storedWorkbook.id}/${storedTab.id}`; if (state.scope !== scope) { state.scope = scope; state.key = ""; state.seen = new WeakSet(); state.generation++; } const refreshed = state.busy && !busy; state.busy = busy; if (busy) { state.generation++; return; } const anchors = Object.entries(storedTab.cells ?? {}) .filter(([, cell]) => cell.kind === "bound" && cell.binding?.mode === "view" && (cell.binding.viewType === "grid" || !cell.binding.block)) .map(([addr]) => addr); if (!anchors.length) { state.generation++; state.key = ""; return; } const key = viewReadKey(storedTab); // History restores the original sheets array. Do not immediately redo an undone push. if (!refreshed && (key === state.key || state.seen.has(storedWorkbook.sheets))) { if (key !== state.key) state.generation++; // Undo also cancels a pending resolver answer. state.key = key; state.seen.add(storedWorkbook.sheets); return; } state.key = key; state.seen.add(storedWorkbook.sheets); const generation = ++state.generation; const current = () => state.generation === generation && state.scope === scope; void (async () => { let projected = storedWorkbook; let lastNotice = ""; const report = (message: string) => { lastNotice = message; viewContext.current.onNotice(message); }; let pending = anchors; while (pending.length && current()) { const origin = pending.shift()!; const target = projected.sheets.find(sheet => sheet.id === storedTab.id)!; const cell = (target.cells ?? {})[origin]; const at = splitAddress(origin); if (!at || cell?.kind !== "bound" || cell.binding?.mode !== "view") continue; const got = await readViewRows.current(projected.id, cell.binding as ViewBinding); if (!current()) return; if (!got.ok) { report(got.message); continue; } const op = viewRefreshOp(target, origin, got.answer); if (typeof op === "string") { report(op); continue; } const shiftAddress = (addr: string) => { for (const step of [op, ...(op.place?.also ? [op.place.also] : [])]) { if (step.delta) addr = shiftForStructure(addr, { sheet: target.name, axis: step.axis, at: step.at, delta: step.delta }, target.name); } return addr; }; const cells = op.place!.cells; const refusal = structureRefusal(projected, target.id, op); if (refusal) { report(refusal); continue; } if (!op.delta && !op.place!.also?.delta && Object.entries(cells).every(([addr, value]) => JSON.stringify((target.cells ?? {})[addr] ?? null) === JSON.stringify(value))) continue; projected = applyStructureWorkbook(projected, target.id, op); state.key = viewReadKey(projected.sheets.find(sheet => sheet.id === storedTab.id)!); // The prop returns the page's async structure operation at runtime. Awaiting it keeps // hydration/commit ordering intact without adding another history or save door. await viewContext.current.onStructure(op); if (!current()) return; pending = pending.map(shiftAddress).filter(addr => splitAddress(addr) !== null); } // A later successful view commits through the page, which clears its notice. Keep any // refused refresh visible after the batch as well as leaving that view's cells intact. if (current() && lastNotice) viewContext.current.onNotice(lastNotice); })().catch(() => { if (current()) viewContext.current.onNotice("The view rows could not be refreshed."); }); }, [storedWorkbook, storedTab, busy, viewWriteRefresh]); const pageView = tab.view?.pageView ?? "normal"; const pageGrid = useMemo(() => pageView === "normal" ? null : sheetPageGrid(workbook, tab.id, workbook.printSettings), [pageView, workbook, tab.id]); // Component-local heading dimensions deliberately shadow the former module names. Hiding // headings removes the column band and row gutter together with chart and frozen-band offsets. // Keep the HEADER_HEIGHT and ROW_MARKER_WIDTH JSX uses byte-for-byte: verify_api.py 6582/8237 // and verify_grid_ux.py 7728 pin those expressions, including the band's three-line block. const headingsVisible = tab.view?.headings !== false; const gridlinesVisible = tab.view?.gridlines !== false; /** Stored as a percent; canvas dimensions use this factor without a CSS transform. */ const zoom = Math.max(10, Math.min(400, Math.round(tab.view?.zoom ?? 100))) / 100; const HEADER_HEIGHT = headingsVisible ? Math.round(SHEET_HEADER_HEIGHT * zoom) : 0; const ROW_MARKER_WIDTH = headingsVisible ? Math.round(SHEET_ROW_MARKER_WIDTH * zoom) : 0; // Copy the shared theme when hiding gridlines: the Data module uses lightTheme too. const gridTheme = useMemo(() => { const base = !gridlinesVisible ? { ...lightTheme, borderColor: "transparent", horizontalBorderColor: "transparent" } : lightTheme; // Ten points is the document's default, not an approximation copied from glide's theme. // Both fonts scale together: glide restores the cell font before drawing headers. const pixels = Math.round(fontPx(DEFAULT_FONT_PT) * zoom); return { ...base, baseFontStyle: `${pixels}px`, headerFontStyle: `600 ${pixels}px` }; }, [gridlinesVisible, zoom]); /** * ⛔⛔ S64-T16 / owner instruction 9 - THE ROW NUMBER MUST NOT RESIZE WHEN ITS ROW IS PICKED. * `.sheet-active-row-header` REDRAWS the row marker over glide's own canvas marker, so the two * have to agree on face, weight AND size or selecting a row visibly grows its number. Glide * draws a marker with `theme.markerFontStyle`, whose library default is `9px` * (`glide-data-grid/common/styles.js`), and `gridTheme` above deliberately does not override it: * unlike cell and header text the marker is therefore NOT scaled by `zoom`. Read the value back * out of the theme rather than restating `9` at the overlay, so a later wave that does set * `markerFontStyle` moves both halves in one edit instead of re-opening this defect. */ const markerFontPx = Number.parseFloat(gridTheme.markerFontStyle ?? "9px") || 9; const [selection, setSelection] = useState(undefined); /** The live value used to floor glide's empty Escape payload without adding selection state. */ const selectionRef = useRef(undefined); /** Pointer and keyboard provenance for selection callbacks emitted by glide itself. */ const pointerSelectingRef = useRef(false); const keyboardSelectingRef = useRef(false); /** * S64-T23 / ruling R10: a header drag is a range of the one axis selection. * These refs track the gesture; there is no second selection model. * The frozen band is covered because `axisBand` already starts at `-bandRows`. */ /** * S64-T23: the column header the pointer is over, with the rectangle it was reported at. * THE RECTANGLE IS NOT DECORATION. Glide skips `onItemHovered` entirely when the pointer has * not changed what it is over (`mouseEventArgsAreEqual`), so this ref is NOT cleared by every * press. The press re-checks that it actually landed inside this rectangle, which is what stops * a stale header from opening a drag on a cell. */ const headerHoverColRef = useRef<{ col: number; rect: Rectangle } | null>(null); /** S64-T23: the live header drag. `anchor` is the column pressed, `last` the column the * pointer is over, `moved` whether the drag ever left the anchor column. */ const headerDragRef = useRef<{ anchor: number; last: number; moved: boolean } | null>(null); /** The border press owns the release too, even if Glide reports it over another header. */ const headerBorderPressRef = useRef(false); // Each canvas owns its marker hover; an out-of-bounds report from its peer cannot clear it. const rowHoverRef = useRef<{ row: number; rect: Rectangle }[]>([]); const rowBorderPressRef = useRef(false); const [rowBorderHover, setRowBorderHover] = useState<{ row: number; rect: Rectangle } | null>(null); const headerPressXRef = useRef(null); /** C9: a panel temporarily folds the rail; only transitions signal its existing listener. */ const panelNavOpenRef = useRef(false); useEffect(() => { if (panelNavOpenRef.current === panelOpen) return; panelNavOpenRef.current = panelOpen; window.dispatchEvent(new CustomEvent(panelEvent, { detail: { open: panelOpen } })); }, [panelEvent, panelOpen]); useEffect(() => () => { if (!panelNavOpenRef.current) return; panelNavOpenRef.current = false; window.dispatchEvent(new CustomEvent(panelEvent, { detail: { open: false } })); }, [panelEvent]); /** Workbook and tab identity, never workbook object identity, owns the one opening selection. */ const openedSelectionRef = useRef(""); /** * A same-place workbook replacement can make glide offer its default A1 while reconciling the * new data object. Remember the selection that was live immediately before that render so the * one callback caused by reconciliation can be distinguished from ordinary navigation. * * This comparison happens during render deliberately: glide may reconcile in its own layout * work before a parent effect could arm the handoff. The handoff contains no drawn state and is * consumed by the next selection event, so later reader input is never pinned. */ const reconciledWorkbookRef = useRef<{ object: Workbook; key: string } | null>(null); const replacementSelectionRef = useRef(null); const renderedWorkbookKey = `${workbook.id}:${tab.id}`; const reconciledWorkbook = reconciledWorkbookRef.current; if (!reconciledWorkbook || reconciledWorkbook.object !== workbook || reconciledWorkbook.key !== renderedWorkbookKey) { const samePlace = reconciledWorkbook?.object.id === workbook.id && reconciledWorkbook.key === renderedWorkbookKey; const current = selectionRef.current; replacementSelectionRef.current = samePlace && current?.current ? current : null; reconciledWorkbookRef.current = { object: workbook, key: renderedWorkbookKey }; } /** * ⭐⭐ W54-T28 / R9(iv) — THE TAB RUN'S MEMORY, AND THE ONE BIT THAT SAYS WHO MOVED. * * `tabRunAt` holds the column a run of Tabs STARTED at, so the Enter that ends the run can * return to it; `shortcuts.ts::tabRunOrigin` owns the rule for what it becomes on each press. * `commitNav` is raised for exactly one selection change by the canvas commit arm and consumed * in `onSelectionChange` below. Editor commits restore their run after that door resets it. * * ⛔ THE FLAG IS WHY THE RESET CAN LIVE IN `onSelectionChange` AT ALL. The done-when asks the * run to reset when the selection moves by anything other than Tab, and that handler is the ONE * door every move goes through - an arrow, a click, the name box, Ctrl+End, a header pick. But * a Tab goes through it too, so without a way to tell the run's own move apart from everybody * else's, the very press that opened the run would immediately close it. * * ⛔ REFS, NOT STATE, AND THAT IS DELIBERATE. Neither one is drawn, and a state update here * would re-render the whole grid on every Tab; worse, `onSelectionChange` would then read the * flag from a stale closure in the same batch that set it. */ const tabRunAt = useRef(null); const commitNav = useRef(false); const overlayCommit = useRef<{ dir: CommitDirection; at: number; from: Item } | null>(null); /** * W59-T02 / R4: the Ctrl+A run remembers its sheet anchor and consecutive press count. * Its own selection must preserve the run, so `selectAllNav` is consumed once at the same * selection door as `commitNav`. A separate flag matters: a Tab commit must end this run. */ const selectAllRunAt = useRef<{ col: number; row: number; count: number } | null>(null); const selectAllNav = useRef(false); /** * ⭐ W51-T17 — THE TWO SURFACES THE KEYBOARD OPENS, and both live INSIDE this component's own * box rather than in a portal: portalling drops every descendant-scoped rule with no error at * all, and neither of these belongs anywhere but over the grid it is reading. */ const [shortcuts, setShortcuts] = useState(false); const [find, setFind] = useState(null); /** * ⛔ THE WRAPPER, SO Ctrl+1 CAN PRESS THE RIBBON'S OWN BUTTON. Contract C1 says the keyboard * and the ribbon reach the SAME Number format menu, and that menu's open state lives inside * `Ribbon.tsx`, which is not this ticket's file and offers no prop for it. The one thing a * ticket may do from outside a component is what a person does: press its control. */ const wrapRef = useRef(null); /** glide's own handle, for the ONE thing a controlled selection cannot do: scroll to itself. */ const gridRef = useRef(null); /** * ⭐ W52-T06 — THE FROZEN BAND'S OWN HANDLE. It mounts a SECOND, separate `DataEditor` * (W51-T34's own note above explains why), so `gridRef.current.getBounds()` reports the MAIN * canvas's screen rect and would misplace the floating formula editor for a cell inside the * band by the band's own height. `openFormulaEditor` reads whichever ref actually owns the row. */ const bandGridRef = useRef(null); const frozenBandRef = useRef(null); // One post-frame pass repairs boundaries, then paints each spill owner. The callback never // queues itself, so this settles after one frame instead of creating a canvas animation. const spillPaintQueue = useRef(new Map void>()); const borderPaintQueue = useRef(new Map void>()); const borderPaintViewports = useRef(new WeakMap()); const borderRowLayout = useRef<{ offsets: number[]; heightAt: (index: number) => number } | null>(null); const spillPaintFrame = useRef(null); // Selection renders can precede the deferred text frame while Glide only blits its cells. // Document/geometry changes invalidate queued text below; selection alone keeps that run. const queueSpillPaint = useCallback((key: string, paint: () => void, border = false) => { (border ? borderPaintQueue : spillPaintQueue).current.set(key, paint); if (spillPaintFrame.current !== null) return; spillPaintFrame.current = window.requestAnimationFrame(() => { spillPaintFrame.current = null; const borders = [...borderPaintQueue.current.values()]; borderPaintQueue.current.clear(); for (const paint of borders) paint(); const paints = [...spillPaintQueue.current.values()]; spillPaintQueue.current.clear(); for (const run of paints) run(); }); }, []); useEffect(() => () => { if (spillPaintFrame.current !== null) window.cancelAnimationFrame(spillPaintFrame.current); spillPaintFrame.current = null; spillPaintQueue.current.clear(); borderPaintQueue.current.clear(); }, []); /** PageUp/PageDown use the body viewport even when the frozen band currently owns focus. */ const bodyPageRowsRef = useRef(1); // ⛔ THE FIND BOX'S CLOSE, THROUGH THE ONE ARBITER. Declared here, beside the state it closes, // and unconditionally, so the hook order never changes between renders. useEscapeClose(find !== null, () => setFind(null)); // Undefined awaits selection bounds; null preserves an explicit dismissal. const [anchor, setAnchor] = useState(undefined); const [menu, setMenu] = useState(null); // S68-T28: clipboard knowledge belongs to this opening, never to the previous menu. const [menuClipboard, setMenuClipboard] = useState<{ owner: SheetMenu; empty: boolean } | null>(null); // S67-T07: the cell menu's New Comment / New Note and Link open these, over the anchor cell. const [noteAsk, setNoteAsk] = useState<{ addr: string; text: string } | null>(null); const [linkAsk, setLinkAsk] = useState(null); const [viewMenu, setViewMenu] = useState(null); const viewMenuRef = useRef(null); const [filterState, setFilterState] = useState(null); const sheetFilter = filterState?.scope === renderedWorkbookKey ? filterState : null; const [filterMenu, setFilterMenu] = useState<{ col: number; anchor: AnchorRect } | null>(null); useEffect(() => { setFilterState(null); setFilterMenu(null); }, [workbook.id, tab.id]); /** * ⭐ THE FORMAT PAINTER'S WHOLE STATE: the style it picked up, waiting for the click that lands * it. `null` means the painter is off, so one value carries both the mode and its payload and * there is no second flag to fall out of step with it. */ const [painter, setPainter] = useState(null); const [ask, setAsk] = useState(null); /** * ⛔ W54-T21 — THE ROW HEIGHT / COLUMN WIDTH DIALOG CLOSES THROUGH THE ARBITER. It used to read * Escape off its own number input, which is the local-handler shape DESIGN.md section 4 names * as the defect: a `role="dialog"` deciding for itself whether it may act. Declared beside the * state it closes, and unconditionally, so the hook order never changes between renders. */ useEscapeClose(ask !== null, () => setAsk(null)); /** * ⭐⭐ W51-T34 / R17 — WHAT THE FREEZE PANES PANEL IS ASKING FOR. Two counts, held together * rather than as two states, because `setFreeze` merges a patch into the record it already has * and answering one of them alone would silently keep whatever the other one was. */ const [freezeAsk, setFreezeAsk] = useState<{ rows: number; cols: number } | null>(null); /** * ⛔ W54-T21 — AND THE FREEZE PANES PANEL, for the same reason and through the same door. It * carried the Escape branch TWICE, once on each of its two number inputs, which is precisely * the drift a single arbiter entry removes: two copies of one rule can disagree. */ useEscapeClose(freezeAsk !== null, () => setFreezeAsk(null)); const [localRowHeight, setLocalRowHeight] = useState({ tabId: tab.id, height: ROW_HEIGHT }); const rowHeight = tab.rowHeight ?? (localRowHeight.tabId === tab.id ? localRowHeight.height : ROW_HEIGHT); const setRowHeight = useCallback((height: number) => { if (onRowHeight) onRowHeight(height); else setLocalRowHeight({ tabId: tab.id, height }); }, [onRowHeight, tab.id]); /** * ⛔ THE HIDDEN BANDS, KEYED BY TAB. A local override exists because the persistence door * (`onHideBands`) is optional until the page wires it, and it carries its own `tabId` so * switching tabs cannot show one sheet's hidden rows on another's grid. */ const [hiddenLocal, setHiddenLocal] = useState<{ tabId: string; rows: number[]; cols: number[] } | null>(null); /** * ⛔⛔ A DRAG IS LOCAL UNTIL IT ENDS, AND THAT IS NOT A POLISH DETAIL. Every commit in this * module is one PUT carrying the `rev` it read, serialised behind one promise, and * `put_workbook` REFUSES a stale rev. `onColumnResize` fires on every mousemove, so committing * there would queue dozens of saves per drag and the reader would watch the reload notice fire. * The dragging width lives here; `onColumnResizeEnd` commits once. */ const [dragWidth, setDragWidth] = useState<{ cols: number[]; width: number } | null>(null); /** A row drag moves only this hairline until release, so it queues exactly one save. */ const [dragRowGuide, setDragRowGuide] = useState(null); const rowResizeGesture = useRef<{ rows: number[]; startY: number; bottom: number; height: number; size: number; zoom: number; moved: boolean; pointerId: number; scope: string; } | null>(null); // Glide clamps resize callbacks to >=20px even with minColumnWidth=0. Keep the pointer's // actual width until release, and give both canvases a positive hairline during the gesture. const resizeGesture = useRef<{ left: number; scale: number; width: number; cols: number[]; committed: boolean; startX: number; moved: boolean; } | null>(null); useEffect(() => { const track = (event: MouseEvent) => { const gesture = resizeGesture.current; if (gesture && !gesture.committed) { if (event.clientX !== gesture.startX) gesture.moved = true; if (!gesture.moved) return; gesture.width = Math.max(MIN_COL_WIDTH * zoom, Math.min(MAX_COL_WIDTH * zoom, (event.clientX - gesture.left) / gesture.scale)); } }; window.addEventListener("mousemove", track, true); window.addEventListener("mouseup", track, true); return () => { window.removeEventListener("mousemove", track, true); window.removeEventListener("mouseup", track, true); }; }, [zoom]); // ── W51-T18: the two surfaces this ticket adds, and the one local fallback it needs ───────── /** R8's Styles group is conditional formatting's ONLY door, and this is what it opens. */ const [rulesOpen, setRulesOpen] = useState(false); /** * ⛔⛔ THE LOCAL RULE LIST EXISTS ONLY BECAUSE THE PERSISTENCE DOOR MIGHT NOT, AND IT HAS TO * STOP EXISTING THE MOMENT THE DOOR ARRIVES. With `onRules` wired the DOCUMENT is the single * answer; a local copy would outlive the state it mirrored and win forever, so a Ctrl+Z that * restored `tab.rules` would repaint the grid from a stale list with nothing on the screen to * explain it. Same shape as `hiddenLocal` above, and for the same reason. */ const [rulesLocal, setRulesLocal] = useState<{ tabId: string; rules: SheetRule[] } | null>(null); /** * ⭐ W54-T10 / LANE B — the chart list's local fallback, the same shape as `rulesLocal` above and * kept for exactly the reason that one is: it exists only while the page has not wired * `onCharts`, and it yields to the document the moment the page has. */ const [chartsLocal, setChartsLocal] = useState<{ tabId: string; charts: SheetChartSpec[] } | null>(null); /** The one existing chart whose persisted range and kind are open in the shared dialog. */ const [chartEditId, setChartEditId] = useState(null); const [selectedChartId, setSelectedChartId] = useState(null); /** The validation list editor: which addresses it will write, and what the anchor holds now. */ const [listAsk, setListAsk] = useState<{ addrs: string[]; list: string[] } | null>(null); /** The dropdown cell editor: the address it belongs to, where it sits, and its search text. */ const [dropdown, setDropdown] = useState<{ addr: string; anchor: ReturnType; query: string } | null>(null); /** W52-T06 — the floating formula editor. `null` means no formula is being authored right now. */ const [formulaEdit, setFormulaEdit] = useState(null); const formulaInputRef = useRef(null); const formulaPointer = useRef<{ pointerId: number; anchor: RealCell; last: RealCell; scope: string; } | null>(null); useEffect(() => { if (!formulaEdit || formulaPointer.current?.scope !== renderedWorkbookKey) formulaPointer.current = null; }, [formulaEdit, renderedWorkbookKey]); const formulaSizerRef = useRef(null); const formulaCaretSizerRef = useRef(null); const formulaCaretPrefixRef = useRef(null); const [formulaBox, setFormulaBox] = useState<{ width: number; height: number } | null>(null); /** S67-T02: how far the grown editor is moved to stay inside the pane (never positive). */ const [formulaShift, setFormulaShift] = useState<{ dx: number; dy: number } | null>(null); const [formulaCaretOffset, setFormulaCaretOffset] = useState<{ x: number; y: number }>(); /** * ⭐⭐ W54-T21 / INSTRUCTION 18 — THE ONE FLAG THAT STOPS ESCAPE COMMITTING WHAT IT CANCELLED. * * ⛔⛔ THE ARBITER BLURS BEFORE IT CLOSES, AND THIS EDITOR'S BLUR IS ITS COMMIT DOOR. Read * `ui/useEscapeClose.ts`: the one capture-phase handler takes the focused element, calls blur * on it, and only THEN calls the topmost entry's close. The floating input's blur is what * commits a formula on a click away, so a naive registration would make Escape write the very * draft it was pressed to throw away - the exact opposite of instruction 18. * * ⛔ SO THE BLUR DOOR DEFERS ITS DECISION BY ONE MICROTASK, WHICH IS DETERMINISTIC AND NOT A * RACE. `blur` then `close` are two statements of ONE synchronous handler, and a microtask * queued inside the first cannot run until that whole handler has returned. The close therefore * always gets to raise this flag first. A frame or a timeout would be a guess; a microtask is * an ordering guarantee. * * ⚠ IT IS RAISED BY BOTH ESCAPE OUTCOMES, not only by the abandon. The first Escape over an * open suggestion list dismisses the LIST and keeps the edit alive (FA-23 #1), and that press * blurs the input just the same, so it has to suppress the commit too or the two-stage ladder * would commit on its first rung. */ const formulaEscaping = useRef(false); /** * ⭐⭐ W53-T02 / INSTRUCTION 11 — EVERY EXIT PATH RETURNS TO READY, AND THE KEYBOARD HAS TO * COME WITH IT. Excel's four cell modes (Ready/Enter/Edit/Point) all fall back to Ready on any * commit, and in Ready the ARROW KEYS MOVE THE GRID SELECTION. Here that only happens while * the grid's own accessibility element holds the keyboard. * * ⛔ MEASURED, NOT ASSUMED. Driving the real app: while editing, `document.activeElement` is * this file's floating ``; one Enter later it is * `BODY`, and the very next ArrowRight moves nothing (E7 stayed E7). Clicking the canvas put * focus back on glide's own `TD` and the same ArrowRight then moved C10 to D10. So the defect * was never a swallowed keydown: the floating editor is NOT glide's own cell overlay (the * block below the render says why), so when it unmounts nothing hands the keyboard back and * the browser parks focus on ``. * * ⛔ IT RUNS OFF `formulaEdit` GOING NON-NULL -> NULL, NOT OFF ANY ONE KEY. That is what covers * Enter, Tab, blur, click-away, Escape and a throw mid-commit THE SAME WAY, with no per-path * duplication: every one of them ends in `setFormulaEdit(null)`, so this is the one place their * effects converge. The ref remembers which grid was in use, because by the time the effect * sees `null` the state that said so is gone. * * ⚠ AND IT NEVER STEALS. It acts only when nothing else took the focus (`` is the * browser's own "the focused node was removed" answer), so clicking a ribbon button or the * formula bar mid-edit still commits and still leaves that control focused. */ const formulaGridWasBand = useRef(false); const formulaWasOpen = useRef(false); useEffect(() => { if (formulaEdit) { formulaWasOpen.current = true; formulaGridWasBand.current = formulaEdit.inBand; return; } if (!formulaWasOpen.current) return; formulaWasOpen.current = false; const active = document.activeElement; if (active !== null && active !== document.body) return; (formulaGridWasBand.current ? bandGridRef : gridRef).current?.focus(); }, [formulaEdit]); // S67-T02 / C1: ONE effect keyed on the draft reports every path that changes it, and every // exit (each ends in `setFormulaEdit(null)`) reports `null`. The ref keeps a new callback // identity from re-firing an unchanged draft; the unmount cleanup covers a closed tab. const onDraftChangeRef = useRef(onDraftChange); onDraftChangeRef.current = onDraftChange; const formulaDraft = formulaEdit ? formulaEdit.draft : null; useEffect(() => { onDraftChangeRef.current?.(formulaDraft); }, [formulaDraft]); useEffect(() => () => onDraftChangeRef.current?.(null), []); const extent = sheetExtent(tab); const widths = tab.colWidths ?? {}; // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⛔⛔ W51-T16 — TWO COORDINATE SYSTEMS MEET IN THIS COMPONENT, AND MIXING THEM ADDRESSES THE // WRONG CELL WITH NO ERROR OF ANY KIND. // // glide counts the rows and columns IT DRAWS. Once a row is hidden, glide's row 3 is no longer // the sheet's row 4: it is the fourth VISIBLE row, which may be row 5 or row 12. So every // number that arrives from the library is a VIEW index and has to be translated before it can // become an A1 address, a `StructureOp.at`, or anything else that means a place in the sheet. // // ⭐ `visRows` AND `visCols` ARE THE ONE TRANSLATION TABLE. Position `i` holds the real // zero-based index that glide's `i` stands for. With nothing hidden they are the identity, // which is exactly why a proof driven only in that state proves nothing: `sheetState.ts`'s node // test drives `visibleIndices` with a band actually hidden. // // ⛔ AND THIS IS WHY `addressesIn` IS NOT USED FOR A SELECTION ANY MORE. A rectangle of VIEW // coordinates is not a rectangle of real ones: hide row 5 inside a selection of rows 3 to 8 and // the real addresses are no longer contiguous. `addressesInView` maps every corner cell one at // a time instead of building a range and hoping. // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⛔⛔ THE LOCAL BAND EXISTS ONLY BECAUSE THE PERSISTENCE DOOR MIGHT NOT, AND IT HAS TO STOP // EXISTING THE MOMENT THE DOOR ARRIVES. With `onHideBands` wired, the DOCUMENT is the single // answer: a local copy would outlive the state it mirrored and win forever, so a Ctrl+Z that // restored `tab.hiddenRows` would repaint the grid with a stale band and the rows would stay // hidden with nothing on the screen to explain why. Two writers, one state, and this is the // half that must yield. const localRows = hiddenLocal?.tabId === tab.id ? hiddenLocal.rows : tab.hiddenRows; const localCols = hiddenLocal?.tabId === tab.id ? hiddenLocal.cols : tab.hiddenCols; const hiddenRows = (onHideBands ? tab.hiddenRows : localRows) ?? []; const hiddenCols = (onHideBands ? tab.hiddenCols : localCols) ?? []; // ⛔ W51-T18: THE SAME TWO-WRITERS RULE, FOR THE SAME REASON. The document wins the moment the // page has wired `onRules`; the local list is only ever the fallback while it has not. const localRules = rulesLocal?.tabId === tab.id ? rulesLocal.rules : tab.rules; const rules = (onRules ? tab.rules : localRules) ?? []; // ⭐ W54-T10 / lane B: THE SAME TWO-WRITERS RULE AGAIN, for the charts the Insert tab appends. // Read as one expression here so the anchor loop below has exactly one list to draw, whichever // writer produced it. const localCharts = chartsLocal?.tabId === tab.id ? chartsLocal.charts : tab.charts; const charts = (onCharts ? tab.charts : localCharts) ?? []; const editingChart = charts.find((chart) => chart.id === chartEditId) ?? null; const copyChartImageToClipboard = useCallback((chartId: string) => { const chart = charts.find(item => item.id === chartId); if (!chart) return; copyChartImage(workbook, tab, chart).catch(() => onNotice("That chart could not be copied as an image.")); }, [charts, onNotice, tab, workbook]); /** * The one chart writer. Insert, settings, drag and structure all replace the same tab-level list, * so a local fallback cannot disagree with the document depending on which gesture produced it. */ const writeCharts = useCallback((next: SheetChartSpec[]) => { if (!onCharts) { setChartsLocal({ tabId: tab.id, charts: next }); onNotice("This chart sits on the sheet for as long as it stays open. Saving it with the " + "workbook arrives with the page's own door."); return; } onCharts(next); }, [onCharts, onNotice, tab.id]); useEffect(() => setChartEditId(null), [tab.id]); // ⚠ MEMOISED ON A STRING KEY, not on the array. A hidden band is rebuilt on every render (it is // read through two `??`s), so an array in the dependency list would be a new object every time // and the memo would rebuild a 100,000 entry table per keystroke on a grown sheet. const rowGroups = useMemo(() => tab.rowGroups ?? [], [tab.rowGroups]); const filterHiddenRows = useMemo(() => sheetFilterHiddenRows(tab, sheetFilter), [tab, sheetFilter]); const effectiveHiddenRows = useMemo(() => [...new Set([ ...outlineHiddenRows(hiddenRows, rowGroups), ...filterHiddenRows, ])].sort((a, b) => a - b), // Manual membership is value-keyed just like the existing display map. // eslint-disable-next-line react-hooks/exhaustive-deps [hiddenRows.join(","), rowGroups, filterHiddenRows]); const hiddenRowsKey = effectiveHiddenRows.join(","); const hiddenColsKey = hiddenCols.join(","); const allVisRows = useMemo( () => visibleIndices(extent.rows, hiddenRowsKey ? hiddenRowsKey.split(",").map(Number) : []), [extent.rows, hiddenRowsKey], ); const visCols = useMemo( () => visibleIndices(extent.cols, hiddenColsKey ? hiddenColsKey.split(",").map(Number) : []), [extent.cols, hiddenColsKey], ); // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W51-T34 / R17 — A THIRD COORDINATE SYSTEM, AND IT IS THE CHEAPEST OF THE THREE. // // glide 6.0.3 has NO leading-row freeze: `freezeTrailingRows` pins rows at the BOTTOM and // nothing pins them at the top, which is why wave 50 shipped no control at all rather than a // dead one. R17 settles that: the frozen rows are drawn by a SECOND `DataEditor` mounted above // the first and scrolled with it, and this is where the sheet's rows are split between them. // // ⭐ THE SPLIT IS A SLICE, AND THAT IS THE WHOLE REASON EVERY OTHER LINE IN THIS FILE IS // UNCHANGED. `visRows` keeps meaning exactly what it meant, the rows the MAIN grid draws, so // `rows={visRows.length}`, `realRow`, `viewIndexOf`, the chart anchors and all thirty // shortcuts keep speaking one coordinate system. What is new is `headRows`, the band above it. // // ⛔ A BAND ROW IS A NEGATIVE MAIN-GRID ROW, and that convention is the price of ONE selection. // The header grid hands its own zero based rows back through `fromBand`, which subtracts the // band size, so a cell in the band arrives everywhere else as a row between `-band` and `-1`. // `realRow` is the ONE place that has to know, which is why it is the only one that does. // ═══════════════════════════════════════════════════════════════════════════════════════════ const frozenCols = frozenBandSize(visCols, tab.freeze?.cols ?? 0); const frozenRows = tab.freeze?.rows ?? 0; /** How many DRAWN rows the frozen band covers. Not `freeze.rows` once a row inside it hides. */ const bandRows = frozenBandSize(allVisRows, frozenRows); /** The rows the HEADER grid draws, in its own zero based order. */ const headRows = useMemo(() => allVisRows.slice(0, bandRows), [allVisRows, bandRows]); /** The rows the MAIN grid draws. The band has already been taken off the front. */ const visRows = useMemo(() => allVisRows.slice(bandRows), [allVisRows, bandRows]); /** glide's column index, as the SHEET's own zero-based column. */ const realCol = useCallback((view: number) => visCols[view] ?? view, [visCols]); /** * glide's row index, as the SHEET's own zero-based row. * * ⛔ A NEGATIVE VIEW ROW IS THE FROZEN BAND, counted back from its end: `-1` is the last frozen * row and `-band` the first. Falling through to `?? view` for those would address row minus one * with no error of any kind, which is why the branch is explicit rather than arithmetic. */ const realRow = useCallback( (view: number) => (view < 0 ? (headRows[headRows.length + view] ?? headRows[0] ?? 0) : (visRows[view] ?? view)), [headRows, visRows], ); /** * ⭐⭐ W51-T34 — THE INVERSE OF `realRow`, AND IT IS THE HALF THAT GETS MISSED. * * Three acts turn a SHEET row back into a view row: the find walk, Ctrl+arrow's edge jump and * Ctrl+End. They searched `visRows`, which since this ticket no longer contains the frozen * rows at all, and `viewIndexOf` does not FAIL on a miss: it returns the nearest visible row at * or below, which for anything in the band is 0. So a find that landed on a frozen row, or * Ctrl+End on a sheet whose last used cell is inside the band, would have selected THE FIRST * BODY ROW and said nothing. With one row frozen that happens to be the row below, which is * close enough to pass a screenshot and wrong on every sheet with two. * * ⛔ SO IT SEARCHES THE WHOLE TABLE AND THEN SUBTRACTS THE BAND, which lands a frozen row on * the negative index `realRow` and `fromBand` already speak, between `-bandRows` and `-1`. */ const viewRowOf = useCallback( (real: number) => viewIndexOf(allVisRows, real) - bandRows, [allVisRows, bandRows], ); /** * ⭐ HOTFIX 2026-09-24: THE NUMBER glide's ROW MARKER PAINTS, AS THE SHEET'S OWN ROW. * glide paints `rowMarkerStartIndex + drawnRow`, blind to hidden rows, so an imported workbook * hiding rows 8 to 26 labelled sheet row 31 as 12 while the name box said F31. ONE function * serves both mounts: the main grid starts at `bandRows + 1` and the band at 1, and in both * cases `shown - bandRows - 1` is exactly the view row `realRow` already speaks (negative in * the band), so the marker, the name box and the selected row's overlay read one number. */ const rowLabel = useCallback((shown: number) => realRow(shown - bandRows - 1) + 1, [realRow, bandRows]); /** The A1 address glide's cell stands for. THE one door from a view coordinate to an address. */ const addrAt = useCallback( (col: number, row: number) => addressOf(realCol(col), realRow(row)), [realCol, realRow], ); /** * ⛔ THE HEADER GRID'S OWN ROW, AS THE MAIN GRID'S. The band grid counts its rows from zero; * everything else in this component counts the main grid's, so the two are told apart by the * SIGN and this is the one door that converts. Every callback the band grid is given is this * function wrapped round the callback the main grid already had, which is what keeps one * selection, one commit door and one paint for both. */ const fromBand = useCallback((item: Item): Item => [item[0], item[1] - bandRows], [bandRows]); /** Every address a VIEW rectangle covers, one cell at a time. See the note above. */ const addressesInView = useCallback((range: CellRange): string[] => { const out: string[] = []; for (let r = Math.min(range.row0, range.row1); r <= Math.max(range.row0, range.row1); r += 1) { for (let c = Math.min(range.col0, range.col1); c <= Math.max(range.col0, range.col1); c += 1) { out.push(addrAt(c, r)); } } return out; }, [addrAt]); const columns = useMemo( () => visCols.map((real, i) => { const letters = indexToCol(real + 1); return { title: letters, id: String(real), width: Math.max(1, dragWidth?.cols.includes(i) ? dragWidth.width : Math.round(lastVisibleWidth(tab, real) * zoom)), }; }), [dragWidth, visCols, tab, zoom], ); const spillWidths = useMemo(() => columns.map(column => column.width / zoom), [columns, zoom]); /** The x offset of one column, summed rather than multiplied: widths differ now. */ const columnX = useCallback( (index: number) => columns.slice(0, index).reduce((x, c) => x + c.width, ROW_MARKER_WIDTH), [columns, ROW_MARKER_WIDTH], ); const cells = tab.cells ?? {}; const borderPaintDocument = useMemo(() => ({}), [workbook.id, tab.id, tab.cells, tab.colWidths, tab.rowHeights, hiddenRowsKey, hiddenColsKey, extent.rows, extent.cols, zoom, frozenCols, bandRows, headingsVisible, rowHeight, dragWidth]); const borderPaintDocumentRef = useRef(borderPaintDocument); // Invalidate before the child grids draw the replacement document, not in a parent effect // (which would discard the child's new layout-effect paints as well). if (borderPaintDocumentRef.current !== borderPaintDocument) { borderPaintDocumentRef.current = borderPaintDocument; borderPaintQueue.current.clear(); borderPaintViewports.current = new WeakMap(); } const spillPaintRules = onRules ? tab.rules : localRules; const spillPaintDocument = useMemo(() => ({}), [borderPaintDocument, tab, workbook.sheets, spillPaintRules, sheetFilter]); const spillPaintDocumentRef = useRef(spillPaintDocument); if (spillPaintDocumentRef.current !== spillPaintDocument) { spillPaintDocumentRef.current = spillPaintDocument; spillPaintQueue.current.clear(); } /** Imported merged ranges reserve their cells even though the client does not merge-paint them. */ const mergedSpillRanges = useMemo(() => { const raw = tab.excel?.mergedCells; if (!Array.isArray(raw)) return [] as { col0: number; row0: number; col1: number; row1: number }[]; return raw.flatMap((value) => { const [from, to = from] = String(value).replace(/\$/g, "").split(":", 2); const a = splitAddress(from); const b = splitAddress(to); if (!a || !b) return []; return [{ col0: Math.min(a.col, b.col) - 1, row0: Math.min(a.row, b.row) - 1, col1: Math.max(a.col, b.col) - 1, row1: Math.max(a.row, b.row) - 1, }]; }); }, [tab.excel]); const blocksSpill = useCallback((col: number, row: number) => { const cell = cells[addrAt(col, row)]; if (cell?.style?.wrap) return true; const documentCol = realCol(col); const documentRow = realRow(row); if (sheetFilter && documentRow === sheetFilter.headerRow && documentCol >= sheetFilter.col0 && documentCol <= sheetFilter.col1) return true; return mergedSpillRanges.some(range => documentCol >= range.col0 && documentCol <= range.col1 && documentRow >= range.row0 && documentRow <= range.row1); }, [addrAt, cells, mergedSpillRanges, realCol, realRow, sheetFilter]); // ⛔ `tab.cells` IS LEGITIMATELY UNDEFINED ON A FIRST RENDER, which is why the line above // already reads it through `?? {}`. `GET /sheets/{id}?tabs=meta` answers tabs with NO cells, so // a tab the page has not fetched yet arrives here with none and `Object.entries(undefined)` // throws INSIDE A RENDER. This lane's own Kanban screenshot is what found it: the console said // "[Sheet] render failed TypeError: Cannot convert undefined or null to object" and the sheet // fell to its error boundary. Read the guarded local, never the prop. const reservedViewBlocks = useMemo(() => Object.entries(cells).flatMap(([origin, cell]) => { const at = splitAddress(origin); return at && cell?.kind === "bound" && cell.binding?.mode === "view" && cell.binding.viewType !== "grid" && cell.binding.block ? [viewBlockGeometry(at, cell.binding)] : []; }), [cells]); const isViewReserved = useCallback((addr: string) => { const pos = splitAddress(addr); return !!pos && reservedViewBlocks.some(box => pos.col - 1 >= box.col0 && pos.col - 1 <= box.col1 && pos.row - 1 >= box.row0 && pos.row - 1 <= box.row1); }, [reservedViewBlocks]); // The page owns refusal/confirmation and atomically reanchors cells, sources and placement. const requestStructure = onStructure; // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W53-T01 / RULING R2 / INSTRUCTION 19 — THE IN-CELL SHIMMER, AND WHY IT IS DRIVEN RATHER // THAN DECLARED. // // R2 splits the sheet's calculation in two: a formula over other cells lands INSTANTLY (there // is no round trip left to wait for), and only a DATABASE-BOUND cell still goes to the server. // Instruction 19 is about what the reader sees during that second half: "show visually that the // formula was refreshed first, quickly, before the database cell gets refreshed". So the wait // is shown where the wait actually is — inside the one cell that is waiting — instead of in a // global status strip that made every cell look busy while most of them were already done. // // ⛔ A CANVAS DOES NOT ANIMATE ITSELF. glide paints on demand, so a moving band needs somebody // to ask for the repaint: this ticks a phase and damages ONLY the pending cells, which is why // the phase is a ref rather than state (state would rebuild `paintCell` and repaint the whole // viewport twelve times a second for a band crossing four cells). // // ⛔⛔ AND IT STOPS. `pendingBoundCells` empty means no interval at all: a permanent animation // promising a number that never arrives is exactly the defect `customer-grid/CustomerGrid.tsx` // already carries a warning about, and it is worse than no animation, because it teaches the // reader that motion means nothing. // ═══════════════════════════════════════════════════════════════════════════════════════════ const shimmerPhase = useRef(0); const pendingBoundCells = useMemo( () => Object.entries(cells) .filter(([, cell]) => boundWaiting(cell)) .map(([addr]) => addr), [cells], ); const pendingBoundKey = pendingBoundCells.join(","); useEffect(() => { if (!pendingBoundKey) { shimmerPhase.current = 0; return undefined; } const addrs = pendingBoundKey.split(","); const id = window.setInterval(() => { shimmerPhase.current = (shimmerPhase.current + 0.06) % 1; const main: { cell: Item }[] = []; const band: { cell: Item }[] = []; for (const addr of addrs) { const at = splitAddress(addr); if (!at) continue; const viewCol = viewIndexOf(visCols, at.col - 1); const viewRow = viewRowOf(at.row - 1); // A NEGATIVE VIEW ROW IS THE FROZEN BAND, which is its own `DataEditor` counting from // zero, so it is damaged through its own handle rather than the main grid's. if (viewRow < 0) band.push({ cell: [viewCol, viewRow + bandRows] as Item }); else main.push({ cell: [viewCol, viewRow] as Item }); } if (main.length > 0) gridRef.current?.updateCells(main); if (band.length > 0) bandGridRef.current?.updateCells(band); }, 90); return () => window.clearInterval(id); }, [bandRows, pendingBoundKey, viewRowOf, visCols]); const plainNumberDisplays = useMemo(() => new Map(), [cells]); const getCellContent = useCallback( ([col, row]: Item): GridCell => { const cell = cells[addrAt(col, row)] ?? null; // Repeated plain numbers share their display text, including during selection summaries. const plainNumber = typeof cell?.value === "number" && Number.isFinite(cell.value) && cell.state !== "refused" && !cell.style?.format && !cell.validation ? cell.value : undefined; let displayData = plainNumber !== undefined ? plainNumberDisplays.get(plainNumber) : undefined; if (displayData === undefined) { displayData = bindingRefusal(cell)?.display ?? formatCellText(cell, displayText(cell)); if (plainNumber !== undefined) plainNumberDisplays.set(plainNumber, displayData); } // ⛔⛔ A REFUSED CELL SHOWS ITS REASON, NOT A BLANK (W49-T09, C2/R16). A blank cell reads as // "nothing here" and a person reasonably sums around it; the whole point of a refusal is // that the reader learns WHY there is no number. The sentence comes from the server, which // is the only side that knows whether the cause was access, a deleted view or a cycle. // // ⭐ `data` AND `displayData` ARE DIFFERENT ON PURPOSE (W50-T18). `data` is what F2 opens // with, which for a formula cell is `=SUM(B4:B8)` and not `31`, exactly as Excel does; it // is also what glide round-trips through its own clipboard HTML, so copying a formula // inside the sheet carries the formula while copying into Excel carries the number. // // ⭐ W50-T19: `displayData` IS WHERE A NUMBER FORMAT LANDS, AND THAT IS WHY IT REACHES THE // EXPORT. glide reads this string for the painted text AND for its own clipboard and // `getCellsForSelection`, so a currency cell copies out as the currency a person chose // rather than as the bare number underneath. `data` is untouched: F2 still opens the // formula or the typed text, exactly as Excel does. return { kind: GridCellKind.Text, data: editableText(cell), displayData, // ⛔ A bound cell does not open glide's OWN text overlay. `onKeyDown`'s typed-character // branch is that cell's editor instead (R5, W52-T09): it opens the SAME floating editor a // fresh formula does, converting the cell the moment Enter commits, with no confirmation // and no glide overlay competing with it for the same rectangle. // // ⛔⛔ W51-T18 / C2: A VALIDATED CELL DOES NOT OPEN glide's TEXT OVERLAY EITHER, and that // is what makes the dropdown the cell's editor rather than a second one competing with // it. glide's overlay is a positioned input over the same rectangle, so leaving it on // would put a free text box on top of a list a person may not type outside of. The other // two doors into such a cell, a PASTE and a FILL, are screened in their own handlers // (`validation.ts::screenEdits`) because those land text this component never sees typed. // // ⛔⛔ W52-T06: A FORMULA CELL DOES NOT OPEN glide's TEXT OVERLAY EITHER, FOR EXACTLY THE // SAME REASON THE VALIDATED CELL ABOVE DOES NOT. `openFormulaEditor` (below) is that // cell's editor: `onCellActivated` opens it for an EXISTING formula, and `onKeyDown`'s // typed-character branch opens it the moment a fresh "=" starts one. glide's own overlay // would otherwise sit on top of the dropdown/ScreenTip a person may be typing INTO. allowOverlay: !readOnly && !viewChromeRefusal(cell) && cell?.kind !== "bound" && cell?.kind !== "formula" && !validationOf(cell), readonly: readOnly || !!viewChromeRefusal(cell) || cell?.kind === "bound" || validationOf(cell) !== null, }; }, // `cells` is the whole dependency: a new workbook object gives a new `cells`, which is what // makes glide repaint. Narrowing this to `tab.id` is the stale-closure bug. // Filter toggles must also invalidate Glide's cell paint, even before rows are hidden. [addrAt, cells, sheetFilter, readOnly, plainNumberDisplays], ); /** * ⭐⭐ W51-T34 — THE BAND'S CELLS ARE THE SAME CELLS, THROUGH THE SAME FUNCTION. A second * content function would be a second opinion about what a bound cell, a refusal or a number * format looks like, and the two would drift the first time either was touched. The band grid * asks the main one, having said which row it means. */ // S67-T01: glide's damage repaint wipes a cell from its x+1, y+1 and never repaints the grid-line // pixels, which is where an outline's outer pixel sits, and its blit check skips a redraw whose // `getCellContent` is unchanged. The main grid's content changes when the editor closes; the // frozen-rows band's does not, so an outline leaving the band bumps this, `getFrozenContent` // gets a new identity, and glide redraws the band whole (grid lines included). const [bandRepaint, setBandRepaint] = useState(0); const getFrozenContent = useCallback( (item: Item): GridCell => getCellContent(fromBand(item)), // `bandRepaint` is read by no line above on purpose: see its declaration. // eslint-disable-next-line react-hooks/exhaustive-deps [fromBand, getCellContent, bandRepaint], ); // Read the canvas result and yield between batches so a large selection remains interactive. const [statusStats, setStatusStats] = useState(null); useEffect(() => { const rects = selectionRects(selection, visCols.length, allVisRows.length, bandRows); if (!holdsTwoOrMore(rects)) { setStatusStats(null); return; } const steps = selectionStatsSteps(cells, visCols, allVisRows, rects, undefined, (col, row) => { const shown = getCellContent([col, row - bandRows]); return shown.kind === GridCellKind.Text ? shown.displayData : ""; }); let handle = 0; const advance = () => { const start = performance.now(); let step = steps.next(); while (!step.done && performance.now() - start < 6) step = steps.next(); if (!step.done) { handle = window.requestAnimationFrame(advance); return; } const shown = step.value.count > 0 ? step.value : null; setStatusStats((prev) => (prev && shown && prev.count === shown.count && prev.sum === shown.sum && prev.numbers === shown.numbers && prev.formatCell === shown.formatCell ? prev : shown)); }; handle = window.requestAnimationFrame(advance); return () => { window.cancelAnimationFrame(handle); steps.return({ count: 0, numbers: 0, sum: 0, average: null, formatCell: null }); }; }, [selection, cells, visCols, allVisRows, bandRows, getCellContent]); const selected = useMemo(() => { const cur = selection?.current?.cell; if (!cur) return null; const addr = addrAt(cur[0], cur[1]); return { addr, cell: cellAt(tab, addr) }; }, [addrAt, selection, tab]); const hasCellAnchor = anchor != null; useEffect(() => { if ((!hasCellAnchor && (anchor !== undefined || selected?.cell?.kind !== "bound")) || !wrapRef.current) return; let frame = 0; const project = () => { cancelAnimationFrame(frame); frame = requestAnimationFrame(() => { frame = requestAnimationFrame(() => { const item = selectionRef.current?.current?.cell; if (!item) return; const bounds = item[1] < 0 ? bandGridRef.current?.getBounds(item[0], item[1] + bandRows) : gridRef.current?.getBounds(item[0], item[1]); if (!bounds || ![bounds.x, bounds.y, bounds.width, bounds.height].every(Number.isFinite)) return; setAnchor(prior => prior === null ? null : prior && (prior.x === bounds.x && prior.y === bounds.y && prior.width === bounds.width && prior.height === bounds.height) ? prior : bounds); }); }); }; // Bound selections need their first anchor as well as layout updates, including the frozen grid. const observer = new ResizeObserver(project); observer.observe(wrapRef.current); project(); return () => { observer.disconnect(); cancelAnimationFrame(frame); }; }, [hasCellAnchor, anchor === undefined, selection, selected?.cell?.kind, bandRows, zoom]); /** * The values needed by the selection door move as the workbook tree moves, but the door itself * must not. glide retains selection internally and can emit its default A1 when a new data * identity also gives it a new callback identity. Keeping one callback lets a same-tab refresh * remain a repaint rather than look like navigation. */ const selectionContextRef = useRef({ addrAt, bandRows, onSelect, tab, viewRowOf, visCols, visRows }); selectionContextRef.current = { addrAt, bandRows, onSelect, tab, viewRowOf, visCols, visRows }; /** * What the NEXT call to `onSelectionChange` is: a reader gesture or an app-owned move. * ⛔ This is a ref, not a parameter: W54-T28 finds the selection door by its exact declaration. */ const selectionIntentRef = useRef<"reader" | "app" | null>(null); const onSelectionChange = useCallback((next: GridSelection) => { const selectionIntent = selectionIntentRef.current; selectionIntentRef.current = null; const context = selectionContextRef.current; // ⭐⭐ W56-T04 / INSTRUCTION 26: ESCAPE MAY DISMISS, BUT IT MAY NOT CLEAR THE LAST CELL. // glide owns Escape and reports an empty selection here. Correct that payload ONCE at this // door; recursively calling this handler, or repairing selection from an effect, makes the // controlled update re-enter glide's own Escape handling and loop. A first-render Escape has // no prior cell, so it starts at the sheet's first visible representation of A1. const prior = selectionRef.current?.current?.cell; const first: Item = [viewIndexOf(context.visCols, 0), context.viewRowOf(0)]; const fromGlide = selectionIntent === null; const readerCaused = (selectionIntent === "reader" || (fromGlide && (pointerSelectingRef.current || keyboardSelectingRef.current))) && next.current?.cell !== undefined; // Only the first callback after a same-workbook, same-tab object replacement is suspect. // Shape cannot distinguish glide's default A1 from a real click on A1, so reader provenance // wins and always consumes the handoff. A gesture-less differing cell is reconciliation: feed // a fresh copy of the prior controlled selection through this same door so React makes glide // paint it again. Consuming before acceptance prevents the controlled repaint from looping. const replacementSelection = replacementSelectionRef.current; replacementSelectionRef.current = null; const replacementCell = replacementSelection?.current?.cell; const offeredCell = next.current?.cell; let offered = next; let overlayRun: number | null | undefined; // W59-T03 / D-697: a captured chord alone is not a grid commit. Require both a fresh stamp // from the prior cell and glide's matching, unmodified move. The canvas commit arm already // aged the run and raised commitNav, so consuming its stamp must not age it a second time. const stamp = overlayCommit.current; overlayCommit.current = null; if (!commitNav.current && fromGlide && stamp && prior && offeredCell && Date.now() - stamp.at < 300 && prior[0] === stamp.from[0] && prior[1] === stamp.from[1]) { const bounds = { minCol: 0, maxCol: Math.max(0, context.visCols.length - 1), minRow: -context.bandRows, maxRow: Math.max(0, context.visRows.length - 1), }; const from = { col: prior[0], row: prior[1] }; const expected = commitTarget(from, stamp.dir, null, bounds); if (offeredCell[0] === expected.col && offeredCell[1] === expected.row) { const origin = tabRunAt.current; if ((stamp.dir === "down" || stamp.dir === "up") && origin !== null) { const land = commitTarget(from, stamp.dir, origin, bounds); offered = { ...offered, current: { ...offered.current!, cell: [land.col, land.row] as Item, range: { x: land.col, y: land.row, width: 1, height: 1 }, }, }; } overlayRun = tabRunOrigin(origin, stamp.dir, prior[0]); } } const overlayCommitted = overlayRun !== undefined; // An overlay commit can replace the workbook before glide offers its next cell. Its // validated move wins over that replacement's reconciliation handoff, just as a click does. if (replacementSelection && replacementCell && offeredCell && fromGlide && !readerCaused && !overlayCommitted && (replacementCell[0] !== offeredCell[0] || replacementCell[1] !== offeredCell[1])) { offered = { ...replacementSelection, current: { ...replacementSelection.current!, cell: [replacementCell[0], replacementCell[1]] as Item, }, }; } const cell = prior ?? first; const accepted: GridSelection = offered.current?.cell ? offered : { columns: CompactSelection.empty(), rows: CompactSelection.empty(), current: { cell, range: { x: cell[0], y: cell[1], width: 1, height: 1 }, rangeStack: [], }, }; selectionRef.current = accepted; setSelection(accepted); // An explicit opening/name-box move also owns the next gesture-less reconciliation. // The first real click or key still wins and consumes this same one-shot handoff. if (selectionIntent === "app") replacementSelectionRef.current = accepted; // ⭐⭐ W54-T28 / R9(iv): "the run resets when the selection is moved by anything other than // Tab", said in the one place every move arrives at. The commit arm raises the flag for its // own move and this consumes it, so a Tab keeps the run and everything else ends it. if (commitNav.current) commitNav.current = false; else tabRunAt.current = null; // W59-T03 / D-697: a validated glide overlay commit is a commit too. The reset above cannot // know that, because glide never reaches `onKeyDown` and so nothing claimed the move; this // puts back the run the commit should leave behind, computed from the origin read BEFORE it. if (overlayRun !== undefined) tabRunAt.current = overlayRun; // W59-T02 / R4: only Ctrl+A's own selection keeps its run, including at the same anchor. if (selectAllNav.current) selectAllNav.current = false; else selectAllRunAt.current = null; // R11: the bar is anchored to the selection and unmounts when the selection changes. Clearing // the anchor here is what makes "disappears when the selection changes" true rather than // approximately true. const sameCell = prior && accepted.current?.cell[0] === prior[0] && accepted.current.cell[1] === prior[1]; setAnchor(sameCell ? null : undefined); // ⭐ W52-T07: the paste highlight names what just happened, not what is still selected, so a // click elsewhere retires it. The copy marquee is the OTHER of the two and deliberately does // not clear here — see its own doc comment beside `copyMarquee`. setPasteHighlight(null); // ═════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W50-T21's HANDOVER, LANDED HERE AND NOT IN AN EFFECT, AND THE DIFFERENCE IS A BUG. // // W50-T21's own note proposed firing this from a `useEffect` on the `selected` memo. That // would have broken the formula bar's NAME BOX, which is the control the same ticket calls // Excel's own. Traced: `onSelect` is an inline arrow in `SheetPage`'s JSX, so it is a new // function on every page render; the effect therefore fires on every RENDER rather than on // every selection. Type `D10` in the name box, and `setBarAddr("D10")` re-renders the page, // which re-fires the effect, which writes the grid's UNCHANGED selection back over it. The // box navigates and snaps straight back. Worse, `selected` also depends on `tab`, and // `withCells` rebuilds the tab on every keystroke, so a bar edit would throw the bar off the // cell it had just committed to. // // ⭐ FIRING FROM THE GESTURE IS BOTH SIMPLER AND CORRECT: the bar follows the grid when // somebody moves the grid, and the name box owns the address the rest of the time. Two // writers, one state, and neither one overwrites the other's act. // // ⭐ The floor above means every selection gesture now sends the selected cell. There is no // cleared-selection branch left to blank the bar or the workbook's remembered position. // ═════════════════════════════════════════════════════════════════════════════════════════ if (!context.onSelect) return; const cur = accepted.current!.cell; const addr = context.addrAt(cur[0], cur[1]); context.onSelect({ addr, cell: cellAt(context.tab, addr), readerCaused }); }, []); // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W51-T34 — ONE SELECTION, TWO GRIDS, AND THE MAIN GRID OWNS IT. // // ⛔ TWO `DataEditor`s MEAN TWO `gridSelection`s UNLESS ONE STATE FEEDS BOTH, and two would be // visible immediately: bold a cell in the band and the ribbon would read the body's anchor. So // `selection` above stays the ONE state, in the MAIN grid's coordinates, and a row inside the // frozen band is held there as a NEGATIVE row (see `realRow`). Each grid is then handed the // selection only while it is the one holding it, and `undefined` while the other is, which is // what stops both drawing a focus ring at once. // // ⚠ THE BAND GRID WRITES BACK THROUGH THE SAME `onSelectionChange`, so a click in the band // clears the action bar anchor and moves the formula bar exactly as a click in the body does. // Nothing about a frozen cell is a special case anywhere else in this file. // ═══════════════════════════════════════════════════════════════════════════════════════════ /** * TWO QUESTIONS, NOT ONE (S64-T22). `bandHoldsActive` asks whether the active cell is in * the frozen band, which is what decides where the RING is drawn and who takes focus. * `inBand` asks the narrower question the pinned `mainSelection` line below consumes: may the * BODY be shown nothing at all? For a whole-COLUMN selection the answer is no, because that * selection belongs to BOTH panes: measured 2026-09-21, Ctrl+Space on a frozen cell selected * the whole column in the model, tinted the header and the band, and left the body white. * A whole-ROW selection anchored in the band is NOT an exception and must keep today's * behaviour, because that row IS the band and the body has none of it to show. * * THE `bandRows` CLAUSE IS NOT DECORATION, and it is kept for its original reason: unfreezing * while a frozen cell is selected leaves a NEGATIVE row in a state with no band to hold it. */ const bandHoldsActive = bandRows > 0 && (selection?.current?.cell[1] ?? 0) < 0; const inBand = bandHoldsActive && (selection?.columns.length ?? 0) === 0; const headerProjectionBounds = useMemo(() => ({ columns: visCols.length, minRow: -bandRows, maxRow: Math.max(0, visRows.length - 1), }), [bandRows, visCols.length, visRows.length]); /** Re-check neighbouring marker bounds: Glide's hover can stay on either side of a border. */ const rowBorderAt = useCallback((x: number, y: number): { row: number; rect: Rectangle } | null => { if (readOnly || !headingsVisible) return null; let hit: { row: number; rect: Rectangle } | null = null; let distance = Infinity; for (const band of [true, false]) { const hovered = rowHoverRef.current[band ? 1 : 0]; if (!hovered || (band && bandRows === 0)) continue; const grid = (band ? bandGridRef : gridRef).current; const count = band ? bandRows : visRows.length; for (const index of [hovered.row - 1, hovered.row, hovered.row + 1]) { if (index < 0 || index >= count) continue; const rect = grid?.getBounds(-1, index); if (!rect || x < rect.x || x >= rect.x + rect.width || Math.abs(y - rect.y - rect.height) > ROW_RESIZE_ZONE) continue; const gap = Math.abs(y - rect.y - rect.height); // At low zoom the zones can overlap. The nearest border still owns the gesture. if (gap < distance) { distance = gap; hit = { row: band ? index - bandRows : index, rect }; } } } return hit; }, [bandRows, headingsVisible, readOnly, visRows.length]); const trackRowResize = useCallback((event: { pointerId: number; clientY: number }) => { const gesture = rowResizeGesture.current; if (!gesture || gesture.pointerId !== event.pointerId) return; if (event.clientY !== gesture.startY) gesture.moved = true; gesture.size = Math.max(MIN_ROW_HEIGHT, Math.min(MAX_ROW_HEIGHT, gesture.height + (event.clientY - gesture.startY) / gesture.zoom)); const box = wrapRef.current?.querySelector(".sheet-grid-canvas")?.getBoundingClientRect(); if (box && gesture.moved) { setDragRowGuide(gesture.bottom + (gesture.size - gesture.height) * gesture.zoom - box.y); } }, []); /** The same patch door as a tab setting: one row or a whole selection takes one undo step. */ const onRowResizeEnd = useCallback((event: { pointerId: number; clientY: number }) => { const gesture = rowResizeGesture.current; if (!gesture || gesture.pointerId !== event.pointerId) return; trackRowResize(event); rowResizeGesture.current = null; setDragRowGuide(null); setRowBorderHover(null); if (readOnly || gesture.scope !== renderedWorkbookKey || !gesture.moved) return; const patch = rowHeightsPatch(tab, gesture.rows, gesture.size); if (Object.keys(patch.rowHeights ?? {}).length) onTabView(patch); }, [onTabView, readOnly, renderedWorkbookKey, tab, trackRowResize]); useEffect(() => { const move = (event: PointerEvent) => { if (!rowResizeGesture.current) return; trackRowResize(event); event.preventDefault(); event.stopPropagation(); }; const release = (event: PointerEvent) => { if (!rowResizeGesture.current) return; onRowResizeEnd(event); pointerSelectingRef.current = false; event.preventDefault(); event.stopPropagation(); }; const cancel = () => { rowResizeGesture.current = null; setDragRowGuide(null); setRowBorderHover(null); pointerSelectingRef.current = false; }; window.addEventListener("pointermove", move, true); window.addEventListener("pointerup", release, true); window.addEventListener("pointercancel", cancel, true); return () => { window.removeEventListener("pointermove", move, true); window.removeEventListener("pointerup", release, true); window.removeEventListener("pointercancel", cancel, true); }; }, [onRowResizeEnd, trackRowResize]); useEffect(() => { rowHoverRef.current = []; rowResizeGesture.current = null; setDragRowGuide(null); setRowBorderHover(null); }, [renderedWorkbookKey, readOnly, zoom, bandRows]); const mainSelection = inBand ? undefined : selection; const frozenSelection = useMemo(() => { if (!selection) return undefined; const current = bandHoldsActive ? selection?.current : undefined; return { // C6: the band is a projection of the document selection, not a second selection. Columns // already share view coordinates; row axes shift from negative document-view coordinates // into this DataEditor's local zero-based band coordinates. Even while the active cell is // in the body, keep this projection alive: the band owns the one column-header canvas and // must be invalidated when a body command changes the document selection. columns: selection.columns, rows: selection.rows.offset(bandRows), current: current ? { cell: [current.cell[0], current.cell[1] + bandRows], range: { ...current.range, y: current.range.y + bandRows }, rangeStack: current.rangeStack.map(range => ({ ...range, y: range.y + bandRows })), } : undefined, }; }, [bandHoldsActive, bandRows, selection]); useEffect(() => { // Glide damages only the newly focused header when `current.cell` moves. Our header paint is // derived from the whole document range/axis, so both the old and new projected sets must be // repainted after the shared selection commits. The grid carrying the letters owns this one // inexpensive header-row damage pass (not both DataEditors). const headers = columns.map((_, col) => ({ cell: [col, -1] as Item })); (bandRows > 0 ? bandGridRef : gridRef).current?.updateCells(headers); }, [bandRows, columns, selection]); const onFrozenSelectionChange = useCallback((next: GridSelection) => { const current = next.current; if (!current) { onSelectionChange(next); return; } onSelectionChange({ ...next, rows: next.rows.offset(-bandRows), current: { ...current, cell: fromBand(current.cell), range: { ...current.range, y: current.range.y - bandRows }, rangeStack: current.rangeStack.map(range => ({ ...range, y: range.y - bandRows })), }, }); }, [bandRows, fromBand, onSelectionChange]); /** * ⭐⭐ THE WORKBOOK GETTER. Bare `A1` reads this tab exactly as before; `SHEET2!A1` resolves * through a case-insensitive name index whose value is the real tab object and stable tab ID. * * ⛔ AN UNKNOWN NAME IS `#REF!`, NEVER AN EMPTY CELL. Blank would be a confident numeric zero * in arithmetic and would make a correct formula look successfully calculated from no sheet. */ const cellValueGetter = useMemo(() => { const byName = new Map( (workbook.sheets ?? []).map((sheet) => [sheet.name.trim().toUpperCase(), sheet]), ); return workbookFormulaGetter((key: string) => { const bang = key.lastIndexOf("!"); const sheetName = bang < 0 ? "" : key.slice(0, bang).toUpperCase(); const addr = (bang < 0 ? key : key.slice(bang + 1)).toUpperCase(); const target = sheetName ? byName.get(sheetName) : tab; if (!target) { return { kind: "error", code: ERROR_REF, message: `${ERROR_REF} This formula names a sheet that is not in this workbook.`, }; } const cell = cellAt(target, addr); const refusal = bindingRefusal(cell); if (refusal) return { kind: "error", code: ERROR_VALUE, message: `${ERROR_VALUE} ${refusal.message}` }; return cellToValue(cell); }); }, [tab, workbook.sheets]); /** * ⭐⭐ W53-T01 / INSTRUCTION 11 — EVERY COMMIT DOOR IN THIS FILE LANDS THROUGH HERE, so a write * and the recalculation it forces are ONE commit: one history step, one queued save. A second * `onCommit` for the dependents would cost two Ctrl+Z presses to undo one edit and would race * itself for the document's `rev`. * * ⛔ IT IS A CALLBACK, NOT AN EFFECT, AND THAT IS THE WHOLE DIFFERENCE. `onCommit` is * `SheetPage.tsx::commitCells`, which pushes history and queues a save; an effect watching the * document would mutate a workbook nobody edited and write it back merely for opening a sheet. */ const applyViewAnswer = useCallback(async ( base: Workbook, target: SheetTab, origin: string, answer: ViewRowsAnswer, binding = (target.cells ?? {})[origin]?.binding, ): Promise => { const latest = viewContext.current; const op = viewRefreshOp(target, origin, answer, binding); if (typeof op === "string") { latest.onNotice(op); return false; } const refusal = structureRefusal(base, target.id, op); if (refusal) { latest.onNotice(refusal); return false; } const projected = applyStructureWorkbook(base, target.id, op); const state = viewRefresh.current; state.seen.add(base.sheets); state.key = viewReadKey(projected.sheets.find(sheet => sheet.id === target.id)!); await latest.onStructure(op); return true; }, []); const resizeViewBlock = useCallback((origin: string, block: { cols: number; rows: number }) => { const context = viewContext.current; const cell = (context.storedTab.cells ?? {})[origin]; if (viewRefresh.current.busy || viewWritePending.current || cell?.binding?.mode !== "view" || cell.binding.viewType === "grid" || !cell.binding.block) return; const binding = { ...cell.binding, block: { cols: block.cols, rows: block.rows } } as ViewBinding; if (JSON.stringify(cell.binding.block) === JSON.stringify(binding.block)) return; // Row data cannot change a non-grid footprint. Resize commits just its binding and the // displaced bands, using precisely the same atomic door as a resolved Grid refresh. void applyViewAnswer(context.storedWorkbook, context.storedTab, origin, { fields: [], rows: [], total: 0, limit: binding.limit, viewType: binding.viewType, editable: false, }, binding); }, [applyViewAnswer]); const commitViewRecord = useCallback(async (addr: string, text: string) => { const context = viewContext.current; if (viewWritePending.current || viewRefresh.current.busy) { context.onNotice("Wait for this Grid to finish saving, then try again."); return; } const base = context.storedWorkbook; const target = context.storedTab; const generation = ++viewRefresh.current.generation; const current = () => viewRefresh.current.generation === generation && viewContext.current.storedWorkbook.id === base.id && viewContext.current.storedTab.id === target.id && viewContext.current.storedWorkbook.sheets === base.sheets; viewWritePending.current = true; try { const result = await writeViewCell(base.id, target, addr, text, current); if (!result.ok) { viewContext.current.onNotice(result.message); return; } if (!current()) { // A record write can finish after navigation or a neighbouring sheet edit. Let the // existing refresh effect resolve the CURRENT footprint; never apply the old one. viewRefresh.current.key = ""; viewRefresh.current.seen = new WeakSet(); setViewWriteRefresh(value => value + 1); viewContext.current.onNotice("The record was saved; the Grid is refreshing."); return; } await applyViewAnswer(base, target, result.origin, result.answer); } catch { viewContext.current.onNotice("The record change could not be confirmed; refresh the Grid before trying again."); } finally { viewWritePending.current = false; } }, [applyViewAnswer]); const commitWithRecalc = useCallback((edits: Record, move?: MovedBlock, landed?: SheetTab) => { if (readOnly) return; const entries = Object.entries(edits); const reserved = entries.some(([addr, value]) => value && isViewReserved(addr)); if (reserved) { onNotice("Resize or remove this view before editing its reserved cells."); return; } const placed = entries.filter(([addr]) => cells[addr]?.viewChild || viewChromeRefusal(cells[addr])); if (placed.length) { const chrome = placed.map(([addr]) => viewChromeRefusal(cells[addr])).find(Boolean); if (chrome) { onNotice(chrome); return; } if (entries.length !== 1) { onNotice("Edit one Grid record cell at a time."); return; } const [addr, cell] = placed[0]; void commitViewRecord(addr, editableText(cell)); return; } const calculated = { ...edits, ...recalcDependents(tab, edits, workbook.sheets, workbook, calculationSession.current) }; const document: Partial> = {}; if (landed) { for (const key of ["rules", "charts", "colWidths"] as const) { if (landed[key] !== tab[key]) Object.assign(document, { [key]: landed[key] ?? (key === "colWidths" ? {} : []) }); } } if (Object.keys(document).length > 0 && !move) { const nextCells = { ...tab.cells }; for (const [addr, cell] of Object.entries(calculated)) { if (cell === null) delete nextCells[addr]; else nextCells[addr] = cell; } const patch: TabViewPatch = { ...document, cells: nextCells }; onTabView(patch); } else { // The page hydrates all tabs before a move. Its existing commit carries these layers too. onCommit(calculated, move && Object.keys(document).length > 0 ? { ...move, pasteTab: document } : move); } }, [commitViewRecord, isViewReserved, onCommit, onNotice, onTabView, tab, workbook, readOnly]); /** ONE typed commit. `commitTyped` picks literal or formula and drops a binding on its own. */ const onCellEdited = useCallback((item: Item, value: EditableGridCell) => { const addr = addrAt(item[0], item[1]); commitWithRecalc({ [addr]: commitTyped(cellAt(tab, addr), typedText(value), cellValueGetter) }); // ⭐ W52-T07: an edit is a stronger "moved on" signal than a selection change; the paste // highlight retires here too, same reasoning as `onSelectionChange`. setPasteHighlight(null); }, [addrAt, cellValueGetter, commitWithRecalc, tab]); /** * The batch door glide uses for a paste it applies itself and for its own fill. Returning * `true` tells glide NOT to also call `onCellEdited` per item, which would produce one save * per cell, each racing the last for the same `rev`. */ const onCellsEdited = useCallback( (items: readonly { location: Item; value: EditableGridCell }[]) => { const edits: Record = {}; for (const item of items) { const addr = addrAt(item.location[0], item.location[1]); const cell = cellAt(tab, addr); // ⭐ R5 (W52-T09): a bound cell is no longer skipped here - `commitTyped` clears its // binding exactly as it does for the single-cell door above. edits[addr] = commitTyped(cell, typedText(item.value), cellValueGetter); } commitWithRecalc(edits); return true; }, [addrAt, cellValueGetter, commitWithRecalc, tab], ); /** * ⭐ W51-T34 — THE BAND IS EDITABLE, THROUGH THE SAME TWO DOORS. A frozen row is still a row of * the sheet, so typing into one has to commit exactly as typing into any other does; a band * that only displayed would be a surface a person can select, style and copy from but not * correct, which is the dead-control shape this ticket exists to remove. */ const onFrozenCellEdited = useCallback( (item: Item, value: EditableGridCell) => onCellEdited(fromBand(item), value), [fromBand, onCellEdited], ); const onFrozenCellsEdited = useCallback( (items: readonly { location: Item; value: EditableGridCell }[]) => onCellsEdited(items.map((item) => ({ ...item, location: fromBand(item.location) }))), [fromBand, onCellsEdited], ); // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W52-T06 — THE FLOATING FORMULA EDITOR. This is a cell whose OWN editor this component is // (`getCellContent` above switches off glide's overlay for `kind: "formula"`), the same pattern // W51-T18 already established for a validated cell's dropdown (`dropdown` state, above). Opened // by `onCellActivated` for an EXISTING formula and by `onKeyDown`'s typed-character branch the // moment a fresh "=" starts one; closed by `commitFormulaEditor` (Enter/Tab/blur) or // `abandonFormulaEditor` (Escape, FA-23 #2 / PM-13). // ═══════════════════════════════════════════════════════════════════════════════════════════ const clampCol = useCallback((c: number) => Math.max(1, Math.min(extent.cols, c)), [extent.cols]); const clampRow = useCallback((r: number) => Math.max(1, Math.min(extent.rows, r)), [extent.rows]); const openFormulaEditor = useCallback(( addr: string, draft: string, caret: number, viewCell: readonly [number, number], inBand: boolean, ) => { if (readOnly) return; const anchor = splitAddress(addr); if (!anchor) return; // A formula edit is the ONE editor at a time this component ever shows, same as every other // anchored surface below (the right-click menu, the validated-cell dropdown). setAnchor(null); setMenu(null); setDropdown(null); setFormulaEdit({ addr, inBand, viewCell, draft, caret, dropdownIndex: 0, dismissed: false, mode: "enter", caretOnly: false, anchor, insertStart: null, pointCell: null, pointBand: null, rangeAnchor: null, }); }, [readOnly]); /** * ⭐⭐ W54-T21 / INSTRUCTION 18 — ESCAPE CANCELS THE EDIT AND THE CELL GOES BACK TO WHAT IT HELD. * * ⛔ THE RESTORE IS A REPAINT, NOT A WRITE, AND THAT IS THE WHOLE POINT. Nothing in this * editor's life touches the document: the draft lives in `formulaEdit` and only a COMMIT ever * reaches `commitWithRecalc`. So the prior value was never lost and re-writing it here would be * a save round trip that could itself fail. What the canvas needs is to be TOLD the cell * changed, because glide repaints damaged cells only and the cell under the editor has been * wearing a reference border and an editor overlay. Damaging it makes the next paint read the * stored cell again, which IS the prior value. * * ⚠ THE FLAG IS RAISED BEFORE THE STATE DROPS, so the blur this abandon is about to be * followed by (see `formulaEscaping` above) cannot commit the draft on its way out. */ const abandonFormulaEditor = useCallback(() => { formulaEscaping.current = true; if (formulaEdit) { const target = [{ cell: [formulaEdit.viewCell[0], formulaEdit.viewCell[1]] as Item }]; (formulaEdit.inBand ? bandGridRef : gridRef).current?.updateCells(target); } setFormulaEdit(null); }, [formulaEdit]); /** Enter/Tab outside point mode, and the second half of PM-12 inside it. */ const commitFormulaEditor = useCallback((move: CommitDirection = "down") => { if (!formulaEdit) return; const { addr, draft, inBand, viewCell } = formulaEdit; // ⭐⭐ W53-T02 — READY IS RESTORED FIRST, THE WRITE SECOND, and the order is the whole point. // `commitWithRecalc` eventually reaches the caller's own save door and this component does // not know what it can throw; clearing the edit BEFORE calling it means a throw mid-commit // still leaves the sheet in Ready mode (arrows working, focus handed back by the effect // beside `formulaEdit`) instead of stranded in Enter or Point mode. Both updates land in the // same React batch, so nothing renders in between and the draft is already destructured. setFormulaEdit(null); // ⭐⭐ W54-T25 / R9(i) — THE AUTO-CLOSE HAPPENS HERE, BEFORE STORAGE, AND ONLY HERE. What // `commitTyped` is handed is what the cell stores, what the formula bar reads back and what // the evaluator computes, so all three see one identical closed text. Closing the DISPLAY // instead would leave a cell that looks balanced and is stored broken. // ⛔ AND THE ABANDON DOOR NEVER PASSES THROUGH HERE. Escape drops the draft without a write // (see `abandonFormulaEditor` above), so an unfinished formula that was cancelled is still // cancelled rather than tidied up and saved. const closed = autoCloseFormula(draft); commitWithRecalc({ [addr]: commitTyped(cellAt(tab, addr), closed, cellValueGetter) }); // W59-T01 / instruction 3: choose the move inside the commit so Tab lands horizontally once. // The default stays down; commitTarget now clamps at the last visible row, matching the // canvas Enter path instead of letting the editor select beyond the sheet. // ⚠ NOT `applySelection` -- that helper is declared FURTHER DOWN this component (it is the // one thing a controlled selection needs `gridRef` for, beside the structural ops below), and // this callback is defined ahead of it. `onSelectionChange` is the same door one layer down. if (!inBand) { const origin = tabRunAt.current; const land = commitTarget( { col: viewCell[0], row: viewCell[1] }, move, origin, { minCol: 0, maxCol: Math.max(0, visCols.length - 1), minRow: -bandRows, maxRow: Math.max(0, visRows.length - 1) }, ); const next: Item = [land.col, land.row]; selectionIntentRef.current = "reader"; onSelectionChange({ columns: CompactSelection.empty(), rows: CompactSelection.empty(), current: { cell: next, range: { x: next[0], y: next[1], width: 1, height: 1 }, rangeStack: [] }, }); // W59-T03 / D-697's second half: that door resets the run for any move it was not told // about. This is a commit, so the run continues from the origin read above. tabRunAt.current = tabRunOrigin(origin, move, viewCell[0]); gridRef.current?.scrollTo(next[0], next[1]); } }, [bandRows, cellValueGetter, commitWithRecalc, formulaEdit, onSelectionChange, tab, visCols, visRows]); /** * ⭐⭐ W54-T21 — THE BLUR DOOR, AND THE ONE REASON IT IS NO LONGER THE COMMIT ITSELF. * * A click away still commits, exactly as it always has. What changed is that the decision is * taken one microtask later, so an Escape that blurred this input on its way to closing the * editor gets to say "not this one" first. See `formulaEscaping` beside the state above for * why the ordering is a guarantee rather than a hope. */ const onFormulaBlur = useCallback(() => { formulaEscaping.current = false; queueMicrotask(() => { if (formulaEscaping.current) return; if (formulaPointer.current) { formulaInputRef.current?.focus(); return; } commitFormulaEditor(); }); }, [commitFormulaEditor]); /** * PM-4/PM-5/PM-7/PM-8: every point-mode proposal, arrived at from either the anchor (a fresh * arrow press) or the previous proposal (a continued one), goes through this ONE splice so * "insert" and "replace the last insert" are the same code path rather than two that can drift. * W57-T01: a whole-column or whole-row proposal changes only the emitted text; it shares the * same insertStart, replacement length and caret rule as a cell or rectangular range. */ const proposeCell = useCallback(( target: RealCell, shift: boolean, wholeAxis?: "column" | "row", /** W57-T02: where a NEW range starts, for a Shift-extended press made before point mode * exists. Without it the anchor would default to `target` and a Ctrl+Shift+Arrow pressed as * the first key after `=SUM(` would emit one cell instead of the run it selected. T02 only * supplies this in enter mode; repeat presses keep the existing range anchor. W57-T04 * also uses it to explicitly name a region's top-left corner while already pointing. */ rangeFrom?: RealCell, ) => { if (!formulaEdit) return; const insertStart = formulaEdit.mode === "point" && formulaEdit.insertStart !== null ? formulaEdit.insertStart : formulaEdit.caret; const oldLen = formulaEdit.mode === "point" ? formulaEdit.caret - insertStart : 0; // W57-T04: an explicit rangeFrom wins so a region can name its anchor outright. This // preserves T02: it only supplies rangeFrom in enter mode, where rangeAnchor is null by // construction, so both orders answer identically for every existing T02 press. const rangeAnchor = shift ? (rangeFrom ?? formulaEdit.rangeAnchor ?? (formulaEdit.mode === "point" ? formulaEdit.pointCell : target)) : null; const text = wholeAxis === "column" ? columnRangeA1(target.col) : wholeAxis === "row" ? rowRangeA1(target.row) : rangeAnchor ? pointRangeText(rangeAnchor, target) : pointAddr(target); const draft = formulaEdit.draft.slice(0, insertStart) + text + formulaEdit.draft.slice(insertStart + oldLen); const caret = insertStart + text.length; setFormulaEdit({ ...formulaEdit, draft, caret, insertStart, mode: "point", pointCell: target, rangeAnchor, pointBand: wholeAxis ?? null, }); // PM-6: the grid scrolls to keep the proposal visible. Best effort on the MAIN grid only -- // a proposal inside the frozen band is permanently on screen by construction (R17). if (!formulaEdit.inBand) { const viewRow = viewRowOf(target.row - 1); if (viewRow >= 0) gridRef.current?.scrollTo(viewIndexOf(visCols, target.col - 1), viewRow); } }, [columnRangeA1, formulaEdit, rowRangeA1, viewRowOf, visCols]); /** PM-9/PM-10/PM-11: `,`/`(`/`)` commit the live reference as literal text and leave point mode. */ const commitPointReference = useCallback((trailer: string) => { if (!formulaEdit) return; const draft = formulaEdit.draft.slice(0, formulaEdit.caret) + trailer + formulaEdit.draft.slice(formulaEdit.caret); setFormulaEdit({ ...formulaEdit, draft, caret: formulaEdit.caret + trailer.length, mode: "enter", pointCell: null, pointBand: null, rangeAnchor: null, insertStart: null, }); }, [formulaEdit]); /** FA-18/FA-20/FA-22: Tab or a double click. NEVER Enter (FA-19). */ const acceptFormulaSuggestion = useCallback((item: SuggestItem) => { if (!formulaEdit) return; const start = tokenStartAt(formulaEdit.draft, formulaEdit.caret); const inserted = acceptedText(item); const draft = formulaEdit.draft.slice(0, start) + inserted + formulaEdit.draft.slice(formulaEdit.caret); setFormulaEdit({ ...formulaEdit, draft, caret: start + inserted.length, dropdownIndex: 0, dismissed: false, }); }, [formulaEdit]); // ⛔⛔ W52-T06 LANE-LEAD FIX (found in independent review, before BUILT): PM-14's "typing a // character leaves point mode" branch in `onFormulaKeyDown`, and its Backspace/Delete sibling, // deliberately do NOT call `preventDefault()` -- the browser's own keystroke does the // inserting/deleting, which then fires a native `input` event and this handler, in the SAME // synchronous dispatch as the keydown that just ran. A full-object `setFormulaEdit({...formulaEdit, // ...})` here would spread the PRE-keystroke closure and silently stomp the mode/pointCell reset // `onKeyDown` just queued (both updates land in the same React batch; the second full-object // replace wins, discarding the first's fields it does not re-list). The FUNCTIONAL updater reads // React's own post-`onKeyDown` state instead of the stale closure, so the two updates merge // correctly regardless of batching order. const onFormulaChange = useCallback((e: ReactChangeEvent) => { const el = e.currentTarget; const draft = el.value; const caret = el.selectionStart ?? el.value.length; setFormulaEdit((prev) => (prev ? { ...prev, draft, caret, dropdownIndex: 0, dismissed: false } : prev)); }, []); const syncFormulaCaret = useCallback((el: HTMLTextAreaElement) => { if (!formulaEdit) return; setFormulaEdit({ ...formulaEdit, caret: el.selectionStart ?? el.value.length }); }, [formulaEdit]); const formulaSuggestions = useMemo( () => (formulaEdit ? suggest(formulaEdit.draft, formulaEdit.caret) : []), [formulaEdit], ); const formulaDropdownOpen = !!formulaEdit && !formulaEdit.dismissed && formulaSuggestions.length > 0; /** * ⭐⭐ W54-T21 / DESIGN.md SECTION 4 — THE FORMULA EDITOR'S ESCAPE, THROUGH THE ONE ARBITER. * * ⛔ IT USED TO BE THREE BRANCHES OF `onFormulaKeyDown`, which is the shape section 4 exists to * end: a surface deciding for itself whether it is allowed to answer a key. The stack decides * now. A menu or a dialog opened over this editor registers LATER, so it is topmost and takes * the press; nothing below hears the key at all. * * ⭐ THE TWO-STAGE LADDER FA-23 #1 SHIPPED IS PRESERVED, AND IT LIVES HERE RATHER THAN IN THE * ARBITER'S `cancelEditFirst`. That option cancels an edit by BLURRING the focused input and * stopping, which for this editor would mean the suggestion list survived and the draft was * committed by the blur - the opposite of both rungs. One entry, one close, and the close reads * the state to decide which rung it is on. * * ⚠ THE DISMISS RUNG RAISES `formulaEscaping` TOO. Its press blurred the input on the way in, * and without the flag that blur would commit the very draft the person is still typing. Focus * comes straight back through W54-T19's keyboard rescue, which sees a focus that went nowhere * while an editor is open and hands it to this input. */ useEscapeClose(formulaEdit !== null, () => { if (formulaDropdownOpen) { formulaEscaping.current = true; setFormulaEdit((prev) => (prev ? { ...prev, dismissed: true } : prev)); return; } abandonFormulaEditor(); }); const onFormulaKeyDown = useCallback((e: ReactKeyboardEvent) => { if (!formulaEdit) return; const { draft, caret, mode, caretOnly } = formulaEdit; const caretArrow = caretOnly && !e.ctrlKey && !e.metaKey && !e.altKey; // W57-T01 / C1: the formula input owns focus, so these keys cannot reach the grid handler. // Use its SAME matcher and action names above point mode's early returns: both entry modes // widen the pointed cell (or the editing anchor) through the ONE proposal splice. Passing // false clears any rectangular range anchor; a repeated press replaces that live proposal, // and the existing caret effect keeps focus just after the reference inside the formula. // W57-T02: dispatch BEFORE the dropdown because it consumes Up/Down without checking Ctrl. // Plain arrows and Tab do not match these actions; F2 can reserve the arrows for the caret // below while the dropdown keeps its existing Tab behavior. const hit: ShortcutId | null = matchShortcut(e); if (hit === "select-column" || hit === "select-row") { e.preventDefault(); const target = mode === "point" ? (formulaEdit.pointCell ?? formulaEdit.anchor) : formulaEdit.anchor; proposeCell(target, false, hit === "select-column" ? "column" : "row"); return; } // W57-T04 / C1: the grid and formula editor share the same region in real coordinates. // Only this boundary converts the zero-based rectangle to the one-based proposal splice. if (hit === "select-region") { e.preventDefault(); const from = formulaEdit.pointCell ?? formulaEdit.anchor; const region = currentRegion({ col: from.col - 1, row: from.row - 1 }, extent, (c, r) => isFilled(tab, c, r)); const topLeft: RealCell = { col: region.col0 + 1, row: region.row0 + 1 }; const bottomRight: RealCell = { col: region.col1 + 1, row: region.row1 + 1 }; proposeCell(bottomRight, true, undefined, topLeft); return; } // W57-T02 / C1: share the grid's edgeIndex walk and keep all A1 edits in proposeCell. // RealCell is 1-based; edgeIndex and isFilled are 0-based. Convert once on entry and once // on exit, or every reference silently lands one cell off. Point mode walks its active end; // a NEW extended range starts at the clamped plain-arrow neighbour and walks from there. // Enter mode only claims reference positions, preserving text navigation elsewhere. A jump // clears rangeAnchor, while an extension keeps the existing anchor across repeat presses. if (hit === "jump-edge" || hit === "extend-edge") { const step = arrowStep(e.key); if (step && (mode === "point" || isRefPosition(draft, caret))) { e.preventDefault(); const extending = hit === "extend-edge"; const rangeFrom: RealCell | undefined = mode === "enter" && extending ? { col: clampCol(formulaEdit.anchor.col + step.dCol), row: clampRow(formulaEdit.anchor.row + step.dRow) } : undefined; const from = mode === "point" ? (formulaEdit.pointCell ?? formulaEdit.anchor) : (rangeFrom ?? formulaEdit.anchor); const fromColZero = from.col - 1; const fromRowZero = from.row - 1; const edgeZero = step.dRow !== 0 ? { col: fromColZero, row: edgeIndex(fromRowZero, extent.rows, step.dRow, (i) => isFilled(tab, fromColZero, i)) } : { col: edgeIndex(fromColZero, extent.cols, step.dCol, (i) => isFilled(tab, i, fromRowZero)), row: fromRowZero }; const edgeCell: RealCell = { col: edgeZero.col + 1, row: edgeZero.row + 1 }; proposeCell(edgeCell, extending, undefined, rangeFrom); return; } } if (formulaDropdownOpen) { if (e.key === "ArrowDown" && !caretArrow) { e.preventDefault(); setFormulaEdit({ ...formulaEdit, dropdownIndex: (formulaEdit.dropdownIndex + 1) % formulaSuggestions.length, }); return; } if (e.key === "ArrowUp" && !caretArrow) { e.preventDefault(); setFormulaEdit({ ...formulaEdit, dropdownIndex: (formulaEdit.dropdownIndex - 1 + formulaSuggestions.length) % formulaSuggestions.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 never asked here, which is what // lets it fall through to a plain commit further down instead of accepting a suggestion. if (acceptsSuggestion(e.key)) { e.preventDefault(); acceptFormulaSuggestion( formulaSuggestions[Math.min(formulaEdit.dropdownIndex, formulaSuggestions.length - 1)], ); return; } // ⛔ W54-T21: FA-23 #1's first rung, the one that dismisses the list, is NOT read here any // more. It is the first rung of the arbiter registration above, and a copy of it in this // handler would be a second owner of one key press. } // ⭐⭐ W54-T25 / R9(i) — F4 CYCLES THE ANCHORS OF THE REFERENCE UNDER THE CARET. // // ⛔ ABOVE THE POINT-MODE BLOCK ON PURPOSE, so one key means one thing wherever the editor is // open. A proposal being pointed at lives in this same draft text, so cycling it is the same // edit on the same string; the mode, the anchor and the insert start are all left alone. // // ⛔⛔ OFF A REFERENCE, THE NEAREST ONE LEFT OF THE CARET CYCLES (D-691), so F2 then F4 works. // A null answer still stops the key: the grid's whole-formula F4 must not take an open editor. if (e.key === "F4") { e.preventDefault(); const cycled = cycleAnchorAtCaret(draft, caret); if (!cycled) return; setFormulaEdit((prev) => (prev ? { ...prev, draft: cycled.text, caret: cycled.caret, dropdownIndex: 0 } : prev)); return; } // W57-T04: F2 switches Excel's Enter/Edit arrow behavior without changing the draft. // Retire any live proposal before allowing native caret movement; its old insertStart // must never be reused after the caret moves. Explicit Ctrl gestures are dispatched above. if (e.key === "F2") { e.preventDefault(); setFormulaEdit({ ...formulaEdit, caretOnly: !caretOnly, mode: "enter", pointCell: null, pointBand: null, rangeAnchor: null, insertStart: null, }); return; } if (mode === "point") { if (ARROW_DELTA[e.key]) { if (caretArrow) { // A Ctrl gesture can propose while F2's caret mode is active. The next plain arrow // retires that proposal, then the browser moves the caret without preventDefault. setFormulaEdit({ ...formulaEdit, mode: "enter", pointCell: null, pointBand: null, rangeAnchor: null, insertStart: null, }); return; } e.preventDefault(); const dir = ARROW_DELTA[e.key]; const from = formulaEdit.pointCell ?? formulaEdit.anchor; proposeCell({ col: clampCol(from.col + dir.dCol), row: clampRow(from.row + dir.dRow) }, e.shiftKey); return; } if (e.key === ",") { e.preventDefault(); commitPointReference(","); return; } if (e.key === "(" || e.key === ")") { e.preventDefault(); commitPointReference(e.key); return; } // PM-12: Enter commits the reference AND the whole formula, one keystroke, two effects. if (e.key === "Enter" || e.key === "Tab") { e.preventDefault(); commitPointReference(""); commitFormulaEditor(); return; } // ⛔ W54-T21: PM-13 - Esc in point mode abandons the WHOLE edit rather than the proposal - // is unchanged behaviour, and it is now the arbiter's second rung above. Point mode reaches // the same abandon the enter mode does, which is what PM-13 always asked for. if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) { // PM-14: any other typed character leaves point mode and is inserted literally. No // `preventDefault` -- the browser's own keystroke does the inserting. setFormulaEdit({ ...formulaEdit, mode: "enter", pointCell: null, pointBand: null, rangeAnchor: null, insertStart: null, }); return; } // W57-T04 - MOVING THE CARET BY HAND LEAVES POINT MODE. insertStart records where the // live proposal begins; after the reader moves elsewhere, reusing it would splice over // unrelated characters. No preventDefault: the browser still moves or deletes, just as // PM-14's sibling branch relies on the browser to insert the typed character. if (e.key === "Backspace" || e.key === "Delete" || e.key === "Home" || e.key === "End") { setFormulaEdit({ ...formulaEdit, mode: "enter", pointCell: null, pointBand: null, rangeAnchor: null, insertStart: null, }); } return; } // PM-4: an arrow key at a legal reference position starts point mode, anchored on the // EDITING cell (never the grid's own selection). if (!caretArrow && ARROW_DELTA[e.key] && isRefPosition(draft, caret)) { e.preventDefault(); const dir = ARROW_DELTA[e.key]; proposeCell( { col: clampCol(formulaEdit.anchor.col + dir.dCol), row: clampRow(formulaEdit.anchor.row + dir.dRow) }, false, ); return; } if (e.key === "Enter") { e.preventDefault(); commitFormulaEditor(); return; } // W59-T01 / instruction 3: plain-edit Tab commits and moves right; Shift+Tab moves left. // The dropdown and point-mode branches above keep ownership of their Tab gestures. if (e.key === "Tab") { if (e.ctrlKey || e.metaKey || e.altKey) return; e.preventDefault(); commitFormulaEditor(e.shiftKey ? "left" : "right"); return; } // ⛔ W54-T21: and NOTHING in this handler reads Escape, in any branch. The arbiter's listener // is capture phase on the document and stops propagation, so a branch here could never fire // anyway - it would be dead code that a later reader would trust. }, [ acceptFormulaSuggestion, arrowStep, clampCol, clampRow, commitFormulaEditor, commitPointReference, currentRegion, edgeIndex, extent.cols, extent.rows, formulaDropdownOpen, formulaEdit, formulaSuggestions, isFilled, matchShortcut, proposeCell, tab, ]); // The caret has to land where `formulaEdit.caret` says on every mutation, which React does not // do for a controlled input on its own (setting `value` programmatically puts the browser's own // caret at the end). One effect covers every mutator above rather than a `requestAnimationFrame` // repeated in each of them. useEffect(() => { if (!formulaEdit) return; const el = formulaInputRef.current; if (!el) return; el.focus(); el.setSelectionRange(formulaEdit.caret, formulaEdit.caret); }, [formulaEdit?.addr, formulaEdit?.caret, formulaEdit?.draft]); /** * ⭐⭐ CR-1/CR-5/CR-10/PM-6 — EVERY CELL A LIVE REFERENCE TOUCHES, KEYED BY ITS REAL 1-BASED * `"col,row"` ADDRESS, TO ITS COLOUR AND REFERENCE ORDINAL. `refsIn` already scans the draft * on every keystroke (CR-10: "recolour on every keystroke"), and since a point-mode proposal is spliced * into the SAME draft text as any other reference (`proposeCell` above), the proposal gets its * border for free through this one map -- PM-6 needs no separate mechanism. * * W59-T05 / INSTRUCTION 17 / R7: ONE OUTER PERIMETER PER REFERENCE. Each cell paints only * edges whose neighbour belongs to a different reference or none. Reference ordinals keep * touching ranges separate even when their slot colours repeat; no interior fill is added. * * ⭐⭐ QI27 / S67-T01 (2026-09-28) — A FORMULA'S REFERENCES ARE OUTLINED ONLY WHILE IT IS * EDITED. The owner revoked W53-T02 / instruction 18 (outlines on a bare selection): arrowing or * clicking onto a formula cell outlines nothing; F2, a double-click or typing opens the editor, * and only the editor's draft lends its text to this engine. That matches Microsoft's own page * ("double-click the cell ... Excel highlights each cell or range of cells referenced by the * formula with a different color"). References a mounted panel asks about (`externalRefs`, * e.g. Filter's "a cell") still outline with or without an editor (O39). One border map, one * paint path (`paintRefBorder` further down) - there is no second outline mechanism. */ const externalRefs = useHighlightedCellRefs(); const formulaRefCells = useMemo(() => { const out = new Map(); const source = formulaEdit ? formulaEdit.draft : ""; // Hotfix 2026-09-24 (owner: "ANYWHERE in the app ... the cell must be highlighted"): every // reference a mounted panel is asking about (`refHighlight.ts`) joins the SAME map, after the // formula's own, so it gets the outline and the repaint this map already has. A reference // naming another tab outlines nothing here. const external = externalRefs.flatMap((text) => refsIn(text).filter((ref) => !ref.start.sheet || ref.start.sheet.toLowerCase() === tab.name.toLowerCase())); if (!source && external.length === 0) return out; let refOrdinal = 0; const formulaRefs = source ? refsIn(source) : []; const slotBase = formulaRefs.reduce((top, ref) => Math.max(top, ref.colorIndex + 1), 0); for (const ref of [...formulaRefs, ...external.map((ref, i) => ({ ...ref, colorIndex: slotBase + i }))]) { const ordinal = refOrdinal++; // Count every reference, including ranges skipped by the cap. let c0 = colToIndex(ref.start.col); let c1 = colToIndex(ref.end.col); let r0 = ref.start.row; let r1 = ref.end.row; if (ref.band === "column") { r0 = 1; r1 = BAND_HIGHLIGHT_SPAN; } else if (ref.band === "row") { c0 = 1; c1 = BAND_HIGHLIGHT_SPAN; } // A pathological typed range or a band with a huge used extent must not stall a paint. if ((Math.abs(c1 - c0) + 1) * (Math.abs(r1 - r0) + 1) > 4000) continue; const color = colorForSlot(ref.colorIndex, "light"); for (let c = Math.min(c0, c1); c <= Math.max(c0, c1); c += 1) { for (let r = Math.min(r0, r1); r <= Math.max(r0, r1); r += 1) { out.set(`${c},${r}`, { color, ref: ordinal }); } } } return out; }, [externalRefs, formulaEdit, tab.name]); // A reference a person just TYPED is scrolled to, so a cell far off screen (R9997) is seen being // outlined rather than outlined out of sight. Opening a panel scrolls nowhere (refHighlight.ts). useCellRefFocus((text) => { const ref = refsIn(text)[0]; if (!ref || (ref.start.sheet && ref.start.sheet.toLowerCase() !== tab.name.toLowerCase())) return; const viewRow = viewRowOf(ref.start.row - 1); if (viewRow >= 0) gridRef.current?.scrollTo(viewIndexOf(visCols, colToIndex(ref.start.col) - 1), viewRow); }); /** * ⭐⭐ W53-T02 / INSTRUCTION 18, VERBATIM — THE LIVE POINT-MODE PROPOSAL, AND IT IS THE ONE * THING DRAWN DASHED. "when navigating with arrow keys from the formula form say from =D7 to * =D6, the CELL of D6 should be dashed outlined in colour so the user knows which cell is * highlighted." * * ⛔ DASHED HERE, SOLID EVERYWHERE ELSE, and the two are not in conflict: they are different * states. `.claude/wiki/research/excel-formula-ux.md` §1 quotes Microsoft on a formula's * SETTLED references - "the cell range has a blue border with square corners" - so a reference * keeps the solid border it already had, in edit AND in select. What is dashed is only the * proposal still moving under the arrow keys, which is exactly the cell instruction 18 names. * * ⚠ AND IT IS NOT THE COPY MARQUEE. `paintMarquee` below also dashes, in `--lp-blue-deep`, * always the same colour; this one carries the REF_COLORS slot colour of the reference it is * building, which the marquee never does, so the two never read as the same event. * * ⭐ IT READS `pointCell`/`rangeAnchor` RATHER THAN RE-SCANNING THE DRAFT, because the draft * cannot say WHICH of its references is the live one: `=F6+F6` has two occurrences of the same * text and only one of them is under the arrow keys. */ // W57-T01: a band inserted in point mode is still the live proposal; the next arrow replaces // it with a cell reference. Dash the whole bounded band until it settles, then leave it solid. const formulaPointCells = useMemo(() => { const out = new Set(); if (!formulaEdit || formulaEdit.mode !== "point" || !formulaEdit.pointCell) return out; let a = formulaEdit.rangeAnchor ?? formulaEdit.pointCell; let b = formulaEdit.pointCell; if (formulaEdit.pointBand === "column") { a = { col: b.col, row: 1 }; b = { col: b.col, row: BAND_HIGHLIGHT_SPAN }; } else if (formulaEdit.pointBand === "row") { a = { col: 1, row: b.row }; b = { col: BAND_HIGHLIGHT_SPAN, row: b.row }; } // The same cap `formulaRefCells` uses: a pathological proposal must not stall a paint. if ((Math.abs(b.col - a.col) + 1) * (Math.abs(b.row - a.row) + 1) > 4000) return out; for (let c = Math.min(a.col, b.col); c <= Math.max(a.col, b.col); c += 1) { for (let r = Math.min(a.row, b.row); r <= Math.max(a.row, b.row); r += 1) { out.add(`${c},${r}`); } } return out; }, [formulaEdit]); /** * ⭐⭐ W53-T02 — THE OUTLINES EXISTED AND NOBODY ASKED FOR THE REPAINT, WHICH IS WHY THEY WERE * INVISIBLE. Measured in the real app before this ticket: with `=F6+G6` open in E6, a screen * scan found the coloured GLYPHS in the editor and nothing at all on F6 or G6; forcing a full * redraw by resizing the window, with no state change of any kind, made both borders appear * (blue 222px wide, red 316px). So `paintRefBorder` was correct all along and glide simply * never redrew the cells it would have painted: a canvas grid repaints DAMAGED cells, and a * new `drawCell` closure alone does not damage the cells whose paint it changes. * * ⛔ THE UNION OF BEFORE AND AFTER, NOT JUST AFTER. A reference that has just been deleted, or * a proposal that has just moved off a cell, has to be repainted to LOSE its border - damaging * only the current set would leave the old outline burnt into the canvas. * * ⭐ THE KEY CARRIES COLOUR AND DASH, not merely the address, so leaving point mode (same * cells, solid instead of dashed) still counts as a change worth a repaint. Same shape as the * shimmer's `pendingBoundKey` above, and a negative view row is the frozen band's own grid for * the same reason. * * ⭐⭐ W54-T23 / INSTRUCTION 17 — IT NOW WALKS **BOTH** OUTLINE SOURCES, AND THAT IS THE WHOLE * OF THIS TICKET'S CHANGE. There are exactly two above: `formulaRefCells`, which falls back to * the SELECTED cell's stored formula when no editor is open, and `formulaPointCells`, the live * dashed proposal. This key used to be built from the first alone, on the reasoning that the * proposal is always written into the draft and so is always a subset of it. That reasoning is * true today and it is not a guarantee: `refsIn` deliberately refuses a token followed by an * opening bracket, reading it as a function name, so a proposal inserted immediately before one * is a point cell with no reference entry at all. Damaging only the first source would then * leave the second's cells outside the one repaint path that can ever take an outline OFF the * canvas. Walking both makes "no outline can outlive its reference" a property of the code * rather than of an argument about it. * * ⚠ A POINT-ONLY CELL CARRIES NO COLOUR, so it is keyed as such and paints nothing: the border * still comes from `formulaRefCells` alone, and this addition changes only WHICH cells are * asked to repaint. Widening a damage set can cost a repaint; it cannot invent a border. * * ⛔ MEASURED FIRST, ON THE OWNER'S OWN SEQUENCE, AND IT WAS ALREADY CLEAN. Thirty two states * were read off the real canvas at this tip by counting pixels in the six REF_COLORS: point * mode, commit, Escape, re-selection, a mouse drag, the blur commit, Delete, undo, a wheel * scroll, a focus that fell to the body, and a reopened editor whose reference was shrunk. Not * one of them left a pixel behind. So this is a HARDENING of a guarantee that already held, not * a repair of a residue that was seen. The frames and counts are in the wave 54 handoff. */ const refPaintKey = useMemo(() => { const parts: string[] = []; for (const [key, entry] of formulaRefCells) { parts.push(`${key}:${entry.color}:${formulaPointCells.has(key) ? "dash" : "solid"}:${entry.ref}`); } for (const key of formulaPointCells) { if (!formulaRefCells.has(key)) parts.push(`${key}:none:dash`); } return parts.join("|"); }, [formulaPointCells, formulaRefCells]); const paintedRefCells = useRef([]); useEffect(() => { const now = refPaintKey ? refPaintKey.split("|").map((p) => p.slice(0, p.indexOf(":"))) : []; const leaving = paintedRefCells.current.filter((key) => !now.includes(key)); const union = new Set([...paintedRefCells.current, ...now]); paintedRefCells.current = now; if (union.size === 0) return; const main: { cell: Item }[] = []; const band: { cell: Item }[] = []; for (const key of union) { const comma = key.indexOf(","); const col = Number(key.slice(0, comma)); const row = Number(key.slice(comma + 1)); if (!Number.isFinite(col) || !Number.isFinite(row)) continue; const viewCol = viewIndexOf(visCols, col - 1); const viewRow = viewRowOf(row - 1); if (viewRow < 0) band.push({ cell: [viewCol, viewRow + bandRows] as Item }); else main.push({ cell: [viewCol, viewRow] as Item }); } if (main.length > 0) gridRef.current?.updateCells(main); if (band.length > 0) bandGridRef.current?.updateCells(band); const leftBand = leaving.some((key) => viewRowOf(Number(key.slice(key.indexOf(",") + 1)) - 1) < 0); if (leftBand) setBandRepaint((n) => n + 1); }, [bandRows, refPaintKey, viewRowOf, visCols]); /** The selected rectangle in glide's own VIEW coordinates, or `null` when nothing is selected. */ const viewRange = useCallback((): CellRange | null => { const current = selection?.current; if (!current) return null; const r = current.range; return { col0: r.x, row0: r.y, col1: r.x + r.width - 1, row1: r.y + r.height - 1 }; }, [selection]); /** * ⛔ IT SITS HERE, ABOVE THE COPY AND PASTE DOORS, AND NOT BESIDE `selectedAddrs` WHERE IT USED * TO. `onPaste` now names `viewRange` in its dependency array (W53-T03), and a dependency array * is evaluated DURING the render that declares the callback: a `const` declared further down * the component body is still in its temporal dead zone at that moment, so the page throws on * first paint rather than on paste. */ /** * ⭐⭐ W51-T19 — THE SHEET'S OWN MEMORY OF WHAT WAS COPIED, AND WHY IT HAS TO EXIST. * * ⛔ A CLIPBOARD CARRIES TEXT. `copySelection` writes what each cell READS, which is what makes * a copy out of the sheet land correctly in Excel, and it is also why a bound cell arrives at a * paste as a bare number with no binding anywhere on it. Without a record of what was copied, * "paste a bound cell and its drag rules apply" is not a feature that can exist: there is * nothing in the payload to apply them to. * * ⚠ IT IS MATCHED ON THE TEXT, WHICH IS THE CONSERVATIVE DIRECTION. The block is used only * when the incoming values are byte for byte the text this component wrote, so a paste from * anywhere else lands as the values it really is. Guessing that a matching number must have * come from a binding would be the worse mistake by far. * * ⚠ AND IT ONLY SEES THE RIBBON'S OWN Copy. glide answers Ctrl+C itself through * `getCellsForSelection` and never tells this component, so Ctrl+C then Ctrl+V on a bound cell * still pastes its number. That is stated here rather than discovered later. */ const copiedRef = useRef(null); /** * ⭐⭐ W52-T07 — THE COPY MARQUEE AND THE PASTE HIGHLIGHT, THE VISIBLE HALF OF THE ABOVE. * * `copiedRef` already carried the copied block's real top-left and dimensions; nothing read it * for paint, and nothing cleared it. These two are plain `useState` (not another ref) because * `paintCell` has to repaint when they change and `useEscapeClose` has to see `active` flip — * neither happens off a ref mutation alone. A rectangle is real top-left col/row plus rows/cols, * exactly the shape `copySelection`'s `held` and `onPaste`'s `values` already hand over. * * ⚠ ASYMMETRIC LIFETIMES, ON PURPOSE. The copy marquee is Excel's own: it survives a selection * change so several pastes can be made from one copy, and clears only on Escape or when a new * copy/cut overwrites it (the closest this app can get to "the clipboard changed" — there is no * browser event for a clipboard write from elsewhere). The paste highlight is the more transient * of the two: it names what just happened rather than what is still available, so it also clears * on the very next selection change or edit, not only on the next paste or on Escape. */ const [copyMarquee, setCopyMarquee] = useState<{ col: number; row: number; cols: number; rows: number } | null>(null); const [pasteHighlight, setPasteHighlight] = useState<{ col: number; row: number; cols: number; rows: number } | null>(null); // ⛔ CONTRACT C8: through the one Escape arbiter, not a second `keydown` listener. Active // whenever either rectangle is showing; clears both together, since Escape is the one shared // "dismiss" gesture and a lone paste highlight with no copy marquee is still worth dismissing. useEscapeClose(copyMarquee !== null || pasteHighlight !== null, () => { copiedRef.current = null; setCopyMarquee(null); setPasteHighlight(null); }); /** * WHAT A COPY OF `range` PUTS ON THE CLIPBOARD, AND WHAT THIS COMPONENT REMEMBERS ABOUT IT. * * ⭐ IT WRITES WHAT THE CELL READS, not what it stores: `formatCellText` over `displayText`, so * a currency cell arrives in Excel as the currency somebody chose. That is the same string * `displayData` carries, which is what makes glide's own Ctrl+C agree with the ribbon's button * — and it is why the two copy doors can share one builder at all. * * ⭐ WAVE 54 BASE KIT: the BODY moved to `clipboardOps.ts::buildCopyPayload` unchanged, with its * four closed-over values handed over as arguments instead. The `useCallback` stays HERE, with * the same dependency array, because two consumers depend on its identity — the native-copy * `useEffect` below and `copySelection` both name `heldFor` in their own arrays. */ const heldFor = useCallback( (range: CellRange) => withClipboardScope(storagePrefix, () => { // C6: a whole axis is a DOCUMENT command. A hidden band or the split between the frozen // and body DataEditors may change what is painted, never which real cells Copy carries. // Feed the existing builder a real-coordinate rectangle and identity mappers for that one // case; ordinary rectangular selections retain their visible-cell projection. if (selection?.columns.length) { const col0 = realCol(Math.min(range.col0, range.col1)); const col1 = realCol(Math.max(range.col0, range.col1)); const documentRange = { col0, col1, row0: 0, row1: Math.max(0, extent.rows - 1) }; return copyCells(tab, buildCopyPayload(documentRange, cells, (col, row) => addressOf(col, row), value => value, value => value, extent), workbook.id, storagePrefix); } if (selection?.rows.length) { const row0 = realRow(Math.min(range.row0, range.row1)); const row1 = realRow(Math.max(range.row0, range.row1)); const documentRange = { col0: 0, col1: Math.max(0, extent.cols - 1), row0, row1 }; return copyCells(tab, buildCopyPayload(documentRange, cells, (col, row) => addressOf(col, row), value => value, value => value, extent), workbook.id, storagePrefix); } return copyCells(tab, buildCopyPayload(range, cells, addrAt, realCol, realRow, { cols: visCols.length, rows: bandRows + visRows.length }), workbook.id, storagePrefix); }), [addrAt, bandRows, cells, extent, realCol, realRow, selection, storagePrefix, tab, visCols.length, visRows.length, workbook.id], ); /** * ⭐⭐ W53-T03 / INSTRUCTION 24 — THE NATIVE Ctrl+C IS A COPY THIS COMPONENT KNOWS ABOUT NOW. * * ⛔ THE DEFECT IT ENDS: glide answers the browser's own copy through `getCellsForSelection` * and never told this component, so after a native Ctrl+C `copiedRef` still held whatever the * ribbon's button last copied, or nothing at all. Copying one BLANK cell that way then reads * back as an empty clipboard, and the paste was refused with "There is nothing on the clipboard * to paste." rather than blanking the selection. * * ⭐ SO THE FIX IS TO TELL THE TRUTH TO THE EXISTING TEST, NOT TO WEAKEN IT. `isRecognizedCopy` * keeps its exact question — is this text the text WE last copied — and simply stops being * asked about a copy nobody recorded. The two questions the ticket names stay separate: an * unset clipboard is still unset; a copied blank region is now a copy this component made. * * ⚠ CAPTURE PHASE, ON THE WRAP. glide listens on the WINDOW, so a bubbling listener here would * still see the event, but capture removes any dependence on what glide does with it. The * marquee is set from the same rectangle the ribbon's Copy sets it from, so the two doors can * never disagree about what is copied. * * ⚠ A COPY OUT OF A TEXT BOX IS NOT A COPY OF CELLS. An editor overlay inside the wrap copies * characters, and recording that as a block copy would leave the sheet believing it holds a * region somebody never selected. */ useEffect(() => { const node = wrapRef.current; if (!node) return undefined; const record = (event: Event) => { const from = event.target; if (from instanceof Element && from.closest("input, textarea, [contenteditable=\"true\"]")) { return; } const range = viewRange(); if (!range) return; const held = heldFor(range); copiedRef.current = held; if (event.type === "cut") rememberCut(held, storagePrefix); setCopyMarquee({ col: held.col, row: held.row, cols: held.cells[0]?.length ?? 0, rows: held.cells.length }); }; node.addEventListener("copy", record, true); node.addEventListener("cut", record, true); return () => { node.removeEventListener("copy", record, true); node.removeEventListener("cut", record, true); }; }, [heldFor, storagePrefix, viewRange]); /** The drag rules for a paste of `values`, or `undefined` when this block is not ours. */ const copiedBlock = useCallback( (values: readonly (readonly string[])[]): DragContext | undefined => { const held = copiedRef.current; if (!held) { return { catalogue: options, shadows: viewShadows, workbookId: workbook.id }; } const text = values.map((row) => row.join("\t")).join("\n"); if (text !== held.text) { return { catalogue: options, shadows: viewShadows, workbookId: workbook.id }; } return { catalogue: options, shadows: viewShadows, workbookId: workbook.id, cells: held.cells, from: { col: held.col, row: held.row }, }; }, [options, viewShadows, workbook.id], ); /** * ⭐⭐ R5 (W52-T09) — TELLING "COPIED A BLANK RANGE" FROM "THE CLIPBOARD IS GENUINELY EMPTY". * Both read back as an empty string: a single blank cell, copied, is `""`; an OS clipboard that * was never written to is also `""`. `copiedRef` is this component's own memory of the last * thing ITS Copy/Cut wrote (`copySelection`), so a match here means the empty text is a real * copy somebody meant to paste back as blanks; anything else means there is nothing to paste. * * ⚠ THE KNOWN GAP: glide answers the browser's own Ctrl+C through `getCellsForSelection` and * never tells this component (see `copiedRef`'s own note), so a native Ctrl+C of a single blank * cell followed by a native Ctrl+V still reads as "genuinely empty" here. That is the honest * limit of tracking only this component's OWN copy door, not a new sentinel invented to paper * over it. */ const isRecognizedCopy = useCallback( (text: string): boolean => { const recovered = recallCopy(text, storagePrefix); // The lookup has already matched either normalized clipboard representation. const held = recovered ? { ...recovered, text } : copiedRef.current; return held !== null && held.text === text; }, [storagePrefix], ); useEffect(() => { // An in-app copy is known to be there, so only an unknown clipboard is read, once per opening. if (!menu || readOnly || copiedRef.current !== null) return; let current = true; // Excel can own the clipboard without any in-app copy. Unknown or denied stays enabled: the // Paste door itself names a denied read when it is used, never on every right-click. void readClipboardPayload().then(({ text }) => { if (current) setMenuClipboard({ owner: menu, empty: !text && !isRecognizedCopy(text) }); }).catch(() => undefined); return () => { current = false; }; }, [isRecognizedCopy, menu, readOnly]); /** The whole axis behind this clipboard text, when this app is the one that copied it. */ const copiedAxis = useCallback((text: string): WholeAxis => { const held = copiedRef.current ?? recallCopy(text, storagePrefix); if (!held) return null; const key = wholeAxisClipboardKey(text); // Glide's HTML copy returns editable text; the ribbon returns formatted text. Matching // just one would preserve the other axis through only one of the two paste doors. return key === wholeAxisClipboardKey(held.text) || (held.editable !== undefined && key === wholeAxisClipboardKey(held.editable)) ? held.wholeAxis ?? null : null; }, [storagePrefix]); /** * ⭐⭐ LAND A BULK DOOR'S EDITS AND SAY EVERYTHING IT HAS TO SAY, IN ONE PASS. * * ⛔⛔ THE TWO FACTS ARE JOINED, NEVER RANKED, AND THAT IS THE POINT OF THIS FUNCTION. A fill * can refuse a value against a cell's list AND keep a bound cell's filter because nothing * loaded, in one drag, on two different cells. Writing them as `if / else if` would make the * first one silence the second, which is the same silent drop this function exists to prevent. * * ⛔⛔ AND A BOUND CELL IS NEVER SCREENED AGAINST A VALIDATION LIST. `screenEdits` compares an * incoming cell's TEXT against the list the target already carries, which is exactly right for * a value somebody typed or pasted and exactly wrong for one a database computed: a locked * bound cell dragged onto a validated address would be refused with "100 is not one of this * cell's allowed values", about a number nobody chose, and the edit would vanish. Before * W51-T19 a bound cell could not reach this door at all, so this is a case the drag rules * created and the drag rules have to answer. */ const landFill = useCallback((out: FillEdit, screen: boolean) => { const dragged: Record = {}; const plain: Record = {}; for (const [addr, cell] of Object.entries(out.edits)) { if (screen && cell && cell.kind === "bound") dragged[addr] = cell; else plain[addr] = cell; } const screened = screen ? screenEdits(tab, plain) : { edits: plain, refusals: [] as { addr: string; message: string }[] }; const edits = { ...dragged, ...screened.edits }; // ⭐ W53-T01: a fill or a paste can change a cell some OTHER formula reads, so the landing // door recalculates its dependents in the same commit every typed edit does. if (Object.keys(edits).length > 0 || (out.tab && ["rules", "charts", "colWidths"].some( key => out.tab?.[key as keyof SheetTab] !== tab[key as keyof SheetTab]))) { commitWithRecalc(edits, out.move, out.tab); // C5: schedule only the bound cells that ACTUALLY landed. The page owns save ordering and // revisions, so this seam carries identities instead of calling Refresh or a second writer. const pending: Record = {}; for (const [addr, cell] of Object.entries(edits)) { if (cell?.kind === "bound") pending[addr] = cell; } if (Object.keys(pending).length > 0) { onEvaluateBindings?.({ tabId: tab.id, cells: pending }); } } const said = [ screened.refusals.length > 0 ? refusalLabel(screened.refusals) : "", boundDragLabel(out), ].filter(Boolean).join(" "); if (said) onNotice(said); }, [commitWithRecalc, onEvaluateBindings, onNotice, tab]); /** * ⭐ THE PASTE IS OURS, NOT GLIDE'S, AND IT RETURNS `false` DELIBERATELY. glide has already * read the clipboard and split it on tabs and newlines by the time this runs, so the TSV work * Excel needs is done; what glide's own application would not do is tell a genuinely empty * clipboard from a copied blank range (R5), or turn a pasted `=B4*2` into a formula. * Returning `false` stops glide there and `pasteCells` lands the block. */ const onPaste = useCallback( (target: Item, values: readonly (readonly string[])[]) => { if (readOnly) return false; // ⭐⭐ R5 (W52-T09) — THE SECOND DOOR NEEDS THE SAME DISTINCTION `pasteFromClipboard` DOES. // glide hands over `values` already parsed, so the text this component would have read // itself is rebuilt the same way `copiedBlock` builds it, and checked against `copiedRef`. // Only a single blank cell's worth of payload (`""`) is EVER ambiguous; a multi-cell blank // range still joins into a non-empty tab/newline string and never reaches this branch. const text = values.map((row) => row.join("\t")).join("\n"); if (!text && !isRecognizedCopy(text)) { onNotice("There is nothing on the clipboard to paste."); return false; } // ⚠ THE TARGET IS TRANSLATED, THE BLOCK IS NOT. A paste lands as a rectangle in the SHEET, // which is Excel's own behaviour: it fills hidden rows too rather than skipping them and // silently landing a person's forty values on the wrong forty cells. // ⭐⭐ W53-T03 — GLIDE HANDS OVER THE ANCHOR, NEVER THE SELECTION, so this door reads the // dragged rectangle itself. That rectangle is what decides how many times the copied block // lands: one copied cell fills a selection of twenty, exactly as Excel does it. const range = viewRange(); const axis = copiedAxis(text); const at = wholeAxisAnchor(axis, { col: realCol(target[0]), row: realRow(target[1]) }, { col: copiedRef.current?.col ?? 0, row: copiedRef.current?.row ?? 0 }); // R18: a whole axis lands once at its anchor. Tiling it over a dragged selection would // give the clicked cell a second meaning; partial ranges keep W53-T03's region unchanged. const out = pasteCells(tab, at.col, at.row, values, { cols: extent.cols, rows: extent.rows }, copiedBlock(values), cellValueGetter, axis !== null ? undefined : range ? { col0: realCol(range.col0), row0: realRow(range.row0), col1: realCol(range.col1), row1: realRow(range.row1) } : undefined, "normal", storagePrefix); // ⛔ A SIZE REFUSAL WRITES NOTHING, so it is said and the door closes before anything is // landed or highlighted. if (out.sizeRefusal || out.layerRefusal) { onNotice(out.sizeRefusal ?? out.layerRefusal ?? ""); return false; } // ⛔⛔ W51-T18 / C2 — A PASTE IS ONE OF THE TWO DOORS THAT CAN LAND A VALUE OUTSIDE A CELL'S // LIST, and it is the one that gets forgotten because the dropdown looks like the whole // feature. The block is screened against the validation the TARGET already carries, the // allowed cells land, and every refusal is named in one sentence rather than forty. // ⚠ S65-T07 turned this OFF and it is turned back ON: R12 governs what a pasted cell // CARRIES, never whether a value the target forbids is allowed to land. The one place the // two rules do meet is disclosed on the ticket rather than settled by retiring this one. landFill(out, true); // ⭐ W52-T07: the WHOLE destination range, not just the anchor `target` glide handed over — // `values`' own shape (rows outer, cols inner) IS that range's size. setPasteHighlight({ col: at.col, row: at.row, cols: values[0]?.length ?? 0, rows: values.length }); return false; }, [cellValueGetter, copiedAxis, copiedBlock, extent.cols, extent.rows, isRecognizedCopy, landFill, onNotice, readOnly, realCol, realRow, storagePrefix, tab, viewRange], ); /** * The fill handle. `preventDefault` stops glide copying the pattern verbatim, because a dragged * FORMULA must have its references shifted (`a1.ts::fillFormula`) and glide has no idea that * the text it is repeating is a formula. * * ⚠ `getCellsForSelection` is load bearing for this, not only for copy: glide returns early and * never calls this handler when that prop is undefined. */ const onFillPattern = useCallback( (event: { patternSource: Rectangle; fillDestination: Rectangle; preventDefault: () => void }) => { event.preventDefault(); const src = event.patternSource; const dst = event.fillDestination; const out = fillCells( tab, { col0: realCol(src.x), row0: realRow(src.y), col1: realCol(src.x + src.width - 1), row1: realRow(src.y + src.height - 1) }, { col0: realCol(dst.x), row0: realRow(dst.y), col1: realCol(dst.x + dst.width - 1), row1: realRow(dst.y + dst.height - 1) }, // ⛔⛔ W51-T19 / R9 / R10 — THE BOUND CELLS ARE DIVERTED BEFORE ANY OF THE LITERAL AND // FORMULA WORK BELOW THEM, and they are diverted INSIDE the one fill primitive rather // than by a second pass here. `fillCells` decides on a bound pattern ahead of its // formula branch and hands it to `dragBoundCell`; the fill handle, Ctrl+D, Ctrl+R and // paste therefore share R5's localisation and R13's signed stepping. { catalogue: options, shadows: viewShadows }, // ⭐ W53-T01 / R2: a dragged formula shows its NUMBER when it lands, not its text. cellValueGetter, ); // ⛔ W51-T18 / C2 — AND THE FILL IS THE SECOND DOOR. Dragging a value down a column lands // it on every cell it passes, list or no list, so it is screened exactly as the paste is. landFill(out, true); }, [cellValueGetter, landFill, options, realCol, realRow, tab, viewShadows], ); /** Every address the selection covers, translated. `[]` when nothing is selected. */ const selectedAddrs = useCallback((): string[] => { const range = viewRange(); if (!range) return []; const out: string[] = []; if (selection?.columns.length) { const col0 = realCol(Math.min(range.col0, range.col1)); const col1 = realCol(Math.max(range.col0, range.col1)); for (let row = 0; row < extent.rows; row += 1) { for (let col = col0; col <= col1; col += 1) out.push(addressOf(col, row)); } return out; } if (selection?.rows.length) { const row0 = realRow(Math.min(range.row0, range.row1)); const row1 = realRow(Math.max(range.row0, range.row1)); for (let row = row0; row <= row1; row += 1) { for (let col = 0; col < extent.cols; col += 1) out.push(addressOf(col, row)); } return out; } return addressesInView(range); }, [addressesInView, extent.cols, extent.rows, realCol, realRow, selection, viewRange]); /** * ⭐⭐ W50-T19 — ONE RIBBON ACT, APPLIED TO THE SELECTION, THROUGH THE ONE COMMIT DOOR. * * It routes to `onCommit`, which is `SheetPage.tsx::commitCells`, so a format change is ONE * history step and ONE save. Ctrl+Z undoes a whole bolded range rather than its last cell, * exactly as it does for a paste, and nothing here opens a second save path. * * ⭐⭐ W51-T16 / D-641 — IT STYLES BLANK CELLS NOW, AND THE COUNT ON THE HEADER STAYS PUT. * W50-T19 carried `if (!cell) continue` here, so selecting three empty cells and pressing * Borders painted nothing: creating a cell would have meant `kind: "literal"`, and * `handTypedCount` counts every literal, so the header would have claimed three hand typed * values nobody typed. Contract C2's `empty` kind removes that trade, and the decision moved * into `cellStyleOps.ts::styleCells` where a node proof can execute it rather than grep it. * (Wave 54 moved that function one file further, out of `sheetState.ts`, which re-exports it.) * * ⚠ R19 / R20, DECIDED AND STATED: styling a BOUND cell is allowed and is NOT a conversion. * A colour changes nothing about where the value comes from, the binding survives, the mark * survives, and the next Refresh repaints the same cell in the same colour. So a cell's KIND is * deliberately not consulted here, which is the opposite of what every EDIT door does under R5. * * ⚠ R10 IS UNTOUCHED: a format presents the stored value and never recomputes it. */ const applyStyle = useCallback((patch: CellStylePatch) => { if (readOnly) return; const addrs = selectedAddrs(); if (addrs.length === 0) { onNotice("Select a cell first, then choose a format for it."); return; } const out = styleCells(tab, addrs, patch); if (Object.keys(out.edits).length === 0) return; onCommit(out.edits); }, [onCommit, onNotice, selectedAddrs, tab, readOnly]); /** * ⭐⭐ S67-T11 (QI16, J16, C2) — EXCEL'S DRAW BORDER PENS. Lane B's Borders menu raises * `aios:sheet-border-draw` with `{mode: "draw" | "grid" | "erase", style, color}`; any other * mode (or a null detail) puts the pen down. While a pen is up, the range a drag covers takes * it when the pointer is released: `draw` the range's outline, `grid` every edge of every cell, * `erase` every side drawn along or inside the range, including an outside neighbour's side on * the same line. Sides are written in C2's shape only. Escape puts the pen down (a claim on the * shared arbiter), and with no pen a click selects exactly as before. */ const [borderPen, setBorderPen] = useState(null); const borderPenRef = useRef(null); borderPenRef.current = borderPen; // Escape puts the pen down, through the sheet's one Escape arbiter like every other surface. useEscapeClose(borderPen !== null, () => setBorderPen(null)); useEffect(() => { const onPen = (event: Event) => { const detail = (event as CustomEvent | null>).detail; const mode = detail?.mode; if (mode !== "draw" && mode !== "grid" && mode !== "erase") { setBorderPen(null); return; } const style = String(detail?.style ?? ""); const color = String(detail?.color ?? ""); setBorderPen({ mode, style: BORDER_PEN_STYLES.includes(style) ? style : "thin", color: /^#[0-9a-fA-F]{6}$/.test(color) ? color : "#000000", }); // The pen is picked from a menu; the grid takes focus so the drag and Escape reach it. gridRef.current?.focus(); }; window.addEventListener("aios:sheet-border-draw", onPen); return () => window.removeEventListener("aios:sheet-border-draw", onPen); }, []); const applyBorderPen = useCallback((pen: BorderPen) => { const selected = selectionRef.current; // A header press selects whole rows or columns; the pen draws on cells only. if (!selected || selected.columns.length > 0 || selected.rows.length > 0) return; const r = selected.current?.range; if (!r) return; const col0 = r.x, row0 = r.y, col1 = r.x + r.width - 1, row1 = r.y + r.height - 1; const line: BorderPenLine = { style: pen.style, color: pen.color }; const borders = new Map>>(); const own = (addr: string) => { if (!borders.has(addr)) borders.set(addr, { ...(cellAt(tab, addr)?.style?.border ?? {}) }); return borders.get(addr)!; }; const set = (addr: string, side: BorderPenSide, value: BorderPenLine | null) => { const border = own(addr); if (value) border[side] = { ...value }; else delete border[side]; }; for (let row = row0; row <= row1; row += 1) { for (let col = col0; col <= col1; col += 1) { const addr = addrAt(col, row); if (pen.mode === "grid") { for (const side of ["top", "right", "bottom", "left"] as const) set(addr, side, line); } else if (pen.mode === "draw") { if (row === row0) set(addr, "top", line); if (row === row1) set(addr, "bottom", line); if (col === col0) set(addr, "left", line); if (col === col1) set(addr, "right", line); } else { for (const side of ["top", "right", "bottom", "left"] as const) set(addr, side, null); // The same line drawn from outside the range is erased with it, as in Excel. if (row === row0 && row - 1 >= -bandRows) set(addrAt(col, row - 1), "bottom", null); if (row === row1 && row + 1 < visRows.length) set(addrAt(col, row + 1), "top", null); if (col === col0 && col > 0) set(addrAt(col - 1, row), "right", null); if (col === col1 && col + 1 < columns.length) set(addrAt(col + 1, row), "left", null); } } } const edits: Record = {}; for (const [addr, border] of borders) { const before = cellAt(tab, addr)?.style?.border ?? {}; if (JSON.stringify(before) === JSON.stringify(border)) continue; // C2's side shape is lane B's to type; until its `CellBorder` lands here the cast carries it. Object.assign(edits, styleCells(tab, [addr], { border: border as unknown as CellStylePatch["border"] }).edits); } if (Object.keys(edits).length > 0) onCommit(edits); }, [addrAt, bandRows, columns.length, onCommit, tab, visRows.length]); // The pen lands when a drag that began on the cells ends; a drag's last selection is glide's. useEffect(() => { const wrap = wrapRef.current; if (!wrap || !borderPen) return; let down = false; // glide's scroller overlays its canvas, so a press on the cells lands on `.dvn-scroller`. const onDown = (event: PointerEvent) => { down = event.button === 0 && !!(event.target as Element | null)?.closest?.(".dvn-scroller"); }; const onUp = () => { if (!down) return; down = false; window.setTimeout(() => { const pen = borderPenRef.current; if (pen) applyBorderPen(pen); }, 0); }; wrap.addEventListener("pointerdown", onDown, true); window.addEventListener("pointerup", onUp, true); return () => { wrap.removeEventListener("pointerdown", onDown, true); window.removeEventListener("pointerup", onUp, true); }; }, [applyBorderPen, borderPen]); /** * ⭐ W51-T15: CLEARING THE SELECTION, SAID ONCE. The Delete key and the ribbon's Clear contents * are the SAME act, so the two cannot disagree about R5: a bound cell in the selection clears * its value AND drops its binding, exactly as any other cell does. */ const clearSelection = useCallback(() => { const addrs = selectedAddrs(); if (addrs.length === 0) { onNotice("Select a cell first, then clear it."); return; } const out = clearCells(tab, addrs); // ⭐⭐ W53-T01 / INSTRUCTION 11 — THE DELETE KEY IS A VALUE CHANGE, AND IT IS THE COMMONEST // ONE. Clearing F6 has to make `=F6+G6` recompute; leaving this on the plain commit would // leave the old sum on screen, which is the same defect the ticket names reached by a // different door. if (Object.keys(out.edits).length > 0) commitWithRecalc(out.edits); }, [commitWithRecalc, onNotice, selectedAddrs, tab]); // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W51-T17 — WHAT A SHORTCUT AND A HEADER CLICK BOTH NEED: ONE WAY TO SET THE SELECTION. // // ⛔ IT GOES THROUGH `onSelectionChange`, NOT `setSelection`. That handler clears the cell // action bar's anchor and fires contract C1's `onSelect`, so a keyboard jump moves the formula // bar exactly as a mouse click does. Writing the state directly would leave the bar reading the // cell a person left three presses ago, which is the class of defect R11 exists about. // // ⛔ AND IT SCROLLS. A controlled `gridSelection` is the ONE thing glide will not follow on its // own; without this, Ctrl+End on a tall sheet selects a cell nobody can see and reads as the // key having done nothing at all. // // ⚠ EVERY COORDINATE HERE IS A VIEW COORDINATE, because that is what glide's selection is. The // translation happens where a REAL index is produced or consumed, which is the edge jump, the // used extent, the structure ops and the find walk, and nowhere else. // ═══════════════════════════════════════════════════════════════════════════════════════════ const applySelection = useCallback(( range: CellRange, cell?: Item, scroll = true, readerCaused = true, axis: "column" | "row" | null = null, ) => { const col0 = Math.min(range.col0, range.col1); const row0 = Math.min(range.row0, range.row1); const col1 = Math.max(range.col0, range.col1); const row1 = Math.max(range.row0, range.row1); const at: Item = cell ?? [col0, row0]; selectionIntentRef.current = readerCaused ? "reader" : "app"; onSelectionChange({ columns: axis === "column" ? CompactSelection.fromSingleSelection([col0, col1 + 1]) : CompactSelection.empty(), rows: axis === "row" ? CompactSelection.fromSingleSelection([row0, row1 + 1]) : CompactSelection.empty(), current: { cell: at, range: { x: col0, y: row0, width: col1 - col0 + 1, height: row1 - row0 + 1 }, rangeStack: [], }, }); // ⛔ A CLICK DOES NOT SCROLL, AND THAT IS NOT A REFINEMENT. A row header selection anchors on // column A and a column header selection on row 1, so scrolling to the anchor would throw a // person scrolled out at column M back to A every time they clicked a row number. They can // already see what they clicked; only a KEY that moved the selection somewhere off screen // needs the view brought to it. // ⛔ W51-T34: NEVER SCROLL TO A BAND ROW. A negative row is a cell in the FROZEN band, which // the main grid does not draw at all, so handing it to glide's `scrollTo` asks a scroller to // reach a row that is not in it. The band is permanently on screen by construction, which is // the whole point of freezing it, so there is nothing to scroll to in the first place. if (scroll) { // The body remains the sole scroll driver. A band destination is already vertically // visible, but may still need horizontal reveal; asking the band to scroll would let the // projected grid disagree with the body until its scroll relay catches up. gridRef.current?.scrollTo(at[0], at[1] < 0 ? 0 : at[1], at[1] < 0 ? "horizontal" : "both"); } }, [onSelectionChange]); /** Transfer keyboard ownership only after the shared document selection accepted its move. */ const handoffNavigationFocus = useCallback((fromRow: number, toRow: number) => { if (!crossesProjectedFocus(fromRow, toRow, bandRows)) return; const owner = projectedFocusOwner(toRow, bandRows); queueMicrotask(() => (owner === "band" ? bandGridRef : gridRef).current?.focus()); }, [bandRows]); /** * C6's missing seam: each DataEditor clamps Arrow/Shift+Arrow to its own local row count. * Intercept only a vertical move whose document range crosses that seam; all ordinary in-pane * navigation remains Glide-owned. A Shift range keeps its anchor/focus owner while its active * edge crosses, matching the body grid's ordinary selection semantics. */ const moveAcrossFrozenBoundary = useCallback((event: GridKeyEventArgs): boolean => { if (formulaEdit || event.ctrlKey || event.metaKey || event.altKey) return false; const target = event.rawEvent?.target; if (target instanceof Element && target.closest('input, textarea, [contenteditable="true"]')) return false; const step = arrowStep(event.key); const cur = selectionRef.current?.current; if (!step || step.dRow === 0 || !cur || bandRows <= 0) return false; const bounds = { minRow: -bandRows, maxRow: Math.max(0, visRows.length - 1) }; if (!event.shiftKey) { const row = Math.max(bounds.minRow, Math.min(bounds.maxRow, cur.cell[1] + step.dRow)); if (!crossesProjectedFocus(cur.cell[1], row, bandRows)) return false; event.cancel(); event.preventDefault(); applySelection({ col0: cur.cell[0], row0: row, col1: cur.cell[0], row1: row }); handoffNavigationFocus(cur.cell[1], row); return true; } const held: SelectionRect = { col0: cur.range.x, row0: cur.range.y, col1: cur.range.x + cur.range.width - 1, row1: cur.range.y + cur.range.height - 1, }; const anchor = { col: cur.cell[0], row: cur.cell[1] }; const start = edgeStart(held, anchor, "row"); const row = Math.max(bounds.minRow, Math.min(bounds.maxRow, start + step.dRow)); const spansSeam = Math.min(held.row0, held.row1) < 0 && Math.max(held.row0, held.row1) >= 0; if (!spansSeam && !crossesProjectedFocus(start, row, bandRows)) return false; event.cancel(); event.preventDefault(); applySelection(extendEdgeRect(held, anchor, row, "row"), cur.cell); return true; }, [applySelection, bandRows, formulaEdit, handoffNavigationFocus, visRows.length]); /** * Let Glide's overlay editor commit first, then repair only the pane-crossing landing its local * row count cannot represent. The draft therefore keeps its native commit/cancel ownership. */ const finishOverlayBoundaryCommit = useCallback(( direction: CommitDirection, from: Item, ) => { const origin = tabRunAt.current; const land = commitTarget({ col: from[0], row: from[1] }, direction, origin, { minCol: 0, maxCol: Math.max(0, visCols.length - 1), minRow: -bandRows, maxRow: Math.max(0, visRows.length - 1), }); if (!crossesProjectedFocus(from[1], land.row, bandRows)) return; requestAnimationFrame(() => { const now = selectionRef.current?.current?.cell; // A successful native move wins. Only repair the local-grid clamp that left the anchor put. if (!now || now[0] !== from[0] || now[1] !== from[1]) return; tabRunAt.current = tabRunOrigin(origin, direction, from[0]); commitNav.current = true; applySelection({ col0: land.col, row0: land.row, col1: land.col, row1: land.row }); handoffNavigationFocus(from[1], land.row); }); }, [applySelection, bandRows, handoffNavigationFocus, visCols.length, visRows.length]); /** * S63-T25 / C6: one whole-axis dispatcher for keys and both DataEditors' header gestures. * `selectionRef` supplies the document anchor synchronously, so a Shift-click delivered by the * frozen grid cannot read a stale body-grid closure. Focus follows the active document row only * after the one selection door accepts it. */ const selectDocumentAxis = useCallback(( axis: "column" | "row", index: number, extend = false, readerCaused = true, ) => { const prior = selectionRef.current?.current?.cell; const anchor = extend ? (axis === "column" ? prior?.[0] : prior?.[1]) ?? index : index; // The active cell deliberately stays where the gesture put it: S63-T25's browser leg // asserts focus stays in the band after Ctrl+Space from a frozen cell. The body is made // to paint by `inBand` above instead. const active: Item = axis === "column" ? [anchor, prior?.[1] ?? -bandRows] : [prior?.[0] ?? 0, anchor]; const range = axisBand(axis, anchor, index, headerProjectionBounds); applySelection(range, active, false, readerCaused, axis); queueMicrotask(() => (active[1] < 0 ? bandGridRef : gridRef).current?.focus()); }, [applySelection, bandRows, headerProjectionBounds]); /** Ctrl+Shift+Space through the same document-address projection from either grid. */ const selectDocumentRegion = useCallback(() => { const cur = selectionRef.current?.current; if (!cur) return; const region = currentRegion({ col: realCol(cur.cell[0]), row: realRow(cur.cell[1]) }, extent, (col, row) => isFilled(tab, col, row)); applySelection({ col0: viewIndexOf(visCols, region.col0), row0: viewRowOf(region.row0), col1: viewIndexOf(visCols, region.col1), row1: viewRowOf(region.row1), }, cur.cell); queueMicrotask(() => (cur.cell[1] < 0 ? bandGridRef : gridRef).current?.focus()); }, [applySelection, extent, realCol, realRow, tab, viewRowOf, visCols]); const focusViewHeader = useCallback((row: number) => { // Glide's focus() can retain an old accessibility cell while a portal owns focus. // Focus the owning canvas instead; its controlled selection identifies the header. const canvas = Array.from(wrapRef.current?.querySelectorAll( ".sheet-grid-canvas .dvn-underlay canvas[tabindex]", ) ?? []).find(node => Boolean(node.closest(".sheet-frozen-rows")) === (row < 0)); canvas?.focus({ preventScroll: true }); }, []); const toggleSheetFilter = useCallback(() => { setFilterMenu(null); if (sheetFilter) { setFilterState(null); return; } const range = viewRange(); const region = range ? sheetFilterRegion(tab, { col0: realCol(range.col0), col1: realCol(range.col1), row0: realRow(range.row0), row1: realRow(range.row1), }) : null; if (!region) { onNotice("This region has no data to filter. Select a header row with data below it."); return; } setFilterState({ ...region, scope: renderedWorkbookKey, values: {} }); if (range) requestAnimationFrame(() => focusViewHeader(range.row0)); }, [sheetFilter, viewRange, tab, realCol, realRow, onNotice, renderedWorkbookKey, focusViewHeader]); const openSheetFilter = useCallback((item: Item, args: { bounds: Rectangle; localEventX?: number; preventDefault: () => void; }) => { const col = realCol(item[0]); if (!sheetFilter || realRow(item[1]) !== sheetFilter.headerRow || col < sheetFilter.col0 || col > sheetFilter.col1 || (args.localEventX !== undefined && args.localEventX < args.bounds.width - 24 * zoom)) return false; args.preventDefault(); setAnchor(null); setMenu(null); setViewMenu(null); setDropdown(null); applySelection({ col0: item[0], col1: item[0], row0: item[1], row1: item[1] }, item, false); // The shared overlay captures this canvas as its focus-restoration target. focusViewHeader(item[1]); setFilterMenu({ col, anchor: rectAnchor(args.bounds) }); return true; }, [sheetFilter, realCol, realRow, zoom, applySelection, focusViewHeader]); const filterChoices = useMemo(() => { if (!sheetFilter || !filterMenu) return []; const values = new Set(); for (let row = sheetFilter.headerRow + 1; row <= sheetFilter.lastRow; row++) values.add(sheetFilterValue(cellAt(tab, addressOf(filterMenu.col, row)))); return [...values].sort((a, b) => a === "" ? 1 : b === "" ? -1 : a.localeCompare(b, undefined, { numeric: true })); }, [tab, sheetFilter, filterMenu]); const filterChecked = sheetFilter && filterMenu ? sheetFilter.values[filterMenu.col] : undefined; const allFilterValuesSelected = filterChecked === undefined || filterChoices.every(value => filterChecked.has(value)); const setFilterValues = (col: number, values: ReadonlySet | null) => { setFilterState(was => { if (!was || was.scope !== renderedWorkbookKey) return was; const next = { ...was.values }; if (values === null) delete next[col]; else next[col] = values; return { ...was, values: next }; }); }; const openViewHeader = useCallback((item: Item, args: { bounds: Rectangle; localEventX: number; preventDefault: () => void; }) => { const header = viewHeaderAt(cells, addrAt(item[0], item[1])); if (!header || args.localEventX < args.bounds.width - 24 * zoom) return false; args.preventDefault(); setAnchor(null); setMenu(null); applySelection({ col0: item[0], col1: item[0], row0: item[1], row1: item[1] }, item, false); // The canvas is the opener the shared overlay captures for restoreFocus. focusViewHeader(item[1]); const opened = { ...header, item, anchor: rectAnchor(args.bounds), binding: cells[header.origin].binding as ViewBinding }; viewMenuRef.current = opened; setViewMenu(opened); return true; }, [addrAt, applySelection, focusViewHeader, tab.cells, zoom]); const closeViewHeader = useCallback(() => { if (viewMenuRef.current !== viewMenu) return; viewMenuRef.current = null; setViewMenu(null); if (!viewMenu) return; // Outside pointerdown may select another cell later in that gesture. Restore the header // after it, using the grid's selection door as well as AnchoredOverlay's DOM focus restore. const [col, row] = viewMenu.item; requestAnimationFrame(() => { applySelection({ col0: col, col1: col, row0: row, row1: row }, [col, row], false); focusViewHeader(row); }); }, [applySelection, focusViewHeader, viewMenu]); const applyViewHeader = useCallback(async ( patch: Pick | Pick, ): Promise => { if (!viewMenu) return false; const context = viewContext.current; const base = context.storedWorkbook; const target = context.storedTab; const cell = (target.cells ?? {})[viewMenu.origin]; if (viewWritePending.current || viewRefresh.current.busy || JSON.stringify(cell?.binding) !== JSON.stringify(viewMenu.binding)) { context.onNotice("The view changed. Reopen its header and try again."); return false; } const state = viewRefresh.current; const generation = ++state.generation; try { const binding = { ...viewMenu.binding, ...patch }; const got = await fetchViewRows(base.id, binding); const latest = viewContext.current; if (viewMenuRef.current !== viewMenu) return false; if (state.generation !== generation || latest.storedWorkbook.id !== base.id || latest.storedTab.id !== target.id || latest.storedWorkbook.sheets !== base.sheets) { latest.onNotice("The sheet changed. Reopen the header and try again."); return false; } if (!got.ok) { latest.onNotice(got.message); return false; } // The new binding and its resolved cells share T12's single undo/persistence door. return await applyViewAnswer(base, target, viewMenu.origin, got.answer, binding); } catch { viewContext.current.onNotice("The view rows could not be refreshed."); return false; } }, [applyViewAnswer, viewMenu]); useEffect(() => { viewMenuRef.current = null; setViewMenu(null); }, [storedWorkbook.id, storedTab.id]); /** * ⭐⭐ W56-T04: ONE OPEN, ONE OPENING CELL, THROUGH THE SAME SELECTION DOOR. * The background binding refresh replaces the workbook object after paint, so object identity * cannot own this effect. The workbook and tab ids do; the ref prevents those later replacements * from pulling the reader back after they have already moved. */ useEffect(() => { const key = `${workbook.id}:${tab.id}:${openAt.addr}:${openAt.request ?? 0}`; if (openAt.workbookId !== workbook.id || openAt.tabId !== tab.id || openedSelectionRef.current === key) return; const requested = splitAddress(openAt.addr) ?? { col: 1, row: 1 }; let col = viewIndexOf(visCols, requested.col - 1); let row = viewRowOf(requested.row - 1); if (realCol(col) !== requested.col - 1 || realRow(row) !== requested.row - 1) { col = viewIndexOf(visCols, 0); row = viewRowOf(0); } // Glide's first viewport measurement follows mount. Reveal after that measurement so a // deep link and a repeated name-box request use the same settled geometry. let revealFrame: number | null = null; const frame = window.requestAnimationFrame(() => { revealFrame = window.requestAnimationFrame(() => { openedSelectionRef.current = key; applySelection({ col0: col, row0: row, col1: col, row1: row }, [col, row], true, false); }); }); return () => { window.cancelAnimationFrame(frame); if (revealFrame !== null) window.cancelAnimationFrame(revealFrame); }; }, [applySelection, openAt.workbookId, openAt.tabId, openAt.addr, openAt.request, realCol, realRow, tab.id, viewRowOf, visCols, workbook.id]); /** * W55-T05 / R4: KeyTips consumes its capture-phase key while focus is on the ribbon, then * dispatches one scoped semantic arrow on this wrapper. Move through `applySelection`, the same * selection door used by every sheet-owned key, and return focus to the grid that owns the * landing row. A component-scoped custom event avoids both a synthetic keyboard replay and the * raw global key listener prohibited by the overlay contract. */ useEffect(() => { const host = wrapRef.current; if (!host) return; const moveFromKeyTips = (event: Event) => { const key = keyTipGridArrow((event as CustomEvent<{ key?: string }>).detail?.key ?? ""); const current = selection?.current?.cell; if (!key || !current) return; const step = arrowStep(key); if (!step) return; const row = Math.max( -bandRows, Math.min(Math.max(0, visRows.length - 1), current[1] + step.dRow), ); applySelection({ col0: current[0], row0: row, col1: current[0], row1: row }); (row < 0 ? bandGridRef : gridRef).current?.focus(); }; host.addEventListener(KEY_TIP_GRID_ARROW_EVENT, moveFromKeyTips); return () => host.removeEventListener(KEY_TIP_GRID_ARROW_EVENT, moveFromKeyTips); }, [applySelection, bandRows, selection, visRows.length]); // S67-T04: the page asks the grid to take focus back (a tab switch closed the Cell Database // panel). glide's own `focus()` focuses the grid AND its current cell; focusing the canvas // element from outside leaves glide's accessibility cell painted in the corner. The name is a // literal on both sides so `SheetPage` never has to import this chunk for it. useEffect(() => { // ⚠ Focused in the same frames as a freshly mounted tab's first paints, glide intermittently // left its row-marker "1" drawn in the header corner (measured 4 px); a short settle before // taking focus does not. let timer = 0; const takeFocus = () => { window.clearTimeout(timer); timer = window.setTimeout(() => { const current = selection?.current?.cell; (current && current[1] < 0 ? bandGridRef : gridRef).current?.focus(); }, 180); }; document.addEventListener(focusEvent, takeFocus); return () => { window.clearTimeout(timer); document.removeEventListener(focusEvent, takeFocus); }; }, [focusEvent, selection]); /** * Ctrl+PgUp and Ctrl+PgDn. See `onSelectTab` in the props above for why there are two paths. * * ⛔ IT WRAPS RATHER THAN STOPPING AT THE ENDS, which is Excel's behaviour and is also the only * one that cannot leave a person pressing a key that does nothing with no explanation. */ const switchTab = useCallback((step: number) => { const sheets = workbook.sheets ?? []; const at = sheets.findIndex((sheet) => sheet.id === tab.id); if (at < 0 || sheets.length < 2) { onNotice("This workbook has one sheet, so there is no other sheet to move to."); return; } const to = (at + step + sheets.length) % sheets.length; const next = sheets[to]; if (!next) return; if (onSelectTab) { onSelectTab(next.id); return; } // ⚠ THE TAB BAR IS A SIBLING OF THIS COMPONENT, NOT A CHILD, so it is found on the document // and by the label its own toolbar carries. The workbook's tabs are its leading buttons, in // the order `workbook.sheets` is in, which is the order this index counts in too. // ⛔ FOUND BY ITS LABEL AND NOT BY `role="toolbar"`, AND THAT IS NOT A STYLE CHOICE. W51-T15 // pins that this file contains exactly ZERO toolbars, by counting the attribute in its // source; the literal inside a query string counts too, and a gate that reads a SELECTOR as // a second toolbar is the trap [[a-gate-that-greps-source-reads-the-comments-too]] names. // The label is unique in the tree anyway: it is the workbook's own tab bar. const bar = (embedded ? wrapRef.current?.closest(".sheet-page") : document)?.querySelector('[aria-label="Sheets"]'); const button = bar?.querySelectorAll("button")[to]; if (button instanceof HTMLButtonElement) button.click(); else onNotice("The sheet tabs are not on screen, so the keyboard cannot reach them."); }, [embedded, onNotice, onSelectTab, tab.id, workbook.sheets]); // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W54-T14 / LANE B — A CELL'S ATTACHMENTS, WIRED IN ONE PLACE. // // A link and a note are the two things a cell can carry that are neither value nor style, and // `LinkDialog.tsx` owns every part of them that can be owned away from this file: the authoring // surface, the two canvas marks, the hover bubble and the resolve-and-follow door. What CANNOT // leave is the wiring, because only this component knows where a cell is on screen, which of // the two grids reported the pointer, and how a sheet coordinate becomes a view one. That is // this block, plus one call in the paint and one line in each grid's click and hover. // // ⛔ NO NEW `RibbonActionKind`. Following a link is a click on the canvas, not a named act, so // `onRibbonAction`'s exhaustive switch is untouched and every other lane still compiles. // ═══════════════════════════════════════════════════════════════════════════════════════════ /** * ⭐ A LINK TO A CELL ON ANOTHER TAB IS TWO STEPS, AND THE SECOND ONE CANNOT RUN YET. Switching * tabs re-renders this component with a different `tab`, and the view coordinates the selection * is written in belong to THAT sheet's visible rows and columns, which do not exist until the * render happens. So the destination is parked here and applied by the effect below, on the * render where it is finally addressable. A ref rather than state: parking it must not itself * cause a render. */ const pendingJump = useRef<{ sheetId: string; col: number; row: number } | null>(null); /** The note under the pointer, or null. `addr` is what keeps a hover from re-rendering per pixel. */ const [noteHover, setNoteHover] = useState<{ addr: string; note: string; anchor: AnchorRect } | null>(null); const [refusalHover, setRefusalHover] = useState<{ addr: string; tabId: string; band: boolean; anchor: AnchorRect } | null>(null); const hoveredRefusal = refusalHover?.tabId === tab.id ? bindingRefusal(cells[refusalHover.addr]) : null; /** Show a tab by id, through the SAME wrap-around door Ctrl+PgUp uses. */ const goToSheet = useCallback((sheetId: string) => { const sheets = workbook.sheets ?? []; const from = sheets.findIndex((sheet) => sheet.id === tab.id); const to = sheets.findIndex((sheet) => sheet.id === sheetId); if (from < 0 || to < 0) { onNotice("That sheet is not in this workbook any more."); return; } if (to !== from) switchTab(to - from); }, [onNotice, switchTab, tab.id, workbook.sheets]); /** * ⛔ THE REFUSAL IS THE `realCol` / `realRow` ROUND TRIP, and that is why it is one test rather * than three. `viewIndexOf` does not fail on a miss, it answers the nearest visible index at or * below, so a hidden column and a column past the end of the sheet both come back as a * PLAUSIBLE view index pointing at the wrong cell. Asking the inverse pair whether that index * really is the cell we asked for catches hidden, out of extent and off the end in one line. */ const goToCell = useCallback((sheetId: string, col: number, row: number) => { if (sheetId !== tab.id) { pendingJump.current = { sheetId, col, row }; goToSheet(sheetId); return; } pendingJump.current = null; const viewCol = viewIndexOf(visCols, col); const viewRow = viewRowOf(row); if (realCol(viewCol) !== col || realRow(viewRow) !== row) { onNotice("That cell is hidden or past the end of this sheet, so there is nothing to open."); return; } applySelection( { col0: viewCol, row0: viewRow, col1: viewCol, row1: viewRow }, [viewCol, viewRow], ); }, [applySelection, goToSheet, onNotice, realCol, realRow, tab.id, viewRowOf, visCols]); useEffect(() => { const jump = pendingJump.current; if (!jump || jump.sheetId !== tab.id) return; goToCell(jump.sheetId, jump.col, jump.row); }, [goToCell, tab.id]); /** Everything `followLink` needs, and nothing this component would not hand any other reader. */ const followContext = useMemo(() => ({ sheets: (workbook.sheets ?? []).map((sheet) => ({ id: sheet.id, name: sheet.name })), tabId: tab.id, goToSheet, goToCell, onNotice, }), [goToCell, goToSheet, onNotice, tab.id, workbook.sheets]); /** * Follow the link on this address, if it carries one. `false` means it does not, which is what * lets both grids' click handlers ask in one line and fall through to what they already did. */ const followCellLink = useCallback( (addr: string): boolean => followLink(cellAt(tab, addr), followContext), [followContext, tab], ); /** * ⭐ ONE HOVER READER FOR BOTH GRIDS, told which one is asking. Every callback the frozen band * grid is given is the main grid's wrapped in `fromBand`, and a hover is no different: a note on * a frozen row has to show its bubble at the row a person is actually pointing at. * * ⛔ IT RETURNS THE CURRENT STATE UNCHANGED WHENEVER NOTHING MOVED. glide fires this on every * pointer move over the canvas, so setting state per event would re-render the whole grid at * mouse frequency, and the bubble's own overlay would remount under the pointer. */ const onNoteHover = useCallback((args: GridMouseEventArgs, band: boolean) => { if (args.kind !== "cell") { setNoteHover((current) => (current ? null : current)); // Both canvases report pointer moves; only the owning canvas may clear its tooltip. setRefusalHover((current) => (current?.band === band ? null : current)); return; } const location = band ? fromBand(args.location) : args.location; const addr = addrAt(location[0], location[1]); const refusal = bindingRefusal(cells[addr]); setRefusalHover((current) => { if (!refusal) return current ? null : current; if (current?.addr === addr && current.tabId === tab.id) return current; return { addr, tabId: tab.id, band, anchor: rectAnchor(args.bounds) }; }); const note = refusal ? "" : cells[addr]?.note ?? ""; setNoteHover((current) => { if (!note) return current ? null : current; if (current && current.addr === addr) return current; return { addr, note, anchor: rectAnchor(args.bounds) }; }); }, [addrAt, cells, fromBand, tab.id]); const onGridItemHovered = useCallback((args: GridMouseEventArgs, band: boolean) => { onNoteHover(args, band); if (args.kind === "cell" && args.location[0] === -1) { rowHoverRef.current[band ? 1 : 0] = { row: args.location[1], rect: args.bounds }; if (!readOnly && !rowResizeGesture.current) { const hit = rowBorderAt(args.bounds.x + args.localEventX, args.bounds.y + args.localEventY); setRowBorderHover(hit); } } // ⛔⛔ ONLY THE CANVAS THAT OWNS THE COLUMN HEADER MAY SPEAK FOR IT, and this line is the // whole of S64-T23's first failed run. BOTH DataEditors report the SAME pointer: with rows // frozen the band draws the header (`headerHeight={bandRows > 0 ? 0 : HEADER_HEIGHT}`) and // the body draws none, so the body answers the identical position as `out-of-bounds` // immediately after the band answered `header`. Measured 2026-09-21 from the page console: // `hover header 2` from the band, then `hover out-of-bounds 2` from the body, and the second // one cleared the column the first had just recorded, so no header press ever saw one. if (band !== (bandRows > 0)) return; const col = args.location[0]; if (args.kind !== "header" || col < 0) { headerHoverColRef.current = null; return; } headerHoverColRef.current = { col, rect: args.bounds }; const drag = headerDragRef.current; // No button held means this is an ordinary hover, not a drag in progress. if (args.buttons === 0 || !drag || col === drag.last) return; drag.last = col; drag.moved = true; selectDocumentAxis("column", col, true, false); }, [bandRows, onNoteHover, readOnly, rowBorderAt, selectDocumentAxis]); /** * ⭐⭐ Ctrl+1 — CONTRACT C1's "THE SAME IMPLEMENTATION, NOT TWO COPIES OF IT", TAKEN LITERALLY. * * The Number format menu's open state lives inside `Ribbon.tsx`, which is not this ticket's * file and carries no prop for it, so the keyboard presses the ribbon's own control. That is * not a workaround for the fence, it is the strongest possible reading of the contract: there * is exactly one menu and one thing that opens it. `data-ribbon` is the same selector * `Ribbon.tsx::focusControl` already queries, so it is a declared seam rather than a guess. * * ⛔ IT DOES NOT FOCUS THE BUTTON FIRST. Every ribbon control cancels its own `mousedown` so * the grid canvas keeps the keyboard, because glide drops the selection the moment the canvas * blurs and the act would land on nothing. The cost is that a menu opened this way is dismissed * by pressing away from it rather than by Escape, and that is reported rather than hidden. * * ⛔ A DISABLED OR ABSENT BUTTON SAYS SO. `HTMLButtonElement.click()` on a disabled button is a * silent no-op, which is exactly the "a control that is present and does nothing" defect * instruction 17 reported. */ const openNumberFormat = useCallback(() => { const button = wrapRef.current?.querySelector('[data-ribbon="format"]'); if (!button) { onNotice("Show the ribbon with the chevron beside the Home tab, then press Ctrl+1 again."); return; } if (button.disabled) { onNotice("The workbook is busy. Try the number format again in a moment."); return; } button.click(); }, [onNotice]); /** * ⭐⭐ Ctrl+PLUS AND Ctrl+MINUS — THREE ANSWERS, AND THE THIRD IS THE DONE-WHEN's OWN WORD. * * A selection covering every row of its columns is a COLUMN act, one covering every column of * its rows is a ROW act, and anything else moves CELLS. The first two go through the page's * existing structure door, which owns R18's refusal wall and the bound-cell confirmation; the * third is `sheetState.ts::shiftCells` and states both of its limits every time it runs. */ const structureForSelection = useCallback((insert: boolean) => { const range = viewRange(); if (!range) { onNotice("Select a cell first, then insert or delete rows, columns or cells."); return; } const axis = structureAxis(range, { cols: visCols.length, rows: visRows.length }); if (axis === "row" || axis === "col") { const span = axis === "row" ? Math.abs(range.row1 - range.row0) + 1 : Math.abs(range.col1 - range.col0) + 1; const at = axis === "row" ? realRow(Math.min(range.row0, range.row1)) + 1 : realCol(Math.min(range.col0, range.col1)) + 1; requestStructure({ axis, at, delta: insert ? span : -span }); return; } const real: CellRange = { col0: realCol(range.col0), row0: realRow(range.row0), col1: realCol(range.col1), row1: realRow(range.row1), }; // ⭐ R5 (W52-T09): `shiftCells` no longer declines the whole act over a bound cell in range - // it drops out with everything else the shift moves. const out = shiftCells(tab, real, insert, { rows: extent.rows }); // ⭐ W53-T01: a shift moves VALUES under the formulas that read those addresses, so the // dependents recompute in the same commit rather than at the next Refresh. if (Object.keys(out.edits).length > 0) commitWithRecalc(out.edits); onNotice(cellShiftLabel(insert, out.dropped)); }, [commitWithRecalc, extent.rows, onNotice, realCol, realRow, requestStructure, tab, viewRange, visCols.length, visRows.length]); /** * Ctrl+F's walk. `step` of `0` lands on the first match, `1` on the next, `-1` on the one * before. The selection it produces is the SAME `GridSelection` every other act reads. */ const walkFind = useCallback((query: string, step: number, from: number) => { const hits = findMatches(tab, query); if (hits.length === 0) { if (query.trim()) onNotice(noMatchLabel(query)); return; } const at = ((from + step) % hits.length + hits.length) % hits.length; const place = splitAddress(hits[at]); if (!place) return; const view = { col: viewIndexOf(visCols, place.col - 1), row: viewRowOf(place.row - 1), }; applySelection({ col0: view.col, row0: view.row, col1: view.col, row1: view.row }); // ⚠ W54-T07 MADE THIS A FUNCTIONAL UPDATE, AND THE REASON IS ONE LINE: the record now carries // the panel's SHAPE (`replacing`) as well as its query, so writing a fresh literal here would // fold the replace row away the moment somebody pressed Next. setFind((was) => ({ ...(was ?? {}), query, at })); }, [applySelection, onNotice, tab, viewRowOf, visCols]); // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W54-T07 — REPLACE, THROUGH THE SAME LIST FIND WALKS AND THE SAME DOOR EVERY BULK EDIT // TAKES. // // ⛔ THERE IS NO SECOND SEARCH HERE. The addresses come from `findMatches`, exactly as the walk // above gets them, so what Replace all changes is precisely the set Next would have visited; // two matchers would eventually disagree about a formula cell and nobody would know which was // right. // // ⛔ AND NO SECOND WRITE PATH. The edits go out through `commitWithRecalc`, which is what Clear // all and the paste already use: one history step, one PUT carrying the `rev` that was read, and // the dependents recomputed in the same commit rather than at the next Refresh. // // ⚠ IT REPLACES IN THE TEXT A PERSON TYPED, NOT IN THE VALUE THEY SEE. `editableText` is // `=SUM(B4:B8)` where `displayText` is `31`, and only the first of those is something a write // can put back. `findMatches` searches BOTH, so a cell can legitimately match on its displayed // number and hold nothing to change; it is left exactly as it was and the count says so. // ═══════════════════════════════════════════════════════════════════════════════════════════ const replaceMatches = useCallback((query: string, into: string, all: boolean) => { const needle = String(query ?? "").trim(); if (!needle) { onNotice("Type what to look for first, then replace it."); return; } const hits = findMatches(tab, needle); if (hits.length === 0) { onNotice(noMatchLabel(needle)); return; } /** A case-insensitive replace of every occurrence, done by index rather than by a regular * expression: a query is free text, and a person searching for a currency amount would * otherwise have their own dots and brackets read as syntax. */ const swap = (text: string): string => { const hay = text.toLowerCase(); const look = needle.toLowerCase(); let out = ""; let from = 0; for (;;) { const hit = hay.indexOf(look, from); if (hit < 0) break; out += text.slice(from, hit) + into; from = hit + look.length; } return out + text.slice(from); }; // ⛔ A SINGLE REPLACE ACTS ON THE MATCH THE PERSON IS STANDING ON, which is the one the walk // last selected. Before any walk there is no such match, so the first press takes the first // one, exactly as Enter in the query box would have. // // ⚠ A MATCH IS A CELL HERE, NOT A CHARACTER OFFSET, and that is a documented deviation from // Excel rather than an oversight. `findMatches` answers with ADDRESSES, so a cell saying the // word twice is one entry in its list and one press of Replace changes both occurrences in // it. Offering finer granularity would mean a second matcher that tracked offsets, and two // matchers eventually disagree about what a match is with nothing to report the difference. const index = all ? -1 : Math.min(Math.max(find?.at ?? -1, 0), hits.length - 1); const targets = all ? hits : [hits[index]]; const edits: Record = {}; for (const addr of targets) { const cell = cellAt(tab, addr); const before = editableText(cell); const after = swap(before); if (after === before) continue; edits[addr] = commitTyped(cell, after); } const changed = Object.keys(edits).length; if (changed === 0) { onNotice(`Nothing writable on this sheet says ${JSON.stringify(needle)}. A cell can match ` + "on the value it shows while holding a formula that does not say it."); return; } commitWithRecalc(edits); // ⚠ THE WALK'S PLACE MOVES BACK ONE, and that is arithmetic rather than caution: the cell just // written no longer matches, so the next render's list is one shorter and everything after the // replaced entry has slid down into its index. Standing one before it means the next press of // Next lands on what really is the next match. if (!all) setFind((was) => ({ ...(was ?? { query: needle }), at: Math.max(-1, index - 1) })); onNotice(changed === 1 ? "Replaced one cell." : `Replaced ${changed} cells.`); }, [commitWithRecalc, find, onNotice, tab]); // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐ W50-T20 — THE STRUCTURE CONTROLS. They RAISE an intent and decide nothing. // // ⛔ THE WALL IS THE PAGE'S, NOT THIS COMPONENT'S, AND THAT SPLIT IS DELIBERATE. Whether an // insert is allowed (R18: a value in the last row has nowhere to go) and whether a delete needs // asking (a bound cell inside the band) are both questions about the WHOLE workbook, and the // one commit door that owns `rev` already lives there. Two places that can refuse the same act // is how one of them ends up out of date. // ═══════════════════════════════════════════════════════════════════════════════════════════ /** * The 1-based row and column the structure controls act on: the selected cell's. * * ⛔ TRANSLATED FIRST. `StructureOp.at` is a place in the SHEET, so taking glide's index raw * would insert a row above the wrong row the moment anything above the selection is hidden. */ const at = useMemo(() => { const cur = selection?.current?.cell; return cur ? { col: realCol(cur[0]) + 1, row: realRow(cur[1]) + 1 } : null; }, [realCol, realRow, selection]); const structure = useCallback((axis: "row" | "col", delta: number, where?: number) => { const index = where ?? (axis === "row" ? at?.row : at?.col); if (!index) { onNotice("Select a cell first, then insert or delete a row or a column."); return; } setMenu(null); requestStructure({ axis, at: index, delta }); }, [at, onNotice, requestStructure]); // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W51-T16 — THE ACTS THEMSELVES. Every one of them ends at `onCommit`, `onStructure`, // `onGrow`, `onFreeze` or a notice, so no control here opens a second save path. // ═══════════════════════════════════════════════════════════════════════════════════════════ /** The style the ribbon's toggles read back from, which is Excel's: the ANCHOR cell's. */ const anchorStyle = selected?.cell?.style ?? null; /** * COPY, and CUT, which is a copy that then clears. * * ⭐ WAVE 54 BASE KIT: the BODY moved to `clipboardOps.ts::runCopySelection` unchanged, with its * six closed-over values handed over as arguments instead. The `useCallback` stays HERE, with * the same dependency array, because the ribbon's Copy and Cut items and the shortcut router * all name `copySelection` in theirs. `copiedRef` and `setCopyMarquee` are absent from that * array for the reason they always were: a ref and a `useState` setter are stable for the life * of the component, so naming them would say something untrue about what this callback watches. * * ⛔ THE CLEAR ONLY HAPPENS IF THE COPY SUCCEEDED, and that rule now lives beside the promise * chain that implements it. A browser that refuses clipboard access on a cut would otherwise * delete a person's cells with nothing on the clipboard to paste back. * * ⭐ WHAT IT PUTS ON THE CLIPBOARD IS {@link heldFor}'s, which glide's own Ctrl+C now records * through the same builder. */ const copySelection = useCallback((cut: boolean) => { if (readOnly && cut) return; runCopySelection(cut, viewRange, heldFor, copiedRef, setCopyMarquee, clearSelection, onNotice); }, [clearSelection, heldFor, onNotice, viewRange, readOnly]); /** * PASTE. Native paste supplies its event payload; the ribbon reads the browser clipboard. * Both reach this same landing body, including validation, refusals, highlighting and undo. */ const pasteFromClipboard = useCallback((options: PasteMode | PasteOptions = { what: "all" }, payload?: ClipboardPayload) => { if (readOnly) { onNotice("You can view this workbook but not change it."); return; } const range = viewRange(); if (!range) { onNotice("Select the top left cell first, then paste."); return; } (payload ? Promise.resolve(payload) : readClipboardPayload()).then(({ text, values }) => { // ⭐⭐ R5 (W52-T09) — "" IS TWO DIFFERENT FACTS. Reading a genuinely empty OS clipboard and // reading back a copy of one BLANK cell both hand back an empty string; `isRecognizedCopy` // is the only thing that can tell them apart (see its own note, beside `copiedBlock`). if (!text && !isRecognizedCopy(text)) { onNotice("There is nothing on the clipboard to paste."); return; } // ⭐⭐ W53-T03: this door always had the dragged rectangle in hand; now it hands it on, so // the ribbon's Paste tiles a copied block across the selection exactly as Ctrl+V does. const axis = copiedAxis(text); const at = wholeAxisAnchor(axis, { col: realCol(range.col0), row: realRow(range.row0) }, { col: copiedRef.current?.col ?? 0, row: copiedRef.current?.row ?? 0 }); // R18: share the native door's anchor and bypass tiling only for a recognized whole axis. const out = pasteCells(tab, at.col, at.row, values, { cols: extent.cols, rows: extent.rows }, copiedBlock(values), cellValueGetter, axis !== null ? undefined : { col0: realCol(range.col0), row0: realRow(range.row0), col1: realCol(range.col1), row1: realRow(range.row1) }, options, storagePrefix); if (out.layerRefusal) { onNotice(out.layerRefusal); return; } if (out.sizeRefusal) { onNotice(out.sizeRefusal); return; } const what = pasteOptionsOf(options).what; landFill(out, ["values", "formulas", "values-number-formats", "formulas-number-formats", "values-source-formatting"].includes(what)); // ⭐ W52-T07: same highlight the glide door sets, from the ribbon's own paste path. setPasteHighlight({ col: at.col, row: at.row, cols: values[0]?.length ?? 0, rows: values.length }); // S68-T27: a Transpose lands the block on its side, so the rectangle turns with it. if (pasteOptionsOf(options).transpose) { setPasteHighlight(held => held && { ...held, cols: held.rows, rows: held.cols }); } }).catch(() => onNotice("This browser did not let the sheet read the clipboard. " + "Press Ctrl+V instead.")); }, [cellValueGetter, copiedAxis, copiedBlock, extent.cols, extent.rows, isRecognizedCopy, landFill, onNotice, readOnly, realCol, realRow, storagePrefix, tab, viewRange]); const [pasteSpecial, setPasteSpecial] = useState<{ payload: ClipboardPayload | null; reason: string } | null>(null); const pasteSpecialRequest = useRef(0); const closePasteSpecial = useCallback(() => { pasteSpecialRequest.current += 1; setPasteSpecial(null); }, []); const openPasteSpecial = useCallback(() => { if (readOnly) { onNotice("You can view this workbook but not change it."); return; } const request = ++pasteSpecialRequest.current; const held = copiedRef.current; if (held) { setPasteSpecial({ payload: parseClipboardPayload(held.text), reason: "" }); return; } setPasteSpecial({ payload: null, reason: "Reading the clipboard..." }); void readClipboardPayload().then(payload => { if (request !== pasteSpecialRequest.current) return; setPasteSpecial(payload.text ? { payload, reason: "" } : { payload: null, reason: "Copy cells first, then choose how to paste them.", }); }).catch(() => { if (request !== pasteSpecialRequest.current) return; setPasteSpecial({ payload: null, reason: "This browser did not let the sheet read the clipboard. Copy cells in this sheet first." }); }); }, [onNotice, readOnly]); useEffect(() => closePasteSpecial(), [closePasteSpecial, readOnly, tab.id, workbook.id]); useEffect(() => { const paste = (event: ClipboardEvent) => { const target = event.target instanceof Node ? event.target : document.activeElement; if (embedded && (!target || !wrapRef.current?.closest(".sheet-page")?.contains(target))) return; if (!embedded && target instanceof Element && target.closest('.sheet-page[data-embedded="true"]')) return; if (event.defaultPrevented || !selectionRef.current?.current || formulaEdit || !event.clipboardData || document.querySelector('dialog[open], [aria-modal="true"]')) return; const ownsPaste = (target: EventTarget | null) => target instanceof Element && (target.closest(`input, textarea, [contenteditable="true"], [contenteditable=""], [contenteditable="plaintext-only"], ${MODAL_SELECTOR}, dialog[open]`) || (target instanceof HTMLElement && target.isContentEditable)); if (ownsPaste(event.target) || ownsPaste(document.activeElement)) return; event.preventDefault(); event.stopPropagation(); pasteFromClipboard({ what: "all" }, parseClipboardPayload( event.clipboardData.getData("text/plain"), event.clipboardData.getData("text/html"))); // Restore the selected grid after a rail-button paste so Ctrl+Z reaches its undo handler. const pasteOwner = inBand ? bandGridRef.current : gridRef.current; pasteOwner?.focus(); }; document.addEventListener("paste", paste, true); return () => document.removeEventListener("paste", paste, true); }, [embedded, formulaEdit, inBand, pasteFromClipboard]); /** * THE FORMAT PAINTER, WHICH IS TWO GESTURES AND NOT ONE. Pressing it picks the anchor cell's * style up; the NEXT click lands it. Pressing it again while it is armed puts it down, so a * person who changed their mind is not stuck with a loaded cursor. */ const toggleFormatPainter = useCallback(() => { if (painter) { setPainter(null); onNotice("The format painter is off."); return; } if (!selected) { onNotice("Select the cell whose format you want to copy, then press Format painter."); return; } setPainter(styleOf(selected.cell) ?? {}); onNotice("The format painter picked up this cell's format. Click a cell to paint it on."); }, [onNotice, painter, selected]); /** Land the painter on one address, REPLACING that cell's style rather than merging into it. */ const paintOnto = useCallback((addr: string) => { const out = styleCells(tab, [addr], paintPatch(painter)); setPainter(null); if (Object.keys(out.edits).length > 0) onCommit(out.edits); }, [onCommit, painter, tab]); /** Indent and outdent, clamped, reading the anchor cell exactly as Ctrl+B does. */ const stepIndent = useCallback((delta: number) => { const current = anchorStyle?.indent ?? 0; applyStyle({ indent: Math.max(0, Math.min(MAX_CELL_INDENT, current + delta)) }); }, [anchorStyle, applyStyle]); /** AutoSum: the contiguous numeric run above the selected cell, else the one to its left. */ const autoSum = useCallback(() => { const cur = selection?.current?.cell; if (!cur) { onNotice("Select the cell the total should land in, then press AutoSum."); return; } const col = realCol(cur[0]); const row = realRow(cur[1]); const formula = autoSumFormula(tab, col, row); if (!formula) { onNotice("AutoSum needs a run of numbers above the cell or to its left, and found none."); return; } const addr = addressOf(col, row); const cell = cellAt(tab, addr); // ⭐ R5 (W52-T09): AutoSum on a bound cell writes over it exactly like any other cell - // `setFormula` already drops a binding on its own. commitWithRecalc({ [addr]: setFormula(cell, formula, cellValueGetter) }); }, [cellValueGetter, commitWithRecalc, onNotice, realCol, realRow, selection, tab]); /** Fill down and fill right, through the same door the fill HANDLE uses. */ const fillSelection = useCallback((axis: "down" | "right") => { const range = viewRange(); if (!range) { onNotice("Select the cell to copy and the cells to fill, then choose a fill."); return; } // ⚠ TRANSLATED CORNER BY CORNER, then filled as a real rectangle: a fill is a spreadsheet // operation on the sheet, and glide's fill handle lands on the same cells for the same drag. const real: CellRange = { col0: realCol(range.col0), row0: realRow(range.row0), col1: realCol(range.col1), row1: realRow(range.row1), }; // Ctrl+D and Ctrl+R carry the same copy rules as the fill handle. R13 now advances periods // and chosen filter options in either direction, whichever door was used. const rules: DragContext = { catalogue: options, shadows: viewShadows }; const out = axis === "down" ? fillDown(tab, real, rules) : fillRight(tab, real, rules); if (Object.keys(out.edits).length === 0) { onNotice(axis === "down" ? "Select the cell to copy and at least one cell below it, then fill down." : "Select the cell to copy and at least one cell to its right, then fill right."); return; } landFill(out, false); }, [landFill, onNotice, options, realCol, realRow, tab, viewRange, viewShadows]); /** Clear formats, and clear all. Clear contents is `clearSelection`, which the Delete key uses. */ const clearSelectionWith = useCallback((which: "formats" | "all") => { const addrs = selectedAddrs(); if (addrs.length === 0) { onNotice("Select a cell first, then clear it."); return; } const out = which === "formats" ? clearFormats(tab, addrs) : clearAll(tab, addrs); // ⚠ ONLY THE `all` BRANCH RECALCULATES, AND THE ASYMMETRY IS THE POINT. Clear all removes // VALUES, so a formula reading one of them has to follow; clear formats removes only a bold // and an alignment, and recomputing the sheet for that would be noise with a history step. if (Object.keys(out.edits).length === 0) return; if (which === "formats") onCommit(out.edits); else commitWithRecalc(out.edits); }, [commitWithRecalc, onCommit, onNotice, selectedAddrs, tab]); /** One hide door for Home, a zero width in Format, and releasing a resize at zero. */ const hideBands = useCallback((axis: "row" | "col", indices: number[]) => { const rows = axis === "row" ? withHidden(hiddenRows, indices, true) : hiddenRows; const hiddenTab = axis === "col" ? indices.reduce((next, index) => hideColumnByWidth(next, index - 1), { ...tab, hiddenCols }) : tab; const cols = axis === "col" ? hiddenTab.hiddenCols ?? [] : hiddenCols; // A sheet keeps at least one visible row and column, including when a width hides it. if (rows.length >= extent.rows || cols.length >= extent.cols) { onNotice("A sheet keeps at least one row and one column on screen, so these cannot all " + "be hidden."); return; } // The page changes only membership here. Its existing colWidths (or the implicit default) // remain intact; lastVisibleWidth reads them again when Unhide restores the column. if (!onHideBands) setHiddenLocal({ tabId: tab.id, rows, cols }); onHideBands?.({ hiddenRows: rows, hiddenCols: cols }); }, [extent.cols, extent.rows, hiddenCols, hiddenRows, onHideBands, onNotice, tab]); /** Hide the rows or the columns the selection covers, and remember them on the tab. */ const hideBand = useCallback((axis: "row" | "col") => { const range = viewRange(); if (!range) { onNotice(axis === "row" ? "Select a cell in the rows to hide, then hide them." : "Select a cell in the columns to hide, then hide them."); return; } const indices: number[] = []; if (axis === "row") { for (let r = Math.min(range.row0, range.row1); r <= Math.max(range.row0, range.row1); r += 1) indices.push(realRow(r) + 1); } else { for (let c = Math.min(range.col0, range.col1); c <= Math.max(range.col0, range.col1); c += 1) indices.push(realCol(c) + 1); } hideBands(axis, indices); }, [hideBands, onNotice, realCol, realRow, viewRange]); /** Bring every hidden row and column back, and say so when there were none. */ const unhideAll = useCallback(() => { if (hiddenRows.length === 0 && hiddenCols.length === 0) { onNotice(nothingHiddenLabel()); return; } if (!onHideBands) setHiddenLocal({ tabId: tab.id, rows: [], cols: [] }); onHideBands?.({ hiddenRows: [], hiddenCols: [] }); }, [hiddenCols.length, hiddenRows.length, onHideBands, onNotice, tab.id]); const selectedRowRange = () => { const held = selectionRef.current; const rows = held?.rows.toArray() ?? []; if (rows.length) return { start: realRow(rows[0]) + 1, end: realRow(rows[rows.length - 1]) + 1 }; const range = held?.current?.range; return range ? { start: realRow(range.y) + 1, end: realRow(range.y + range.height - 1) + 1 } : null; }; const groupRows = () => { if (!onRowGroups || busy) return; const range = selectedRowRange(); if (!range) { onNotice("Select a row range first."); return; } const refusal = rowGroupRefusal(rowGroups, range.start, range.end, extent.rows); if (refusal) { onNotice(refusal); return; } onRowGroups([...rowGroups, { id: crypto.randomUUID(), ...range, collapsed: false }]); }; const ungroupRows = () => { if (!onRowGroups || busy) return; const range = selectedRowRange(); if (!range) return; // Remove the innermost matching group, preserving the other nested levels and manual hides. const found = rowGroups.filter(group => group.start <= range.start && group.end >= range.end) .sort((a, b) => (a.end - a.start) - (b.end - b.start))[0]; if (found) onRowGroups(rowGroups.filter(group => group.id !== found.id)); else onNotice("Select rows inside a group first."); }; const toggleRowGroup = (id: string) => { if (!onRowGroups || busy) return; const next = rowGroups.map(group => group.id === id ? { ...group, collapsed: !group.collapsed } : group); const visible = visibleIndices(extent.rows, outlineHiddenRows(hiddenRows, next)); if (visible.length === 0) { onNotice("Leave a row visible outside the group."); return; } setAnchor(null); const current = selectionRef.current?.current?.cell; const real = current ? realRow(current[1]) : 0; const following = visible.findIndex(row => row >= real); const row = (following < 0 ? visible.length - 1 : following) - frozenBandSize(visible, frozenRows); onRowGroups(next); // Reproject after the document commit updates selectionContextRef. A collapsed selection // must not leave the name box/edit door pointing at the hidden cell beside a different row. requestAnimationFrame(() => { selectionIntentRef.current = "app"; onSelectionChange({ columns: CompactSelection.empty(), rows: CompactSelection.empty(), current: { cell: [current?.[0] ?? 0, row], range: { x: current?.[0] ?? 0, y: row, width: 1, height: 1 }, rangeStack: [] } }); }); }; /** One document patch makes a bulk width change one save and one undo step. */ const commitColumnWidths = useCallback((changes: readonly { col: number; width: number }[]) => { if (readOnly || changes.length === 0) return; if (changes.length === 1) { onColumnWidth(changes[0].col, changes[0].width); return; } const colWidths = { ...tab.colWidths }; let changed = false; for (const { col, width } of changes) { const letters = indexToCol(col + 1); if ((colWidths[letters] ?? DEFAULT_COL_WIDTH) === width) continue; changed = true; if (width === DEFAULT_COL_WIDTH) delete colWidths[letters]; else colWidths[letters] = width; } if (changed) onTabView({ colWidths }); }, [onColumnWidth, onTabView, readOnly, tab.colWidths]); /** Apply what the row height or column width dialog was given. */ const applyAsk = useCallback((value: number) => { if (!ask) return; if (ask.kind === "row-height") { setRowHeight(Math.max(MIN_ROW_HEIGHT, Math.min(MAX_ROW_HEIGHT, Math.round(value)))); } else { const range = viewRange(); if (!range) { onNotice("Select a cell in the column first, then set its width."); setAsk(null); return; } const width = Math.max(MIN_COL_WIDTH, Math.min(MAX_COL_WIDTH, Math.round(value))); if (width === 0) hideBand("col"); else commitColumnWidths(Array.from({ length: Math.abs(range.col1 - range.col0) + 1 }, (_, index) => ({ col: realCol(Math.min(range.col0, range.col1) + index), width }))); } setAsk(null); }, [ask, commitColumnWidths, hideBand, onNotice, realCol, setRowHeight, viewRange]); // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W54-T07 / S68-T30 — AUTOFIT MEASURES EACH SELECTED AXIS IN DOCUMENT PIXELS. // // A column fits its widest value; a row fits its own tallest content. The row border and the // ribbon now write `rowHeights` through `onTabView`, the same one-history-step document door // that persists bulk column widths. An explicit height wins over wrapping and the shared base; // the base remains the fallback for rows that have never been resized. // // ⭐ THE MEASUREMENT IS THE PAINT'S OWN, TWICE OVER. It uses the module-level offscreen context // and `wrapIntoLines` W54-T06 added for the row heights, and it builds the font string from the // same `fontPx` / `fontStack` / `SIZE_PX` that `paintCell` builds it from, with the same // padding. A column sized in Inter cannot then be painted in Georgia. // // ⚠ AND IT ANSWERS WITH A SENTENCE WHERE IT CANNOT MEASURE. `measureContext` is null where // there is no document at all, and a selection of empty cells has no widest text; neither is // allowed to become a guess that silently resizes somebody's sheet. // ═══════════════════════════════════════════════════════════════════════════════════════════ /** * The font string one cell's text is measured in, which is the string `paintCell` sets on the * canvas before it draws that cell, plus the size in pixels the caller needs for a line height. */ const cellFontOf = useCallback((style: CellStyle | undefined) => { // ⚠ READ ONCE INTO A LOCAL. `SIZE_PX` is keyed by the four step NAMES and `fontPx` takes the // point number, so the branch has to narrow a slot that carries either; narrowing an optional // chain rather than a plain value is the shape that silently stops narrowing. const asked = style?.size; const size = typeof asked === "number" ? fontPx(asked) : SIZE_PX[asked ?? "m"] ?? SIZE_PX.m; const weight = style?.bold ? "600 " : ""; const slant = style?.italic ? "italic " : ""; return { size, font: `${slant}${weight}${size}px ${fontStack(style?.font, lightTheme.fontFamily)}`, /** `paintCell`'s own left inset, indent included, mirrored so the two cannot disagree. */ pad: 8 + Math.max(0, Math.min(MAX_CELL_INDENT, style?.indent ?? 0)) * 8, }; }, []); /** Widen or narrow every selected column to its own widest value. */ const autoFitColumns = useCallback((picked?: readonly number[]) => { if (readOnly) return; const range = viewRange(); const ctx = measureContext(); if ((!picked && !range) || !ctx) { onNotice("Select a cell in the columns to fit first, then fit them to their contents."); return; } const cols = picked ?? Array.from({ length: Math.abs(range!.col1 - range!.col0) + 1 }, (_, index) => Math.min(range!.col0, range!.col1) + index); const fitted: { col: number; width: number }[] = []; for (const c of cols) { const real = realCol(c); let widest = 0; for (const [addr, cell] of Object.entries(cells)) { const at = splitAddress(addr); if (!at || at.col - 1 !== real) continue; const text = formatCellText(cell, displayText(cell)); if (!text) continue; const face = cellFontOf(cell?.style); ctx.font = face.font; // The right inset is the paint's own 8, the left one is `pad`, which carries the indent. widest = Math.max(widest, ctx.measureText(text).width + face.pad + 8); } if (widest <= 0) continue; fitted.push({ col: real, width: Math.max(MIN_COL_WIDTH, Math.min(MAX_COL_WIDTH, Math.ceil(widest))) }); } commitColumnWidths(fitted); if (fitted.length === 0) { onNotice("These columns hold nothing to measure, so their width is left as it is."); } }, [cellFontOf, cells, commitColumnWidths, onNotice, readOnly, realCol, viewRange]); /** Fit each selected row to its own tallest content, through the border's document door. */ const autoFitRows = useCallback((picked?: readonly number[]) => { if (readOnly) return; const range = viewRange(); const ctx = measureContext(); if ((!picked && !range) || !ctx) { onNotice("Select a cell in the rows to fit first, then fit them to their contents."); return; } const widthOf = new Map(); for (const column of columns) widthOf.set(Number(column.id), column.width / zoom); const rows = picked ?? Array.from({ length: Math.abs(range!.row1 - range!.row0) + 1 }, (_, index) => Math.min(range!.row0, range!.row1) + index); const rowHeights: NonNullable = {}; let measured = false; for (const r of rows) { const real = realRow(r); let tallest = 0; for (const [addr, cell] of Object.entries(cells)) { const at = splitAddress(addr); if (!at || at.row - 1 !== real) continue; const text = formatCellText(cell, displayText(cell)); if (!text) continue; const face = cellFontOf(cell?.style); ctx.font = face.font; // ⚠ ONLY A WRAPPED CELL RUNS TO MORE THAN ONE LINE. An unwrapped value is clipped by its // own column rather than folded, so measuring it against the column's width would ask for // room the paint will never use. const width = widthOf.get(at.col - 1); const lines = cell?.style?.wrap && width !== undefined ? wrapIntoLines(ctx, text, width - face.pad - 8).length : 1; // The 8 is the paint's own top and bottom inset (4 each), exactly as `wrapHeights` uses. tallest = Math.max(tallest, lines * Math.round(face.size * 1.35) + 8); } if (tallest <= 0) continue; measured = true; Object.assign(rowHeights, rowHeightsPatch(tab, [real], Math.ceil(tallest)).rowHeights); } if (!measured) { onNotice("These rows hold nothing to measure, so the row height is left as it is."); return; } if (Object.keys(rowHeights).length) onTabView({ rowHeights }); }, [cellFontOf, cells, columns, onNotice, onTabView, readOnly, realRow, tab, viewRange, zoom]); /** * ⭐⭐ W51-T34 / R17 — THE ONE DOOR BOTH FREEZE AXES GO THROUGH, and it is the page's own * `onFreeze`, which is `setFreeze` behind `commitSheets`: one history step, one PUT, and the * clamp into the sheet's extent happens there rather than being restated here. * * ⚠ BOTH NUMBERS ARE SENT EVERY TIME. `setFreeze` MERGES the patch it is given, so sending * only the one that changed would leave the other at whatever it happened to be, which is how * "freeze the first row" would silently keep a column freeze somebody had already removed. */ const applyFreeze = useCallback((next: { rows: number; cols: number }) => { onFreeze({ rows: Math.max(0, Math.round(next.rows || 0)), cols: Math.max(0, Math.round(next.cols || 0)), }); setFreezeAsk(null); }, [onFreeze]); // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W51-T18 — THE TWO ACTS THIS TICKET ADDS, AND BOTH TAKE DOORS THAT ALREADY EXIST. // // A rule list is a TAB level document key, so it takes `onRules` (or the local fallback while // the page has not wired it). A validation is a CELL key, so it takes `onCommit`, which is the // one commit door every other bulk act in this component already uses: one history step, one // PUT, one `rev`. // ═══════════════════════════════════════════════════════════════════════════════════════════ /** The selection as a rule's `range`, which is what a new rule opens with. */ const selectionRange = useCallback((): string => { const range = viewRange(); if (!range) return "A1"; const first = addrAt(Math.min(range.col0, range.col1), Math.min(range.row0, range.row1)); const last = addrAt(Math.max(range.col0, range.col1), Math.max(range.row0, range.row1)); return first === last ? first : `${first}:${last}`; }, [addrAt, viewRange]); /** Save the rules dialog's draft, and say where they went when the page has no door yet. */ const saveRules = useCallback((next: SheetRule[]) => { if (!onRules) { setRulesLocal({ tabId: tab.id, rules: next }); onNotice("These rules paint this sheet for as long as it stays open. Saving them with the " + "workbook arrives with the page's own door."); } onRules?.(next); setRulesOpen(false); }, [onNotice, onRules, tab.id]); /** Open the validation list editor on the selection, with the anchor cell's list in it. */ const openValidation = useCallback(() => { const addrs = selectedAddrs(); if (addrs.length === 0) { onNotice("Select the cells that should offer a list first."); return; } setListAsk({ addrs, list: [...(validationOf(cellAt(tab, addrs[0]))?.list ?? [])] }); }, [onNotice, selectedAddrs, tab]); /** * ⭐⭐ S67-T07 (QI19, R31) — THE CELL MENU'S ACTS, EACH ROUTED TO THE DOOR THE RIBBON ALREADY USES: * the clipboard (`copySelection` / `pasteFromClipboard`), structure (`structure` and * `structureForSelection`), `clearSelection`, `applyStyle`, the sheet filter state, the note and * link writers' cell shape, validation and number format. Format Cells... raises contract C3's * `aios:sheet-format-cells`, which lane B's FormatCellsDialog mounts on. * ⚠ Sort A to Z / Z to A are the one local implementation: the Data ribbon's row sort is private * to `ribbonData.tsx`, outside every fence this wave; this is the same stable, blanks-last, * numbers-before-text order, committed as one step (COMBINE note in S67-T07's record). */ const onCellMenuAct = useCallback((act: CellMenuAct) => { const range = viewRange(); const col0 = range ? realCol(Math.min(range.col0, range.col1)) : 0; const col1 = range ? realCol(Math.max(range.col0, range.col1)) : 0; const row0 = range ? realRow(Math.min(range.row0, range.row1)) : 0; const row1 = range ? realRow(Math.max(range.row0, range.row1)) : 0; const style = anchorStyle; const anchorAddr = addressOf(col0, row0); const sortRowsBy = (direction: 1 | -1) => { if (!range || row1 <= row0) { onNotice("Select two or more rows to sort."); return; } const keyOf = (cell: Cell | null | undefined): [number, number | string] => { const v = cell ? cellToValue(cell) : null; if (!v || v.kind === "empty" || !("value" in v) || v.value === "") return [2, ""]; if (v.kind === "number") return [0, v.value]; return [1, String(v.value)]; }; const rows = []; for (let r = row0; r <= row1; r += 1) { const cellsOfRow = []; for (let c = col0; c <= col1; c += 1) cellsOfRow.push(cellAt(tab, addressOf(c, r))); rows.push({ cellsOfRow, index: r - row0, key: keyOf(cellsOfRow[0]) }); } rows.sort((a, b) => { if (a.key[0] !== b.key[0]) return a.key[0] - b.key[0]; if (a.key[0] === 2) return a.index - b.index; const cmp = a.key[0] === 0 ? (a.key[1] as number) - (b.key[1] as number) : String(a.key[1]).localeCompare(String(b.key[1]), undefined, { numeric: true }); return cmp * direction || a.index - b.index; }); const edits: Record = {}; rows.forEach((row, i) => row.cellsOfRow.forEach((cell, j) => { edits[addressOf(col0 + j, row0 + i)] = cell ?? null; })); commitWithRecalc(edits); }; switch (act) { case "cut": copySelection(true); return; case "copy": copySelection(false); return; case "paste": case "paste-values": case "paste-formulas": case "paste-formatting": case "paste-transpose": case "paste-link": pasteFromClipboard(MENU_PASTE_OPTIONS[act]); return; case "paste-special": openPasteSpecial(); return; case "insert-down": structureForSelection(true); return; case "delete-up": structureForSelection(false); return; case "insert-right": case "delete-left": return; case "insert-row": structure("row", row1 - row0 + 1, row0 + 1); return; case "insert-col": structure("col", col1 - col0 + 1, col0 + 1); return; case "delete-row": structure("row", -(row1 - row0 + 1), row0 + 1); return; case "delete-col": structure("col", -(col1 - col0 + 1), col0 + 1); return; case "clear-contents": clearSelection(); return; case "filter-reapply": setFilterState((was) => (was ? { ...was } : was)); return; case "filter-clear": setFilterState((was) => (was ? { ...was, values: {} } : was)); return; case "filter-value": { if (!range) return; const value = sheetFilterValue(cellAt(tab, anchorAddr)); if (sheetFilter && col0 >= sheetFilter.col0 && col0 <= sheetFilter.col1 && row0 > sheetFilter.headerRow) { setFilterState((was) => (was ? { ...was, values: { ...was.values, [col0]: new Set([value]) } } : was)); return; } // The current region's top row is its header, as Excel reads it. let header = row0; while (header > 0 && isFilled(tab, col0, header - 1)) header -= 1; const region = header < row0 ? sheetFilterRegion(tab, { col0, col1: col0, row0: header, row1: header }) : null; if (!region) { onNotice("This cell has no header above it to filter under."); return; } setFilterState({ ...region, scope: renderedWorkbookKey, values: { [col0]: new Set([value]) } }); return; } case "sort-asc": sortRowsBy(1); return; case "sort-desc": sortRowsBy(-1); return; case "new-comment": case "new-note": setNoteAsk({ addr: anchorAddr, text: cellAt(tab, anchorAddr)?.note ?? "" }); return; case "format-cells": window.dispatchEvent(new CustomEvent("aios:sheet-format-cells", { detail: { tab: "number" } })); return; case "pick-list": openValidation(); return; case "link": setLinkAsk(anchorAddr); return; case "bold": applyStyle({ bold: style?.bold ? null : true }); return; case "italic": applyStyle({ italic: style?.italic ? null : true }); return; case "center": applyStyle({ align: style?.align === "center" ? null : "center" }); return; case "accounting": onNotice(NOT_YET_FORMAT_CODE); return; case "percent": applyStyle({ format: { kind: "percent", decimals: 0 } }); return; case "comma": applyStyle({ format: { kind: "number", decimals: 2, thousands: true } }); return; case "decimal-more": case "decimal-less": { const held = style?.format; const was = held && !held.code ? held : { kind: "number" as const, decimals: 0 }; const decimals = Math.max(0, Math.min(10, (was.decimals ?? 0) + (act === "decimal-more" ? 1 : -1))); applyStyle({ format: { ...was, decimals } }); return; } case "grow-font": case "shrink-font": { const now = fontPt(style?.size ?? null); const ladder = [...FONT_SIZE_LADDER]; const next = act === "grow-font" ? ladder.find((pt) => pt > now) ?? ladder[ladder.length - 1] : [...ladder].reverse().find((pt) => pt < now) ?? ladder[0]; applyStyle({ size: next }); return; } case "format-painter": toggleFormatPainter(); return; // Excel's mini toolbar buttons apply their last colour; the first use is Excel's default. case "fill": applyStyle({ fill: "#FFFF00" }); return; case "font-color": applyStyle({ color: "#FF0000" }); return; case "borders": applyStyle({ border: { ...(style?.border ?? {}), bottom: true } }); return; case "merge-center": return; } }, [anchorStyle, applyStyle, clearSelection, commitWithRecalc, copySelection, onNotice, openPasteSpecial, openValidation, pasteFromClipboard, realCol, realRow, renderedWorkbookKey, sheetFilter, structure, structureForSelection, tab, toggleFormatPainter, viewRange]); /** * Write the list onto every selected cell, as ONE commit. * * ⚠ `validationEdits`'s OWN bound-cell skip (`validation.ts`) is a different question from R5's * retired convert wall: a list of allowed entries is a promise a connector never made, so a * bound cell there is left exactly as it was, and this states that in its own words rather * than through the retired tally sentence sheetState.ts once exported for this. */ const saveValidation = useCallback((list: string[]) => { if (!listAsk) return; const out = validationEdits(tab, listAsk.addrs, list); if (Object.keys(out.edits).length > 0) onCommit(out.edits); if (out.boundSkipped > 0) { onNotice(out.boundSkipped === 1 ? "One cell reads from a connected database, so it cannot take a list of allowed values." : `${out.boundSkipped} cells read from a connected database, so they cannot take a list ` + "of allowed values."); } setListAsk(null); }, [listAsk, onCommit, onNotice, tab]); /** * Take one choice from the dropdown. * * ⛔ THE FREE TYPED SEARCH TEXT GOES THROUGH THE SAME CHECK. Pressing Enter on a query that * matches nothing is the one gesture that can ask a validated cell for a value outside its * list, and it is refused with a SENTENCE rather than ignored: a dropdown that silently did * nothing would read as broken (`validation.ts::checkEntry`). */ const chooseValue = useCallback((text: string) => { if (!dropdown) return; const list = validationOf(cellAt(tab, dropdown.addr))?.list ?? []; const verdict = checkEntry(list, text); if (!verdict.ok) { onNotice(verdict.message ?? ""); return; } const cell = cellAt(tab, dropdown.addr); const next = commitTyped(cell, canonicalEntry(list, text)); // ⭐ W53-T01: choosing from the list WRITES A VALUE, so a formula reading this cell follows // it exactly as it follows a typed one. commitWithRecalc({ // ⚠ THE LIST SURVIVES THE CHOICE. `commitTyped` builds a fresh literal, so handing back its // result unchanged would delete the very validation that produced the value. [dropdown.addr]: next ? { ...next, validation: { list: [...list] } } : { kind: "empty", state: "fresh", validation: { list: [...list] } }, }); setDropdown(null); }, [commitWithRecalc, dropdown, onNotice, tab]); // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W51-T15 DECLARED THE VOCABULARY, W51-T16 ANSWERS EVERY WORD OF IT. // // ⛔⛔ THE `default` ARM IS A COMPILE ERROR, NOT A COMMENT. `_exhaustive: never` only accepts // `action.kind` when every member of the union has been handled above, so adding a control to // `Ribbon.tsx::RibbonActionKind` without wiring it here fails `tsc` rather than shipping a // button that does nothing. That silent fall-through IS the defect instruction 17 reported, so // the fix is the one that cannot be made again. // // ⚠ ONE ACT STILL ANSWERS WITH A SENTENCE RATHER THAN AN EFFECT, and it is named where it is // declared: a custom format code needs contract C7's parser (W51-T20). It is not silent. // W51-T18 turned the other one into a door. // ═══════════════════════════════════════════════════════════════════════════════════════════ const onRibbonAction = useCallback((action: RibbonAction) => { if (readOnly && (!["copy", "find", "go-to"].includes(action.kind) || (action.kind === "find" && action.arg === "replace"))) return; if (action.kind === "paste" && action.arg === "special") { openPasteSpecial(); return; } if (action.kind === "paste" && (action.arg === "transpose" || action.arg === "link")) { pasteFromClipboard(MENU_PASTE_OPTIONS[action.arg === "transpose" ? "paste-transpose" : "paste-link"]); return; } switch (action.kind) { // -- the workbook's own doors, handed in by contract C1 -------------------------------- case "refresh": onRefresh?.(); return; case "import": onOpenImport?.(); return; // -- Clipboard -------------------------------------------------------------------------- case "paste": pasteFromClipboard(pasteOptionsFrom(action.arg)); return; case "cut": copySelection(true); return; case "copy": if (selectedChartId) { copyChartImageToClipboard(selectedChartId); return; } copySelection(false); return; case "format-painter": toggleFormatPainter(); return; // -- Font ------------------------------------------------------------------------------- case "font-size": applyStyle({ size: SIZE_OF_STEP[String(action.arg ?? "normal")] ?? "m" }); return; // -- Alignment. The vertical three are a SET, so pressing the one already on turns it off, // exactly as the horizontal three already do. case "align-top": case "align-middle": case "align-bottom": { const to = action.kind.slice("align-".length) as CellValign; applyStyle({ valign: anchorStyle?.valign === to ? null : to }); return; } case "wrap-text": applyStyle({ wrap: !anchorStyle?.wrap }); return; case "indent-decrease": stepIndent(-1); return; case "indent-increase": stepIndent(1); return; // -- Number. Both of these need a reader this tree does not have yet, and say so. -------- case "format-accounting": case "format-custom": onNotice(NOT_YET_FORMAT_CODE); return; // -- Styles. R8: this group is conditional formatting's ONLY door. ----------------------- case "conditional-formatting": setRulesOpen(true); return; // ⭐⭐ W54-T05 — A COLOUR SCALE AND A DATA BAR ARE BUILT FROM THE SELECTION AND GO OUT // THROUGH `saveRules`, WHICH IS THE DOOR THE DIALOG ALREADY USES. There is no second // writer of `tab.rules` in this file and there must not be: the local list, the cap // refusal and the "these last as long as the sheet stays open" notice all live behind // that one function, and a second path would have to restate all three. // // ⚠ THE BOUNDS ARE MEASURED NOW AND STORED, WHICH IS A REAL LIMITATION RATHER THAN A // SHORTCUT TAKEN QUIETLY. They ride `op: "between"` in `value` and `value2`, which the // server already persists, so the rule survives a save with no new field; the price is // that the scale does not re-normalise when the numbers later change. Make the rule // again over the selection to re-measure it. `rules.ts::scaleRule` says the same thing // where the decision lives. case "colour-scale": case "data-bars": { const addrs = selectedAddrs(); const bounds = numericBounds(addrs.map((addr) => ruleSubject(cellAt(tab, addr)))); if (!bounds) { onNotice("Select a block of numbers first. A colour scale and a data bar both read " + "the values in the selection to work out the range they spread across."); return; } const range = selectionRange(); const built = action.kind === "colour-scale" ? scaleRule(range, bounds.low, bounds.high) : barRule(range, bounds.low, bounds.high); const out = addRule(rules, built); if (out.refusal) { onNotice(out.refusal); return; } saveRules(out.rules); return; } // -- Cells ------------------------------------------------------------------------------ case "insert-row": structure("row", 1); return; case "delete-row": structure("row", -1); return; case "insert-column": structure("col", 1); return; case "delete-column": structure("col", -1); return; case "add-rows": onGrow(0, 100); return; case "add-columns": onGrow(10, 0); return; case "row-height": setAsk({ kind: "row-height", value: rowHeight }); return; case "column-width": setAsk({ kind: "column-width", value: COL_WIDTH }); return; case "hide-rows": hideBand("row"); return; case "hide-columns": hideBand("col"); return; case "unhide": unhideAll(); return; // ⭐ W54-T07 — the two AUTOFITS. Their asymmetry is stated where they are implemented, // beside `applyAsk`, which is the writer they share with the manual dialog. case "autofit-rows": autoFitRows(); return; case "autofit-columns": autoFitColumns(); return; // ⭐⭐ W51-T34 / R17 — THE FREEZE ACT OPENS THE PANES PANEL NOW, because R17 asks for // ROWS AND COLUMNS and a single toggle can only ever answer one of them. Every // act the toggle had is still inside it, freezing the first column included, and // the panel is this component's own: `Ribbon.tsx` belongs to W51-T15 and adding a // second Freeze item there would be a second home for one control. case "freeze": setFreezeAsk({ rows: frozenRows, cols: tab.freeze?.cols ?? 0 }); return; // -- Editing ---------------------------------------------------------------------------- case "autosum": autoSum(); return; case "fill-down": fillSelection("down"); return; case "fill-right": fillSelection("right"); return; case "clear-contents": clearSelection(); return; case "clear-formats": clearSelectionWith("formats"); return; case "clear-all": clearSelectionWith("all"); return; // ⭐⭐ W54-T07 — FIND AND SELECT'S THREE, AND NOT ONE OF THEM BUILDS A SURFACE. // // ⛔ `find` DOES EXACTLY WHAT Ctrl+F DOES, to the byte, because it is the same box: opening // it fresh over an open one would throw away a query somebody is halfway through typing, // which is why both doors take the `was ?? ...` shape rather than assigning. // ⛔ `replace` OPENS THAT SAME BOX with its second row showing. There is no second find box // in this app and there must not be: a second matcher would eventually disagree with // `findMatches` about what a formula cell says, and nothing would report the difference. // ⭐ `go-to` FOCUSES THE FORMULA BAR'S CELL ADDRESS INPUT, which is Excel's Name Box and // already jumps to whatever address is typed into it. Reaching it by its accessible name // is the idiom `Ribbon.tsx`'s own roving focus uses to reach a control it does not hold a // ref to, and the bar is rendered INSIDE this component's wrapper, so the query is // scoped to this grid rather than to the document. case "find": setFind((was) => was ?? { query: "", at: -1 }); return; case "replace": setFind((was) => ({ query: was?.query ?? "", at: was?.at ?? -1, replace: was?.replace ?? "", replacing: true, })); return; case "go-to": { const box = wrapRef.current?.querySelector( 'input[aria-label="Cell address"]', ); if (!box) { onNotice("The cell address box is not on screen, so there is nowhere to type an " + "address to go to."); return; } box.focus(); box.select(); return; } default: { const _exhaustive: never = action.kind; return _exhaustive; } } }, [anchorStyle, applyStyle, autoFitColumns, autoFitRows, autoSum, clearSelection, clearSelectionWith, copyChartImageToClipboard, copySelection, fillSelection, frozenCols, frozenRows, hideBand, onGrow, onNotice, onOpenImport, onRefresh, openPasteSpecial, pasteFromClipboard, rowHeight, rules, saveRules, selectedAddrs, selectedChartId, selectionRange, stepIndent, structure, tab, toggleFormatPainter, unhideAll, readOnly]); // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W54-T19 (INSTRUCTION 13) — THE HALF OF THE DEFECT THAT NEVER REACHES glide AT ALL. // // ⛔⛔ MEASURED, NOT REASONED. At 1440x900 against a real authenticated sheet: with the canvas // focused, twelve ArrowDown and eight ArrowRight move the selection and every scroll offset on // the page stays at zero. Blur the canvas so `document.body` holds the keyboard, and fifteen // ArrowDown drag `.dvn-scroller` from 0 to 600 while the selection does not move one cell. // `.dvn-scroller` is glide's own scroller (6836 tall inside a 653 tall box), so the page LOOKS // like the sheet scrolled itself and the selected cell sits frozen where it was. That is the // owner's report exactly, and no edit to the handler above can reach it: glide's `onKeyDown` // fires only while its canvas holds the keyboard. // // ⛔⛔ SO THE FIX IS THE FOCUS, NOT THE KEY. The scroll is the browser's answer to an arrow that // nothing owns, so the sheet stops letting the keyboard fall on the floor in the first place: // whenever focus goes NOWHERE while the sheet is up, the grid takes it straight back, and the // next arrow reaches glide and moves the selection exactly as it does in the healthy path. // Every one of the ticket's states resolves to the same one cause. A fast click on a chrome // region that takes no focus, and an overlay that closes while its own focused node unmounts, // both leave `document.activeElement` on ``; a menu, a text box or a button that DOES // hold focus is never touched here, because focus did not go nowhere. // // ⛔ AND IT IS THE ONLY SHAPE AVAILABLE, WHICH IS WORTH RECORDING RATHER THAN REDISCOVERING. // `verify_grid_ux.py`'s W52-T07 contract C8 leg asserts that this file contains NO raw keydown // listener at all, so that Escape can never be answered anywhere but the one arbiter. A // document level key guard for the arrows would red that leg. Reaching for the focus instead // satisfies both rules honestly rather than dodging one of them. // // ⚠ DEFERRED BY ONE FRAME, AND RE-TESTED. A click that lands somewhere focusable blurs first // and focuses second, so claiming the keyboard synchronously inside `focusout` would fight the // very gesture that is about to place it correctly. One frame later the browser has settled, // and the claim happens only if the keyboard is still nowhere. // // ⚠ TWO GRIDS AND ONE EDITOR. A selection inside the frozen band lives on the band's own // `DataEditor` (`frozenSelection`), and while a formula is being authored the arrows belong to // that input's point mode, so the claim goes to whichever of the three currently owns them. // // ⛔ NOTHING HERE READS Escape, in any branch. Escape belongs to the sheet's own arbiter and to // DESIGN.md section 4. // ═══════════════════════════════════════════════════════════════════════════════════════════ useEffect(() => { let frame = 0; const claim = () => { const at = document.activeElement; // Somebody took the keyboard in the meantime, which is the outcome this wants anyway. if (at !== null && at !== document.body && at !== document.documentElement) return; if (document.querySelector(MODAL_SELECTOR)) return; if (formulaEdit) { formulaInputRef.current?.focus(); return; } (inBand ? bandGridRef : gridRef).current?.focus(); }; const rescue = (event: FocusEvent) => { const target = event.target as Node | null; if (embedded && (!target || !wrapRef.current?.contains(target))) return; if (!embedded && target instanceof Element && target.closest('.sheet-page[data-embedded="true"]')) return; // A related target means another control took the keyboard on purpose. Only a focus that // went NOWHERE is the state an arrow scrolls in. if (event.relatedTarget !== null) return; if (!document.hasFocus()) return; frame = window.requestAnimationFrame(claim); }; document.addEventListener("focusout", rescue, true); if (!embedded) claim(); return () => { window.cancelAnimationFrame(frame); document.removeEventListener("focusout", rescue, true); }; }, [embedded, formulaEdit, inBand]); // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W51-T17 — RULING R7's EXCEL WORKING SET, THROUGH THE ONE TABLE IN `shortcuts.ts`. // // ⛔⛔ THE `default` ARM IS A COMPILE ERROR, NOT A COMMENT, exactly as the ribbon's is. A row // added to `SHORTCUTS` without an arm here fails `tsc`, so the panel can never advertise a key // this handler drops. That is the second half of the no-drift rule; the first half is that the // panel has no chords of its own to drift WITH. // // ⛔ THE CANVAS KEEPS THE FIVE IT ALREADY DOES CORRECTLY (`shortcuts.ts::ShortcutOwner`). They // still have arms below because the switch is exhaustive; those arms are reached only if the // table's `owner` changes, and they say so. // // ⛔ EVERY SHEET-OWNED CHORD TAKES BOTH DOORS. `cancel()` stops glide and `preventDefault()` // stops the BROWSER, and the second one is not politeness: Ctrl+R reloads the page, Ctrl+D // bookmarks it, Ctrl+Plus and Ctrl+Minus zoom it and Ctrl+F opens its find bar. A person who // pressed Ctrl+R expecting a fill right and got a page reload has lost unsaved work. // // ⚠ AND Ctrl+F IS NOT SWALLOWED WHERE THE SHEET IS NOT LOOKING. This handler is glide's own // `onKeyDown`, which fires only while the grid canvas holds the keyboard, so the browser's find // still opens everywhere else on the page. That is why there is no document listener here. // ⚠ W54-T19 KEPT IT THAT WAY. The arrow that never reaches this handler is answered by taking // the FOCUS back (the effect above), not by reading keys off the document, so contract C8's // "no raw keydown listener in this file" still holds and Escape still has exactly one arbiter. // ═══════════════════════════════════════════════════════════════════════════════════════════ // S68-T28 / R18: both canvas and accessibility-table doors supply the same focus facts. const pasteShortcutContext = useCallback((target?: EventTarget | null) => { const active = document.activeElement; const textInput = (node: EventTarget | null | undefined) => node instanceof Element && (!!node.closest('input, textarea, select, [contenteditable="true"], [contenteditable=""], [contenteditable="plaintext-only"]') || (node instanceof HTMLElement && node.isContentEditable)); return { gridFocused: !!active && !!wrapRef.current?.contains(active) && !!active.closest(".sheet-grid-canvas") && !document.querySelector('dialog[open], [aria-modal="true"]'), typing: formulaEdit !== null || textInput(target) || textInput(active), }; }, [formulaEdit]); const onKeyDown = useCallback( (event: GridKeyEventArgs) => { const viewerHit = readOnly ? matchShortcut(event) : null; if (readOnly && ((viewerHit !== null && !["jump-edge", "extend-edge", "extend-cell", "go-home", "go-end", "page-up", "page-down", "prev-sheet", "next-sheet", "select-all", "select-column", "select-row", "select-region", "find", "show-shortcuts"].includes(viewerHit)) || (!event.ctrlKey && !event.metaKey && !event.altKey && (event.key.length === 1 || event.key === "F2")))) { event.cancel(); event.preventDefault(); event.stopPropagation(); return; } // glide invokes this before applying its own key-driven selection. Keep that callback tied // to the reader's key for this event only; a later data-identity reconciliation has no key. keyboardSelectingRef.current = true; queueMicrotask(() => { keyboardSelectingRef.current = false; }); // Glide carries the physical code in rawEvent. The common DOM capture normally answers // first; this keeps the canvas door correct when Glide invokes its callback directly. if (matchShortcutInGrid({ ...event, code: event.rawEvent?.code }, pasteShortcutContext(event.rawEvent?.target)) === "paste-special") { event.cancel(); event.preventDefault(); event.stopPropagation(); openPasteSpecial(); return; } // S67-T07: Shift+F10 and the Menu key open Excel's cell menu at the current cell. if ((event.shiftKey && event.key === "F10") || event.key === "ContextMenu") { const item = selectionRef.current?.current?.cell; const bounds = item && (item[1] < 0 ? bandGridRef : gridRef).current ?.getBounds(item[0], item[1] < 0 ? item[1] + bandRows : item[1]); if (item && bounds) { event.cancel(); event.preventDefault(); setAnchor(null); setMenu({ anchor: rectAnchor(bounds), col: realCol(item[0]) + 1, row: realRow(item[1] < 0 ? item[1] : item[1]) + 1, on: "cell", }); return; } } // A canvas button also has a keyboard door, without another key listener. if (event.altKey && !event.ctrlKey && !event.metaKey && event.key === "ArrowDown") { const item = selectionRef.current?.current?.cell; const bounds = item && (item[1] < 0 ? bandGridRef : gridRef).current ?.getBounds(item[0], item[1] < 0 ? item[1] + bandRows : item[1]); if (item && bounds && openSheetFilter(item, { bounds, preventDefault: () => { event.cancel(); event.preventDefault(); } })) return; } // ═════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W54-T28 (INSTRUCTION 19, R9(iv)) — ENTER DOWN, TAB RIGHT, AND THE RETURN. // // R9(iv), verbatim: "Commit navigation: Enter down, Tab right, Shift+Enter up, Shift+Tab // left, and Enter returns to the column the Tab run started at." // // ⛔⛔ THE DEFECT, MEASURED IN A REAL BROWSER AT 1440x900 READING BOTH THE ADDRESS BOX AND // `document.activeElement`. On an empty sheet at B3, Enter left the address at B3 and put // the focus in a `gdg-input` textarea; Shift+Enter did the same. Three Tabs reached E3 // correctly, and the Enter after them opened an editor on E3 rather than landing on B4. An // arrow pressed next then read as inert, because the editor was sitting open swallowing it. // // ⛔⛔ THE CAUSE IS ONE STRING, AND IT IS DELIBERATELY NOT CHANGED. `KEYBINDINGS` above // binds `activateCell` to space, Enter, shift+Enter and F2, so the grid library ACTIVATED // the cell instead of committing and moving. That library calls THIS handler first and // skips its own table entirely once the press has been cancelled, so answering the four // keys here leaves the string exactly as it was - which matters twice over: W54-T25's F2 // clause depends on `activateCell` still carrying F2, and space still starts an edit. // // ⛔ TAB AND SHIFT+TAB WERE ALREADY RIGHT, AND THEY ARE STILL BROUGHT THROUGH HERE. The // library binds neither, so they were moving the selection by the browser's own focus // traversal through the accessibility table - which is why the measurement found the focus // on a `TD` afterwards, one press away from leaving the grid altogether. Answering all four // in one arm is what makes the run's origin knowable, and stopping the browser is what // keeps the keyboard on the canvas so the next arrow key works straight away. // // ⛔ IT SITS ABOVE THE SHORTCUT LOOKUP, NOT INSIDE EITHER BRANCH BELOW. `commitDirection` // refuses any press carrying Ctrl, Meta or Alt, so Ctrl+Enter still fills the selection and // Alt+Enter still inserts a line break; nothing else in the table claims a bare Enter or // Tab. Arrows are untouched, because that same function answers null for all four of them. // // ⚠ THE ARITHMETIC IS NOT HERE. `commitDirection`, `commitTarget` and `tabRunOrigin` live // in the import-free `shortcuts.ts`, so a gate RUNS R9(iv) rather than reading it. // // ⚠ THE BOUNDS ARE ASKED FOR, NEVER WRITTEN DOWN. `visCols` and `visRows` come from the // open sheet's own extent (W54-T29 moved it to 200 by 10,000), and the row floor is the // frozen band's negative range, so Shift+Enter can still walk up into a frozen row. // ═════════════════════════════════════════════════════════════════════════════════════ const commit = commitDirection(event); const commitFrom = selection?.current?.cell; if (commit !== null && commitFrom) { event.cancel(); event.preventDefault(); const origin = tabRunAt.current; const land = commitTarget( { col: commitFrom[0], row: commitFrom[1] }, commit, origin, { minCol: 0, maxCol: Math.max(0, visCols.length - 1), minRow: -bandRows, maxRow: Math.max(0, visRows.length - 1), }, ); tabRunAt.current = tabRunOrigin(origin, commit, commitFrom[0]); commitNav.current = true; applySelection({ col0: land.col, row0: land.row, col1: land.col, row1: land.row }); handoffNavigationFocus(commitFrom[1], land.row); return; } if (moveAcrossFrozenBoundary(event)) return; const hit: ShortcutId | null = matchShortcut(event); // ═════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W54-T19 (INSTRUCTION 13) — AN ARROW STOPS THE BROWSER FIRST, BEFORE ANY BRANCHING. // // ⛔⛔ THE DEFECT, AND IT IS INSIDE glide RATHER THAN IN THIS FILE. glide 6.0.3 matches an // arrow through its own keybindings and then sets `cancelOnlyOnMove`, so it stops the // browser ONLY when the selection actually moved. On the last row, the last column, or // with no current cell, the match happens, the move does not, nothing stops the browser, // and the native arrow scroll runs on `.dvn-scroller` instead. That is the owner's exact // report, word for word: the cell freezes in place and the page scrolls. // // ⛔ SO IT SITS ABOVE ALL THREE EXITS. The `hit === null` fall through returns early for a // plain arrow, and `shortcutOwner(hit) === "canvas"` returns early for Shift+Arrow, so a // guard placed after either one would miss the two commonest presses in the sheet. // // ⛔ IT STOPS THE BROWSER AND NOTHING ELSE. This is deliberately not the `cancel` half of // the pair used below: cancelling would tell glide to keep its hands off, and glide is // precisely the thing that MOVES the selection for a plain arrow and extends it for // Shift+Arrow. Stopping only the native scroll leaves both of those exactly as they were. // // ⚠ AND IT IS THE FOUR ARROWS ONLY. A blanket stop on every key here would swallow the // printable character that opens the formula editor a few lines below, and typing in a // sheet would stop working. // ═════════════════════════════════════════════════════════════════════════════════════ if (isArrowKey(event.key)) event.preventDefault(); if (hit === null) { // ⭐⭐ R5 (W52-T09): TYPING OVER A BOUND CELL NO LONGER ASKS FIRST. A bound cell is still // `readonly` (glide's own type-to-edit never opens for it), so the keystroke still has to // be caught here or it would be lost - but instead of routing to a confirm dialog (the // page's own retired callback), it opens the SAME floating editor a fresh formula does, // below. // `commitFormulaEditor` writes through `commitTyped`, which drops the binding on its own, // so the cell converts the moment Enter commits, with no confirmation. This is also // instruction 27's fix: that dialog never returned focus to the grid canvas on close, so // an arrow key afterwards scrolled the PAGE instead of moving the selection; removing the // dialog removes the surface that could ever steal that focus. This is not a shortcut, // which is why it sits outside the table. const current = selection?.current; if (!current) return; const primary = event.ctrlKey || event.metaKey; if (!primary && !event.altKey && event.key.length === 1) { const addr = addrAt(current.cell[0], current.cell[1]); const cell = cellAt(tab, addr); const chrome = viewChromeRefusal(cell); if (chrome) { event.cancel(); event.preventDefault(); onNotice(chrome); return; } // Record values, including a leading '=', belong to Data's editor/write contract. if (cell?.viewChild) return; const inBand = current.cell[1] < 0; const viewCell: readonly [number, number] = inBand ? [current.cell[0], current.cell[1] + bandRows] : current.cell; // ═══════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W54-T22 (INSTRUCTION 16) — ONE `=` PRODUCES ONE `=`, NEVER TWO. // // ⛔⛔ THE DEFECT, MEASURED IN A REAL BROWSER AT 1440x900, THREE TIMES. Click a cell, // press `=` once, and the floating editor holds `==`. Press `=` then `1` and it holds // `==1`. Type `=1+1` and it holds `==1+1`. ONLY THE FIRST CHARACTER DOUBLES, and that // is most of the diagnosis: a handler running twice would double every key, and a // concatenating draft would grow without bound. It is ONE extra insertion, arriving // exactly at the moment this component's editor mounts and takes the keyboard. // // ⛔⛔ THE CAUSE IS THE MISSING SECOND DOOR, AND THE TWO DOORS ARE INDEPENDENT. glide's // `cancel` is glide-only - it raises glide's own cancelled flag and stops glide - while // `preventDefault` is the real DOM one that stops the BROWSER. The two branches below // took only the first, so the browser's own default action for that same keydown still // ran; by the time it did, the effect beside `formulaEdit` had focused // `formulaInputRef`, so the browser typed the character a SECOND time into an input // whose draft `openFormulaEditor` had already set to exactly that character. Every // later keystroke arrives once because by then the input is the only thing focused and // `onFormulaChange` reads its value raw. // // ⛔ SO THE STOP IS SCOPED TO THE BRANCHES THAT OPEN THIS COMPONENT'S OWN EDITOR, and // the predicate is hoisted so ONE decision covers both of them. Every other printable // character falls through to glide's OWN type-to-edit overlay, which mounts an empty // textarea and RELIES on that same default action to deliver its first character. A // blanket stop here would make typing a letter open an empty editor and swallow the // keystroke, so this must never widen past the two branches below. // // ⚠ IT HOLDS IN THE FROZEN BAND FOR FREE: both `DataEditor` mounts are wired to this // one handler, so there is no second copy of this decision to keep in step. // ═══════════════════════════════════════════════════════════════════════════════════ const opensOwnEditor = !!(cell && cell.kind === "bound") || (!validationOf(cell) && (cell?.kind === "formula" || event.key === "=")); if (opensOwnEditor) event.preventDefault(); if (cell && cell.kind === "bound") { event.cancel(); openFormulaEditor(addr, event.key, 1, viewCell, inBand); return; } // ⭐⭐ W52-T06 — A FORMULA IS AUTHORED THROUGH THIS COMPONENT'S OWN EDITOR, NOT glide's. // Two triggers open it: typing "=" fresh over any other editable cell (Excel's own // "start a formula" gesture), or typing ANY character directly over a cell that already // holds one (glide's default type-to-edit is switched off for such a cell in // `getCellContent`, so without this branch the keystroke would be silently lost rather // than opening anything). if (!validationOf(cell) && (cell?.kind === "formula" || event.key === "=")) { event.cancel(); openFormulaEditor(addr, event.key, 1, viewCell, inBand); } } return; } if (shortcutOwner(hit) === "canvas") return; event.cancel(); event.preventDefault(); const cur = selection?.current; switch (hit) { // -- the only remaining canvas-owned movement: in-pane Shift+Arrow. ------------------- // Unreachable while the table says `canvas`. case "extend-cell": return; // -- moving and selecting ------------------------------------------------------------- case "jump-edge": case "extend-edge": { const step = arrowStep(event.key); if (!step || !cur) return; // ⭐⭐ W54-T20 — TWO PERPENDICULAR PRESSES LEAVE A BLOCK, NOT A LINE. // // ⛔ THE EXTENSION TRAVELS FROM THE CURRENT RECTANGLE'S ACTIVE END, and it moves ONE // axis. Handing the anchor in on both axes, which is what this arm used to do, made // every press recompute a fresh jump from the anchor and collapse the axis it was not // moving, so Ctrl+Shift+Down followed by Ctrl+Shift+Left replaced a column with a row. // The anchor still never moves: it is passed to `applySelection` unchanged, and it is // one corner of the rectangle {@link extendEdgeRect} returns. const anchor = { col: cur.cell[0], row: cur.cell[1] }; const axis: SelectionAxis = step.dRow !== 0 ? "row" : "col"; const held: SelectionRect = { col0: cur.range.x, row0: cur.range.y, col1: cur.range.x + cur.range.width - 1, row1: cur.range.y + cur.range.height - 1, }; const startAt = hit === "extend-edge" ? edgeStart(held, anchor, axis) : (axis === "row" ? anchor.row : anchor.col); const col = realCol(axis === "row" ? anchor.col : startAt); const row = realRow(axis === "row" ? startAt : anchor.row); // ⛔ THE EDGE IS COMPUTED IN THE SHEET'S OWN COORDINATES AND MAPPED BACK. A run of // values is a run of ADDRESSES; walking glide's visible rows would stop at a hidden // band and call it the end of the data. const real = step.dRow !== 0 ? { col, row: edgeIndex(row, extent.rows, step.dRow, (i) => isFilled(tab, col, i)) } : { col: edgeIndex(col, extent.cols, step.dCol, (i) => isFilled(tab, i, row)), row }; const to = { col: viewIndexOf(visCols, real.col), row: viewRowOf(real.row) }; if (hit === "jump-edge") { applySelection({ col0: to.col, row0: to.row, col1: to.col, row1: to.row }); handoffNavigationFocus(cur.cell[1], to.row); } else { applySelection( extendEdgeRect(held, anchor, axis === "row" ? to.row : to.col, axis), cur.cell, ); } return; } case "go-home": { if (!cur) return; const to: Item = [0, -bandRows]; applySelection({ col0: to[0], row0: to[1], col1: to[0], row1: to[1] }, to); handoffNavigationFocus(cur.cell[1], to[1]); return; } case "go-end": { const used = usedExtent(tab); if (!used) { onNotice("This sheet holds nothing yet, so there is no last cell to go to."); return; } const to = { col: viewIndexOf(visCols, used.col), row: viewRowOf(used.row) }; applySelection({ col0: to.col, row0: to.row, col1: to.col, row1: to.row }); handoffNavigationFocus(cur?.cell[1] ?? to.row, to.row); return; } case "page-up": case "page-down": { if (!cur) return; const direction = hit === "page-up" ? -1 : 1; const row = Math.max(-bandRows, Math.min(Math.max(0, visRows.length - 1), cur.cell[1] + direction * bodyPageRowsRef.current)); applySelection({ col0: cur.cell[0], row0: row, col1: cur.cell[0], row1: row }); handoffNavigationFocus(cur.cell[1], row); return; } case "prev-sheet": switchTab(-1); return; case "next-sheet": switchTab(1); return; case "select-column": if (!cur) return; selectDocumentAxis("column", cur.cell[0]); return; case "select-row": if (!cur) return; selectDocumentAxis("row", cur.cell[1]); return; case "select-all": { if (!cur) return; const anchor = { col: realCol(cur.cell[0]), row: realRow(cur.cell[1]) }; const run = selectAllRunAt.current; const count = run && run.col === anchor.col && run.row === anchor.row ? run.count + 1 : 1; selectAllRunAt.current = { ...anchor, count }; const region = selectAllTarget(anchor, extent, (c, r) => isFilled(tab, c, r), count); selectAllNav.current = true; applySelection({ col0: viewIndexOf(visCols, region.col0), row0: viewRowOf(region.row0), col1: viewIndexOf(visCols, region.col1), row1: viewRowOf(region.row1), }, cur.cell); return; } case "select-region": { selectDocumentRegion(); return; } // -- entering and filling. Each one reaches the RIBBON's act, never a second copy. ----- case "fill-down": onRibbonAction({ kind: "fill-down" }); return; case "fill-right": onRibbonAction({ kind: "fill-right" }); return; case "autosum": onRibbonAction({ kind: "autosum" }); return; case "refresh": onRibbonAction({ kind: "refresh" }); return; case "clear-contents": onRibbonAction({ kind: "clear-contents" }); return; case "fill-selection": { const range = viewRange(); if (!range) return; // ⭐ EXCEL'S Ctrl+ENTER: the anchor's entry lands in every selected cell. `fillCells` // with a ONE CELL source is exactly that, references shifted, in one commit. const real: CellRange = { col0: realCol(range.col0), row0: realRow(range.row0), col1: realCol(range.col1), row1: realRow(range.row1), }; const out = fillCells( tab, { col0: real.col0, row0: real.row0, col1: real.col0, row1: real.row0 }, real, // ⛔ W51-T19: Ctrl+Enter IS A FILL, so it carries the same drag rules the handle, // Ctrl+D and Ctrl+R do. A door that reached `fillCells` without them would drag a // bound cell by a different rule from the one beside it, which is exactly the split // "one primitive, every door" exists to prevent. { catalogue: options, shadows: viewShadows }, cellValueGetter, ); if (Object.keys(out.edits).length === 0) { onNotice("Select the cell to copy and the cells to fill, then press Ctrl+Enter."); return; } landFill(out, false); return; } case "line-break": { if (!cur) return; // ⭐ R5 (W52-T09): a bound cell is no longer walled off here - `appendLineBreak` // writes through `commitTyped`, which drops its binding on its own. const out = appendLineBreak(tab, addrAt(cur.cell[0], cur.cell[1])); if (Object.keys(out.edits).length > 0) commitWithRecalc(out.edits); return; } case "today": { if (!cur) return; const addr = addrAt(cur.cell[0], cur.cell[1]); const cell = cellAt(tab, addr); // ⭐ R5 (W52-T09): Ctrl+; on a bound cell writes over it exactly like any other cell. commitWithRecalc({ [addr]: commitTyped(cell, dateStamp(new Date()), cellValueGetter) }); return; } // -- undo, redo and the workbook's own doors ------------------------------------------ case "undo": onUndo(); return; case "redo": case "redo-alt": onRedo(); return; case "save-now": onSaveNow?.(); return; // -- structure -------------------------------------------------------------------------- case "insert-at-selection": structureForSelection(true); return; case "delete-at-selection": structureForSelection(false); return; // -- formatting. The three toggles read the ANCHOR cell, exactly as the ribbon does. --- case "bold": if (!cur) return; applyStyle({ bold: !anchorStyle?.bold }); return; case "italic": if (!cur) return; applyStyle({ italic: !anchorStyle?.italic }); return; case "underline": if (!cur) return; applyStyle({ underline: !anchorStyle?.underline }); return; case "number-format": openNumberFormat(); return; case "format-currency": applyStyle({ format: { kind: "currency", decimals: 2 } }); return; case "format-percent": applyStyle({ format: { kind: "percent", decimals: 0 } }); return; case "format-general": applyStyle({ format: null }); return; case "format-date": applyStyle({ format: { kind: "date" } }); return; // -- the formula's anchors, the find box, and this list -------------------------------- case "cycle-anchors": { if (!cur) return; const addr = addrAt(cur.cell[0], cur.cell[1]); const cell = cellAt(tab, addr); if (!cell || cell.kind !== "formula") { onNotice("F4 cycles the dollar anchors of a formula, and this cell holds none."); return; } const next = cycleAnchors(cell.formula ?? ""); if (!next || next === cell.formula) return; commitWithRecalc({ [addr]: setFormula(cell, next, cellValueGetter) }); return; } case "find": setFind((was) => was ?? { query: "", at: -1 }); return; case "show-shortcuts": setShortcuts(true); return; case "paste-special": openPasteSpecial(); return; default: { const _exhaustive: never = hit; return _exhaustive; } } }, [addrAt, anchorStyle, applySelection, applyStyle, bandRows, cellValueGetter, commitWithRecalc, extent.cols, extent.rows, handoffNavigationFocus, moveAcrossFrozenBoundary, onCommit, onNotice, onRedo, onRibbonAction, onSaveNow, onUndo, openFormulaEditor, openSheetFilter, options, openNumberFormat, openPasteSpecial, pasteShortcutContext, realCol, realRow, selectDocumentAxis, selectDocumentRegion, selection, structureForSelection, switchTab, tab, viewRange, viewRowOf, viewShadows, visCols, visRows, readOnly], ); // ══════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W51-T34 — THE FOUR COLUMN ACTS, HOISTED, BECAUSE THE BAND GRID CARRIES THE LETTERS. // // ⛔ THE MAIN GRID IS GIVEN `headerHeight={0}` WHENEVER A BAND IS ON SCREEN, so the column // letters are drawn once rather than twice, by the band grid on top. That moves every act that // lives on the header strip with them: a resize, a column select and a right click all arrive // at the BAND grid while rows are frozen and at the MAIN grid while they are not. Written once // and handed to both, so neither can be the one that was forgotten. // // ⚠ A RESIZE IS THE ONE THAT SHOWS. `onColumnResize` fires per mousemove into `dragWidth`, // and `columns` above already folds `dragWidth` in, so passing THE SAME `columns` array to both // grids makes the two follow a drag together for free. A band grid given its own column list // would tear away from the body while the mouse was still down. // ══════════════════════════════════════════════════════════════════════════════════════════ const onColumnResizeStart = useCallback( (_col: GridColumn, size: number, colIndex: number) => { if (readOnly) return; const grid = bandRows > 0 ? bandGridRef.current : gridRef.current; const bounds = grid?.getBounds(colIndex, -1); if (!bounds) return; resizeGesture.current = { left: bounds.x, scale: bounds.width / size, width: size, committed: false, cols: columnsForResize(selectionRef.current, colIndex, headerProjectionBounds), startX: headerPressXRef.current ?? bounds.x + bounds.width, moved: false, }; }, [bandRows, headerProjectionBounds, readOnly], ); const onColumnResize = useCallback( (_col: GridColumn, newSize: number, _colIndex: number) => { const gesture = resizeGesture.current; // Glide's native double-click fitter emits only onColumnResize, with no gesture or end. // The wrapper's double-click owns AutoFit, so that isolated preview must never stick. if (readOnly || !gesture || gesture.committed) return; setDragWidth({ cols: gesture.cols, width: Math.max(1, gesture.width ?? newSize) }); }, [readOnly], ); const onColumnResizeEnd = useCallback( (_col: GridColumn, newSize: number, _colIndex: number) => { setDragWidth(null); const gesture = resizeGesture.current; if (readOnly || !gesture || gesture.committed) return; const width = Math.max(MIN_COL_WIDTH, Math.min(MAX_COL_WIDTH, Math.round((gesture?.width ?? newSize) / zoom))); const cols = gesture.cols; gesture.committed = true; queueMicrotask(() => { resizeGesture.current = null; }); // A border click is not a drag; the two presses before AutoFit take no history steps. if (!gesture.moved) return; // ⛔ TRANSLATED. `setColumnWidth` keys the width by COLUMN LETTER, so handing it a view // index would remember D's width against C the moment a column is hidden. if (width === 0) hideBands("col", cols.map(col => realCol(col) + 1)); else commitColumnWidths(cols.map(col => ({ col: realCol(col), width }))); }, [commitColumnWidths, hideBands, readOnly, realCol, zoom], ); const onHeaderClicked = useCallback((colIndex: number, args: { shiftKey: boolean; isEdge?: boolean }) => { // S64-T23: a click fires on RELEASE. When the pointer travelled across other headers the drag // has already set the range, and re-running the click would collapse it to one column. const drag = headerDragRef.current; headerDragRef.current = null; if (args.isEdge || headerBorderPressRef.current) return; if (drag?.moved) return; selectDocumentAxis("column", colIndex, args.shiftKey, false); }, [selectDocumentAxis]); const onHeaderContextMenu = useCallback( (colIndex: number, args: { preventDefault: () => void; bounds: Rectangle }) => { args.preventDefault(); setAnchor(null); setMenu({ anchor: rectAnchor(args.bounds), col: realCol(colIndex) + 1, row: 0, on: "column", }); }, [realCol], ); // ══════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W51-T34 — THE LOCKSTEP. THIS IS THE WHOLE FEATURE AND IT IS WHERE IT WOULD BREAK. // // Two grids that drift by a column are worse than no freeze at all, so the offset is COMPUTED // from glide's own scroller maths rather than guessed: `lockstepScrollX` inverts what // `scrolling-data-grid.js` reports, and its node proof drives the sign of `tx` and the frozen // column boundary. The main grid is the only driver; the band grid never reports back, because // two grids each answering the other's scroll oscillate. // // ⚠ `scrollOffsetX` IS NOT ONLY AN INITIAL VALUE, whatever its doc comment says: glide's // effect on it reruns on every change and writes `scrollRef.current.scrollLeft`, which is what // makes it a controlled horizontal position. Verified in `data-editor.js`. // ══════════════════════════════════════════════════════════════════════════════════════════ const [bandScrollX, setBandScrollX] = useState(0); /** The controlled position, readable from a listener that must not re-run on every scroll. */ const bandScrollXRef = useRef(0); bandScrollXRef.current = bandScrollX; /** Glide's own scroll coordinates. Chart anchors consume the same x/y and sub-cell transforms. */ const [chartViewport, setChartViewport] = useState({ x: 0, y: 0, tx: 0, ty: 0 }); const pageOverlayRef = useRef(null); const [pageOverlaySize, setPageOverlaySize] = useState({ width: 0, height: 0 }); useLayoutEffect(() => { const node = pageOverlayRef.current; if (!node) return; const measure = () => setPageOverlaySize({ width: node.clientWidth, height: node.clientHeight }); measure(); const observer = new ResizeObserver(measure); observer.observe(node); return () => observer.disconnect(); }, [pageGrid]); const onVisibleRegionChanged = useCallback((range: Rectangle, tx: number, ty: number) => { bodyPageRowsRef.current = Math.max(1, range.height - 4); const next = { x: Math.max(0, range.x), y: Math.max(0, range.y), tx: Number.isFinite(tx) ? tx : 0, ty: Number.isFinite(ty) ? ty : 0, }; setChartViewport((before) => ( before.x === next.x && before.y === next.y && before.tx === next.tx && before.ty === next.ty ? before : next )); if (bandRows <= 0) return; setBandScrollX(lockstepScrollX(columns.map((c) => c.width), frozenCols, range.x, tx)); }, [bandRows, columns, frozenCols]); /** * W62-T01: wheel input over the frozen band scrolled it away from the body. The listener * must be native and non-passive so preventDefault works, unlike React's passive wheel * handler. Forward both axes to the body, which remains the only scroll driver. */ useEffect(() => { const band = frozenBandRef.current; if (!band) return; const onWheel = (event: WheelEvent) => { // ⚠ Ctrl+wheel and Cmd+wheel are the BROWSER's zoom, not a scroll. Taking those would make // the frozen band the one region of the page a reader cannot zoom from. if (event.ctrlKey || event.metaKey) return; const body = [...(wrapRef.current?.querySelectorAll( ".sheet-grid-canvas .dvn-scroller", ) ?? [])].filter((scroller) => scroller.closest(".sheet-frozen-rows") === null); if (body.length === 0) return; const deltaX = event.deltaX || (event.shiftKey ? event.deltaY : 0); const deltaY = event.shiftKey ? 0 : event.deltaY; body.forEach((scroller) => { const unitX = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? scroller.clientWidth : 1; const unitY = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? scroller.clientHeight : 1; scroller.scrollLeft += deltaX * unitX; scroller.scrollTop += deltaY * unitY; }); event.preventDefault(); }; band.addEventListener("wheel", onWheel, { passive: false }); // ⛔⛔ AND THE WHEEL IS NOT THE ONLY THING THAT CAN MOVE THE BAND, which a SCREENSHOT is what // caught. With 7 rows and 2 columns frozen, clicking a body cell and pressing Ctrl+Right put // the selection on GR7 - a row INSIDE THE BAND, so the band grid owns that selection, and // glide scrolled ITS OWN scroller to bring GR into view. The body never moved: the frame // showed the header and the frozen rows at columns GL..GR while the body under them still // drew C..I. Same defect as the wheel, a different input, and there will be others (a // programmatic `scrollTo`, a find that lands in the band, a future glide version). // // ⭐ SO THE RULE IS STATED ONCE, GENERALLY: the band's scroller is never the authority. Any // scroll it takes on its own is TRANSFERRED to the body, which is the only driver; the body's // own report then writes `scrollOffsetX` back and the two agree. // ⚠ NO LOOP, and the reason is the comparison: a scroll the BODY caused arrives here already // equal to the controlled value, so it transfers nothing. Only a position the body did not // ask for is ever pushed. const onBandScroll = () => { const scroller = band.querySelector(".dvn-scroller"); const body = [...(wrapRef.current?.querySelectorAll( ".sheet-grid-canvas .dvn-scroller", ) ?? [])].filter((el) => el.closest(".sheet-frozen-rows") === null); if (!scroller || body.length === 0) return; if (Math.abs(scroller.scrollLeft - bandScrollXRef.current) < 1) return; const wanted = scroller.scrollLeft; body.forEach((el) => { el.scrollLeft = wanted; }); }; band.addEventListener("scroll", onBandScroll, { capture: true, passive: true }); return () => { band.removeEventListener("wheel", onWheel); band.removeEventListener("scroll", onBandScroll, { capture: true } as EventListenerOptions); }; }, [bandRows]); // W61-T10 / R12: measure the real glyphs, first at their natural width, then at the // visible grid edge. The frozen band's handle remains the authority for its cell bounds. const formulaBounds = formulaEdit ? (formulaEdit.inBand ? bandGridRef : gridRef).current?.getBounds( formulaEdit.viewCell[0], formulaEdit.viewCell[1]) : undefined; useLayoutEffect(() => { if (!formulaEdit) { setFormulaBox(null); setFormulaShift(null); setFormulaCaretOffset(undefined); return; } const sizer = formulaSizerRef.current; const caretSizer = formulaCaretSizerRef.current; const prefix = formulaCaretPrefixRef.current; if (!sizer || !caretSizer || !prefix) return; const canvas = wrapRef.current?.querySelector(".sheet-grid-canvas"); const measure = () => { const boundsRef = formulaEdit.inBand ? bandGridRef : gridRef; const bounds = boundsRef.current?.getBounds(formulaEdit.viewCell[0], formulaEdit.viewCell[1]); if (!bounds) return; // S67-T02: the draft grows right from the cell over its neighbours (and across the frozen // divider) to the pane edge, then wraps. A cell too close to that edge would leave a box // one cell wide, so the box widens LEFT to a readable width instead, its right edge on the // pane edge the way Excel grows a right-aligned cell. It never leaves the pane. const pane = canvas?.getBoundingClientRect(); const paneLeft = Math.max(0, pane?.left ?? 0); const paneTop = Math.max(0, pane?.top ?? 0); const paneBottom = Math.min(window.innerHeight - FORMULA_MODE_RESERVE, pane?.bottom ?? window.innerHeight); const roomRight = Math.max(bounds.width, (canvas?.getBoundingClientRect().right ?? window.innerWidth) - bounds.x - 4); sizer.style.maxWidth = "none"; const natural = Math.ceil(sizer.offsetWidth); const readable = Math.max(bounds.width, Math.min(FORMULA_EDITOR_READABLE_WIDTH, (pane?.width ?? window.innerWidth) - 8)); const maxWidth = roomRight >= Math.min(natural, readable) ? roomRight : Math.min(natural, readable); sizer.style.maxWidth = `${maxWidth}px`; const width = Math.max(bounds.width, Math.ceil(sizer.offsetWidth)); const height = Math.max(bounds.height, Math.ceil(sizer.offsetHeight)); setFormulaBox({ width, height }); // Wrapped lines grow down; past the pane bottom the box moves up so the last line stays // on screen rather than falling off the bottom edge. The Enter/Point label under the box // may hang past the pane, never past the window. const roomBelow = paneBottom - 4 - bounds.y; const dx = Math.min(0, Math.max(paneLeft + 4 - bounds.x, roomRight - width)); const dy = height <= roomBelow ? 0 : Math.min(0, Math.max(paneTop + 4 - bounds.y, roomBelow - height)); setFormulaShift((prev) => (prev && prev.dx === dx && prev.dy === dy ? prev : { dx, dy })); // The prefix ends at the caret, but the suffix stays in the same inline flow: dropping // it would measure a different wrap when the caret sits in the middle of a word. caretSizer.style.width = `${width}px`; const range = document.createRange(); range.setStart(prefix.firstChild ?? prefix, prefix.firstChild?.textContent?.length ?? 0); range.collapse(true); const rects = range.getClientRects(); const caretRect = rects[rects.length - 1]; const origin = caretSizer.getBoundingClientRect(); const lineHeight = Number.parseFloat(getComputedStyle(sizer).lineHeight); const line = caretRect ? Math.max(0, Math.floor((caretRect.top - origin.top - 1) / lineHeight)) : 0; setFormulaCaretOffset({ x: caretRect ? caretRect.left - origin.left : 8, y: 1 + (line + 1) * lineHeight, }); }; measure(); // Formula-bar growth and viewport resizing can move the canvas without a keystroke. const observer = new ResizeObserver(measure); if (canvas) observer.observe(canvas); window.addEventListener("resize", measure); return () => { observer.disconnect(); window.removeEventListener("resize", measure); }; }, [formulaEdit?.draft, formulaEdit?.caret, formulaEdit?.addr, formulaEdit?.inBand, formulaBounds?.x, formulaBounds?.y, formulaBounds?.width, formulaBounds?.height]); // ⭐ INSTRUCTION 26 — THE COLUMN LETTERS ARE CENTRED, EXCEL'S OWN CONVENTION. glide's own // `drawHeaderInner` left-aligns a plain `title` string with no alignment prop, so a custom // `drawHeader` is the only route (mechanics copied from `customer-grid/CustomerGrid.tsx`'s // own `drawGridHeader`; the drawing itself is new — that file's is icon marks, not centring). // Shared by BOTH `DataEditor` mounts below: whichever one currently owns the header row // (`headerHeight`) is the one that actually paints it, but both are wired so neither loses // the letters when the frozen band's row count changes. // // ⛔ THE ROW-MARKER COLUMN IS LEFT TO GLIDE. `rowMarkers="number"` injects its own header cell // with a blank `title` (`data-editor.js::mangledCols` sets it to `""`) and its own `rowMarker` // flag - real at runtime but not on the PUBLIC `GridColumn` this callback is typed with (it // lives on the internal-only `InnerColumnExtension`), so the empty title is the type-safe way // to tell it apart from this sheet's own lettered columns; calling glide's own default paint // for it keeps its select-all checkbox instead of centring an empty string. // // ⚠ THE SECOND ARGUMENT IS NAMED `drawDefault`, NOT `drawContent`. `verify_api.py`'s W51-T19 / // D-642 legs assert `paintCell`'s OWN two-branch `drawContent()` contract with a whole-file // `grid_code.count("drawContent()")` - a blunt substring count, not a scope-aware one - so a // third literal call under that name here would push the count to 3 and fail a leg about a // completely different callback. Same glide arg, same call, different name: nothing about the // paint changes, only the identifier that keeps this closure's default-paint call out of a // count that was never written to expect a second `drawHeader`/`drawCell`-shaped callback. const drawColumnHeader = useCallback((args, drawDefault) => { if (args.column.title === "") { drawDefault(); return; } const { ctx, rect, column, columnIndex, theme, hoverAmount } = args; const projected = selectionProjectsHeader( selection, "column", columnIndex, headerProjectionBounds, ); ctx.save(); // Glide paints `bgHeaderHasFocus` for the active cell's column before this callback, even // when the document command is a whole-row axis. Repaint every custom header's background // from the projection so a mere anchor cannot masquerade as a selected column. ctx.fillStyle = projected ? tokenColour("--lp-blue-tint", "#EDF3FD") : hoverAmount > 0 ? theme.bgHeaderHovered : theme.bgHeader; ctx.fillRect(rect.x, rect.y, rect.width, rect.height); if (projected) { ctx.strokeStyle = tokenColour("--lp-blue-deep", "#768FB6"); ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(rect.x, rect.y + rect.height - 0.5); ctx.lineTo(rect.x + rect.width, rect.y + rect.height - 0.5); ctx.stroke(); } // ⚠ `headerFontFull` is real at runtime but lives on `FullTheme`, not the public `Theme` // this callback is typed with — built from the two parts instead, same string, no cast // (same note as `CustomerGrid.tsx::drawGridHeader`). ctx.font = `${theme.headerFontStyle} ${theme.fontFamily}`; ctx.fillStyle = projected ? tokenColour("--lp-blue-deep", "#768FB6") : tokenColour("--lp-ink", "#202433"); ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText(column.title, rect.x + rect.width / 2, rect.y + rect.height / 2); ctx.restore(); }, [headerProjectionBounds, selection]); // ══════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W51-T34 — ONE PAINT, TWO GRIDS, AND SHARING IT IS NOT A TIDY. // // ⛔⛔ THE FROZEN BAND IS A SECOND `DataEditor`, and a second `drawCell` written beside this // one would be a second answer to D-642. That defect was NOT a state bug: glide 6.0.3 declares // `DrawCellCallback = (args, drawContent) => void`, so the RETURN IS IGNORED and nothing paints // a cell's text unless `drawContent()` is CALLED. A band grid handed a one-argument callback // would paint every corner mark and NO value, on the rows a person froze precisely because // they are the ones worth keeping in sight. So the callback is written ONCE, here, and the // band grid is handed this same function with its row said in the main grid's terms. // ══════════════════════════════════════════════════════════════════════════════════════════ const paintCell = useCallback((args, drawContent) => { // ═══════════════════════════════════════════════════════════════════════════════ // ⛔⛔ D-642, AND THE CAUSE WAS A LIBRARY CONTRACT NOBODY HAD READ. // // glide 6.0.3 declares `DrawCellCallback = (args, drawContent: () => void) => void`. // TWO things follow, and W50-T19 got both backwards: // 1. THE RETURN TYPE IS `void`. A returned boolean is IGNORED. The comment that // said "`false` means glide's own text renderer still runs, and it runs AFTER // this" describes a contract this version does not have. // 2. THE DEFAULT RENDERER IS THE SECOND ARGUMENT. Nothing paints a cell's text // unless `drawContent()` is CALLED. // So every cell fell to this callback, which painted its corner mark and returned a // boolean into the void: the mark appeared and the VALUE NEVER DID. That is exactly // instruction 9 ("typing into a cell registers in the formula rail but the cell does // not display the value") and D-642, and it was never a state bug - `setLiteral` // writes `display`, `getCellContent` returns it, and glide's own clipboard hands back // `4321` for a cell that paints blank. // // ⭐ THE ORDER IS THE OTHER HALF. In the unstyled branch `drawContent()` runs FIRST // so the mark lands ON TOP of the text; in the styled branch it is never called, // because that branch owns the whole paint and calling it would double-paint the // smear W50-T19 correctly warned about. // ═══════════════════════════════════════════════════════════════════════════════ const { ctx, rect, col, row } = args; // Record where this canvas was actually drawn, not where a scroll event wants it to go. // Main and frozen-band canvases advance independently. Even an unbordered cell can be the // only new draw after a blit, so update the origin before checking for borders. const rowLayout = borderRowLayout.current!; const rowIndex = row + bandRows; while (rowLayout.offsets.length <= rowIndex) { const index = rowLayout.offsets.length - 1; rowLayout.offsets.push(rowLayout.offsets[index] + rowLayout.heightAt(index)); } const transform = ctx.getTransform(); const viewport = borderPaintViewports.current.get(ctx) ?? { x: 0, y: 0, transform }; if (col >= frozenCols) viewport.x = rect.x - columnX(col); viewport.y = rect.y - (rowLayout.offsets[rowIndex] - (row < 0 ? 0 : rowLayout.offsets[bandRows])); viewport.transform = transform; borderPaintViewports.current.set(ctx, viewport); // Glide supplies the resolved fill at runtime but omits it from DrawCellCallback's public // type. Keep the theme fallback for that narrower declaration and for test doubles. const cellFillColor = (args as typeof args & { cellFillColor?: string }).cellFillColor ?? args.theme.bgCell; const cell = cells[addrAt(col, row)] ?? null; const filterHeader = sheetFilter !== null && realRow(row) === sheetFilter.headerRow && realCol(col) >= sheetFilter.col0 && realCol(col) <= sheetFilter.col1; const paintFilterButton = () => { if (!filterHeader) return; const size = Math.min(20 * zoom, rect.height - 4, rect.width - 4); if (size < 4) return; const x = rect.x + rect.width - size - 2; const y = rect.y + (rect.height - size) / 2; const active = sheetFilter.values[realCol(col)] !== undefined; ctx.save(); ctx.fillStyle = tokenColour(active ? "--lp-blue-tint" : "--lp-surface-2", args.theme.bgCell); ctx.strokeStyle = tokenColour(active ? "--lp-blue-deep" : "--lp-line", args.theme.borderColor); ctx.lineWidth = 1; ctx.beginPath(); ctx.roundRect(x, y, size, size, Math.min(3, size / 4)); ctx.fill(); ctx.stroke(); ctx.strokeStyle = tokenColour(active ? "--lp-blue-deep" : "--lp-muted", args.theme.textDark); ctx.lineWidth = Math.max(1, zoom); ctx.lineJoin = "round"; ctx.beginPath(); ctx.moveTo(x + size * .22, y + size * .28); ctx.lineTo(x + size * .78, y + size * .28); ctx.lineTo(x + size * .57, y + size * .52); ctx.lineTo(x + size * .57, y + size * .78); ctx.lineTo(x + size * .43, y + size * .69); ctx.lineTo(x + size * .43, y + size * .52); ctx.closePath(); ctx.stroke(); ctx.restore(); }; // S65-T06: Glide clips shared boundaries during damage paints. Restore them on the same // canvas after that clip is released, ahead of the spill mask. Include the touching edge // of each neighbour: repainting an UNBORDERED cell must not erase its neighbour's border. // Only adjacent projected cells participate; hidden columns use addrAt's existing projection. const ownBorder = cell?.style?.border; const borderAt = (c: number, r: number) => c >= 0 && c < columns.length && r >= -bandRows && r < visRows.length ? cells[addrAt(c, r)]?.style?.border : undefined; const border = { left: ownBorder?.left || borderAt(col - 1, row)?.right, right: ownBorder?.right || borderAt(col + 1, row)?.left, top: ownBorder?.top || borderAt(col, row - 1)?.bottom, bottom: ownBorder?.bottom || borderAt(col, row + 1)?.top, }; if (border.left || border.right || border.top || border.bottom) { // Glide reuses its rect object for later cells in the same draw. Snapshot its values, // never the mutable object, for this one pending frame. const borderRect = { ...rect }; const originX = viewport.x; const originY = viewport.y; // S66-T03: the freeze divider's own pixel column belongs to glide's divider line. Glide // repaints that line on later draws, so a repair that also painted it made the divider's // crossing black after a scrollbar move and grey after arrow keys; the scrolling pane now // starts one pixel right of it, so both paths show the same divider. const paneLeft = col < frozenCols ? ROW_MARKER_WIDTH : columnX(frozenCols) + (frozenCols > 0 ? 1 : 0); const paneTop = row < 0 || bandRows === 0 ? HEADER_HEIGHT : 0; queueSpillPaint(`border:${row}:${col}`, () => { // A newer draw replaces the same key. A cell merely blitted by a later scroll still // needs its repair, translated to that draw's origin; off-pane strips are clipped away. const latest = borderPaintViewports.current.get(ctx); if (!latest) return; const currentRect = { ...borderRect, x: borderRect.x + (col < frozenCols ? 0 : latest.x - originX), y: borderRect.y + latest.y - originY }; // S67-T05 / D-3280: the frozen side stops AT the divider too, so neither pane's late // paint ever owns the divider's pixel column and every scroll path shows glide's line. const paneRight = col < frozenCols ? columnX(frozenCols) : ctx.canvas.width / latest.transform.a; const paneBottom = ctx.canvas.height / latest.transform.d; if (currentRect.x + currentRect.width < paneLeft || currentRect.x >= paneRight || currentRect.y + currentRect.height < paneTop || currentRect.y >= paneBottom) return; ctx.save(); ctx.setTransform(latest.transform); ctx.beginPath(); ctx.rect(paneLeft, paneTop, Math.max(0, paneRight - paneLeft), Math.max(0, paneBottom - paneTop)); ctx.clip(); paintCellBorders(ctx, currentRect, border); ctx.restore(); }, true); } // Sparkline marks are painted in each value branch below, after the resolved fill and // borders. Text and selection overlays still finish the cell, including no-text plots. // ═══════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W51-T18 — THE RULE IS ASKED BEFORE THE EARLY RETURN, AND THAT IS THE HALF // THAT GETS MISSED. `is empty` is one of C2's ten operators, so a rule over // `B2:D40` is asked about addresses with NO cell record at all: a blank cell is not // an address the engine may skip, it is the exact case that operator exists for. // Returning here on `!cell` would leave "highlight the gaps" painting nothing, with // the rule visibly present in the dialog. // // ⛔ THE COORDINATES ARE TRANSLATED. A rule's `range` is in the SHEET's own // coordinates and glide's `col` and `row` are positions among the VISIBLE ones, so // hiding a column would move every rule one column left with no error at all. // // ⛔ AND THE STYLE IS COMPUTED, NEVER STORED. `overlayRuleStyle` lays the rule's // fill, ink and weight over the cell's OWN style for this paint only; nothing is // written to the document, which is what keeps a rule editable and reversible. // ═══════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W61-T05 / THE COMBINE — A FORMULA RULE IS EVALUATED AGAINST A CONTEXT, AND THIS IS // WHERE IT GETS ONE. `formula` joined `cell` and the range kinds as a rule kind in lane A; // `rules.ts::ruleApplies` hands `matchesRule` the context and `ruleOwns` stamps this address // onto it, so a condition like `=B2>AVERAGE($B$2:$B$40)` can read the sheet it is painting. // Without it the context is `null`, `matchesRule` cannot resolve a reference, and a formula // rule SAVES, RELOADS and DECIDES correctly while painting nothing at all — which is exactly // the shape of a bug nobody finds, because every surface except the pixels says it works. // ⚠ BOTH DOORS, NOT ONE. `ruleStyleAt` and `ruleBarAt` walk the same first-match list, so a // context passed to only one of them would let a formula rule win the fill and lose the bar. const ruleStyle = ruleStyleAt(rules, realCol(col), realRow(row), ruleSubject(cell), { get: cellValueGetter, sheet: tab.name }); // ⭐⭐ W54-T05 — THE DATA BAR IS ASKED SEPARATELY BECAUSE A PROPORTION IS NOT A STYLE. // `RuleStyle` can say a fill, an ink and a weight; it cannot say "three fifths of the way // across this cell". Both questions walk the SAME first-match list inside `rules.ts`, so the // bar and the fill can never come from two different rules, and a bar rule answers the style // door with an empty style: it claims the cell against the rules below it without filling it. const ruleBar = ruleBarAt(rules, realCol(col), realRow(row), ruleSubject(cell), { get: cellValueGetter, sheet: tab.name }); // ⭐⭐ W52-T06 / CR-1, CR-5, CR-10, PM-6 — THE COLOURED REFERENCE BORDER. Read BEFORE the // `!cell` early return, for the same reason `ruleStyle` is (W51-T18's own note two lines up): // a formula can reference a perfectly BLANK cell, and that cell still has to wear the border, // not be treated as nothing to paint. // // ⭐⭐ W53-T02 / INSTRUCTION 18 — ONE BORDER, TWO WEIGHTS OF CERTAINTY. A settled reference // keeps Microsoft's own "border with square corners" (solid), whether the formula is being // edited or merely selected; the cell the arrow keys are still moving over is DASHED in that // same reference's slot colour, which is the state instruction 18 describes. The colour is // what tells it apart from the copy marquee's own dash further down. const refKey = `${realCol(col) + 1},${realRow(row) + 1}`; const refEntry = formulaRefCells.get(refKey); const refProposed = formulaPointCells.has(refKey); const paintRefBorder = () => { if (!refEntry) return; const sameRef = (dc: number, dr: number) => formulaRefCells.get(`${realCol(col) + 1 + dc},${realRow(row) + 1 + dr}`)?.ref === refEntry.ref; ctx.save(); ctx.strokeStyle = refEntry.color; ctx.lineWidth = 2; if (refProposed) ctx.setLineDash([4, 3]); ctx.beginPath(); if (!sameRef(-1, 0)) { ctx.moveTo(rect.x + 1, rect.y); ctx.lineTo(rect.x + 1, rect.y + rect.height); } if (!sameRef(1, 0)) { ctx.moveTo(rect.x + rect.width - 1, rect.y); ctx.lineTo(rect.x + rect.width - 1, rect.y + rect.height); } if (!sameRef(0, -1)) { ctx.moveTo(rect.x, rect.y + 1); ctx.lineTo(rect.x + rect.width, rect.y + 1); } if (!sameRef(0, 1)) { ctx.moveTo(rect.x, rect.y + rect.height - 1); ctx.lineTo(rect.x + rect.width, rect.y + rect.height - 1); } ctx.stroke(); ctx.setLineDash([]); ctx.restore(); }; // ═══════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W52-T07 — THE COPY MARQUEE AND THE PASTE HIGHLIGHT, ONE MORE CONCERN THIS SAME // CALLBACK PAINTS. Same shape as `paintMark` two closures below (one function, two // independent visual facts) and called from the SAME three exit branches as // `paintRefBorder`, for the same reason: a copied or just-pasted BLANK cell still has // to wear its rectangle, so this is read before the `!cell` early return too. // // ⭐ DASHED for the copy source (Excel's own "marching ants" convention, held static — // a per-frame animated offset is not worth a canvas repaint loop for what a static // dashed border already communicates), SOLID tinted fill for the paste destination, so // the two moments never read as the same event. // ═══════════════════════════════════════════════════════════════════════════════ const realC = realCol(col); const realR = realRow(row); const inMarqueeRange = (r: { col: number; row: number; cols: number; rows: number } | null) => !!r && realC >= r.col && realC < r.col + r.cols && realR >= r.row && realR < r.row + r.rows; const paintMarquee = () => { if (inMarqueeRange(copyMarquee)) { ctx.save(); ctx.strokeStyle = tokenColour("--lp-blue-deep", "#768fb6"); ctx.lineWidth = 1.5; ctx.setLineDash([4, 3]); ctx.strokeRect(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2); ctx.setLineDash([]); ctx.restore(); } if (inMarqueeRange(pasteHighlight)) { ctx.save(); ctx.globalAlpha = 0.65; ctx.fillStyle = tokenColour("--lp-green-tint", "#ebf6ef"); ctx.fillRect(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2); ctx.globalAlpha = 1; ctx.strokeStyle = tokenColour("--lp-green-deep", "#35754e"); ctx.lineWidth = 1; ctx.strokeRect(rect.x + 0.5, rect.y + 0.5, rect.width - 1, rect.height - 1); ctx.restore(); } }; /** * ⭐⭐ W53-T01 / R2 / INSTRUCTION 19 — THE ONE CELL THAT IS STILL WAITING SAYS SO ITSELF. * A soft band crosses a database-bound cell that has not resolved yet, and nothing else on * the sheet moves: the formulas next to it already have their numbers. * * ⛔ SLICES RATHER THAN A CANVAS GRADIENT, and that is a colour rule and not a graphics * preference. A gradient stop needs a colour WITH an alpha channel, which would mean writing * an `rgba()` literal here; every colour in this file comes from a `--lp-*` token through * `tokenColour` (DESIGN.md), so the softness is made with `globalAlpha` instead. */ const paintShimmer = () => { if (!boundWaiting(cell)) return; const bandWidth = Math.max(24, rect.width * 0.5); const head = rect.x - bandWidth + (rect.width + bandWidth) * shimmerPhase.current; const slices = 8; const slice = bandWidth / slices; ctx.save(); ctx.beginPath(); ctx.rect(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2); ctx.clip(); ctx.fillStyle = tokenColour("--lp-blue-tint", "#edf3fd"); for (let i = 0; i < slices; i += 1) { ctx.globalAlpha = 0.55 * Math.sin((Math.PI * (i + 0.5)) / slices); ctx.fillRect(head + slice * i, rect.y + 1, slice + 1, rect.height - 2); } ctx.globalAlpha = 1; ctx.restore(); }; // Each damaged cell repaints only its own slice. The owner's box controls layout, // never the clip, so a later neighbour paint cannot erase or strand spilled glyphs. const textStyleAt = (ownerCol: number, ownerCell: Cell): CellStyle => { const ownerRule = ownerCol === col ? ruleStyle : ruleStyleAt(rules, realCol(ownerCol), realRow(row), ruleSubject(ownerCell), { get: cellValueGetter, sheet: tab.name }); return ownerRule ? overlayRuleStyle(ownerCell.style, ownerRule) : ownerCell.style ?? {}; }; const measureSpill: SpillMeasure = (text, ownerCell, ownerCol) => { const ownerStyle = textStyleAt(ownerCol, ownerCell); const size = (typeof ownerStyle.size === "number" ? fontPx(ownerStyle.size) : SIZE_PX[ownerStyle.size ?? "m"] ?? SIZE_PX.m) * zoom; ctx.save(); ctx.font = `${ownerStyle.italic ? "italic " : ""}${ownerStyle.bold ? "600 " : ""}${size}px ${fontStack(ownerStyle.font, lightTheme.fontFamily)}`; const width = ctx.measureText(text).width / zoom; ctx.restore(); return width; }; const spill = spillOwnerAt( cells, addrAt, spillWidths, frozenCols, col, row, measureSpill, blocksSpill, ); const spills = !spill && cellSpillsAt( cells, addrAt, spillWidths, frozenCols, col, row, measureSpill, blocksSpill, ); const paintTextSpill = (): boolean => { if (filterHeader) return false; const ownerCell = spill?.ownerCell ?? cell; if ((!spill && !spills) || !ownerCell) return false; const ownerCol = spill?.ownerCol ?? col; let x = rect.x; for (let c = ownerCol; c < col; c += 1) x -= columns[c].width; for (let c = col; c < ownerCol; c += 1) x += columns[c].width; const ownerBox = { ...rect, x, width: columns[ownerCol].width }; const ownerStyle = textStyleAt(ownerCol, ownerCell); const sameOwnerAt = (candidate: number) => candidate === ownerCol || (candidate >= 0 && candidate < columns.length && spillOwnerAt(cells, addrAt, spillWidths, frozenCols, candidate, row, measureSpill, blocksSpill)?.ownerCol === ownerCol); let first = ownerCol; let last = ownerCol; while (sameOwnerAt(first - 1)) first -= 1; while (sameOwnerAt(last + 1)) last += 1; let runLeft = ownerBox.x; let runRight = ownerBox.x + ownerBox.width; for (let c = first; c < ownerCol; c += 1) runLeft -= columns[c].width; for (let c = ownerCol + 1; c <= last; c += 1) runRight += columns[c].width; const band = spillTextBand(ownerBox, ownerStyle, zoom); // Glide reuses its Rectangle object for the next cell. Copy these scalars before the // deferred paint or the run clips against whichever cell happened to paint last. const rowTop = rect.y; const rowHeight = rect.height; // Hotfix 2026-09-24 (owner: "weeks left to end of year" in small font floating in the sheet, // "it keeps appearing when i zoom in zoom out"). Glide scales the canvas by the device pixel // ratio only between its own save and restore, so a paint run a frame later drew in the // UNSCALED space: at any browser zoom but 100% the run landed shrunk and offset, a ghost of // the label. The border paint above already carries the transform; this run now does too. const spillTransform = ctx.getTransform(); // S67-T05 (QI8, ERROR 27): the run is painted a FRAME LATER, and a wheel scroll in that // frame moves the canvas under it; painted at the draw-time x it landed over the frozen // columns and stayed there. It now follows the viewport glide last drew at, exactly like the // border repair above, and clips to its owner's pane, so a label spilling left out of the // scrolling pane stops at the freeze divider instead of writing over A:E. const spillOriginX = viewport.x; const spillOriginY = viewport.y; const ownerFrozen = ownerCol < frozenCols; const spillPaneLeft = ownerFrozen ? ROW_MARKER_WIDTH : columnX(frozenCols) + (frozenCols > 0 ? 1 : 0); // Glide paints gridlines after drawCell. Deduplicate every participating cell into one // owner run, then mask only its interior separators and redraw the text in the next frame. queueSpillPaint(`${row}:${ownerCol}`, () => { const latest = borderPaintViewports.current.get(ctx); const dx = latest && !ownerFrozen ? latest.x - spillOriginX : 0; const dy = latest ? latest.y - spillOriginY : 0; const transform = latest?.transform ?? spillTransform; const spillPaneRight = ownerFrozen ? columnX(frozenCols) : ctx.canvas.width / transform.a; const left = Math.max(runLeft + dx + 1, spillPaneLeft); const right = Math.min(runRight + dx - 1, spillPaneRight); if (right <= left) return; ctx.save(); ctx.setTransform(transform); // The scroll since the draw, applied once; the clip is the pane-bounded run. ctx.translate(dx, dy); ctx.beginPath(); ctx.rect(left - dx, rowTop + 1, right - left, rowHeight - 2); ctx.clip(); ctx.fillStyle = cellFillColor; let separatorX = runLeft; for (let c = first; c < last; c += 1) { separatorX += columns[c].width; ctx.fillRect(Math.floor(separatorX - 1), band.top, 3, Math.max(0, band.bottom - band.top)); } drawCellTextRun(ctx, ownerBox, ownerCell, ownerStyle, zoom); ctx.restore(); }); return true; }; // ⭐⭐ W62-T02 — THE SPILL FOR AN EMPTY CELL, AND IT IS A SEPARATE STATEMENT ABOVE THE EXIT // RATHER THAN A LINE INSIDE IT. `verify_grid_ux.py`'s [COPY PASTE MARQUEE] family (W52-T07) // pins the exit below BYTE FOR BYTE, because the whole of that ticket was a blank cell inside // a copied block still wearing its marquee. Reformatting it to make room here reds a family // belonging to another ticket for a line that changed no pixel, which is exactly the trap // this file's own D-642 note describes one screen up. // // ⚠ SO THE ORDER IS SPILL FIRST, DEFAULT RENDERER SECOND, AND IT IS SAFE FOR A STATED REASON // rather than by luck: glide's `drawTextCell` returns without touching the canvas when its // data is the empty string, which is every cell reaching this branch. The cell BACKGROUND is // painted by glide before `drawCell` is called at all, so nothing here can erase the run. if (!cell && !ruleStyle) paintFilterButton(); if (!cell && !ruleStyle) paintTextSpill(); if (!cell && !ruleStyle) { drawContent(); paintRefBorder(); paintMarquee(); return; } const mark = cell ? MARK_STYLE[markOf(cell)] : undefined; const viewHeader = viewHeaderAt(cells, addrAt(col, row)); const caret = validationOf(cell) !== null || viewHeader !== null; const paintMark = () => { // ⭐ W51-T18: THE DROPDOWN'S CARET RIDES HERE, so it is drawn in BOTH branches for // the same reason R19's corner mark is: a validated cell that also carries a bold // would silently lose its only affordance and read as an ordinary cell. if (caret) { ctx.save(); if (viewHeader) { ctx.fillStyle = style?.fill ? tokenColour(style.fill, args.theme.bgCell) : args.theme.bgCell; ctx.fillRect(rect.x + rect.width - 24 * zoom, rect.y + 9 * zoom, 23 * zoom, Math.max(0, rect.height - 10 * zoom)); } ctx.strokeStyle = tokenColour("--lp-muted", "#6b7280"); ctx.lineWidth = 1.4; ctx.lineCap = "round"; const cx = rect.x + rect.width - 11 * (viewHeader ? zoom : 1); const cy = rect.y + rect.height / 2 - 1; ctx.beginPath(); ctx.moveTo(cx - 3.5, cy); ctx.lineTo(cx, cy + 3.5); ctx.lineTo(cx + 3.5, cy); ctx.stroke(); ctx.restore(); } if (!mark) return; ctx.save(); ctx.fillStyle = tokenColour(mark.fill, "#1F4E78"); if (mark.corner === "tri") { ctx.beginPath(); ctx.moveTo(rect.x + rect.width - 7, rect.y + 1); ctx.lineTo(rect.x + rect.width - 1, rect.y + 1); ctx.lineTo(rect.x + rect.width - 1, rect.y + 7); ctx.closePath(); ctx.fill(); } else if (mark.corner === "dot") { ctx.beginPath(); ctx.arc(rect.x + rect.width - 5, rect.y + 5, 2.2, 0, Math.PI * 2); ctx.fill(); } else { ctx.fillRect(rect.x + 1, rect.y + 1, 2.5, rect.height - 2); } ctx.restore(); }; // ⛔ W51-T18: A CELL WITH NO OWN STYLE BUT A MATCHING RULE MUST TAKE THE STYLED // BRANCH. `stylePaints` answers about the cell's own style alone, so leaving the // condition as it was would compute a rule's fill and then hand the cell straight // back to glide, which knows nothing about it: the dialog would list a rule that // paints nothing. The `|| ruleStyle` is that whole bug, in two words. const baseStyle = ruleStyle ? overlayRuleStyle(cell?.style, ruleStyle) : cell?.style; // Give even an unstyled refusal the shared text routine and the cell's own spacing. const style = bindingRefusal(cell) ? { ...baseStyle, color: "--lp-red-deep" } : baseStyle; if ((!stylePaints(style) && !ruleStyle) || !style) { if (cell) drawSparkline(ctx, rect, cell, cells, zoom); // ⭐ `drawContent()` IS the default renderer, and it must run BEFORE the mark so // the mark sits on top of the value rather than under it. if (!paintTextSpill()) drawContent(); // ⭐ W54-T14 / LANE B — the link underline and the note corner, in BOTH branches for the // same reason R19's own mark is in both: an attachment on a bold cell would otherwise // vanish, and a cell that shows nothing of what it carries carries it invisibly. paintFilterButton(); paintCellMarks(ctx, rect, cell); paintCellLimitMark(ctx, rect, cell, zoom); paintShimmer(); paintMark(); paintRefBorder(); paintMarquee(); return; } ctx.save(); // 1. S64-T18 / owner instruction 9: inset the fill so visible gridlines survive. // With gridlines hidden, that inset cuts between adjacent fills; paint the exact cell rect. if (style.fill) { ctx.fillStyle = tokenColour(style.fill, "#ffffff"); if (gridlinesVisible) { ctx.fillRect(rect.x + 1, rect.y + 1, rect.width - 1, rect.height - 1); } else { ctx.fillRect(rect.x, rect.y, rect.width, rect.height); } } // 1b. THE DATA BAR, AFTER THE BACKGROUND AND BEFORE THE TEXT CLIP, which is the whole of the // ordering decision: painted later it would cover the number it measures, and painted // inside the clip it would be cut by the text box rather than by the cell. The fraction // is already clamped to 0..1 by the engine; the extra guard here is against a width of // zero, which some canvas implementations still stroke as a hairline. if (ruleBar && ruleBar.fraction > 0) { const barWidth = Math.max(1, Math.round((rect.width - 2) * ruleBar.fraction)); ctx.save(); ctx.fillStyle = tokenColour(ruleBar.fill, "#dbeafe"); ctx.fillRect(rect.x + 1, rect.y + 2, barWidth, rect.height - 3); ctx.restore(); } // 2. THE EXPLICIT BORDER, before the spill's post-line mask. A crossed interior segment may // be covered only inside the text band; unrelated segments and every outer edge survive. paintCellBorders(ctx, rect, style.border); if (cell) drawSparkline(ctx, rect, cell, cells, zoom); // 3. THE TEXT. Spill owns its expanded, separator-reaching clip; an ordinary run retains the // old inset clip. Clipping before asking the spill would also clip away its line mask. if (!paintTextSpill()) { ctx.beginPath(); ctx.rect(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2); ctx.clip(); drawCellTextRun(ctx, rect, cell, style, zoom); } ctx.restore(); // 4. W54-T14 / LANE B — the attachment marks, this branch's half of the pair above. paintCellMarks(ctx, rect, cell); paintCellLimitMark(ctx, rect, cell, zoom); paintShimmer(); paintMark(); paintRefBorder(); paintMarquee(); paintFilterButton(); // ⚠ W51-T34: THE BOOLEAN STAYS, AND IT IS DELIBERATE RATHER THAN LEFTOVER. glide 6.0.3 // IGNORES it (D-642 above says so in full), so it changes no behaviour; what it still does // is mark, in the code, WHICH branch owns its whole paint, and `verify_api.py`'s W50-T19 // leg reads it as exactly that. Deleting it as dead reds a gate in another ticket's // territory for a line that was never wrong, only no longer load bearing. return true; // ⛔ New dependencies stay in the suffix. `verify_grid_ux.py` 13468's // W62-T02 claim matches `frozenCols, pasteHighlight` as ADJACENT TEXT, so putting this // entry in alphabetical order between them reds a leg that owns the spill paint. React // does not care what order a dependency array is in; that gate does. }, [addrAt, blocksSpill, cellValueGetter, cells, columns, copyMarquee, formulaPointCells, formulaRefCells, frozenCols, pasteHighlight, queueSpillPaint, realCol, realRow, rules, spillWidths, tab.name, zoom, gridlinesVisible, bandRows, columnX, HEADER_HEIGHT, ROW_MARKER_WIDTH, visRows.length, sheetFilter]); /** * ⭐ THE BAND'S PAINT: the SAME callback, told which row it is looking at. `fromBand` is not * used here because glide hands a draw argument rather than an `Item`, and rebuilding the whole * record would drop the fields the renderer needs; only the row moves. */ const paintFrozenCell = useCallback( (args, drawContent) => paintCell({ ...args, row: args.row - bandRows }, drawContent), [bandRows, paintCell], ); // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W54-T06 — A WRAPPED ROW GETS TALLER, AND ITS HEIGHT IS DERIVED RATHER THAN STORED. // // ⛔⛔ NOTHING NEW IS WRITTEN TO THE DOCUMENT, AND THAT IS THE DESIGN RATHER THAN A SHORTCUT. // A row's needed height is a pure function of facts the tab ALREADY persists: which cells wrap, // what they say, the face and size they say it in, and how wide their column is. Imported // `rowHeights` remain authoritative below; otherwise the height falls out of the stored `wrap` // flag on the next render without a second writer of geometry. // // ⭐ THE MEASUREMENT IS THE PAINT'S OWN. Same `wrapIntoLines`, same font string built from the // same `fontPx` / `fontStack` / `SIZE_PX` the styled branch uses, same padding, same 1.35 line // height. A row sized in Inter cannot then be painted in Georgia. // // ⚠ KEYED BY THE SHEET'S ROW, NOT THE VIEW'S, so hiding a row or a column moves nothing: the // lookup below translates through `realRow`, exactly as `addrAt` does. // ═══════════════════════════════════════════════════════════════════════════════════════════ const wrapHeights = useMemo(() => { const out = new Map(); const ctx = measureContext(); if (!ctx) return out; // ⛔ A HIDDEN COLUMN CONTRIBUTES NOTHING. `columns` is the VISIBLE table, so a wrapped cell // in a column nobody can see has no width to wrap against and no say in the row's height. const widthOf = new Map(); // Wrapping is measured at document size; the row-height readers apply zoom once below. for (const column of columns) widthOf.set(Number(column.id), column.width / zoom); for (const [addr, cell] of Object.entries(cells)) { const style = cell?.style; if (!style?.wrap) continue; const at = splitAddress(addr); if (!at) continue; const width = widthOf.get(at.col - 1); if (width === undefined) continue; const text = formatCellText(cell, displayText(cell)); if (!text) continue; const size = typeof style.size === "number" ? fontPx(style.size) : SIZE_PX[style.size ?? "m"] ?? SIZE_PX.m; const weight = style.bold ? "600 " : ""; const slant = style.italic ? "italic " : ""; ctx.font = `${slant}${weight}${size}px ${fontStack(style.font, lightTheme.fontFamily)}`; const pad = 8 + Math.max(0, Math.min(MAX_CELL_INDENT, style.indent ?? 0)) * 8; const count = wrapIntoLines(ctx, text, width - pad - 8).length; // The 8 is the paint's own top and bottom inset (4 each), which is what `valign` top and // bottom measure from, so a row is exactly as tall as the block plus the room it sits in. const needed = Math.min(MAX_ROW_HEIGHT, count * Math.round(size * 1.35) + 8); const row = at.row - 1; out.set(row, Math.max(out.get(row) ?? 0, needed)); } return out; }, [cells, columns, zoom]); /** * ⭐⭐ THE HEIGHT GLIDE IS HANDED, AS A FUNCTION OF THE DOCUMENT ROW. `DataEditor` takes * `number | ((index: number) => number)`, so this is a supported shape rather than a trick. * An imported per-row dimension is exact at 100% zoom and wins over both compact defaults and * wrapping. Rows without one retain the sheet-wide base and derived wrap growth. */ const documentRowHeight = useCallback((real: number) => { const imported = tab.rowHeights?.[String(real + 1)]; return typeof imported === "number" && Number.isFinite(imported) && imported > 0 ? imported : Math.max(rowHeight, wrapHeights.get(real) ?? 0); }, [rowHeight, tab.rowHeights, wrapHeights]); const rowHeightAt = useCallback( (index: number) => Math.round(documentRowHeight(realRow(index)) * zoom), [documentRowHeight, realRow, zoom], ); const allRowHeightAt = useCallback( (index: number) => Math.round(documentRowHeight(allVisRows[index]) * zoom), [allVisRows, documentRowHeight, zoom], ); // Extend only as far as Glide draws; do not scan a large sheet on every arrow press. borderRowLayout.current = useMemo(() => ({ offsets: [0], heightAt: allRowHeightAt }), [allRowHeightAt]); const frozenRowHeightAt = useCallback( (index: number) => Math.round(documentRowHeight(headRows[index]) * zoom), [documentRowHeight, headRows, zoom], ); const frozenBandHeight = headRows.reduce((height, _, index) => height + frozenRowHeightAt(index), 0); const outlineItems = useMemo(() => rowOutlineItems(rowGroups, allVisRows), [rowGroups, allVisRows]); const outlineOffsets = useMemo(() => { const offsets = [0]; for (let index = 0; rowGroups.length > 0 && index < allVisRows.length; index++) offsets.push(offsets[index] + allRowHeightAt(index)); return offsets; }, [allVisRows, allRowHeightAt, rowGroups.length]); const outlineTop = (index: number) => HEADER_HEIGHT + outlineOffsets[index] - (index < bandRows ? 0 : (outlineOffsets[Math.min(allVisRows.length, bandRows + chartViewport.y)] - outlineOffsets[bandRows] - chartViewport.ty)); const outlinePaint = outlineItems.map(item => ({ ...item, top: outlineTop(item.index) + Math.max(0, (allRowHeightAt(item.index) - 24) / 2), bottom: outlineTop(item.last) + allRowHeightAt(item.last), })).filter(item => item.top >= (item.index < bandRows ? HEADER_HEIGHT : HEADER_HEIGHT + frozenBandHeight)); const outlineLevels = rowGroups.length ? Math.max(1, ...outlineItems.map(item => item.level + 1)) : 0; // Match SheetChartLayer's scroll offsets and frozen-pane clipping. Page starts already use // document pixels, so only zoom and the shared viewport projection belong in this layer. const pageScrollY = useMemo(() => allVisRows.slice(bandRows, bandRows + chartViewport.y) .reduce((offset, _, index) => offset + allRowHeightAt(bandRows + index), -chartViewport.ty), [allVisRows, bandRows, chartViewport.y, chartViewport.ty, allRowHeightAt]); const pageProjections = pageGrid ? chartPaneProjections({ left: columnX(0), top: HEADER_HEIGHT }, { ...pageOverlaySize, markerWidth: columnX(0), headerHeight: HEADER_HEIGHT, frozenWidth: columnX(frozenCols) - columnX(0), frozenHeight: frozenBandHeight, scrollX: lockstepScrollX(columns.map(column => column.width), frozenCols, chartViewport.x, chartViewport.tx), scrollY: pageScrollY, }) : []; // Search each pane's current bounds. Scrolled cells can lie underneath the frozen columns. const formulaCellAtPointer = useCallback((x: number, y: number): RealCell | null => { const canvas = wrapRef.current?.querySelector(".sheet-grid-canvas"); const area = canvas?.getBoundingClientRect(); if (!area || x < area.left + ROW_MARKER_WIDTH || x >= area.right || y < area.top + HEADER_HEIGHT || y >= area.bottom) return null; const band = frozenBandRef.current?.getBoundingClientRect(); const inFrozenRows = bandRows > 0 && !!band && y < band.bottom; const grid = (inFrozenRows ? bandGridRef : gridRef).current; if (!grid) return null; // Glide walks variable row heights in getBounds. Keep every lookup near the visible rows. const rowStart = inFrozenRows ? 0 : Math.max(0, chartViewport.y - 1); const visibleRows = Math.ceil(area.height / Math.max(1, Math.floor(MIN_ROW_HEIGHT * zoom))) + 2; const probeCol = Math.min(visCols.length - 1, Math.max(frozenCols, chartViewport.x)); const frozenEdge = frozenCols > 0 ? grid.getBounds(frozenCols - 1, rowStart) : undefined; const inFrozenCols = !!frozenEdge && x < frozenEdge.x + frozenEdge.width; const find = (start: number, end: number, position: number, axis: "x" | "y") => { while (start < end) { const mid = Math.floor((start + end) / 2); const rect = grid.getBounds(axis === "x" ? mid : probeCol, axis === "y" ? mid : rowStart); if (!rect) return -1; const size = axis === "x" ? rect.width : rect.height; if (position < rect[axis]) end = mid; else if (position >= rect[axis] + size) start = mid + 1; else return mid; } return -1; }; const col = find(inFrozenCols ? 0 : frozenCols, inFrozenCols ? frozenCols : visCols.length, x, "x"); const row = find(rowStart, Math.min(inFrozenRows ? bandRows : visRows.length, rowStart + visibleRows), y, "y"); if (col < 0 || row < 0) return null; return { col: realCol(col) + 1, row: realRow(inFrozenRows ? row - bandRows : row) + 1 }; }, [bandRows, chartViewport.x, chartViewport.y, frozenCols, HEADER_HEIGHT, ROW_MARKER_WIDTH, realCol, realRow, visCols.length, visRows.length, zoom]); const onFormulaPointerDown = useCallback((event: ReactPointerEvent): boolean => { if (!formulaEdit || event.button !== 0 || !event.isPrimary || !(event.target instanceof Element) || !event.target.closest("canvas, .dvn-scroller") || !formulaEdit.draft.startsWith("=") || (formulaEdit.mode !== "point" && !isRefPosition(formulaEdit.draft, formulaEdit.caret))) return false; const target = formulaCellAtPointer(event.clientX, event.clientY); if (!target) return false; event.preventDefault(); event.stopPropagation(); formulaPointer.current = { pointerId: event.pointerId, anchor: target, last: target, scope: renderedWorkbookKey, }; event.currentTarget.setPointerCapture(event.pointerId); proposeCell(target, false); formulaInputRef.current?.focus(); return true; }, [formulaCellAtPointer, formulaEdit, proposeCell, renderedWorkbookKey]); const onFormulaPointerMove = useCallback((event: ReactPointerEvent): boolean => { const drag = formulaPointer.current; if (!drag || drag.pointerId !== event.pointerId || drag.scope !== renderedWorkbookKey || !formulaEdit) return false; event.preventDefault(); event.stopPropagation(); const target = formulaCellAtPointer(event.clientX, event.clientY); if (target && (target.col !== drag.last.col || target.row !== drag.last.row)) { drag.last = target; proposeCell(target, true, undefined, drag.anchor); } formulaInputRef.current?.focus(); return true; }, [formulaCellAtPointer, formulaEdit, proposeCell, renderedWorkbookKey]); const onFormulaPointerEnd = useCallback((event: ReactPointerEvent): boolean => { if (formulaPointer.current?.pointerId !== event.pointerId) return false; formulaPointer.current = null; event.preventDefault(); event.stopPropagation(); if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId); formulaInputRef.current?.focus(); return true; }, []); /** Row markers are Glide-internal cells, so `drawCell` deliberately never receives them. */ const activeRowHeaders = (() => { const canvas = wrapRef.current?.querySelector(".sheet-grid-canvas"); if (!canvas || !selection) return []; const origin = canvas.getBoundingClientRect(); const visibleLimit = Math.max(8, Math.ceil(origin.height / Math.max(1, MIN_ROW_HEIGHT * zoom)) + 4); const candidates: number[] = []; for (let row = -bandRows; row < Math.min(0, -bandRows + visibleLimit); row += 1) { candidates.push(row); } const bodyStart = Math.max(0, chartViewport.y - 1); for (let row = bodyStart; row < Math.min(visRows.length, bodyStart + visibleLimit); row += 1) { candidates.push(row); } return candidates.flatMap((row) => { if (!selectionProjectsHeader(selection, "row", row, headerProjectionBounds)) return []; const grid = row < 0 ? bandGridRef.current : gridRef.current; const bounds = grid?.getBounds(-1, row < 0 ? row + bandRows : row); if (!bounds || ![bounds.x, bounds.y, bounds.width, bounds.height].every(Number.isFinite) || bounds.y + bounds.height <= origin.y || bounds.y >= origin.bottom) return []; return [{ row, label: realRow(row) + 1, left: bounds.x - origin.x, top: bounds.y - origin.y, width: bounds.width, height: bounds.height }]; }); })(); /** * ⭐⭐ W54-T10 / LANE B — THE INSERT TAB'S DOOR, BUILT WHERE THE DOCUMENT ACTUALLY IS. * * ⛔ IT IS NOT A NEW `RibbonActionKind`, and that is deliberate rather than a shortcut: the act * union is closed by the exhaustive switch at the bottom of `onRibbonAction`, and a chart, a * sparkline, a link and a note are DOCUMENT WRITES rather than named acts. They take the * document's own doors, one per level. `onCells` IS `onCommit`, so a sparkline, a link and a * note are one history step and one save exactly like a paste; `onCharts` is the tab-level door * above, with its local fallback while the page has not wired one. * * ⛔ AND THE SELECTION CROSSES IN SHEET COORDINATES, TRANSLATED HERE. glide's indices count * VISIBLE rows and columns, so `realCol` / `realRow` run before the rectangle leaves this file. * A ribbon tab must never see a view index: it has no way to know one from a real one. */ // Wave 60 base kit: the door ALSO carries `SheetViewDoor` (the open tab's `view` and the two // View callbacks). `Ribbon.tsx` types `insert` as `RibbonInsertDoor` and is not this kit's file, // so the fields ride along at runtime and a ribbon change reads them by widening that type with // `Partial` from `./types` (no import back into this file). const insertDoor = useMemo(() => { const range = viewRange(); return { tabId: tab.id, filterActive: sheetFilter !== null, toggleFilter: toggleSheetFilter, view: tab.view, onTabView, onTabVisibility, hiddenTabs: workbook.sheets .filter(sheet => (sheet.visibility ?? "visible") === "hidden") .map(sheet => ({ id: sheet.id, name: sheet.name })), canHideTab: workbook.sheets.filter(sheet => (sheet.visibility ?? "visible") === "visible").length > 1, zoomToSelection: () => { const canvas = wrapRef.current?.querySelector(".sheet-grid-canvas"); if (!range || !canvas || !visCols.length || !allVisRows.length) return; const col0 = Math.max(0, Math.min(range.col0, range.col1)); const col1 = Math.min(visCols.length - 1, Math.max(range.col0, range.col1)); const row0 = Math.max(0, Math.min(range.row0, range.row1) + bandRows); const row1 = Math.min(allVisRows.length - 1, Math.max(range.row0, range.row1) + bandRows); if (col0 > col1 || row0 > row1) return; // The main scroller is last when a frozen band mounts its own canvas above it. const scrollers = canvas.querySelectorAll(".dvn-scroller"); const scroller = scrollers[scrollers.length - 1]; const viewportWidth = scroller?.clientWidth ?? canvas.clientWidth; const viewportHeight = canvas.clientHeight - (scroller ? scroller.offsetHeight - scroller.clientHeight : 0); if (viewportWidth <= 0 || viewportHeight <= 0) return; // Frozen cells occupy room even when the selected range is in the scrolling body. const fitWidths = visCols.filter((_, i) => i < frozenCols || (i >= col0 && i <= col1)) .map(real => widths[indexToCol(real + 1)] ?? COL_WIDTH); const fitHeights = allVisRows.filter((_, i) => i < bandRows || (i >= row0 && i <= row1)) .map(documentRowHeight); if (headingsVisible) { fitWidths.push(SHEET_ROW_MARKER_WIDTH); fitHeights.push(SHEET_HEADER_HEIGHT); } const total = (sizes: number[], factor: number, round = false) => sizes.reduce( (sum, size) => sum + (round ? Math.round(size * factor) : size * factor), 0, ); let percent = Math.max(10, Math.min(400, Math.floor(100 * Math.min( viewportWidth / total(fitWidths, 1), viewportHeight / total(fitHeights, 1), )))); // Use the canvas's per-cell rounding so a fitted last row or column is not clipped. while (percent > 10 && (total(fitWidths, percent / 100, true) > viewportWidth || total(fitHeights, percent / 100, true) > viewportHeight)) percent--; onTabView({ zoom: percent }); requestAnimationFrame(() => gridRef.current?.scrollTo( col0, Math.max(0, row0 - bandRows), row1 < bandRows ? "horizontal" : "both", 0, 0, { hAlign: "start", vAlign: "start" }, )); }, selection: range ? { col0: realCol(Math.min(range.col0, range.col1)), row0: realRow(Math.min(range.row0, range.row1)), col1: realCol(Math.max(range.col0, range.col1)), row1: realRow(Math.max(range.row0, range.row1)), } : null, charts, onCreatePivot, onCharts: writeCharts, onCells: onCommit, cellAt: (col: number, row: number) => cellAt(tab, addressOf(col, row)), }; }, [allVisRows, bandRows, charts, frozenCols, headingsVisible, onCommit, onTabView, onTabVisibility, realCol, realRow, rowHeight, tab, viewRange, visCols, widths, workbook, wrapHeights, writeCharts, sheetFilter, toggleSheetFilter, onCreatePivot]); return (
setRefusalHover(null)} onScrollCapture={() => setRefusalHover(null)} onPointerDownCapture={onFormulaPointerDown} onPointerMoveCapture={onFormulaPointerMove} onPointerUpCapture={onFormulaPointerEnd} onPointerCancelCapture={onFormulaPointerEnd} onLostPointerCapture={onFormulaPointerEnd}> {/* ⭐ THE HOME RIBBON, THEN THE FORMULA BAR, THEN THE CELLS. That order is instruction 10 said in three lines of JSX, and it is why the bar arrives as a SLOT: it has to sit under a ribbon that lives inside this component. The ribbon is given the ANCHOR cell's style, so a toggle reports what Excel reports. */} 0 || bandRows > 0} canImport={onOpenImport !== undefined} onApply={applyStyle} onAction={onRibbonAction} insert={insertDoor} /> {/* ⛔ NOTHING WHEN THERE IS NOTHING. An empty wrapper here would take padding and a border from whatever rule it matched, and every pixel above the grid is a pixel the canvas does not get. `.sheet-fx` already carries `flex: 0 0 auto`, so the bar is rendered bare. */} {isValidElement(formulaBar) && (isViewReserved(formulaBar.props.addr) || cells[formulaBar.props.addr]?.viewChild || viewChromeRefusal(cells[formulaBar.props.addr])) ? cloneElement(formulaBar, { onCommit: commitWithRecalc, disabled: formulaBar.props.disabled || isViewReserved(formulaBar.props.addr) || !!viewChromeRefusal(cells[formulaBar.props.addr]) }) : formulaBar}
{ // S63-T25 / C6: the accessibility table, frozen canvas and body canvas are three DOM // key targets but one Sheet command surface. Intercept the selection working set at // their common ancestor before either DataEditor consumes Space. Text editors keep // their own formula-reference semantics. const target = event.target; const typing = target instanceof Element && !!target.closest('input, textarea, [contenteditable="true"]'); if (matchShortcutInGrid(event, pasteShortcutContext(target)) === "paste-special") { if (readOnly) { event.preventDefault(); event.stopPropagation(); return; } event.preventDefault(); event.stopPropagation(); openPasteSpecial(); return; } const held = selectionRef.current; if (!typing && !formulaEdit && event.altKey && event.shiftKey && (event.key === "ArrowRight" || event.key === "ArrowLeft")) { event.preventDefault(); event.stopPropagation(); if (readOnly) return; if (event.key === "ArrowRight") groupRows(); else ungroupRows(); return; } const primary = event.ctrlKey || event.metaKey; const copyKey = event.key.toLowerCase(); // A selection may span both DataEditors. Letting the focused one answer native Copy // truncates the payload at its own row count (or fills the other half with Loading // cells), so the common owner writes the document payload assembled by `heldFor`. if (!typing && !formulaEdit && primary && !event.altKey && (copyKey === "c" || copyKey === "x") && !!held?.current) { event.preventDefault(); event.stopPropagation(); if (readOnly && copyKey === "x") return; copySelection(copyKey === "x"); return; } const selectionCommand = typing || formulaEdit ? null : matchShortcut(event); if (selectionCommand === "select-column" || selectionCommand === "select-row" || selectionCommand === "select-region") { event.preventDefault(); event.stopPropagation(); keyboardSelectingRef.current = true; queueMicrotask(() => { keyboardSelectingRef.current = false; }); const current = selectionRef.current?.current?.cell; if (selectionCommand === "select-column" && current) { selectDocumentAxis("column", current[0]); } else if (selectionCommand === "select-row" && current) { selectDocumentAxis("row", current[1]); } else if (selectionCommand === "select-region") { selectDocumentRegion(); } return; } const dir = commitDirection(event); const from = selectionRef.current?.current?.cell; if (dir === null || formulaEdit || !from) return; overlayCommit.current = { dir, at: Date.now(), from: [from[0], from[1]] }; if (typing) finishOverlayBoundaryCommit(dir, from); }} onPointerDownCapture={(event) => { pointerSelectingRef.current = true; headerPressXRef.current = event.clientX; headerBorderPressRef.current = false; rowBorderPressRef.current = false; const rowBorder = event.button === 0 ? rowBorderAt(event.clientX, event.clientY) : null; if (rowBorder && !readOnly) { rowBorderPressRef.current = true; headerDragRef.current = null; const height = rowBorder.rect.height / zoom; rowResizeGesture.current = { rows: rowsForResize(selectionRef.current, rowBorder.row, headerProjectionBounds).map(realRow), startY: event.clientY, bottom: rowBorder.rect.y + rowBorder.rect.height, height, size: height, zoom, moved: false, pointerId: event.pointerId, scope: renderedWorkbookKey, }; event.currentTarget.setPointerCapture(event.pointerId); event.preventDefault(); event.stopPropagation(); return; } // S64-T23 / R10: a press on a column header starts a whole-column drag. The anchor is // set HERE rather than on release, because `onHeaderClicked` only fires on mouse up and // an extend needs an anchor before the pointer has moved anywhere. // S64-T23: the press must land inside the header rectangle the hover reported, or the // remembered column is stale and this is not a header press at all. const hovered = headerHoverColRef.current; // S68-T29: Glide gives the left half of a border zone to the preceding column. // Its hover may be stale, so preserve the held selection beside either rect edge. if (event.button === 0 && hovered && event.clientY >= hovered.rect.y && event.clientY < hovered.rect.y + hovered.rect.height && borderHit(event.clientX, hovered.rect)) { headerBorderPressRef.current = true; headerDragRef.current = null; // Glide's exterior last-border path starts its drag without onColumnResizeStart. // Prime that one gesture here so it uses the same selection and commit as the rest. if (hovered.col === visCols.length - 1 && event.clientX >= hovered.rect.x + hovered.rect.width) { onColumnResizeStart(columns[hovered.col], columns[hovered.col].width, hovered.col); } return; } const inside = hovered !== undefined && hovered !== null && event.clientX >= hovered.rect.x && event.clientX < hovered.rect.x + hovered.rect.width && event.clientY >= hovered.rect.y && event.clientY < hovered.rect.y + hovered.rect.height; const col = inside && hovered ? hovered.col : null; if (col === null || event.button !== 0) { headerDragRef.current = null; return; } // A Shift press keeps the held anchor, which is what a Shift header click means today. if (!event.shiftKey) selectDocumentAxis("column", col, false, false); headerDragRef.current = { anchor: event.shiftKey ? selectionRef.current?.current?.cell[0] ?? col : col, last: col, moved: false, }; }} onDoubleClickCapture={(event) => { if (event.button !== 0 || readOnly) return; const rowBorder = rowBorderAt(event.clientX, event.clientY); if (rowBorder) { event.preventDefault(); event.stopPropagation(); autoFitRows(rowsForResize(selectionRef.current, rowBorder.row, headerProjectionBounds)); return; } const grid = bandRows > 0 ? bandGridRef.current : gridRef.current; // Fresh bounds identify the border after a prior resize; the hover rect can predate it. for (let col = 0; col < visCols.length; col += 1) { const rect = grid?.getBounds(col, -1); if (!rect || event.clientY < rect.y || event.clientY >= rect.y + rect.height || !borderHit(event.clientX, rect) || event.clientX < rect.x + rect.width - COLUMN_RESIZE_ZONE) continue; event.preventDefault(); autoFitColumns(columnsForResize(selectionRef.current, col, headerProjectionBounds)); return; } }} onPointerUpCapture={() => { queueMicrotask(() => { pointerSelectingRef.current = false; }); }} onPointerCancelCapture={() => { pointerSelectingRef.current = false; }} onPointerMoveCapture={(event) => { if (rowResizeGesture.current) return; const hit = rowBorderAt(event.clientX, event.clientY); setRowBorderHover(prior => prior?.row === hit?.row && prior?.rect.x === hit?.rect.x && prior?.rect.y === hit?.rect.y && prior?.rect.height === hit?.rect.height ? prior : hit); }} onPointerLeave={() => { if (!rowResizeGesture.current) setRowBorderHover(null); }} > {rowBorderHover && !readOnly &&