// sheet/FormatCellsDialog.tsx — Excel's Format Cells dialog, Number and Border tabs (S67-T16, // instruction 16, J16, contract C3). // // ⭐ WHO OPENS IT. "More Borders..." in the Borders gallery, and lane A's right-click "Format // Cells...", both raise `aios:sheet-format-cells` `{detail: {tab}}` (C3). `ribbonHome.tsx` owns the // one listener and MOUNTS this component; this file only draws the dialog and hands back ONE // patch. It holds no document state: the draft lives here until OK, and Cancel drops it whole. // // ⭐⭐ ONE RANGE EDIT, NAMING ONLY WHAT THE PERSON TOUCHED. The Border tab keeps a draft of // S67-T14's `CellBorderEdit["edges"]`: an edge the person SET carries a line, an edge they // CLEARED carries `null`, and an edge they never touched is simply ABSENT, so // `cellStyleOps.ts::styleCells` leaves it exactly as it is. OK sends that draft once, beside the // Number tab's `format` when that tab was changed too, so the whole dialog is one commit and one // undo step. // // ⚠ THE SHELL IS THE KIT'S `ui/ConfirmDialog.tsx`, which registers through `useOverlayLayer`: // Escape and the close button cancel, focus is trapped and returns to the opener, and a stray // press on the scrim never discards the draft. No keydown listener for Escape lives here. // // ⚠ DESIGN CONTRACT (DESIGN.md 2 through 4): chrome in sentence case except Excel's own names // ("Format Cells", the tab names, the preset names), inline SVG on `currentColor`, tokens for // every chrome colour. The line colours are the person's DATA (DESIGN.md 3) and are painted as // the hex they are. No em dash or en dash in any string that reaches a screen. import { useId, useState } from "react"; import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from "react"; import { ConfirmDialog } from "../ui/ConfirmDialog"; import { IconBorderBottom, IconBorderLeft, IconBorderNone, IconBorderOutside, IconBorderRight, IconBorderTop, LineStyleSample, } from "./borderIcons"; import { CELL_BORDER_STYLES, DEFAULT_BORDER_LINE, formatCellText } from "./types"; import type { Cell, CellBorderEdge, CellBorderEdit, CellBorderLine, CellBorderStyle, CellFormat, CellFormatKind, CellStyle, CellStylePatch, } from "./types"; import "../styles/wave67/format-cells.css"; export type FormatCellsTab = "number" | "border"; export interface FormatCellsDialogProps { /** The tab the request named. */ tab: FormatCellsTab; /** The ANCHOR cell's style, as the ribbon reads it. */ style: CellStyle | null; /** The line the dialog starts with: the ribbon's session pen. */ line: CellBorderLine; /** T15's Standard Colors row, handed in so there is one list, not two. */ lineColors: readonly { hex: string; label: string }[]; lineStyleLabel: Record; /** ONE patch for the selection. Called only when something changed. */ onApply: (patch: CellStylePatch) => void; onClose: () => void; } type EdgeDraft = CellBorderEdit["edges"]; const LINE_HEX = /^#[0-9a-f]{6}$/; /** Excel's dialog order and names for the five kinds the document carries. */ const CATEGORIES: { kind: CellFormatKind; label: string }[] = [ { kind: "general", label: "General" }, { kind: "number", label: "Number" }, { kind: "currency", label: "Currency" }, { kind: "date", label: "Date" }, { kind: "percent", label: "Percentage" }, ]; /** The ribbon's own defaults when a kind is chosen (`ribbonHome.tsx`, Number Format menu). */ const defaultDecimals = (kind: CellFormatKind): number | undefined => kind === "currency" ? 2 : kind === "date" || kind === "general" ? undefined : 0; const hasDecimals = (kind: CellFormatKind) => kind === "number" || kind === "currency" || kind === "percent"; const EDGE_LABEL: Record = { top: "Top border", insideH: "Inside horizontal border", bottom: "Bottom border", left: "Left border", insideV: "Inside vertical border", right: "Right border", }; const OUTER: CellBorderEdge[] = ["top", "bottom", "left", "right"]; const INSIDE: CellBorderEdge[] = ["insideH", "insideV"]; const ALL_EDGES: CellBorderEdge[] = [...OUTER, ...INSIDE]; const sameLine = (a: CellBorderLine, b: CellBorderLine) => a.style === b.style && a.color === b.color; /** * The anchor cell's value, for the Number tab's sample. The ribbon context carries the anchor's * STYLE and not its value, so the sample reads what the formula bar shows for the anchor. A * formula (its text starts with "=") or a blank cell falls back to a stated sample figure. */ const anchorSample = (): { text: string; fromCell: boolean } => { const bar = document.querySelector( 'textarea[aria-label="Formula"], input[aria-label="Formula"]', ); const text = bar?.value?.trim() ?? ""; if (!text || text.startsWith("=")) return { text: "", fromCell: false }; return { text, fromCell: true }; }; const sampleText = (raw: string, format: CellFormat | null): string => { const numeric = raw !== "" && Number.isFinite(Number(raw.replace(/,/g, ""))); const text = raw || (format?.kind === "date" ? new Date().toISOString().slice(0, 10) : "1234.5"); const value: unknown = numeric ? Number(raw.replace(/,/g, "")) : raw ? raw : text; const cell: Cell = { kind: "literal", state: "fresh", text, value, style: format ? { format } : undefined, }; return formatCellText(cell, text); }; // ── icons the gallery file does not carry, drawn in its house style ───────────────────────────── // `borderIcons.tsx` is S67-T15's file and has no Inside icon; these follow its cell exactly: // an 11 by 11 box split in four, faint dotted grid, solid where the control writes. const GRID = "M2.5 2.5H13.5M2.5 13.5H13.5M2.5 2.5V13.5M13.5 2.5V13.5M2.5 8H13.5M8 2.5V13.5"; function InsideIcon({ h, v }: { h: boolean; v: boolean }) { return ( ); } const EDGE_ICON: Record ReactNode> = { top: () => , insideH: () => , bottom: () => , left: () => , insideV: () => , right: () => , }; // ── the preview: a 2 by 2 block, so both inside edges exist ───────────────────────────────────── const PX0 = 16; const PX1 = 144; const PY0 = 12; const PY1 = 92; const PXM = (PX0 + PX1) / 2; const PYM = (PY0 + PY1) / 2; const EDGE_SEGMENT: Record = { top: [PX0, PY0, PX1, PY0], bottom: [PX0, PY1, PX1, PY1], left: [PX0, PY0, PX0, PY1], right: [PX1, PY0, PX1, PY1], insideH: [PX0, PYM, PX1, PYM], insideV: [PXM, PY0, PXM, PY1], }; /** One edge in its line, drawn the way `cellBorders.ts::paintCellBorders` paints it. */ function PreviewLine({ edge, line }: { edge: CellBorderEdge; line: CellBorderLine }) { const [x1, y1, x2, y2] = EDGE_SEGMENT[edge]; const common = { stroke: line.color, fill: "none", strokeLinecap: "butt" as const }; if (line.style === "double") { const horizontal = y1 === y2; const dx = horizontal ? 0 : 1.6; const dy = horizontal ? 1.6 : 0; return ( ); } const width = line.style === "medium" ? 2 : line.style === "thick" ? 3 : 1; const dash = line.style === "dashed" ? "5 3" : line.style === "dotted" ? "1 2" : line.style === "hair" ? "1 1" : undefined; return ( ); } /** A roving arrow-key handler for a row of radios or tabs: moves the choice and the focus. */ const rovingKeys = ( values: readonly T[], current: T, choose: (next: T) => void, ) => (e: ReactKeyboardEvent) => { const forward = e.key === "ArrowRight" || e.key === "ArrowDown"; const back = e.key === "ArrowLeft" || e.key === "ArrowUp"; if (!forward && !back && e.key !== "Home" && e.key !== "End") return; e.preventDefault(); e.stopPropagation(); const at = Math.max(0, values.indexOf(current)); const next = e.key === "Home" ? 0 : e.key === "End" ? values.length - 1 : (at + (forward ? 1 : -1) + values.length) % values.length; choose(values[next]); const group = e.currentTarget; window.requestAnimationFrame(() => { group.querySelector('[aria-checked="true"], [aria-selected="true"]')?.focus(); }); }; export function FormatCellsDialog({ tab, style, line: startLine, lineColors, lineStyleLabel, onApply, onClose, }: FormatCellsDialogProps) { const ids = useId(); const [active, setActive] = useState(tab); // ── Number tab draft ── const startFormat = style?.format ?? null; const [kind, setKind] = useState(startFormat?.kind ?? "general"); const [decimals, setDecimals] = useState( startFormat?.decimals ?? defaultDecimals(startFormat?.kind ?? "general") ?? 0, ); const [thousands, setThousands] = useState(startFormat?.thousands === true); const [numberTouched, setNumberTouched] = useState(false); const [sample] = useState(anchorSample); // ── Border tab draft ── const [line, setLine] = useState( LINE_HEX.test(startLine.color) ? startLine : { ...DEFAULT_BORDER_LINE }, ); const [edges, setEdges] = useState({}); const chooseKind = (next: CellFormatKind) => { setKind(next); setDecimals(defaultDecimals(next) ?? 0); setNumberTouched(true); }; const draftFormat = (): CellFormat | null => { if (kind === "general") return null; const next: CellFormat = { kind }; if (hasDecimals(kind)) next.decimals = decimals; if (kind === "number") next.thousands = thousands; if (kind === "currency" && startFormat?.kind === "currency" && startFormat.currency) { next.currency = startFormat.currency; } return next; }; const toggleEdge = (edge: CellBorderEdge) => { setEdges((was) => { const current = was[edge]; return { ...was, [edge]: current && sameLine(current, line) ? null : { ...line } }; }); }; const preset = (which: "none" | "outline" | "inside") => { setEdges((was) => { const next: EdgeDraft = { ...was }; if (which === "none") for (const edge of ALL_EDGES) next[edge] = null; else for (const edge of which === "outline" ? OUTER : INSIDE) next[edge] = { ...line }; return next; }); }; const confirm = () => { const patch: CellStylePatch = {}; if (numberTouched) patch.format = draftFormat(); if (Object.keys(edges).length > 0) patch.border = { edges: { ...edges } }; if (Object.keys(patch).length === 0) onClose(); else onApply(patch); }; const edgeState = (edge: CellBorderEdge) => edges[edge] === undefined ? "unchanged" : edges[edge] === null ? "cleared" : "set"; const edgeButton = (edge: CellBorderEdge) => { const state = edgeState(edge); return ( ); }; const tabs: { id: FormatCellsTab; label: string }[] = [ { id: "number", label: "Number" }, { id: "border", label: "Border" }, ]; const tabId = (id: FormatCellsTab) => `${ids}-tab-${id}`; const panelId = (id: FormatCellsTab) => `${ids}-panel-${id}`; const numberPanel = (
Category
c.kind), kind, chooseKind)} > {CATEGORIES.map((entry) => ( ))}
Sample {sampleText(sample.text, draftFormat())} {!sample.fromCell && (

A sample figure: the active cell holds no typed value.

)} {hasDecimals(kind) && ( )} {kind === "number" && ( )} {kind === "general" && (

General cells show the value as it was typed.

)}
); const colorChoices = [{ hex: DEFAULT_BORDER_LINE.color, label: "Automatic" }, ...lineColors]; const borderPanel = (
Line Style
setLine((l) => ({ ...l, style: s })))} > {CELL_BORDER_STYLES.map((s) => ( ))}
Color
c.hex), line.color, (hex) => setLine((l) => ({ ...l, color: hex })), )} > {colorChoices.map((entry, at) => { const on = line.color === entry.hex; const roving = on || (at === 0 && !colorChoices.some((c) => c.hex === line.color)); return ( ); })}
Presets
Border
{edgeButton("top")} {edgeButton("insideH")} {edgeButton("bottom")}
{edgeButton("left")} {edgeButton("insideV")} {edgeButton("right")}

Choose a line, then click a preset, the preview or the buttons beside it. Sides you leave alone stay as they are.

); const body = (
t.id), active, setActive)} > {tabs.map((t) => ( ))}
{tabs.map((t) => ( ))}
); return ( ); }