Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
File size: 22,381 Bytes
2eae9f0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 | // 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}
/>
);
}
|