// --------------------------------------------------------------------------------------------- // sheet/RulesDialog.tsx — W51-T18, the conditional formatting editor and the validation list // editor (contract C2, contract C8, rulings R1 and R8). // // ⭐⭐ TWO DIALOGS IN ONE FILE, AND THAT IS A FENCE DECISION SAID OUT LOUD. This ticket's `files` // list names `RulesDialog.tsx` and no second component file, and the validation editor is the // same shape as the rules editor wearing one control instead of a list: a base-kit dialog with a // body, a refusal line and one commit door. Putting it here keeps `SheetGrid.tsx` from growing a // third inline panel; the alternative was widening the ticket's own fence, which a worker may not // do. `ValidationDialog` is exported beside `RulesDialog` and neither knows about the other. // // ⛔⛔ CONTRACT C8, IN FULL. Both use `ui/ConfirmDialog::ConfirmDialog` as their SHELL: centred at // min(420px, 100vw - 32px), Cancel first and focused, Tab trapped, Escape and backdrop cancel, // focus returned to the opener. Nothing here writes a second Escape listener; `ConfirmDialog` // reaches the ONE arbiter through `useOverlayLayer`, and a `document.addEventListener` added in // this file would race it and win or lose on registration order. // // ⚠ THE SHELL GENUINELY CARRIES A LIST EDITOR, so no second dialog shape was built. Its `body` is // a `ReactNode` and its panel scrolls, which is what a hundred rules need. // // ⭐⭐ S67-T12 (instruction 9, journey J9): EXCEL'S RULES MANAGER, LIST THEN DETAIL. Every rule // used to be a fully expanded card, so fifty stored rules were fifty forms with no separation and // a refusal computed from the whole list on open. Now each rule is ONE summary row (what it tests, // its format preview, where it applies), clicking a row opens that rule's editor under it and // closes any other, and a refusal is raised only by Save and only on the row it belongs to. The // wider panel is `.lp-dialog:has(.sheet-rules)` in sheet-engine.css, the `:has()` precedent of // `wave59/templates.css`, so the kit's own markup is untouched. // // ⚠ DESIGN CONTRACT: sentence case, no ALL CAPS chrome, scale tokens only and no literal // font-size, colour tokens never hues, inline SVG on `currentColor` and no emoji, 150 ms ease-out // on opacity and transform, and no em dash or en dash in any string that reaches a screen. // --------------------------------------------------------------------------------------------- import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react"; import { ConfirmDialog } from "../ui/ConfirmDialog"; import { useCellRefHighlight } from "./refHighlight"; import { DEFAULT_BAR_FILL, DEFAULT_RULE_SCALE, RULE_FILLS, RULE_INKS, RULE_KIND_LABEL, RULE_OPS, RULE_OP_LABEL, RULE_SCALES, RULE_SCALE_MAX_TYPES, RULE_SCALE_MIN_TYPES, RULE_SCALE_TYPE_LABEL, addRule, blankRule, moveRule, rampBackground, rangeText, removeRule, ruleArity, ruleCondition, ruleKind, rulePaint, ruleRefusal, ruleSummary, scaleBackground, scaleEnds, updateRule, } from "./rules"; import { listText, parseList } from "./validation"; import { CELL_COLOUR_PATTERN, MAX_SHEET_RULES, MAX_VALIDATION_LIST, SHEET_RULE_KINDS } from "./types"; import type { SheetRule, SheetRuleKind, SheetRuleOp, SheetRuleScaleType } from "./types"; export interface RulesDialogProps { open: boolean; /** The rules the tab carries today. The dialog edits a DRAFT and commits it once. */ rules: readonly SheetRule[]; /** The selection's range, which is what a new rule opens with. `A1` when nothing is selected. */ range: string; onCancel: () => void; onSave: (rules: SheetRule[]) => void; } /** * ⚠ THE HOOKS LIVE BELOW THE `open` GATE, exactly as `ConfirmDialog` splits its own. The draft * has to START from the tab's rules every time the dialog opens, and a component that stays * mounted while closed would keep yesterday's draft and silently offer it back. */ export function RulesDialog({ open, rules, range, onCancel, onSave }: RulesDialogProps) { if (!open) return null; return ; } /** The chevron a move button wears. Inline SVG on `currentColor`, never a glyph and never an * emoji (DESIGN.md 4). One shape, rotated by CSS, so the pair cannot drift apart. */ function IconChevron() { return ( ); } /** The cross a delete button wears. Same vocabulary as the shortcuts panel's close. */ function IconRemove() { return ( ); } function RulesSurface({ rules, range, onCancel, onSave, }: Omit) { const [draft, setDraft] = useState(() => (rules ?? []).map((r) => ({ ...r }))); /** ⭐ S67-T12: ONE rule is edited at a time, as in Excel's Rules Manager. `null` = list only. */ const [openId, setOpenId] = useState(null); /** * ⛔⛔ S67-T12: A RULE'S REFUSAL IS RAISED BY SAVE AND WORN BY ITS OWN ROW. The dialog used to * compute `rulesRefusal(draft)` on every render, so a stored rule the editor could not represent * put a red sentence on the screen the moment the dialog opened, before anybody did anything, * and Save then stopped at that first rule and saved nothing. Nothing is judged on open now. */ const [flags, setFlags] = useState>({}); /** The cap's own refusal, which is raised by an ACT rather than by the draft's shape. */ const [notice, setNotice] = useState(""); const [colourRefusals, setColourRefusals] = useState>({}); const [reveal, setReveal] = useState(null); const rows = useRef(new Map()); const stored = useMemo(() => new Map((rules ?? []).map((r) => [r.id, r] as const)), [rules]); useEffect(() => { if (!reveal) return; rows.current.get(reveal)?.scrollIntoView({ block: "nearest" }); setReveal(null); }, [reveal]); const colourRefusal = useCallback((id: string, reason: string) => { setColourRefusals((current) => { if ((current[id] ?? "") === reason) return current; const next = { ...current }; if (reason) next[id] = reason; else delete next[id]; return next; }); }, []); const clearFlag = useCallback((id: string) => { setFlags((current) => { if (!(id in current)) return current; const next = { ...current }; delete next[id]; return next; }); }, []); const add = useCallback(() => { const out = addRule(draft, blankRule(range)); setNotice(out.refusal ?? ""); if (out.refusal) return; const id = out.rules[out.rules.length - 1].id; setDraft(out.rules); setOpenId(id); setReveal(id); }, [draft, range]); const patch = useCallback((id: string, next: Partial) => { setNotice(""); clearFlag(id); setDraft((current) => updateRule(current, id, next)); }, [clearFlag]); const flagged = Object.keys(flags).length > 0; /** * ⭐⭐ S67-T12: SAVE JUDGES EACH RULE ON ITS OWN, AND A BROKEN ONE NEVER HOLDS THE REST HOSTAGE. * * Only a rule ADDED or CHANGED in this dialog is judged: a rule the tab already stored and * nobody touched is saved exactly as it was stored, because the server accepted it and the * owner's complaint was a refusal about a rule he "didn't even do anything" to. The first press * flags every incomplete edited rule on its own row and saves nothing, so a person sees which * rules and why. A press while every incomplete rule is already flagged saves the others: a * flagged rule the tab already stored is kept as it was stored (this editor never deletes it), * and a flagged rule added in this dialog is left out. A rule that breaks after its row was * judged is flagged again rather than dropped unseen. */ const confirm = () => { if (Object.values(colourRefusals).some(Boolean)) return; const found: Record = {}; for (const rule of draft) { const was = stored.get(rule.id); if (was && JSON.stringify(was) === JSON.stringify(rule)) continue; const why = ruleRefusal(rule); if (why) found[rule.id] = why; } const ids = Object.keys(found); if (ids.length === 0) { onSave(draft); return; } if (ids.some((id) => flags[id] !== found[id])) { setFlags(found); setReveal(ids[0]); return; } onSave(draft.flatMap((rule) => { if (!found[rule.id]) return [rule]; const kept = stored.get(rule.id); return kept ? [kept] : []; })); }; return ( {/* ⭐⭐ THE ORDER RULE, SAID ON THE SURFACE THAT OWNS IT. Two rules matching one cell is ordinary, and a person who cannot see which one wins will reorder at random until the sheet looks right. `rules.ts::ruleStyleAt` stops at the first match and takes its whole style; this sentence is that behaviour in words. */}

