mirror of
https://github.com/webstudio-is/webstudio.git
synced 2026-12-01 21:05:42 +09:00
fix: Show scoped Tag colors on selected descendants (#6677)
When an H2 gets its color from a Tag selector on its container, selecting the H2 can show black in the Style panel. The panel now shows the matching color. A Token or Local style on the H2 can still override the container's Tag selector. ## Plan and progress - [x] Reproduce the selected H2 showing the container color instead of its nested Tag color. - [x] Give descendant Tag selectors the intended CSS specificity in Builder and published CSS. - [x] Include matching ancestor Tag declarations in the Style panel's color calculation. - [x] Cover the selected H2 and regular and atomic CSS output with focused tests. - [x] Review documentation impact and update the Tag styles and selectors guides. - [x] Match the panel's competing ancestor Tag rules to CSS breakpoint and stylesheet order. - [x] Match the editing preview's selector specificity to the saved rule. - [x] Use the descendant separator directly when detecting nested selectors. - [x] Allow the same supported selector forms in Tag, Token, and Local sources. - [x] Match global Tag descendant styles in the editing preview and Style panel. - [x] Document nested Tag selector examples in the Tag styles guide. - [x] Explain supported selectors in Add more while its input is focused. - [x] Review and simplify nested state matching; preserve the entered selector text. - [x] Consolidate cascade declaration lookup and reuse the validated selector parse result. - [x] Align Builder and MCP selector entry with one validation rule; preserve saved selectors. - [x] Fix nested-selector source badges and preserve valid instance selection. - [x] Keep descendant conditions scoped to the matched element during inheritance. - [x] Match saved nested selectors regardless of tag casing or leading whitespace. - [ ] Verify both fixes, resolve review threads, and review CI. The panel model needs ancestor matching because it computes styles without querying the rendered element. The complete PR adds about 195 net non-test lines. The added work covers selector entry, active nested states, and matching Tag rules in the panel; the saved CSS output already supported nested tags. CSS generation uses `:where()` around the container selector so the nested tag can override the global tag style while the H2's own Token can override the nested tag style. No stored data changes. Checks passed locally: focused Builder style source, active state, panel model, and canvas preview tests; CSS data and runtime tests; Builder, CSS data, and project-build typechecks; lint, formatting, and `git diff --check`. The focused Add more menu was checked in Storybook in both themes. CI passed for commit `838cf4293f`; CI for `224f11e274` is pending. The full Builder app suite was started but stopped after it stopped producing results; the two affected suites passed independently. This follow-up adds 67 net non-test lines to track matching states by instance and match saved descendant selectors using the shared parser. No fixture inputs or generated fixture outputs changed. Ref #5657
This commit is contained in:
1 parent
2b9ce760bb
commit
b0d7cc2e7b
30 files changed
+1071
-338
No files matched your search
@@ -2,11 +2,111 @@ import { act } from "react-dom/test-utils";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
import { userEvent } from "@vitest/browser/context";
|
||||
import { TooltipProvider } from "@webstudio-is/design-system";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import { getTagStyleId } from "@webstudio-is/sdk";
|
||||
import {
|
||||
selectInstance,
|
||||
$selectedInstanceSelector,
|
||||
$selectedPageId,
|
||||
$selectedStyleSources,
|
||||
$selectedStyleState,
|
||||
$temporaryTagStyleId,
|
||||
} from "~/shared/nano-states";
|
||||
import {
|
||||
$breakpoints,
|
||||
$instances,
|
||||
$pages,
|
||||
$styleSources,
|
||||
} from "~/shared/sync/data-stores";
|
||||
import type { ComputedStyleDecl } from "~/shared/style-object-model";
|
||||
import { createAssetManagerTestRenderer } from "~/builder/shared/asset-manager/test-utils";
|
||||
import { PropertyInlineLabel } from "./property-label";
|
||||
import { PropertyInfo, PropertyInlineLabel } from "./property-label";
|
||||
|
||||
const renderer = createAssetManagerTestRenderer();
|
||||
afterEach(renderer.cleanup);
|
||||
afterEach(() => {
|
||||
renderer.cleanup();
|
||||
selectInstance(undefined);
|
||||
$selectedPageId.set(undefined);
|
||||
$pages.set(undefined);
|
||||
$instances.set(new Map());
|
||||
$styleSources.set(new Map());
|
||||
$breakpoints.set(new Map());
|
||||
$selectedStyleSources.set(new Map());
|
||||
$selectedStyleState.set(undefined);
|
||||
$temporaryTagStyleId.set(undefined);
|
||||
});
|
||||
|
||||
test("nested source badge keeps a valid ancestor selection and is cascaded", async () => {
|
||||
const pages = createDefaultPages({ rootInstanceId: "container" });
|
||||
$pages.set(pages);
|
||||
$selectedPageId.set(pages.homePageId);
|
||||
$instances.set(
|
||||
new Map([
|
||||
[
|
||||
"container",
|
||||
{
|
||||
type: "instance" as const,
|
||||
id: "container",
|
||||
component: "Box",
|
||||
children: [{ type: "id" as const, value: "heading" }],
|
||||
},
|
||||
],
|
||||
[
|
||||
"heading",
|
||||
{
|
||||
type: "instance" as const,
|
||||
id: "heading",
|
||||
component: "Heading",
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
])
|
||||
);
|
||||
const tagStyleId = getTagStyleId("div");
|
||||
$styleSources.set(
|
||||
new Map([[tagStyleId, { type: "tag", id: tagStyleId, tag: "div" }]])
|
||||
);
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "Base" }]]));
|
||||
selectInstance(["heading", "container"]);
|
||||
const value = { type: "keyword", value: "red" } as const;
|
||||
const styles: ComputedStyleDecl[] = [
|
||||
{
|
||||
property: "color",
|
||||
source: {
|
||||
name: "remote",
|
||||
instanceId: "container",
|
||||
styleSourceId: tagStyleId,
|
||||
breakpointId: "base",
|
||||
state: " h2:hover",
|
||||
},
|
||||
cascadedValue: value,
|
||||
computedValue: value,
|
||||
usedValue: value,
|
||||
},
|
||||
];
|
||||
const container = renderer.render(
|
||||
<PropertyInfo
|
||||
title="Color"
|
||||
property="color"
|
||||
description=""
|
||||
styles={styles}
|
||||
/>
|
||||
);
|
||||
|
||||
const sourceButton = Array.from(container.querySelectorAll("button")).find(
|
||||
(button) => button.textContent?.includes("div")
|
||||
);
|
||||
expect(sourceButton).toBeDefined();
|
||||
await act(async () => userEvent.click(sourceButton!));
|
||||
|
||||
expect($selectedInstanceSelector.get()).toEqual(["container"]);
|
||||
expect($selectedStyleSources.get().get("container")).toBe(tagStyleId);
|
||||
expect($selectedStyleState.get()).toBe(" h2:hover");
|
||||
expect($temporaryTagStyleId.get()).toBe(tagStyleId);
|
||||
expect(container.textContent).toContain("Cascaded:");
|
||||
$instances.set(new Map($instances.get()));
|
||||
expect($selectedInstanceSelector.get()).toEqual(["container"]);
|
||||
});
|
||||
|
||||
test("inline property labels offer keyboard-accessible information without a reset action", async () => {
|
||||
const container = renderer.render(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useStore } from "@nanostores/react";
|
||||
import { useState, type ReactNode } from "react";
|
||||
import { ROOT_INSTANCE_ID } from "@webstudio-is/sdk";
|
||||
import { AlertIcon, ResetIcon } from "@webstudio-is/icons";
|
||||
import { toValue, type CssProperty } from "@webstudio-is/css-engine";
|
||||
import { propertiesData } from "@webstudio-is/css-data";
|
||||
@@ -159,7 +160,12 @@ export const PropertyInfo = ({
|
||||
if (target === undefined) {
|
||||
return;
|
||||
}
|
||||
selectInstance(target.instanceSelector);
|
||||
const targetSelector = target.instanceSelector;
|
||||
selectInstance(
|
||||
targetSelector.length > 1 && targetSelector.at(-1) === ROOT_INSTANCE_ID
|
||||
? targetSelector.slice(0, -1)
|
||||
: targetSelector
|
||||
);
|
||||
if (source.styleSourceId) {
|
||||
if (styleSources.get(source.styleSourceId)?.type === "tag") {
|
||||
$temporaryTagStyleId.set(source.styleSourceId);
|
||||
@@ -211,13 +217,15 @@ export const PropertyInfo = ({
|
||||
selectedInstanceId !== undefined &&
|
||||
(sourceColor === "remote" || sourceColor === "preset")
|
||||
) {
|
||||
const sourceInstances = styles
|
||||
.filter((style) => style.source.name === sourceColor)
|
||||
.map((style) => style.source.instanceId);
|
||||
const matchingStyles = styles.filter(
|
||||
(style) => style.source.name === sourceColor
|
||||
);
|
||||
if (
|
||||
sourceInstances.every(
|
||||
(instanceId) =>
|
||||
instanceId !== undefined && instanceId !== selectedInstanceId
|
||||
matchingStyles.every(
|
||||
({ source }) =>
|
||||
source.instanceId !== undefined &&
|
||||
source.instanceId !== selectedInstanceId &&
|
||||
source.state?.startsWith(" ") !== true
|
||||
)
|
||||
) {
|
||||
sourceLabel = sourceColor === "remote" ? "Inherited" : "Preset";
|
||||
@@ -227,7 +235,9 @@ export const PropertyInfo = ({
|
||||
: "Comes from a Webstudio component default on an ancestor element.";
|
||||
} else if (
|
||||
sourceColor === "remote" &&
|
||||
sourceInstances.every((instanceId) => instanceId === selectedInstanceId)
|
||||
matchingStyles.every(
|
||||
({ source }) => source.instanceId === selectedInstanceId
|
||||
)
|
||||
) {
|
||||
sourceDescription =
|
||||
"Comes from another style source, breakpoint, or state on this element.";
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
$propsIndex,
|
||||
$selectedBreakpoint,
|
||||
$selectedInstanceStates,
|
||||
$selectedInstanceStatesByInstanceId,
|
||||
$selectedOrLastStyleSourceSelector,
|
||||
} from "~/shared/nano-states";
|
||||
import { $breakpoints } from "~/shared/sync/data-stores";
|
||||
@@ -233,6 +234,7 @@ export const $styleObjectModel = computed(
|
||||
$instanceComponents,
|
||||
$matchingBreakpoints,
|
||||
$selectedInstanceStates,
|
||||
$selectedInstanceStatesByInstanceId,
|
||||
],
|
||||
(
|
||||
styles,
|
||||
@@ -242,7 +244,8 @@ export const $styleObjectModel = computed(
|
||||
instanceTags,
|
||||
instanceComponents,
|
||||
matchingBreakpoints,
|
||||
matchingStates
|
||||
matchingStates,
|
||||
matchingStatesByInstanceId
|
||||
): StyleObjectModel => {
|
||||
const tagStyleIds = new Map<string, string>();
|
||||
for (const source of styleSources.values()) {
|
||||
@@ -259,6 +262,7 @@ export const $styleObjectModel = computed(
|
||||
instanceComponents,
|
||||
matchingBreakpoints,
|
||||
matchingStates,
|
||||
matchingStatesByInstanceId,
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
+38
@@ -190,6 +190,44 @@ test("describes Copy and keeps the style source menu width stable", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("describes the supported selectors when Add more receives focus", () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
act(() =>
|
||||
root.render(
|
||||
<StyleSourceMenu
|
||||
open
|
||||
onOpenChange={() => {}}
|
||||
selectedItemSelector={undefined}
|
||||
item={{
|
||||
id: "tag-style:button",
|
||||
label: "button",
|
||||
source: "tag",
|
||||
disabled: false,
|
||||
locked: false,
|
||||
states: [],
|
||||
}}
|
||||
hasStyles={false}
|
||||
states={[]}
|
||||
/>
|
||||
)
|
||||
);
|
||||
const input = document.querySelector<HTMLInputElement>(
|
||||
"[role=menu] form input"
|
||||
);
|
||||
expect(input).not.toBeNull();
|
||||
act(() => input?.focus());
|
||||
expect(document.querySelector("[role=menu]")?.textContent).toContain(
|
||||
"Start with a tag, such as h2, h2:hover, or h2::before"
|
||||
);
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
}
|
||||
});
|
||||
|
||||
test("disables Copy when a source has no declarations", () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
|
||||
@@ -124,6 +124,8 @@ const menuActionDescriptions = {
|
||||
unlock: "Allow style changes on this token again.",
|
||||
detach: "Remove this token from the element without deleting it.",
|
||||
delete: "Permanently delete this token and all its styles from the project.",
|
||||
addMore:
|
||||
"Use :hover or [data-state=open] to style this element in a state, and ::before to style its pseudo-element. Start with a tag, such as h2, h2:hover, or h2::before, to style nested elements.",
|
||||
} as const;
|
||||
|
||||
type MenuAction = keyof typeof menuActionDescriptions;
|
||||
@@ -172,11 +174,13 @@ const getSelectorDescription = (selector: string | null | undefined) => {
|
||||
|
||||
const SelectorCombobox = ({
|
||||
existingSelectors,
|
||||
allowDescendants,
|
||||
onFocus,
|
||||
onBlur,
|
||||
onSelect,
|
||||
}: {
|
||||
existingSelectors: string[];
|
||||
allowDescendants: boolean;
|
||||
onFocus: () => void;
|
||||
onBlur: () => void;
|
||||
onSelect: (selector: string) => void;
|
||||
}) => {
|
||||
const [value, setValue] = useState("");
|
||||
@@ -184,10 +188,10 @@ const SelectorCombobox = ({
|
||||
|
||||
const handleSubmit = (selector: string) => {
|
||||
let normalizedSelector = selector;
|
||||
let validation = validateSelector(normalizedSelector, { allowDescendants });
|
||||
if (validation.success === false && allowDescendants) {
|
||||
let validation = validateSelector(normalizedSelector);
|
||||
if (validation.success === false) {
|
||||
const tagSelector = ` ${selector}`;
|
||||
const tagValidation = validateSelector(tagSelector, { allowDescendants });
|
||||
const tagValidation = validateSelector(tagSelector);
|
||||
if (tagValidation.success && tagValidation.type === "tag") {
|
||||
normalizedSelector = tagSelector;
|
||||
validation = tagValidation;
|
||||
@@ -202,14 +206,14 @@ const SelectorCombobox = ({
|
||||
setValue("");
|
||||
};
|
||||
|
||||
const availableItems = allSelectors.filter(
|
||||
(selector) =>
|
||||
(allowDescendants || tags.includes(selector) === false) &&
|
||||
existingSelectors.every((s) => s.trim() !== selector)
|
||||
const availableItems = allSelectors.filter((selector) =>
|
||||
existingSelectors.every((s) => s.trim() !== selector)
|
||||
);
|
||||
|
||||
return (
|
||||
<form
|
||||
onFocus={onFocus}
|
||||
onBlur={onBlur}
|
||||
onKeyDown={(event) => event.stopPropagation()}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
@@ -271,13 +275,7 @@ type StyleSourceMenuProps = {
|
||||
};
|
||||
|
||||
export const StyleSourceMenu = (props: StyleSourceMenuProps) => {
|
||||
const availableStates =
|
||||
props.item.source === "tag"
|
||||
? props.states.filter(
|
||||
({ selector }) =>
|
||||
validateSelector(selector, { allowDescendants: false }).success
|
||||
)
|
||||
: props.states;
|
||||
const availableStates = props.states;
|
||||
const [highlightedSelector, setHighlightedSelector] = useState<{
|
||||
selector: string;
|
||||
type: "state" | "pseudoElement" | "tag";
|
||||
@@ -549,7 +547,11 @@ export const StyleSourceMenu = (props: StyleSourceMenuProps) => {
|
||||
existingSelectors={availableStates.map(
|
||||
(state) => state.selector
|
||||
)}
|
||||
allowDescendants={props.item.source !== "tag"}
|
||||
onFocus={() => {
|
||||
setHighlightedSelector(undefined);
|
||||
setHighlightedAction("addMore");
|
||||
}}
|
||||
onBlur={() => setHighlightedAction(undefined)}
|
||||
onSelect={(selector) =>
|
||||
props.onAddSelector?.(props.item.id, selector)
|
||||
}
|
||||
|
||||
@@ -6,11 +6,13 @@ import {
|
||||
$selectedInstanceOutline,
|
||||
$selectedInstanceOutlines,
|
||||
$selectedInstanceStates,
|
||||
$selectedInstanceStatesByInstanceId,
|
||||
selectInstances,
|
||||
} from "~/shared/nano-states";
|
||||
import {
|
||||
$instances,
|
||||
$styleSourceSelections,
|
||||
$styleSources,
|
||||
$styles,
|
||||
} from "~/shared/sync/data-stores";
|
||||
import { subscribeSelected } from "./selected-instance-effects";
|
||||
@@ -95,9 +97,11 @@ beforeEach(() => {
|
||||
])
|
||||
);
|
||||
$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 = "";
|
||||
@@ -113,8 +117,10 @@ afterEach(() => {
|
||||
$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([]);
|
||||
});
|
||||
@@ -173,6 +179,47 @@ describe("subscribeSelected", () => {
|
||||
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",
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} 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,
|
||||
@@ -15,12 +16,16 @@ import {
|
||||
$stylesIndex,
|
||||
$propValuesByInstanceSelectorWithMemoryProps,
|
||||
$selectedInstanceStates,
|
||||
$selectedInstanceStatesByInstanceId,
|
||||
$selectedStyleState,
|
||||
$allSelectedInstanceSelectors,
|
||||
type UnitSizes,
|
||||
type PropertySizes,
|
||||
} from "~/shared/nano-states";
|
||||
import { $styleSourceSelections } from "~/shared/sync/data-stores";
|
||||
import {
|
||||
$styleSourceSelections,
|
||||
$styleSources,
|
||||
} from "~/shared/sync/data-stores";
|
||||
import {
|
||||
getAllElementsBoundingBox,
|
||||
getVisibleElementsByInstanceSelector,
|
||||
@@ -288,44 +293,104 @@ const subscribeSelectedInstance = (
|
||||
const { propertySizes, computedValues } = readComputedStyles(element);
|
||||
$selectedInstanceSizes.set({ unitSizes, propertySizes, computedValues });
|
||||
|
||||
const availableStates = new Set<string>();
|
||||
const instanceStyleSourceIds = new Set(
|
||||
$styleSourceSelections.get().get(instanceId)?.values
|
||||
);
|
||||
instanceStyleSourceIds.add(getTagStyleId(element.localName));
|
||||
const styleSourceSelections = $styleSourceSelections.get();
|
||||
const styleSources = $styleSources.get();
|
||||
const styles = $styles.get();
|
||||
for (const styleDecl of styles.values()) {
|
||||
if (
|
||||
instanceStyleSourceIds.has(styleDecl.styleSourceId) &&
|
||||
styleDecl.state
|
||||
) {
|
||||
availableStates.add(styleDecl.state);
|
||||
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);
|
||||
}
|
||||
}
|
||||
const activeStates = new Set<string>();
|
||||
for (const state of availableStates) {
|
||||
if (
|
||||
validateSelector(state, { allowDescendants: false }).success === false
|
||||
) {
|
||||
for (const [index, id] of selectedInstanceSelector.entries()) {
|
||||
const target = elementsByInstanceId.get(id);
|
||||
if (!target) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
// pseudo classes like :open or :current are not supported in .matches method
|
||||
if (element.matches(state)) {
|
||||
activeStates.add(state);
|
||||
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);
|
||||
}
|
||||
} catch {
|
||||
warnOnce(true, `state selector "${state}" is invalid`);
|
||||
}
|
||||
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 activeStates = new Set<string>();
|
||||
for (const styleDecl of styles.values()) {
|
||||
if (!styleDecl.state) {
|
||||
continue;
|
||||
}
|
||||
if (ownSources.has(styleDecl.styleSourceId)) {
|
||||
availableStates.add(styleDecl.state);
|
||||
}
|
||||
if (ancestorSources.has(styleDecl.styleSourceId)) {
|
||||
const validation = validateSelector(styleDecl.state);
|
||||
if (
|
||||
validation.success &&
|
||||
validation.type === "tag" &&
|
||||
validation.tag.toLowerCase() === target.localName &&
|
||||
validation.condition
|
||||
) {
|
||||
try {
|
||||
if (target.matches(styleDecl.state.trim())) {
|
||||
activeStates.add(validation.condition);
|
||||
}
|
||||
} catch {
|
||||
warnOnce(true, `state selector "${styleDecl.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 (
|
||||
activeStates.size !== selectedStates.size ||
|
||||
Array.from(activeStates).some(
|
||||
(state) => selectedStates.has(state) === false
|
||||
)
|
||||
) {
|
||||
if (!areSetsEqual(activeStates, selectedStates)) {
|
||||
$selectedInstanceStates.set(activeStates);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -228,20 +228,41 @@ describe("renderStateStyles", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("descendant tag styles preview on the matching tag", () => {
|
||||
test.each([" h1", ' h2[a="123"]', " h2:hover", " h2::before"])(
|
||||
"descendant tag styles preview on the matching tag: %s",
|
||||
(state) => {
|
||||
const sheet = createTestSheet();
|
||||
renderStateStyles({
|
||||
instanceStyles: {
|
||||
instanceId: "box",
|
||||
selectedState: state,
|
||||
breakpoints: [{ id: "base", label: "Base" }],
|
||||
styles: [createStyleDecl()],
|
||||
},
|
||||
sheet,
|
||||
transformValue: mockTransformValue,
|
||||
toStyleValue: mockToStyleValue,
|
||||
});
|
||||
expect(sheet.cssText).toContain(`:where([data-ws-id="box"])${state}`);
|
||||
}
|
||||
);
|
||||
|
||||
test("global Tag descendant preview keeps the saved selector specificity", () => {
|
||||
const sheet = createTestSheet();
|
||||
renderStateStyles({
|
||||
instanceStyles: {
|
||||
instanceId: "box",
|
||||
selectedState: " h1",
|
||||
selectedState: " h2:hover",
|
||||
breakpoints: [{ id: "base", label: "Base" }],
|
||||
styles: [createStyleDecl()],
|
||||
styles: [createStyleDecl({ styleSourceId: getTagStyleId("div") })],
|
||||
},
|
||||
sheet,
|
||||
transformValue: mockTransformValue,
|
||||
toStyleValue: mockToStyleValue,
|
||||
});
|
||||
expect(sheet.cssText).toContain('[data-ws-id="box"] h1');
|
||||
expect(sheet.cssText).toContain(
|
||||
':where([data-ws-id="box"]):where(div) h2:hover'
|
||||
);
|
||||
});
|
||||
|
||||
test("Tag preview selectors stay below instance selectors at every breakpoint", () => {
|
||||
@@ -995,7 +1016,7 @@ test("ephemeral Tag state edits update and clean up the selected preview", () =>
|
||||
expect(
|
||||
document.querySelector('style[data-webstudio="state-styles"]')
|
||||
?.textContent
|
||||
).toContain('[data-ws-id="ephemeral-tag-test"] h1');
|
||||
).toContain(':where([data-ws-id="ephemeral-tag-test"]) h1');
|
||||
} finally {
|
||||
$ephemeralStyles.set([]);
|
||||
unsubscribeEphemeral();
|
||||
|
||||
@@ -848,14 +848,19 @@ const getTagStatePreviewSelector = (
|
||||
tag: string,
|
||||
state: string
|
||||
) =>
|
||||
shouldSimulateState(state)
|
||||
? `:where(${selector}):is(${tag}, ${tag}${state})`
|
||||
: `:where(${selector})${tag}${getStatePreviewSelector(state)}`;
|
||||
state.startsWith(" ")
|
||||
? `:where(${selector}):where(${tag})${state}`
|
||||
: shouldSimulateState(state)
|
||||
? `:where(${selector}):is(${tag}, ${tag}${state})`
|
||||
: `:where(${selector})${tag}${getStatePreviewSelector(state)}`;
|
||||
|
||||
const getInstanceStatePreviewSelector = (selector: string, state: string) =>
|
||||
shouldSimulateState(state)
|
||||
? `${selector}:is(*, ${state})`
|
||||
: `${selector}${getStatePreviewSelector(state)}`;
|
||||
const getInstanceStatePreviewSelector = (selector: string, state: string) => {
|
||||
if (shouldSimulateState(state)) {
|
||||
return `${selector}:is(*, ${state})`;
|
||||
}
|
||||
const base = state.startsWith(" ") ? `:where(${selector})` : selector;
|
||||
return `${base}${getStatePreviewSelector(state)}`;
|
||||
};
|
||||
|
||||
const shouldRenderEphemeralTagState = (
|
||||
styleDecl: StyleDecl,
|
||||
|
||||
@@ -319,6 +319,9 @@ export const $selectedStyleSource = computed(
|
||||
* to display style values as remote
|
||||
*/
|
||||
export const $selectedInstanceStates = atom(new Set<string>());
|
||||
export const $selectedInstanceStatesByInstanceId = atom(
|
||||
new Map<string, Set<string>>()
|
||||
);
|
||||
|
||||
export const $hoveredInstanceSelector = atom<undefined | InstanceSelector>(
|
||||
undefined
|
||||
|
||||
@@ -1103,6 +1103,285 @@ test("tag token provides the source for an unstyled matching element", () => {
|
||||
).toMatchObject({ styleSourceId: id, instanceId: "box" });
|
||||
});
|
||||
|
||||
test("shows the div's nested h2 color when h2 is selected", () => {
|
||||
const model = createModel({
|
||||
css: "container { color: black; }",
|
||||
jsx: (
|
||||
<Box ws:id="container" class="container">
|
||||
<Heading ws:id="heading" ws:tag="h2" class="headingLocal" />
|
||||
</Box>
|
||||
),
|
||||
});
|
||||
const descendantStyle: StyleDecl = {
|
||||
styleSourceId: "container",
|
||||
breakpointId: "base",
|
||||
state: " h2",
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "purple" },
|
||||
};
|
||||
model.styles.set(getStyleDeclKey(descendantStyle), descendantStyle);
|
||||
|
||||
expect(
|
||||
getComputedStyleDecl({
|
||||
model,
|
||||
instanceSelector: ["heading", "container"],
|
||||
styleSourceId: "headingLocal",
|
||||
property: "color",
|
||||
})
|
||||
).toMatchObject({
|
||||
cascadedValue: { type: "keyword", value: "purple" },
|
||||
usedValue: { type: "keyword", value: "purple" },
|
||||
source: {
|
||||
instanceId: "container",
|
||||
styleSourceId: "container",
|
||||
state: " h2",
|
||||
},
|
||||
});
|
||||
|
||||
for (const state of ['[a="123"]', ":hover", "::before"]) {
|
||||
const scopedStyle: StyleDecl = {
|
||||
...descendantStyle,
|
||||
state: ` h2${state}`,
|
||||
value: { type: "keyword", value: "green" },
|
||||
};
|
||||
model.styles.set(getStyleDeclKey(scopedStyle), scopedStyle);
|
||||
expect(
|
||||
getComputedStyleDecl({
|
||||
model,
|
||||
instanceSelector: ["heading", "container"],
|
||||
styleSourceId: "headingLocal",
|
||||
state,
|
||||
property: "color",
|
||||
}).usedValue
|
||||
).toEqual({ type: "keyword", value: "green" });
|
||||
}
|
||||
|
||||
model.styleSourceSelections.set("heading", {
|
||||
instanceId: "heading",
|
||||
values: ["headingToken"],
|
||||
});
|
||||
const headingStyle: StyleDecl = {
|
||||
...descendantStyle,
|
||||
styleSourceId: "headingToken",
|
||||
state: undefined,
|
||||
value: { type: "keyword", value: "red" },
|
||||
};
|
||||
model.styles.set(getStyleDeclKey(headingStyle), headingStyle);
|
||||
expect(
|
||||
getComputedStyleDecl({
|
||||
model,
|
||||
instanceSelector: ["heading", "container"],
|
||||
property: "color",
|
||||
}).usedValue
|
||||
).toEqual({ type: "keyword", value: "red" });
|
||||
});
|
||||
|
||||
test("keeps a descendant attribute state off its ancestor's inherited color", () => {
|
||||
const model = createModel({
|
||||
css: "container { color: black; }",
|
||||
jsx: (
|
||||
<Box ws:id="container" class="container">
|
||||
<Heading ws:id="heading" ws:tag="h2" />
|
||||
</Box>
|
||||
),
|
||||
matchingStates: new Set(["[data-active]"]),
|
||||
});
|
||||
model.matchingStatesByInstanceId = new Map([
|
||||
["container", new Set()],
|
||||
["heading", new Set(["[data-active]"])],
|
||||
]);
|
||||
const parentState: StyleDecl = {
|
||||
styleSourceId: "container",
|
||||
breakpointId: "base",
|
||||
state: "[data-active]",
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
};
|
||||
const nestedState: StyleDecl = {
|
||||
...parentState,
|
||||
state: " h2[data-active]",
|
||||
property: "paddingTop",
|
||||
value: { type: "unit", unit: "px", value: 10 },
|
||||
};
|
||||
for (const styleDecl of [parentState, nestedState]) {
|
||||
model.styles.set(getStyleDeclKey(styleDecl), styleDecl);
|
||||
}
|
||||
expect(
|
||||
getComputedStyleDecl({
|
||||
model,
|
||||
instanceSelector: ["heading", "container"],
|
||||
styleSourceId: "heading",
|
||||
property: "color",
|
||||
}).usedValue
|
||||
).toEqual({ type: "keyword", value: "black" });
|
||||
model.matchingStatesByInstanceId?.set(
|
||||
"container",
|
||||
new Set(["[data-active]"])
|
||||
);
|
||||
expect(
|
||||
getComputedStyleDecl({
|
||||
model,
|
||||
instanceSelector: ["heading", "container"],
|
||||
styleSourceId: "heading",
|
||||
property: "color",
|
||||
}).usedValue
|
||||
).toEqual({ type: "keyword", value: "red" });
|
||||
});
|
||||
|
||||
test("matches saved nested tag casing and leading whitespace", () => {
|
||||
const model = createModel({
|
||||
css: "",
|
||||
jsx: (
|
||||
<Box ws:id="container" class="container">
|
||||
<Heading ws:id="heading" ws:tag="h2" />
|
||||
</Box>
|
||||
),
|
||||
});
|
||||
const styleDecl: StyleDecl = {
|
||||
styleSourceId: "container",
|
||||
breakpointId: "base",
|
||||
state: " H2",
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "purple" },
|
||||
};
|
||||
model.styles.set(getStyleDeclKey(styleDecl), styleDecl);
|
||||
expect(
|
||||
getComputedStyleDecl({
|
||||
model,
|
||||
instanceSelector: ["heading", "container"],
|
||||
property: "color",
|
||||
})
|
||||
).toMatchObject({
|
||||
usedValue: { type: "keyword", value: "purple" },
|
||||
source: { state: " H2" },
|
||||
});
|
||||
});
|
||||
|
||||
test("shows nested global Tag color and lets an attached Token override it", () => {
|
||||
const model = createModel({
|
||||
css: "",
|
||||
jsx: (
|
||||
<Box ws:id="container">
|
||||
<Heading ws:id="heading" ws:tag="h2" class="headingToken" />
|
||||
</Box>
|
||||
),
|
||||
matchingBreakpoints: ["base", "small"],
|
||||
});
|
||||
const id = getTagStyleId("div");
|
||||
model.tagStyleIds.set("div", id);
|
||||
const globalStyle: StyleDecl = {
|
||||
styleSourceId: id,
|
||||
breakpointId: "base",
|
||||
state: " h2:hover",
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "purple" },
|
||||
};
|
||||
model.styles.set(getStyleDeclKey(globalStyle), globalStyle);
|
||||
const selected = {
|
||||
model,
|
||||
instanceSelector: ["heading", "container"],
|
||||
state: ":hover",
|
||||
property: "color" as const,
|
||||
};
|
||||
expect(getComputedStyleDecl(selected).usedValue).toEqual({
|
||||
type: "keyword",
|
||||
value: "purple",
|
||||
});
|
||||
const headingTagId = getTagStyleId("h2");
|
||||
model.tagStyleIds.set("h2", headingTagId);
|
||||
const headingTagStyle: StyleDecl = {
|
||||
...globalStyle,
|
||||
styleSourceId: headingTagId,
|
||||
state: ":hover",
|
||||
value: { type: "keyword", value: "red" },
|
||||
};
|
||||
model.styles.set(getStyleDeclKey(headingTagStyle), headingTagStyle);
|
||||
expect(getComputedStyleDecl(selected).usedValue).toEqual({
|
||||
type: "keyword",
|
||||
value: "red",
|
||||
});
|
||||
const responsiveStyle: StyleDecl = {
|
||||
...globalStyle,
|
||||
breakpointId: "small",
|
||||
value: { type: "keyword", value: "green" },
|
||||
};
|
||||
model.styles.set(getStyleDeclKey(responsiveStyle), responsiveStyle);
|
||||
expect(getComputedStyleDecl(selected).usedValue).toEqual({
|
||||
type: "keyword",
|
||||
value: "green",
|
||||
});
|
||||
const tokenStyle: StyleDecl = {
|
||||
...globalStyle,
|
||||
styleSourceId: "headingToken",
|
||||
state: ":hover",
|
||||
value: { type: "keyword", value: "blue" },
|
||||
};
|
||||
model.styles.set(getStyleDeclKey(tokenStyle), tokenStyle);
|
||||
expect(getComputedStyleDecl(selected).usedValue).toEqual({
|
||||
type: "keyword",
|
||||
value: "blue",
|
||||
});
|
||||
});
|
||||
|
||||
test("matches breakpoint and source order for nested Tag styles", () => {
|
||||
const model = createModel({
|
||||
css: "",
|
||||
jsx: (
|
||||
<Box ws:id="outer" class="outer">
|
||||
<Box ws:id="inner" class="inner">
|
||||
<Heading ws:id="heading" ws:tag="h2" />
|
||||
</Box>
|
||||
</Box>
|
||||
),
|
||||
matchingBreakpoints: ["base", "small"],
|
||||
});
|
||||
const innerStyle: StyleDecl = {
|
||||
styleSourceId: "inner",
|
||||
breakpointId: "base",
|
||||
state: " h2",
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
};
|
||||
const outerStyle: StyleDecl = {
|
||||
...innerStyle,
|
||||
styleSourceId: "outer",
|
||||
breakpointId: "small",
|
||||
value: { type: "keyword", value: "purple" },
|
||||
};
|
||||
model.styles.set(getStyleDeclKey(innerStyle), innerStyle);
|
||||
model.styles.set(getStyleDeclKey(outerStyle), outerStyle);
|
||||
|
||||
expect(
|
||||
getComputedStyleDecl({
|
||||
model,
|
||||
instanceSelector: ["heading", "inner", "outer"],
|
||||
property: "color",
|
||||
}).usedValue
|
||||
).toEqual({ type: "keyword", value: "purple" });
|
||||
|
||||
model.styles.delete(getStyleDeclKey(outerStyle));
|
||||
outerStyle.breakpointId = "base";
|
||||
model.styles.set(getStyleDeclKey(outerStyle), outerStyle);
|
||||
expect(
|
||||
getComputedStyleDecl({
|
||||
model,
|
||||
instanceSelector: ["heading", "inner", "outer"],
|
||||
property: "color",
|
||||
}).usedValue
|
||||
).toEqual({ type: "keyword", value: "red" });
|
||||
|
||||
model.styleSourceSelections = new Map(
|
||||
[...model.styleSourceSelections].reverse()
|
||||
);
|
||||
expect(
|
||||
getComputedStyleDecl({
|
||||
model,
|
||||
instanceSelector: ["heading", "inner", "outer"],
|
||||
property: "color",
|
||||
}).usedValue
|
||||
).toEqual({ type: "keyword", value: "purple" });
|
||||
});
|
||||
|
||||
test("selected tag token remains the source when an instance overrides it", () => {
|
||||
const model = createModel({
|
||||
css: "local { color: blue; }",
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
parseCssVar,
|
||||
propertiesData,
|
||||
isPseudoElement,
|
||||
validateSelector,
|
||||
} from "@webstudio-is/css-data";
|
||||
import {
|
||||
type StyleValue,
|
||||
@@ -86,6 +87,7 @@ export type StyleObjectModel = {
|
||||
* all currently matching and ordered breakpointsgg
|
||||
*/
|
||||
matchingStates: Set<string>;
|
||||
matchingStatesByInstanceId?: Map<Instance["id"], Set<string>>;
|
||||
};
|
||||
|
||||
export const getPresetStyleDeclKey = ({
|
||||
@@ -121,6 +123,7 @@ export const getPresetStyleDeclKey = ({
|
||||
const getCascadedValue = ({
|
||||
model,
|
||||
instanceId,
|
||||
ancestorIds = [],
|
||||
styleSourceId: selectedStyleSourceId,
|
||||
state: selectedState,
|
||||
property,
|
||||
@@ -128,6 +131,7 @@ const getCascadedValue = ({
|
||||
}: {
|
||||
model: StyleObjectModel;
|
||||
instanceId: Instance["id"];
|
||||
ancestorIds?: Instance["id"][];
|
||||
styleSourceId?: StyleDecl["styleSourceId"];
|
||||
state?: StyleDecl["state"];
|
||||
property: CssProperty;
|
||||
@@ -141,8 +145,10 @@ const getCascadedValue = ({
|
||||
instanceTags,
|
||||
instanceComponents,
|
||||
matchingBreakpoints,
|
||||
matchingStates,
|
||||
} = model;
|
||||
const matchingStates = model.matchingStatesByInstanceId
|
||||
? (model.matchingStatesByInstanceId.get(instanceId) ?? new Set<string>())
|
||||
: model.matchingStates;
|
||||
const tag = instanceTags.get(instanceId);
|
||||
const component = instanceComponents.get(instanceId);
|
||||
let selectedIndex = -1;
|
||||
@@ -204,69 +210,132 @@ const getCascadedValue = ({
|
||||
// user styles
|
||||
const styleSourceIds = styleSourceSelections.get(instanceId)?.values ?? [];
|
||||
const tagStyleId = tag ? tagStyleIds.get(tag) : undefined;
|
||||
const nestedStyles = new Map<string, StyleDecl>();
|
||||
if (tag && ancestorIds.length > 0) {
|
||||
for (const declaration of styles.values()) {
|
||||
if (
|
||||
declaration.property !== camelCaseProperty(property) ||
|
||||
!declaration.state?.startsWith(" ")
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const selector = validateSelector(declaration.state);
|
||||
if (
|
||||
selector.success &&
|
||||
selector.type === "tag" &&
|
||||
selector.tag.toLowerCase() === tag
|
||||
) {
|
||||
nestedStyles.set(
|
||||
getStyleDeclKey({
|
||||
...declaration,
|
||||
state: ` ${tag}${selector.condition}`,
|
||||
}),
|
||||
declaration
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
selectedStyleSourceId ??= styleSourceIds.at(-1);
|
||||
const addDeclaration = ({
|
||||
styleSourceId,
|
||||
breakpointId,
|
||||
state,
|
||||
sourceInstanceId,
|
||||
}: {
|
||||
styleSourceId: string;
|
||||
breakpointId: string;
|
||||
state?: string;
|
||||
sourceInstanceId: string;
|
||||
}) => {
|
||||
const key = getStyleDeclKey({
|
||||
styleSourceId,
|
||||
breakpointId,
|
||||
state,
|
||||
property: camelCaseProperty(property),
|
||||
});
|
||||
const styleDecl = nestedStyles.get(key) ?? styles.get(key);
|
||||
const isSelected =
|
||||
sourceInstanceId === instanceId &&
|
||||
styleSourceId === selectedStyleSourceId &&
|
||||
state === selectedState;
|
||||
if (isSelected) {
|
||||
selectedIndex = styleDecl ? declaredValues.length : -1;
|
||||
}
|
||||
if (!styleDecl) {
|
||||
if (isSelected && styleSourceId === tagStyleId) {
|
||||
selectedTagStyleSource = undefined;
|
||||
}
|
||||
return;
|
||||
}
|
||||
const declarationSource: StyleValueSource = {
|
||||
name: "remote",
|
||||
instanceId: sourceInstanceId,
|
||||
styleSourceId,
|
||||
state: styleDecl.state,
|
||||
breakpointId,
|
||||
};
|
||||
if (isSelected && styleSourceId === tagStyleId) {
|
||||
selectedTagStyleSource = declarationSource;
|
||||
}
|
||||
source = declarationSource;
|
||||
declaredValues.push(styleDecl.value);
|
||||
};
|
||||
// Within each state, resolve all Tag breakpoints before instance styles.
|
||||
// Instance selectors then win over Tag selectors across breakpoints.
|
||||
const ancestorIdSet = new Set(ancestorIds);
|
||||
for (const state of states) {
|
||||
if (tagStyleId) {
|
||||
if (tag) {
|
||||
const descendantState = ` ${tag}${state ?? ""}`;
|
||||
for (const breakpointId of matchingBreakpoints) {
|
||||
const key = getStyleDeclKey({
|
||||
styleSourceId: tagStyleId,
|
||||
breakpointId,
|
||||
state,
|
||||
property: camelCaseProperty(property),
|
||||
});
|
||||
const styleDecl = styles.get(key);
|
||||
if (tagStyleId === selectedStyleSourceId && state === selectedState) {
|
||||
selectedIndex = styleDecl ? declaredValues.length : -1;
|
||||
selectedTagStyleSource = styleDecl
|
||||
? {
|
||||
name: "remote",
|
||||
instanceId,
|
||||
styleSourceId: tagStyleId,
|
||||
state,
|
||||
breakpointId,
|
||||
}
|
||||
: undefined;
|
||||
// Global Tag CSS follows breakpoint and source order. Within one
|
||||
// source, the nested rule is emitted before the tag's own rule.
|
||||
for (const [sourceTag, styleSourceId] of tagStyleIds) {
|
||||
const ancestorId = ancestorIds.find(
|
||||
(id) => instanceTags.get(id) === sourceTag
|
||||
);
|
||||
if (ancestorId) {
|
||||
addDeclaration({
|
||||
styleSourceId,
|
||||
breakpointId,
|
||||
state: descendantState,
|
||||
sourceInstanceId: ancestorId,
|
||||
});
|
||||
}
|
||||
if (sourceTag === tag) {
|
||||
addDeclaration({
|
||||
styleSourceId,
|
||||
breakpointId,
|
||||
state,
|
||||
sourceInstanceId: instanceId,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (styleDecl) {
|
||||
source = {
|
||||
name: "remote",
|
||||
instanceId,
|
||||
styleSourceId: tagStyleId,
|
||||
state,
|
||||
breakpointId,
|
||||
};
|
||||
declaredValues.push(styleDecl.value);
|
||||
}
|
||||
// Attached Token and Local descendant rules follow the global Tag sheet.
|
||||
for (const breakpointId of matchingBreakpoints) {
|
||||
for (const [ancestorId, selection] of styleSourceSelections) {
|
||||
if (!ancestorIdSet.has(ancestorId)) {
|
||||
continue;
|
||||
}
|
||||
for (const ancestorSourceId of selection.values) {
|
||||
addDeclaration({
|
||||
styleSourceId: ancestorSourceId,
|
||||
breakpointId,
|
||||
state: descendantState,
|
||||
sourceInstanceId: ancestorId,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const breakpointId of matchingBreakpoints) {
|
||||
for (const styleSourceId of styleSourceIds) {
|
||||
const key = getStyleDeclKey({
|
||||
addDeclaration({
|
||||
styleSourceId,
|
||||
breakpointId,
|
||||
state,
|
||||
property: camelCaseProperty(property),
|
||||
sourceInstanceId: instanceId,
|
||||
});
|
||||
const styleDecl = styles.get(key);
|
||||
if (
|
||||
styleSourceId === selectedStyleSourceId &&
|
||||
state === selectedState
|
||||
) {
|
||||
// reset selection from another state or breakpoint
|
||||
selectedIndex = styleDecl ? declaredValues.length : -1;
|
||||
}
|
||||
if (styleDecl) {
|
||||
source = {
|
||||
name: "remote",
|
||||
instanceId,
|
||||
styleSourceId,
|
||||
state,
|
||||
breakpointId,
|
||||
};
|
||||
declaredValues.push(styleDecl.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -458,6 +527,7 @@ export const getComputedStyleDecl = ({
|
||||
const cascaded = getCascadedValue({
|
||||
model,
|
||||
instanceId: targetInstanceId,
|
||||
ancestorIds: instanceSelector.slice(1),
|
||||
styleSourceId,
|
||||
state,
|
||||
property,
|
||||
@@ -589,8 +659,9 @@ export const getComputedStyleDecl = ({
|
||||
const cascaded = getCascadedValue({
|
||||
model,
|
||||
instanceId,
|
||||
ancestorIds: instanceSelector.slice(index + 1),
|
||||
styleSourceId,
|
||||
state,
|
||||
state: index === 0 ? state : undefined,
|
||||
property,
|
||||
});
|
||||
const inheritedCascadedValue = cascadedValue;
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
$dataSourceVariables,
|
||||
$dragAndDropState,
|
||||
$selectedInstanceStates,
|
||||
$selectedInstanceStatesByInstanceId,
|
||||
$canvasIframeState,
|
||||
$uploadingFilesDataStore,
|
||||
$memoryProps,
|
||||
@@ -373,6 +374,10 @@ export const createObjectPool = () => {
|
||||
new NanostoresSyncObject("dragAndDropState", $dragAndDropState),
|
||||
new NanostoresSyncObject("ephemeralStyles", $ephemeralStyles),
|
||||
new NanostoresSyncObject("selectedInstanceStates", $selectedInstanceStates),
|
||||
new NanostoresSyncObject(
|
||||
"selectedInstanceStatesByInstanceId",
|
||||
$selectedInstanceStatesByInstanceId
|
||||
),
|
||||
new NanostoresSyncObject("canvasIframeState", $canvasIframeState),
|
||||
new NanostoresSyncObject(
|
||||
"uploadingFilesDataStore",
|
||||
|
||||
@@ -45,16 +45,14 @@ States are CSS pseudo-classes that apply styles when a condition is true, such a
|
||||
|
||||
### Custom states
|
||||
|
||||
You can type any valid CSS pseudo-class into the Style Sources dropdown. If it's not in the predefined list, Webstudio will accept it as a custom selector.
|
||||
Use **Add more** in a Tag, Token, or Local style source to enter a selector that is not in the list.
|
||||
|
||||
{% hint style="info" %}
|
||||
Custom states can target descendants while staying scoped to the selected instance. For example, `:hover .button` targets descendants with the [custom class](custom-classes-and-attributes.md) `button` while the selected instance is hovered, and `:hover > .icon` targets only direct children with the custom class `icon`.
|
||||
Start with `:` or `[` to target the current source's element or its pseudo-elements. For example, `:hover` applies while the element is hovered, `[data-state=open]` applies when its attribute matches, and `::before` targets its pseudo-element. You can combine conditions, such as `[data-state=open]:hover`.
|
||||
|
||||
You can also select a descendant tag in a Local source or Token. For example, `p` targets paragraphs inside that instance. A [Tag style](tag-styles.md) targets one tag across the site instead.
|
||||
Start with an HTML tag name to style that tag nested inside the current source's element. For example, `h2`, `h2:hover`, `h2[a="123"]`, and `h2::before` target nested headings. Quote numeric attribute values as in `a="123"`. A [Tag style](tag-styles.md) applies its nested tag selector across the site; a Token or Local source applies it only where that source is used.
|
||||
|
||||
Prefer [CSS variables for parent-child interactions](css-variables.md#parent-child-interactions). They keep each property on the child that uses it, can coordinate several children from one parent state, and do not couple the interaction to descendant classes or structure. Use a descendant custom state when the interaction specifically requires selector-based targeting.
|
||||
|
||||
Start a custom state with a pseudo-class, pseudo-element, or attribute selector for the selected instance. You can then use a descendant (` `) or child (`>`) combinator. A tag name on its own is treated as a descendant selector. Selector lists, class or ID selectors at the start, and sibling combinators (`+` and `~`) are rejected because they can target elements outside the selected instance.
|
||||
**Add more** accepts one nested tag with optional conditions. It does not accept multiple top-level selectors, direct class or ID selectors such as `.card` or `h2.card`, a second nested element, or combinators such as `>`, `+`, and `~`. For parent-child interactions, [CSS variables](css-variables.md#parent-child-interactions) let the parent change a value used by the child.
|
||||
{% endhint %}
|
||||
|
||||
## Pseudo-elements
|
||||
|
||||
@@ -10,7 +10,7 @@ description: Set site-wide styles for HTML tags such as div, h1, and button.
|
||||
|
||||
1. Select an instance on the canvas, such as a `div`.
|
||||
2. Open the **Style sources** field at the top of the Style panel.
|
||||
3. Select `div` under **Tag style**. Its source appears first in the field.
|
||||
3. Select `div` under **Tag**. Its source appears first in the field.
|
||||
4. Select that source and set a style. The Tag style is saved when you add its first style.
|
||||
|
||||
<picture>
|
||||
@@ -29,7 +29,7 @@ Open the Tag style's menu and choose a state such as `:hover` or `:focus-visible
|
||||
<img src="../../.gitbook/assets/tag-style-states-light.png" alt="div Tag style menu with Copy above hover and focus-visible states" width="240">
|
||||
</picture>
|
||||
|
||||
A Tag style targets its tag and state across the site. To style a descendant within one element instead, use a [custom state or selector](states-and-selectors.md#custom-states) on a Token or Local source.
|
||||
A Tag style targets its tag and state across the site. In **Add more**, `:hover`, `[data-state=open]`, and `::before` target the Tag style's own element. Enter an HTML tag to target a nested element on every matching instance: `h2`, `h2:hover`, `h2[a="123"]`, and `h2::before` are supported. The same [selector forms](states-and-selectors.md#custom-states) work in Token and Local sources, where they apply only to instances using that source.
|
||||
|
||||
## Copy and paste
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// Edit markdown files in src/docs instead.
|
||||
export const cliDocs = {
|
||||
"api-use-cases":
|
||||
'# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get-more-tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get-more-tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search values and ids across every Builder namespace without sending full project data to the model.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nest
Line truncated
|
||||
'# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get-more-tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get-more-tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search values and ids across every Builder namespace without sending full project data to the model.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nest
Line truncated
|
||||
"manual-api":
|
||||
'# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\n- Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.\n- Never pass a project id. Commands use configured project only.\n- Read ids before writing. Do not invent ids for existing records.\n- stdout is one JSON object. stderr is diagnostics.\n- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.\n\n## Start\n\n{{start}}\n\n## Read First\n\n{{readFirst}}\n\n## Project Session Cache\n\n- CLI commands use one local ProjectSession snapshot for the configured project.\n- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.\n- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.\n- Successful mutation commits update the local snapshot only after the remote commit succeeds.\n- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.\n- Use --refresh on local-capable commands to refresh required namespaces before running.\n- Successful JSON responses include compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.\n\n## Search project data\n\nRun `webstudio search-project \'{"query":"known value"}\'` to search all Builder\nnamespaces in the local project session. Narrow it with\n`{"query":"Brand","namespaces":["styleSources","styles"]}` when only specific\nnamespaces are relevant. Results contain the current value, stable match id,\nnamespace path, owning entity, resolved references, and affected pages.\n\nValues in recognized credential fields are excluded and reported in\n`excludedSensitiveValueCount`.\n\nThe command synchronizes its required Builder namespaces, then searches locally\nand returns only matches. Namespace filters limit values matched; related\nnamespaces may still supply route and reference context, and synchronization is\nunchanged. This reduces data sent to the model, not project synchronization. It\nsearches asset metadata, not asset binaries or document contents.\n\n## CLI Capability Inventory\n\nFor a short end-consumer summary of what MCP can do, see\n`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same\nproject, page, element, style, data, asset, publish, domain, and visual\nverification capabilities without internal command names.\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP Tool Operations\n\nThese are MCP tools. From a shell, call them with the shortcut form `webstudio <tool> \'<json>\'` or with the explicit form `webstudio mcp single-op-call <tool> \'<json>\'`:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\nAn Editor link with API access can patch text and editable props inside a\nContent Block. The server checks the complete batch before saving it. Pages,\nassets, component structure, and design changes still require Builder access.\n\nEach transaction has:\n\n{\n"id": "patch-transaction-label",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nThe transaction id is a patch label used for optimistic synchronization. It is\nnot a Builder record id. Do not invent ids for pages, instances, props,\nbreakpoints, resources, variables, folders, assets, or other project records.\n\nPatch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.\n\nSupported namespaces:\n\n- pages: redirects, page records, and folders\n- projectSettings: project-wide metadata and compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reusable design tokens\n- styleSourceSelections: instance-to-style-source connections\n- dataSources: data variables, parameters, and resource data sources\n- resources: data resource definitions\n- assets: project asset records handled by the existing asset patch path\n- breakpoints: responsive breakpoints\n- marketplaceProduct: marketplace metadata\n\n## Data Sources\n\n`dataSources` is the internal Builder namespace for variables. Public API, CLI,\nand M
Line truncated
|
||||
"manual-llm":
|
||||
|
||||
@@ -675,10 +675,12 @@ Notes:
|
||||
Commands:
|
||||
|
||||
- MCP tool: update-selected-styles {"updates":[{"instanceId":"<buttonInstanceId>","styleSourceId":"tag-style:button","property":"color","value":{"type":"keyword","value":"red"}}]}
|
||||
- MCP tool: update-selected-styles {"updates":[{"instanceId":"<divInstanceId>","styleSourceId":"tag-style:div","state":" h2:hover","property":"color","value":{"type":"keyword","value":"red"}}]}
|
||||
|
||||
Notes:
|
||||
|
||||
- Use `tag-style:<tag>` to create or edit a Tag style. The first update creates its style source; no instance attachment is saved.
|
||||
- For a nested tag, set `state` to a space followed by the tag and optional condition, such as ` h2:hover`. The same selector forms work in Tag, Token, and Local styles.
|
||||
- Use `delete-selected-styles` with the same `instanceId`, `styleSourceId`, and `property` to remove a declaration.
|
||||
|
||||
## Update local styles
|
||||
|
||||
@@ -2,6 +2,24 @@ import { describe, test, expect } from "vitest";
|
||||
import { validateSelector } from "./selector-validation";
|
||||
|
||||
describe("validateSelector", () => {
|
||||
test("reads the condition from one nested tag", () => {
|
||||
expect(validateSelector(' h2[data-state="open"]:hover')).toMatchObject({
|
||||
success: true,
|
||||
type: "tag",
|
||||
tag: "h2",
|
||||
condition: '[data-state="open"]:hover',
|
||||
});
|
||||
expect(validateSelector(" h2[ data-state = open ]:hover")).toMatchObject({
|
||||
success: true,
|
||||
type: "tag",
|
||||
tag: "h2",
|
||||
condition: "[ data-state = open ]:hover",
|
||||
});
|
||||
expect(validateSelector(" h2:before")).toMatchObject({
|
||||
success: true,
|
||||
type: "pseudo-element",
|
||||
});
|
||||
});
|
||||
test.each([
|
||||
":hover, body",
|
||||
"body:hover",
|
||||
@@ -30,20 +48,45 @@ describe("validateSelector", () => {
|
||||
"[data-state=open] [data-part=content]",
|
||||
":hover > .icon",
|
||||
":not(.disabled) > [aria-hidden=true]",
|
||||
])("accepts states targeting descendants: %s", (selector) => {
|
||||
expect(validateSelector(selector).success).toBe(true);
|
||||
});
|
||||
|
||||
test.each([" p", " button:hover", " a[aria-current=page]"])(
|
||||
"accepts one descendant tag and its states: %s",
|
||||
])(
|
||||
"keeps saved state descendants without accepting new ones: %s",
|
||||
(selector) => {
|
||||
expect(validateSelector(selector)).toMatchObject({
|
||||
success: true,
|
||||
type: "tag",
|
||||
});
|
||||
expect(
|
||||
validateSelector(selector, { allowLegacyStateDescendants: true })
|
||||
.success
|
||||
).toBe(true);
|
||||
expect(validateSelector(selector).success).toBe(false);
|
||||
}
|
||||
);
|
||||
|
||||
test.each([
|
||||
":hover",
|
||||
"[data-state=open]",
|
||||
"::before",
|
||||
" h2",
|
||||
" h2:hover",
|
||||
' h2[a="123"]',
|
||||
" h2::before",
|
||||
])(
|
||||
"accepts a styled-element condition or one nested tag in Add more: %s",
|
||||
(selector) => {
|
||||
expect(validateSelector(selector).success).toBe(true);
|
||||
}
|
||||
);
|
||||
|
||||
test.each([
|
||||
" p",
|
||||
" button:hover",
|
||||
" a[aria-current=page]",
|
||||
' div[a="123"]',
|
||||
" div::before",
|
||||
])("accepts one descendant tag and its states: %s", (selector) => {
|
||||
expect(validateSelector(selector)).toMatchObject({
|
||||
success: true,
|
||||
type: "tag",
|
||||
});
|
||||
});
|
||||
|
||||
test.each([" p strong", " .card", " #card", " p + span"])(
|
||||
"rejects unsupported descendant tag selectors: %s",
|
||||
(selector) => {
|
||||
|
||||
@@ -6,23 +6,27 @@ export type SelectorValidationResult =
|
||||
| { success: false; error: string }
|
||||
| {
|
||||
success: true;
|
||||
type: "pseudo-class" | "pseudo-element" | "attribute" | "tag";
|
||||
};
|
||||
type: "pseudo-class" | "pseudo-element" | "attribute";
|
||||
}
|
||||
| { success: true; type: "tag"; tag: string; condition: string };
|
||||
|
||||
/**
|
||||
* Validates an open CSS state suffix scoped to the current element.
|
||||
*
|
||||
* Builder states are not a closed component-state enum. Valid pseudo-classes,
|
||||
* pseudo-elements, and attribute selectors may be compounded. Descendant and
|
||||
* child selectors may follow that state because the CSS engine anchors the
|
||||
* complete suffix to the generated instance selector. Selector lists,
|
||||
* pseudo-elements, and attribute selectors may be compounded. New input accepts
|
||||
* only a state on the styled element or one nested tag. Existing saved state
|
||||
* descendants may be checked with allowLegacyStateDescendants. Selector lists,
|
||||
* unanchored selectors, and sibling combinators are rejected.
|
||||
* @param selector - The selector to validate (e.g., ":hover", "::before", "[data-state=open]")
|
||||
* @returns SelectorValidationResult with success status and type or error message
|
||||
*/
|
||||
export const validateSelector = (
|
||||
selector: string,
|
||||
{ allowDescendants = true }: { allowDescendants?: boolean } = {}
|
||||
{
|
||||
allowDescendants = true,
|
||||
allowLegacyStateDescendants = false,
|
||||
}: { allowDescendants?: boolean; allowLegacyStateDescendants?: boolean } = {}
|
||||
): SelectorValidationResult => {
|
||||
if (!selector || selector.trim() === "") {
|
||||
return { success: false, error: "Selector cannot be empty" };
|
||||
@@ -44,7 +48,10 @@ export const validateSelector = (
|
||||
}
|
||||
|
||||
try {
|
||||
const ast = csstree.parse(selector, { context: "selectorList" });
|
||||
const ast = csstree.parse(selector, {
|
||||
context: "selectorList",
|
||||
positions: isTagSelector,
|
||||
});
|
||||
if (ast.type !== "SelectorList" || ast.children.size !== 1) {
|
||||
return {
|
||||
success: false,
|
||||
@@ -68,6 +75,12 @@ export const validateSelector = (
|
||||
error: "Selector must be one state scoped to the current element",
|
||||
};
|
||||
}
|
||||
if (allowLegacyStateDescendants === false && firstCombinatorIndex !== -1) {
|
||||
return {
|
||||
success: false,
|
||||
error: "Invalid CSS selector syntax",
|
||||
};
|
||||
}
|
||||
const stateNodes = selectorNodes.slice(
|
||||
0,
|
||||
firstCombinatorIndex === -1 ? undefined : firstCombinatorIndex
|
||||
@@ -145,11 +158,30 @@ export const validateSelector = (
|
||||
return { success: false, error: "Invalid pseudo-class" };
|
||||
}
|
||||
|
||||
if (
|
||||
isTagSelector &&
|
||||
stateNodes[0]?.type === "TypeSelector" &&
|
||||
pseudoElementNames.length === 0 &&
|
||||
pseudoClassNames.length > 0 &&
|
||||
pseudoClassNames.every((name) => isKnownSelector(name, pseudoElements))
|
||||
) {
|
||||
// Keep the legacy single-colon pseudo-element classification.
|
||||
return { success: true, type: "pseudo-element" };
|
||||
}
|
||||
if (isTagSelector && stateNodes[0]?.type === "TypeSelector") {
|
||||
return {
|
||||
success: true,
|
||||
type: "tag",
|
||||
tag: stateNodes[0].name,
|
||||
condition: selector.slice(stateNodes[0].loc?.end.offset),
|
||||
};
|
||||
}
|
||||
|
||||
if (pseudoElementNames.length > 0) {
|
||||
// Validate that the pseudo-element actually exists
|
||||
// Some pseudo-elements are functional (e.g., ::part(), ::slotted())
|
||||
// The list includes both "part" and "part()" variants
|
||||
return { success: true, type: isTagSelector ? "tag" : "pseudo-element" };
|
||||
return { success: true, type: "pseudo-element" };
|
||||
}
|
||||
|
||||
if (pseudoClassNames.length > 0) {
|
||||
@@ -160,15 +192,11 @@ export const validateSelector = (
|
||||
) {
|
||||
return { success: true, type: "pseudo-element" };
|
||||
}
|
||||
return { success: true, type: isTagSelector ? "tag" : "pseudo-class" };
|
||||
return { success: true, type: "pseudo-class" };
|
||||
}
|
||||
|
||||
if (foundAttribute) {
|
||||
return { success: true, type: isTagSelector ? "tag" : "attribute" };
|
||||
}
|
||||
|
||||
if (isTagSelector) {
|
||||
return { success: true, type: "tag" };
|
||||
return { success: true, type: "attribute" };
|
||||
}
|
||||
|
||||
// If we get here, something unexpected happened
|
||||
|
||||
@@ -197,15 +197,15 @@ test("support descendant suffix", () => {
|
||||
});
|
||||
expect(generateAtomic(sheet, { getKey: () => "" }).cssText)
|
||||
.toMatchInlineSnapshot(`
|
||||
"@media all {
|
||||
.c143pt9k:hover {
|
||||
display: block
|
||||
}
|
||||
.cpdl2lp img:hover {
|
||||
display: block
|
||||
}
|
||||
}"
|
||||
`);
|
||||
"@media all {
|
||||
.c143pt9k:hover {
|
||||
display: block
|
||||
}
|
||||
:where(.cpdl2lp) img:hover {
|
||||
display: block
|
||||
}
|
||||
}"
|
||||
`);
|
||||
});
|
||||
|
||||
test("generate prefixed and unprefixed in the same rule", () => {
|
||||
@@ -269,15 +269,15 @@ test("generate merged properties as single rule", () => {
|
||||
});
|
||||
expect(generateAtomic(sheet, { getKey: () => "" }).cssText)
|
||||
.toMatchInlineSnapshot(`
|
||||
"@media all {
|
||||
.cdj9gv4 {
|
||||
margin: auto
|
||||
}
|
||||
.c340vfr img {
|
||||
margin: 10px
|
||||
}
|
||||
}"
|
||||
`);
|
||||
"@media all {
|
||||
.cdj9gv4 {
|
||||
margin: auto
|
||||
}
|
||||
:where(.c340vfr) img {
|
||||
margin: 10px
|
||||
}
|
||||
}"
|
||||
`);
|
||||
});
|
||||
|
||||
test("convert :local-link to [aria-current=page] selector", () => {
|
||||
|
||||
@@ -263,7 +263,14 @@ export class NestingRule {
|
||||
if (nestedSelector === ":local-link") {
|
||||
nestedSelector = "[aria-current=page]";
|
||||
}
|
||||
const selector = this.#selector + this.#descendantSuffix + nestedSelector;
|
||||
const isDescendant =
|
||||
this.#descendantSuffix.startsWith(" ") ||
|
||||
nestedSelector.startsWith(" ");
|
||||
const baseSelector =
|
||||
isDescendant && this.#selector
|
||||
? `:where(${this.#selector})`
|
||||
: this.#selector;
|
||||
const selector = baseSelector + this.#descendantSuffix + nestedSelector;
|
||||
let style = styleBySelector.get(selector);
|
||||
if (style === undefined) {
|
||||
style = new Map();
|
||||
|
||||
@@ -265,6 +265,23 @@ describe("mixin rule", () => {
|
||||
`);
|
||||
});
|
||||
|
||||
test.each([' div[a="123"]', " div:hover", " div::before"])(
|
||||
"keeps scoped tag selector specificity for %s",
|
||||
(selector) => {
|
||||
const sheet = createRegularStyleSheet();
|
||||
const rule = sheet.addNestingRule(".container");
|
||||
rule.setDeclaration({
|
||||
breakpoint: "base",
|
||||
selector,
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
});
|
||||
expect(rule.toString({ breakpoint: "base" })).toContain(
|
||||
`:where(.container)${selector} {`
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
test("invalidate cache after applying mixins", () => {
|
||||
const sheet = createRegularStyleSheet();
|
||||
const rule = sheet.addNestingRule(".instance");
|
||||
@@ -749,15 +766,15 @@ describe("Style Sheet Regular", () => {
|
||||
value: { type: "keyword", value: "auto" },
|
||||
});
|
||||
expect(sheet.cssText).toMatchInlineSnapshot(`
|
||||
"@media all {
|
||||
.instance:hover {
|
||||
width: auto
|
||||
}
|
||||
.instance img:hover {
|
||||
width: auto
|
||||
}
|
||||
}"
|
||||
`);
|
||||
"@media all {
|
||||
.instance:hover {
|
||||
width: auto
|
||||
}
|
||||
:where(.instance) img:hover {
|
||||
width: auto
|
||||
}
|
||||
}"
|
||||
`);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -800,15 +817,15 @@ test("generate merged properties as single rule", () => {
|
||||
unit: "px",
|
||||
});
|
||||
expect(sheet.cssText).toMatchInlineSnapshot(`
|
||||
"@media all {
|
||||
instance {
|
||||
margin: auto
|
||||
}
|
||||
instance img {
|
||||
margin: 10px
|
||||
}
|
||||
}"
|
||||
`);
|
||||
"@media all {
|
||||
instance {
|
||||
margin: auto
|
||||
}
|
||||
:where(instance) img {
|
||||
margin: 10px
|
||||
}
|
||||
}"
|
||||
`);
|
||||
});
|
||||
|
||||
test("convert :local-link to [aria-current=page] selector", () => {
|
||||
|
||||
@@ -66,4 +66,11 @@ test("rejects malformed state selectors before saving styles", () => {
|
||||
new Map([["valid", { ...style("color", "red"), state: ":hover" }]])
|
||||
).success
|
||||
).toBe(true);
|
||||
expect(
|
||||
writableStyles.safeParse(
|
||||
new Map([
|
||||
["legacy", { ...style("color", "red"), state: ":hover .button" }],
|
||||
])
|
||||
).success
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -27,7 +27,8 @@ export const writableStyles = styles.refine((value) =>
|
||||
parseGeneratedStyleDeclaration(style).errors.length === 0 &&
|
||||
(style.state === undefined ||
|
||||
style.state === "" ||
|
||||
validateSelector(style.state).success)
|
||||
validateSelector(style.state, { allowLegacyStateDescendants: true })
|
||||
.success)
|
||||
)
|
||||
);
|
||||
|
||||
|
||||
@@ -21,7 +21,21 @@ test("Tag style clipboard data accepts only a supported tag and its CSS selector
|
||||
parseTagStyleTransferData(
|
||||
'/* @webstudio/tag-style-css/v1 "button" */\n.ws-tag-style p { color: red; }'
|
||||
).valid
|
||||
).toBe(false);
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("Tag style clipboard data accepts one nested tag with a state", () => {
|
||||
const parsed = parseTagStyleTransferData(
|
||||
'/* @webstudio/tag-style-css/v1 "button" */\n.ws-tag-style h2:hover { color: red; }'
|
||||
);
|
||||
expect(parsed.valid).toBe(true);
|
||||
if (parsed.valid) {
|
||||
expect(parsed.data.fragment.styles).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ state: " h2:hover", property: "color" }),
|
||||
])
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("reads a CSS token with variables, states, breakpoints, images, and fonts", () => {
|
||||
|
||||
@@ -341,8 +341,9 @@ const parseStyleSourceTransferData = (
|
||||
(kind === "tag" &&
|
||||
style.selector !== ":root" &&
|
||||
style.state !== undefined &&
|
||||
validateSelector(style.state, { allowDescendants: false }).success ===
|
||||
false)
|
||||
validateSelector(style.state, {
|
||||
allowLegacyStateDescendants: true,
|
||||
}).success === false)
|
||||
)
|
||||
) {
|
||||
return { owned: true, valid: false };
|
||||
|
||||
@@ -648,7 +648,9 @@ export const analyzeProject = (
|
||||
for (const declaration of state.styles.values()) {
|
||||
if (
|
||||
declaration.state !== undefined &&
|
||||
validateSelector(declaration.state).success === false
|
||||
validateSelector(declaration.state, {
|
||||
allowLegacyStateDescendants: true,
|
||||
}).success === false
|
||||
) {
|
||||
matches.push({
|
||||
kind: "style",
|
||||
|
||||
@@ -63,6 +63,7 @@ import {
|
||||
styleReplaceInput,
|
||||
styleUpdateDeclarationsInput,
|
||||
styleUpdateInput,
|
||||
selectedStyleUpdateDeclarationsInput,
|
||||
defineCssVariables,
|
||||
deleteDesignTokenStyles,
|
||||
deleteSelectedStyleDeclarations,
|
||||
@@ -1102,31 +1103,43 @@ describe("runtime style operations", () => {
|
||||
"body:hover",
|
||||
":hover + .tooltip",
|
||||
":hover ~ .tooltip",
|
||||
])(
|
||||
"rejects state selectors that escape the styled element when writing: %s",
|
||||
(state) => {
|
||||
expect(
|
||||
styleUpdateInput.safeParse({
|
||||
instanceId: "box",
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
state,
|
||||
})
|
||||
).toMatchObject({ success: false });
|
||||
expect(
|
||||
designTokenCreateInput.safeParse({
|
||||
name: "Primary",
|
||||
declarations: [
|
||||
{
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
state,
|
||||
},
|
||||
],
|
||||
})
|
||||
).toMatchObject({ success: false });
|
||||
}
|
||||
);
|
||||
":hover .button",
|
||||
":hover > .icon",
|
||||
])("rejects unsupported state selectors when writing: %s", (state) => {
|
||||
expect(
|
||||
styleUpdateInput.safeParse({
|
||||
instanceId: "box",
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
state,
|
||||
})
|
||||
).toMatchObject({ success: false });
|
||||
expect(
|
||||
designTokenCreateInput.safeParse({
|
||||
name: "Primary",
|
||||
declarations: [
|
||||
{
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
state,
|
||||
},
|
||||
],
|
||||
})
|
||||
).toMatchObject({ success: false });
|
||||
expect(
|
||||
selectedStyleUpdateDeclarationsInput.safeParse({
|
||||
updates: [
|
||||
{
|
||||
instanceId: "box",
|
||||
styleSourceId: "token",
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
state,
|
||||
},
|
||||
],
|
||||
})
|
||||
).toMatchObject({ success: false });
|
||||
});
|
||||
|
||||
test("accepts an invalid state as an existing declaration deletion coordinate", () => {
|
||||
expect(
|
||||
@@ -1146,60 +1159,15 @@ describe("runtime style operations", () => {
|
||||
".box[data-state=open] > [data-part=content]",
|
||||
],
|
||||
])(
|
||||
"preserves an editable descendant state through mutation and generated CSS: %s",
|
||||
"preserves saved descendant states in generated CSS: %s",
|
||||
(state, generatedSelector) => {
|
||||
expect(
|
||||
styleUpdateInput.safeParse({
|
||||
instanceId: "box",
|
||||
property: "borderTopColor",
|
||||
value: { type: "keyword", value: "currentcolor" },
|
||||
state,
|
||||
})
|
||||
).toMatchObject({ success: true });
|
||||
|
||||
const mutation = updateStyleDeclarations(
|
||||
{
|
||||
breakpoints: runtimeBreakpoints,
|
||||
instances: toMap([instance("box")]),
|
||||
styles: new Map(),
|
||||
styleSources: sources([local("local")]),
|
||||
styleSourceSelections: new Map([
|
||||
["box", { instanceId: "box", values: ["local"] }],
|
||||
]),
|
||||
},
|
||||
{
|
||||
updates: [
|
||||
{
|
||||
instanceId: "box",
|
||||
property: "borderTopColor",
|
||||
value: { type: "keyword", value: "currentcolor" },
|
||||
state,
|
||||
},
|
||||
],
|
||||
},
|
||||
{ createId }
|
||||
);
|
||||
const patch = mutation.payload
|
||||
.find((change) => change.namespace === "styles")
|
||||
?.patches.at(0);
|
||||
if (patch === undefined || patch.op === "remove") {
|
||||
throw new Error("Expected a style declaration patch");
|
||||
}
|
||||
const declaration = patch.value as StyleDecl;
|
||||
|
||||
expect(declaration).toMatchObject({
|
||||
property: "borderTopColor",
|
||||
state,
|
||||
breakpointId: "desktop",
|
||||
});
|
||||
|
||||
const sheet = createRegularStyleSheet();
|
||||
const rule = sheet.addNestingRule(".box");
|
||||
rule.setDeclaration({
|
||||
breakpoint: declaration.breakpointId,
|
||||
selector: declaration.state ?? "",
|
||||
property: declaration.property,
|
||||
value: declaration.value,
|
||||
breakpoint: "desktop",
|
||||
selector: state,
|
||||
property: "borderTopColor",
|
||||
value: { type: "keyword", value: "currentcolor" },
|
||||
});
|
||||
expect(rule.toString({ breakpoint: "desktop" })).toContain(
|
||||
`${generatedSelector} {\n border-top-color: currentcolor\n}`
|
||||
@@ -1680,30 +1648,34 @@ describe("runtime style operations", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("rejects a descendant selector on a tag token", () => {
|
||||
test("accepts a nested tag selector on a global Tag style", () => {
|
||||
const id = getTagStyleId("button");
|
||||
expect(() =>
|
||||
updateSelectedStyleDeclarations(
|
||||
{
|
||||
breakpoints: runtimeBreakpoints,
|
||||
instances: toMap([instance("button-instance")]),
|
||||
styles: new Map(),
|
||||
styleSources: new Map(),
|
||||
styleSourceSelections: new Map(),
|
||||
},
|
||||
{
|
||||
updates: [
|
||||
{
|
||||
instanceId: "button-instance",
|
||||
styleSourceId: id,
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
state: " p",
|
||||
},
|
||||
],
|
||||
}
|
||||
)
|
||||
).toThrow();
|
||||
const mutation = updateSelectedStyleDeclarations(
|
||||
{
|
||||
breakpoints: runtimeBreakpoints,
|
||||
instances: toMap([instance("button-instance")]),
|
||||
styles: new Map(),
|
||||
styleSources: new Map(),
|
||||
styleSourceSelections: new Map(),
|
||||
},
|
||||
{
|
||||
updates: [
|
||||
{
|
||||
instanceId: "button-instance",
|
||||
styleSourceId: id,
|
||||
property: "color",
|
||||
value: { type: "keyword", value: "red" },
|
||||
state: " h2:hover",
|
||||
},
|
||||
],
|
||||
}
|
||||
);
|
||||
expect(mutation.payload).toContainEqual({
|
||||
namespace: "styleSources",
|
||||
patches: [
|
||||
{ op: "add", path: [id], value: { type: "tag", id, tag: "button" } },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("renames, locks, and deletes style sources", () => {
|
||||
|
||||
@@ -2050,7 +2050,9 @@ const getExistingStyleDeletionKeys = <
|
||||
styleKey !== undefined && existingStyleKeys.has(styleKey) === true;
|
||||
if (
|
||||
deletion.state !== undefined &&
|
||||
validateSelector(deletion.state).success === false &&
|
||||
validateSelector(deletion.state, {
|
||||
allowLegacyStateDescendants: true,
|
||||
}).success === false &&
|
||||
exists === false
|
||||
) {
|
||||
return throwBuilderRuntimeError(
|
||||
@@ -3489,17 +3491,6 @@ export const updateSelectedStyleDeclarations = (
|
||||
id: update.styleSourceId,
|
||||
tag: tag!,
|
||||
};
|
||||
if (
|
||||
styleSource.type === "tag" &&
|
||||
update.state !== undefined &&
|
||||
validateSelector(update.state, { allowDescendants: false }).success ===
|
||||
false
|
||||
) {
|
||||
return throwBuilderRuntimeError(
|
||||
"BAD_REQUEST",
|
||||
"Selector must be one state scoped to the current element"
|
||||
);
|
||||
}
|
||||
if (isStyleSourceLocked(styleSource)) {
|
||||
return throwBuilderRuntimeError("BAD_REQUEST", "Style source is locked");
|
||||
}
|
||||
|
||||
@@ -101,8 +101,8 @@ test("renders a tag selector inside an attached token as a descendant", () => {
|
||||
assetBaseUrl: "/",
|
||||
});
|
||||
|
||||
expect(cssText).toContain(".w-box p");
|
||||
expect(atomicCssText).toMatch(/\.c[a-z0-9]+ p/);
|
||||
expect(cssText).toContain(":where(.w-box) p");
|
||||
expect(atomicCssText).toMatch(/:where\(\.c[a-z0-9]+\) p/);
|
||||
});
|
||||
|
||||
test("generates distinct upright and italic variable font faces", () => {
|
||||
@@ -228,39 +228,39 @@ test("generate descendant selector", () => {
|
||||
assetBaseUrl: "",
|
||||
});
|
||||
expect(cssText).toMatchInlineSnapshot(`
|
||||
"
|
||||
@media all {
|
||||
.w-body {
|
||||
color: blue
|
||||
}
|
||||
.w-body:hover {
|
||||
color: red
|
||||
}
|
||||
.w-body a {
|
||||
color: blue
|
||||
}
|
||||
.w-body a:hover {
|
||||
color: red
|
||||
}
|
||||
}"
|
||||
`);
|
||||
"
|
||||
@media all {
|
||||
.w-body {
|
||||
color: blue
|
||||
}
|
||||
.w-body:hover {
|
||||
color: red
|
||||
}
|
||||
:where(.w-body) a {
|
||||
color: blue
|
||||
}
|
||||
:where(.w-body) a:hover {
|
||||
color: red
|
||||
}
|
||||
}"
|
||||
`);
|
||||
expect(atomicCssText).toMatchInlineSnapshot(`
|
||||
"
|
||||
@media all {
|
||||
.c17hlgoh {
|
||||
color: blue
|
||||
}
|
||||
.c92zrdl:hover {
|
||||
color: red
|
||||
}
|
||||
.chhpmat a {
|
||||
color: blue
|
||||
}
|
||||
.c32fhpn a:hover {
|
||||
color: red
|
||||
}
|
||||
}"
|
||||
`);
|
||||
"
|
||||
@media all {
|
||||
.c17hlgoh {
|
||||
color: blue
|
||||
}
|
||||
.c92zrdl:hover {
|
||||
color: red
|
||||
}
|
||||
:where(.chhpmat) a {
|
||||
color: blue
|
||||
}
|
||||
:where(.c32fhpn) a:hover {
|
||||
color: red
|
||||
}
|
||||
}"
|
||||
`);
|
||||
expect(atomicClasses).toMatchInlineSnapshot(`
|
||||
Map {
|
||||
"body" => [
|
||||
|
||||
Reference in new issue
Block a user