// sheet/Ribbon.tsx — the Sheet ribbon's SHELL (wave 50, W50-T19/A1; wave 51, W51-T15, ruling R8; // split per tab by wave 54's base kit). // // ⭐⭐ W54 BASE KIT 2a — THIS FILE IS THE FRAME, AND THE TABS ARE MODULES. It carries the tab // strip, the five action buttons, the roving-focus handler, the shared control vocabulary // (`control`, `group`, `word`, `item`) and a REGISTRY. Every Home group lives in `ribbonHome.tsx`; // a second tab is a second module registered in `TABS`, and neither module edits the other. The // reason is mechanical rather than tidy: two wave-54 lanes both extend the ribbon, and two lanes // cannot share one file. // // ⭐⭐ WHAT THIS COMPONENT IS AND IS NOT. It is a `role="toolbar"` of STATELESS controls: every // button reports one patch or one named act and holds nothing. The selection, the cells and the // commit all live in `SheetGrid.tsx`, which routes a patch through the page's ONE commit door so a // format change is one history step and one save, exactly like a paste. A ribbon that kept its own // idea of the current style would drift from the cell the moment an undo landed. // // ⭐⭐ W51-T15 — TWO EMISSIONS, AND THE SECOND ONE IS A CONTRACT WITH A LATER TICKET. // `onApply(CellStylePatch)` is a style the document already understands. `onAction({kind, arg})` // is a NAMED ACT, and its `kind` is a closed TypeScript union on purpose: W51-T16 implements the // acts, and a union is what stops it inventing a name this file does not emit or handling one that // never arrives. Every control in R8's roster is present, labelled and focusable NOW even where // its act is still owned by that ticket; a control that exists but is unreachable is the harder // defect to find later. // // ⛔ THERE IS EXACTLY ONE `role="toolbar"` HERE AND NONE IN `SheetGrid.tsx` (W51-T15). It used to // be two: this one, plus a second strip labelled "Rows and columns" carrying Insert row, Delete // row, Insert column, Delete column, Add rows, Add columns and Freeze panes. R8 puts those // acts in the Cells group of the Home row, so the strip is folded in and gone. Two toolbars over // one grid was also the thing instruction 8 was complaining about: a second white line. // // ⭐ ROVING FOCUS, AND IT SURVIVES A COLLAPSE. The whole ribbon is ONE tab stop and the arrows move // within it (ArrowLeft / ArrowRight, Home / End), which is the WAI-ARIA toolbar pattern. When the // ribbon is COLLAPSED the roving order shrinks to the tab strip and the chevron rather than // disappearing, because a collapsed ribbon a keyboard cannot re-open is a trap. The handler and // the ref both live on the SHELL, one level above the toolbar row, which is what lets the row // itself unmount without taking the keyboard with it. // // ⛔ THE ROVING HANDLER IS GATED ON `open === ""`. A colour swatch grid and a format menu are // their own arrow-key surfaces; leaving the toolbar handler live underneath would move the // toolbar's focus out from under an open popover, which is the class of defect that makes a menu // feel haunted. // // ⚠ DESIGN CONTRACT (DESIGN.md 2 through 5). Buttons reset native chrome; icons are inline SVG on // `currentColor` and NEVER emoji; a colour swatch is a token-styled span, never a coloured glyph; // colour and type are token only, so no literal `font-size` and no literal hue; Excel's Title Case (R41) // labels with no ALL CAPS chrome; motion is 150 ms ease-out on opacity and transform only; z-order // rides a `--cg-z-*` token. No em dash or en dash in any string that reaches a screen. import { Children, cloneElement, createContext, isValidElement, useContext, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import type { KeyboardEvent, MouseEvent as ReactMouseEvent, ReactNode } from "react"; import type { Cell, CellStyle, CellStylePatch, SheetChartSpec, Workbook, SheetPrintSettings, SheetViewDoor } from "./types"; import { AnchoredOverlay } from "../customer-grid/OverlaySurface"; import { OverlayScroll } from "../ui/OverlayScroll"; import { RailHeaderSlot } from "../shell/railHeader"; import { EXPORT_FORMATS, runSheetExport, sheetExportLosses, planSheetPdf, type SheetExportRange, type SheetExportFormat, type SheetExportSnapshot, } from "./sheetExport"; import ExportDialog from "./ExportDialog"; // ⭐ W52-T15 — a component-owned side-effect import, exactly like `customer-grid/Toolbar.tsx`'s // own `import "./filters.css"`. See the stylesheet's own header for why this is not an // `index.css` `@import` line. import "../styles/wave52/ribbon.css"; import "../styles/wave57/sheet-fullscreen.css"; import "../styles/wave57/ribbon-view.css"; import "../styles/wave58/sheet.css"; // ⭐⭐ W54 base kit 2a — THE REGISTERED TABS. Each module exports its own descriptor and its own // control keys; this file imports them and nothing else from either. import { HOME_TAB } from "./ribbonHome"; // ⭐⭐ W54-T10 (lane B) — the second registered tab. Same three exports, same registry, and the // shell learns nothing about it beyond its descriptor. import { INSERT_TAB } from "./ribbonInsert"; // W55-T06 adopts the public Excel audit's tab grouping through Loopable's existing ribbon // registry and command vocabulary. The tab modules cite the audit and keep unsupported commands // visibly unavailable rather than widening SheetGrid's closed action union. import { FORMULAS_TAB } from "./ribbonFormulas"; import { DATA_TAB } from "./ribbonData"; import { VIEW_TAB } from "./ribbonView"; // ⭐⭐ W52-T17 (instruction 20, ruling R7) — the KeyTips overlay is a SEPARATE keyboard-capture // layer, mounted once, that reads this file's DOM (`[data-kt]`, `[data-kt-opens]`) rather than // threading new props through 30+ `control()` call sites. See that file's own header for the // contract (C5) and the depth model (tabs -> Home controls -> one opened gallery). import KeyTips from "./KeyTips"; import SheetSearch from "./SheetSearch"; import type { SheetSearchCommand } from "./SheetSearch"; import type { RefreshScope, SheetMountAddress } from "./sheetApi"; import { addressOf } from "./sheetState"; import { sheetAddressHash } from "./index"; // W53-T07 (instr 25): the portalled popover's own surface. A body-level node keeps no // ancestor rule, so its background, edge and shadow travel with it. See the file header. // ⚠ SHELL, NOT HOME: `.sheet-ribbon-pop` is the surface EVERY tab's gallery paints on, so the // import stays here where both tabs inherit it. import "../styles/wave53/ribbon-pop.css"; /** Opens the active cell's binding editor through SheetPage's document listener. */ export const OPEN_CELL_DATA_EVENT = "aios:sheet-open-cell-data"; export const SheetRefreshContext = createContext<{ tabId: string; refresh: (scope: RefreshScope) => Promise; } | null>(null); export function selectedRefreshScope(kind: "cell" | "range", tabId: string, selection: NonNullable): RefreshScope { const start = addressOf(selection.col0, selection.row0); return kind === "cell" ? { cell: `${tabId}!${start}` } : { range: `${tabId}!${start}:${addressOf(selection.col1, selection.row1)}` }; } /** The page owns hydration, saves and identity; the ribbon owns export choices. */ export const SheetExportContext = createContext<{ book: Workbook; activeSheetId: string; capture: () => Promise; savePrintSettings: (settings: SheetPrintSettings) => Promise; } | null>(null); /** * ⭐⭐ THE ACT VOCABULARY, CLOSED. W51-T16 builds against this union and nothing else; adding a * control means adding its name here first, which is exactly the review moment that was missing * when the borders button shipped doing nothing (instruction 17). */ export type RibbonActionKind = // Clipboard | "paste" | "cut" | "copy" | "format-painter" // Font | "font-size" // Alignment | "align-top" | "align-middle" | "align-bottom" | "wrap-text" | "indent-decrease" | "indent-increase" // Number (the two formats the document model does not carry yet) | "format-accounting" | "format-custom" // Styles | "conditional-formatting" // ⭐ W54-T05 — the two Styles acts that build a rule FROM THE SELECTION rather than opening the // editor. They are separate members because each reads the selection's own numbers to work out // the range it spreads across, which no `arg` on the existing act could carry. | "colour-scale" | "data-bars" // Cells | "insert-row" | "insert-column" | "delete-row" | "delete-column" | "add-rows" | "add-columns" | "row-height" | "column-width" | "hide-rows" | "hide-columns" | "unhide" | "freeze" // ⭐ W54-T07 — the two AUTOFITS, which are the same two questions the manual sizes ask, asked // from the content instead. They are separate members rather than an `arg` on the existing acts // because neither opens the number dialog at all: each measures the selection and writes. | "autofit-rows" | "autofit-columns" // Editing | "autosum" | "fill-down" | "fill-right" | "clear-contents" | "clear-formats" | "clear-all" // ⭐ W54-T07 — FIND AND SELECT'S THREE, and all three reach a surface that ALREADY EXISTS: // `find` and `replace` open the one find box `SheetGrid.tsx` has carried since W51-T17 (the // second one with its replace row showing), and `go-to` focuses the formula bar's cell address // input, which is this app's Name Box and already jumps to whatever is typed into it. No act // here opens a second search surface, and none may. | "find" | "replace" | "go-to" // ⭐ W52-T15 (instruction 14) — the workbook's own acts. Their CONTROLS moved out of the // groups row and into the tab strip (`sheet-ribbon-tabs`), in the SAME horizontal space as // the Home tab; the act NAMES stay here because `SheetGrid.tsx`'s exhaustive switch still owns // what each one does, and that switch does not change in this ticket. | "refresh" | "import"; export interface RibbonAction { kind: RibbonActionKind; /** A step name (`small`), a count, or nothing. Never a free sentence. */ arg?: string | number; } /** * ⭐⭐ W54-T10 (lane B) — THE INSERT TAB'S DOOR, AND WHY IT IS NOT A NEW `RibbonActionKind`. * * ⛔ THE ACT UNION IS CLOSED BY AN EXHAUSTIVE SWITCH IN A FILE THIS LANE DOES NOT OWN. * `SheetGrid.tsx::onRibbonAction` ends on `const _exhaustive: never = action.kind`, so a new * member there is a compile error until that switch grows an arm, and growing it is another * ticket's surface. That is the mechanical reason. The DESIGN reason is the better one: a chart, a * sparkline, a link and a note are not NAMED ACTS at all. They are DOCUMENT WRITES, and the * document already has doors for both shapes of them, one per level. A chart is a TAB level key, * so it takes the tab's own replace-the-list door; a sparkline, a link and a note are CELL keys, * so they take the same one commit door a style patch takes, which is what makes an inserted * sparkline one history step and one save exactly like a paste. * * ⚠ OPTIONAL, for the reason `SheetGrid.tsx::onRules` states in full: a required prop would break * every other lane's tree at the merge. Where it is absent the Insert tab renders every control * DISABLED rather than wired to nothing, which is the fake affordance `canImport` refuses by name. */ export interface RibbonInsertDoor extends Partial { /** S70-T17: workbook tab creation stays outside the cell action union. */ onCreatePivot?: () => void; /** Fit the selected range using the grid's own visible geometry. */ zoomToSelection?: () => void; /** Tabs the user has hidden, for the View tab's Unhide list. `veryHidden` tabs are NOT here: * Excel does not offer them either, and the kit has no door to restore one. */ hiddenTabs?: readonly { id: string; name: string }[]; canHideTab?: boolean; /** The selection as a SHEET-coordinate rectangle, or null when nothing is selected. */ selection: { col0: number; row0: number; col1: number; row1: number } | null; /** This tab's charts, and the one door that replaces the list. */ charts: readonly SheetChartSpec[]; onCharts: (next: SheetChartSpec[]) => void; /** One or many cells, through the SAME commit door a style patch takes. */ onCells: (edits: Record) => void; /** Read a cell in SHEET coordinates, so a link or a note AMENDS rather than replaces. */ cellAt: (col: number, row: number) => Cell | null; } export interface RibbonProps { storagePrefix?: string; address?: SheetMountAddress; eventScope?: string; /** * The style of the cell the selection is ANCHORED on, which is what the toggles report as * pressed. Excel does the same: a mixed selection shows the anchor's state and a toggle then * applies that decision to the whole range. */ style: CellStyle | null; /** No selection, or a workbook that is saving: every control is inert but still readable. */ disabled?: boolean; /** Viewers can navigate and export, while document commands remain disabled. */ readOnly?: boolean; /** Whether the sheet currently freezes its leading column, so the Freeze item reads back. */ frozen?: boolean; /** ⛔ NO FAKE AFFORDANCE. Import is offered only where the page actually has a door for it. */ canImport?: boolean; onApply: (patch: CellStylePatch) => void; onAction: (action: RibbonAction) => void; /** ⭐ W54-T10 — the Insert tab's document doors. See {@link RibbonInsertDoor}. */ insert?: RibbonInsertDoor; } // ═══════════════════════════════════════════════════════════════════════════════════════════════ // THE REGISTRY, AND THE ROVING ORDER DERIVED FROM IT RATHER THAN RESTATED BESIDE IT. // // ⛔ A HAND MAINTAINED PARALLEL ARRAY IS HOW ROVING FOCUS DIES SILENTLY: one `data-ribbon` typo and // `focusControl`'s query returns null, with every gate still green. `ControlKey` is derived from // the registry below, so a control rendered under a name that is not in it is a TYPE ERROR. // ═══════════════════════════════════════════════════════════════════════════════════════════════ /** * ⭐⭐ THE REGISTERED TABS, IN STRIP ORDER. A tab module owns its own groups, its own control keys * and its own descriptor; this list is the whole of what the shell knows about any of them. * * ⭐⭐ INSERT IS REGISTERED AS OF W54-T10, AND IT WAS HELD BACK UNTIL IT HAD SOMETHING TO SHOW. * The base kit shipped `ribbonInsert.tsx` exporting its descriptor with an EMPTY group list and * deliberately left this array one entry long, because a registered empty tab paints a clickable * tab that opens a blank toolbar row, and a visibly broken strip is worse than an unregistered * module. W54-T10 gave the tab its four groups (Charts, Sparklines, Links, Comments) and added its * descriptor here in the same change. Nothing else in this file moved to do it: `ControlKey`, * `STRIP`, `reachable`, the tab-strip JSX and `Popover` are every one of them derived from this * array, so a THIRD tab is the same one line. */ const TABS = [HOME_TAB, INSERT_TAB, FORMULAS_TAB, DATA_TAB, VIEW_TAB] as const; /** * ⭐⭐ W52-T15 (instruction 14, contract C4) — IMPORT, REFRESH AND FULL SCREEN LIVE IN THE TAB * STRIP, NOT IN A RIBBON GROUP. They render in `sheet-ribbon-tabs`, which is on screen whether the * groups row is collapsed or not, so they belong with the collapse chevron in the set the roving * handler reaches even when collapsed rather than in a group array that vanishes with the rest. * W56-T17 adds Export to that same always-visible strip for the same reason. * * ⚠ THE KEY IS HERE AND THE BUTTON IS IN THE JSX, because the five differ in shape: Import and * Export each have their own data door, three carry an icon beside a word, Full Screen reports a * pressed state, and the chevron is not a plain control button at all. `ControlKey` is derived * from these keys, so the JSX still cannot render an action under a name this list does not carry. * * ⭐⭐ W54-T08 (owner instruction 7) — FULL SCREEN IS NO LONGER THE ODD ONE OUT. It used to paint * its mark with the label living only in `aria-label` and `title`, and this note used to read as * though that shape were settled. The owner has overruled it: the Sheet's control says * "Full Screen" on screen, the way the Data module's always has. */ const ACTIONS = [ { key: "import" }, { key: "refresh" }, { key: "export" }, { key: "fullscreen" }, { key: "collapse" }, ] as const; type TabId = (typeof TABS)[number]["id"]; type ControlKey = | "overflow" | (typeof TABS)[number]["key"] | (typeof ACTIONS)[number]["key"] | (typeof TABS)[number]["keys"][number]; /** * ⭐ WHICH POPOVER IS OPEN, NAMED BY THE CONTROL THAT OWNS IT. Every popover hangs off a control, * so the state is a `ControlKey` or nothing, and `closePop` reads it back to return focus to that * exact button. Derived rather than hand-listed since W54, so a newly registered tab's gallery * needs no edit here. */ export type Popover = "" | ControlKey; /** * The strip: the tab buttons and the five actions. This is exactly what stays on screen when the * groups row is collapsed, which is why it is also the collapsed roving order. */ const STRIP: readonly ControlKey[] = [ ...TABS.map((tab) => tab.key), ...ACTIONS.map((action) => action.key), ]; /** * ⭐⭐ WHAT A TAB MODULE RENDERS AGAINST. Everything a group needs and nothing more: the shared * control vocabulary, the state a control reads back, and the two emissions. A tab module is a * pure function of this, which is what lets two lanes own two tabs without either one reaching * into the shell's state or holding any of its own. */ export interface RibbonTabContext { style: CellStyle | null; readOnly?: boolean; frozen: boolean; open: Popover; anchorEl: HTMLElement | null; /** The page's own door, unfiltered: an act that must NOT close an open gallery uses this. */ onApply: (patch: CellStylePatch) => void; apply: (patch: CellStylePatch) => void; act: (kind: RibbonActionKind, arg?: string | number) => void; /** View-only state owned by the ribbon shell, with no new document or SheetGrid action. */ fullscreen: boolean; toggleFullscreen: () => void; newWindowBlocked: boolean; openNewWindow: () => void; openCellData: () => void; openPop: (which: Popover) => (event: ReactMouseEvent) => void; closePop: () => void; control: ( key: ControlKey, label: string, body: ReactNode, onClick: (event: ReactMouseEvent) => void, pressed?: boolean, expanded?: boolean, kt?: string, ktOpens?: "gallery", controlDisabled?: boolean, popupRole?: "menu" | "dialog", ) => ReactNode; group: (name: string, body: ReactNode, extra?: string) => ReactNode; word: (text: string) => ReactNode; large: (body: ReactNode) => ReactNode; stack: (...rows: ReactNode[]) => ReactNode; /** A command the current Sheet door cannot execute, stated visibly instead of acting dead. */ unavailable: (label: string, body: ReactNode) => ReactNode; item: (label: string, onClick: () => void, on?: boolean, role?: string, kt?: string) => ReactNode; /** * ⭐ W54-T10 — the Insert tab's document doors, handed through unchanged. Undefined on a page * that has not wired them, which is what the Insert tab reads to render itself disabled rather * than offering a control with nothing behind it. See {@link RibbonInsertDoor}. */ insert?: RibbonInsertDoor; } /** * ⭐ COLLAPSE IS REMEMBERED PER PERSON, and the key is namespaced so nothing else in the app can * collide with it. A throwing read (a private window refuses storage) renders EXPANDED, which is * the state that shows every control rather than the state that hides them. */ const COLLAPSE_KEY = "aios.sheet.ribbon.collapsed"; const readCollapsed = (prefix = ""): boolean => { try { return window.localStorage.getItem(prefix + COLLAPSE_KEY) === "1"; } catch { return false; } }; const writeCollapsed = (next: boolean, prefix = "") => { try { window.localStorage.setItem(prefix + COLLAPSE_KEY, next ? "1" : "0"); } catch { // Storage is refused in a private window. The ribbon still collapses for this session. } }; function IconRefresh() { return ( ); } /** A document leaving through a downward arrow, in the same hand-drawn line style as Refresh. */ function IconExport() { return ( ); } /** * ⭐ W52-T15 (instruction 26, contract C4) — THE SAME MARK THE DATA MODULE'S FULL SCREEN CONTROL * WEARS. `customer-grid/Toolbar.tsx::IconFullScreen` draws this exact path (four corner brackets * closing toward the centre) but is not exported and that whole directory is lane G's fence this * wave (⛔ import-only, never edit), so the geometry travels here as the same `d` string rather * than as a shared component. One drawing, two copies, never a redraw: if the Data module's mark * ever moves, this one is the other half of that diff. */ function IconFullScreen() { return ( ); } /** One chevron drawing serves collapse and horizontal scrolling through rotation. */ function IconChevron({ direction }: { direction: "up" | "down" | "left" | "right" }) { const rotation = { up: 0, down: 180, left: -90, right: 90 }[direction]; return ( ); } /** Keep each tab's wrappers, including Insert's native disabled fieldset, on both sides. */ function partitionRibbonGroups(node: ReactNode, visibleCount: number, folded: boolean): ReactNode { return Children.map(node, (child) => { if (!isValidElement<{ children?: ReactNode; "data-ribbon-group"?: number }>(child)) return child; const index = child.props["data-ribbon-group"]; if (index !== undefined) return (index >= visibleCount) === folded ? child : null; if (!child.props.children) return child; const children = partitionRibbonGroups(child.props.children, visibleCount, folded); return Children.count(children) ? cloneElement(child, undefined, children) : null; }); } /** Stateful child controls must be mounted by React, never called as groups(ctx) functions. * The recording context returns no buttons, and open is empty, so no overlay or action mounts. */ export function ribbonCommandWrites(key: string, label?: string): boolean { if (key === "findselect" && label !== undefined) return !/^(Find|Go To)/i.test(label); return !key.startsWith("tab-") && !["copy", "findselect", "refresh", "export", "fullscreen", "collapse", "overflow", "cell-data", "data-queries-connections", "view-new-window", "view-fullscreen", "view-go-to"].includes(key); } function RibbonCommandProbe({ node, context, tab, group, disabled, runControl, publish }: { node: React.ReactElement<{ ctx: RibbonTabContext }>; context: RibbonTabContext; tab: TabId; group: string; disabled: boolean; runControl: (tab: TabId, key: ControlKey) => void; publish: (commands: SheetSearchCommand[]) => void; }) { const records = useMemo(() => [], []); const ctx = useMemo(() => ({ ...context, open: "", anchorEl: null, control: (key, label, _body, _onClick, _pressed, _expanded, _kt, _opens, controlDisabled) => { const command = { id: `${tab}:${key}`, key, label, location: group, disabled: disabled || !!controlDisabled || (!!context.readOnly && ribbonCommandWrites(key)), run: () => runControl(tab, key) }; const at = records.findIndex(record => record.id === command.id); if (at < 0) records.push(command); else records[at] = command; return null; }, }), [context, disabled, group, records, runControl, tab]); useLayoutEffect(() => { publish(records); }, [publish, records]); return cloneElement(node, { ctx }); } /** Evaluate the registered definitions only when search opens. Group arguments evaluate first; * group() drains that buffer and assigns its name. Gallery passes reveal their item closures. */ function recordRibbonCommands( context: RibbonTabContext, disabled: boolean, runControl: (tab: TabId, key: ControlKey) => void, publish: (commands: SheetSearchCommand[]) => void, ): ReactNode { type Recorded = SheetSearchCommand & { kind: "control" | "item"; opensGallery?: boolean }; const all: Recorded[] = []; const probes: ReactNode[] = []; const childRecords = new Map(); let base: SheetSearchCommand[] = []; for (const tab of TABS) { const pass = (gallery?: Recorded) => { const records: Recorded[] = []; let pending: Recorded[] = []; const ctx: RibbonTabContext = { ...context, open: gallery ? gallery.key as Popover : "", anchorEl: null, control: (key, label, _body, _onClick, _pressed, _expanded, _kt, opensGallery, controlDisabled) => { const record: Recorded = { id: `${tab.id}:${key}`, key, label, location: tab.label, kind: "control", opensGallery: opensGallery === "gallery", disabled: disabled || !!controlDisabled || (tab.id === "insert" && !context.insert) || (!!context.readOnly && ribbonCommandWrites(key)), run: () => runControl(tab.id, key), }; pending.push(record); records.push(record); // A marker lets group() retain native fieldset disabling without mounting any UI. return ; }, item: (label, onClick) => { if (gallery) { const record: Recorded = { id: `${tab.id}:${gallery.key}:item:${label}`, key: gallery.key, label, location: gallery.location, kind: "item", disabled: gallery.disabled || (!!context.readOnly && ribbonCommandWrites(gallery.key, label)), run: onClick, }; pending.push(record); records.push(record); } return null; }, unavailable: (label) => { const record: Recorded = { id: `${tab.id}:unavailable:${label}`, key: "", label, location: tab.label, kind: "control", disabled: true, run: () => {}, }; pending.push(record); records.push(record); return null; }, group: (name, body) => { const location = `${tab.label} > ${name}`; pending.forEach(record => { record.location = location; }); const walk = (node: ReactNode, fenced = false) => Children.forEach(node, child => { if (!isValidElement<{ children?: ReactNode; disabled?: boolean; ctx?: RibbonTabContext; "data-search-command"?: string }>(child)) return; const blocked = fenced || (child.type === "fieldset" && !!child.props.disabled); const record = pending.find(entry => entry.id === child.props["data-search-command"]); if (record && blocked) record.disabled = true; if (!gallery && child.props.ctx === ctx) { const index = probes.length; probes.push(} context={context} tab={tab.id} group={location} disabled={disabled || blocked} runControl={runControl} publish={commands => { childRecords.set(index, commands); publish([...base, ...Array.from(childRecords.values()).flat()]); }} />); } else walk(child.props.children, blocked); }); walk(body); pending = []; return null; }, }; tab.groups(ctx); return records; }; const controls = pass(); const items = controls.filter(control => control.opensGallery) .flatMap(control => pass(control).filter(record => record.kind === "item")); all.push(...controls.filter(control => !items.some(item => item.key === control.key && item.label === control.label)), ...items); } base = [...new Map(all.map(command => [command.id, command])).values()]; publish(base); return <>{probes}; } export default function Ribbon({ storagePrefix = "", address, eventScope = "", style, disabled = false, readOnly = false, frozen = false, canImport = false, onApply, onAction, insert, }: RibbonProps) { const [focus, setFocus] = useState(TABS[0].key); const [open, setOpen] = useState(""); /** * ⭐⭐ W53-T07 (instruction 25) — THE TRIGGER ELEMENT, CAPTURED ON CLICK, because a portalled * menu has no DOM parent to position against. `AnchoredOverlay` takes this as its `anchor` and * also puts it in its own `outsideElements`, so a pointerdown on the trigger does NOT count as * an outside press: the plain toggle below still closes an open menu, and clicking a DIFFERENT * trigger dismisses the first and opens the second, with no `stopPropagation` anywhere. * ⚠ Nullable by declaration in `AnchoredOverlayProps`, so a null anchor is safe rather than a * render-time TypeError. */ const [anchorEl, setAnchorEl] = useState(null); const exportContext = useContext(SheetExportContext); const refreshContext = useContext(SheetRefreshContext); const [exportBusy, setExportBusy] = useState(false); const [exportError, setExportError] = useState(""); const [exportReview, setExportReview] = useState<{ format: SheetExportFormat; snapshot: SheetExportSnapshot; losses: string[]; options: { range?: SheetExportRange; pdf?: SheetPrintSettings }; } | null>(null); const [printOpen, setPrintOpen] = useState(false); const [printSettings, setPrintSettings] = useState({sheetIds:[],paper:"letter",orientation:"landscape",fit:"width"}); const [pageFrom, setPageFrom] = useState(""); const [pageTo, setPageTo] = useState(""); const [exportScope, setExportScope] = useState<"sheet" | "selection">("sheet"); const exportUnavailable = !exportContext; const [collapsed, setCollapsed] = useState(() => readCollapsed(storagePrefix)); const rootRef = useRef(null); const scrollRef = useRef(null); const overflowRef = useRef(null); const overflowTriggerRef = useRef(null); const [overflowOpen, setOverflowOpen] = useState(false); const [groupFit, setGroupFit] = useState<{ tab: TabId; count: number } | null>(null); /** Which registered tab is showing. */ const [active, setActive] = useState(TABS[0].id); const activeTab = TABS.find((tab) => tab.id === active) ?? TABS[0]; const visibleGroupCount = groupFit?.tab === active ? groupFit.count : Infinity; const hasOverflow = Number.isFinite(visibleGroupCount); /** * The keys the arrows may reach right now. Collapsed, that is the strip and nothing else — and * the strip now carries Import, Refresh, Export and Full Screen too. * Expanded, it is the strip plus the controls of the tab that is actually showing, read off its * own descriptor rather than a list kept beside it. Import is only in the order on a page that * actually has an import door, in both branches. */ const reachable = useMemo( () => (collapsed ? STRIP : [...STRIP, ...activeTab.keys, ...(hasOverflow ? ["overflow" as const] : [])]) .filter((key) => (key !== "import" || canImport) && (key !== "export" || !exportUnavailable)), [activeTab, canImport, collapsed, exportUnavailable, hasOverflow], ); // ⛔ FOCUS MUST LAND ON SOMETHING THAT EXISTS. Collapsing while the focus sits on a control that // is about to unmount would leave the roving state pointing at nothing: every arrow press after // it would query a `data-ribbon` that is not in the tree, and NO control would carry tabIndex 0, // so the toolbar would drop out of the tab order entirely with every gate still green. useEffect(() => { if (!reachable.includes(focus)) setFocus(reachable[0]); }, [focus, reachable]); useEffect(() => { if (hasOverflow && !overflowOpen && overflowRef.current?.querySelector(`[data-ribbon="${focus}"]`)) { setFocus("overflow"); } }, [focus, hasOverflow, overflowOpen, visibleGroupCount]); const focusControl = useCallback((key: ControlKey) => { setFocus(key); const selector = `[data-ribbon="${key}"]`; const foldedControl = overflowRef.current?.querySelector(selector); if (foldedControl) { // Closed folded groups remain mounted for measurement; reveal them before focusing. setOverflowOpen(true); requestAnimationFrame(() => overflowRef.current?.querySelector(selector)?.focus()); } else { rootRef.current?.querySelector(selector)?.focus(); } }, []); const closeOverflow = useCallback(() => { setOverflowOpen(false); setFocus("overflow"); overflowTriggerRef.current?.querySelector("button")?.focus(); }, []); const toggleCollapsed = useCallback(() => { setCollapsed((was) => { const next = !was; writeCollapsed(next, storagePrefix); return next; }); setOpen(""); setOverflowOpen(false); }, [storagePrefix]); /** * ⭐ W52-T15 (instruction 26) — FULL SCREEN, SELF CONTAINED. The Data module's control flips a * flag its host (`CustomerGrid.tsx`) owns and paints as a CSS class on its own shell; the Sheet * page has no such flag yet and wiring one is `SheetPage.tsx` work outside this ticket's files. * So this button drives the browser's OWN Fullscreen API on the sheet's grid wrapper instead — * real, working full screen, with no edit needed anywhere else. `document.fullscreenchange` is * the one event that also fires when a person exits with Escape or the browser's own chrome, so * the label and the pressed state stay honest either way. */ const [fullscreen, setFullscreen] = useState( () => typeof document !== "undefined" && !!document.fullscreenElement, ); useEffect(() => { const onChange = () => setFullscreen(!!document.fullscreenElement); document.addEventListener("fullscreenchange", onChange); return () => document.removeEventListener("fullscreenchange", onChange); }, []); const toggleFullscreen = useCallback(() => { if (document.fullscreenElement) { void document.exitFullscreen(); return; } const target = rootRef.current?.closest(".sheet-grid-wrap") ?? rootRef.current; target?.requestFullscreen().catch(() => { // A browser that refuses (no user gesture, or the API is unsupported) leaves the sheet // exactly as it was rather than throwing into the console. }); }, []); const [newWindowBlocked, setNewWindowBlocked] = useState(false); const openNewWindow = useCallback(() => { // The noopener feature also returns null on success. Open a blank window to detect a // real refusal, then detach its opener before any workbook code can load. const nextWindow = window.open("about:blank", "_blank", "popup"); if (!nextWindow) { setNewWindowBlocked(true); return; } nextWindow.opener = null; const url = eventScope.startsWith("embed:") ? new URL(sheetAddressHash({ wb: address?.wb ?? null, tab: address?.tab }), window.location.origin + window.location.pathname).href : window.location.href; nextWindow.location.replace(url); setNewWindowBlocked(false); }, [address, eventScope]); const openCellData = useCallback(() => { const name = eventScope.startsWith("embed:") ? `${OPEN_CELL_DATA_EVENT}:${eventScope}` : OPEN_CELL_DATA_EVENT; document.dispatchEvent(new CustomEvent(name)); }, [eventScope]); // ⭐⭐ W53-T07 — THE HAND-ROLLED OUTSIDE-PRESS LISTENER IS GONE, AND ITS REASON SURVIVED THE // DELETION. It read: *"a popover closes on an outside press, and on `mousedown` rather than // `click`, because a click listener fires after the grid canvas has already taken focus and // dropped its selection."* That hazard is real and it is now handled EARLIER, not dropped: // `AnchoredOverlay` calls `useOverlayLayer`, which dismisses on capture-phase **`pointerdown`** // (`customer-grid/OverlaySurface.tsx`), and `pointerdown` fires before `mousedown`, which fires // before `click`. The shared door is strictly earlier than the listener it replaces. // ⛔ DO NOT REINSTATE ONE. `DESIGN.md` section 4's Overlays paragraph names the three legal // doors (`ui/useEscapeClose.ts`, `AnchoredOverlay`, `useOverlayLayer`) and says in terms that a // local `keydown` listener is the defect, not the shortcut: a menu opened inside a dialog used // to race that dialog, and the winner depended on listener registration order rather than on // what the person was looking at. A second listener under a registered layer restores the race. // ⚠ `rootRef.contains(target)` would also now be WRONG on its own terms: the menu is a child of // ``, so a press inside the menu reads as "outside my own UI". const onKeyDown = useCallback((event: KeyboardEvent) => { // ⭐ W53-T07 — NO `Escape` BRANCH HERE ANY MORE. `useEscapeClose`, reached through // `AnchoredOverlay`, owns Escape for whichever overlay is topmost and resolves it to exactly // one surface; `closePop` below is what returns focus to the trigger afterwards. A branch here // would be a second claimant on the same key. // The toolbar's arrows belong to the toolbar only while nothing is open above it. if (open) return; if (event.target instanceof HTMLElement && event.target.matches("input, textarea, select, [contenteditable=true]")) return; const enabledKeys = reachable.filter(key => { const selector = `[data-ribbon="${key}"]`; const button = rootRef.current?.querySelector(selector) ?? overflowRef.current?.querySelector(selector); return button && !button.matches(":disabled"); }); if (!enabledKeys.length) return; const at = Math.max(0, enabledKeys.indexOf(focus)); if (event.key === "ArrowRight") { event.preventDefault(); focusControl(enabledKeys[(at + 1) % enabledKeys.length]); } else if (event.key === "ArrowLeft") { event.preventDefault(); focusControl(enabledKeys[(at - 1 + enabledKeys.length) % enabledKeys.length]); } else if (event.key === "Home") { event.preventDefault(); focusControl(enabledKeys[0]); } else if (event.key === "End") { event.preventDefault(); focusControl(enabledKeys[enabledKeys.length - 1]); } }, [focus, focusControl, open, reachable]); const apply = useCallback((patch: CellStylePatch) => { if (readOnly) return; setOpen(""); if (overflowOpen) closeOverflow(); onApply(patch); }, [closeOverflow, onApply, overflowOpen, readOnly]); const act = useCallback((kind: RibbonActionKind, arg?: string | number) => { if (readOnly && !["copy", "find", "go-to"].includes(kind)) return; setOpen(""); if (overflowOpen) closeOverflow(); onAction({ kind, arg }); }, [closeOverflow, onAction, overflowOpen, readOnly]); /** * ⭐⭐ W53-T07 — CLOSING A MENU RETURNS FOCUS TO THE CONTROL THAT OWNS IT, and that is the * `done-when`'s third clause. Every `Popover` value is also a `ControlKey` by construction, so * the trigger is named by the state itself and no second map can drift out of step. * ⛔ `restoreFocus` CANNOT DO THIS JOB HERE, and the reason is worth keeping: every ribbon * button carries `onMouseDown={(e) => e.preventDefault()}` so that pressing it never blurs the * grid canvas, which means the trigger NEVER RECEIVES FOCUS on a mouse open. `useOverlayLayer` * snapshots `document.activeElement` at mount and restores that, so it would faithfully restore * the canvas. Focusing the trigger on OPEN instead would blur the canvas for the whole life of * the menu, which is precisely the state the `preventDefault` above exists to avoid. Returning * focus on CLOSE gets both: the canvas keeps the keyboard while the menu is deciding, and the * toolbar gets it back when the menu is gone. This is also exactly what the retired `Escape` * branch used to do. */ const closePop = () => { if (open) focusControl(open as ControlKey); setOpen(""); }; /** Open (or toggle) one popover, remembering the button it hangs from. */ const openPop = (which: Popover) => (event: ReactMouseEvent) => { setAnchorEl(event.currentTarget); setOpen((was) => (was === which ? "" : which)); }; const toggleExport = (event: ReactMouseEvent) => { if (open === "export") { openPop("export")(event); return; } if (!exportContext) return; const saved=exportContext.book.printSettings; setPrintSettings(saved??{sheetIds:exportContext.book.sheets.map(s=>s.id),paper:"letter",orientation:"landscape",fit:"width"}); setPageFrom(saved?.from===undefined?"":String(saved.from)); setPageTo(saved?.to===undefined?"":String(saved.to)); setPrintOpen(false); setExportReview(null); setExportError(""); setExportScope("sheet"); openPop("export")(event); }; /** * One control. `data-ribbon` is what the roving handler finds; `tabIndex` is the roving part. * * ⭐⭐ W52-T16 (contract C4) — `kt` IS THE KEY-TIP SEQUENCE, and it is the ONLY thing a later * KeyTip overlay (W52-T17) may read: that ticket's badge layer walks `[data-kt]` and never * hardcodes a control list, so a control added here without a `kt` is invisible to it forever, * not merely undecorated. `ktOpens` is set to `"gallery"` for a control whose click OPENS a * popover rather than firing an act directly — every `control(...)` call below that also passes * `expanded` (the border gallery, the fill/text colour swatches, the font-size steps, Insert, * Delete, cell Format, Clear) carries it; a control that fires straight through does not. */ const control = ( key: ControlKey, label: string, body: ReactNode, // ⚠ W53-T07 widened this from `() => void`. A zero-argument lambda is assignable to a // one-argument function type, so every existing call site compiles unchanged; only the // popover triggers actually read the event, for `event.currentTarget` as the anchor. onClick: (event: ReactMouseEvent) => void, pressed?: boolean, expanded?: boolean, kt?: string, ktOpens?: "gallery", controlDisabled?: boolean, popupRole: "menu" | "dialog" = "menu", ) => ( ); /** * ⭐ A GROUP IS NAMED TWICE ON PURPOSE: once for a screen reader (`role="group"` plus its label) * and once on the screen, in the caption under its controls. R8 names the seven groups and the * owner reads them by name, so a row of unnamed clusters would not be the thing that was asked * for. Sentence case, muted, and a scale token, never a literal size (DESIGN.md 2). */ let groupIndex = 0; const group = (name: string, body: ReactNode, extra = "") => (
{readOnly && name === "Font" ?
{body}
: body}
{name}
); /** A plain word inside a control. A ribbon is not an icon quiz. */ const word = (text: string) => {text}; // R19: every tab shares these slots; flat icon-plus-word rows hid whole groups in overflow. const large = (body: ReactNode) => {body}; const stack = (...rows: ReactNode[]) => ( {rows.map((row, index) => {row})} ); /** * A disabled command is intentionally outside the roving registry. Native `disabled` keeps it * inert; the visible status and accessible name explain why it does not receive focus or fire. */ const unavailable = (label: string, body: ReactNode) => ( ); // ⭐ W52-T17 — the optional 5th argument `kt` is the THIRD-LEVEL key-tip badge (KT-11): a // gallery item painted with its own letter once the gallery that owns it is open. Additive and // undefined everywhere this ticket did not touch, so every existing `item(...)` call site keeps // compiling unchanged. const item = (label: string, onClick: () => void, on = false, role = "menuitem", kt?: string) => ( ); /** Same idiom as the Data module's own `fullscreenLabel` (`customer-grid/Toolbar.tsx`). */ const fullscreenLabel = fullscreen ? "Exit Full Screen" : "Full Screen"; const exportLabel = exportUnavailable ? "Export unavailable" : "Export"; const selectionRange: SheetExportRange | null = insert?.selection ? { col0: Math.min(insert.selection.col0, insert.selection.col1), row0: Math.min(insert.selection.row0, insert.selection.row1), col1: Math.max(insert.selection.col0, insert.selection.col1), row1: Math.max(insert.selection.row0, insert.selection.row1), } : null; const selectionChoice = !!selectionRange && (selectionRange.col0 !== selectionRange.col1 || selectionRange.row0 !== selectionRange.row1); const downloadExport = async (format: SheetExportFormat) => { if (!exportContext || exportBusy) return; setExportBusy(true); setExportError(""); try { const snapshot=await exportContext.capture(); if(snapshot.book.id!==exportContext.book.id)throw new Error("The workbook changed. Open Export again."); const pdf={...printSettings,from:pageFrom.trim()===""?undefined:Number(pageFrom),to:pageTo.trim()===""?undefined:Number(pageTo)}; if(format==="pdf") { planSheetPdf(snapshot.book,pdf); snapshot.book={...snapshot.book,printSettings:pdf}; } const options={range:format==="csv"&&exportScope==="selection"&&selectionRange?selectionRange:undefined,pdf}; const losses=sheetExportLosses(format,snapshot,options); if(losses.length) { setExportReview({format,snapshot,options,losses}); return; } if(format==="pdf"&&!readOnly)await exportContext.savePrintSettings(pdf); await runSheetExport(format,snapshot,options); closePop(); } catch(error) { setExportError(error instanceof Error?error.message:"The file could not be exported."); } finally { setExportBusy(false); } }; const downloadReviewedExport = async () => { if (!exportReview || !exportContext || exportBusy) return; setExportBusy(true); setExportError(""); try { const {format,snapshot,options}=exportReview; if(snapshot.book.id!==exportContext.book.id)throw new Error("The workbook changed. Open Export again."); if(format==="pdf"&&options.pdf&&!readOnly)await exportContext.savePrintSettings(options.pdf); await runSheetExport(format,snapshot,options); setExportReview(null); closePop(); } catch(error) { setExportError(error instanceof Error?error.message:"The file could not be exported."); } finally { setExportBusy(false); } }; const tabContext: RibbonTabContext = { style, frozen, open, anchorEl, readOnly, onApply: patch => { if (!readOnly) onApply(patch); }, apply, act, fullscreen, toggleFullscreen, newWindowBlocked, openNewWindow, openCellData, openPop, closePop, control, group, word, large, stack, unavailable, item, insert, }; const buildSearchCommands = (publish: (commands: SheetSearchCommand[]) => void) => { setOpen(""); setOverflowOpen(false); const runControl = (tab: TabId, key: ControlKey) => { setActive(tab); setCollapsed(false); writeCollapsed(false, storagePrefix); setOpen(""); requestAnimationFrame(() => { focusControl(key); // focusControl may reveal a folded group, which needs one render before its click. requestAnimationFrame(() => { const selector = `[data-ribbon="${key}"]`; const button = overflowRef.current?.querySelector(selector) ?? rootRef.current?.querySelector(selector); if (button && !button.matches(":disabled")) button.click(); }); }); }; // Strip actions are already rendered from this shell's definitions. Read their real labels // and native disabled state, rather than maintaining another list of Import/Export/etc. const strip = Array.from(rootRef.current?.querySelectorAll( ".sheet-ribbon-tabs-actions [data-ribbon]", ) ?? []).map(button => { const key = button.dataset.ribbon as ControlKey; return { id: `strip:${key}`, key, label: button.getAttribute("aria-label") ?? button.textContent ?? key, location: "Ribbon", disabled: button.matches(":disabled"), run: () => runControl(active, key), }; }); return recordRibbonCommands(tabContext, disabled, runControl, commands => publish([...commands, ...strip])); }; const activeGroups = activeTab.groups(tabContext); const overflowContent = (
{partitionRibbonGroups(activeGroups, visibleGroupCount, true)}
); useLayoutEffect(() => { const scroller = scrollRef.current; const trigger = overflowTriggerRef.current; if (!scroller || !trigger || collapsed) return; // An open form must not remount during a resize. Refit immediately after it closes. if (open || overflowOpen) return; const groups = [ ...scroller.querySelectorAll("[data-ribbon-group]"), ...(overflowRef.current?.querySelectorAll("[data-ribbon-group]") ?? []), ].sort((a, b) => Number(a.dataset.ribbonGroup) - Number(b.dataset.ribbonGroup)); const fitGroups = () => { // Keep natural widths even for folded groups; never measure a compressed flex child. // Normalize the last-child divider so folding cannot change the measured total by a pixel. const widths = groups.map(element => { const border = parseFloat(window.getComputedStyle(element).borderRightWidth) || 0; return Math.ceil(element.getBoundingClientRect().width - border + 1); }); const available = scroller.clientWidth; if (!available || widths.length !== groupIndex) return; let count = Infinity; if (widths.reduce((sum, width) => sum + width, 0) > available) { const budget = Math.max(0, available - trigger.getBoundingClientRect().width - 8); count = 0; let used = 0; while (count < widths.length && used + widths[count] <= budget) used += widths[count++]; } const focusedGroup = document.activeElement?.closest("[data-ribbon-group]"); if (focusedGroup && scroller.contains(focusedGroup) && Number(focusedGroup.dataset.ribbonGroup) >= count) { setFocus("overflow"); requestAnimationFrame(() => trigger.querySelector("button")?.focus()); } else if (count === Infinity && trigger.contains(document.activeElement)) { setFocus(activeTab.key); requestAnimationFrame(() => rootRef.current?.querySelector(`[data-ribbon="${activeTab.key}"]`)?.focus()); } setGroupFit(current => current?.tab === active && current.count === count ? current : { tab: active, count }); scroller.scrollLeft = 0; }; fitGroups(); const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(fitGroups); observer?.observe(scroller); observer?.observe(trigger); groups.forEach(element => observer?.observe(element)); window.addEventListener("resize", fitGroups); return () => { observer?.disconnect(); window.removeEventListener("resize", fitGroups); }; }, [active, activeTab.key, collapsed, groupIndex, open, overflowOpen, visibleGroupCount]); const toggleOverflow = () => { if (overflowOpen) { closeOverflow(); return; } setOpen(""); setOverflowOpen(true); requestAnimationFrame(() => { const first = overflowRef.current?.querySelector("[data-ribbon]:not(:disabled)"); if (first) { setFocus(first.dataset.ribbon as ControlKey); first.focus(); } else { setFocus("overflow"); overflowTriggerRef.current?.querySelector("button")?.focus(); } }); }; return (
{/* ⭐ THE TAB STRIP, PAINTED FROM THE REGISTRY. One registered tab today, and it is still a tab strip: it is where the collapse chevron belongs and where a second tab joins without moving anything, because the button below is written once for whatever is registered. ⭐⭐ W52-T15 (instruction 14, contract C4) — IMPORT, REFRESH AND FULL SCREEN SIT HERE NOW, in the SAME HORIZONTAL STRIP as the tabs, rather than in a "Workbook" ribbon group that Excel has no equivalent of. W56-T17 adds Export beside them without moving it into the collapsible group row. */}
{TABS.map((tab) => ( ))}
{canImport && control("import", "Import", word("Import"), () => act("import"))} {control("refresh", "Refresh", <>{word("Refresh")}, openPop("refresh"), false, open === "refresh", undefined, "gallery", !refreshContext)} {open === "refresh" && refreshContext && ( {(["cell", "range", "workbook"] as const).map(kind => ( ))} )} {control("export", exportLabel, <>{word("Export")}, toggleExport, false, open === "export", "E", "gallery", exportUnavailable)} {open === "export" && exportContext && ( {exportReview ? entry.format===exportReview.format)!.label} busy={exportBusy} onBack={()=>{setExportReview(null);setExportError("");}} onDownload={()=>void downloadReviewedExport()}/> : printOpen ?
Sheets
{exportContext.book.sheets.map(sheet=>)}
: <> {selectionChoice&&} {EXPORT_FORMATS.map(({format,label})=>)} } {exportBusy&&Preparing file…} {exportError&&{exportError}}
)}
{/* ⭐⭐ W54-T08 (owner instruction 7) — THE WORD IS PAINTED, exactly like Refresh one line above and exactly like the Data module's own control, which renders its `fullscreenLabel` in a span beside the same mark. This used to be the mark alone. The string already flipped with the state, so only the paint was missing. */} {control("fullscreen", fullscreenLabel, <>{word(fullscreenLabel)}, toggleFullscreen, fullscreen)}
{!collapsed && (
{partitionRibbonGroups(activeGroups, visibleGroupCount, false)} {control("overflow", "More Groups", <>{word("More Groups")}, toggleOverflow, false, overflowOpen, hasOverflow ? "Y" : undefined, "gallery", undefined, "dialog")}
)} {!collapsed && (overflowOpen && hasOverflow ? ( {overflowContent} ) : ( ))} {/* ⭐⭐ W52-T17 (instruction 20, ruling R7) — mounted ONCE, absolutely positioned via its own `position: fixed` overlay (styles/wave52/ribbon.css), so it adds no layout of its own (the design contract's "appear without layout shift"). It reads this DOM tree through `containerRef` and never receives or mutates any of THIS component's own state. */}
); }