Skip to content

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.

feat: Pseudo elements (#5572)

Oleg Isonen1f4c53419da2
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index ea147b2ce1..f2204c5a68 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -15,18 +15,33 @@
- Never alias the same type or variable to different names (e.g., `type AliasName = OriginalName`) - always use the original name consistently throughout the codebase
- Spreading `undefined` works fine in JavaScript/TypeScript - the spread operator skips it. Never return empty objects `{}` when you can just `return` (or omit return for `undefined`). Example: `return { ...obj, ...maybeUndefined }` works correctly.
+## UI Labels and Text
+
+- All visible labels and text must use sentence case capitalization:
+ - First word capitalized
+ - Subsequent words lowercase (unless proper nouns or acronyms)
+ - Examples: "Pseudo elements", "More states", "Component states"
+ - Not: "Pseudo Elements", "More States", "Component States"
+
## Running Commands
-- For global workspace commands (e.g., "update fixtures", "run checks"), always check the root `package.json` scripts first
-- The root package.json at `/workspaces/webstudio/package.json` contains commands like:
- - `pnpm fixtures` - updates all fixtures (link, sync, build)
- - `pnpm checks` - runs all checks (tests, typecheck, lint, fixtures)
- - `pnpm build` - builds all packages
+- **When user says "checks" or "run checks" or "global checks"**: Run `pnpm -w run checks` (works from any directory)
+- The `-w` flag runs scripts from the workspace root regardless of current directory
+- The root package.json contains these workspace-level commands:
+ - `pnpm -w run checks` - runs all checks (tests, typecheck, lint, fixtures) - **USE THIS FOR "checks"**
+ - `pnpm -w run fixtures` - updates all fixtures (link, sync, build)
+ - `pnpm -w run build` - builds all packages
+ - `pnpm -w run playwright` - installs Playwright browser dependencies (run if animation tests fail with missing dependencies)
- Before running any commands, always check `get_errors` tool first to see TypeScript and ESLint errors in the VS Code editor
- Only run `pnpm typecheck` and `pnpm eslint` when user explicitly says "run checks" or after completing substantial changes
- `pnpm typecheck` is slow - avoid running it unnecessarily during development
- Fix all eslint and TypeScript errors before considering work complete
+### Test Failures
+
+- If tests fail with "Host system is missing dependencies to run browsers" error, run `pnpm playwright` to install Playwright dependencies
+- This is common in fresh dev containers or after container rebuilds
+
## File Organization
- Files named `types.ts` must only contain TypeScript type definitions, interfaces, and type aliases
@@ -41,6 +56,9 @@
- Only create shared utility files when functions are used across different directories
- Files prefixed with `use-` contain React hooks and state management (e.g., `use-assets.tsx`)
- Separate pure utilities from side-effect code (React hooks, network calls, DOM operations)
+- **Never create wrapper files that just re-export from packages** - import directly from the package where it's used
+- When moving code to a shared package, update all import sites to use the package directly
+- **When moving/refactoring code**: Always check where functions/types are actually used (grep for imports) and place them accordingly - don't assume, verify
## Testing
@@ -133,7 +151,10 @@ import { __testing__ } from "./implementation";
const { internalHelper } = __testing__;
```
-Don't create separate utility files just for testing.
+- `__testing__` exports must always be placed at the end of the module
+- Don't create separate utility files just for testing
+- Explicit return types are not needed - TypeScript infers them
+- When encountering magic numbers without comments, check `git log -S "<number>" --oneline` to find the commit that introduced it and add explanation from commit message as a comment
## Debugging
diff --git a/apps/builder/app/builder/features/command-panel/groups/duplicate-tokens-group.tsx b/apps/builder/app/builder/features/command-panel/groups/duplicate-tokens-group.tsx
index 3b1be32514..0c8ae332eb 100644
--- a/apps/builder/app/builder/features/command-panel/groups/duplicate-tokens-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/duplicate-tokens-group.tsx
@@ -314,7 +314,7 @@ export const DuplicateTokensGroup = ({
}
}}
>
- <Text variant="labelsTitleCase">
+ <Text variant="labels">
{token.name}{" "}
<Text as="span" color="moreSubtle">
{formatUsageCount(usages)} · {duplicates.length} duplicate
diff --git a/apps/builder/app/builder/features/pages/image-info.tsx b/apps/builder/app/builder/features/pages/image-info.tsx
index d64ef26ed9..4f8db51bac 100644
--- a/apps/builder/app/builder/features/pages/image-info.tsx
+++ b/apps/builder/app/builder/features/pages/image-info.tsx
@@ -49,20 +49,20 @@ export const ImageInfo = ({ asset, onDelete }: ImageInfoProps) => {
css={{ gridTemplateColumns: "max-content 1fr" }}
>
<ImageIcon />
- <Text truncate variant={"labelsSentenceCase"}>
+ <Text truncate variant={"labels"}>
{formatAssetName(asset)}
</Text>
</Grid>
<Grid columns={2} gap={1} align={"center"}>
<Flex gap={1}>
<DimensionsIcon />
- <Text variant={"labelsTitleCase"}>
+ <Text variant={"labels"}>
{asset.meta.width} x {asset.meta.height} Px
</Text>
</Flex>
<Flex gap={1}>
<AspectRatioIcon />
- <Text variant={"labelsTitleCase"}>
+ <Text variant={"labels"}>
{getFormattedAspectRatio(asset.meta)}
</Text>
</Flex>
diff --git a/apps/builder/app/builder/features/settings-panel/controls/code.tsx b/apps/builder/app/builder/features/settings-panel/controls/code.tsx
index 7e2c8078f0..ca5151cf79 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/code.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/code.tsx
@@ -208,7 +208,7 @@ export const CodeControl = ({
}
>
<Flex gap="1" align="center">
- <Text variant="labelsTitleCase">Code Editor</Text>
+ <Text variant="labels">Code Editor</Text>
{errorInfo}
</Flex>
</DialogTitle>
diff --git a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx
index 44ab9a2b6c..f7dc429241 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx
@@ -126,7 +126,7 @@ export const TextContent = ({
</DialogTitleActions>
}
>
- <Text variant="labelsTitleCase">Text Content</Text>
+ <Text variant="labels">Text Content</Text>
</DialogTitle>
}
size="small"
diff --git a/apps/builder/app/builder/features/settings-panel/variables-section.tsx b/apps/builder/app/builder/features/settings-panel/variables-section.tsx
index 96831d3c9f..b5deb5689f 100644
--- a/apps/builder/app/builder/features/settings-panel/variables-section.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variables-section.tsx
@@ -100,7 +100,7 @@ const EmptyVariables = () => {
return (
<Flex direction="column" gap="2">
<Flex justify="center" align="center">
- <Text variant="labelsSentenceCase" align="center">
+ <Text variant="labels" align="center">
No data variables created
<br /> on this instance
</Text>
diff --git a/apps/builder/app/builder/features/style-panel/shared/recent-selectors.ts b/apps/builder/app/builder/features/style-panel/shared/recent-selectors.ts
new file mode 100644
index 0000000000..4a0db8aa62
--- /dev/null
+++ b/apps/builder/app/builder/features/style-panel/shared/recent-selectors.ts
@@ -0,0 +1,24 @@
+import type { Styles } from "@webstudio-is/sdk";
+
+/**
+ * Extract all unique selectors (states) used in the project styles
+ * Returns them sorted by most recently used (based on order in styles map)
+ */
+export const getUsedSelectors = (styles: Styles): string[] => {
+ const selectorsSet = new Set<string>();
+ const selectorsOrder: string[] = [];
+
+ // Iterate through all styles and collect unique states
+ for (const styleDecl of styles.values()) {
+ if (styleDecl.state && styleDecl.state.trim()) {
+ const selector = styleDecl.state;
+ if (!selectorsSet.has(selector)) {
+ selectorsSet.add(selector);
+ // Add to front to maintain most recent first
+ selectorsOrder.unshift(selector);
+ }
+ }
+ }
+
+ return selectorsOrder;
+};
diff --git a/apps/builder/app/builder/features/style-panel/style-panel.tsx b/apps/builder/app/builder/features/style-panel/style-panel.tsx
index 59ff59af8e..71fbf49c20 100644
--- a/apps/builder/app/builder/features/style-panel/style-panel.tsx
+++ b/apps/builder/app/builder/features/style-panel/style-panel.tsx
@@ -84,7 +84,7 @@ export const ModeMenu = () => {
onFocus={() => setFocusedValue("focus")}
>
<Flex justify="between" grow>
- <Text variant="labelsTitleCase">Focus mode</Text>
+ <Text variant="labels">Focus mode</Text>
<Kbd value={["alt", "shift", "s"]} />
</Flex>
</DropdownMenuRadioItem>
@@ -94,7 +94,7 @@ export const ModeMenu = () => {
onFocus={() => setFocusedValue("advanced")}
>
<Flex justify="between" grow>
- <Text variant="labelsTitleCase">Advanced mode</Text>
+ <Text variant="labels">Advanced mode</Text>
<Kbd value={["alt", "shift", "a"]} />
</Flex>
</DropdownMenuRadioItem>
diff --git a/apps/builder/app/builder/features/style-panel/style-source-section.tsx b/apps/builder/app/builder/features/style-panel/style-source-section.tsx
index cae93bdeff..5766b7b288 100644
--- a/apps/builder/app/builder/features/style-panel/style-source-section.tsx
+++ b/apps/builder/app/builder/features/style-panel/style-source-section.tsx
@@ -3,6 +3,7 @@ import { useStore } from "@nanostores/react";
import { nanoid } from "nanoid";
import { computed } from "nanostores";
import { pseudoClassesByTag } from "@webstudio-is/html-data";
+import { isPseudoElement } from "@webstudio-is/css-data";
import {
type Instance,
type StyleSource,
@@ -36,7 +37,6 @@ import { serverSyncStore } from "~/shared/sync/sync-stores";
import { subscribe } from "~/shared/pubsub";
import { $selectedInstance } from "~/shared/awareness";
import { $instanceTags } from "./shared/model";
-import { humanizeString } from "~/shared/string-utils";
// Declare command for this module
declare module "~/shared/pubsub" {
@@ -279,26 +279,76 @@ const clearStyles = (styleSourceId: StyleSource["id"]) => {
};
const $componentStates = computed(
- [$selectedInstance, $registeredComponentMetas, $instanceTags],
- (selectedInstance, registeredComponentMetas, instanceTags) => {
+ [
+ $selectedInstance,
+ $registeredComponentMetas,
+ $instanceTags,
+ $styles,
+ $selectedStyleState,
+ ],
+ (
+ selectedInstance,
+ registeredComponentMetas,
+ instanceTags,
+ styles,
+ selectedStyleState
+ ) => {
if (selectedInstance === undefined) {
return;
}
const tag = instanceTags.get(selectedInstance.id);
- const tagStates = [
+ const allStates = [
...pseudoClassesByTag["*"],
...(pseudoClassesByTag[tag ?? ""] ?? []),
- ].map((state) => ({
- category: "states" as const,
- label: humanizeString(state),
- selector: state,
- }));
+ ];
+
+ // Get recently used selectors from project styles
+ const usedSelectors = new Set<string>();
+ for (const styleDecl of styles.values()) {
+ if (styleDecl.state && styleDecl.state.trim()) {
+ usedSelectors.add(styleDecl.state);
+ }
+ }
+
+ // Include currently selected state so it appears in the menu immediately
+ // even before any styles are added to it
+ if (selectedStyleState && selectedStyleState.trim()) {
+ usedSelectors.add(selectedStyleState);
+ }
+
+ // Combine predefined states with recently used, removing duplicates
+ const allStateSelectors = new Set([...allStates, ...usedSelectors]);
+
+ const states = Array.from(allStateSelectors)
+ .filter((state) => !isPseudoElement(state))
+ .map((state) => ({
+ type: "state" as const,
+ label: state,
+ selector: state,
+ source: allStates.includes(state)
+ ? ("native" as const)
+ : ("custom" as const),
+ }));
+
+ const pseudoElements = Array.from(allStateSelectors)
+ .filter((state) => isPseudoElement(state))
+ .map((state) => ({
+ type: "pseudoElement" as const,
+ label: state,
+ selector: state,
+ source: allStates.includes(state)
+ ? ("native" as const)
+ : ("custom" as const),
+ }));
+
const meta = registeredComponentMetas.get(selectedInstance.component);
const componentStates = (meta?.states ?? []).map((item) => ({
- category: "component-states" as const,
+ type: "state" as const,
...item,
+ source: "component" as const,
}));
- return [...tagStates, ...componentStates];
+
+ return [...states, ...componentStates, ...pseudoElements];
}
);
@@ -345,6 +395,9 @@ export const StyleSourcesSection = () => {
const selectedInstanceStatesByStyleSourceId = useStore(
$selectedInstanceStatesByStyleSourceId
);
+ const selectedOrLastStyleSourceSelector = useStore(
+ $selectedOrLastStyleSourceSelector
+ );
// Subscribe to focusStyleSourceInput command
useEffect(() => {
@@ -362,9 +415,6 @@ export const StyleSourcesSection = () => {
selectedInstanceStatesByStyleSourceId.get(styleSource.id) ?? []
)
);
- const selectedOrLastStyleSourceSelector = useStore(
- $selectedOrLastStyleSourceSelector
- );
const [editingItemId, setEditingItemId] = useState<StyleSource["id"]>();
diff --git a/apps/builder/app/builder/features/style-panel/style-source/index.ts b/apps/builder/app/builder/features/style-panel/style-source/index.ts
index 57d1c6f8c8..ba2dd3f3fa 100644
--- a/apps/builder/app/builder/features/style-panel/style-source/index.ts
+++ b/apps/builder/app/builder/features/style-panel/style-source/index.ts
@@ -1,3 +1,7 @@
export * from "./style-source-input";
export * from "./style-source-badge";
-export type { ItemSource, StyleSourceError } from "./style-source-control";
+export type {
+ ItemSelector,
+ ItemSource,
+ StyleSourceError,
+} from "./style-source-control";
diff --git a/apps/builder/app/builder/features/style-panel/style-source/style-source-control.tsx b/apps/builder/app/builder/features/style-panel/style-source/style-source-control.tsx
index 1974f459d2..1d898bebd5 100644
--- a/apps/builder/app/builder/features/style-panel/style-source/style-source-control.tsx
+++ b/apps/builder/app/builder/features/style-panel/style-source/style-source-control.tsx
@@ -110,6 +110,11 @@ const Menu = (props: MenuProps) => {
export type ItemSource = "token" | "tag" | "local";
+export type ItemSelector = {
+ styleSourceId: string;
+ state?: string;
+};
+
type EditableTextProps = {
value: string;
isEditing: boolean;
@@ -367,7 +372,9 @@ export const StyleSourceControl = ({
</StyleSourceButton>
</Flex>
{stateLabel !== undefined && (
- <StyleSourceState source={source}>{stateLabel}</StyleSourceState>
+ <Tooltip content={state || stateLabel} side="top">
+ <StyleSourceState source={source}>{stateLabel}</StyleSourceState>
+ </Tooltip>
)}
{showMenu && (
<Menu open={menuOpen} onOpenChange={setMenuOpen}>
diff --git a/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx b/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx
index ec839004ec..6be22e0a36 100644
--- a/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx
+++ b/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx
@@ -25,18 +25,11 @@ import {
type CSS,
ComboboxLabel,
ComboboxSeparator,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuSeparator,
- rawTheme,
+ InputField,
theme,
styled,
ComboboxScrollArea,
- InputField,
- Flex,
- Text,
} from "@webstudio-is/design-system";
-import { CheckMarkIcon, DotIcon } from "@webstudio-is/icons";
import type { StyleSource } from "@webstudio-is/sdk";
import {
forwardRef,
@@ -52,6 +45,7 @@ import {
import { mergeRefs } from "@react-aria/utils";
import {
type ItemSource,
+ type ItemSelector,
type StyleSourceError,
menuCssVars,
StyleSourceControl,
@@ -59,9 +53,10 @@ import {
import { useSortable } from "./use-sortable";
import { matchSorter } from "match-sorter";
import { StyleSourceBadge } from "./style-source-badge";
-import { humanizeString } from "~/shared/string-utils";
import { $computedStyleDeclarations } from "../shared/model";
import type { ComputedStyleDecl } from "~/shared/style-object-model";
+import { validateSelector } from "@webstudio-is/css-data";
+import { StyleSourceMenu, type SelectorConfig } from "./style-source-menu";
type IntermediateItem = {
id: StyleSource["id"];
@@ -72,11 +67,6 @@ type IntermediateItem = {
states: string[];
};
-export type ItemSelector = {
- styleSourceId: StyleSource["id"];
- state?: string;
-};
-
const TextFieldContainer = styled("div", {
// Custom
display: "flex",
@@ -236,10 +226,10 @@ const TextFieldBase: ForwardRefRenderFunction<
}
label={item.label}
stateLabel={
- item.id === selectedItemSelector?.styleSourceId
- ? states.find(
- (state) => state.selector === selectedItemSelector.state
- )?.label
+ item.id === selectedItemSelector?.styleSourceId &&
+ selectedItemSelector.state
+ ? states.find((s) => s.selector === selectedItemSelector.state)
+ ?.label || selectedItemSelector.state
: undefined
}
error={item.id === error?.id ? error : undefined}
@@ -266,17 +256,6 @@ const TextFieldBase: ForwardRefRenderFunction<
const TextField = forwardRef(TextFieldBase);
TextField.displayName = "TextField";
-type ComponentState = {
- category: "states" | "component-states";
- selector: string;
- label: string;
-};
-
-const categories = [
- "states",
- "component-states",
-] satisfies ComponentState["category"][];
-
type StyleSourceInputProps<Item extends IntermediateItem> = {
inputRef: (element: HTMLInputElement | null) => void;
error?: StyleSourceError;
@@ -284,7 +263,7 @@ type StyleSourceInputProps<Item extends IntermediateItem> = {
value?: Array<Item>;
selectedItemSelector: undefined | ItemSelector;
editingItemId?: Item["id"];
- componentStates?: ComponentState[];
+ componentStates?: SelectorConfig[];
onSelectAutocompleteItem?: (item: Item) => void;
onDetachItem?: (id: Item["id"]) => void;
onDeleteItem?: (id: Item["id"]) => void;
@@ -349,160 +328,15 @@ const markAddedValues = <Item extends IntermediateItem>(
return items.map((item) => ({ ...item, isAdded: valueIds.has(item.id) }));
};
-const renderMenuItems = (props: {
- selectedItemSelector: undefined | ItemSelector;
- item: IntermediateItem;
- hasStyles: boolean;
- states: ComponentState[];
- onSelect?: (itemSelector: ItemSelector) => void;
- onEdit?: (itemId: IntermediateItem["id"]) => void;
- onDuplicate?: (itemId: IntermediateItem["id"]) => void;
- onConvertToToken?: (itemId: IntermediateItem["id"]) => void;
- onDisable?: (itemId: IntermediateItem["id"]) => void;
- onEnable?: (itemId: IntermediateItem["id"]) => void;
- onDetach?: (itemId: IntermediateItem["id"]) => void;
- onDelete?: (itemId: IntermediateItem["id"]) => void;
- onClearStyles?: (itemId: IntermediateItem["id"]) => void;
-}) => {
- return (
- <>
- <DropdownMenuLabel>
- <Flex gap="1" justify="between" align="center">
- <Text css={{ fontWeight: "bold" }} truncate>
- {props.item.label}
- </Text>
- {props.hasStyles && (
- <DotIcon size="12" color={rawTheme.colors.foregroundPrimary} />
- )}
- </Flex>
- </DropdownMenuLabel>
- {props.item.source !== "local" && (
- <DropdownMenuItem onSelect={() => props.onEdit?.(props.item.id)}>
- Rename
- </DropdownMenuItem>
- )}
- {props.item.source !== "local" && (
- <DropdownMenuItem onSelect={() => props.onDuplicate?.(props.item.id)}>
- Duplicate
- </DropdownMenuItem>
- )}
- {props.item.source === "local" && (
- <DropdownMenuItem
- onSelect={() => props.onConvertToToken?.(props.item.id)}
- >
- Convert to token
- </DropdownMenuItem>
- )}
- {props.item.source === "local" && (
- <DropdownMenuItem
- destructive={true}
- onSelect={() => props.onClearStyles?.(props.item.id)}
- >
- Clear styles
- </DropdownMenuItem>
- )}
- {/* @todo implement disabling
- {props.disabled ? (
- <DropdownMenuItem onSelect={() => props.onEnable?.(props.itemId)}>
- Enable
- </DropdownMenuItem>
- ) : (
- <DropdownMenuItem onSelect={() => props.onDisable?.(props.itemId)}>
- Disable
- </DropdownMenuItem>
- )}
- */}
- {props.item.source !== "local" && (
- <DropdownMenuItem onSelect={() => props.onDetach?.(props.item.id)}>
- Detach
- </DropdownMenuItem>
- )}
- {props.item.source !== "local" && (
- <DropdownMenuItem
- destructive={true}
- onSelect={() => props.onDelete?.(props.item.id)}
- >
- Delete
- </DropdownMenuItem>
- )}
-
- {categories.map((currentCategory) => {
- const categoryStates = props.states.filter(
- ({ category }) => category === currentCategory
- );
- // prevent rendering empty category
- if (categoryStates.length === 0) {
- return;
- }
- return (
- <Fragment key={currentCategory}>
- <DropdownMenuSeparator />
- <DropdownMenuLabel>
- {humanizeString(currentCategory)}
- </DropdownMenuLabel>
- {categoryStates.map(({ label, selector }) => (
- <DropdownMenuItem
- key={selector}
- withIndicator={true}
- icon={
- props.item.id === props.selectedItemSelector?.styleSourceId &&
- selector === props.selectedItemSelector.state && (
- <CheckMarkIcon
- color={
- props.item.states.includes(selector)
- ? rawTheme.colors.foregroundPrimary
- : rawTheme.colors.foregroundIconMain
- }
- size={12}
- />
- )
- }
- onSelect={() =>
- props.onSelect?.({
- styleSourceId: props.item.id,
- // toggle state selection
- state:
- props.selectedItemSelector?.state === selector
- ? undefined
- : selector,
- })
- }
- >
- <Flex justify="between" align="center" grow>
- {label}
- {props.item.states.includes(selector) && (
- <DotIcon
- size="12"
- color={rawTheme.colors.foregroundPrimary}
- />
- )}
- </Flex>
- </DropdownMenuItem>
- ))}
- </Fragment>
- );
- })}
-
- <DropdownMenuSeparator />
- {props.item.source === "local" && (
- <DropdownMenuItem hint>
- Style instances without creating a token or override a token locally.
- </DropdownMenuItem>
- )}
- {props.item.source === "token" && (
- <DropdownMenuItem hint>
- Reuse styles across multiple instances by creating a token.
- </DropdownMenuItem>
- )}
- </>
- );
-};
-
export const StyleSourceInput = (
props: StyleSourceInputProps<IntermediateItem>
) => {
const value = props.value ?? [];
const [label, setLabel] = useState("");
+ const [selectorInputValue, setSelectorInputValue] = useState("");
+ const [selectorValidation, setSelectorValidation] = useState<
+ ReturnType<typeof validateSelector>
+ >({ success: true, type: "pseudo-class" });
const {
items,
@@ -557,6 +391,53 @@ export const StyleSourceInput = (
const states = props.componentStates ?? [];
+ const handleSelectorInputChange = (value: string) => {
+ setSelectorInputValue(value);
+ // Don't validate while typing, only show validation errors after Enter
+ setSelectorValidation({ success: true, type: "pseudo-class" });
+ };
+
+ const handleSelectorInputKeyDown = (
+ event: React.KeyboardEvent,
+ itemId: IntermediateItem["id"]
+ ) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ event.stopPropagation();
+
+ const selector = selectorInputValue.trim();
+
+ // Empty selector removes state
+ if (selector === "") {
+ props.onSelectItem?.({
+ styleSourceId: itemId,
+ state: undefined,
+ });
+ setSelectorInputValue("");
+ setSelectorValidation({ success: true, type: "pseudo-class" });
+ return;
+ }
+
+ // Validate non-empty selectors
+ const validation = validateSelector(selector);
+ setSelectorValidation(validation);
+
+ if (validation.success) {
+ // Select the item with the new selector
+ props.onSelectItem?.({
+ styleSourceId: itemId,
+ state: selector,
+ });
+ setSelectorInputValue("");
+ setSelectorValidation({ success: true, type: "pseudo-class" });
+ }
+ // If validation failed, keep the input value so user can fix it
+ } else if (event.key === "Escape") {
+ setSelectorInputValue("");
+ setSelectorValidation({ success: true, type: "pseudo-class" });
+ }
+ };
+
return (
<ComboboxRoot open={isOpen}>
<Box {...getComboboxProps()}>
@@ -566,23 +447,27 @@ export const StyleSourceInput = (
{...inputProps}
inputRef={props.inputRef}
error={props.error}
- renderStyleSourceMenuItems={(item, hasStyles) =>
- renderMenuItems({
- selectedItemSelector: props.selectedItemSelector,
- item,
- hasStyles,
- states,
- onSelect: props.onSelectItem,
- onDuplicate: props.onDuplicateItem,
- onConvertToToken: props.onConvertToToken,
- onEnable: props.onEnableItem,
- onDisable: props.onDisableItem,
- onEdit: props.onEditItem,
- onDetach: props.onDetachItem,
- onDelete: props.onDeleteItem,
- onClearStyles: props.onClearStyles,
- })
- }
+ renderStyleSourceMenuItems={(item, hasStyles) => (
+ <StyleSourceMenu
+ selectedItemSelector={props.selectedItemSelector}
+ item={item}
+ hasStyles={hasStyles}
+ states={states}
+ selectorInputValue={selectorInputValue}
+ selectorValidation={selectorValidation}
+ onSelectorInputChange={handleSelectorInputChange}
+ onSelectorInputKeyDown={handleSelectorInputKeyDown}
+ onSelect={props.onSelectItem}
+ onDuplicate={props.onDuplicateItem}
+ onConvertToToken={props.onConvertToToken}
+ onEnable={props.onEnableItem}
+ onDisable={props.onDisableItem}
+ onEdit={props.onEditItem}
+ onDetach={props.onDetachItem}
+ onDelete={props.onDeleteItem}
+ onClearStyles={props.onClearStyles}
+ />
+ )}
onChangeItem={props.onChangeItem}
onSelectItem={props.onSelectItem}
onEditItem={props.onEditItem}
diff --git a/apps/builder/app/builder/features/style-panel/style-source/style-source-menu.tsx b/apps/builder/app/builder/features/style-panel/style-source/style-source-menu.tsx
new file mode 100644
index 0000000000..3bc43dfc6c
--- /dev/null
+++ b/apps/builder/app/builder/features/style-panel/style-source/style-source-menu.tsx
@@ -0,0 +1,337 @@
+import { Fragment, useState } from "react";
+import {
+ Box,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ Flex,
+ InputErrorsTooltip,
+ InputField,
+ rawTheme,
+ Text,
+ theme,
+} from "@webstudio-is/design-system";
+import { CheckMarkIcon, DotIcon } from "@webstudio-is/icons";
+import {
+ validateSelector,
+ pseudoClassDescriptions,
+ pseudoElementDescriptions,
+} from "@webstudio-is/css-data";
+import type { ItemSource, ItemSelector } from "./style-source-control";
+
+export type SelectorConfig = {
+ type: "state" | "pseudoElement";
+ selector: string;
+ label: string;
+ description?: string;
+ source?: "native" | "component" | "custom";
+};
+
+type IntermediateItem = {
+ id: string;
+ label: string;
+ disabled: boolean;
+ source: ItemSource;
+ isAdded?: boolean;
+ states: string[];
+};
+
+const selectorLabels = [
+ "state",
+ "pseudoElement",
+] satisfies SelectorConfig["type"][];
+
+const categoryLabels: Record<SelectorConfig["type"], string> = {
+ state: "States",
+ pseudoElement: "Pseudo elements",
+};
+
+const menuActionDescriptions = {
+ rename: "Change the name of this token to better describe its purpose.",
+ duplicate: "Create a copy of this token with all its styles.",
+ convertToToken:
+ "Turn local styles into a reusable token you can apply to other elements.",
+ clearStyles: "Remove all styles from this local style source.",
+ detach: "Remove this token from the element without deleting it.",
+ delete: "Permanently delete this token and all its styles from the project.",
+} as const;
+
+type MenuAction = keyof typeof menuActionDescriptions;
+
+const getDescription = (selector: string, type: "state" | "pseudoElement") => {
+ // Normalize the selector to match the description keys
+ const normalized = selector.startsWith(":") ? selector : `:${selector}`;
+ const doubleColon = selector.startsWith("::")
+ ? selector
+ : `::${selector.replace(/^:/, "")}`;
+
+ if (type === "pseudoElement") {
+ return (
+ pseudoElementDescriptions[doubleColon] ??
+ pseudoElementDescriptions[selector]
+ );
+ }
+ return (
+ pseudoClassDescriptions[normalized] ?? pseudoClassDescriptions[selector]
+ );
+};
+
+type StyleSourceMenuProps = {
+ selectedItemSelector: undefined | ItemSelector;
+ item: IntermediateItem;
+ hasStyles: boolean;
+ states: SelectorConfig[];
+ selectorInputValue: string;
+ selectorValidation: ReturnType<typeof validateSelector>;
+ onSelectorInputChange: (value: string) => void;
+ onSelectorInputKeyDown: (
+ event: React.KeyboardEvent,
+ itemId: IntermediateItem["id"]
+ ) => void;
+ onSelect?: (itemSelector: ItemSelector) => void;
+ onEdit?: (itemId: IntermediateItem["id"]) => void;
+ onDuplicate?: (itemId: IntermediateItem["id"]) => void;
+ onConvertToToken?: (itemId: IntermediateItem["id"]) => void;
+ onDisable?: (itemId: IntermediateItem["id"]) => void;
+ onEnable?: (itemId: IntermediateItem["id"]) => void;
+ onDetach?: (itemId: IntermediateItem["id"]) => void;
+ onDelete?: (itemId: IntermediateItem["id"]) => void;
+ onClearStyles?: (itemId: IntermediateItem["id"]) => void;
+};
+
+export const StyleSourceMenu = (props: StyleSourceMenuProps) => {
+ const [highlightedSelector, setHighlightedSelector] = useState<{
+ selector: string;
+ type: "state" | "pseudoElement";
+ description?: string;
+ }>();
+ const [highlightedAction, setHighlightedAction] = useState<MenuAction>();
+
+ // Get description for highlighted or selected item
+ const selectedState = props.selectedItemSelector?.state;
+ const selectedConfig = selectedState
+ ? props.states.find((s) => s.selector === selectedState)
+ : undefined;
+ const descriptionSelector =
+ highlightedSelector ??
+ (selectedConfig
+ ? {
+ selector: selectedConfig.selector,
+ type: selectedConfig.type,
+ description: selectedConfig.description,
+ }
+ : undefined);
+
+ // Priority: action description > selector description > source description
+ const actionDescription = highlightedAction
+ ? menuActionDescriptions[highlightedAction]
+ : undefined;
+
+ const selectorDescription = descriptionSelector
+ ? (descriptionSelector.description ??
+ getDescription(descriptionSelector.selector, descriptionSelector.type))
+ : undefined;
+
+ // Get source description based on item source
+ const sourceDescription =
+ props.item.source === "local"
+ ? "Style instances without creating a token or override a token locally."
+ : props.item.source === "token"
+ ? "Reuse styles across multiple instances by creating a token."
+ : undefined;
+
+ const description =
+ actionDescription ?? selectorDescription ?? sourceDescription;
+
+ return (
+ <>
+ <DropdownMenuLabel>
+ <Flex gap="1" justify="between" align="center">
+ <Text css={{ fontWeight: "bold" }} truncate>
+ {props.item.label}
+ </Text>
+ {props.hasStyles && (
+ <DotIcon size="12" color={rawTheme.colors.foregroundPrimary} />
+ )}
+ </Flex>
+ </DropdownMenuLabel>
+ {props.item.source !== "local" && (
+ <DropdownMenuItem
+ onFocus={() => {
+ setHighlightedSelector(undefined);
+ setHighlightedAction("rename");
+ }}
+ onSelect={() => props.onEdit?.(props.item.id)}
+ >
+ Rename
+ </DropdownMenuItem>
+ )}
+ {props.item.source !== "local" && (
+ <DropdownMenuItem
+ onFocus={() => {
+ setHighlightedSelector(undefined);
+ setHighlightedAction("duplicate");
+ }}
+ onSelect={() => props.onDuplicate?.(props.item.id)}
+ >
+ Duplicate
+ </DropdownMenuItem>
+ )}
+ {props.item.source === "local" && (
+ <DropdownMenuItem
+ onFocus={() => {
+ setHighlightedSelector(undefined);
+ setHighlightedAction("convertToToken");
+ }}
+ onSelect={() => props.onConvertToToken?.(props.item.id)}
+ >
+ Convert to token
+ </DropdownMenuItem>
+ )}
+ {props.item.source === "local" && (
+ <DropdownMenuItem
+ destructive={true}
+ onFocus={() => {
+ setHighlightedSelector(undefined);
+ setHighlightedAction("clearStyles");
+ }}
+ onSelect={() => props.onClearStyles?.(props.item.id)}
+ >
+ Clear styles
+ </DropdownMenuItem>
+ )}
+ {props.item.source !== "local" && (
+ <DropdownMenuItem
+ onFocus={() => {
+ setHighlightedSelector(undefined);
+ setHighlightedAction("detach");
+ }}
+ onSelect={() => props.onDetach?.(props.item.id)}
+ >
+ Detach
+ </DropdownMenuItem>
+ )}
+ {props.item.source !== "local" && (
+ <DropdownMenuItem
+ destructive={true}
+ onFocus={() => {
+ setHighlightedSelector(undefined);
+ setHighlightedAction("delete");
+ }}
+ onSelect={() => props.onDelete?.(props.item.id)}
+ >
+ Delete
+ </DropdownMenuItem>
+ )}
+ {selectorLabels.map((currentCategory) => {
+ const categoryStates = props.states.filter(
+ ({ type }) => type === currentCategory
+ );
+ if (categoryStates.length === 0) {
+ return;
+ }
+ return (
+ <Fragment key={currentCategory}>
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel>
+ {categoryLabels[currentCategory]}
+ </DropdownMenuLabel>
+ {categoryStates.map(
+ ({ label, selector, source, type, description }, index) => {
+ const previousItem = categoryStates[index - 1];
+ const showSeparator =
+ index > 0 &&
+ source === "component" &&
+ previousItem?.source !== "component";
+
+ return (
+ <Fragment key={selector}>
+ {showSeparator && <DropdownMenuSeparator />}
+ <DropdownMenuItem
+ withIndicator={true}
+ onFocus={() => {
+ setHighlightedAction(undefined);
+ setHighlightedSelector({ selector, type, description });
+ }}
+ icon={
+ props.item.id ===
+ props.selectedItemSelector?.styleSourceId &&
+ selector === props.selectedItemSelector.state && (
+ <CheckMarkIcon
+ color={
+ props.item.states.includes(selector)
+ ? rawTheme.colors.foregroundPrimary
+ : rawTheme.colors.foregroundIconMain
+ }
+ size={12}
+ />
+ )
+ }
+ onSelect={() =>
+ props.onSelect?.({
+ styleSourceId: props.item.id,
+ state:
+ props.selectedItemSelector?.state === selector
+ ? undefined
+ : selector,
+ })
+ }
+ >
+ <Flex justify="between" align="center" grow>
+ <Text variant="labels" truncate>
+ {label}
+ </Text>
+ {props.item.states.includes(selector) && (
+ <DotIcon
+ size="12"
+ color={rawTheme.colors.foregroundPrimary}
+ />
+ )}
+ </Flex>
+ </DropdownMenuItem>
+ </Fragment>
+ );
+ }
+ )}
+ </Fragment>
+ );
+ })}
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel>Custom</DropdownMenuLabel>
+ <Box css={{ padding: theme.spacing[4] }}>
+ <InputErrorsTooltip
+ variant="wrapped"
+ errors={
+ props.selectorValidation.success === false
+ ? [props.selectorValidation.error]
+ : undefined
+ }
+ side="bottom"
+ >
+ <InputField
+ value={props.selectorInputValue}
+ onChange={(event) =>
+ props.onSelectorInputChange(event.target.value)
+ }
+ onFocus={() => {
+ setHighlightedSelector(undefined);
+ setHighlightedAction(undefined);
+ }}
+ onKeyDown={(event) => {
+ event.stopPropagation();
+ props.onSelectorInputKeyDown(event, props.item.id);
+ }}
+ placeholder="::before"
+ autoFocus={false}
+ color={
+ props.selectorValidation.success === false ? "error" : undefined
+ }
+ css={{ width: "100%" }}
+ />
+ </InputErrorsTooltip>
+ </Box>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem hint>{description}</DropdownMenuItem>
+ </>
+ );
+};
diff --git a/apps/builder/app/builder/features/topbar/menu/menu.tsx b/apps/builder/app/builder/features/topbar/menu/menu.tsx
index 8d0b6102a5..6c1406c1bb 100644
--- a/apps/builder/app/builder/features/topbar/menu/menu.tsx
+++ b/apps/builder/app/builder/features/topbar/menu/menu.tsx
@@ -96,7 +96,7 @@ export const Menu = () => {
$openProjectSettings.set("general");
}}
>
- Project Settings
+ Project settings
</DropdownMenuItem>
</Tooltip>
<DropdownMenuItem onSelect={() => emitCommand("openBreakpointsMenu")}>
@@ -246,7 +246,7 @@ export const Menu = () => {
{isDesignMode && (
<DropdownMenuItem onSelect={() => emitCommand("openCommandPanel")}>
- Search & Commands
+ Search & commands
<DropdownMenuItemRightSlot>
<Kbd value={["meta", "k"]} />
</DropdownMenuItemRightSlot>
@@ -254,7 +254,7 @@ export const Menu = () => {
)}
<DropdownMenuItem onSelect={() => emitCommand("openKeyboardShortcuts")}>
- Keyboard Shortcuts
+ Keyboard shortcuts
<DropdownMenuItemRightSlot>
<Kbd value={["shift", "?"]} />
</DropdownMenuItemRightSlot>
diff --git a/apps/builder/app/builder/features/topbar/publish.tsx b/apps/builder/app/builder/features/topbar/publish.tsx
index b60ab14e06..044bfa59ca 100644
--- a/apps/builder/app/builder/features/topbar/publish.tsx
+++ b/apps/builder/app/builder/features/topbar/publish.tsx
@@ -1010,7 +1010,7 @@ const ExportContent = (props: { projectId: Project["id"] }) => {
<Grid columns={1} gap={2}>
<div />
<Grid columns={2} gap={2} align={"center"}>
- <Text color="main" variant="labelsTitleCase">
+ <Text color="main" variant="labels">
Destination
</Text>
@@ -1064,7 +1064,7 @@ const ExportContent = (props: { projectId: Project["id"] }) => {
<Separator css={{ alignSelf: "unset" }} />
</Grid>
<Grid columns={1} gap={1}>
- <Text color="main" variant="labelsTitleCase">
+ <Text color="main" variant="labels">
Step 1
</Text>
<Text color="subtle">
@@ -1094,7 +1094,7 @@ const ExportContent = (props: { projectId: Project["id"] }) => {
<Grid columns={1} gap={2}>
<Grid columns={1} gap={1}>
- <Text color="main" variant="labelsTitleCase">
+ <Text color="main" variant="labels">
Step 2
</Text>
<Text color="subtle">
@@ -1119,7 +1119,7 @@ const ExportContent = (props: { projectId: Project["id"] }) => {
<Grid columns={1} gap={2}>
<Grid columns={1} gap={1}>
- <Text color="main" variant="labelsTitleCase">
+ <Text color="main" variant="labels">
Step 3
</Text>
<Text color="subtle">
diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/media-badge.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/media-badge.tsx
index 015ded2947..b51b1d72d6 100644
--- a/apps/builder/app/builder/features/workspace/canvas-tools/media-badge.tsx
+++ b/apps/builder/app/builder/features/workspace/canvas-tools/media-badge.tsx
@@ -32,10 +32,10 @@ export const MediaBadge = () => {
}
return (
<Flex gap="2" className={labelStyle()} align="center">
- <Text variant="labelsTitleCase" color="contrast" className={badgeStyle()}>
+ <Text variant="labels" color="contrast" className={badgeStyle()}>
{breakpoint.maxWidth ?? breakpoint.minWidth}
</Text>
- <Text variant="labelsSentenceCase">{media}</Text>
+ <Text variant="labels">{media}</Text>
</Flex>
);
};
diff --git a/apps/builder/app/builder/inspector.tsx b/apps/builder/app/builder/inspector.tsx
index 9330b43540..d271f7129c 100644
--- a/apps/builder/app/builder/inspector.tsx
+++ b/apps/builder/app/builder/inspector.tsx
@@ -40,7 +40,7 @@ const InstanceInfo = ({ instance }: { instance: Instance }) => {
<Flex shrink={false}>
<InstanceIcon instance={instance} />
</Flex>
- <Text truncate variant="labelsSentenceCase">
+ <Text truncate variant="labels">
{getInstanceLabel(instance)}
</Text>
</Flex>
diff --git a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx b/apps/builder/app/builder/shared/asset-manager/asset-info.tsx
index 5a06010dfd..086bbf65ea 100644
--- a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx
+++ b/apps/builder/app/builder/shared/asset-manager/asset-info.tsx
@@ -455,11 +455,11 @@ const AssetInfoContent = ({
>
<Flex align="center" css={{ gap: theme.spacing[3] }}>
<CloudIcon />
- <Text variant="labelsSentenceCase">{prettyBytes(size)}</Text>
+ <Text variant="labels">{prettyBytes(size)}</Text>
</Flex>
<Flex align="center" css={{ gap: theme.spacing[3] }}>
<PageIcon />
- <Text variant="labelsSentenceCase">
+ <Text variant="labels">
{getMimeTypeByExtension(ext) ?? "unknown"}
</Text>
</Flex>
@@ -467,15 +467,13 @@ const AssetInfoContent = ({
<>
<Flex align="center" gap={1}>
<DimensionsIcon />
- <Text variant="labelsSentenceCase">
+ <Text variant="labels">
{meta.width} x {meta.height}
</Text>
</Flex>
<Flex align="center" gap={1}>
<AspectRatioIcon />
- <Text variant="labelsSentenceCase">
- {getFormattedAspectRatio(meta)}
- </Text>
+ <Text variant="labels">{getFormattedAspectRatio(meta)}</Text>
</Flex>
</>
)}
@@ -490,7 +488,7 @@ const AssetInfoContent = ({
>
<UsageDot />
</Flex>
- <Text variant="labelsSentenceCase">{usages.length} uses</Text>
+ <Text variant="labels">{usages.length} uses</Text>
</Flex>
</Grid>
</Box>
diff --git a/apps/builder/app/builder/shared/binding-popover.tsx b/apps/builder/app/builder/shared/binding-popover.tsx
index 9b3fe35d4e..f9f9580c09 100644
--- a/apps/builder/app/builder/shared/binding-popover.tsx
+++ b/apps/builder/app/builder/shared/binding-popover.tsx
@@ -140,7 +140,7 @@ const BindingPanel = ({
>
<Box css={{ paddingBottom: theme.spacing[5] }}>
<Flex gap="1" css={{ padding: theme.panel.padding }}>
- <Text variant="labelsSentenceCase">Variables</Text>
+ <Text variant="labels">Variables</Text>
<Tooltip
variant="wrapped"
content={
@@ -152,7 +152,7 @@ const BindingPanel = ({
</Flex>
{scopeEntries.length === 0 && (
<Flex justify="center" align="center" css={{ py: theme.spacing[5] }}>
- <Text variant="labelsSentenceCase" align="center">
+ <Text variant="labels" align="center">
No variables available
</Text>
</Flex>
@@ -191,7 +191,7 @@ const BindingPanel = ({
</CssValueListArrowFocus>
</Box>
<Flex gap="1" css={{ padding: theme.panel.padding }}>
- <Text variant="labelsSentenceCase">Expression Editor</Text>
+ <Text variant="labels">Expression Editor</Text>
<Tooltip
variant="wrapped"
content={
diff --git a/apps/builder/app/builder/shared/css-editor/add-style-input.tsx b/apps/builder/app/builder/shared/css-editor/add-style-input.tsx
index 21c3725e5e..f6b042cdbf 100644
--- a/apps/builder/app/builder/shared/css-editor/add-style-input.tsx
+++ b/apps/builder/app/builder/shared/css-editor/add-style-input.tsx
@@ -301,11 +301,7 @@ export const AddStyleInput = forwardRef<
{...combobox.getItemProps({ item, index })}
key={index}
>
- <Text
- variant="labelsSentenceCase"
- truncate
- css={{ maxWidth: "25ch" }}
- >
+ <Text variant="labels" truncate css={{ maxWidth: "25ch" }}>
{item.label}
</Text>
</ComboboxListboxItem>
diff --git a/apps/builder/app/canvas/shared/styles.test.ts b/apps/builder/app/canvas/shared/styles.test.ts
new file mode 100644
index 0000000000..3e8859cfa8
--- /dev/null
+++ b/apps/builder/app/canvas/shared/styles.test.ts
@@ -0,0 +1,746 @@
+import { describe, test, expect } from "vitest";
+import type { Instance, StyleDecl } from "@webstudio-is/sdk";
+import {
+ descendantComponent,
+ ROOT_INSTANCE_ID,
+ rootComponent,
+} from "@webstudio-is/sdk";
+import {
+ createRegularStyleSheet,
+ FakeStyleElement,
+} from "@webstudio-is/css-engine";
+import { __testing__ } from "./styles";
+
+const {
+ getEphemeralProperty,
+ getInstanceSelector,
+ getPresetStyleSelector,
+ computeDescendantSelectors,
+ computeInstanceStyles,
+ computeEditableCursorRules,
+ computeStylesDiff,
+ toDeclarationParams,
+ renderStateStyles,
+} = __testing__;
+
+const createTestSheet = () =>
+ createRegularStyleSheet({ element: new FakeStyleElement() });
+
+const mockTransformValue = () => undefined;
+
+// Simple passthrough - just return the style value
+const mockToStyleValue = (styleDecl: Pick<StyleDecl, "value">) =>
+ styleDecl.value;
+
+const createStyleDecl = (overrides: Partial<StyleDecl> = {}): StyleDecl => ({
+ styleSourceId: "style-source-1",
+ breakpointId: "base",
+ property: "color",
+ value: { type: "keyword", value: "red" },
+ ...overrides,
+});
+
+describe("renderStateStyles", () => {
+ test("clears sheet when instanceStyles is undefined", () => {
+ const sheet = createTestSheet();
+ sheet.addMediaRule("base");
+ const rule = sheet.addNestingRule('[data-ws-id="old"]');
+ rule.setDeclaration({
+ breakpoint: "base",
+ selector: "",
+ property: "color",
+ value: { type: "keyword", value: "blue" },
+ });
+ renderStateStyles({
+ instanceStyles: undefined,
+ sheet,
+ transformValue: mockTransformValue,
+ toStyleValue: mockToStyleValue,
+ });
+ expect(sheet.cssText).toBe("");
+ });
+
+ describe("pseudo-elements keep their selector", () => {
+ test("::before styles apply to ::before selector", () => {
+ const sheet = createTestSheet();
+ renderStateStyles({
+ instanceStyles: {
+ instanceId: "box",
+ selectedState: "::before",
+ breakpoints: [{ id: "base", label: "Base" }],
+ styles: [
+ createStyleDecl({
+ property: "content",
+ value: { type: "keyword", value: '""' },
+ }),
+ ],
+ },
+ sheet,
+ transformValue: mockTransformValue,
+ toStyleValue: mockToStyleValue,
+ });
+ expect(sheet.cssText).toContain("::before");
+ expect(sheet.cssText).toContain('content: ""');
+ });
+
+ test("::after styles apply to ::after selector", () => {
+ const sheet = createTestSheet();
+ renderStateStyles({
+ instanceStyles: {
+ instanceId: "box",
+ selectedState: "::after",
+ breakpoints: [{ id: "base", label: "Base" }],
+ styles: [
+ createStyleDecl({
+ property: "content",
+ value: { type: "keyword", value: '""' },
+ }),
+ ],
+ },
+ sheet,
+ transformValue: mockTransformValue,
+ toStyleValue: mockToStyleValue,
+ });
+ expect(sheet.cssText).toContain("::after");
+ });
+
+ test("::placeholder keeps selector", () => {
+ const sheet = createTestSheet();
+ renderStateStyles({
+ instanceStyles: {
+ instanceId: "input",
+ selectedState: "::placeholder",
+ breakpoints: [{ id: "base", label: "Base" }],
+ styles: [createStyleDecl()],
+ },
+ sheet,
+ transformValue: mockTransformValue,
+ toStyleValue: mockToStyleValue,
+ });
+ expect(sheet.cssText).toContain("::placeholder");
+ });
+ });
+
+ describe("pseudo-classes render without state for preview", () => {
+ test(":hover styles apply without :hover selector", () => {
+ const sheet = createTestSheet();
+ renderStateStyles({
+ instanceStyles: {
+ instanceId: "button",
+ selectedState: ":hover",
+ breakpoints: [{ id: "base", label: "Base" }],
+ styles: [
+ createStyleDecl({
+ property: "backgroundColor",
+ value: { type: "keyword", value: "blue" },
+ }),
+ ],
+ },
+ sheet,
+ transformValue: mockTransformValue,
+ toStyleValue: mockToStyleValue,
+ });
+ expect(sheet.cssText).not.toContain(":hover");
+ expect(sheet.cssText).toContain("background-color: blue");
+ });
+
+ test(":focus styles apply without :focus selector", () => {
+ const sheet = createTestSheet();
+ renderStateStyles({
+ instanceStyles: {
+ instanceId: "input",
+ selectedState: ":focus",
+ breakpoints: [{ id: "base", label: "Base" }],
+ styles: [createStyleDecl()],
+ },
+ sheet,
+ transformValue: mockTransformValue,
+ toStyleValue: mockToStyleValue,
+ });
+ expect(sheet.cssText).not.toContain(":focus");
+ });
+
+ test(":active styles apply without :active selector", () => {
+ const sheet = createTestSheet();
+ renderStateStyles({
+ instanceStyles: {
+ instanceId: "button",
+ selectedState: ":active",
+ breakpoints: [{ id: "base", label: "Base" }],
+ styles: [createStyleDecl()],
+ },
+ sheet,
+ transformValue: mockTransformValue,
+ toStyleValue: mockToStyleValue,
+ });
+ expect(sheet.cssText).not.toContain(":active");
+ });
+ });
+
+ test("creates nesting rule with correct instance selector", () => {
+ const sheet = createTestSheet();
+ renderStateStyles({
+ instanceStyles: {
+ instanceId: "my-instance-123",
+ selectedState: ":hover",
+ breakpoints: [{ id: "base", label: "Base" }],
+ styles: [createStyleDecl()],
+ },
+ sheet,
+ transformValue: mockTransformValue,
+ toStyleValue: mockToStyleValue,
+ });
+ expect(sheet.cssText).toContain('[data-ws-id="my-instance-123"]');
+ });
+
+ test("renders multiple style declarations", () => {
+ const sheet = createTestSheet();
+ renderStateStyles({
+ instanceStyles: {
+ instanceId: "box",
+ selectedState: "::before",
+ breakpoints: [{ id: "base", label: "Base" }],
+ styles: [
+ createStyleDecl({
+ property: "content",
+ value: { type: "keyword", value: '""' },
+ }),
+ createStyleDecl({
+ property: "color",
+ value: { type: "keyword", value: "red" },
+ }),
+ createStyleDecl({
+ property: "fontSize",
+ value: { type: "unit", unit: "px", value: 16 },
+ }),
+ ],
+ },
+ sheet,
+ transformValue: mockTransformValue,
+ toStyleValue: mockToStyleValue,
+ });
+ expect(sheet.cssText).toContain('content: ""');
+ expect(sheet.cssText).toContain("color: red");
+ expect(sheet.cssText).toContain("font-size: 16px");
+ });
+});
+
+describe("getEphemeralProperty", () => {
+ test("generates property name from styleSourceId, state, and property", () => {
+ expect(
+ getEphemeralProperty({
+ styleSourceId: "source-1",
+ state: ":hover",
+ property: "color",
+ })
+ ).toBe("--source-1-:hover-color");
+ });
+
+ test("handles missing state as empty string", () => {
+ expect(
+ getEphemeralProperty({
+ styleSourceId: "source-1",
+ property: "backgroundColor",
+ })
+ ).toBe("--source-1--backgroundColor");
+ });
+
+ test("handles pseudo-element state", () => {
+ expect(
+ getEphemeralProperty({
+ styleSourceId: "abc",
+ state: "::before",
+ property: "content",
+ })
+ ).toBe("--abc-::before-content");
+ });
+});
+
+describe("computeDescendantSelectors", () => {
+ const createInstance = (
+ id: string,
+ component: string,
+ children: Instance["children"] = []
+ ): Instance => ({
+ type: "instance",
+ id,
+ component,
+ children,
+ });
+
+ const createProp = (
+ id: string,
+ instanceId: string,
+ name: string,
+ value: string
+ ) => ({
+ id,
+ instanceId,
+ name,
+ type: "string" as const,
+ value,
+ });
+
+ test("returns empty map when no descendant components", () => {
+ const instances = new Map([
+ ["box", createInstance("box", "Box", [{ type: "id", value: "text" }])],
+ ["text", createInstance("text", "Text")],
+ ]);
+ const props = new Map();
+ expect(computeDescendantSelectors(instances, props)).toEqual(new Map());
+ });
+
+ test("computes selector for descendant component with parent and selector prop", () => {
+ const instances = new Map([
+ [
+ "parent",
+ createInstance("parent", "Box", [{ type: "id", value: "descendant" }]),
+ ],
+ ["descendant", createInstance("descendant", descendantComponent)],
+ ]);
+ const props = new Map([
+ ["prop-1", createProp("prop-1", "descendant", "selector", " > div")],
+ ]);
+ const result = computeDescendantSelectors(instances, props);
+ expect(result.get("descendant")).toBe('[data-ws-id="parent"] > div');
+ });
+
+ test("ignores descendant without selector prop", () => {
+ const instances = new Map([
+ [
+ "parent",
+ createInstance("parent", "Box", [{ type: "id", value: "descendant" }]),
+ ],
+ ["descendant", createInstance("descendant", descendantComponent)],
+ ]);
+ const props = new Map();
+ const result = computeDescendantSelectors(instances, props);
+ expect(result.has("descendant")).toBe(false);
+ });
+
+ test("ignores descendant without parent", () => {
+ const instances = new Map([
+ ["descendant", createInstance("descendant", descendantComponent)],
+ ]);
+ const props = new Map([
+ ["prop-1", createProp("prop-1", "descendant", "selector", " > div")],
+ ]);
+ const result = computeDescendantSelectors(instances, props);
+ expect(result.has("descendant")).toBe(false);
+ });
+
+ test("handles multiple descendants", () => {
+ const instances = new Map([
+ [
+ "parent",
+ createInstance("parent", "Box", [
+ { type: "id", value: "desc1" },
+ { type: "id", value: "desc2" },
+ ]),
+ ],
+ ["desc1", createInstance("desc1", descendantComponent)],
+ ["desc2", createInstance("desc2", descendantComponent)],
+ ]);
+ const props = new Map([
+ ["p1", createProp("p1", "desc1", "selector", " .item")],
+ ["p2", createProp("p2", "desc2", "selector", " a")],
+ ]);
+ const result = computeDescendantSelectors(instances, props);
+ expect(result.get("desc1")).toBe('[data-ws-id="parent"] .item');
+ expect(result.get("desc2")).toBe('[data-ws-id="parent"] a');
+ });
+});
+
+describe("computeInstanceStyles", () => {
+ const createInstance = (id: string): Instance => ({
+ type: "instance",
+ id,
+ component: "Box",
+ children: [],
+ });
+
+ test("returns undefined when selectedInstance is undefined", () => {
+ expect(
+ computeInstanceStyles({
+ selectedInstance: undefined,
+ selectedStyleState: ":hover",
+ breakpoints: new Map(),
+ styleSourceSelections: new Map(),
+ styles: new Map(),
+ })
+ ).toBeUndefined();
+ });
+
+ test("returns undefined when selectedStyleState is undefined", () => {
+ expect(
+ computeInstanceStyles({
+ selectedInstance: createInstance("box"),
+ selectedStyleState: undefined,
+ breakpoints: new Map(),
+ styleSourceSelections: new Map(),
+ styles: new Map(),
+ })
+ ).toBeUndefined();
+ });
+
+ test("filters styles by selected state and instance style sources", () => {
+ const result = computeInstanceStyles({
+ selectedInstance: createInstance("box"),
+ selectedStyleState: ":hover",
+ breakpoints: new Map([["base", { id: "base", label: "Base" }]]),
+ styleSourceSelections: new Map([
+ ["box", { values: ["local", "token-1"] }],
+ ]),
+ styles: new Map([
+ [
+ "key1",
+ createStyleDecl({
+ styleSourceId: "local",
+ breakpointId: "base",
+ state: ":hover",
+ property: "color",
+ value: { type: "keyword", value: "red" },
+ }),
+ ],
+ [
+ "key2",
+ createStyleDecl({
+ styleSourceId: "local",
+ breakpointId: "base",
+ property: "fontSize",
+ value: { type: "unit", unit: "px", value: 16 },
+ }),
+ ],
+ [
+ "key3",
+ createStyleDecl({
+ styleSourceId: "other",
+ breakpointId: "base",
+ state: ":hover",
+ property: "marginTop",
+ value: { type: "unit", unit: "px", value: 0 },
+ }),
+ ],
+ ]),
+ });
+ expect(result).toEqual({
+ instanceId: "box",
+ selectedState: ":hover",
+ breakpoints: [{ id: "base", label: "Base" }],
+ styles: [
+ {
+ styleSourceId: "local",
+ breakpointId: "base",
+ state: ":hover",
+ property: "color",
+ value: { type: "keyword", value: "red" },
+ },
+ ],
+ });
+ });
+
+ test("includes styles from multiple style sources", () => {
+ const result = computeInstanceStyles({
+ selectedInstance: createInstance("box"),
+ selectedStyleState: "::before",
+ breakpoints: new Map([["base", { id: "base", label: "Base" }]]),
+ styleSourceSelections: new Map([
+ ["box", { values: ["local", "token-1"] }],
+ ]),
+ styles: new Map([
+ [
+ "key1",
+ createStyleDecl({
+ styleSourceId: "local",
+ breakpointId: "base",
+ state: "::before",
+ property: "content",
+ value: { type: "keyword", value: '""' },
+ }),
+ ],
+ [
+ "key2",
+ createStyleDecl({
+ styleSourceId: "token-1",
+ breakpointId: "base",
+ state: "::before",
+ property: "color",
+ value: { type: "keyword", value: "blue" },
+ }),
+ ],
+ ]),
+ });
+ expect(result?.styles).toHaveLength(2);
+ });
+});
+
+describe("computeEditableCursorRules", () => {
+ const createInstance = (
+ id: string,
+ children: Instance["children"] = []
+ ): Instance => ({
+ id,
+ type: "instance",
+ component: "Box",
+ children,
+ });
+
+ test("returns empty array when no selectors", () => {
+ const result = computeEditableCursorRules([], new Map());
+ expect(result).toEqual([]);
+ });
+
+ test("generates cursor rule for editable instances", () => {
+ const instances = new Map<string, Instance>([
+ ["inst-1", createInstance("inst-1")],
+ ["inst-2", createInstance("inst-2")],
+ ]);
+ const selectors = [["inst-1"], ["inst-2"]] as [string][];
+ const result = computeEditableCursorRules(selectors, instances);
+ expect(result).toHaveLength(1);
+ expect(result[0]).toContain('[data-ws-id="inst-1"]');
+ expect(result[0]).toContain('[data-ws-id="inst-2"]');
+ expect(result[0]).toContain("cursor: text");
+ });
+
+ test("excludes instances with expression children", () => {
+ const instances = new Map<string, Instance>([
+ ["inst-1", createInstance("inst-1")],
+ [
+ "inst-2",
+ createInstance("inst-2", [{ type: "expression", value: "someExpr" }]),
+ ],
+ ]);
+ const selectors = [["inst-1"], ["inst-2"]] as [string][];
+ const result = computeEditableCursorRules(selectors, instances);
+ expect(result).toHaveLength(1);
+ expect(result[0]).toContain('[data-ws-id="inst-1"]');
+ expect(result[0]).not.toContain('[data-ws-id="inst-2"]');
+ });
+
+ test("excludes instances not found in map", () => {
+ const instances = new Map<string, Instance>([
+ ["inst-1", createInstance("inst-1")],
+ ]);
+ const selectors = [["inst-1"], ["inst-missing"]] as [string][];
+ const result = computeEditableCursorRules(selectors, instances);
+ expect(result).toHaveLength(1);
+ expect(result[0]).toContain('[data-ws-id="inst-1"]');
+ expect(result[0]).not.toContain("inst-missing");
+ });
+
+ test("chunks selectors into groups of 20", () => {
+ const instances = new Map<string, Instance>();
+ const selectors: [string][] = [];
+ for (let i = 0; i < 25; i++) {
+ const id = `inst-${i}`;
+ instances.set(id, createInstance(id));
+ selectors.push([id]);
+ }
+ const result = computeEditableCursorRules(selectors, instances);
+ expect(result).toHaveLength(2);
+ });
+
+ test("skips empty chunks", () => {
+ const instances = new Map<string, Instance>();
+ // All instances have expression children, so all chunks are empty
+ for (let i = 0; i < 5; i++) {
+ const id = `inst-${i}`;
+ instances.set(
+ id,
+ createInstance(id, [{ type: "expression", value: "expr" }])
+ );
+ }
+ const selectors = Array.from(instances.keys()).map((id) => [id]) as [
+ string,
+ ][];
+ const result = computeEditableCursorRules(selectors, instances);
+ expect(result).toEqual([]);
+ });
+});
+
+describe("computeStylesDiff", () => {
+ const style1 = createStyleDecl({
+ styleSourceId: "source-1",
+ breakpointId: "base",
+ property: "color",
+ value: { type: "keyword", value: "red" },
+ });
+ const style2 = createStyleDecl({
+ styleSourceId: "source-2",
+ breakpointId: "base",
+ property: "display",
+ value: { type: "keyword", value: "flex" },
+ });
+ const mockTransform = () => undefined;
+
+ test("returns all styles as added when prev is empty", () => {
+ const styles = new Map([
+ ["key1", style1],
+ ["key2", style2],
+ ]);
+ const result = computeStylesDiff({
+ styles,
+ transformValue: mockTransform,
+ prevStylesSet: new Set(),
+ prevTransformValue: mockTransform,
+ });
+ expect(result.addedStyles.size).toBe(2);
+ expect(result.deletedStyles.size).toBe(0);
+ expect(result.nextPrevStylesSet.size).toBe(2);
+ });
+
+ test("returns removed styles as deleted", () => {
+ const prevStyles = new Set([style1, style2]);
+ const styles = new Map([["key1", style1]]);
+ const result = computeStylesDiff({
+ styles,
+ transformValue: mockTransform,
+ prevStylesSet: prevStyles,
+ prevTransformValue: mockTransform,
+ });
+ expect(result.addedStyles.size).toBe(0);
+ expect(result.deletedStyles.size).toBe(1);
+ expect(result.deletedStyles.has(style2)).toBe(true);
+ });
+
+ test("returns new styles as added and removed as deleted", () => {
+ const style3 = createStyleDecl({
+ styleSourceId: "source-3",
+ breakpointId: "base",
+ property: "width",
+ value: { type: "unit", value: 100, unit: "px" },
+ });
+ const prevStyles = new Set([style1, style2]);
+ const styles = new Map([
+ ["key1", style1],
+ ["key3", style3],
+ ]);
+ const result = computeStylesDiff({
+ styles,
+ transformValue: mockTransform,
+ prevStylesSet: prevStyles,
+ prevTransformValue: mockTransform,
+ });
+ expect(result.addedStyles.size).toBe(1);
+ expect(result.addedStyles.has(style3)).toBe(true);
+ expect(result.deletedStyles.size).toBe(1);
+ expect(result.deletedStyles.has(style2)).toBe(true);
+ });
+
+ test("invalidates cache when transformValue changes", () => {
+ const newTransform = () => undefined;
+ const prevStyles = new Set([style1]);
+ const styles = new Map([
+ ["key1", style1],
+ ["key2", style2],
+ ]);
+ const result = computeStylesDiff({
+ styles,
+ transformValue: newTransform,
+ prevStylesSet: prevStyles,
+ prevTransformValue: mockTransform, // different reference
+ });
+ // All styles are "added" because cache was invalidated
+ expect(result.addedStyles.size).toBe(2);
+ expect(result.deletedStyles.size).toBe(0);
+ });
+
+ test("no changes when styles are identical", () => {
+ const prevStyles = new Set([style1, style2]);
+ const styles = new Map([
+ ["key1", style1],
+ ["key2", style2],
+ ]);
+ const result = computeStylesDiff({
+ styles,
+ transformValue: mockTransform,
+ prevStylesSet: prevStyles,
+ prevTransformValue: mockTransform,
+ });
+ expect(result.addedStyles.size).toBe(0);
+ expect(result.deletedStyles.size).toBe(0);
+ });
+});
+
+describe("toDeclarationParams", () => {
+ test("converts StyleDecl to declaration params", () => {
+ const styleDecl = createStyleDecl({
+ breakpointId: "tablet",
+ state: ":hover",
+ property: "backgroundColor",
+ });
+ const result = toDeclarationParams(styleDecl);
+ expect(result).toEqual({
+ breakpoint: "tablet",
+ selector: ":hover",
+ property: "backgroundColor",
+ });
+ });
+
+ test("converts undefined state to empty string", () => {
+ const styleDecl = createStyleDecl({
+ breakpointId: "base",
+ state: undefined,
+ property: "color",
+ });
+ const result = toDeclarationParams(styleDecl);
+ expect(result).toEqual({
+ breakpoint: "base",
+ selector: "",
+ property: "color",
+ });
+ });
+
+ test("handles pseudo-element state", () => {
+ const styleDecl = createStyleDecl({
+ breakpointId: "base",
+ state: "::before",
+ property: "content",
+ });
+ const result = toDeclarationParams(styleDecl);
+ expect(result).toEqual({
+ breakpoint: "base",
+ selector: "::before",
+ property: "content",
+ });
+ });
+});
+
+describe("getInstanceSelector", () => {
+ test("returns :root for ROOT_INSTANCE_ID", () => {
+ expect(getInstanceSelector(ROOT_INSTANCE_ID)).toBe(":root");
+ });
+
+ test("returns attribute selector for regular instance ID", () => {
+ expect(getInstanceSelector("inst-123")).toBe('[data-ws-id="inst-123"]');
+ });
+
+ test("returns attribute selector for empty string", () => {
+ expect(getInstanceSelector("")).toBe('[data-ws-id=""]');
+ });
+});
+
+describe("getPresetStyleSelector", () => {
+ test("returns :root for rootComponent", () => {
+ expect(getPresetStyleSelector(rootComponent, "div")).toBe(":root");
+ });
+
+ test("returns :where selector for regular component", () => {
+ expect(getPresetStyleSelector("Box", "div")).toBe(
+ 'div:where([data-ws-component="Box"])'
+ );
+ });
+
+ test("uses tag in selector", () => {
+ expect(getPresetStyleSelector("Button", "button")).toBe(
+ 'button:where([data-ws-component="Button"])'
+ );
+ });
+
+ test("handles custom component names", () => {
+ expect(getPresetStyleSelector("MyCustomComponent", "span")).toBe(
+ 'span:where([data-ws-component="MyCustomComponent"])'
+ );
+ });
+});
diff --git a/apps/builder/app/canvas/shared/styles.ts b/apps/builder/app/canvas/shared/styles.ts
index b668fdf869..983dee45a2 100644
--- a/apps/builder/app/canvas/shared/styles.ts
+++ b/apps/builder/app/canvas/shared/styles.ts
@@ -7,14 +7,17 @@ import {
getStyleDeclKey,
descendantComponent,
rootComponent,
+ type Breakpoint,
type StyleDecl,
type StyleSourceSelection,
createImageValueTransformer,
addFontRules,
} from "@webstudio-is/sdk";
import { collapsedAttribute, idAttribute } from "@webstudio-is/react-sdk";
+import { isPseudoElement } from "@webstudio-is/css-data";
import {
StyleValue,
+ type StyleSheetRegular,
type TransformValue,
type VarValue,
createRegularStyleSheet,
@@ -69,6 +72,13 @@ export const editablePlaceholderAttribute = "data-ws-editable-placeholder";
// https://developer.mozilla.org/en-US/docs/Web/CSS/attr#backwards_compatibility
export const editingPlaceholderVariable = "--ws-editing-placeholder";
+// Minimum size to prevent elements from collapsing to zero dimensions on canvas
+// This value provides enough visual space to see and interact with empty elements
+const collapsePadding = "50px";
+
+const hasExpressionChildren = (instance: Instance) =>
+ instance.children.some((child) => child.type === "expression");
+
const helperStylesShared = [
// Display a placeholder text for elements that are editable but currently empty
`:is([${editablePlaceholderAttribute}]):empty::before {
@@ -87,6 +97,7 @@ const helperStylesShared = [
left: 0;
right: 0;
top: 0;
+ /* Ensures placeholder text is visible even in narrow containers */
min-width: 100px;
opacity: 0.3;
}
@@ -107,16 +118,16 @@ const helperStylesShared = [
// 4. This rule is used here and not in collapsing detection because `data-lexical-editor` might not be set instantly.
// Mistakes in collapsing will be corrected in the next cycle.
`[${idAttribute}]:where(:not(body):not([data-lexical-editor])[${collapsedAttribute}="w"]) {
- padding-right: 50px;
+ padding-right: ${collapsePadding};
}`,
// Has no height, will collapse
`[${idAttribute}]:where(:not(body):not([data-lexical-editor])[${collapsedAttribute}="h"]) {
- padding-top: 50px;
+ padding-top: ${collapsePadding};
}`,
// Has no width or height, will collapse
`[${idAttribute}]:where(:not(body):not([data-lexical-editor])[${collapsedAttribute}="wh"]) {
- padding-right: 50px;
- padding-top: 50px;
+ padding-right: ${collapsePadding};
+ padding-top: ${collapsePadding};
}`,
`[${idAttribute}][contenteditable], [${idAttribute}]:focus {
outline: 0;
@@ -126,6 +137,21 @@ const helperStylesShared = [
}`,
];
+// Common user-select and cursor rules for canvas modes
+const helperStylesUserSelect = [
+ // When double clicking into an element to edit text, it should not select the word.
+ `[${idAttribute}] {
+ user-select: none;
+ /* Safari */
+ -webkit-user-select: none;
+ cursor: default;
+ }`,
+ `[${idAttribute}][contenteditable] {
+ /* Safari */
+ cursor: initial;
+ }`,
+];
+
// Helper styles on for canvas in design mode
// - Only instances that would collapse without helper should receive helper
// - Helper is removed when any CSS property is changed on that instance that would prevent collapsing, so that helper is not needed
@@ -138,38 +164,11 @@ const helperStylesShared = [
// If user sets `height: 100px` or does anything that would give it a height - we remove the helper padding right away, so user can actually see the height they set
//
// In other words we prevent elements from collapsing when they have 0 height or width by making them non-zero on canvas, but then we remove those paddings as soon as element doesn't collapse.
-const helperStyles = [
- // When double clicking into an element to edit text, it should not select the word.
- `[${idAttribute}] {
- user-select: none;
- /* Safari */
- -webkit-user-select: none;
- cursor: default;
- }`,
- `
- [${idAttribute}][contenteditable] {
- /* Safari */
- cursor: initial;
- }
- `,
-
- ...helperStylesShared,
-];
+const helperStyles = [...helperStylesUserSelect, ...helperStylesShared];
// Find all editable elements and set cursor text inside
const helperStylesContentEdit = [
- `[${idAttribute}] {
- user-select: none;
- /* Safari */
- -webkit-user-select: none;
- cursor: default;
- }`,
- `
- [${idAttribute}][contenteditable] {
- /* Safari */
- cursor: initial;
- }
- `,
+ ...helperStylesUserSelect,
...helperStylesShared,
];
@@ -187,6 +186,41 @@ const subscribeDesignModeHelperStyles = () => {
};
};
+/**
+ * Compute CSS rules for editable elements in content edit mode.
+ * Groups selectors into chunks to avoid overly long :is() selectors.
+ */
+const computeEditableCursorRules = (
+ editableInstanceSelectors: InstanceSelector[],
+ instances: Map<Instance["id"], Instance>
+) => {
+ const rules: string[] = [];
+ // 20 is arbitrary but keeps selector length reasonable
+ const chunkSize = 20;
+ for (let i = 0; i < editableInstanceSelectors.length; i += chunkSize) {
+ const chunk = editableInstanceSelectors
+ .slice(i, i + chunkSize)
+ .filter((selector) => {
+ const instance = instances.get(selector[0]);
+ if (instance === undefined) {
+ return false;
+ }
+ // Instances with expression children are not directly editable
+ return hasExpressionChildren(instance) === false;
+ });
+ if (chunk.length === 0) {
+ continue;
+ }
+ const selectors = chunk.map(
+ (selector) => `[${idAttribute}="${selector[0]}"]`
+ );
+ rules.push(
+ `:is(${selectors.join(", ")}), :is(${selectors.join(", ")}) a { cursor: text; }`
+ );
+ }
+ return rules;
+};
+
const subscribeContentEditModeHelperStyles = () => {
const renderHelperStyles = () => {
helpersSheet.clear();
@@ -214,35 +248,11 @@ const subscribeContentEditModeHelperStyles = () => {
results: editableInstanceSelectors,
});
- // Group IDs into chunks of 20 since :is() allows for more efficient grouping
- const chunkSize = 20;
- for (let i = 0; i < editableInstanceSelectors.length; i += chunkSize) {
- const chunk = editableInstanceSelectors
- .slice(i, i + chunkSize)
- .filter((selector) => {
- const instance = instances.get(selector[0]);
- if (instance === undefined) {
- return false;
- }
-
- const hasExpressionChildren = instance.children.some(
- (child) => child.type === "expression"
- );
-
- if (hasExpressionChildren) {
- return false;
- }
-
- return true;
- });
-
- const selectors = chunk.map(
- (selector) => `[${idAttribute}="${selector[0]}"]`
- );
-
- helpersSheet.addPlaintextRule(
- `:is(${selectors.join(", ")}), :is(${selectors.join(", ")}) a { cursor: text; }`
- );
+ for (const rule of computeEditableCursorRules(
+ editableInstanceSelectors,
+ instances
+ )) {
+ helpersSheet.addPlaintextRule(rule);
}
}
@@ -281,7 +291,9 @@ const $transformValue = computed($assets, (assets) =>
})
);
-const getEphemeralProperty = (styleDecl: StyleDecl) => {
+const getEphemeralProperty = (
+ styleDecl: Pick<StyleDecl, "styleSourceId" | "state" | "property">
+) => {
const { styleSourceId, state = "", property } = styleDecl;
return `--${styleSourceId}-${state}-${property}`;
};
@@ -292,7 +304,7 @@ const toVarValue = (
styleDecl: StyleDecl,
transformValue: TransformValue,
fallback?: StyleValue
-): undefined | VarValue => {
+): VarValue => {
return {
type: "var",
// var style value is relying on name without leading "--"
@@ -305,40 +317,100 @@ const toVarValue = (
};
};
-const $descendantSelectors = computed(
- [$instances, $props],
- (instances, props) => {
- const parentIdByInstanceId = new Map<Instance["id"], Instance["id"]>();
- const descendantInstanceIds: Instance["id"][] = [];
- for (const instance of instances.values()) {
- if (instance.component === descendantComponent) {
- descendantInstanceIds.push(instance.id);
- }
- for (const child of instance.children) {
- if (child.type === "id") {
- parentIdByInstanceId.set(child.value, instance.id);
- }
- }
+const computeDescendantSelectors = <
+ P extends { instanceId: string; name: string; type: string; value?: unknown },
+>(
+ instances: Map<Instance["id"], Instance>,
+ props: Map<string, P>
+) => {
+ const parentIdByInstanceId = new Map<Instance["id"], Instance["id"]>();
+ const descendantInstanceIds: Instance["id"][] = [];
+ for (const instance of instances.values()) {
+ if (instance.component === descendantComponent) {
+ descendantInstanceIds.push(instance.id);
}
- const descendantSelectorByInstanceId = new Map<Instance["id"], string>();
- for (const prop of props.values()) {
- if (prop.name === "selector" && prop.type === "string") {
- descendantSelectorByInstanceId.set(prop.instanceId, prop.value);
+ for (const child of instance.children) {
+ if (child.type === "id") {
+ parentIdByInstanceId.set(child.value, instance.id);
}
}
- const descendantSelectors = new Map<Instance["id"], string>();
- for (const instanceId of descendantInstanceIds) {
- const parentId = parentIdByInstanceId.get(instanceId);
- const selector = descendantSelectorByInstanceId.get(instanceId);
- if (parentId && selector) {
- descendantSelectors.set(
- instanceId,
- `[${idAttribute}="${parentId}"]${selector}`
- );
- }
+ }
+ const descendantSelectorByInstanceId = new Map<Instance["id"], string>();
+ for (const prop of props.values()) {
+ if (prop.name === "selector" && prop.type === "string") {
+ descendantSelectorByInstanceId.set(prop.instanceId, prop.value as string);
+ }
+ }
+ const descendantSelectors = new Map<Instance["id"], string>();
+ for (const instanceId of descendantInstanceIds) {
+ const parentId = parentIdByInstanceId.get(instanceId);
+ const selector = descendantSelectorByInstanceId.get(instanceId);
+ if (parentId && selector) {
+ descendantSelectors.set(
+ instanceId,
+ `[${idAttribute}="${parentId}"]${selector}`
+ );
}
- return descendantSelectors;
}
+ return descendantSelectors;
+};
+
+/**
+ * Convert StyleDecl to declaration params for sheet operations.
+ */
+const toDeclarationParams = (styleDecl: StyleDecl) => ({
+ breakpoint: styleDecl.breakpointId,
+ selector: styleDecl.state ?? "",
+ property: styleDecl.property,
+});
+
+/**
+ * Compute added and deleted styles by comparing current styles with previous.
+ * Returns new prevStylesSet to track for next diff.
+ */
+const computeStylesDiff = ({
+ styles,
+ transformValue,
+ prevStylesSet,
+ prevTransformValue,
+}: {
+ styles: Map<string, StyleDecl>;
+ transformValue: TransformValue;
+ prevStylesSet: Set<StyleDecl>;
+ prevTransformValue: TransformValue | undefined;
+}) => {
+ // invalidate styles cache when assets are changed
+ let effectivePrevStyles = prevStylesSet;
+ if (prevTransformValue !== transformValue) {
+ effectivePrevStyles = new Set();
+ }
+ const stylesSet = new Set(styles.values());
+ const addedStyles = setDifference(stylesSet, effectivePrevStyles);
+ const deletedStyles = setDifference(effectivePrevStyles, stylesSet);
+ return { addedStyles, deletedStyles, nextPrevStylesSet: stylesSet };
+};
+
+/**
+ * Convert instance ID to CSS selector.
+ * ROOT_INSTANCE_ID maps to ":root", others to attribute selector.
+ */
+const getInstanceSelector = (instanceId: string) =>
+ instanceId === ROOT_INSTANCE_ID
+ ? ":root"
+ : `[${idAttribute}="${instanceId}"]`;
+
+/**
+ * Convert component and tag to preset CSS selector.
+ * rootComponent maps to ":root", others use :where() for low specificity.
+ */
+const getPresetStyleSelector = (component: string, tag: string) =>
+ component === rootComponent
+ ? ":root"
+ : `${tag}:where([data-ws-component="${component}"])`;
+
+const $descendantSelectors = computed(
+ [$instances, $props],
+ computeDescendantSelectors
);
/**
@@ -378,31 +450,26 @@ export const subscribeStyles = () => {
[$styles, $transformValue],
(styles, transformValue) => [styles, transformValue] as const
).subscribe(([styles, transformValue]) => {
- // invalidate styles cache when assets are changed
- if (prevTransformValue !== transformValue) {
- prevTransformValue = transformValue;
- prevStylesSet = new Set();
- }
- const stylesSet = new Set(styles.values());
- const addedStyles = setDifference(stylesSet, prevStylesSet);
- const deletedStyles = setDifference(prevStylesSet, stylesSet);
- prevStylesSet = stylesSet;
- // delete before adding declaraions by the same key
+ const { addedStyles, deletedStyles, nextPrevStylesSet } = computeStylesDiff(
+ {
+ styles,
+ transformValue,
+ prevStylesSet,
+ prevTransformValue,
+ }
+ );
+ prevTransformValue = transformValue;
+ prevStylesSet = nextPrevStylesSet;
+ // delete before adding declarations by the same key
for (const styleDecl of deletedStyles) {
const rule = userSheet.addMixinRule(styleDecl.styleSourceId);
- rule.deleteDeclaration({
- breakpoint: styleDecl.breakpointId,
- selector: styleDecl.state ?? "",
- property: styleDecl.property,
- });
+ rule.deleteDeclaration(toDeclarationParams(styleDecl));
}
for (const styleDecl of addedStyles) {
const rule = userSheet.addMixinRule(styleDecl.styleSourceId);
rule.setDeclaration({
- breakpoint: styleDecl.breakpointId,
- selector: styleDecl.state ?? "",
- property: styleDecl.property,
- value: toVarValue(styleDecl, transformValue) ?? styleDecl.value,
+ ...toDeclarationParams(styleDecl),
+ value: toVarValue(styleDecl, transformValue),
});
}
renderUserSheetInTheNextFrame();
@@ -416,11 +483,7 @@ export const subscribeStyles = () => {
const addedSelections = setDifference(selectionsSet, prevSelectionsSet);
prevSelectionsSet = selectionsSet;
for (const { instanceId, values } of addedSelections) {
- const selector =
- instanceId === ROOT_INSTANCE_ID
- ? ":root"
- : `[${idAttribute}="${instanceId}"]`;
- const rule = userSheet.addNestingRule(selector);
+ const rule = userSheet.addNestingRule(getInstanceSelector(instanceId));
rule.applyMixins(values);
}
renderUserSheetInTheNextFrame();
@@ -500,11 +563,9 @@ export const GlobalStyles = () => {
presetSheet.addMediaRule("presets");
for (const [component, meta] of metas) {
for (const [tag, styles] of Object.entries(meta.presetStyle ?? {})) {
- const selector =
- component === rootComponent
- ? ":root"
- : `${tag}:where([data-ws-component="${component}"])`;
- const rule = presetSheet.addNestingRule(selector);
+ const rule = presetSheet.addNestingRule(
+ getPresetStyleSelector(component, tag)
+ );
for (const declaration of styles) {
rule.setDeclaration({
breakpoint: "presets",
@@ -521,6 +582,42 @@ export const GlobalStyles = () => {
return null;
};
+const computeInstanceStyles = ({
+ selectedInstance,
+ selectedStyleState,
+ breakpoints,
+ styleSourceSelections,
+ styles,
+}: {
+ selectedInstance: Instance | undefined;
+ selectedStyleState: string | undefined;
+ breakpoints: Map<string, Breakpoint>;
+ styleSourceSelections: Map<string, { values: string[] }>;
+ styles: Map<string, StyleDecl>;
+}) => {
+ if (selectedInstance === undefined || selectedStyleState === undefined) {
+ return;
+ }
+ const styleSources = new Set(
+ styleSourceSelections.get(selectedInstance.id)?.values
+ );
+ const instanceStyles: StyleDecl[] = [];
+ for (const styleDecl of styles.values()) {
+ if (
+ styleDecl.state === selectedStyleState &&
+ styleSources.has(styleDecl.styleSourceId)
+ ) {
+ instanceStyles.push(styleDecl);
+ }
+ }
+ return {
+ instanceId: selectedInstance.id,
+ selectedState: selectedStyleState,
+ breakpoints: Array.from(breakpoints.values()),
+ styles: instanceStyles,
+ };
+};
+
const $instanceStyles = computed(
[
$selectedInstance,
@@ -535,60 +632,75 @@ const $instanceStyles = computed(
breakpoints,
styleSourceSelections,
styles
- ) => {
- if (selectedInstance === undefined || selectedStyleState === undefined) {
- return;
- }
- const styleSources = new Set(
- styleSourceSelections.get(selectedInstance.id)?.values
- );
- const instanceStyles: StyleDecl[] = [];
- for (const styleDecl of styles.values()) {
- if (
- styleDecl.state === selectedStyleState &&
- styleSources.has(styleDecl.styleSourceId)
- ) {
- instanceStyles.push(styleDecl);
- }
- }
- return {
- instanceId: selectedInstance.id,
- breakpoints: Array.from(breakpoints.values()),
- styles: instanceStyles,
- };
- }
+ ) =>
+ computeInstanceStyles({
+ selectedInstance,
+ selectedStyleState,
+ breakpoints,
+ styleSourceSelections,
+ styles,
+ })
);
+/**
+ * Render state styles to a stylesheet.
+ *
+ * For pseudo-classes like :hover, render without state so users can preview
+ * the styles without triggering the state.
+ * For pseudo-elements like ::before, keep the selector so styles apply
+ * to the pseudo-element, not the parent.
+ */
+const renderStateStyles = ({
+ instanceStyles,
+ sheet,
+ transformValue,
+ toStyleValue,
+}: {
+ instanceStyles: ReturnType<typeof $instanceStyles.get>;
+ sheet: StyleSheetRegular;
+ transformValue: TransformValue;
+ toStyleValue: (
+ styleDecl: StyleDecl,
+ transformValue: TransformValue
+ ) => StyleValue;
+}) => {
+ sheet.clear();
+ if (instanceStyles === undefined) {
+ sheet.render();
+ return;
+ }
+ const { instanceId, selectedState, breakpoints, styles } = instanceStyles;
+ for (const breakpoint of breakpoints) {
+ sheet.addMediaRule(breakpoint.id, breakpoint);
+ }
+ const selector = `[${idAttribute}="${instanceId}"]`;
+ const rule = sheet.addNestingRule(selector);
+ const stateSelector = isPseudoElement(selectedState) ? selectedState : "";
+ for (const styleDecl of styles) {
+ rule.setDeclaration({
+ breakpoint: styleDecl.breakpointId,
+ selector: stateSelector,
+ property: styleDecl.property,
+ value: toStyleValue(styleDecl, transformValue),
+ });
+ }
+ sheet.setTransformer(transformValue);
+ sheet.render();
+};
+
/**
* render currently selected state styles as stateless
* in separate sheet and clear when state is not selected
*/
const subscribeStateStyles = () => {
return $instanceStyles.subscribe((instanceStyles) => {
- if (instanceStyles === undefined) {
- stateSheet.clear();
- stateSheet.render();
- return;
- }
- // reset state sheet on every update to avoid stale styles
- stateSheet.clear();
- const { instanceId, breakpoints, styles } = instanceStyles;
- for (const breakpoint of breakpoints.values()) {
- stateSheet.addMediaRule(breakpoint.id, breakpoint);
- }
- const selector = `[${idAttribute}="${instanceId}"]`;
- const rule = stateSheet.addNestingRule(selector);
- for (const styleDecl of styles) {
- rule.setDeclaration({
- breakpoint: styleDecl.breakpointId,
- // render without state
- selector: "",
- property: styleDecl.property,
- value: toVarValue(styleDecl, $transformValue.get()) ?? styleDecl.value,
- });
- }
- stateSheet.setTransformer($transformValue.get());
- stateSheet.render();
+ renderStateStyles({
+ instanceStyles,
+ sheet: stateSheet,
+ transformValue: $transformValue.get(),
+ toStyleValue: (styleDecl, transformValue) =>
+ toVarValue(styleDecl, transformValue),
+ });
});
};
@@ -631,7 +743,7 @@ const subscribeEphemeralStyle = () => {
// add ephemeral styles
if (ephemeralStyles.length > 0) {
canvasApi.setInert();
- const selector = `[${idAttribute}="${instance.id}"]`;
+ const selector = getInstanceSelector(instance.id);
const rule = userSheet.addNestingRule(selector);
let ephemeralSheetUpdated = false;
for (const styleDecl of ephemeralStyles) {
@@ -658,34 +770,37 @@ const subscribeEphemeralStyle = () => {
const mixinRule = userSheet.addMixinRule(styleDecl.styleSourceId);
- // Use the actual style value as a fallback (non-ephemeral); see the “Lazy” comment above.
+ // Use the actual style value as a fallback (non-ephemeral); see the "Lazy" comment above.
const computedStyleDecl = createComputedStyleDeclStore(
hyphenateProperty(styleDecl.property)
).get();
- const value =
- toVarValue(
- styleDecl,
- $transformValue.get(),
- computedStyleDecl.cascadedValue
- ) ?? computedStyleDecl.cascadedValue;
+ const value = toVarValue(
+ styleDecl,
+ $transformValue.get(),
+ computedStyleDecl.cascadedValue
+ );
mixinRule.setDeclaration({
- breakpoint: styleDecl.breakpointId,
- selector: styleDecl.state ?? "",
- property: styleDecl.property,
+ ...toDeclarationParams(styleDecl),
value,
});
rule.addMixin(styleDecl.styleSourceId);
- // temporary render var() in state sheet as well
+ // When editing state styles (e.g., :hover), also render var() in stateSheet
+ // so ephemeral updates are visible in the state preview
if (styleDecl.state !== undefined) {
const stateRule = stateSheet.addNestingRule(selector);
+ // For pseudo-elements (::before, ::after), keep the selector so styles
+ // apply to the pseudo-element. For pseudo-classes (:hover, :focus),
+ // render without state so users can preview without triggering the state.
+ const stateSelector = isPseudoElement(styleDecl.state)
+ ? styleDecl.state
+ : "";
stateRule.setDeclaration({
breakpoint: styleDecl.breakpointId,
- // render without state
- selector: "",
+ selector: stateSelector,
property: styleDecl.property,
value,
});
@@ -701,3 +816,15 @@ const subscribeEphemeralStyle = () => {
}
});
};
+
+export const __testing__ = {
+ getEphemeralProperty,
+ getInstanceSelector,
+ getPresetStyleSelector,
+ computeDescendantSelectors,
+ computeInstanceStyles,
+ computeEditableCursorRules,
+ computeStylesDiff,
+ toDeclarationParams,
+ renderStateStyles,
+};
diff --git a/apps/builder/app/dashboard/dashboard.tsx b/apps/builder/app/dashboard/dashboard.tsx
index 93ede7ac1d..60917e7e42 100644
--- a/apps/builder/app/dashboard/dashboard.tsx
+++ b/apps/builder/app/dashboard/dashboard.tsx
@@ -114,7 +114,7 @@ const NavigationItems = ({
className={sidebarLinkStyle()}
>
{item.prefix}
- <Text variant="labelsSentenceCase" color="main">
+ <Text variant="labels" color="main">
{item.children}
</Text>
</NavLink>
diff --git a/apps/builder/app/dashboard/projects/project-dialogs.tsx b/apps/builder/app/dashboard/projects/project-dialogs.tsx
index f39a1773d6..cf76a54d95 100644
--- a/apps/builder/app/dashboard/projects/project-dialogs.tsx
+++ b/apps/builder/app/dashboard/projects/project-dialogs.tsx
@@ -349,7 +349,7 @@ export const DeleteProjectDialog = ({
<Text
as="span"
color="destructive"
- variant="labelsSentenceCase"
+ variant="labels"
css={{ userSelect: "text" }}
>
{` ${title} `}
diff --git a/apps/builder/app/shared/code-editor-base.tsx b/apps/builder/app/shared/code-editor-base.tsx
index dc730fe33f..22c01bdd27 100644
--- a/apps/builder/app/shared/code-editor-base.tsx
+++ b/apps/builder/app/shared/code-editor-base.tsx
@@ -166,7 +166,7 @@ const autocompletionTooltipTheme = EditorView.theme({
padding: rawTheme.spacing[3],
},
".cm-tooltip.cm-tooltip-autocomplete ul li": {
- ...textVariants.labelsTitleCase,
+ ...textVariants.labels,
textTransform: "none",
position: "relative",
display: "flex",
diff --git a/apps/builder/app/shared/project-settings/project-settings.tsx b/apps/builder/app/shared/project-settings/project-settings.tsx
index b9c87d844e..888606295a 100644
--- a/apps/builder/app/shared/project-settings/project-settings.tsx
+++ b/apps/builder/app/shared/project-settings/project-settings.tsx
@@ -107,7 +107,7 @@ export const ProjectSettingsDialog = ({
}}
align="center"
>
- <Text variant="labelsTitleCase" truncate>
+ <Text variant="labels" truncate>
{name}
</Text>
</Flex>
diff --git a/apps/builder/app/shared/project-settings/section-general.tsx b/apps/builder/app/shared/project-settings/section-general.tsx
index 332e9551ac..80a9dc9158 100644
--- a/apps/builder/app/shared/project-settings/section-general.tsx
+++ b/apps/builder/app/shared/project-settings/section-general.tsx
@@ -130,7 +130,7 @@ export const SectionGeneral = ({ projectId }: { projectId?: string }) => {
<Grid gap={1} css={sectionSpacing}>
<Flex gap={1} align="center">
- <Text variant="labelsSentenceCase">Project ID:</Text>
+ <Text variant="labels">Project ID:</Text>
<Text userSelect="text">{effectiveProjectId}</Text>
<CopyToClipboard text={effectiveProjectId} copyText="Copy ID">
<IconButton aria-label="Copy ID">
diff --git a/apps/builder/app/shared/style-object-model.test.tsx b/apps/builder/app/shared/style-object-model.test.tsx
index 3702d14075..0603f74000 100644
--- a/apps/builder/app/shared/style-object-model.test.tsx
+++ b/apps/builder/app/shared/style-object-model.test.tsx
@@ -1729,3 +1729,439 @@ describe("style value source", () => {
});
});
});
+
+describe("pseudo-element inheritance", () => {
+ test("pseudo-elements do not cascade non-inherited properties", () => {
+ const model = createModel({
+ css: `
+ boxLocal {
+ width: 100px;
+ height: 50px;
+ display: flex;
+ }
+ boxLocal::before {
+ content: "test";
+ }
+ `,
+ jsx: <$.Box ws:id="box" class="boxLocal"></$.Box>,
+ });
+ const instanceSelector = ["box"];
+
+ // Non-inherited properties should NOT cascade to pseudo-element
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "width",
+ }).usedValue
+ ).toEqual({ type: "keyword", value: "auto" });
+
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "height",
+ }).usedValue
+ ).toEqual({ type: "keyword", value: "auto" });
+
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "display",
+ }).usedValue
+ ).toEqual({ type: "keyword", value: "inline" });
+
+ // Directly set property on pseudo-element should work
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "content",
+ }).usedValue
+ ).toEqual({ type: "unparsed", value: '"test"' });
+ });
+
+ test("pseudo-elements inherit inherited properties", () => {
+ const model = createModel({
+ css: `
+ boxLocal {
+ color: red;
+ font-size: 16px;
+ font-family: Arial;
+ }
+ boxLocal::before {
+ content: "test";
+ }
+ `,
+ jsx: <$.Box ws:id="box" class="boxLocal"></$.Box>,
+ });
+ const instanceSelector = ["box"];
+
+ // Inherited properties should be inherited by pseudo-element
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "color",
+ }).usedValue
+ ).toEqual({ type: "keyword", value: "red" });
+
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "font-size",
+ }).usedValue
+ ).toEqual({ type: "unit", unit: "px", value: 16 });
+
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "font-family",
+ }).usedValue
+ ).toEqual({ type: "fontFamily", value: ["Arial"] });
+ });
+
+ test("pseudo-elements can override inherited properties", () => {
+ const model = createModel({
+ css: `
+ boxLocal {
+ color: red;
+ font-size: 16px;
+ }
+ boxLocal::before {
+ color: blue;
+ font-size: 20px;
+ }
+ `,
+ jsx: <$.Box ws:id="box" class="boxLocal"></$.Box>,
+ });
+ const instanceSelector = ["box"];
+
+ // Pseudo-element can override inherited properties
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "color",
+ }).usedValue
+ ).toEqual({ type: "keyword", value: "blue" });
+
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "font-size",
+ }).usedValue
+ ).toEqual({ type: "unit", unit: "px", value: 20 });
+ });
+
+ test("pseudo-elements support inherit keyword", () => {
+ const model = createModel({
+ css: `
+ boxLocal {
+ width: 100px;
+ color: red;
+ }
+ boxLocal::before {
+ width: inherit;
+ color: inherit;
+ }
+ `,
+ jsx: <$.Box ws:id="box" class="boxLocal"></$.Box>,
+ });
+ const instanceSelector = ["box"];
+
+ // Explicit inherit should work for non-inherited properties
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "width",
+ }).usedValue
+ ).toEqual({ type: "unit", unit: "px", value: 100 });
+
+ // Explicit inherit should work for inherited properties
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "color",
+ }).usedValue
+ ).toEqual({ type: "keyword", value: "red" });
+ });
+
+ test("pseudo-elements support initial keyword", () => {
+ const model = createModel({
+ css: `
+ boxLocal {
+ color: red;
+ }
+ boxLocal::before {
+ color: initial;
+ }
+ `,
+ jsx: <$.Box ws:id="box" class="boxLocal"></$.Box>,
+ });
+ const instanceSelector = ["box"];
+
+ // Initial keyword should reset to initial value
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "color",
+ }).usedValue
+ ).toEqual({ type: "keyword", value: "black" });
+ });
+
+ test("pseudo-elements support unset keyword", () => {
+ const model = createModel({
+ css: `
+ boxLocal {
+ color: red;
+ width: 100px;
+ }
+ boxLocal::before {
+ color: unset;
+ width: unset;
+ }
+ `,
+ jsx: <$.Box ws:id="box" class="boxLocal"></$.Box>,
+ });
+ const instanceSelector = ["box"];
+
+ // Unset on inherited property should inherit
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "color",
+ }).usedValue
+ ).toEqual({ type: "keyword", value: "red" });
+
+ // Unset on non-inherited property should use initial value
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "width",
+ }).usedValue
+ ).toEqual({ type: "keyword", value: "auto" });
+ });
+
+ test("multiple pseudo-elements on same instance", () => {
+ const model = createModel({
+ css: `
+ boxLocal {
+ color: red;
+ width: 100px;
+ }
+ boxLocal::before {
+ content: "before";
+ color: blue;
+ }
+ boxLocal::after {
+ content: "after";
+ color: green;
+ }
+ `,
+ jsx: <$.Box ws:id="box" class="boxLocal"></$.Box>,
+ });
+ const instanceSelector = ["box"];
+
+ // ::before should have its own color
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "color",
+ }).usedValue
+ ).toEqual({ type: "keyword", value: "blue" });
+
+ // ::before should not cascade width
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "width",
+ }).usedValue
+ ).toEqual({ type: "keyword", value: "auto" });
+
+ // ::after should have its own color
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::after",
+ property: "color",
+ }).usedValue
+ ).toEqual({ type: "keyword", value: "green" });
+
+ // ::after should not cascade width
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::after",
+ property: "width",
+ }).usedValue
+ ).toEqual({ type: "keyword", value: "auto" });
+ });
+
+ test("pseudo-elements with custom properties", () => {
+ const model = createModel({
+ css: `
+ boxLocal {
+ --my-color: red;
+ --my-size: 100px;
+ color: var(--my-color);
+ }
+ boxLocal::before {
+ color: var(--my-color);
+ width: var(--my-size);
+ }
+ `,
+ jsx: <$.Box ws:id="box" class="boxLocal"></$.Box>,
+ });
+ const instanceSelector = ["box"];
+
+ // Custom properties are always inherited
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "--my-color",
+ }).computedValue
+ ).toEqual({ type: "unparsed", value: "red" });
+
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "--my-size",
+ }).computedValue
+ ).toEqual({ type: "unit", unit: "px", value: 100 });
+
+ // Pseudo-element should be able to use inherited custom properties
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "color",
+ }).usedValue
+ ).toEqual({ type: "unparsed", value: "red" });
+
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::before",
+ property: "width",
+ }).usedValue
+ ).toEqual({ type: "unit", unit: "px", value: 100 });
+ });
+
+ test("pseudo-classes still cascade properties (not pseudo-elements)", () => {
+ const model = createModel({
+ css: `
+ boxLocal {
+ width: 100px;
+ color: red;
+ }
+ boxLocal:hover {
+ color: blue;
+ }
+ `,
+ jsx: <$.Box ws:id="box" class="boxLocal"></$.Box>,
+ matchingStates: new Set([":hover"]),
+ });
+ const instanceSelector = ["box"];
+
+ // Pseudo-classes should still cascade properties (original behavior)
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: ":hover",
+ property: "width",
+ }).usedValue
+ ).toEqual({ type: "unit", unit: "px", value: 100 });
+
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: ":hover",
+ property: "color",
+ }).usedValue
+ ).toEqual({ type: "keyword", value: "blue" });
+ });
+
+ test("pseudo-element ::placeholder", () => {
+ const model = createModel({
+ css: `
+ inputLocal {
+ color: black;
+ font-size: 16px;
+ width: 200px;
+ }
+ inputLocal::placeholder {
+ color: gray;
+ }
+ `,
+ jsx: <$.Input ws:id="input" ws:tag="input" class="inputLocal"></$.Input>,
+ });
+ const instanceSelector = ["input"];
+
+ // ::placeholder should inherit font-size but not width
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::placeholder",
+ property: "font-size",
+ }).usedValue
+ ).toEqual({ type: "unit", unit: "px", value: 16 });
+
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::placeholder",
+ property: "width",
+ }).usedValue
+ ).toEqual({ type: "keyword", value: "auto" });
+
+ // ::placeholder should have its own color
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: "::placeholder",
+ property: "color",
+ }).usedValue
+ ).toEqual({ type: "keyword", value: "gray" });
+ });
+});
diff --git a/apps/builder/app/shared/style-object-model.ts b/apps/builder/app/shared/style-object-model.ts
index c27f3c5776..a546606db3 100644
--- a/apps/builder/app/shared/style-object-model.ts
+++ b/apps/builder/app/shared/style-object-model.ts
@@ -6,6 +6,7 @@ import {
html,
parseCssVar,
propertiesData,
+ isPseudoElement,
} from "@webstudio-is/css-data";
import {
type StyleValue,
@@ -127,12 +128,14 @@ const getCascadedValue = ({
styleSourceId: selectedStyleSourceId,
state: selectedState,
property,
+ forPseudoElement = false,
}: {
model: StyleObjectModel;
instanceId: Instance["id"];
styleSourceId?: StyleDecl["styleSourceId"];
state?: StyleDecl["state"];
property: CssProperty;
+ forPseudoElement?: boolean;
}) => {
const {
styles,
@@ -152,8 +155,8 @@ const getCascadedValue = ({
// https://drafts.csswg.org/css-cascade-5/#declared
const declaredValues: StyleValue[] = [];
- // browser styles
- if (tag) {
+ // browser styles - pseudo-elements don't inherit browser styles from parent
+ if (tag && !forPseudoElement) {
const key = `${tag}:${property}`;
const browserValue = html.get(key);
if (browserValue) {
@@ -162,15 +165,25 @@ const getCascadedValue = ({
}
const states = new Set<undefined | string>();
- // allow stateless to be overwritten
- states.add(undefined);
- for (const state of matchingStates) {
- states.add(state);
- }
- // move selected state in the end if already present in matching states
- if (selectedState) {
- states.delete(selectedState);
- states.add(selectedState);
+
+ // When computing for a pseudo-element, only include the pseudo-element state itself
+ // This prevents cascading of properties from the parent element
+ if (forPseudoElement) {
+ if (selectedState) {
+ states.add(selectedState);
+ }
+ } else {
+ // Original behavior for non-pseudo-elements
+ // allow stateless to be overwritten
+ states.add(undefined);
+ for (const state of matchingStates) {
+ states.add(state);
+ }
+ // move selected state in the end if already present in matching states
+ if (selectedState) {
+ states.delete(selectedState);
+ states.add(selectedState);
+ }
}
// preset component styles
@@ -367,6 +380,150 @@ export const getComputedStyleDecl = ({
let cascadedValue: undefined | StyleValue;
let source: StyleValueSource = { name: "default" };
+ // Check if we're computing for a pseudo-element
+ const computingForPseudoElement = state ? isPseudoElement(state) : false;
+
+ // If computing for a pseudo-element, treat it as a virtual child instance
+ // First compute the parent's value (without the pseudo-element state)
+ // Then compute the pseudo-element's value with inheritance from parent
+ if (computingForPseudoElement && instanceSelector.length > 0) {
+ // Step 1: Compute parent's value without the pseudo-element state
+ // Use a separate graph for parent lookup to avoid false cycle detection
+ // (parent using var(--x) doesn't mean pseudo-element can't also use var(--x))
+ const parentDecl = getComputedStyleDecl({
+ model,
+ instanceSelector,
+ styleSourceId,
+ state: undefined, // No state for parent
+ property,
+ customPropertiesGraph: new Map(),
+ });
+
+ // Step 2: Use parent's computed value as the inherited value for the pseudo-element
+ const inheritedValue: StyleValue = parentDecl.computedValue;
+ const inheritedSource: StyleValueSource =
+ parentDecl.source.name === "local"
+ ? { ...parentDecl.source, name: "remote" }
+ : parentDecl.source;
+
+ // Step 3: Get cascaded value for the pseudo-element itself
+ const targetInstanceId = instanceSelector[0];
+ const cascaded = getCascadedValue({
+ model,
+ instanceId: targetInstanceId,
+ styleSourceId,
+ state,
+ property,
+ forPseudoElement: true, // Flag to only collect pseudo-element styles
+ });
+
+ cascadedValue = cascaded?.value;
+ source = cascaded?.source ?? { name: "default" };
+
+ // Step 4: Resolve specified value with inheritance from parent
+ let specifiedValue: StyleValue = initialValue;
+
+ // explicit defaulting
+ // https://drafts.csswg.org/css-cascade-5/#defaulting-keywords
+ if (matchKeyword(cascadedValue, "initial")) {
+ specifiedValue = initialValue;
+ } else if (
+ matchKeyword(cascadedValue, "inherit") ||
+ // treat currentcolor as inherit when used on color property
+ // https://www.w3.org/TR/css-color-3/#currentColor-def
+ (property === "color" && matchKeyword(cascadedValue, "currentcolor"))
+ ) {
+ specifiedValue = inheritedValue;
+ } else if (matchKeyword(cascadedValue, "unset")) {
+ if (inherited) {
+ specifiedValue = inheritedValue;
+ } else {
+ specifiedValue = initialValue;
+ }
+ } else if (cascadedValue) {
+ specifiedValue = cascadedValue;
+ }
+ // defaulting https://drafts.csswg.org/css-cascade-5/#defaulting
+ else if (inherited) {
+ specifiedValue = inheritedValue;
+ cascadedValue = parentDecl.cascadedValue;
+ source = inheritedSource;
+ } else {
+ specifiedValue = initialValue;
+ }
+
+ // https://drafts.csswg.org/css-cascade-5/#computed
+ computedValue = specifiedValue;
+
+ // Handle custom properties and var() substitution
+ let usedCustomProperties = customPropertiesGraph.get(targetInstanceId);
+ if (usedCustomProperties === undefined) {
+ usedCustomProperties = new Set();
+ customPropertiesGraph.set(targetInstanceId, usedCustomProperties);
+ }
+
+ let invalid = false;
+ const parentUsedCustomProperties = usedCustomProperties;
+ usedCustomProperties = new Set<CssProperty>(usedCustomProperties);
+ customPropertiesGraph.set(targetInstanceId, usedCustomProperties);
+
+ computedValue = substituteVars(computedValue, (varValue) => {
+ const customProperty = `--${varValue.value}` as const;
+ // https://www.w3.org/TR/css-variables-1/#cycles
+ if (parentUsedCustomProperties.has(customProperty)) {
+ invalid = true;
+ return varValue;
+ }
+ usedCustomProperties.add(customProperty);
+
+ const fallback: undefined | VarFallback = varValue.fallback;
+ // Custom properties are always inherited, so look them up from parent (without state)
+ const customPropertyValue = getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state: undefined, // Don't pass pseudo-element state for custom property lookup
+ property: customProperty,
+ customPropertiesGraph,
+ });
+ let replacement = customPropertyValue.computedValue;
+ // https://www.w3.org/TR/css-variables-1/#invalid-variables
+ if (
+ replacement.type === "guaranteedInvalid" ||
+ (isCustomProperty === false && replacement.type === "invalid")
+ ) {
+ if (inherited) {
+ replacement = fallback ?? inheritedValue;
+ } else {
+ replacement = fallback ?? initialValue;
+ }
+ }
+ return replacement;
+ });
+
+ if (invalid) {
+ computedValue = invalidValue;
+ }
+
+ // https://drafts.csswg.org/css-cascade-5/#used
+ let usedValue: StyleValue = computedValue;
+ // https://drafts.csswg.org/css-color-4/#resolving-other-colors
+ if (matchKeyword(computedValue, "currentcolor")) {
+ const currentColor = getComputedStyleDecl({
+ model,
+ instanceSelector,
+ state, // Keep the pseudo-element state for currentcolor resolution
+ property: "color",
+ });
+ usedValue = currentColor.usedValue;
+ }
+
+ // fallback to initial value
+ cascadedValue ??= initialValue;
+
+ return { property, source, cascadedValue, computedValue, usedValue };
+ }
+
+ // Original behavior for non-pseudo-elements
// start computing from the root
for (let index = instanceSelector.length - 1; index >= 0; index -= 1) {
const instanceId = instanceSelector[index];
diff --git a/apps/builder/app/shared/token-conflict-dialog.tsx b/apps/builder/app/shared/token-conflict-dialog.tsx
index e10f6110fd..9b818f1115 100644
--- a/apps/builder/app/shared/token-conflict-dialog.tsx
+++ b/apps/builder/app/shared/token-conflict-dialog.tsx
@@ -139,7 +139,7 @@ export const TokenConflictDialog = () => {
>
<Radio value="theirs" />
<Flex direction="column" gap="1">
- <Text variant="labelsTitleCase">Theirs</Text>
+ <Text variant="labels">Theirs</Text>
<Text color="subtle">
Keep incoming tokens with a suffix added to their names
(e.g., "primary-color-1")
@@ -162,7 +162,7 @@ export const TokenConflictDialog = () => {
>
<Radio value="ours" />
<Flex direction="column" gap="1">
- <Text variant="labelsTitleCase">Ours</Text>
+ <Text variant="labels">Ours</Text>
<Text color="subtle">
Discard incoming tokens and use your existing project
tokens instead
@@ -185,7 +185,7 @@ export const TokenConflictDialog = () => {
>
<Radio value="merge" />
<Flex direction="column" gap="1">
- <Text variant="labelsTitleCase">Merge</Text>
+ <Text variant="labels">Merge</Text>
<Text color="subtle">
Combine both into your existing token (incoming styles
override existing ones)
diff --git a/packages/css-data/bin/mdn-data.ts b/packages/css-data/bin/mdn-data.ts
index d6604a46c4..e35a005a72 100755
--- a/packages/css-data/bin/mdn-data.ts
+++ b/packages/css-data/bin/mdn-data.ts
@@ -371,6 +371,12 @@ const pseudoElements = Object.keys(selectors)
})
.map((selector) => selector.slice(2));
+const pseudoClasses = Object.keys(selectors)
+ .filter((selector) => {
+ return selector.startsWith(":") && !selector.startsWith("::");
+ })
+ .map((selector) => selector.slice(1));
+
const getKeywordValues = (filteredProperties: FilteredProperties) => {
const result = { ...customData.keywordValues };
// https://www.w3.org/TR/css-values/#common-keywords
@@ -480,6 +486,7 @@ writeToFile(
Object.keys(filteredData.animatableLonghands)
);
writeToFile("pseudo-elements.ts", "pseudoElements", pseudoElements);
+writeToFile("pseudo-classes.ts", "pseudoClasses", pseudoClasses);
const typesFile = join(
process.cwd(),
diff --git a/packages/css-data/bin/prompts/pseudo-selectors.prompt.md b/packages/css-data/bin/prompts/pseudo-selectors.prompt.md
new file mode 100644
index 0000000000..544572f0ec
--- /dev/null
+++ b/packages/css-data/bin/prompts/pseudo-selectors.prompt.md
@@ -0,0 +1,24 @@
+```prompt
+I created a no-code app for building websites. People who don't know HTML and CSS can use it to create sites easily. My app has a styles panel where users can apply styles to pseudo-classes and pseudo-elements. When the user hovers over a pseudo-class or pseudo-element name, we show a tooltip with information about what it does.
+
+The fundamental purpose of tooltip information is to teach users how to use a part of the UI to accomplish their intentions, therefore explanations should be descriptive and educative. Here is an example of a good explanation and a bad one:
+
+- Good for :hover: "Matches when the user's pointer is over the element, like when moving a mouse cursor over a button."
+- Bad for :hover: "Applies styles when hovering". That's frustratingly useless because it just repeats the name without adding any teaching information.
+
+I will now give you a list of CSS pseudo-classes and pseudo-elements and I want you to generate a matching list of explanations that are no longer than 200 characters and teach the user what the selector is about!
+
+Here is the list of CSS pseudo selectors:
+
+```
+
+{selectors}
+
+````
+
+Respond with a matching list of explanations as a markdown code block.
+Very important: don't repeat the selector name at the beginning of the explanation!
+
+The response should start with ```markdown
+
+````
diff --git a/packages/css-data/src/__generated__/pseudo-classes.ts b/packages/css-data/src/__generated__/pseudo-classes.ts
new file mode 100644
index 0000000000..7404ab0bfd
--- /dev/null
+++ b/packages/css-data/src/__generated__/pseudo-classes.ts
@@ -0,0 +1,79 @@
+// This file was generated by pnpm mdn-data
+export const pseudoClasses = [
+ "active",
+ "active-view-transition",
+ "active-view-transition-type()",
+ "any-link",
+ "autofill",
+ "blank",
+ "buffering",
+ "checked",
+ "current",
+ "default",
+ "defined",
+ "dir()",
+ "disabled",
+ "empty",
+ "enabled",
+ "first",
+ "first-child",
+ "first-of-type",
+ "focus",
+ "focus-visible",
+ "focus-within",
+ "fullscreen",
+ "future",
+ "has()",
+ "has-slotted",
+ "host",
+ "host()",
+ "host-context()",
+ "hover",
+ "in-range",
+ "indeterminate",
+ "invalid",
+ "is()",
+ "lang()",
+ "last-child",
+ "last-of-type",
+ "left",
+ "link",
+ "local-link",
+ "modal",
+ "muted",
+ "not()",
+ "nth-child()",
+ "nth-last-child()",
+ "nth-last-of-type()",
+ "nth-of-type()",
+ "only-child",
+ "only-of-type",
+ "open",
+ "optional",
+ "out-of-range",
+ "past",
+ "paused",
+ "picture-in-picture",
+ "placeholder-shown",
+ "playing",
+ "popover-open",
+ "read-only",
+ "read-write",
+ "required",
+ "right",
+ "root",
+ "scope",
+ "seeking",
+ "stalled",
+ "state()",
+ "target",
+ "target-current",
+ "target-within",
+ "user-invalid",
+ "user-valid",
+ "valid",
+ "visited",
+ "volume-locked",
+ "where()",
+ "xr-overlay",
+] as const;
diff --git a/packages/css-data/src/__generated__/pseudo-selector-descriptions.ts b/packages/css-data/src/__generated__/pseudo-selector-descriptions.ts
new file mode 100644
index 0000000000..6cf0320603
--- /dev/null
+++ b/packages/css-data/src/__generated__/pseudo-selector-descriptions.ts
@@ -0,0 +1,153 @@
+// This file was auto-generated
+// Descriptions for CSS pseudo-classes
+export const pseudoClassDescriptions: Record<string, string> = {
+ ":active":
+ "Matches when the element is being activated, like when a button is being pressed.",
+ ":any-link": "Matches links that are either visited or unvisited.",
+ ":autofill":
+ "Matches form elements that have been auto-filled by the browser.",
+ ":checked":
+ "Matches checkboxes, radio buttons, or options that are currently selected or toggled on.",
+ ":default":
+ "Matches the default form element in a group, like a submit button.",
+ ":defined":
+ "Matches any element that has been defined, including custom elements.",
+ ":disabled":
+ "Matches form elements that are currently disabled and cannot be interacted with.",
+ ":empty": "Matches elements that have no children, including text nodes.",
+ ":enabled":
+ "Matches form elements that are currently enabled and can be interacted with.",
+ ":first-child": "Matches an element that is the first child of its parent.",
+ ":first-of-type": "Matches the first element of its type among siblings.",
+ ":focus":
+ "Matches when the element has received focus, like when clicked or tabbed to.",
+ ":focus-visible":
+ "Matches when the element has focus and the browser determines focus should be visible.",
+ ":focus-within":
+ "Matches when the element or any of its descendants has focus.",
+ ":fullscreen":
+ "Matches when the element is currently displayed in fullscreen mode.",
+ ":has()":
+ "Matches elements that contain elements matching the specified selector.",
+ ":hover":
+ "Matches when the user's pointer is over the element, like when moving a mouse cursor over it.",
+ ":in-range": "Matches input elements with values within the specified range.",
+ ":indeterminate":
+ "Matches form elements in an indeterminate state, like partially-checked checkboxes.",
+ ":invalid":
+ "Matches form elements with invalid content according to their validation rules.",
+ ":is()":
+ "Matches elements that match any of the selectors in the list. Useful for grouping.",
+ ":lang()":
+ "Matches elements based on the language they are determined to be in.",
+ ":last-child": "Matches an element that is the last child of its parent.",
+ ":last-of-type": "Matches the last element of its type among siblings.",
+ ":link": "Matches links that have not yet been visited.",
+ ":modal":
+ "Matches an element that is in a modal state, blocking interaction with others.",
+ ":not()": "Matches elements that do not match the specified selector.",
+ ":nth-child()":
+ "Matches elements based on their position among siblings using a formula.",
+ ":nth-last-child()":
+ "Matches elements based on position from the end among siblings.",
+ ":nth-last-of-type()":
+ "Matches elements of the same type by position from the end.",
+ ":nth-of-type()":
+ "Matches elements of the same type based on position among siblings.",
+ ":only-child": "Matches an element that is the only child of its parent.",
+ ":only-of-type":
+ "Matches an element that is the only one of its type among siblings.",
+ ":open":
+ "Matches elements like details or dialog when they are in an open state.",
+ ":optional": "Matches form elements that are not required.",
+ ":out-of-range":
+ "Matches input elements with values outside the specified range.",
+ ":placeholder-shown":
+ "Matches input elements currently showing placeholder text.",
+ ":read-only": "Matches elements that are not editable by the user.",
+ ":read-write": "Matches elements that are editable by the user.",
+ ":required":
+ "Matches form elements that must be filled out before submitting.",
+ ":root":
+ "Matches the root element of the document, typically the <html> element.",
+ ":target":
+ "Matches an element whose ID matches the URL's fragment identifier.",
+ ":user-invalid":
+ "Matches form elements with invalid input after user interaction.",
+ ":user-valid":
+ "Matches form elements with valid input after user interaction.",
+ ":valid":
+ "Matches form elements with valid content according to their validation rules.",
+ ":visited": "Matches links that have been visited by the user.",
+ ":where()":
+ "Like :is() but with zero specificity. Matches any selector in the list.",
+ // Media-related
+ ":paused":
+ "Matches media elements like video or audio when playback is paused.",
+ ":playing":
+ "Matches media elements like video or audio when playback is active.",
+ ":muted": "Matches media elements that are currently muted.",
+ ":buffering": "Matches media elements that are buffering content.",
+ ":seeking":
+ "Matches media elements when the user is seeking to a new position.",
+ ":stalled": "Matches media elements when the download has stalled.",
+ ":volume-locked": "Matches media elements when volume cannot be changed.",
+ // Picture-in-picture
+ ":picture-in-picture":
+ "Matches the element currently displayed in picture-in-picture mode.",
+ // Popover
+ ":popover-open": "Matches popover elements that are currently shown.",
+};
+
+// Descriptions for CSS pseudo-elements
+export const pseudoElementDescriptions: Record<string, string> = {
+ "::after":
+ "Creates a virtual element as the last child of the selected element for inserting content.",
+ "::before":
+ "Creates a virtual element as the first child of the selected element for inserting content.",
+ "::backdrop":
+ "Styles the box behind a fullscreen or modal element, covering the entire viewport.",
+ "::cue": "Styles the WebVTT cues (captions/subtitles) for media elements.",
+ "::file-selector-button":
+ "Styles the button of file input elements that opens the file picker.",
+ "::first-letter":
+ "Applies styles to the first letter of a block-level element.",
+ "::first-line": "Applies styles to the first line of a block-level element.",
+ "::grammar-error":
+ "Styles text that the browser has flagged as grammatically incorrect.",
+ "::highlight()":
+ "Styles custom highlighted ranges created via the CSS Custom Highlight API.",
+ "::marker": "Styles the marker box of list items, like bullets or numbers.",
+ "::part()":
+ "Styles elements within a shadow tree that have been exposed via the part attribute.",
+ "::placeholder":
+ "Styles the placeholder text in input and textarea elements.",
+ "::selection":
+ "Styles the portion of an element that is selected by the user.",
+ "::slotted()": "Styles elements placed into a slot within a shadow tree.",
+ "::spelling-error": "Styles text that the browser has flagged as misspelled.",
+ "::target-text":
+ "Styles the text fragment that was scrolled to via a URL fragment.",
+ // View transitions
+ "::view-transition": "Represents the root of the view transition overlay.",
+ "::view-transition-group()":
+ "Represents a single view transition snapshot group.",
+ "::view-transition-image-pair()":
+ "Represents the old and new views of a transition snapshot.",
+ "::view-transition-new()":
+ "Represents the new view state during a view transition.",
+ "::view-transition-old()":
+ "Represents the old view state during a view transition.",
+ // Scroll markers
+ "::scroll-marker":
+ "Styles scroll markers generated for scroll snap containers.",
+ "::scroll-marker-group": "Styles the container for scroll markers.",
+ // Details
+ "::details-content":
+ "Styles the expandable content portion of a details element.",
+ // Picker
+ "::picker-icon": "Styles the icon in picker controls like date inputs.",
+ "::picker()": "Styles the popup picker interface for form controls.",
+ // Checkmark
+ "::checkmark": "Styles the checkmark in checkbox or option elements.",
+};
diff --git a/packages/css-data/src/index.ts b/packages/css-data/src/index.ts
index b11d0d27ce..0cb3b42c91 100644
--- a/packages/css-data/src/index.ts
+++ b/packages/css-data/src/index.ts
@@ -8,6 +8,11 @@ export {
} from "./__generated__/property-value-descriptions";
export * from "./__generated__/animatable-properties";
export * from "./__generated__/pseudo-elements";
+export * from "./__generated__/pseudo-classes";
+export {
+ pseudoClassDescriptions,
+ pseudoElementDescriptions,
+} from "./__generated__/pseudo-selector-descriptions";
export * from "./property-parsers";
// shorthand property parsers
@@ -17,3 +22,26 @@ export * from "./shorthands";
export { shorthandProperties } from "./__generated__/shorthand-properties";
export { properties as propertiesData } from "./__generated__/properties";
+
+// Utility functions
+import { pseudoElements } from "./__generated__/pseudo-elements";
+
+/**
+ * Check if a state string represents a pseudo-element (e.g., "::before", "::after")
+ * rather than a pseudo-class (e.g., ":hover", ":focus")
+ */
+export const isPseudoElement = (state: string): boolean => {
+ if (!state) {
+ return false;
+ }
+
+ // Pseudo-elements start with :: (or single : for legacy syntax)
+ // Remove the colons and check against the list
+ const normalized = state.replace(/^::?/, "");
+ return (pseudoElements as readonly string[]).includes(normalized);
+};
+
+export {
+ validateSelector,
+ type SelectorValidationResult,
+} from "./selector-validation";
diff --git a/packages/css-data/src/selector-validation.test.ts b/packages/css-data/src/selector-validation.test.ts
new file mode 100644
index 0000000000..bd0dd54a9d
--- /dev/null
+++ b/packages/css-data/src/selector-validation.test.ts
@@ -0,0 +1,329 @@
+import { describe, test, expect } from "vitest";
+import { validateSelector } from "./selector-validation";
+
+describe("validateSelector", () => {
+ describe("valid selectors", () => {
+ test("simple pseudo-classes", () => {
+ const selectors = [
+ ":hover",
+ ":focus",
+ ":active",
+ ":visited",
+ ":disabled",
+ ":checked",
+ ":focus-visible",
+ ":focus-within",
+ ];
+
+ for (const selector of selectors) {
+ const result = validateSelector(selector);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.type).toBe("pseudo-class");
+ }
+ }
+ });
+
+ test("simple pseudo-elements", () => {
+ const selectors = [
+ "::before",
+ "::after",
+ "::placeholder",
+ "::first-line",
+ "::first-letter",
+ "::selection",
+ "::marker",
+ "::backdrop",
+ ];
+
+ for (const selector of selectors) {
+ const result = validateSelector(selector);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.type).toBe("pseudo-element");
+ }
+ }
+ });
+
+ test("legacy single-colon pseudo-elements", () => {
+ const selectors = [":before", ":after", ":first-line", ":first-letter"];
+
+ for (const selector of selectors) {
+ const result = validateSelector(selector);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.type).toBe("pseudo-element");
+ }
+ }
+ });
+
+ test("functional pseudo-classes with simple selectors", () => {
+ const selectors = [":not(div)", ":is(a)", ":where(span)", ":has(p)"];
+
+ for (const selector of selectors) {
+ const result = validateSelector(selector);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.type).toBe("pseudo-class");
+ }
+ }
+ });
+
+ test("functional pseudo-classes with An+B notation", () => {
+ const selectors = [
+ ":nth-child(2n)",
+ ":nth-last-child(odd)",
+ ":nth-of-type(3n+1)",
+ ":nth-last-of-type(even)",
+ ];
+
+ for (const selector of selectors) {
+ const result = validateSelector(selector);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.type).toBe("pseudo-class");
+ }
+ }
+ });
+
+ test("functional pseudo-classes with nested selectors", () => {
+ const selectors = [
+ ":not(.class)",
+ ":is(#id)",
+ ":where([attr])",
+ ":has(> div)",
+ ];
+
+ for (const selector of selectors) {
+ const result = validateSelector(selector);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.type).toBe("pseudo-class");
+ }
+ }
+ });
+
+ test("shadow DOM pseudo-classes", () => {
+ const selectors = [":host", ":host(.class)", ":host-context(.class)"];
+
+ for (const selector of selectors) {
+ const result = validateSelector(selector);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.type).toBe("pseudo-class");
+ }
+ }
+ });
+
+ test("linguistic pseudo-classes", () => {
+ const selectors = [":lang(en)", ":dir(rtl)", ":dir(ltr)"];
+
+ for (const selector of selectors) {
+ const result = validateSelector(selector);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.type).toBe("pseudo-class");
+ }
+ }
+ });
+
+ test("custom state pseudo-class", () => {
+ const result = validateSelector(":state(custom)");
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.type).toBe("pseudo-class");
+ }
+ });
+
+ test("time-dimensional pseudo-classes", () => {
+ const selectors = [":current", ":past", ":future"];
+
+ for (const selector of selectors) {
+ const result = validateSelector(selector);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.type).toBe("pseudo-class");
+ }
+ }
+ });
+
+ test("less common pseudo-elements from generated list", () => {
+ const selectors = [
+ "::grammar-error",
+ "::spelling-error",
+ "::target-text",
+ "::file-selector-button",
+ ];
+
+ for (const selector of selectors) {
+ const result = validateSelector(selector);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.type).toBe("pseudo-element");
+ }
+ }
+ });
+
+ test("functional pseudo-elements", () => {
+ const selectors = ["::part(tab)", "::slotted(span)"];
+
+ for (const selector of selectors) {
+ const result = validateSelector(selector);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.type).toBe("pseudo-element");
+ }
+ }
+ });
+ });
+
+ describe("attribute selectors", () => {
+ test("basic attribute selectors", () => {
+ const selectors = [
+ "[data-state]",
+ "[data-state=open]",
+ "[data-state=closed]",
+ "[aria-expanded=true]",
+ "[aria-hidden=false]",
+ ];
+
+ for (const selector of selectors) {
+ const result = validateSelector(selector);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.type).toBe("attribute");
+ }
+ }
+ });
+
+ test("attribute selectors with operators", () => {
+ const selectors = [
+ "[class~=foo]",
+ "[lang|=en]",
+ "[href^=https]",
+ '[src$=".png"]',
+ "[title*=hello]",
+ ];
+
+ for (const selector of selectors) {
+ const result = validateSelector(selector);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.type).toBe("attribute");
+ }
+ }
+ });
+
+ test("attribute selectors with quotes", () => {
+ const selectors = [
+ '[data-state="open"]',
+ "[data-state='closed']",
+ '[aria-label="menu button"]',
+ ];
+
+ for (const selector of selectors) {
+ const result = validateSelector(selector);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.type).toBe("attribute");
+ }
+ }
+ });
+
+ test("case-insensitive attribute selectors", () => {
+ const selectors = ["[type=text i]", "[href$=PDF i]"];
+
+ for (const selector of selectors) {
+ const result = validateSelector(selector);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.type).toBe("attribute");
+ }
+ }
+ });
+ });
+
+ describe("invalid selectors", () => {
+ test("empty selector", () => {
+ const result = validateSelector("");
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.error).toBe("Selector cannot be empty");
+ }
+ });
+
+ test("whitespace-only selector", () => {
+ const result = validateSelector(" ");
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.error).toBe("Selector cannot be empty");
+ }
+ });
+
+ test("selector not starting with colon or bracket", () => {
+ const result = validateSelector("hover");
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.error).toBe(
+ "Selector must start with a colon (:) for pseudo-classes, double colon (::) for pseudo-elements, or bracket ([) for attribute selectors"
+ );
+ }
+ });
+
+ test("invalid pseudo-class name", () => {
+ const result = validateSelector(":not-a-real-pseudo-class");
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.error).toBe("Invalid pseudo-class");
+ }
+ });
+
+ test("invalid functional pseudo-class name", () => {
+ const result = validateSelector(":blablubb(div)");
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.error).toBe("Invalid pseudo-class");
+ }
+ });
+
+ test("invalid pseudo-element name", () => {
+ const result = validateSelector("::not-a-real-pseudo-element");
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.error).toBe("Invalid pseudo-element");
+ }
+ });
+
+ test("unbalanced parentheses in functional pseudo-class", () => {
+ const result = validateSelector(":not(div");
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.error).toBe("Invalid CSS selector syntax");
+ }
+ });
+
+ test("unbalanced parentheses - too many closing", () => {
+ const result = validateSelector(":not(div))");
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.error).toBe("Invalid CSS selector syntax");
+ }
+ });
+
+ test("invalid syntax inside functional pseudo-class", () => {
+ // css-tree is lenient and will parse this
+ // The browser will ultimately reject truly invalid selectors
+ const result = validateSelector(":has(>>invalid)");
+ // This actually parses in css-tree (it's lenient)
+ expect(result.success).toBe(true);
+ });
+
+ test("unbalanced brackets in attribute selector", () => {
+ const result = validateSelector("[data-state");
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.error).toBe("Invalid CSS selector syntax");
+ }
+ });
+ });
+});
diff --git a/packages/css-data/src/selector-validation.ts b/packages/css-data/src/selector-validation.ts
new file mode 100644
index 0000000000..2ea4dc92c5
--- /dev/null
+++ b/packages/css-data/src/selector-validation.ts
@@ -0,0 +1,122 @@
+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" };
+
+/**
+ * Validates a CSS pseudo-class, pseudo-element, or attribute selector
+ * @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
+): SelectorValidationResult => {
+ if (!selector || selector.trim() === "") {
+ return { success: false, error: "Selector cannot be empty" };
+ }
+
+ // Must start with a colon or bracket
+ if (!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 {
+ // Parse as a rule to validate syntax
+ // We wrap it in a dummy selector because css-tree requires a full rule
+ const ast = csstree.parse(`dummy${selector} {}`);
+
+ let foundPseudoClass = false;
+ let foundPseudoElement = false;
+ let foundAttribute = false;
+ let pseudoClassName: string | undefined;
+ let pseudoElementName: string | undefined;
+
+ // Walk the AST to find pseudo-class, pseudo-element, or attribute selectors
+ csstree.walk(ast, (node) => {
+ if (node.type === "PseudoClassSelector") {
+ foundPseudoClass = true;
+ pseudoClassName = node.name;
+ }
+ if (node.type === "PseudoElementSelector") {
+ foundPseudoElement = true;
+ pseudoElementName = node.name;
+ }
+ if (node.type === "AttributeSelector") {
+ foundAttribute = true;
+ }
+ });
+
+ // Determine the type based on what we found
+ if (foundPseudoElement) {
+ // Validate that the pseudo-element actually exists
+ // Some pseudo-elements are functional (e.g., ::part(), ::slotted())
+ // The list includes both "part" and "part()" variants
+ if (pseudoElementName) {
+ const withParens = `${pseudoElementName}()`;
+ if (
+ (pseudoElements as readonly string[]).includes(pseudoElementName) ||
+ (pseudoElements as readonly string[]).includes(withParens)
+ ) {
+ return { success: true, type: "pseudo-element" };
+ }
+ }
+ // Invalid pseudo-element name
+ return {
+ success: false,
+ error: "Invalid pseudo-element",
+ };
+ }
+
+ if (foundPseudoClass) {
+ // Check if it's actually a legacy pseudo-element (single colon)
+ // Legacy syntax: :before, :after, :first-line, :first-letter
+ if (
+ pseudoClassName &&
+ (pseudoElements as readonly string[]).includes(pseudoClassName)
+ ) {
+ return { success: true, type: "pseudo-element" };
+ }
+
+ // Validate that the pseudo-class actually exists
+ // Some pseudo-classes are functional (e.g., :has(), :not())
+ // The list includes both "has" and "has()" variants
+ if (pseudoClassName) {
+ const withParens = `${pseudoClassName}()`;
+ if (
+ (pseudoClasses as readonly string[]).includes(pseudoClassName) ||
+ (pseudoClasses as readonly string[]).includes(withParens)
+ ) {
+ return { success: true, type: "pseudo-class" };
+ }
+ }
+
+ // Invalid pseudo-class name
+ return {
+ success: false,
+ error: "Invalid 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",
+ };
+ }
+};
diff --git a/packages/css-engine/src/core/create-style-sheet.ts b/packages/css-engine/src/core/create-style-sheet.ts
index 3ee58612d0..2493020fc0 100644
--- a/packages/css-engine/src/core/create-style-sheet.ts
+++ b/packages/css-engine/src/core/create-style-sheet.ts
@@ -1,7 +1,10 @@
import { StyleSheetRegular } from "./style-sheet-regular";
-import { StyleElement } from "./style-element";
+import { StyleElement, FakeStyleElement } from "./style-element";
-export const createRegularStyleSheet = (options?: { name?: string }) => {
- const element = new StyleElement(options?.name);
+export const createRegularStyleSheet = (options?: {
+ name?: string;
+ element?: StyleElement | FakeStyleElement;
+}) => {
+ const element = options?.element ?? new StyleElement(options?.name);
return new StyleSheetRegular(element);
};
diff --git a/packages/css-engine/src/core/index.ts b/packages/css-engine/src/core/index.ts
index 222d4023ff..faef6f4b5f 100644
--- a/packages/css-engine/src/core/index.ts
+++ b/packages/css-engine/src/core/index.ts
@@ -10,6 +10,7 @@ export { mergeStyles } from "./merger";
export { generateStyleMap } from "./rules";
export type { StyleSheetRegular } from "./style-sheet-regular";
export * from "./create-style-sheet";
+export { FakeStyleElement } from "./style-element";
export * from "./to-value";
export { hyphenateProperty } from "./to-property";
export * from "./match-media";
diff --git a/packages/css-engine/src/core/style-element.ts b/packages/css-engine/src/core/style-element.ts
index 450335991d..1d99a4d571 100644
--- a/packages/css-engine/src/core/style-element.ts
+++ b/packages/css-engine/src/core/style-element.ts
@@ -36,3 +36,20 @@ export class StyleElement {
}
}
}
+
+/**
+ * A fake style element that does nothing.
+ * Useful for testing stylesheets without DOM.
+ */
+export class FakeStyleElement {
+ get isMounted() {
+ return false;
+ }
+ mount() {}
+ unmount() {}
+ render(_cssText: string) {}
+ setAttribute(_name: string, _value: string) {}
+ getAttribute(_name: string) {
+ return;
+ }
+}
diff --git a/packages/css-engine/src/core/style-sheet.ts b/packages/css-engine/src/core/style-sheet.ts
index 005df89929..026911b03d 100644
--- a/packages/css-engine/src/core/style-sheet.ts
+++ b/packages/css-engine/src/core/style-sheet.ts
@@ -8,7 +8,7 @@ import {
type MediaRuleOptions,
} from "./rules";
import { compareMedia } from "./compare-media";
-import { StyleElement } from "./style-element";
+import { StyleElement, FakeStyleElement } from "./style-element";
import type { TransformValue } from "./to-value";
export class StyleSheet {
@@ -19,8 +19,8 @@ export class StyleSheet {
nestingRules: Map<string, NestingRule> = new Map();
#fontFaceRules: Array<FontFaceRule> = [];
#transformValue?: TransformValue;
- #element: StyleElement;
- constructor(element: StyleElement) {
+ #element: StyleElement | FakeStyleElement;
+ constructor(element: StyleElement | FakeStyleElement) {
this.#element = element;
}
setTransformer(transformValue: TransformValue) {
diff --git a/packages/design-system/src/__generated__/figma-design-tokens.ts b/packages/design-system/src/__generated__/figma-design-tokens.ts
index 40367790b1..70fcd5266c 100644
--- a/packages/design-system/src/__generated__/figma-design-tokens.ts
+++ b/packages/design-system/src/__generated__/figma-design-tokens.ts
@@ -69,25 +69,13 @@ export const typography = {
textDecoration: "none",
textIndent: "0px",
},
- labelsTitleCase: {
+ labels: {
fontFamily:
"Inter Variable, InterVariable, Inter, -apple-system, system-ui, sans-serif",
fontWeight: 500,
fontSize: "12px",
lineHeight: "16px",
letterSpacing: "0.005em",
- textTransform: "capitalize",
- textDecoration: "none",
- textIndent: "0px",
- },
- labelsSentenceCase: {
- fontFamily:
- "Inter Variable, InterVariable, Inter, -apple-system, system-ui, sans-serif",
- fontWeight: 500,
- fontSize: "12px",
- lineHeight: "16px",
- letterSpacing: "0.005em",
- textTransform: "none",
textDecoration: "none",
textIndent: "0px",
},
diff --git a/packages/design-system/src/components/__DEPRECATED__/list.tsx b/packages/design-system/src/components/__DEPRECATED__/list.tsx
index 05b876b918..cf535e2acf 100644
--- a/packages/design-system/src/components/__DEPRECATED__/list.tsx
+++ b/packages/design-system/src/components/__DEPRECATED__/list.tsx
@@ -72,7 +72,7 @@ export const DeprecatedListItem = forwardRef<
justify="between"
>
<Text
- variant="labelsSentenceCase"
+ variant="labels"
truncate
color={state === "disabled" ? "subtle" : "main"}
>
diff --git a/packages/design-system/src/components/ai-command-bar/command-bar.stories.tsx b/packages/design-system/src/components/ai-command-bar/command-bar.stories.tsx
index f94c17f32a..8f39286824 100644
--- a/packages/design-system/src/components/ai-command-bar/command-bar.stories.tsx
+++ b/packages/design-system/src/components/ai-command-bar/command-bar.stories.tsx
@@ -18,7 +18,7 @@ const CommandBarContent = () => {
return (
<>
<CommandBarContentSection>
- <Text variant={"labelsSentenceCase"} align={"center"}>
+ <Text variant={"labels"} align={"center"}>
Previous propmts
</Text>
<div />
diff --git a/packages/design-system/src/components/button.tsx b/packages/design-system/src/components/button.tsx
index 42780f9d16..0d84730022 100644
--- a/packages/design-system/src/components/button.tsx
+++ b/packages/design-system/src/components/button.tsx
@@ -130,7 +130,7 @@ export const buttonStyle = css({
},
});
-const TextContainer = styled("span", textVariants.labelsSentenceCase, {
+const TextContainer = styled("span", textVariants.labels, {
padding: `0 ${theme.spacing[2]}`,
overflow: "hidden",
textOverflow: "ellipsis",
diff --git a/packages/design-system/src/components/command.stories.tsx b/packages/design-system/src/components/command.stories.tsx
index fabda3b3e4..87bb221212 100644
--- a/packages/design-system/src/components/command.stories.tsx
+++ b/packages/design-system/src/components/command.stories.tsx
@@ -39,7 +39,7 @@ const CommandContent = () => {
<CommandIcon>
<InfoCircleIcon />
</CommandIcon>
- <Text variant="labelsTitleCase">Calendar</Text>
+ <Text variant="labels">Calendar</Text>
</Flex>
</CommandItem>
<CommandItem>
@@ -47,7 +47,7 @@ const CommandContent = () => {
<CommandIcon>
<InfoCircleIcon />
</CommandIcon>
- <Text variant="labelsTitleCase">Search Emoji</Text>
+ <Text variant="labels">Search Emoji</Text>
</Flex>
</CommandItem>
<CommandItem>
@@ -55,7 +55,7 @@ const CommandContent = () => {
<CommandIcon>
<InfoCircleIcon />
</CommandIcon>
- <Text variant="labelsTitleCase">Calculator</Text>
+ <Text variant="labels">Calculator</Text>
</Flex>
</CommandItem>
</CommandGroup>
@@ -69,7 +69,7 @@ const CommandContent = () => {
<CommandIcon>
<InfoCircleIcon />
</CommandIcon>
- <Text variant="labelsTitleCase">Profile</Text>
+ <Text variant="labels">Profile</Text>
</Flex>
<Kbd value={["meta", "p"]} />
</CommandItem>
@@ -78,7 +78,7 @@ const CommandContent = () => {
<CommandIcon>
<InfoCircleIcon />
</CommandIcon>
- <Text variant="labelsTitleCase">Billing</Text>
+ <Text variant="labels">Billing</Text>
</Flex>
<Kbd value={["meta", "b"]} />
</CommandItem>
@@ -87,7 +87,7 @@ const CommandContent = () => {
<CommandIcon>
<InfoCircleIcon />
</CommandIcon>
- <Text variant="labelsTitleCase">Settings</Text>
+ <Text variant="labels">Settings</Text>
</Flex>
<Kbd value={["meta", "s"]} />
</CommandItem>
diff --git a/packages/design-system/src/components/command.tsx b/packages/design-system/src/components/command.tsx
index b315220f2d..38fd21090b 100644
--- a/packages/design-system/src/components/command.tsx
+++ b/packages/design-system/src/components/command.tsx
@@ -479,7 +479,7 @@ export const CommandItem = ({
};
export const CommandGroupHeading = styled("div", {
- ...textVariants.labelsSentenceCase,
+ ...textVariants.labels,
color: theme.colors.foregroundMoreSubtle,
display: "flex",
backgroundColor: theme.colors.backgroundControls,
@@ -490,7 +490,7 @@ export const CommandGroupHeading = styled("div", {
});
export const CommandGroupFooter = styled("div", {
- ...textVariants.labelsSentenceCase,
+ ...textVariants.labels,
color: theme.colors.foregroundMoreSubtle,
display: "flex",
gap: theme.spacing[5],
diff --git a/packages/design-system/src/components/label.tsx b/packages/design-system/src/components/label.tsx
index 24389cc2fd..49c7048f1b 100644
--- a/packages/design-system/src/components/label.tsx
+++ b/packages/design-system/src/components/label.tsx
@@ -109,7 +109,7 @@ const StyledLabel = styled(RadixLabel, {
},
text: {
title: textVariants.titles,
- sentence: textVariants.labelsSentenceCase,
+ sentence: textVariants.labels,
mono: textVariants.mono,
},
},
diff --git a/packages/design-system/src/components/menu.tsx b/packages/design-system/src/components/menu.tsx
index 496b8aec42..b638bdd21b 100644
--- a/packages/design-system/src/components/menu.tsx
+++ b/packages/design-system/src/components/menu.tsx
@@ -70,8 +70,8 @@ export const menuItemCss = css({
},
variants: {
text: {
- title: textVariants.labelsTitleCase,
- sentence: textVariants.labelsSentenceCase,
+ title: textVariants.labels,
+ sentence: textVariants.labels,
},
withIndicator: {
true: {
@@ -85,7 +85,7 @@ export const menuItemCss = css({
},
hint: {
true: {
- ...textVariants.labelsSentenceCase,
+ ...textVariants.labels,
px: theme.spacing[5],
background: theme.colors.backgroundMenuHint,
borderRadius: theme.borderRadius[2],
diff --git a/packages/design-system/src/components/toast.tsx b/packages/design-system/src/components/toast.tsx
index d83bd9acc5..7f847cf0eb 100644
--- a/packages/design-system/src/components/toast.tsx
+++ b/packages/design-system/src/components/toast.tsx
@@ -172,7 +172,7 @@ const InternalToast = ({
overflow: "hidden",
textOverflow: "ellipsis",
}}
- variant={"labelsSentenceCase"}
+ variant={"labels"}
>
{children}
</Text>
diff --git a/packages/design-system/src/components/toggle-group.tsx b/packages/design-system/src/components/toggle-group.tsx
index a2ef39c8b7..5ed20c3752 100644
--- a/packages/design-system/src/components/toggle-group.tsx
+++ b/packages/design-system/src/components/toggle-group.tsx
@@ -92,7 +92,7 @@ const BaseToggleGroupButton = forwardRef<
}
css={{
height: theme.spacing[10],
- ...textVariants.labelsTitleCase,
+ ...textVariants.labels,
}}
/>
);
diff --git a/packages/design-system/src/components/toolbar.tsx b/packages/design-system/src/components/toolbar.tsx
index a4113a7ce3..626d4b631a 100644
--- a/packages/design-system/src/components/toolbar.tsx
+++ b/packages/design-system/src/components/toolbar.tsx
@@ -26,7 +26,7 @@ export const ToolbarToggleGroup = styled(ToolbarPrimitive.ToggleGroup, {
const focusRing = focusRingStyle();
-const toggleItemStyle = css(textVariants.labelsTitleCase, {
+const toggleItemStyle = css(textVariants.labels, {
// reset styles
boxSizing: "border-box",
position: "relative",
diff --git a/packages/design-system/src/components/tree.tsx b/packages/design-system/src/components/tree.tsx
index b531807237..9c1dba7a45 100644
--- a/packages/design-system/src/components/tree.tsx
+++ b/packages/design-system/src/components/tree.tsx
@@ -509,7 +509,7 @@ export const TreeNodeLabel = ({
<>
{prefix}
<Text
- variant="labelsSentenceCase"
+ variant="labels"
truncate
css={{
marginLeft: prefix ? theme.spacing[3] : 0,