fix(overlay): make the Stroke section answer for all four edges

Every read in the section was `border-top-*` answering for the whole box, so
`.header { border-bottom: 1px solid }` showed as unstroked and editing it wrote
to the wrong edge. `edgeValue()` folds all four longhands through `agreed`,
comparing colours with `sameColor` so one colour spelled two ways is not
reported as Mixed.

The eye was a live bug rather than a cosmetic one. Three writes still went
through the `border-style` shorthand, while `hasStroke` reads longhands through
`ctx.gate`, which does no shorthand expansion. A pending longhand `solid`
therefore shadowed a shorthand `none` forever: the eye toggled, the gate kept
reading `solid`, and nothing happened again. All three writes go through
`writeAllEdges` now. `strokeColor` is passed as the colour row's re-seed reader
for the same class of reason — without it the four registered properties push
four `setValue` calls and `border-left-color` wins by arriving last.

`splitBorder` had no first-wins guard on `width`, so `border: 1px solid
var(--border)` let the `var()` overwrite `1px` and left the colour undefined
entirely. The forced-state preview got `border-*-width: var(--border)` and no
colour at all.

First tests for `renderStroke`, covering all six defects, plus a `MixedEdges`
story and the `mixedBorder` specimen it renders.
This commit is contained in:
Nayan
2026-08-16 13:05:37 +05:30
parent 46d45ae885
commit ac4c1cc4af
7 changed files with 433 additions and 14 deletions
@@ -104,6 +104,55 @@ describe("expandShorthands", () => {
"padding-top": "4px",
});
});
/*
* `border`'s three parts are order-independent and all optional, so each word
* is classified rather than positioned — and a `var()` is the one word that
* could be any of them.
*
* `LOOKS_LIKE_LENGTH` matches `^var\(`, which it has to: `border-width:
* var(--w)` is ordinary. But so is `border: 1px solid var(--border)`, and
* there the `var()` is the *colour*. With no guard the last matching word won,
* so `var(--border)` overwrote the `1px` and the colour was dropped entirely —
* a forced-state preview for such a rule got `border-*-width: var(--border)`
* and no colour at all.
*/
it("does not let a var() colour overwrite the border width", () => {
expect(expand({ border: "1px solid var(--border)" })).toEqual({
"border-bottom-color": "var(--border)",
"border-bottom-style": "solid",
"border-bottom-width": "1px",
"border-left-color": "var(--border)",
"border-left-style": "solid",
"border-left-width": "1px",
"border-right-color": "var(--border)",
"border-right-style": "solid",
"border-right-width": "1px",
"border-top-color": "var(--border)",
"border-top-style": "solid",
"border-top-width": "1px",
});
});
it("still reads a lone var() as the width, which is the ambiguous case", () => {
// Nothing in the string says which slot it fills, and first-wins puts it in
// the one a single `var()` most often means.
expect(expand({ "border-top": "var(--w) solid" })).toEqual({
"border-top-style": "solid",
"border-top-width": "var(--w)",
});
});
it("keeps a calc() width beside a var() colour", () => {
// `calc(` is in the same regex as `var(` and took the same wrong branch.
expect(expand({ "border-top": "calc(1px + 1px) dashed var(--c)" })).toEqual(
{
"border-top-color": "var(--c)",
"border-top-style": "dashed",
"border-top-width": "calc(1px + 1px)",
}
);
});
});
describe("stripStates", () => {
+17 -1
View File
@@ -452,6 +452,19 @@ const LINE_STYLES = new Set([
* The three are order-independent and all optional, so each word is classified
* rather than positioned: a line-style keyword is the style, something that parses as
* a length (or a width keyword) is the width, and whatever is left is the colour.
*
* The `out.width === undefined` guard is what stops `var()` eating the colour.
* `LOOKS_LIKE_LENGTH` matches `^var\(` — it has to, because `border-width:
* var(--w)` is ordinary — but so is `border: 1px solid var(--border)`, and there
* the *colour* is the `var()`. With no guard the last matching word won, so
* `var(--border)` overwrote the `1px` and `out.color` was left undefined
* entirely: the forced-state preview for such a rule got `border-*-width:
* var(--border)` and no colour at all.
*
* A `var()` in this position is genuinely ambiguous — nothing in the string says
* which slot it fills. But a shorthand has at most one width, so first-wins is
* strictly better than last-wins: it keeps the unambiguous `1px` where it
* belongs and leaves the ambiguous word in the only slot still open.
*/
function splitBorder(value: string): {
color?: string;
@@ -463,7 +476,10 @@ function splitBorder(value: string): {
const lower = word.toLowerCase();
if (LINE_STYLES.has(lower)) {
out.style = lower;
} else if (WIDTH_KEYWORD.has(lower) || LOOKS_LIKE_LENGTH.test(word)) {
} else if (
out.width === undefined &&
(WIDTH_KEYWORD.has(lower) || LOOKS_LIKE_LENGTH.test(word))
) {
out.width = word;
} else {
out.color = word;
@@ -97,3 +97,28 @@ export const Narrow: StoryObj = {
narrow: true,
}),
};
/**
* Four edges that disagree — the specimen the catalogue was missing.
*
* None of the five stories above uses an element whose edges differ, which is
* why nothing here caught the section answering for the whole box from
* `border-top-*`. This one shows a red top, teal right, blue bottom and amber
* left: the colour row must read `Mixed` and the width field must open split.
*
* Two things to try, both of which used to be wrong. Picking a colour imposes
* it on all four edges — that is the point of `Mixed`, "several values, one of
* which you are about to impose". And the eye must still hide the stroke after
* `+` Add stroke has been pressed: it wrote the `border-style` shorthand while
* `hasStroke` reads the longhands through `ctx.gate`, so a pending `solid`
* shadowed it forever and the eye did nothing.
*/
export const MixedEdges: StoryObj = {
render: () =>
sectionStory(renderStroke, "mixedBorder", {
caption: {
try: "pick a colour — it must land on all four edges; then press the eye, `+` Add stroke, and the eye again",
what: "Four differing edges. The colour row reads `Mixed` rather than claiming the top edge's red for the box.",
},
}),
};
@@ -0,0 +1,215 @@
/**
* The Stroke section, on the four edges it speaks for.
*
* Nothing tested `renderStroke` at all, and it had six defects of one shape: it
* claimed things it did not do. Every *read* asked `border-top-*` and answered
* for the whole box — so `.header { border-bottom: 1px solid #eee }`, the
* canonical divider, showed as an unstroked element, and four differing edge
* colours showed as the top one. Three *writes* used the `border-style`
* shorthand while the file's own header claimed it never did, and one of those
* was live: `hasStroke` reads the longhands through `ctx.gate`, which does no
* shorthand expansion, so once *Add stroke* had written a pending `solid` the
* shorthand `none` could never win and the eye stopped working.
*
* The section is driven through a recording context rather than the full panel,
* for the reason `svg-paint.test.ts` gives: what matters is which properties
* the closures write, and a stub is the only way to see them.
*/
import { afterEach, describe, expect, it } from "vitest";
import type { SectionContext } from "./context";
import { renderStroke } from "./stroke";
afterEach(() => {
for (const child of Array.from(document.body.children)) {
child.remove();
}
});
interface ColorRow {
onChange: (next: string) => void;
properties: readonly string[];
/** The re-seed escape hatch. Absent is the bug this file was written for. */
read?: () => string;
value: string;
}
interface Recorded {
changes: [string, string][];
colorRow: ColorRow | null;
reseeds: number;
}
/** A SectionContext that records writes and captures the colour row's wiring. */
function recordingCtx(): { ctx: SectionContext; got: Recorded } {
const got: Recorded = { changes: [], colorRow: null, reseeds: 0 };
const stub = document.createElement("div");
const ctx = {
colorRow: (
value: string,
_tip: string,
onChange: (next: string) => void,
_node?: Element,
properties: readonly string[] = [],
read?: () => string
) => {
got.colorRow = { onChange, properties, read, value };
return stub.cloneNode() as HTMLElement;
},
// The real gate is "pending edit, then computed style". Computed alone is
// enough here: happy-dom applies inline styles, and no test below has a
// pending edit the DOM has not already taken.
gate: (node: Element) => (property: string) =>
getComputedStyle(node).getPropertyValue(property),
gestures: {},
headerAction: () => stub.cloneNode() as HTMLElement,
onChange: (property: string, value: string) => {
got.changes.push([property, value]);
},
register: () => undefined,
repaintScope: () => (paint: () => void) => paint(),
reseed: () => {
got.reseeds += 1;
},
section: (_id: string, _label: string, body: HTMLElement) => body,
tokenSlot: () => null,
} as unknown as SectionContext;
return { ctx, got };
}
/** An element with a border, written per-edge so nothing is a shorthand. */
function bordered(edges: Partial<Record<string, string>>): HTMLElement {
const node = document.createElement("div");
for (const side of ["top", "right", "bottom", "left"]) {
node.style.setProperty(`border-${side}-style`, "solid");
node.style.setProperty(`border-${side}-width`, "1px");
node.style.setProperty(
`border-${side}-color`,
edges[side] ?? "rgb(0, 0, 0)"
);
}
document.body.append(node);
return node;
}
/** Click a button by its accessible name. */
function press(root: HTMLElement, label: string): void {
const button = root.querySelector<HTMLElement>(`[aria-label="${label}"]`);
if (!button) {
throw new Error(`no "${label}" button`);
}
button.click();
}
describe("the colour row speaks for four edges", () => {
it("shows the shared colour when they agree", () => {
const { ctx, got } = recordingCtx();
renderStroke(ctx, bordered({}));
expect(got.colorRow?.value).toBe("rgb(0, 0, 0)");
});
it("shows Mixed when they do not", () => {
// Was: the top edge's colour, imposed on the other three by the first edit.
const { ctx, got } = recordingCtx();
renderStroke(
ctx,
bordered({ bottom: "rgb(0, 0, 255)", top: "rgb(255, 0, 0)" })
);
expect(got.colorRow?.value).toBe("Mixed");
});
it("does not call one colour Mixed for being spelled two ways", () => {
/*
* The reason this compares with `sameColor` rather than `===`. Once an edit
* is pending, `applyPreview` has written the picker's modern
* `rgb(r g b / a)` into the inline style of the edges just written while
* the rest still read back the engine's legacy form. String equality calls
* that a disagreement and shows `Mixed` on a box the user just made uniform.
*/
const node = bordered({});
node.style.setProperty("border-top-color", "rgb(0 0 0 / 1)");
const { ctx, got } = recordingCtx();
renderStroke(ctx, node);
expect(got.colorRow?.value).not.toBe("Mixed");
});
it("imposes a picked colour on all four edges", () => {
const { ctx, got } = recordingCtx();
renderStroke(ctx, bordered({ top: "rgb(255, 0, 0)" }));
got.colorRow?.onChange("rgb(0, 255, 0)");
expect(got.changes).toEqual([
["border-top-color", "rgb(0, 255, 0)"],
["border-right-color", "rgb(0, 255, 0)"],
["border-bottom-color", "rgb(0, 255, 0)"],
["border-left-color", "rgb(0, 255, 0)"],
]);
});
});
describe("the re-seed escape hatch", () => {
it("is supplied, or the fix dies on the first refresh", () => {
/*
* The row registers four properties, and without a `read` the re-seed pass
* pushes the raw value of each in turn — so `border-left-color` wins and a
* `Mixed` row silently settles on the left edge after one undo. The
* assertion is on the wiring because that is where the bug lived.
*/
const { ctx, got } = recordingCtx();
renderStroke(
ctx,
bordered({ bottom: "rgb(0, 0, 255)", top: "rgb(255, 0, 0)" })
);
expect(got.colorRow?.properties).toHaveLength(4);
expect(got.colorRow?.read).toBeTypeOf("function");
});
it("re-derives the same value the seed did", () => {
// `vector.ts` states the invariant: the seed and the re-seed `read` have to
// agree, or the next refresh contradicts the render.
const { ctx, got } = recordingCtx();
renderStroke(
ctx,
bordered({ bottom: "rgb(0, 0, 255)", top: "rgb(255, 0, 0)" })
);
expect(got.colorRow?.read?.()).toBe(got.colorRow?.value);
});
});
describe("every write is a longhand", () => {
it("hides the stroke with four longhands, not the shorthand", () => {
/*
* The known bug. `hasStroke` reads per-edge `border-<edge>-style` through
* `ctx.gate`, a per-property lookup with no shorthand expansion — so after
* *Add stroke* had written the longhands once, a pending `solid` on them
* shadowed the shorthand `none` forever and the eye was a no-op.
*/
const { ctx, got } = recordingCtx();
const body = renderStroke(ctx, bordered({}));
press(body, "Hide stroke");
expect(got.changes).toEqual([
["border-top-style", "none"],
["border-right-style", "none"],
["border-bottom-style", "none"],
["border-left-style", "none"],
]);
expect(got.changes.some(([p]) => p === "border-style")).toBe(false);
});
it("removes the stroke with longhands, as it always did", () => {
// The control this one was already modelled on.
const { ctx, got } = recordingCtx();
const body = renderStroke(ctx, bordered({}));
press(body, "Remove stroke");
expect(got.changes.map(([p]) => p)).toEqual([
"border-top-style",
"border-right-style",
"border-bottom-style",
"border-left-style",
"border-top-width",
"border-right-width",
"border-bottom-width",
"border-left-width",
]);
expect(got.changes.some(([p]) => p === "border-style")).toBe(false);
expect(got.changes.some(([p]) => p === "border-width")).toBe(false);
});
});
+109 -13
View File
@@ -5,8 +5,10 @@ import { createTextField } from "../controls/num-field";
import { createQuadField } from "../controls/quad-field";
import { createSegmented } from "../controls/segmented";
import { createSelect } from "../controls/select";
import { sameColor } from "../css-value";
import { STROKE_POSITION, STROKE_SIDES, STROKE_STYLE } from "../descriptors";
import { hasStroke } from "../gates";
import { agreed } from "../mixed";
import { readValue } from "../style-model";
import type { SectionContext } from "./context";
@@ -37,6 +39,16 @@ import type { SectionContext } from "./context";
* A shorthand also cannot be taken back cleanly — `border-width: 0px` leaves the four
* longhands in place and merely loses to them — which is why Remove looked like it had
* worked while the quad field still read `8`.
*
* The first line was aspirational for a long time. Three writes still used the
* shorthand — the eye, the width field's implied `solid`, and the Style select —
* and the eye's was a live bug: `hasStroke` reads the longhands through
* `ctx.gate`, which does no shorthand expansion, so once *Add stroke* had
* written a pending `solid` on them the shorthand `none` could never win, and
* the eye did nothing. All three go through `writeAllEdges` now.
*
* The reads had the mirror-image problem and are fixed the same way: every one
* of them asked `border-top-*` and answered for the box. See `edgeValue`.
*/
const EDGES = ["top", "right", "bottom", "left"] as const;
@@ -50,9 +62,42 @@ function writeAllEdges(
}
}
/**
* What all four edges say, or `MIXED` when they disagree.
*
* Every read in this section used to be `readValue(node, "border-top-*")` — the
* top edge speaking for the box. That is the same mistake the *writes* were
* fixed for: `.header { border-bottom: 1px solid #eee }` is the canonical
* divider, and this section showed it as an unstroked element with a black
* colour. Set three sides to red and the fourth to blue and the row claimed red
* for all four, then imposed it on the first edit.
*
* Colours compare through `sameColor`, not `===`. These four values do not all
* come from the same place once an edit is pending: `applyPreview` writes the
* picker's `rgb(r g b / a)` into the inline style of the edges just written,
* while the rest still read back the engine's legacy `rgb(r, g, b)`. String
* equality calls that a disagreement and shows `Mixed` on a box the user just
* made uniform. Note `panel.seed` compares with `===`, which is right for the
* keywords and lengths it handles and would be wrong here.
*/
function edgeValue(
node: Element,
suffix: "width" | "style" | "color",
fallback: string
): string {
return agreed(
EDGES.map((edge) => readValue(node, `border-${edge}-${suffix}`)),
fallback,
suffix === "color" ? (a, b) => sameColor(a, b, node) : undefined
);
}
export function renderStroke(ctx: SectionContext, node: Element): HTMLElement {
const body = el("div", { class: cls("sect-body") });
/** The stroke's colour, or `MIXED`. Used as both the seed and the re-seed. */
const strokeColor = (): string => edgeValue(node, "color", "#000000");
// Colour writes the four longhands, not the `border-color` shorthand.
// The widths beside it have always been longhands, so the shorthand was the
// one declaration in this section that could not describe what the section
@@ -71,7 +116,7 @@ export function renderStroke(ctx: SectionContext, node: Element): HTMLElement {
rows.replaceChildren(
el("div", { class: cls("rows-row") }, [
ctx.colorRow(
readValue(node, "border-top-color") || "#000000",
strokeColor(),
"Stroke colour",
(next) => {
for (const side of STROKE_SIDES) {
@@ -79,7 +124,22 @@ export function renderStroke(ctx: SectionContext, node: Element): HTMLElement {
}
},
node,
STROKE_SIDES.map((side) => `border-${side.name}-color`)
STROKE_SIDES.map((side) => `border-${side.name}-color`),
/*
* The sixth argument, and it is not optional here.
*
* Without it the re-seed pass pushes the raw per-property value
* (`panel.colorRow`'s `setValue`), and this row registers *four*
* properties — so it takes four `setValue` calls, one per edge, and
* `border-left-color` wins. A `Mixed` row would settle on the left
* edge's colour after the first undo, refresh or discard, which is
* the panel changing what it claims for no reason the user can see.
*
* The same expression as the seed, deliberately: `vector.ts` states
* the invariant — "the seed and the re-seed `read` have to agree on
* this" — and the only way to keep it is to have one function.
*/
strokeColor
),
// The eye keeps the widths and drops the stroke out of what gets
// painted — the same contract `row-list`'s disabled rows have. It
@@ -92,7 +152,21 @@ export function renderStroke(ctx: SectionContext, node: Element): HTMLElement {
class: cls("row-icon"),
"data-tip": "Hide stroke",
onClick: () => {
ctx.onChange("border-style", "none");
/*
* Longhands, like everything else here — this wrote the
* `border-style` shorthand and was a no-op after the first
* *Add stroke*.
*
* `hasStroke` asks `ctx.gate` for each `border-<edge>-style`, and
* the gate is `changeSet.snapshot(node, property)?.to ??
* readValue(node, property)` — a per-property lookup with no
* shorthand expansion. Add writes the four longhands, so once a
* pending `solid` exists on them it shadows a pending `none` on
* the shorthand forever: the inline preview applied,
* `borderTopStyle` computed to `none`, and the section went on
* showing a stroke the element was not painting.
*/
writeAllEdges(ctx.onChange, "style", "none");
paintRows();
paintAdd();
},
@@ -136,11 +210,20 @@ export function renderStroke(ctx: SectionContext, node: Element): HTMLElement {
// A border with no style is invisible however wide it is; setting one
// implies the other, and leaving that to the user is a trap.
onWrote: (_property, css) => {
/*
* All four edges, and longhands out.
*
* `edgeValue` returns `none` only when every edge agrees on it, so an
* element that already paints one edge is left alone — widening it
* should not silently draw the other three. The old
* `border-top-style === "none"` test asked one edge and then wrote the
* shorthand across all four, which is both halves of the same mistake.
*/
if (
Number.parseFloat(css) > 0 &&
readValue(node, "border-top-style") === "none"
edgeValue(node, "style", "none") === "none"
) {
ctx.onChange("border-style", "solid");
writeAllEdges(ctx.onChange, "style", "solid");
paintRows();
paintAdd();
}
@@ -208,9 +291,7 @@ export function renderStroke(ctx: SectionContext, node: Element): HTMLElement {
const paintAdd = (): void => {
const on = hasStroke(ctx.gate(node));
add.toggleAttribute("disabled", on);
add.dataset.tip = on
? "An element has one CSS border. For a second ring, use an outline or a spread-only shadow"
: "Add stroke";
add.dataset.tip = on ? "CSS gives an element one border" : "Add stroke";
};
paintAdd();
@@ -270,8 +351,7 @@ function openStrokeSettings(
);
if (centre) {
centre.toggleAttribute("disabled", true);
centre.dataset.tip =
"CSS borders sit inside or outside the box — there is no centre";
centre.dataset.tip = "CSS has no centre border";
}
body.append(popRow("Position", position.element));
@@ -281,10 +361,26 @@ function openStrokeSettings(
* only solid and dash — so a segmented group would mix icon cells and text
* pills, which is exactly the shape `segmented.ts` warns against.
*/
/*
* Seeded from all four edges and writing all four, like the rest of the
* section.
*
* `STROKE_STYLE.cssProperty` is the `border-style` shorthand, so
* `createSelect` emits that — the third and last place this section wrote a
* declaration it could not read back. The `OnChange` is wrapped rather than
* the descriptor changed or `createSelect` taught a new trick: the select's
* job is to pick one of five keywords, and which properties that lands on is
* the section's business.
*
* A `MIXED` seed needs no handling here either. `createSelect` renders
* `options.find(o => o.value === current)?.label ?? current`, so it shows the
* word and marks nothing active — which is exactly right, and is why
* `panel.seed` made the sentinel a plain string.
*/
const style = createSelect(
STROKE_STYLE,
readValue(node, "border-top-style") || "none",
ctx.onChange
edgeValue(node, "style", "none"),
(_property, value) => writeAllEdges(ctx.onChange, "style", value)
);
body.append(popRow("Style", style.element));
@@ -305,7 +401,7 @@ function openStrokeSettings(
const field = createTextField({ glyph: label[0], label });
field.input.disabled = true;
field.input.placeholder = "—";
field.element.dataset.tip = `${label} length is chosen by the browser; CSS cannot set it`;
field.element.dataset.tip = `The browser picks the ${label.toLowerCase()} length`;
dashes.append(field.element);
}
body.append(popRow("Dashes", dashes));
@@ -49,6 +49,7 @@ describe("specimens", () => {
"hero",
"icon",
"image",
"mixedBorder",
"note",
"paragraph",
"path",
+17
View File
@@ -389,6 +389,23 @@ const SPECIMENS = {
* more common shape in a real app, and it is the arm that would silently stop
* working if the scan were dropped.
*/
/**
* Four edges that disagree, which the Stroke section used to hide.
*
* Every read in that section asked `border-top-*` and answered for the whole
* box, so this element displayed as a uniform red 1px border — and the first
* edit imposed red on all four. Inline styles rather than a class, because
* what is under test is per-edge disagreement and a stylesheet rule would let
* a shorthand creep back in.
*/
mixedBorder: {
covers:
"four differing border colours and widths on one element · the Mixed sentinel on a hand-built colour row · hasStroke",
label: "a box with four different edges",
markup: `<div data-subject style="padding:24px;border-style:solid;border-top-color:#e11d48;border-right-color:#0d9488;border-bottom-color:#2563eb;border-left-color:#ca8a04;border-top-width:1px;border-right-width:4px;border-bottom-width:1px;border-left-width:4px">Four edges, four colours.</div>`,
wrap: "block",
},
note: {
covers: "hasText via the text-node scan rather than the TEXTY tag set",
label: "a note",