The first rule that matches a cell paints it, and it paints the whole cell. Move a rule up to let it win.

{draft.length === 0 ? (

No rules yet.

) : (
{/* ⭐ S67-T12: EXCEL'S RULES MANAGER COLUMNS, in sentence case (DESIGN.md 2). */}
    {draft.map((rule, index) => ( { if (el) rows.current.set(rule.id, el); else rows.current.delete(rule.id); }} onToggle={() => setOpenId((current) => (current === rule.id ? null : rule.id))} onPatch={patch} onColourRefusal={colourRefusal} onMove={(delta) => { setNotice(""); setDraft((current) => moveRule(current, rule.id, delta)); }} onRemove={() => { setNotice(""); clearFlag(rule.id); setOpenId((current) => (current === rule.id ? null : current)); setDraft((current) => removeRule(current, rule.id)); }} /> ))}
)}
{draft.length} of {MAX_SHEET_RULES}
{notice ? (

{notice}

) : null} )} /> ); } /** * ⭐ S67-T12: THE FORMAT COLUMN. The paint a rule lays on a matching cell, drawn small: the fill, * the ink and the weight on sample text for a flat rule, the ramp for a colour scale, the bar for a * data bar. It reads the DRAFT, so changing a colour in the open editor repaints this at once. */ function RulePreview({ rule }: { rule: SheetRule }) { const kind = ruleKind(rule); if (kind === "scale") { return ( ); } if (kind === "bar") { return ( ); } const style = rule.style ?? {}; if (!style.fill && !style.color && style.bold !== true) { return No format; } return ( AaBbCc ); } interface RuleRowProps { rule: SheetRule; index: number; count: number; open: boolean; /** The refusal Save raised for this rule, or `""`. */ flag: string; /** Whether the tab already stored this rule, which decides what saving the others does to it. */ stored: boolean; rowRef: (el: HTMLLIElement | null) => void; onToggle: () => void; onPatch: (id: string, next: Partial) => void; onColourRefusal: (id: string, reason: string) => void; onMove: (delta: number) => void; onRemove: () => void; } /** * ⭐⭐ S67-T12: ONE SUMMARY ROW PER RULE, and the rule's editor opens UNDER its own row only when * that row is clicked. The row is a real button (`aria-expanded`), so Enter and Space open it too. */ function RuleRow({ rule, index, count, open, flag, stored, rowRef, onToggle, onPatch, onColourRefusal, onMove, onRemove, }: RuleRowProps) { const ids = useId(); const where = rangeText(rule.range); const condition = ruleCondition(rule); return (
  • {flag ? (

    {flag} {stored ? "Saving the other rules keeps this one as it was." : "Saving the other rules leaves this one out."}

    ) : null} {open ? ( ) : null}
  • ); } interface RuleEditorProps { rule: SheetRule; editorId: string; onPatch: (id: string, next: Partial) => void; onColourRefusal: (id: string, reason: string) => void; } function RuleEditor({ rule, editorId, onPatch, onColourRefusal }: RuleEditorProps) { const ids = useId(); const kind = ruleKind(rule); const arity = ruleArity(rule.op); // The OPEN rule's range and any cell its formula names are outlined on the grid // (refHighlight.ts). S67-T12: only the open rule, so fifty stored rules no longer outline at once. useCellRefHighlight([rangeText(rule.range), kind === "formula" ? String(rule.value ?? "") : ""]); /** * ⭐⭐ CHANGING THE KIND CHANGES WHAT THE RULE NEEDS TO BE COMPLETE, so it carries those needs * with it rather than leaving a half-formed rule the save would refuse with a sentence about a * control the card is no longer showing. A scale and a bar both ride `op: "between"`, which is * what makes the server persist their two bounds with no new field; a scale gains the default * ramp and a bar gains a fill. * * ⚠ `kind: undefined` IS HOW `cell` IS WRITTEN. It is the default and is stored as an absence * (`types.ts::SHEET_RULE_KINDS`), so a rule switched to a scale and back is byte for byte the * rule it started as. `JSON.stringify` drops an undefined value, which is what makes that true * all the way to the document rather than only in this component. */ const setKind = (next: SheetRuleKind) => { if (next === kind) return; if (next === "cell") { onPatch(rule.id, { kind: undefined }); return; } if (next === "formula") { onPatch(rule.id, { kind: next, op: "eq", value: "", value2: undefined, scale: undefined }); return; } // ⭐ S67-T13: a new colour scale spreads from the lowest to the highest value, Excel's // default, and carries no stale bound from the kind it was switched from. if (next === "scale") { onPatch(rule.id, { kind: next, op: "between", value: undefined, value2: undefined, scale: { ...(rule.scale ?? { low: DEFAULT_RULE_SCALE.low, high: DEFAULT_RULE_SCALE.high }), minType: "lowest", maxType: "highest", }, }); return; } onPatch(rule.id, { kind: next, op: "between", scale: rule.scale, style: next === "bar" ? { fill: rule.style?.fill || DEFAULT_BAR_FILL } : rule.style, }); }; return (
    {/* ⭐⭐ W54-T05 — THE KIND IS ON THE CARD, NOT HIDDEN BEHIND THE MENU THAT MADE IT. A colour scale and a data bar are created from the ribbon's Conditional formatting gallery, and an editor that could not represent them would have listed a rule it could not describe, or worse, quietly rewritten it into a condition nobody chose. */} {/* ⚠ S66-T12: a select field sizes to its longest label (`is-select`), so "Highlight cells" and "Is not empty" are never clipped by a shared flex row. */} {kind === "cell" ? ( ) : null} {kind === "formula" ? ( ) : null} {kind === "scale" ? ( <> ) : null} {kind !== "formula" && kind !== "scale" && arity >= 1 ? ( ) : null} {kind !== "formula" && kind !== "scale" && arity === 2 ? ( ) : null}
    {/* ⛔ THE PALETTE IS TOKEN NAMES (`rules.ts::RULE_FILLS` / `RULE_INKS`), the ribbon's own, so a palette change repaints every rule ever written. `var(--lp-*)` in the swatch is a token reference and never a hue (DESIGN.md 3). */} {/* ⭐ A SCALE CHOOSES A RAMP, NOT A COLOUR. Its two ends are what the document stores (`scale: {low, high}`) and the bands between them are looked up from those two names, so a person picks the ramp whole rather than assembling one end at a time and being left with a scale that runs from red to red. */} {kind === "scale" ? (
    Scale
    {RULE_SCALES.map((ramp) => { const on = rule.scale?.low === ramp.low && rule.scale?.high === ramp.high; return (
    ) : null} {/* ⚠ A SCALE PAINTS FROM ITS RAMP AND FROM NOTHING ELSE, so it is offered no flat fill, no ink and no weight: a control that wrote a key `ruleStyleAt` never reads for that kind is the fake affordance the ribbon's own contract refuses by name. A BAR keeps the fills, because a bar's colour IS its rule's fill, and loses the ink and the weight for the same reason. */} {kind === "bar" ? (
    Bar
    {RULE_FILLS.map((entry) => (
    ) : null} {kind === "cell" || kind === "formula" ? (
    Paint
    ) : null}
    ); } /** * ⭐⭐ S67-T13: ONE END OF A COLOUR SCALE, AS EXCEL'S RULES MANAGER EDITS IT. A type picker * (Lowest value / Highest value, Number, Percent, Percentile) and, unless the end is measured * from the data, the number that type needs. It reads through `rules.ts::scaleEnds`, so an * imported boundless scale opens as lowest to highest with nothing to fix. * * ⚠ TYPING PINS THE TYPE. A legacy scale's `number` end is read from its stored number, so * clearing that box without pinning would flip the end back to lowest under the cursor and hide * the box being typed in. */ function ScaleEndFields({ rule, which, onPatch }: { rule: SheetRule; which: "min" | "max"; onPatch: RuleEditorProps["onPatch"]; }) { const ids = useId(); const ends = scaleEnds(rule); const end = which === "min" ? ends.min : ends.max; const measured: SheetRuleScaleType = which === "min" ? "lowest" : "highest"; const offered = which === "min" ? RULE_SCALE_MIN_TYPES : RULE_SCALE_MAX_TYPES; const options = offered.includes(end.type) ? offered : [...offered, end.type]; const name = which === "min" ? "Minimum" : "Maximum"; const raw = which === "min" ? rule.value : rule.value2; const scale = rule.scale ?? { low: DEFAULT_RULE_SCALE.low, high: DEFAULT_RULE_SCALE.high }; const withType = (type: SheetRuleScaleType) => ( which === "min" ? { ...scale, minType: type } : { ...scale, maxType: type } ); const withValue = (value: string | undefined): Partial => ( which === "min" ? { value } : { value2: value } ); return ( <> {end.type !== "lowest" && end.type !== "highest" ? ( ) : null} ); } type RuleColourInput = HTMLInputElement & { lpApplyColour?: (value: string) => void }; // The ribbon uses native change: React onChange maps to input and would patch on every drag. // Refresh the callback on each render, but bind only once to each mounted input. const bindRuleColour = (apply: (value: string) => void) => (el: RuleColourInput | null) => { if (!el) return; el.lpApplyColour = apply; if (el.dataset.lpColourBound === "1") return; el.dataset.lpColourBound = "1"; el.addEventListener("change", () => el.lpApplyColour?.(el.value.toLowerCase())); }; function RuleColourControl({ rule, which, label, palette, onPatch, onRefusal }: { rule: SheetRule; which: "color" | "fill"; label: string; palette: readonly { token: string; label: string }[]; onPatch: RuleEditorProps["onPatch"]; onRefusal: RuleEditorProps["onColourRefusal"]; }) { const id = useId(); const chosen = rule.style?.[which]; const custom = chosen?.startsWith("#") ? chosen.toLowerCase() : ""; const [hex, setHex] = useState(custom); const [refusal, setRefusal] = useState(""); useEffect(() => { setHex(custom); setRefusal(""); onRefusal(id, ""); }, [custom, id, onRefusal]); useEffect(() => { return () => onRefusal(id, ""); }, [id, onRefusal]); const report = (reason: string) => { setRefusal(reason); onRefusal(id, reason); }; const hexRefusal = (value: string) => { const colour = value.trim().toLowerCase(); return colour.startsWith("#") && new RegExp(CELL_COLOUR_PATTERN).test(colour) ? "" : "Use a six digit hex colour, such as #C8A24B."; }; const choose = (colour: string | undefined) => { setHex(colour?.startsWith("#") ? colour : ""); report(""); onPatch(rule.id, { style: { ...rule.style, [which]: colour } }); }; const commitHex = (value: string) => { const reason = hexRefusal(value); if (reason) { report(reason); return; } choose(value.trim().toLowerCase()); }; return (
    {label}
    {palette.map((entry) => ( ))}
    { // The dialog learns of a half typed colour at once, so Save cannot slip past it, but // the line itself only appears on commit (blur or Enter), never mid word. const reason = e.target.value === custom ? "" : hexRefusal(e.target.value); setHex(e.target.value); onRefusal(id, reason); if (!reason) setRefusal(""); }} onBlur={() => { if (hex !== custom) commitHex(hex); }} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); commitHex(hex); } }} />
    {refusal ? : null}
    ); } // ── the validation list editor ──────────────────────────────────────────────────────────────── export interface ValidationDialogProps { open: boolean; /** How many cells the list is about to be set on, so the title can say what it will change. */ count: number; /** The list the anchor cell carries today, or an empty array. */ list: readonly string[]; onCancel: () => void; onSave: (list: string[]) => void; } /** The same `open` split, for the same reason: the draft starts from the cell every time. */ export function ValidationDialog({ open, count, list, onCancel, onSave }: ValidationDialogProps) { if (!open) return null; return ; } function ValidationSurface({ count, list, onCancel, onSave }: Omit) { const [text, setText] = useState(() => listText(list)); const [notice, setNotice] = useState(""); const boxId = useId(); const parsed = parseList(text); return ( { const out = parseList(text); if (out.refusal) { setNotice(out.refusal); return; } onSave(out.list); }} body={(