Files
webstudio/packages/css-data/src/selector-validation.ts
T
Oleg Isonen b0d7cc2e7b 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
2026-11-11 20:52:01 +01:00

214 lines
6.9 KiB
TypeScript

import * as csstree from "css-tree";
import { pseudoElements } from "./__generated__/pseudo-elements";
import { pseudoClasses } from "./__generated__/pseudo-classes";
export type SelectorValidationResult =
| { success: false; error: string }
| {
success: true;
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. 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,
allowLegacyStateDescendants = false,
}: { allowDescendants?: boolean; allowLegacyStateDescendants?: boolean } = {}
): SelectorValidationResult => {
if (!selector || selector.trim() === "") {
return { success: false, error: "Selector cannot be empty" };
}
// A leading space marks a descendant tag selector. The CSS engine appends
// state strings directly to the styled element's selector.
const isTagSelector = selector.startsWith(" ");
if (
!isTagSelector &&
!selector.startsWith(":") &&
!selector.startsWith("[")
) {
return {
success: false,
error:
"Selector must start with a colon (:) for pseudo-classes, double colon (::) for pseudo-elements, or bracket ([) for attribute selectors",
};
}
try {
const ast = csstree.parse(selector, {
context: "selectorList",
positions: isTagSelector,
});
if (ast.type !== "SelectorList" || ast.children.size !== 1) {
return {
success: false,
error: "Selector must be one state scoped to the current element",
};
}
const parsedSelector = ast.children.first;
const selectorNodes =
parsedSelector?.type === "Selector"
? parsedSelector.children.toArray()
: [];
const firstCombinatorIndex = selectorNodes.findIndex(
(node) => node.type === "Combinator"
);
if (
allowDescendants === false &&
(isTagSelector || firstCombinatorIndex !== -1)
) {
return {
success: false,
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
);
const hasValidTagStart =
isTagSelector &&
firstCombinatorIndex === -1 &&
stateNodes[0]?.type === "TypeSelector" &&
stateNodes
.slice(1)
.every(
(node) =>
node.type === "PseudoClassSelector" ||
node.type === "PseudoElementSelector" ||
node.type === "AttributeSelector"
);
if (
parsedSelector?.type !== "Selector" ||
stateNodes.length === 0 ||
(!hasValidTagStart &&
stateNodes.some(
(node) =>
node.type !== "PseudoClassSelector" &&
node.type !== "PseudoElementSelector" &&
node.type !== "AttributeSelector"
)) ||
(isTagSelector && !hasValidTagStart) ||
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 an element-scoped state, optionally followed by a descendant or child selector",
};
}
const pseudoClassNames: string[] = [];
const pseudoElementNames: string[] = [];
let foundAttribute = false;
// Walk the AST to find pseudo-class, pseudo-element, or attribute selectors
csstree.walk(ast, (node) => {
if (node.type === "PseudoClassSelector") {
pseudoClassNames.push(node.name);
}
if (node.type === "PseudoElementSelector") {
pseudoElementNames.push(node.name);
}
if (node.type === "AttributeSelector") {
foundAttribute = true;
}
});
// Determine the type based on what we found
const isKnownSelector = (name: string, known: readonly string[]) =>
known.includes(name) || known.includes(`${name}()`);
if (
pseudoElementNames.some(
(name) => isKnownSelector(name, pseudoElements) === false
)
) {
return { success: false, error: "Invalid pseudo-element" };
}
const invalidPseudoClass = pseudoClassNames.find(
(name) =>
isKnownSelector(name, pseudoClasses) === false &&
isKnownSelector(name, pseudoElements) === false
);
if (invalidPseudoClass !== undefined) {
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: "pseudo-element" };
}
if (pseudoClassNames.length > 0) {
// Check if it's actually a legacy pseudo-element (single colon)
// Legacy syntax: :before, :after, :first-line, :first-letter
if (
pseudoClassNames.every((name) => isKnownSelector(name, pseudoElements))
) {
return { success: true, type: "pseudo-element" };
}
return { success: true, type: "pseudo-class" };
}
if (foundAttribute) {
return { success: true, type: "attribute" };
}
// If we get here, something unexpected happened
return {
success: false,
error: "Invalid CSS selector syntax",
};
} catch {
return {
success: false,
error: "Invalid CSS selector syntax",
};
}
};