runloopable / web /src /sheet /FormatCellsDialog.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
2eae9f0 verified
Raw History Blame Contribute Delete
22.4 kB
// 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<CellBorderStyle, string>;
/** 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<CellBorderEdge, string> = {
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<HTMLTextAreaElement | HTMLInputElement>(
'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 (
<svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon sheet-border-icon">
<path d={GRID} strokeWidth="1" strokeDasharray="0.6 1.6" opacity="0.5" />
{h && <path d="M2.5 8H13.5" />}
{v && <path d="M8 2.5V13.5" />}
</svg>
);
}
const EDGE_ICON: Record<CellBorderEdge, () => ReactNode> = {
top: () => <IconBorderTop />,
insideH: () => <InsideIcon h v={false} />,
bottom: () => <IconBorderBottom />,
left: () => <IconBorderLeft />,
insideV: () => <InsideIcon h={false} v />,
right: () => <IconBorderRight />,
};
// ── 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<CellBorderEdge, [number, number, number, number]> = {
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 (
<path
d={`M${x1 - dx} ${y1 - dy}L${x2 - dx} ${y2 - dy}M${x1 + dx} ${y1 + dy}L${x2 + dx} ${y2 + dy}`}
strokeWidth="1"
{...common}
/>
);
}
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 (
<path
d={`M${x1} ${y1}L${x2} ${y2}`}
strokeWidth={width}
strokeDasharray={dash}
opacity={line.style === "hair" ? 0.7 : undefined}
{...common}
/>
);
}
/** A roving arrow-key handler for a row of radios or tabs: moves the choice and the focus. */
const rovingKeys = <T,>(
values: readonly T[],
current: T,
choose: (next: T) => void,
) => (e: ReactKeyboardEvent<HTMLElement>) => {
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<HTMLElement>('[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<FormatCellsTab>(tab);
// ── Number tab draft ──
const startFormat = style?.format ?? null;
const [kind, setKind] = useState<CellFormatKind>(startFormat?.kind ?? "general");
const [decimals, setDecimals] = useState<number>(
startFormat?.decimals ?? defaultDecimals(startFormat?.kind ?? "general") ?? 0,
);
const [thousands, setThousands] = useState<boolean>(startFormat?.thousands === true);
const [numberTouched, setNumberTouched] = useState(false);
const [sample] = useState(anchorSample);
// ── Border tab draft ──
const [line, setLine] = useState<CellBorderLine>(
LINE_HEX.test(startLine.color) ? startLine : { ...DEFAULT_BORDER_LINE },
);
const [edges, setEdges] = useState<EdgeDraft>({});
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 (
<button
key={edge}
type="button"
className={"sheet-format-cells-edge is-" + state}
aria-pressed={state === "set"}
aria-label={`${EDGE_LABEL[edge]}, ${state}`}
title={EDGE_LABEL[edge]}
data-edge={edge}
onClick={() => toggleEdge(edge)}
>
{EDGE_ICON[edge]()}
</button>
);
};
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 = (
<div className="sheet-format-cells-number">
<div className="sheet-format-cells-col">
<span className="sheet-format-cells-heading" id={`${ids}-category`}>Category</span>
<div
role="radiogroup"
aria-labelledby={`${ids}-category`}
className="sheet-format-cells-list"
onKeyDown={rovingKeys(CATEGORIES.map((c) => c.kind), kind, chooseKind)}
>
{CATEGORIES.map((entry) => (
<button
key={entry.kind}
type="button"
role="radio"
aria-checked={entry.kind === kind}
tabIndex={entry.kind === kind ? 0 : -1}
className={"sheet-format-cells-option" + (entry.kind === kind ? " is-on" : "")}
onClick={() => chooseKind(entry.kind)}
>
{entry.label}
</button>
))}
</div>
</div>
<div className="sheet-format-cells-col sheet-format-cells-detail">
<span className="sheet-format-cells-heading">Sample</span>
<output className="sheet-format-cells-sample" aria-live="polite">
{sampleText(sample.text, draftFormat())}
</output>
{!sample.fromCell && (
<p className="sheet-format-cells-note">A sample figure: the active cell holds no typed value.</p>
)}
{hasDecimals(kind) && (
<label className="sheet-format-cells-field">
<span>Decimal places</span>
<input
type="number"
min={0}
max={10}
step={1}
value={decimals}
className="sheet-format-cells-input"
onChange={(e) => {
const n = Math.round(Number(e.currentTarget.value));
setDecimals(Number.isFinite(n) ? Math.min(10, Math.max(0, n)) : 0);
setNumberTouched(true);
}}
/>
</label>
)}
{kind === "number" && (
<label className="sheet-format-cells-check">
<input
type="checkbox"
checked={thousands}
onChange={(e) => {
setThousands(e.currentTarget.checked);
setNumberTouched(true);
}}
/>
<span>Use 1000 separator (,)</span>
</label>
)}
{kind === "general" && (
<p className="sheet-format-cells-note">General cells show the value as it was typed.</p>
)}
</div>
</div>
);
const colorChoices = [{ hex: DEFAULT_BORDER_LINE.color, label: "Automatic" }, ...lineColors];
const borderPanel = (
<div className="sheet-format-cells-border">
<div className="sheet-format-cells-col">
<span className="sheet-format-cells-heading">Line</span>
<span className="sheet-format-cells-sub" id={`${ids}-style`}>Style</span>
<div
role="radiogroup"
aria-labelledby={`${ids}-style`}
className="sheet-format-cells-list sheet-format-cells-styles"
onKeyDown={rovingKeys(CELL_BORDER_STYLES, line.style, (s) => setLine((l) => ({ ...l, style: s })))}
>
{CELL_BORDER_STYLES.map((s) => (
<button
key={s}
type="button"
role="radio"
aria-checked={line.style === s}
aria-label={lineStyleLabel[s]}
title={lineStyleLabel[s]}
tabIndex={line.style === s ? 0 : -1}
className={"sheet-format-cells-option sheet-format-cells-style"
+ (line.style === s ? " is-on" : "")}
onClick={() => setLine((l) => ({ ...l, style: s }))}
>
<LineStyleSample style={s} />
</button>
))}
</div>
<span className="sheet-format-cells-sub" id={`${ids}-color`}>Color</span>
<div
role="radiogroup"
aria-labelledby={`${ids}-color`}
className="sheet-format-cells-swatches"
onKeyDown={rovingKeys(
colorChoices.map((c) => 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 (
<button
key={entry.label}
type="button"
role="radio"
aria-checked={on}
aria-label={entry.label}
title={entry.label}
tabIndex={roving ? 0 : -1}
className={"sheet-format-cells-swatch" + (on ? " is-on" : "")}
onClick={() => setLine((l) => ({ ...l, color: entry.hex }))}
>
<span className="sheet-format-cells-chip" style={{ background: entry.hex }} />
</button>
);
})}
</div>
<label className="sheet-format-cells-field sheet-format-cells-custom">
<input
type="color"
aria-label="More colors"
className="sheet-format-cells-color"
value={line.color}
onChange={(e) => {
const hex = e.currentTarget.value.toLowerCase();
if (LINE_HEX.test(hex)) setLine((l) => ({ ...l, color: hex }));
}}
/>
<span>More colors...</span>
</label>
</div>
<div className="sheet-format-cells-col">
<span className="sheet-format-cells-heading" id={`${ids}-presets`}>Presets</span>
<div className="sheet-format-cells-presets" role="group" aria-labelledby={`${ids}-presets`}>
<button type="button" className="sheet-format-cells-preset" onClick={() => preset("none")}>
<IconBorderNone />
<span>None</span>
</button>
<button type="button" className="sheet-format-cells-preset" onClick={() => preset("outline")}>
<IconBorderOutside />
<span>Outline</span>
</button>
<button type="button" className="sheet-format-cells-preset" onClick={() => preset("inside")}>
<InsideIcon h v />
<span>Inside</span>
</button>
</div>
<span className="sheet-format-cells-heading" id={`${ids}-border`}>Border</span>
<div className="sheet-format-cells-board" role="group" aria-labelledby={`${ids}-border`}>
<div className="sheet-format-cells-edges is-rows">
{edgeButton("top")}
{edgeButton("insideH")}
{edgeButton("bottom")}
</div>
<svg
viewBox={`0 0 ${PX1 + PX0} ${PY1 + PY0}`}
className="sheet-format-cells-preview"
aria-hidden="true"
>
{/* Excel's corner ticks: where each edge would run, drawn faint. */}
{ALL_EDGES.map((edge) => {
if (edges[edge]) return null;
const [x1, y1, x2, y2] = EDGE_SEGMENT[edge];
return (
<path
key={`guide-${edge}`}
d={`M${x1} ${y1}L${x2} ${y2}`}
className={"sheet-format-cells-guide" + (edges[edge] === null ? " is-cleared" : "")}
/>
);
})}
{ALL_EDGES.map((edge) => {
const set = edges[edge];
return set ? <PreviewLine key={`line-${edge}`} edge={edge} line={set} /> : null;
})}
{ALL_EDGES.map((edge) => {
const [x1, y1, x2, y2] = EDGE_SEGMENT[edge];
// The hit strip stops short of the corners, so a press near one is unambiguous.
const inset = 8;
const horizontal = y1 === y2;
const d = horizontal
? `M${x1 + inset} ${y1}L${x2 - inset} ${y2}`
: `M${x1} ${y1 + inset}L${x2} ${y2 - inset}`;
return (
<path
key={`hit-${edge}`}
d={d}
className="sheet-format-cells-hit"
data-edge={edge}
onClick={() => toggleEdge(edge)}
/>
);
})}
</svg>
<div className="sheet-format-cells-edges is-cols">
{edgeButton("left")}
{edgeButton("insideV")}
{edgeButton("right")}
</div>
</div>
<p className="sheet-format-cells-note">
Choose a line, then click a preset, the preview or the buttons beside it. Sides you
leave alone stay as they are.
</p>
</div>
</div>
);
const body = (
<div className="sheet-format-cells">
<div
role="tablist"
aria-label="Format Cells"
className="sheet-format-cells-tabs"
onKeyDown={rovingKeys(tabs.map((t) => t.id), active, setActive)}
>
{tabs.map((t) => (
<button
key={t.id}
type="button"
role="tab"
id={tabId(t.id)}
aria-selected={active === t.id}
aria-controls={panelId(t.id)}
tabIndex={active === t.id ? 0 : -1}
data-format-tab={t.id}
className={"sheet-format-cells-tab" + (active === t.id ? " is-on" : "")}
onClick={() => setActive(t.id)}
>
{t.label}
</button>
))}
</div>
<div className="sheet-format-cells-panels">
{tabs.map((t) => (
<div
key={t.id}
role="tabpanel"
id={panelId(t.id)}
aria-labelledby={tabId(t.id)}
hidden={active !== t.id}
className="sheet-format-cells-panel"
>
{t.id === "number" ? numberPanel : borderPanel}
</div>
))}
</div>
</div>
);
return (
<ConfirmDialog
open
title="Format Cells"
body={body}
confirmLabel="OK"
cancelLabel="Cancel"
tone="primary"
onConfirm={confirm}
onCancel={onClose}
/>
);
}