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: Autocompletion of custom selectors in the token menu (#5573)

Oleg Isonen46fd1c2e0de6
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index f2204c5a68..5cad1d1e14 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -12,9 +12,16 @@
- Never use one-line if statements: `if (condition) something;`
- Never use the `function` keyword - always use arrow functions (`const name = () => {}`) or function expressions with arrow syntax
- Functions must never have more than 3 parameters - use an object parameter instead
+- Components should have no more than 10 props - if more are needed, consider restructuring
- 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.
+## Comments
+
+- Don't state the obvious that's already written clearly with code
+- Explain WHY you do things, not WHAT you do
+- Only explain WHAT when logic is non-trivial to clarify intent
+
## UI Labels and Text
- All visible labels and text must use sentence case capitalization:
@@ -165,3 +172,22 @@ const { internalHelper } = __testing__;
## UI/UX
- Never decide on implementation details around UI and UX yourself, always ask user and provide choices
+
+## Social Posts (Release Announcements)
+
+When writing social posts for new releases:
+
+- Start with "New in Webstudio:" to make it clear it's a release
+- Use a single relevant emoji at the start
+- No hashtags
+- No version numbers
+- Use terminology from the UI that users will recognize (e.g., "Style panel", "Collection component")
+- Keep it factual — don't use marketing language like "without writing code" or "game-changer"
+- Explain what the feature does, not why it's impressive
+- One post per major feature
+- To get features for a release, run: `git log <previous-tag>..<current-tag> --oneline` and look for commits prefixed with `feat:`
+
+## Code Review
+
+- After completing changes, review your own code against all instructions in this document.
+- If a component or module needs refactoring (e.g., too many props, too complex, violates guidelines), ask the user before proceeding.
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 1d898bebd5..df0868b28d 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
@@ -1,7 +1,4 @@
import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuTrigger,
Text,
styled,
Box,
@@ -9,16 +6,14 @@ import {
Flex,
Tooltip,
} from "@webstudio-is/design-system";
-import { ChevronDownIcon } from "@webstudio-is/icons";
import type { StyleSource } from "@webstudio-is/sdk";
-import { type ReactNode, useState } from "react";
+import { type ReactNode } from "react";
import { useContentEditable } from "~/shared/dom-hooks";
const menuTriggerVisibilityVar = "--ws-style-source-menu-trigger-visibility";
const menuTriggerVisibilityOverrideVar =
"--ws-style-source-menu-trigger-visibility-override";
const menuTriggerGradientVar = "--ws-style-source-menu-trigger-gradient";
-const visibility = `var(${menuTriggerVisibilityOverrideVar}, var(${menuTriggerVisibilityVar}))`;
export const menuCssVars = ({
show,
@@ -36,78 +31,6 @@ export const menuCssVars = ({
};
};
-const MenuTrigger = styled("button", {
- display: "inline-flex",
- border: "none",
- boxSizing: "border-box",
- minWidth: 0,
- alignItems: "center",
- position: "absolute",
- right: 0,
- top: 0,
- height: "100%",
- padding: 0,
- borderTopRightRadius: theme.borderRadius[4],
- borderBottomRightRadius: theme.borderRadius[4],
- color: theme.colors.foregroundContrastMain,
- visibility,
- "&:hover, &[data-state=open]": {
- ...menuCssVars({ show: true }),
- "&::after": {
- content: '""',
- display: "block",
- position: "absolute",
- top: 0,
- right: 0,
- width: "100%",
- height: "100%",
- visibility,
- backgroundColor: theme.colors.backgroundButtonHover,
- borderTopRightRadius: theme.borderRadius[4],
- borderBottomRightRadius: theme.borderRadius[4],
- pointerEvents: "none",
- },
- },
-});
-
-const MenuTriggerGradient = styled(Box, {
- position: "absolute",
- top: 0,
- right: 0,
- width: theme.sizes.controlHeight,
- height: "100%",
- visibility,
- background: `var(${menuTriggerGradientVar})`,
- borderTopRightRadius: theme.borderRadius[4],
- borderBottomRightRadius: theme.borderRadius[4],
- pointerEvents: "none",
-});
-
-type MenuProps = {
- children: ReactNode;
- open?: boolean;
- onOpenChange?: (open: boolean) => void;
-};
-
-const Menu = (props: MenuProps) => {
- return (
- <DropdownMenu modal open={props.open} onOpenChange={props.onOpenChange}>
- <DropdownMenuTrigger asChild>
- <MenuTrigger aria-label="Menu Button">
- <MenuTriggerGradient />
- <ChevronDownIcon style={{ position: "relative" }} />
- </MenuTrigger>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- onCloseAutoFocus={(event) => event.preventDefault()}
- css={{ maxWidth: theme.spacing[26] }}
- >
- {props.children}
- </DropdownMenuContent>
- </DropdownMenu>
- );
-};
-
export type ItemSource = "token" | "tag" | "local";
export type ItemSelector = {
@@ -285,7 +208,7 @@ type StyleSourceControlProps = {
id: StyleSource["id"];
error?: StyleSourceError;
label: string;
- menuItems: ReactNode;
+ menu: ReactNode;
selected: boolean;
state: undefined | string;
stateLabel: undefined | string;
@@ -297,11 +220,12 @@ type StyleSourceControlProps = {
onSelect: () => void;
onChangeValue: (value: string) => void;
onChangeEditing: (isEditing: boolean) => void;
+ onOpenMenu?: () => void;
};
export const StyleSourceControl = ({
id,
- menuItems,
+ menu,
selected,
state,
stateLabel,
@@ -315,14 +239,14 @@ export const StyleSourceControl = ({
onChangeValue,
onChangeEditing,
onSelect,
+ onOpenMenu,
}: StyleSourceControlProps) => {
const showMenu = isEditing === false && isDragging === false;
- const [menuOpen, setMenuOpen] = useState(false);
const handleContextMenu = (event: React.MouseEvent) => {
if (showMenu && disabled === false && isEditing === false) {
event.preventDefault();
- setMenuOpen(true);
+ onOpenMenu?.();
}
};
@@ -376,11 +300,7 @@ export const StyleSourceControl = ({
<StyleSourceState source={source}>{stateLabel}</StyleSourceState>
</Tooltip>
)}
- {showMenu && (
- <Menu open={menuOpen} onOpenChange={setMenuOpen}>
- {menuItems}
- </Menu>
- )}
+ {showMenu && menu}
</StyleSourceContainer>
</Tooltip>
);
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 6be22e0a36..2448f248b9 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
@@ -55,7 +55,6 @@ import { matchSorter } from "match-sorter";
import { StyleSourceBadge } from "./style-source-badge";
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 = {
@@ -96,7 +95,12 @@ type TextFieldBaseWrapperProps<Item extends IntermediateItem> = Omit<
label: string;
containerRef?: RefObject<HTMLDivElement>;
inputRef?: RefObject<HTMLInputElement>;
- renderStyleSourceMenuItems: (item: Item, hasStyles: boolean) => ReactNode;
+ renderMenu: (params: {
+ item: Item;
+ hasStyles: boolean;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ }) => ReactNode;
onChangeItem?: (item: Item) => void;
onSort?: (items: Array<Item>) => void;
onSelectItem?: (itemSelector: ItemSelector) => void;
@@ -106,6 +110,42 @@ type TextFieldBaseWrapperProps<Item extends IntermediateItem> = Omit<
error?: StyleSourceError;
};
+// Wrapper component to manage menu state per item
+const StyleSourceControlWithMenu = <Item extends IntermediateItem>({
+ item,
+ hasStyles,
+ renderMenu,
+ ...props
+}: Omit<
+ ComponentProps<typeof StyleSourceControl>,
+ "menu" | "id" | "hasStyles" | "onOpenMenu"
+> & {
+ item: Item;
+ hasStyles: boolean;
+ renderMenu: (params: {
+ item: Item;
+ hasStyles: boolean;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ }) => ReactNode;
+}) => {
+ const [menuOpen, setMenuOpen] = useState(false);
+ return (
+ <StyleSourceControl
+ {...props}
+ id={item.id}
+ hasStyles={hasStyles}
+ onOpenMenu={() => setMenuOpen(true)}
+ menu={renderMenu({
+ item,
+ hasStyles,
+ open: menuOpen,
+ onOpenChange: setMenuOpen,
+ })}
+ />
+ );
+};
+
// Returns true if style source has defined styles including on the states.
const getHasStylesMap = <Item extends IntermediateItem>(
styleSourceItems: Array<Item>,
@@ -142,7 +182,7 @@ const TextFieldBase: ForwardRefRenderFunction<
label,
value,
selectedItemSelector,
- renderStyleSourceMenuItems,
+ renderMenu,
onChangeItem,
onSort,
onSelectItem,
@@ -214,10 +254,10 @@ const TextFieldBase: ForwardRefRenderFunction<
aria-label="New Style Source Input"
/>
{value.map((item) => (
- <StyleSourceControl
+ <StyleSourceControlWithMenu
key={item.id}
- menuItems={renderStyleSourceMenuItems(item, hasStyles(item.id))}
- id={item.id}
+ item={item}
+ renderMenu={renderMenu}
selected={item.id === selectedItemSelector?.styleSourceId}
state={
item.id === selectedItemSelector?.styleSourceId
@@ -333,10 +373,6 @@ export const StyleSourceInput = (
) => {
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,
@@ -391,53 +427,6 @@ 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()}>
@@ -447,16 +436,20 @@ export const StyleSourceInput = (
{...inputProps}
inputRef={props.inputRef}
error={props.error}
- renderStyleSourceMenuItems={(item, hasStyles) => (
+ renderMenu={({ item, hasStyles, open, onOpenChange }) => (
<StyleSourceMenu
+ open={open}
+ onOpenChange={onOpenChange}
selectedItemSelector={props.selectedItemSelector}
item={item}
hasStyles={hasStyles}
states={states}
- selectorInputValue={selectorInputValue}
- selectorValidation={selectorValidation}
- onSelectorInputChange={handleSelectorInputChange}
- onSelectorInputKeyDown={handleSelectorInputKeyDown}
+ onAddSelector={(itemId, selector) => {
+ props.onSelectItem?.({
+ styleSourceId: itemId,
+ state: selector,
+ });
+ }}
onSelect={props.onSelectItem}
onDuplicate={props.onDuplicateItem}
onConvertToToken={props.onConvertToToken}
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
index 3bc43dfc6c..a9adf64ac7 100644
--- 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
@@ -1,23 +1,29 @@
import { Fragment, useState } from "react";
import {
Box,
+ Combobox,
+ DropdownMenu,
+ DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
+ DropdownMenuTrigger,
Flex,
- InputErrorsTooltip,
- InputField,
rawTheme,
+ styled,
Text,
theme,
} from "@webstudio-is/design-system";
-import { CheckMarkIcon, DotIcon } from "@webstudio-is/icons";
+import { CheckMarkIcon, ChevronDownIcon, DotIcon } from "@webstudio-is/icons";
import {
- validateSelector,
pseudoClassDescriptions,
pseudoElementDescriptions,
} from "@webstudio-is/css-data";
-import type { ItemSource, ItemSelector } from "./style-source-control";
+import {
+ menuCssVars,
+ type ItemSource,
+ type ItemSelector,
+} from "./style-source-control";
export type SelectorConfig = {
type: "state" | "pseudoElement";
@@ -36,6 +42,59 @@ type IntermediateItem = {
states: string[];
};
+const menuTriggerVisibilityVar = "--ws-style-source-menu-trigger-visibility";
+const menuTriggerVisibilityOverrideVar =
+ "--ws-style-source-menu-trigger-visibility-override";
+const visibility = `var(${menuTriggerVisibilityOverrideVar}, var(${menuTriggerVisibilityVar}))`;
+const menuTriggerGradientVar = "--ws-style-source-menu-trigger-gradient";
+
+const MenuTrigger = styled("button", {
+ display: "inline-flex",
+ border: "none",
+ boxSizing: "border-box",
+ minWidth: 0,
+ alignItems: "center",
+ position: "absolute",
+ right: 0,
+ top: 0,
+ height: "100%",
+ padding: 0,
+ borderTopRightRadius: theme.borderRadius[4],
+ borderBottomRightRadius: theme.borderRadius[4],
+ color: theme.colors.foregroundContrastMain,
+ visibility,
+ "&:hover, &[data-state=open]": {
+ ...menuCssVars({ show: true }),
+ "&::after": {
+ content: '""',
+ display: "block",
+ position: "absolute",
+ top: 0,
+ right: 0,
+ width: "100%",
+ height: "100%",
+ visibility,
+ backgroundColor: theme.colors.backgroundButtonHover,
+ borderTopRightRadius: theme.borderRadius[4],
+ borderBottomRightRadius: theme.borderRadius[4],
+ pointerEvents: "none",
+ },
+ },
+});
+
+const MenuTriggerGradient = styled(Box, {
+ position: "absolute",
+ top: 0,
+ right: 0,
+ width: theme.sizes.controlHeight,
+ height: "100%",
+ visibility,
+ background: `var(${menuTriggerGradientVar})`,
+ borderTopRightRadius: theme.borderRadius[4],
+ borderBottomRightRadius: theme.borderRadius[4],
+ pointerEvents: "none",
+});
+
const selectorLabels = [
"state",
"pseudoElement",
@@ -58,6 +117,12 @@ const menuActionDescriptions = {
type MenuAction = keyof typeof menuActionDescriptions;
+// All available CSS selectors for autocomplete
+const allSelectors = [
+ ...Object.keys(pseudoClassDescriptions),
+ ...Object.keys(pseudoElementDescriptions),
+];
+
const getDescription = (selector: string, type: "state" | "pseudoElement") => {
// Normalize the selector to match the description keys
const normalized = selector.startsWith(":") ? selector : `:${selector}`;
@@ -76,18 +141,64 @@ const getDescription = (selector: string, type: "state" | "pseudoElement") => {
);
};
+const getSelectorDescription = (selector: string | null | undefined) => {
+ if (selector === undefined || selector === null) {
+ return;
+ }
+ // Determine type based on which description object contains the selector
+ const type =
+ selector in pseudoElementDescriptions ? "pseudoElement" : "state";
+ const description = getDescription(selector, type);
+ if (description === undefined) {
+ return;
+ }
+ return <Box css={{ maxWidth: theme.spacing[26] }}>{description}</Box>;
+};
+
+const SelectorCombobox = ({
+ existingSelectors,
+ onSelect,
+}: {
+ existingSelectors: string[];
+ onSelect: (selector: string) => void;
+}) => {
+ const [value, setValue] = useState("");
+
+ return (
+ <Box onKeyDown={(event) => event.stopPropagation()}>
+ <Combobox<string>
+ autoFocus={false}
+ placeholder="::before"
+ suffix={<span />}
+ getItems={() =>
+ allSelectors.filter((selector) =>
+ existingSelectors.every((s) => s !== selector)
+ )
+ }
+ value={value}
+ itemToString={(item) => item ?? ""}
+ defaultHighlightedIndex={0}
+ getDescription={getSelectorDescription}
+ onItemSelect={(item) => {
+ if (item) {
+ onSelect(item);
+ setValue("");
+ }
+ }}
+ onChange={(newValue) => setValue(newValue ?? "")}
+ />
+ </Box>
+ );
+};
+
type StyleSourceMenuProps = {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
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;
+ onAddSelector?: (itemId: IntermediateItem["id"], selector: string) => void;
onSelect?: (itemSelector: ItemSelector) => void;
onEdit?: (itemId: IntermediateItem["id"]) => void;
onDuplicate?: (itemId: IntermediateItem["id"]) => void;
@@ -144,194 +255,188 @@ export const StyleSourceMenu = (props: StyleSourceMenuProps) => {
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>
- );
- }
+ <DropdownMenu modal open={props.open} onOpenChange={props.onOpenChange}>
+ <DropdownMenuTrigger asChild>
+ <MenuTrigger aria-label="Menu Button">
+ <MenuTriggerGradient />
+ <ChevronDownIcon style={{ position: "relative" }} />
+ </MenuTrigger>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ onCloseAutoFocus={(event) => event.preventDefault()}
+ autoFocus
+ css={{ maxWidth: theme.spacing[26] }}
+ >
+ <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} />
)}
- </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)
- }
+ </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(undefined);
+ setHighlightedAction("clearStyles");
}}
- onKeyDown={(event) => {
- event.stopPropagation();
- props.onSelectorInputKeyDown(event, props.item.id);
+ onSelect={() => props.onClearStyles?.(props.item.id)}
+ >
+ Clear styles
+ </DropdownMenuItem>
+ )}
+ {props.item.source !== "local" && (
+ <DropdownMenuItem
+ onFocus={() => {
+ setHighlightedSelector(undefined);
+ setHighlightedAction("detach");
}}
- placeholder="::before"
- autoFocus={false}
- color={
- props.selectorValidation.success === false ? "error" : undefined
+ 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") ||
+ (source === "custom" &&
+ previousItem?.source !== "custom"));
+
+ 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>Add more</DropdownMenuLabel>
+ <Box css={{ padding: theme.spacing[4] }}>
+ <SelectorCombobox
+ existingSelectors={props.states.map((state) => state.selector)}
+ onSelect={(selector) =>
+ props.onAddSelector?.(props.item.id, selector)
}
- css={{ width: "100%" }}
/>
- </InputErrorsTooltip>
- </Box>
- <DropdownMenuSeparator />
- <DropdownMenuItem hint>{description}</DropdownMenuItem>
- </>
+ </Box>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem hint>{description}</DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
);
};
diff --git a/packages/design-system/src/components/combobox.tsx b/packages/design-system/src/components/combobox.tsx
index 17f562070f..c3f1c6c6c0 100644
--- a/packages/design-system/src/components/combobox.tsx
+++ b/packages/design-system/src/components/combobox.tsx
@@ -26,6 +26,7 @@ import {
} from "downshift";
import { matchSorter } from "match-sorter";
import { styled, theme } from "../stitches.config";
+import { focusFirstCollectionItem } from "../utilities";
import {
menuItemCss,
menuCss,
@@ -190,15 +191,13 @@ const StyledPopoverContent = styled(PopoverContent, {
export const ComboboxContent = forwardRef(
(
- { style, ...props }: ComponentProps<typeof PopoverContent>,
+ { style, onOpenAutoFocus, ...props }: ComponentProps<typeof PopoverContent>,
forwardRef: Ref<HTMLDivElement>
) => {
return (
<Portal>
<StyledPopoverContent
- onOpenAutoFocus={(event) => {
- event.preventDefault();
- }}
+ onOpenAutoFocus={onOpenAutoFocus}
{...props}
ref={forwardRef}
/>
@@ -330,7 +329,19 @@ export const useCombobox = <Item,>({
}
},
- stateReducer,
+ stateReducer: (state, actionAndChanges) => {
+ // Apply user's state reducer first
+ const userChanges = stateReducer(state, actionAndChanges);
+ // When menu opens, set highlighted index to defaultHighlightedIndex
+ if (
+ userChanges.isOpen === true &&
+ state.isOpen === false &&
+ defaultHighlightedIndex !== -1
+ ) {
+ return { ...userChanges, highlightedIndex: defaultHighlightedIndex };
+ }
+ return userChanges;
+ },
itemToString,
inputValue: value ? itemToString(value) : "",
onInputValueChange(state) {
@@ -499,7 +510,20 @@ export const Combobox = <Item,>({
onInvalid={onInvalid}
/>
</ComboboxAnchor>
- <ComboboxContent>
+ <ComboboxContent
+ onOpenAutoFocus={(event) => {
+ if (
+ props.defaultHighlightedIndex === undefined ||
+ props.defaultHighlightedIndex === -1
+ ) {
+ return;
+ }
+ event.preventDefault();
+ if (event.currentTarget instanceof HTMLElement) {
+ focusFirstCollectionItem(event.currentTarget);
+ }
+ }}
+ >
<ComboboxListbox {...combobox.getMenuProps()}>
<ComboboxScrollArea>
{combobox.isOpen &&
@@ -515,9 +539,9 @@ export const Combobox = <Item,>({
);
})}
</ComboboxScrollArea>
- {description && (
+ {descriptions.some(Boolean) && (
<ComboboxItemDescription descriptions={descriptions}>
- {description}
+ {description ?? " "}
</ComboboxItemDescription>
)}
</ComboboxListbox>
diff --git a/packages/design-system/src/components/dropdown-menu.tsx b/packages/design-system/src/components/dropdown-menu.tsx
index 153b7549b7..453b08ac8d 100644
--- a/packages/design-system/src/components/dropdown-menu.tsx
+++ b/packages/design-system/src/components/dropdown-menu.tsx
@@ -1,12 +1,16 @@
import {
forwardRef,
+ useState,
+ useEffect,
type ComponentProps,
type ElementRef,
type ReactElement,
type ReactNode,
} from "react";
+import { mergeRefs } from "@react-aria/utils";
import { ChevronRightIcon } from "@webstudio-is/icons";
import { styled } from "../stitches.config";
+import { focusFirstCollectionItem } from "../utilities";
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
import {
menuCss,
@@ -32,14 +36,26 @@ const DropdownMenuContentStyled = styled(
);
export const DropdownMenuContent = forwardRef<
ElementRef<typeof DropdownMenuContentStyled>,
- ComponentProps<typeof DropdownMenuContentStyled>
->((props, ref) => {
+ ComponentProps<typeof DropdownMenuContentStyled> & { autoFocus?: boolean }
+>(({ autoFocus, ...props }, forwardedRef) => {
+ const [node, setNode] = useState<HTMLDivElement | null>(null);
+
+ useEffect(() => {
+ if (autoFocus && node) {
+ focusFirstCollectionItem(node);
+ }
+ }, [autoFocus, node]);
+
return (
<DropdownMenuPrimitive.Portal>
- <DropdownMenuContentStyled {...props} ref={ref} />
+ <DropdownMenuContentStyled
+ {...props}
+ ref={mergeRefs(forwardedRef, setNode)}
+ />
</DropdownMenuPrimitive.Portal>
);
});
+DropdownMenuContent.displayName = "DropdownMenuContent";
const SubContentStyled = styled(DropdownMenuPrimitive.SubContent, subMenuCss);
export const DropdownMenuSubContent = forwardRef<
diff --git a/packages/design-system/src/utilities.ts b/packages/design-system/src/utilities.ts
index bb134122a4..aba6c11e1a 100644
--- a/packages/design-system/src/utilities.ts
+++ b/packages/design-system/src/utilities.ts
@@ -163,3 +163,16 @@ export const useDebounceEffect = () => {
setUpdateCallback(() => callback);
}, []);
};
+
+/**
+ * Radix may steal focus back to the previously focused element
+ * when opening popovers/dropdowns. This ensures the newly opened UI gets focus.
+ */
+export const focusFirstCollectionItem = (container: HTMLElement) => {
+ requestAnimationFrame(() => {
+ const firstItem = container.querySelector("[data-radix-collection-item]");
+ if (firstItem instanceof HTMLElement) {
+ firstItem.focus();
+ }
+ });
+};