Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
fix: Restore scoped descendant selectors (#6195)
Oleg Isonenb2d62b2e492c
diff --git a/docs/university/foundations/css-variables.md b/docs/university/foundations/css-variables.mdindex 3111297303..01e661bc9d 100644--- a/docs/university/foundations/css-variables.md+++ b/docs/university/foundations/css-variables.md@@ -156,6 +156,8 @@ Here are some use cases for local variables:With CSS variables, you can interact with the parent and modify the styles of any of the children.+Prefer CSS variables over a [descendant custom state](states-and-selectors.md#custom-states) such as `:hover .button` for parent-child interactions. They keep each property on the child that uses it and are especially useful when one parent state coordinates several properties or children. Define a variable on the parent, use it for the relevant property on each child, and change the variable's value in the parent's `:hover` state.+<figure><img src="../../.gitbook/assets/parent-child-demo.gif" alt=""><figcaption><p>Hovering the link and the children change (icon color, icon bg, and arrow appears)</p></figcaption></figure>{% embed url="https://youtu.be/rg49mmDvdlE" %}diff --git a/docs/university/foundations/states-and-selectors.md b/docs/university/foundations/states-and-selectors.mdindex 0b92d2cb1f..1c5e30b6e7 100644--- a/docs/university/foundations/states-and-selectors.md+++ b/docs/university/foundations/states-and-selectors.md@@ -36,7 +36,11 @@ States are CSS pseudo-classes that apply styles when a condition is true, such aYou 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.{% hint style="info" %}-Custom selectors are useful for advanced cases, but stick to the predefined states when possible — they are validated and shown in autocomplete.+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`.++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 the selector with a pseudo-class, pseudo-element, or attribute selector for the selected instance. You can then use a descendant (` `) or child (`>`) combinator. Selector lists, selectors that start with a type, class, or ID, and sibling combinators (`+` and `~`) are rejected because they can target elements outside the selected instance.{% endhint %}## Pseudo-elements@@ -87,7 +91,7 @@ Pseudo-elements target virtual parts of an element, such as inserting content beStates work together with [Tokens](design-tokens.md). When you have a Token selected, adding a state applies styles for that state _within that Token_. This keeps hover styles, focus styles, and base styles neatly organized.-You can also use [CSS variables](css-variables.md) to create parent-child interactions — define variables on the parent, then change their values on the `:hover` state so all children update at once. See [Parent-child interactions](css-variables.md#parent-child-interactions) for details.+You can also use [CSS variables](css-variables.md) to coordinate several parent-child style changes — define variables on the parent, then change their values on the `:hover` state so all children update at once. See [Parent-child interactions](css-variables.md#parent-child-interactions) for details.## Relateddiff --git a/packages/css-data/src/selector-validation.test.ts b/packages/css-data/src/selector-validation.test.tsindex d50f660d18..cc6c928eb4 100644--- a/packages/css-data/src/selector-validation.test.ts+++ b/packages/css-data/src/selector-validation.test.ts@@ -4,11 +4,11 @@ import { validateSelector } from "./selector-validation";describe("validateSelector", () => {test.each([":hover, body",- ":hover > div",- ":hover .child","body:hover",".class","#identifier",+ ":hover + .tooltip",+ ":hover ~ .tooltip",])("rejects selector syntax that can escape element scope: %s",(selector) => {@@ -24,6 +24,16 @@ describe("validateSelector", () => {expect(validateSelector(selector).success).toBe(true);});+ test.each([+ ":hover .button",+ ":focus-within input",+ "[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([":not-a-real-state:hover",":hover:not-a-real-state",diff --git a/packages/css-data/src/selector-validation.ts b/packages/css-data/src/selector-validation.tsindex a5006fe43c..bf3c509136 100644--- a/packages/css-data/src/selector-validation.ts+++ b/packages/css-data/src/selector-validation.ts@@ -10,9 +10,10 @@ export type SelectorValidationResult =* 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, but selector- * lists, type/class/id selectors, and combinators are rejected because the CSS- * engine appends this value directly to the generated instance selector.+ * 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,+ * 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*/@@ -41,21 +42,37 @@ export const validateSelector = (};}const parsedSelector = ast.children.first;+ const selectorNodes =+ parsedSelector?.type === "Selector"+ ? parsedSelector.children.toArray()+ : [];+ const firstCombinatorIndex = selectorNodes.findIndex(+ (node) => node.type === "Combinator"+ );+ const stateNodes = selectorNodes.slice(+ 0,+ firstCombinatorIndex === -1 ? undefined : firstCombinatorIndex+ );if (parsedSelector?.type !== "Selector" ||- parsedSelector.children- .toArray()- .some(- (node) =>- node.type !== "PseudoClassSelector" &&- node.type !== "PseudoElementSelector" &&- node.type !== "AttributeSelector"- )+ stateNodes.length === 0 ||+ stateNodes.some(+ (node) =>+ node.type !== "PseudoClassSelector" &&+ node.type !== "PseudoElementSelector" &&+ node.type !== "AttributeSelector"+ ) ||+ selectorNodes.some(+ (node) =>+ node.type === "Combinator" && node.name !== " " && node.name !== ">"+ ) ||+ (firstCombinatorIndex !== -1 &&+ stateNodes.some((node) => node.type === "PseudoElementSelector"))) {return {success: false,error:- "Selector must be a pseudo-class, pseudo-element, or attribute suffix scoped to the current element",+ "Selector must be an element-scoped state, optionally followed by a descendant or child selector",};}diff --git a/packages/project-build/src/runtime/audit.ts b/packages/project-build/src/runtime/audit.tsindex e5cee2d624..a1b6d8d0cf 100644--- a/packages/project-build/src/runtime/audit.ts+++ b/packages/project-build/src/runtime/audit.ts@@ -915,7 +915,7 @@ export const auditRules = {"styles","warning","The style state selector is not a valid element-scoped suffix and may escape its component or generate invalid CSS.",- "Replace it with one pseudo-class, pseudo-element, attribute selector, or a compound suffix that remains scoped to the styled element."+ "Start with a pseudo-class, pseudo-element, or attribute selector. Descendant and child selectors may follow, but selector lists and sibling combinators are not supported."),"orphan-style-breakpoint": rule("styles",diff --git a/packages/project-build/src/runtime/styles.test.ts b/packages/project-build/src/runtime/styles.test.tsindex f7204aaf6b..3c574d6e10 100644--- a/packages/project-build/src/runtime/styles.test.ts+++ b/packages/project-build/src/runtime/styles.test.ts@@ -1067,7 +1067,12 @@ const instance = (id: string): Instance => ({});describe("runtime style operations", () => {- test.each([":hover, body", ":hover > div", "body:hover"])(+ test.each([+ ":hover, body",+ "body:hover",+ ":hover + .tooltip",+ ":hover ~ .tooltip",+ ])("rejects state selectors that escape the styled element when writing: %s",(state) => {expect(@@ -1103,56 +1108,74 @@ describe("runtime style operations", () => {).toMatchObject({ success: true });});- test("preserves an editable compound state through mutation and generated CSS", () => {- const state = ":hover:focus-visible";- 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;+ test.each([+ [":hover .button", ".box:hover .button"],+ [":focus-within input", ".box:focus-within input"],+ [+ "[data-state=open] > [data-part=content]",+ ".box[data-state=open] > [data-part=content]",+ ],+ ])(+ "preserves an editable descendant state through mutation and generated CSS: %s",+ (state, generatedSelector) => {+ expect(+ styleUpdateInput.safeParse({+ instanceId: "box",+ property: "borderTopColor",+ value: { type: "keyword", value: "currentcolor" },+ state,+ })+ ).toMatchObject({ success: true });- expect(declaration).toMatchObject({- property: "borderTopColor",- state,- breakpointId: "desktop",- });+ 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;- const sheet = createRegularStyleSheet();- const rule = sheet.addNestingRule(".box");- rule.setDeclaration({- breakpoint: declaration.breakpointId,- selector: declaration.state ?? "",- property: declaration.property,- value: declaration.value,- });- expect(rule.toString({ breakpoint: "desktop" })).toContain(- ".box:hover:focus-visible {\n border-top-color: currentcolor\n}"- );- });+ 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,+ });+ expect(rule.toString({ breakpoint: "desktop" })).toContain(+ `${generatedSelector} {\n border-top-color: currentcolor\n}`+ );+ }+ );test("rejects declarations for unknown breakpoints", () => {expect(() =>