loopable / web /src /sheet /RulesDialog.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
a93637f verified
Raw History Blame
37.8 kB
// ---------------------------------------------------------------------------------------------
// 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 <RulesSurface rules={rules} range={range} onCancel={onCancel} onSave={onSave} />;
}
/** 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 (
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false" className="sheet-rules-icon">
<path d="M4 10l4-4 4 4" fill="none" stroke="currentColor" strokeWidth="1.6"
strokeLinecap="round" strokeLinejoin="round" />
</svg>
);
}
/** The cross a delete button wears. Same vocabulary as the shortcuts panel's close. */
function IconRemove() {
return (
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false" className="sheet-rules-icon">
<path d="M4 4l8 8M12 4l-8 8" fill="none" stroke="currentColor" strokeWidth="1.6"
strokeLinecap="round" />
</svg>
);
}
function RulesSurface({
rules, range, onCancel, onSave,
}: Omit<RulesDialogProps, "open">) {
const [draft, setDraft] = useState<SheetRule[]>(() => (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<string | null>(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<Record<string, string>>({});
/** 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<Record<string, string>>({});
const [reveal, setReveal] = useState<string | null>(null);
const rows = useRef(new Map<string, HTMLLIElement>());
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<SheetRule>) => {
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<string, string> = {};
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 (
<ConfirmDialog
open
title="Conditional formatting"
tone="primary"
cancelLabel="Cancel"
confirmLabel={flagged ? "Save the other rules" : "Save rules"}
onCancel={onCancel}
onConfirm={confirm}
body={(
<div className="sheet-rules">
{/* ⭐⭐ 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. */}
<p className="sheet-rules-note">
The first rule that matches a cell paints it, and it paints the whole cell. Move a rule
up to let it win.
</p>
{draft.length === 0 ? (
<p className="sheet-rules-empty">No rules yet.</p>
) : (
<div className="sheet-rules-table">
{/* ⭐ S67-T12: EXCEL'S RULES MANAGER COLUMNS, in sentence case (DESIGN.md 2). */}
<div className="sheet-rules-head" aria-hidden="true">
<span />
<span>Rule</span>
<span>Format</span>
<span>Applies to</span>
<span />
</div>
<ol className="sheet-rules-list" aria-label="Rules, in the order they apply">
{draft.map((rule, index) => (
<RuleRow
key={rule.id}
rule={rule}
index={index}
count={draft.length}
open={openId === rule.id}
flag={flags[rule.id] ?? ""}
stored={stored.has(rule.id)}
rowRef={(el) => {
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));
}}
/>
))}
</ol>
</div>
)}
<div className="sheet-rules-foot">
<button type="button" className="sheet-rules-add" onClick={add}>
Add a rule
</button>
<span className="sheet-rules-count">
{draft.length} of {MAX_SHEET_RULES}
</span>
</div>
{notice ? (
<p className="sheet-rules-refusal" role="alert">{notice}</p>
) : null}
</div>
)}
/>
);
}
/**
* ⭐ 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 (
<span className="sheet-rules-preview is-ramp" role="img" aria-label="Colour scale"
style={{ background: scaleBackground(rule) }} />
);
}
if (kind === "bar") {
return (
<span className="sheet-rules-preview is-bar" role="img" aria-label="Data bar">
<span className="sheet-rules-preview-bar" style={{ background: rulePaint(rule.style?.fill) }} />
</span>
);
}
const style = rule.style ?? {};
if (!style.fill && !style.color && style.bold !== true) {
return <span className="sheet-rules-preview is-none">No format</span>;
}
return (
<span className={"sheet-rules-preview" + (style.bold ? " is-bold" : "")}
style={{ background: rulePaint(style.fill), color: rulePaint(style.color) }}>
AaBbCc
</span>
);
}
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<SheetRule>) => 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 (
<li ref={rowRef}
className={"sheet-rules-card" + (open ? " is-open" : "") + (flag ? " is-flagged" : "")}>
<div className="sheet-rules-line">
<span className="sheet-rules-order" aria-hidden="true">{index + 1}</span>
<button
type="button"
className="sheet-rules-pick"
aria-expanded={open}
aria-controls={open ? `${ids}-editor` : undefined}
aria-describedby={flag ? `${ids}-flag` : undefined}
aria-label={`Rule ${index + 1}: ${ruleSummary(rule)}`}
onClick={onToggle}
>
<span className="sheet-rules-summary" title={condition}>{condition}</span>
<RulePreview rule={rule} />
<span className="sheet-rules-where" title={where}>{where}</span>
</button>
<div className="sheet-rules-moves">
<button
type="button"
className="sheet-rules-move"
aria-label={`Move rule ${index + 1} up`}
title="Move up"
disabled={index === 0}
onClick={() => onMove(-1)}
>
<IconChevron />
</button>
<button
type="button"
className="sheet-rules-move is-down"
aria-label={`Move rule ${index + 1} down`}
title="Move down"
disabled={index === count - 1}
onClick={() => onMove(1)}
>
<IconChevron />
</button>
<button
type="button"
className="sheet-rules-remove"
aria-label={`Delete rule ${index + 1}`}
title="Delete this rule"
onClick={onRemove}
>
<IconRemove />
</button>
</div>
</div>
{flag ? (
<p className="sheet-rules-flag" id={`${ids}-flag`}>
{flag} {stored
? "Saving the other rules keeps this one as it was."
: "Saving the other rules leaves this one out."}
</p>
) : null}
{open ? (
<RuleEditor rule={rule} editorId={`${ids}-editor`} onPatch={onPatch}
onColourRefusal={onColourRefusal} />
) : null}
</li>
);
}
interface RuleEditorProps {
rule: SheetRule;
editorId: string;
onPatch: (id: string, next: Partial<SheetRule>) => 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 (
<div className="sheet-rules-editor" id={editorId}>
<div className="sheet-rules-row">
<label className="sheet-rules-field">
<span className="sheet-rules-label" id={`${ids}-range`}>Applies to</span>
<input
className="sheet-rules-input"
type="text"
value={rangeText(rule.range)}
aria-labelledby={`${ids}-range`}
placeholder="B2:D40"
onChange={(e) => onPatch(rule.id, { range: e.target.value })}
/>
</label>
</div>
<div className="sheet-rules-row">
{/* ⭐⭐ 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. */}
<label className="sheet-rules-field is-select">
<span className="sheet-rules-label" id={`${ids}-kind`}>Rule</span>
<select
className="sheet-rules-select"
value={kind}
aria-labelledby={`${ids}-kind`}
onChange={(e) => setKind(e.target.value as SheetRuleKind)}
>
{SHEET_RULE_KINDS.map((entry) => (
<option key={entry} value={entry}>{RULE_KIND_LABEL[entry]}</option>
))}
</select>
</label>
{kind === "cell" ? (
<label className="sheet-rules-field is-select">
<span className="sheet-rules-label" id={`${ids}-op`}>Condition</span>
<select
className="sheet-rules-select"
value={rule.op}
aria-labelledby={`${ids}-op`}
onChange={(e) => onPatch(rule.id, { op: e.target.value as SheetRuleOp })}
>
{RULE_OPS.map((op) => (
<option key={op} value={op}>{RULE_OP_LABEL[op]}</option>
))}
</select>
</label>
) : null}
{kind === "formula" ? (
<label className="sheet-rules-field">
<span className="sheet-rules-label">Formula</span>
<input
className="sheet-field sheet-rules-input"
type="text"
value={String(rule.value ?? "")}
aria-label="Formula"
placeholder="=$C8<0"
onChange={(e) => onPatch(rule.id, { op: "eq", value: e.target.value })}
/>
</label>
) : null}
{kind === "scale" ? (
<>
<ScaleEndFields rule={rule} which="min" onPatch={onPatch} />
<ScaleEndFields rule={rule} which="max" onPatch={onPatch} />
</>
) : null}
{kind !== "formula" && kind !== "scale" && arity >= 1 ? (
<label className="sheet-rules-field">
<span className="sheet-rules-label" id={`${ids}-value`}>
{arity === 2 ? "From" : "Value"}
</span>
<input
className="sheet-rules-input"
type="text"
value={String(rule.value ?? "")}
aria-labelledby={`${ids}-value`}
onChange={(e) => onPatch(rule.id, { value: e.target.value })}
/>
</label>
) : null}
{kind !== "formula" && kind !== "scale" && arity === 2 ? (
<label className="sheet-rules-field">
<span className="sheet-rules-label" id={`${ids}-value2`}>To</span>
<input
className="sheet-rules-input"
type="text"
value={String(rule.value2 ?? "")}
aria-labelledby={`${ids}-value2`}
onChange={(e) => onPatch(rule.id, { value2: e.target.value })}
/>
</label>
) : null}
</div>
{/* β›” 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" ? (
<div className="sheet-rules-row sheet-rules-paint">
<span className="sheet-rules-label">Scale</span>
<div className="sheet-rules-swatches" role="group" aria-label="Colour scale">
{RULE_SCALES.map((ramp) => {
const on = rule.scale?.low === ramp.low && rule.scale?.high === ramp.high;
return (
<button
key={ramp.id}
type="button"
className={"sheet-rules-swatch" + (on ? " is-on" : "")}
style={{ background: rampBackground(ramp.bands) }}
aria-label={ramp.label}
aria-pressed={on}
title={ramp.label}
onClick={() => onPatch(rule.id, {
scale: { ...rule.scale, low: ramp.low, high: ramp.high },
})}
/>
);
})}
</div>
</div>
) : 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" ? (
<div className="sheet-rules-row sheet-rules-paint">
<span className="sheet-rules-label">Bar</span>
<div className="sheet-rules-swatches" role="group" aria-label="Fill colour">
{RULE_FILLS.map((entry) => (
<button
key={entry.token}
type="button"
className={"sheet-rules-swatch" + (rule.style?.fill === entry.token ? " is-on" : "")}
style={{ background: `var(${entry.token})` }}
aria-label={`${entry.label} fill`}
aria-pressed={rule.style?.fill === entry.token}
title={`${entry.label} fill`}
onClick={() => onPatch(rule.id, {
style: {
...rule.style,
fill: rule.style?.fill === entry.token ? undefined : entry.token,
},
})}
/>
))}
</div>
</div>
) : null}
{kind === "cell" || kind === "formula" ? (
<div className="sheet-rules-field" role="group" aria-label="Paint">
<div className="sheet-rules-row sheet-rules-paint">
<span className="sheet-rules-label">Paint</span>
<button
type="button"
className={"sheet-rules-bold" + (rule.style?.bold ? " is-on" : "")}
aria-pressed={rule.style?.bold === true}
aria-label="Bold"
title="Bold"
onClick={() => onPatch(rule.id, {
style: { ...rule.style, bold: rule.style?.bold ? undefined : true },
})}
>
B
</button>
</div>
<RuleColourControl rule={rule} which="color" label="Font colour"
palette={RULE_INKS} onPatch={onPatch} onRefusal={onColourRefusal} />
<RuleColourControl rule={rule} which="fill" label="Fill colour"
palette={RULE_FILLS} onPatch={onPatch} onRefusal={onColourRefusal} />
</div>
) : null}
</div>
);
}
/**
* ⭐⭐ 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<SheetRule> => (
which === "min" ? { value } : { value2: value }
);
return (
<>
<label className="sheet-rules-field is-select">
<span className="sheet-rules-label" id={`${ids}-type`}>{name}</span>
<select
className="sheet-rules-select"
value={end.type}
aria-labelledby={`${ids}-type`}
onChange={(e) => {
const type = e.target.value as SheetRuleScaleType;
onPatch(rule.id, {
scale: withType(type),
...(type === measured ? withValue(undefined) : {}),
});
}}
>
{options.map((type) => (
<option key={type} value={type}>{RULE_SCALE_TYPE_LABEL[type]}</option>
))}
</select>
</label>
{end.type !== "lowest" && end.type !== "highest" ? (
<label className="sheet-rules-field">
<span className="sheet-rules-label" id={`${ids}-value`}>Value</span>
<input
className="sheet-rules-input"
type="text"
inputMode="decimal"
value={String(raw ?? "")}
aria-label={`${name} value`}
placeholder={end.type === "number" ? "" : "0 to 100"}
onChange={(e) => onPatch(rule.id, {
scale: withType(end.type),
...withValue(e.target.value),
})}
/>
</label>
) : 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 (
<div className="sheet-rules-field" role="group" aria-labelledby={`${id}-label`}>
<div className="sheet-rules-row sheet-rules-paint">
<span className="sheet-rules-label" id={`${id}-label`}>{label}</span>
<button type="button" className="sheet-rules-add" aria-pressed={!chosen}
onClick={() => choose(undefined)}>None</button>
</div>
<div className="sheet-rules-row sheet-rules-paint">
<div className="sheet-rules-swatches">
{palette.map((entry) => (
<button key={entry.token} type="button"
className={"sheet-rules-swatch" + (which === "color" ? " is-ink" : "")
+ (chosen === entry.token ? " is-on" : "")}
style={which === "color" ? { color: `var(${entry.token})` }
: { background: `var(${entry.token})` }}
aria-label={`${entry.label} ${which === "color" ? "text" : "fill"}`}
aria-pressed={chosen === entry.token}
title={entry.label}
onClick={() => choose(chosen === entry.token ? undefined : entry.token)}
>
{which === "color" ? "A" : null}
</button>
))}
</div>
<label className="sheet-rules-row sheet-rules-paint">
<input type="color"
key={chosen || "none"}
className={"sheet-ribbon-custom-input sheet-rules-swatch" + (custom ? " is-on" : "")}
aria-label={`Custom ${label.toLowerCase()}`}
title={custom || "Choose a custom colour"}
style={{ background: custom || undefined }}
defaultValue={custom || (which === "color" ? "#000000" : "#ffffff")}
ref={bindRuleColour(commitHex)}
/>
<span className="sheet-rules-label">Custom</span>
</label>
</div>
<div className="sheet-rules-field">
<input type="text" className="sheet-rules-input" aria-label={`${label} hex`}
aria-invalid={Boolean(refusal)} aria-describedby={refusal ? `${id}-refusal` : undefined}
value={hex} placeholder="#rrggbb" spellCheck={false}
onChange={(e) => {
// 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); }
}}
/>
</div>
{refusal ? <p className="sheet-rules-refusal" id={`${id}-refusal`} role="alert">{refusal}</p> : null}
</div>
);
}
// ── 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 <ValidationSurface count={count} list={list} onCancel={onCancel} onSave={onSave} />;
}
function ValidationSurface({ count, list, onCancel, onSave }: Omit<ValidationDialogProps, "open">) {
const [text, setText] = useState(() => listText(list));
const [notice, setNotice] = useState("");
const boxId = useId();
const parsed = parseList(text);
return (
<ConfirmDialog
open
title="Values this cell accepts"
tone="primary"
cancelLabel="Cancel"
confirmLabel="Save list"
onCancel={onCancel}
onConfirm={() => {
const out = parseList(text);
if (out.refusal) {
setNotice(out.refusal);
return;
}
onSave(out.list);
}}
body={(
<div className="sheet-validation">
<label className="sheet-validation-label" htmlFor={boxId}>
One value per line. {count === 1 ? "This cell" : `These ${count} cells`} will offer them
as a dropdown and refuse anything else.
</label>
<textarea
id={boxId}
className="sheet-validation-box"
rows={8}
spellCheck={false}
autoFocus
value={text}
placeholder={"Royal\nFisch"}
onChange={(e) => { setNotice(""); setText(e.target.value); }}
/>
<p className="sheet-validation-count">
{parsed.refusal ? "" : `${parsed.list.length} of ${MAX_VALIDATION_LIST} values.`}
{parsed.list.length === 0 && !parsed.refusal
? " Saving an empty list removes the dropdown."
: ""}
</p>
{notice || parsed.refusal ? (
<p className="sheet-validation-refusal" role="alert">{notice || parsed.refusal}</p>
) : null}
</div>
)}
/>
);
}