Files
webstudio/apps/builder/app/canvas/selected-instance-effects.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

576 lines
18 KiB
TypeScript

import warnOnce from "warn-once";
import { getTagStyleId, type Instance } from "@webstudio-is/sdk";
import type { CssProperty, UnitValue } from "@webstudio-is/css-engine";
import {
isPseudoElement,
propertiesData,
validateSelector,
} from "@webstudio-is/css-data";
import { selectorIdAttribute } from "@webstudio-is/react-sdk";
import { subscribeWindowResize } from "~/shared/dom-hooks";
import { areSetsEqual } from "~/shared/collection-equality";
import {
$isResizingCanvas,
$selectedInstanceSizes,
$selectedInstanceRenderState,
$stylesIndex,
$propValuesByInstanceSelectorWithMemoryProps,
$selectedInstanceStates,
$selectedInstanceStatesByInstanceId,
$selectedStyleState,
$allSelectedInstanceSelectors,
type UnitSizes,
type PropertySizes,
} from "~/shared/nano-states";
import {
$styleSourceSelections,
$styleSources,
} from "~/shared/sync/data-stores";
import {
getAllElementsBoundingBox,
getVisibleElementsByInstanceSelector,
getAllElementsByInstanceSelector,
scrollIntoView,
hasDoNotTrackMutationRecord,
} from "~/shared/dom-utils";
import { subscribeScrollState } from "~/canvas/shared/scroll-state";
import {
$selectedInstanceOutline,
$selectedInstanceOutlines,
} from "~/shared/nano-states";
import { $instances } from "~/shared/sync/data-stores";
import { inflateInstance } from "~/canvas/inflator";
import {
areInstanceSelectorsEqual,
type InstanceSelector,
} from "@webstudio-is/project-build/runtime";
const toRect = (rect: DOMRect) => ({
top: rect.top,
left: rect.left,
width: rect.width,
height: rect.height,
});
const setOutline = (
selector: InstanceSelector,
instanceId: Instance["id"],
elements: HTMLElement[],
syncSingleOutline: boolean
) => {
const outline = {
selector,
instanceId,
rect: toRect(
getAllElementsBoundingBox(elements, {
fallbackToParent: syncSingleOutline,
})
),
};
const outlines = $selectedInstanceOutlines.get();
const index = outlines.findIndex((item) =>
areInstanceSelectorsEqual(item.selector, selector)
);
if (index === -1) {
$selectedInstanceOutlines.set([...outlines, outline]);
} else {
const nextOutlines = [...outlines];
nextOutlines[index] = outline;
$selectedInstanceOutlines.set(nextOutlines);
}
if (syncSingleOutline) {
$selectedInstanceOutline.set(outline);
}
};
const hideOutline = (
selector: InstanceSelector,
syncSingleOutline: boolean
) => {
$selectedInstanceOutlines.set(
$selectedInstanceOutlines
.get()
.filter(
(item) => areInstanceSelectorsEqual(item.selector, selector) === false
)
);
if (syncSingleOutline) {
$selectedInstanceOutline.set(undefined);
}
};
const calculateUnitSizes = (element: HTMLElement): UnitSizes => {
// Based on this https://stackoverflow.com/questions/1248081/how-to-get-the-browser-viewport-dimensions/8876069#8876069
// this is crossbrowser way to get viewport sizes vw vh in px
const vw =
Math.max(document.documentElement.clientWidth, window.innerWidth) / 100;
const vh =
Math.max(document.documentElement.clientHeight, window.innerHeight) / 100;
// em in px is equal to current computed style for font size
const em = Number.parseFloat(getComputedStyle(element).fontSize);
// rem in px is equal to root computed style for font size
const rem = Number.parseFloat(
getComputedStyle(document.documentElement).fontSize
);
// we create a node with 1ch width, measure it in px and remove it
const node = document.createElement("div");
node.style.width = "1ch";
node.style.position = "absolute";
element.appendChild(node);
const ch = Number.parseFloat(getComputedStyle(node).width);
element.removeChild(node);
return {
ch, // 1ch in pixels
vw, // 1vw in pixels
vh, // 1vh in pixels
em, // 1em in pixels
rem, // 1rem in pixels
px: 1, // always 1, simplifies conversions and types, i.e valueTo = valueFrom * unitSizes[from] / unitSizes[to]
};
};
const readComputedStyles = (element: HTMLElement) => {
const selectedState = $selectedStyleState.get();
const pseudoElement =
selectedState && isPseudoElement(selectedState) ? selectedState : undefined;
const propertySizes: PropertySizes = {};
const computedValues: Partial<Record<CssProperty, string>> = {};
let computedStyle: CSSStyleDeclaration;
try {
computedStyle = getComputedStyle(element, pseudoElement);
} catch {
// Some selectable pseudo-elements cannot be sampled with getComputedStyle.
return { propertySizes, computedValues };
}
for (const property in propertiesData) {
const propertyValue = computedStyle.getPropertyValue(property);
computedValues[property as CssProperty] = propertyValue;
try {
const value = CSSStyleValue.parse(property, propertyValue);
if (value instanceof CSSUnitValue) {
propertySizes[property as CssProperty] = {
type: "unit",
// px | number | percent etc
unit:
value.unit === "percent" ? "%" : (value.unit as UnitValue["unit"]),
value: value.value,
};
}
} catch (error) {
// failed with unknown property like -moz-osx-font-smoothing
// also firefox does not support CSSStyleValue
}
}
if (pseudoElement === undefined && computedStyle.aspectRatio === "auto") {
const parentStyle =
element.parentElement && getComputedStyle(element.parentElement);
const isOutOfFlow =
computedStyle.position === "absolute" ||
computedStyle.position === "fixed";
const isFlexItem = !isOutOfFlow && parentStyle?.display.includes("flex");
const isGridItem = !isOutOfFlow && parentStyle?.display.includes("grid");
const verticalWritingMode =
parentStyle?.writingMode.startsWith("vertical") ||
parentStyle?.writingMode.startsWith("sideways");
const flexMainHeight =
parentStyle?.flexDirection.startsWith("column") !== verticalWritingMode;
for (const property of ["min-width", "min-height"] as const) {
if (computedValues[property] !== "auto") {
continue;
}
const isMainAxis = (property === "min-height") === flexMainHeight;
const overflow =
property === "min-height"
? computedStyle.overflowY
: computedStyle.overflowX;
const nonScrollable = overflow === "visible" || overflow === "clip";
// Flex and grid items can have a content-based automatic minimum only
// on non-scrollable axes. Flex cross-axis minima always use zero.
if (
parentStyle?.display === "contents" ||
(isGridItem && nonScrollable) ||
(isFlexItem && isMainAxis && nonScrollable)
) {
continue;
}
computedValues[property] = "0px";
}
}
return { propertySizes, computedValues };
};
const subscribeSelectedInstance = (
selectedInstanceSelector: Readonly<InstanceSelector>,
debounceEffect: (callback: () => void) => void,
syncSingleSelectionStores: boolean
) => {
if (selectedInstanceSelector.length === 0) {
return;
}
const selector = [...selectedInstanceSelector];
const instanceId = selectedInstanceSelector[0];
let visibleElements = getVisibleElementsByInstanceSelector(
selectedInstanceSelector
);
const updateScroll = () => {
if (syncSingleSelectionStores === false) {
return;
}
const bbox = getAllElementsBoundingBox(visibleElements);
if (visibleElements.length === 0) {
return;
}
scrollIntoView(visibleElements[0], bbox);
};
const updateElements = () => {
visibleElements = getVisibleElementsByInstanceSelector(
selectedInstanceSelector
);
};
const updateInflation = () => {
if (visibleElements.length === 0) {
return;
}
for (const element of visibleElements) {
const selectorId = element.getAttribute(selectorIdAttribute);
if (selectorId === null) {
continue;
}
const instanceSelector = selectorId.split(",");
if (instanceSelector.length === 0) {
continue;
}
inflateInstance(instanceSelector[0], false);
}
// Synchronously execute inflateInstance to calculate right outline
// This fixes an issue, when new element outline was calculated before inflation calculations
inflateInstance(instanceId, true);
};
updateInflation();
const showOutline = () => {
if ($isResizingCanvas.get()) {
return;
}
setOutline(
selector,
instanceId,
visibleElements,
syncSingleSelectionStores
);
};
// effect close to rendered element also catches dnd remounts
// so actual state is always provided here
showOutline();
const updateStores = () => {
if (syncSingleSelectionStores === false) {
return;
}
const elements = getAllElementsByInstanceSelector(selectedInstanceSelector);
if (elements.length === 0) {
return;
}
const [element] = elements;
// trigger style recomputing every time instance styles are changed
const unitSizes = calculateUnitSizes(element);
const { propertySizes, computedValues } = readComputedStyles(element);
$selectedInstanceSizes.set({ unitSizes, propertySizes, computedValues });
const styleSourceSelections = $styleSourceSelections.get();
const styleSources = $styleSources.get();
const { stylesByStyleSourceId } = $stylesIndex.get();
const matchingStatesByInstanceId = new Map<string, Set<string>>();
const elementsByInstanceId = new Map<string, HTMLElement>();
for (
let ancestor: HTMLElement | null = element;
ancestor;
ancestor = ancestor.parentElement
) {
const id = ancestor.getAttribute(selectorIdAttribute)?.split(",")[0];
if (id) {
elementsByInstanceId.set(id, ancestor);
}
}
for (const [index, id] of selectedInstanceSelector.entries()) {
const target = elementsByInstanceId.get(id);
if (!target) {
continue;
}
const ownSources = new Set(styleSourceSelections.get(id)?.values);
ownSources.add(getTagStyleId(target.localName));
const ancestorSources = new Set<string>();
for (const ancestorId of selectedInstanceSelector.slice(index + 1)) {
for (const sourceId of styleSourceSelections.get(ancestorId)?.values ??
[]) {
ancestorSources.add(sourceId);
}
}
for (
let ancestor = target.parentElement;
ancestor;
ancestor = ancestor.parentElement
) {
const sourceId = getTagStyleId(ancestor.localName);
if (styleSources.get(sourceId)?.type === "tag") {
ancestorSources.add(sourceId);
}
}
const availableStates = new Set<string>();
const ancestorStates = new Set<string>();
const activeStates = new Set<string>();
for (const sourceId of ownSources) {
for (const styleDecl of stylesByStyleSourceId.get(sourceId) ?? []) {
if (styleDecl.state) {
availableStates.add(styleDecl.state);
}
}
}
for (const sourceId of ancestorSources) {
for (const styleDecl of stylesByStyleSourceId.get(sourceId) ?? []) {
if (styleDecl.state?.startsWith(" ")) {
ancestorStates.add(styleDecl.state);
}
}
}
for (const state of ancestorStates) {
const validation = validateSelector(state);
if (
validation.success &&
validation.type === "tag" &&
validation.tag.toLowerCase() === target.localName &&
validation.condition
) {
try {
if (target.matches(state.trim())) {
activeStates.add(validation.condition);
}
} catch {
warnOnce(true, `state selector "${state}" is invalid`);
}
}
}
for (const state of availableStates) {
if (
validateSelector(state, { allowDescendants: false }).success === false
) {
continue;
}
try {
// pseudo classes like :open or :current are not supported in .matches method
if (target.matches(state)) {
activeStates.add(state);
}
} catch {
warnOnce(true, `state selector "${state}" is invalid`);
}
}
matchingStatesByInstanceId.set(id, activeStates);
}
const previousStates = $selectedInstanceStatesByInstanceId.get();
if (
previousStates.size !== matchingStatesByInstanceId.size ||
[...matchingStatesByInstanceId].some(([id, states]) => {
const previous = previousStates.get(id);
return previous === undefined || !areSetsEqual(states, previous);
})
) {
$selectedInstanceStatesByInstanceId.set(matchingStatesByInstanceId);
}
const activeStates =
matchingStatesByInstanceId.get(instanceId) ?? new Set<string>();
const selectedStates = $selectedInstanceStates.get();
if (!areSetsEqual(activeStates, selectedStates)) {
$selectedInstanceStates.set(activeStates);
}
};
let updateStoreTimeouHandle: undefined | ReturnType<typeof setTimeout>;
const update = () => {
debounceEffect(() => {
updateElements();
// Disconnect before inflation so the observer doesn't see
// the inline style changes inflation makes on the parent element.
// updateObservers() reconnects after.
mutationObserver.disconnect();
// Having hover etc, element can have no size because of that
// Newly created element can have 0 size
updateInflation();
// contentRect has wrong x/y values for absolutely positioned element.
// getBoundingClientRect is used instead.
showOutline();
updateStores();
// Having that elements can be changed (i.e. div => address tag change, observe again)
updateObservers();
});
};
// update scroll state
updateScroll();
// Lightweight update
const updateOutline: MutationCallback = (mutationRecords) => {
if (hasDoNotTrackMutationRecord(mutationRecords)) {
return;
}
showOutline();
};
const resizeObserver = new ResizeObserver(update);
const mutationHandler: MutationCallback = (mutationRecords) => {
if (hasDoNotTrackMutationRecord(mutationRecords)) {
return;
}
update();
};
// detect movement of the element within same parent
// React prevent remount when key stays the same
// `attributes: true` fixes issues with popups after trigger text editing
// that cause radix to incorrectly set content in a wrong position at first render
const mutationObserver = new MutationObserver(mutationHandler);
const updateObservers = () => {
for (const element of visibleElements) {
resizeObserver.observe(element);
const parent = element?.parentElement;
if (parent) {
mutationObserver.observe(parent, {
childList: true,
attributes: true,
attributeOldValue: true,
attributeFilter: ["style", "class"],
});
}
}
};
const bodyStyleMutationObserver = new MutationObserver(updateOutline);
// previewStyle variables
bodyStyleMutationObserver.observe(document.body, {
attributes: true,
attributeOldValue: true,
attributeFilter: ["style", "class"],
});
updateObservers();
updateStores();
const unsubscribe$stylesIndex = $stylesIndex.subscribe(update);
const unsubscribeSelectedStyleState = $selectedStyleState.subscribe(update);
const unsubscribe$instances = $instances.subscribe(update);
const unsubscribePropValuesStore =
$propValuesByInstanceSelectorWithMemoryProps.subscribe(update);
const unsubscribeIsResizingCanvas = $isResizingCanvas.subscribe(
(isResizing) => {
if (isResizing) {
return hideOutline(selector, syncSingleSelectionStores);
}
showOutline();
}
);
const unsubscribeScrollState = subscribeScrollState({
onScrollStart() {
hideOutline(selector, syncSingleSelectionStores);
},
onScrollEnd() {
showOutline();
},
});
const unsubscribeWindowResize = subscribeWindowResize({
onResizeStart() {
hideOutline(selector, syncSingleSelectionStores);
},
onResizeEnd() {
showOutline();
},
});
if (syncSingleSelectionStores) {
$selectedInstanceRenderState.set("mounted");
}
return () => {
clearTimeout(updateStoreTimeouHandle);
hideOutline(selector, syncSingleSelectionStores);
if (syncSingleSelectionStores) {
$selectedInstanceRenderState.set("notMounted");
}
resizeObserver.disconnect();
mutationObserver.disconnect();
bodyStyleMutationObserver.disconnect();
unsubscribeIsResizingCanvas();
unsubscribeScrollState();
unsubscribeWindowResize();
unsubscribe$stylesIndex();
unsubscribeSelectedStyleState();
unsubscribe$instances();
unsubscribePropValuesStore();
};
};
export const subscribeSelected = (
debounceEffect: (callback: () => void) => void
) => {
let previousSelectedInstances: readonly InstanceSelector[] | undefined =
undefined;
let unsubscribeSelectedInstances = () => {};
const unsubscribe = $allSelectedInstanceSelectors.subscribe(
(instanceSelectors) => {
if (instanceSelectors !== previousSelectedInstances) {
unsubscribeSelectedInstances();
$selectedInstanceOutline.set(undefined);
$selectedInstanceOutlines.set([]);
const unsubscribes = instanceSelectors.map((instanceSelector) =>
subscribeSelectedInstance(
instanceSelector,
debounceEffect,
instanceSelectors.length === 1
)
);
unsubscribeSelectedInstances = () => {
for (const unsubscribe of unsubscribes) {
unsubscribe?.();
}
};
previousSelectedInstances = instanceSelectors;
}
}
);
return () => {
unsubscribe();
unsubscribeSelectedInstances();
};
};