loopable / web /src /sheet /cellStyleOps.ts
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
a93637f verified
Raw History Blame Contribute Delete
16 kB
// ---------------------------------------------------------------------------------------------
// sheet/cellStyleOps.ts β€” THE STYLE WRITERS, LIFTED OUT OF `sheetState.ts`.
//
// ⭐ WAVE 54 BASE KIT β€” a SEAM, not a redesign. Every function below was moved verbatim out of
// `sheetState.ts`, comments and all, so that the lanes that write styles and the lanes that write
// values stop meeting in one 2,100 line file. `sheetState.ts` imports them straight back and
// re-exports them under their own names, so no consumer's import line changed and no behaviour did.
//
// β›” `pasteCells` DID NOT COME WITH THEM, ON PURPOSE. It writes VALUES, and it happens to carry a
// style along with each one; a paste is not a style act. It stays in `sheetState.ts` beside the
// other bulk value doors, which is where every reader already looks for it.
//
// ⚠ THE IMPORT OF `cellAt` POINTS BACK AT `sheetState.ts`, WHICH IS A CYCLE, AND IT IS SAFE FOR
// ONE REASON WORTH WRITING DOWN. Nothing here reads that module at LOAD time: `cellAt` is called
// from inside a function body, so by the time anybody calls `styleCells` both modules are fully
// evaluated. `verify_api.py` compiles this file to CommonJS beside `sheetState.js` and RUNS it,
// which is where a load-time cycle would show up as `undefined is not a function`.
//
// ⚠ AND THAT RUN HAS NOT HAPPENED YET, SO SAY SO RATHER THAN IMPLY IT. The wave-54 base worktree
// carries no `web/node_modules`, so the compile-and-run half of that gate could not execute on
// the change that created this file. The cycle is safe by CONSTRUCTION, which is an argument;
// the first tree with dependencies installed is where it becomes evidence.
//
// β›” AND NOTHING HERE MAY IMPORT OUTSIDE `src/sheet/`. tsc's emitted ROOT moves with the import
// graph, so one `../ui/*` import would drop every emitted module a level down and break every
// `require` path the battery's Sheet proofs use. [[tsc-outdir-root-moves-with-the-import-graph]]
// ---------------------------------------------------------------------------------------------
import type {
Cell, CellBorder, CellBorderEdit, CellBorderLine, CellStyle, CellStylePatch, SheetTab,
} from "./types";
import { applyBorderEdges, applyStylePatch, isBorderEdit } from "./types";
import { addressOf, cellAt, splitAddress } from "./sheetState";
import type { BulkEdit } from "./sheetState";
// ═════════════════════════════════════════════════════════════════════════════════════════════
// W51-T16 β€” THE STYLE ENGINE AND THE RIBBON'S ACTS, ALL OF THEM PURE (contract C2, D-641).
//
// ⭐⭐ WHY THE PURE HALF IS HERE AND NOT IN THE COMPONENT. `SheetGrid.tsx` imports glide, which
// cannot be loaded under node, so anything living there can only ever be GREPPED by a gate. Every
// function below is executed by `verify_api.py`'s compile-and-run harness instead, which is what
// lets the battery prove that AutoSum picks the right range and that styling a blank block leaves
// `handTypedCount` alone, rather than proving that the words appear in a file.
//
// β›”β›” THE ONE NUMBER THIS SECTION MUST NOT MOVE. The sheet PRINTS its hand typed count on the
// screen (`handTypedLabel`, `.sheet-grid-literals`), and `handTypedCount` counts every
// `kind: "literal"` cell. So a styled blank is `kind: "empty"` and nothing here may take a
// shortcut through `literal`: bolding twenty blank cells and claiming twenty typed values would
// be a lie the owner reads straight off the header.
// ═════════════════════════════════════════════════════════════════════════════════════════════
/**
* ⭐⭐ D-641, AND IT IS THE WHOLE TICKET: FORMATTING APPLIES TO EMPTY CELLS.
*
* W50-T19's `applyStyle` carried `if (!cell) continue`, so selecting three blank cells and
* pressing Borders painted nothing. It could not do otherwise at the time: creating a cell would
* have meant `kind: "literal"`, and the count on the header would have risen by three. C2's
* `empty` kind is what removes that trade.
*
* β›” IT PRUNES ITS OWN CREATIONS. A patch that leaves an empty cell with no style at all removes
* the cell rather than storing `{kind: "empty", state: "fresh"}`, which is a document the server
* would keep forever and which means exactly what an absence means.
*
* ⚠ R19 / R20, DECIDED IN W50-T19 AND UNCHANGED: styling a BOUND cell is allowed and is NOT a
* conversion. A colour changes nothing about where the value comes from, so a cell's KIND is
* deliberately not consulted here at all β€” the opposite of what R5 (W52-T09) made every EDIT
* door do, which is write a bound cell exactly as it writes any other one.
*/
export const styleCells = (
tab: SheetTab | null | undefined,
addrs: readonly string[],
patch: CellStylePatch,
): BulkEdit => {
// ⭐ S67-T14: a RANGE border edit is not a per cell patch. The other keys go through the loop
// below exactly as before; the edit is then laid over the result as ONE block.
if (isBorderEdit(patch.border)) {
const { border: edit, ...rest } = patch;
const first = Object.keys(rest).length > 0 ? styleCells(tab, addrs, rest).edits : {};
const rect = boundingRect(addrs);
if (!rect) return { edits: first };
const cells: Record<string, Cell> = { ...(tab?.cells ?? {}) };
for (const [addr, cell] of Object.entries(first)) {
if (cell) cells[addr] = cell;
else delete cells[addr];
}
const view = { ...(tab ?? {}), cells } as SheetTab;
return { edits: { ...first, ...borderEdits(view, rect, edit).edits } };
}
const edits: Record<string, Cell | null> = {};
for (const addr of addrs) {
const cell = cellAt(tab, addr);
const style = applyStylePatch(cell?.style, patch);
if (!cell) {
// THE LINE D-641 ASKED FOR. A blank address becomes a style-only cell, and only when the
// patch actually left a style on it.
if (style) edits[addr] = { kind: "empty", state: "fresh", style };
continue;
}
if (cell.kind === "empty" && !style && !cell.validation) {
edits[addr] = null;
continue;
}
const next: Cell = { ...cell };
if (style) next.style = style;
else delete next.style;
if (Object.prototype.hasOwnProperty.call(patch, "format") && next.formulaMeta?.inferredFormat) {
next.formulaMeta = { ...next.formulaMeta };
delete next.formulaMeta.inferredFormat;
}
edits[addr] = next;
}
return { edits };
};
/** A zero based, inclusive rectangle of cells, spelled as a rule's and a chart's are. */
export interface BorderRect { col0: number; row0: number; col1: number; row1: number }
/** The bounding rectangle of a set of A1 addresses, or `null` when none of them is an address. */
export const boundingRect = (addrs: readonly string[]): BorderRect | null => {
let rect: BorderRect | null = null;
for (const addr of addrs) {
const at = splitAddress(addr);
if (!at) continue;
const col = at.col - 1;
const row = at.row - 1;
rect = rect
? { col0: Math.min(rect.col0, col), row0: Math.min(rect.row0, row),
col1: Math.max(rect.col1, col), row1: Math.max(rect.row1, row) }
: { col0: col, row0: row, col1: col, row1: row };
}
return rect;
};
type SideEdits = Partial<Record<keyof CellBorder, CellBorderLine | null>>;
/**
* ⭐⭐ S67-T14: BORDER A RANGE AS ONE BLOCK, THE WAY EXCEL DOES. Pure: tab and edit in, edits out.
*
* - an OUTER edge (`top`, `bottom`, `left`, `right`) goes on that side of the range's edge cells,
* and the FACING side of the neighbour just outside the range is CLEARED whenever the edge is
* set or cleared: one visible edge has one owner, so No Border also removes a line a
* neighbour drew on the shared edge;
* - an INSIDE edge (`insideH`, `insideV`) sets, or clears, BOTH facing sides of every inner
* boundary, which is Excel's own per cell storage;
* - an edge NOT NAMED is untouched, which is why Top on a boxed range keeps the box.
*
* A style only cell whose style empties is removed, exactly as {@link styleCells} prunes.
*/
export const borderEdits = (
tab: SheetTab | null | undefined,
rect: BorderRect,
edit: CellBorderEdit,
): BulkEdit => {
const col0 = Math.min(rect.col0, rect.col1);
const col1 = Math.max(rect.col0, rect.col1);
const row0 = Math.min(rect.row0, rect.row1);
const row1 = Math.max(rect.row0, rect.row1);
const edges = edit.edges ?? {};
const plan = new Map<string, SideEdits>();
const put = (col: number, row: number, side: keyof CellBorder, line: CellBorderLine | null) => {
if (col < 0 || row < 0) return;
const addr = addressOf(col, row);
plan.set(addr, { ...(plan.get(addr) ?? {}), [side]: line });
};
const named = (edge: keyof typeof edges) => Object.prototype.hasOwnProperty.call(edges, edge);
const lineOf = (edge: keyof typeof edges) => edges[edge] ?? null;
// The outer edges: the range's own side, then the neighbour's facing side cleared.
for (let c = col0; c <= col1; c += 1) {
if (named("top")) { put(c, row0, "top", lineOf("top")); put(c, row0 - 1, "bottom", null); }
if (named("bottom")) { put(c, row1, "bottom", lineOf("bottom")); put(c, row1 + 1, "top", null); }
}
for (let r = row0; r <= row1; r += 1) {
if (named("left")) { put(col0, r, "left", lineOf("left")); put(col0 - 1, r, "right", null); }
if (named("right")) { put(col1, r, "right", lineOf("right")); put(col1 + 1, r, "left", null); }
}
// The inside lines: both facing sides of every inner boundary.
if (named("insideH")) {
for (let r = row0; r < row1; r += 1) for (let c = col0; c <= col1; c += 1) {
put(c, r, "bottom", lineOf("insideH"));
put(c, r + 1, "top", lineOf("insideH"));
}
}
if (named("insideV")) {
for (let c = col0; c < col1; c += 1) for (let r = row0; r <= row1; r += 1) {
put(c, r, "right", lineOf("insideV"));
put(c + 1, r, "left", lineOf("insideV"));
}
}
const edits: Record<string, Cell | null> = {};
for (const [addr, sides] of plan) {
const cell = cellAt(tab, addr);
const before = cell?.style?.border;
// A clear that meets nothing is not an edit: a neighbour with no line on that side is left
// byte for byte alone rather than rewritten as itself.
const touches = Object.entries(sides).some(([side, line]) =>
line !== null || (before && side in before));
if (!touches) continue;
const border = applyBorderEdges(before, sides);
const style = applyStylePatch(cell?.style, { border: border ?? null });
if (!cell) {
if (style) edits[addr] = { kind: "empty", state: "fresh", style };
continue;
}
if (cell.kind === "empty" && !style && !cell.validation) {
edits[addr] = null;
continue;
}
const next: Cell = { ...cell };
if (style) next.style = style;
else delete next.style;
edits[addr] = next;
}
return { edits };
};
/**
* CLEAR FORMATS: the value stays, the styling goes. A cell that was ONLY styling disappears with
* it, because a `kind: "empty"` cell carrying no style is an absence written down.
*/
export const clearFormats = (
tab: SheetTab | null | undefined,
addrs: readonly string[],
): BulkEdit => {
const edits: Record<string, Cell | null> = {};
for (const addr of addrs) {
const cell = cellAt(tab, addr);
if (!cell || !cell.style) continue;
if (cell.kind === "empty" && !cell.validation) {
edits[addr] = null;
continue;
}
const next: Cell = { ...cell };
delete next.style;
if (next.formulaMeta?.inferredFormat) {
next.formulaMeta = { ...next.formulaMeta };
delete next.formulaMeta.inferredFormat;
}
edits[addr] = next;
}
return { edits };
};
/**
* CLEAR ALL: the value AND the styling. This is the only one of the three that empties the map.
*
* ⭐⭐ R5 (W52-T09): NO WALL HERE EITHER, ANY MORE. A bound cell clears exactly like any other:
* its whole record is removed, value and binding together. {@link clearFormats} never needed a
* wall in the first place, since removing a colour from a bound cell leaves it reading from
* exactly the database it read before.
*/
export const clearAll = (
tab: SheetTab | null | undefined,
addrs: readonly string[],
): BulkEdit => {
const edits: Record<string, Cell | null> = {};
for (const addr of addrs) {
const cell = cellAt(tab, addr);
if (!cell) continue;
edits[addr] = null;
}
return { edits };
};
/** The style a Format painter picked up. `null` when the cell it was picked from carries none. */
export const styleOf = (cell: Cell | null | undefined): CellStyle | null =>
cell?.style ? { ...cell.style } : null;
/** R12: the address is the cell-map key. Copy every payload property, including future ones. */
export const copyCell = (cell: Cell | null | undefined): Cell | null =>
cell ? structuredClone(cell) : null;
/** Replace only a cell's formatting layer, preserving content and every other target layer. */
export const replaceCellStyle = (
cell: Cell | null | undefined,
style: CellStyle | null | undefined,
): Cell | null => {
if (style) {
const base: Cell = cell ?? { kind: "empty", state: "fresh" };
const next = { ...base, style: { ...style }, formulaMeta: { ...base.formulaMeta } };
delete next.formulaMeta.inferredFormat;
return next;
}
if (!cell?.style) return cell ?? null;
const next: Cell = { ...cell };
delete next.style;
if (next.formulaMeta?.inferredFormat) {
next.formulaMeta = { ...next.formulaMeta };
delete next.formulaMeta.inferredFormat;
}
if (next.kind === "empty" && !next.validation && !next.link && !next.note && !next.sparkline) {
return null;
}
return next;
};
/**
* β›”β›” EVERY KEY `CellStyle` CARRIES, AND A MISSING ONE IS A SILENT HALF-PAINT. The Format painter
* REPLACES a style rather than merging into it, so it has to say `null` for the keys the picked
* up style does not have. A key absent from this list is a key the painter leaves behind: paint a
* plain cell's format onto a bold one and the target stays bold, which reads as the painter
* having half worked and is the harder defect to notice.
*/
export const STYLE_KEYS = [
"bold", "italic", "underline", "color", "fill", "align", "format", "border",
// ⭐ W54-T03 / R10 ADDS `font`, AND IT HAD TO BE ADDED HERE IN THE SAME CHANGE THAT FIRST
// WROTE IT. `types.ts`'s own note on `textRotation` states the rule this obeys: the lane that
// first writes a style key names it here, or the painter leaves that key behind on every cell
// it paints over. Paint a Georgia cell's style onto an Arial one and the target would have
// stayed Arial, which reads as the painter having half worked.
// ⭐⭐ W54-T06 ADDS `textRotation`, AND IT IS THE KEY THIS LIST'S OWN NOTE WAS WRITTEN ABOUT.
// The base kit declared the slot and left it out of here on purpose, because nothing wrote it
// yet; this lane's Orientation gallery is the first writer, so the name lands in the SAME
// change. Paint a horizontal cell's style onto a cell turned 45 degrees and, without this, the
// target would have stayed turned while every other key was replaced.
"valign", "wrap", "indent", "size", "font", "textRotation",
] as const;
/** The patch that makes a cell's style EQUAL to `style`, clearing everything `style` omits. */
export const paintPatch = (style: CellStyle | null | undefined): CellStylePatch => {
const source = (style ?? {}) as Record<string, unknown>;
const patch: Record<string, unknown> = {};
for (const key of STYLE_KEYS) patch[key] = source[key] ?? null;
return patch as CellStylePatch;
};