Files
webstudio/apps/builder/app/canvas/selected-instance-effects.test.ts
T
Oleg Isonen 8454113d31 fix: Restore Tag selectors and speed up selection (#6679)
The Builder was stalling when selecting instances because Tag selector
resolution repeatedly scanned and parsed project styles for every
displayed property. This PR indexes that data when styles change, reuses
style source suggestions, and avoids an unnecessary stylesheet rebuild
on multi-selection. It also restores the documented `:hover .button` and
`:hover > .icon` selectors, fixes their editing preview, and adds sharp
light and dark Tag styles screenshots.

Ref #5657
Closes #6678

### Plan and tools
- [x] Reproduce the selector rejection in shared validator and runtime
tests.
- [x] Restore one shared validation path for new and saved selectors.
Keep CSS parsing through css-tree.
- [x] Update Tag styles and States and selectors docs, navigation emoji,
and paired Storybook screenshots.
- [x] Measure the instance selection slowdown and remove repeated full
scans while preserving source order.
- [x] Audit the full selection path and reuse existing style indexes in
state matching and style controls.
- [x] Avoid redundant Tag CSS rebuild on multi-selection and test that
real preview styles still clear.
- [x] Fix descendant state previews for Token, Local, and Tag styles;
verify live Tag editing.
- [x] Run targeted tests, typechecks, lint, formatting, and inspect both
screenshot themes.
- [ ] Monitor PR checks and address failures.
- [ ] Approve the new Storybook baseline after user review.

Verification: CSS data 62 tests; project build styles 167 tests; Builder
style panel/model 113 targeted tests; canvas selection and styles 89
targeted tests; CSS data/project build/Builder typechecks; lint;
formatting. A local benchmark with 5,100 styles, 5,001 instance
selections, and 100 property reads fell from 99 ms to 6 ms for reads
after the second fix, plus 6 ms to build indexes when data changed. The
original repeated style scan measured 716 ms for 100 reads with no
instance selection map. These measure the affected calculation, not
total Builder selection time. Two older selection-time style scans
remain and cost about 0.1 ms each per 5,100 declarations in a synthetic
Node scan; their output ordering needs a separate check before changing
them. Previewing an unrelated Token or Local edit still rebuilds the Tag
stylesheet, an editing-time cost outside the reported selection path. No
fixture inputs or generated fixture bundles changed. Agent evaluations
were not run because they require separate approval.
2026-11-12 00:25:24 +01:00

358 lines
9.7 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { getTagStyleId, type StyleDecl } from "@webstudio-is/sdk";
import { idAttribute, selectorIdAttribute } from "@webstudio-is/react-sdk";
import {
$allSelectedInstanceSelectors,
$selectedInstanceOutline,
$selectedInstanceOutlines,
$selectedInstanceStates,
$selectedInstanceStatesByInstanceId,
$stylesIndex,
selectInstances,
} from "~/shared/nano-states";
import {
$instances,
$styleSourceSelections,
$styleSources,
$styles,
} from "~/shared/sync/data-stores";
import { subscribeSelected } from "./selected-instance-effects";
import { subscribeInstanceSelection } from "./instance-selection-events";
import { createCanvasElement } from "./test-utils";
const createInstance = (id: string) => ({
type: "instance" as const,
id,
component: "Box",
children: [],
});
class ResizeObserver {
observe() {}
disconnect() {}
}
class TestDOMRect {
left: number;
top: number;
width: number;
height: number;
x: number;
y: number;
right: number;
bottom: number;
constructor(x = 0, y = 0, width = 0, height = 0) {
this.left = x;
this.top = y;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.right = x + width;
this.bottom = y + height;
}
static fromRect(rect: Partial<globalThis.DOMRectReadOnly>) {
return new TestDOMRect(rect.x, rect.y, rect.width, rect.height);
}
toJSON() {
return this;
}
}
class TestDOMMatrix {
inverse() {
return this;
}
}
class TestDOMPoint {
x: number;
y: number;
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
matrixTransform() {
return this;
}
}
let unsubscribe = () => {};
let abortController: AbortController;
beforeEach(() => {
vi.stubGlobal("ResizeObserver", ResizeObserver);
vi.stubGlobal("DOMRect", TestDOMRect);
vi.stubGlobal("DOMMatrix", TestDOMMatrix);
vi.stubGlobal("DOMPoint", TestDOMPoint);
vi.stubGlobal("requestAnimationFrame", () => 0);
$instances.set(
new Map([
["box", createInstance("box")],
["heading", createInstance("heading")],
])
);
$styleSourceSelections.set(new Map());
$styleSources.set(new Map());
$styles.set(new Map());
$allSelectedInstanceSelectors.set([]);
$selectedInstanceStates.set(new Set());
$selectedInstanceStatesByInstanceId.set(new Map());
$selectedInstanceOutline.set(undefined);
$selectedInstanceOutlines.set([]);
document.body.innerHTML = "";
abortController = new AbortController();
});
afterEach(() => {
abortController.abort();
unsubscribe();
unsubscribe = () => {};
vi.unstubAllGlobals();
document.body.innerHTML = "";
$instances.set(new Map());
$styles.set(new Map());
$styleSourceSelections.set(new Map());
$styleSources.set(new Map());
$allSelectedInstanceSelectors.set([]);
$selectedInstanceStates.set(new Set());
$selectedInstanceStatesByInstanceId.set(new Map());
$selectedInstanceOutline.set(undefined);
$selectedInstanceOutlines.set([]);
});
describe("subscribeSelected", () => {
test("detects active states defined only by the selected tag style", () => {
const button = document.createElement("button");
button.disabled = true;
button.setAttribute(idAttribute, "box");
button.setAttribute(selectorIdAttribute, "box");
document.body.appendChild(button);
$instances.set(
new Map([["box", { ...createInstance("box"), tag: "button" }]])
);
const declaration: StyleDecl = {
styleSourceId: getTagStyleId("button"),
breakpointId: "base",
state: ":disabled",
property: "color",
value: { type: "keyword", value: "red" },
};
$styles.set(new Map([["button-disabled", declaration]]));
$stylesIndex.get();
const allStyles = vi.spyOn($styles.get(), "values");
unsubscribe = subscribeSelected((callback) => callback());
selectInstances([["box"]]);
expect($selectedInstanceStates.get()).toEqual(new Set([":disabled"]));
expect(allStyles).not.toHaveBeenCalled();
});
test("does not treat a descendant selector as an active instance state", () => {
const div = document.createElement("div");
div.setAttribute(idAttribute, "box");
div.setAttribute(selectorIdAttribute, "box");
document.body.appendChild(div);
$styleSourceSelections.set(
new Map([["box", { instanceId: "box", values: ["token"] }]])
);
$styles.set(
new Map([
[
"token-descendant",
{
styleSourceId: "token",
breakpointId: "base",
state: " div",
property: "paddingTop",
value: { type: "unit", value: 20, unit: "px" },
},
],
])
);
unsubscribe = subscribeSelected((callback) => callback());
selectInstances([["box"]]);
expect($selectedInstanceStates.get()).toEqual(new Set());
});
test("detects an active attribute condition on a nested global Tag style", () => {
const parent = document.createElement("div");
parent.setAttribute(idAttribute, "box");
parent.setAttribute(selectorIdAttribute, "box");
const heading = document.createElement("h2");
heading.setAttribute(idAttribute, "heading");
heading.setAttribute(selectorIdAttribute, "heading,box");
heading.setAttribute("data-state", "open");
parent.appendChild(heading);
document.body.appendChild(parent);
const id = getTagStyleId("div");
$styleSources.set(new Map([[id, { type: "tag", id, tag: "div" }]]));
$styles.set(
new Map([
[
"nested-tag-attribute",
{
styleSourceId: id,
breakpointId: "base",
state: " h2[ data-state = open ]",
property: "color",
value: { type: "keyword", value: "red" },
},
],
])
);
unsubscribe = subscribeSelected((callback) => callback());
selectInstances([["heading", "box"]]);
expect($selectedInstanceStates.get()).toEqual(
new Set(["[ data-state = open ]"])
);
expect($selectedInstanceStatesByInstanceId.get()).toEqual(
new Map([
["heading", new Set(["[ data-state = open ]"])],
["box", new Set()],
])
);
});
test("creates both outline stores for one selected instance", () => {
createCanvasElement({
selector: "box,body",
rect: { left: 10, top: 20, width: 100, height: 50 },
});
unsubscribe = subscribeSelected((callback) => callback());
selectInstances([["box", "body"]]);
expect($selectedInstanceOutlines.get()).toEqual([
expect.objectContaining({
selector: ["box", "body"],
instanceId: "box",
}),
]);
expect(Object.keys($selectedInstanceOutlines.get()[0].rect)).toEqual([
"top",
"left",
"width",
"height",
]);
expect($selectedInstanceOutline.get()).toEqual(
expect.objectContaining({
instanceId: "box",
})
);
});
test("creates an outline for every selected instance without single outline", () => {
createCanvasElement({
selector: "box,body",
rect: { left: 10, top: 20, width: 100, height: 50 },
});
createCanvasElement({
selector: "heading,body",
rect: { left: 20, top: 40, width: 140, height: 70 },
});
unsubscribe = subscribeSelected((callback) => callback());
selectInstances([
["box", "body"],
["heading", "body"],
]);
expect(
$selectedInstanceOutlines.get().map((outline) => outline.selector)
).toEqual([
["box", "body"],
["heading", "body"],
]);
expect($selectedInstanceOutline.get()).toBeUndefined();
});
test("does not fall back to parent rect for zero-size multi-selected instances", () => {
const parent = createCanvasElement({
selector: "parent,body",
rect: { left: 5, top: 10, width: 500, height: 300 },
});
createCanvasElement({
selector: "box,parent,body",
rect: { left: 0, top: 0, width: 0, height: 0 },
parent,
});
createCanvasElement({
selector: "heading,parent,body",
rect: { left: 20, top: 40, width: 140, height: 70 },
parent,
});
unsubscribe = subscribeSelected((callback) => callback());
selectInstances([
["box", "parent", "body"],
["heading", "parent", "body"],
]);
expect($selectedInstanceOutlines.get()[0]).toEqual(
expect.objectContaining({
selector: ["box", "parent", "body"],
rect: expect.objectContaining({
left: 0,
top: 0,
width: 0,
height: 0,
}),
})
);
expect(
$selectedInstanceOutlines
.get()
.some(
(outline) => outline.rect.width === 500 && outline.rect.height === 300
)
).toBe(false);
});
test("creates outlines when instances are selected by canvas clicks", () => {
const box = createCanvasElement({
selector: "box,body",
rect: { left: 10, top: 20, width: 100, height: 50 },
});
const heading = createCanvasElement({
selector: "heading,body",
rect: { left: 20, top: 40, width: 140, height: 70 },
});
unsubscribe = subscribeSelected((callback) => callback());
subscribeInstanceSelection({ signal: abortController.signal });
box.dispatchEvent(new MouseEvent("click", { bubbles: true }));
expect(
$selectedInstanceOutlines.get().map((outline) => outline.selector)
).toEqual([["box", "body"]]);
expect($selectedInstanceOutline.get()).toEqual(
expect.objectContaining({
instanceId: "box",
})
);
heading.dispatchEvent(
new MouseEvent("click", { bubbles: true, metaKey: true })
);
expect(
$selectedInstanceOutlines.get().map((outline) => outline.selector)
).toEqual([
["box", "body"],
["heading", "body"],
]);
expect($selectedInstanceOutline.get()).toBeUndefined();
});
});