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: Manage CSS variables (#5490)

Oleg Isonen326007bafa33
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsx
index 813101e7ea..11aefceaa7 100644
--- a/apps/builder/app/builder/builder.tsx
+++ b/apps/builder/app/builder/builder.tsx
@@ -61,6 +61,7 @@ import { mergeRefs } from "@react-aria/utils";
import { CommandPanel } from "./features/command-panel";
import { DeleteUnusedTokensDialog } from "~/builder/shared/style-source-utils";
import { DeleteUnusedDataVariablesDialog } from "~/builder/shared/data-variable-utils";
+import { DeleteUnusedCssVariablesDialog } from "~/builder/shared/css-variable-utils";
import {
initCopyPaste,
@@ -443,6 +444,7 @@ export const Builder = ({
<CommandPanel />
<DeleteUnusedTokensDialog />
<DeleteUnusedDataVariablesDialog />
+ <DeleteUnusedCssVariablesDialog />
<RemoteDialog />
</div>
</TooltipProvider>
diff --git a/apps/builder/app/builder/features/command-panel/command-state.ts b/apps/builder/app/builder/features/command-panel/command-state.ts
index 6779a45c69..f85d4e4a5f 100644
--- a/apps/builder/app/builder/features/command-panel/command-state.ts
+++ b/apps/builder/app/builder/features/command-panel/command-state.ts
@@ -42,3 +42,12 @@ export const closeCommandPanel = ({
export const $commandContent = atom<ReactNode>();
export const $commandSearch = atom("");
+
+export const focusCommandPanel = () => {
+ requestAnimationFrame(() => {
+ const input = document.querySelector<HTMLInputElement>(
+ "[cmdk-root] [cmdk-input]"
+ );
+ input?.focus();
+ });
+};
diff --git a/apps/builder/app/builder/features/command-panel/groups/css-variables-group.tsx b/apps/builder/app/builder/features/command-panel/groups/css-variables-group.tsx
new file mode 100644
index 0000000000..9bf6f3a2d2
--- /dev/null
+++ b/apps/builder/app/builder/features/command-panel/groups/css-variables-group.tsx
@@ -0,0 +1,194 @@
+import { useState } from "react";
+import { computed } from "nanostores";
+import { useStore } from "@nanostores/react";
+import {
+ CommandGroup,
+ CommandGroupHeading,
+ CommandItem,
+ Text,
+ toast,
+ useSelectedAction,
+ useResetActionIndex,
+} from "@webstudio-is/design-system";
+import type { Instance } from "@webstudio-is/sdk";
+import type { CssProperty } from "@webstudio-is/css-engine";
+import {
+ DeleteCssVariableDialog,
+ RenameCssVariableDialog,
+ $usedCssVariablesInInstances,
+ $cssVariableInstancesByVariable,
+ $cssVariableDefinitionsByVariable,
+} from "~/builder/shared/css-variable-utils";
+import { deleteProperty } from "~/builder/features/style-panel/shared/use-style-data";
+import { InstanceList, showInstance } from "../shared/instance-list";
+import {
+ $commandContent,
+ closeCommandPanel,
+ focusCommandPanel,
+} from "../command-state";
+import type { BaseOption } from "../shared/types";
+import { getInstanceLabel } from "~/builder/shared/instance-label";
+import { $instances } from "~/shared/nano-states";
+import { $registeredComponentMetas } from "~/shared/nano-states";
+
+export type CssVariableOption = BaseOption & {
+ type: "cssVariable";
+ property: string;
+ instanceId: Instance["id"];
+ usages: number;
+};
+
+export const $cssVariableOptions = computed(
+ [
+ $cssVariableDefinitionsByVariable,
+ $usedCssVariablesInInstances,
+ $instances,
+ $registeredComponentMetas,
+ ],
+ (definitionsByVariable, usedVariablesInInstances, instances, metas) => {
+ const cssVariableOptions: CssVariableOption[] = [];
+
+ // Create options for each defined CSS variable on each instance
+ for (const [property, instanceIds] of definitionsByVariable) {
+ for (const instanceId of instanceIds) {
+ const instance = instances.get(instanceId);
+ if (!instance) {
+ continue;
+ }
+ const meta = metas.get(instance.component);
+ const instanceLabel = getInstanceLabel(instance, meta);
+
+ cssVariableOptions.push({
+ terms: [
+ "css variables",
+ property,
+ property.slice(2), // Include name without --
+ instanceLabel,
+ ],
+ type: "cssVariable",
+ property,
+ instanceId,
+ usages: usedVariablesInInstances.get(property) ?? 0,
+ });
+ }
+ }
+
+ return cssVariableOptions;
+ }
+);
+
+const CssVariableInstances = ({ property }: { property: string }) => {
+ const instancesByVariable = useStore($cssVariableInstancesByVariable);
+ const usedInInstanceIds = instancesByVariable.get(property) ?? new Set();
+
+ return (
+ <InstanceList
+ instanceIds={usedInInstanceIds}
+ onSelect={(instanceId) => {
+ showInstance(instanceId, "style");
+ closeCommandPanel();
+ }}
+ />
+ );
+};
+
+export const CssVariablesGroup = ({
+ options,
+}: {
+ options: CssVariableOption[];
+}) => {
+ const action = useSelectedAction();
+ const resetActionIndex = useResetActionIndex();
+ const instances = useStore($instances);
+ const metas = useStore($registeredComponentMetas);
+ const [variableDialog, setVariableDialog] = useState<
+ { action: "rename" | "delete"; property: string } | undefined
+ >();
+
+ return (
+ <>
+ <CommandGroup
+ name="cssVariable"
+ heading={<CommandGroupHeading>CSS Variables</CommandGroupHeading>}
+ actions={["select", "find usages", "rename", "delete"]}
+ >
+ {options.map(({ property, instanceId, usages }) => {
+ const instance = instances.get(instanceId);
+ const meta = instance ? metas.get(instance.component) : undefined;
+ const instanceLabel = instance
+ ? getInstanceLabel(instance, meta)
+ : "";
+
+ return (
+ <CommandItem
+ keywords={["test"]}
+ key={`${property}-${instanceId}`}
+ // preserve selected state when rerender
+ value={`${property}-${instanceId}`}
+ onSelect={() => {
+ if (action === "select") {
+ showInstance(instanceId, "style");
+ closeCommandPanel();
+ }
+ if (action === "find usages") {
+ $commandContent.set(
+ <CssVariableInstances property={property} />
+ );
+ }
+ if (action === "rename") {
+ setVariableDialog({ action: "rename", property });
+ }
+ if (action === "delete") {
+ setVariableDialog({ action: "delete", property });
+ }
+ }}
+ >
+ <Text>
+ {property}{" "}
+ <Text as="span" color="moreSubtle">
+ {usages === 0
+ ? "unused"
+ : `${usages} ${usages === 1 ? "usage" : "usages"}`}
+ </Text>
+ </Text>
+ <Text as="span" color="moreSubtle">
+ {instanceLabel}
+ </Text>
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ <RenameCssVariableDialog
+ cssVariable={
+ variableDialog?.action === "rename" ? variableDialog : undefined
+ }
+ onClose={() => {
+ setVariableDialog(undefined);
+ resetActionIndex();
+ focusCommandPanel();
+ }}
+ onConfirm={(_oldProperty, newProperty) => {
+ toast.success(
+ `CSS variable renamed from "${variableDialog?.property}" to "${newProperty}"`
+ );
+ setVariableDialog(undefined);
+ }}
+ />
+ <DeleteCssVariableDialog
+ cssVariable={
+ variableDialog?.action === "delete" ? variableDialog : undefined
+ }
+ onClose={() => {
+ setVariableDialog(undefined);
+ resetActionIndex();
+ focusCommandPanel();
+ }}
+ onConfirm={(property) => {
+ deleteProperty(property as CssProperty);
+ toast.success(`CSS variable "${variableDialog?.property}" deleted`);
+ setVariableDialog(undefined);
+ }}
+ />
+ </>
+ );
+};
diff --git a/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx b/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx
index 99deb21ff3..5125c1c353 100644
--- a/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx
@@ -1,5 +1,6 @@
import { useState } from "react";
import { computed } from "nanostores";
+import { useStore } from "@nanostores/react";
import {
CommandGroup,
CommandGroupHeading,
@@ -7,12 +8,15 @@ import {
Text,
toast,
useSelectedAction,
+ useResetActionIndex,
} from "@webstudio-is/design-system";
-import { $instances, $dataSources } from "~/shared/nano-states";
-import { selectInstance as selectInstanceBySelector } from "~/shared/awareness";
-import { $activeInspectorPanel } from "~/builder/shared/nano-states";
-import { $commandContent, closeCommandPanel } from "../command-state";
-import { InstanceList, selectInstance } from "../shared/instance-list";
+import { $dataSources, $instances } from "~/shared/nano-states";
+import {
+ $commandContent,
+ closeCommandPanel,
+ focusCommandPanel,
+} from "../command-state";
+import { InstanceList, showInstance } from "../shared/instance-list";
import { deleteVariableMutable } from "~/shared/data-variables";
import { updateWebstudioData } from "~/shared/instance-utils";
import {
@@ -21,6 +25,8 @@ import {
$usedVariablesInInstances,
} from "~/builder/shared/data-variable-utils";
import type { BaseOption } from "../shared/types";
+import { getInstanceLabel } from "~/builder/shared/instance-label";
+import { $registeredComponentMetas } from "~/shared/nano-states";
export type DataVariableOption = BaseOption & {
type: "dataVariable";
@@ -31,8 +37,13 @@ export type DataVariableOption = BaseOption & {
};
export const $dataVariableOptions = computed(
- [$dataSources, $instances, $usedVariablesInInstances],
- (dataSources, instances, usedInInstances) => {
+ [
+ $dataSources,
+ $instances,
+ $usedVariablesInInstances,
+ $registeredComponentMetas,
+ ],
+ (dataSources, instances, usedInInstances, metas) => {
const dataVariableOptions: DataVariableOption[] = [];
for (const dataSource of dataSources.values()) {
@@ -42,9 +53,17 @@ export const $dataVariableOptions = computed(
) {
const instance = instances.get(dataSource.scopeInstanceId);
if (instance) {
+ const meta = metas.get(instance.component);
+ const instanceLabel = getInstanceLabel(instance, meta);
const usages = usedInInstances.get(dataSource.id)?.size ?? 0;
dataVariableOptions.push({
- terms: ["variable", "variables", "data", dataSource.name],
+ terms: [
+ "variable",
+ "variables",
+ "data",
+ dataSource.name,
+ instanceLabel,
+ ],
type: "dataVariable",
id: dataSource.id,
name: dataSource.name,
@@ -67,8 +86,8 @@ const DataVariableInstances = ({ variableId }: { variableId: string }) => {
<InstanceList
instanceIds={instanceIds}
onSelect={(instanceId) => {
- selectInstance(instanceId);
- $activeInspectorPanel.set("settings");
+ showInstance(instanceId, "settings");
+ closeCommandPanel();
}}
/>
);
@@ -80,90 +99,95 @@ export const DataVariablesGroup = ({
options: DataVariableOption[];
}) => {
const action = useSelectedAction();
- const [variableToRename, setVariableToRename] =
- useState<DataVariableOption>();
- const [variableToDelete, setVariableToDelete] =
- useState<DataVariableOption>();
-
- const handleSelect = (option: DataVariableOption) => {
- if (action === "find") {
- if (option.usages > 0) {
- $commandContent.set(<DataVariableInstances variableId={option.id} />);
- } else {
- toast.error("Variable is not used in any instance");
- }
- return;
- }
-
- if (action === "rename") {
- setVariableToRename(option);
- return;
- }
-
- if (action === "delete") {
- setVariableToDelete(option);
- return;
- }
-
- closeCommandPanel();
-
- // Find the instance selector
- const instanceSelector: string[] = [option.instanceId];
-
- // Select the instance
- selectInstanceBySelector(instanceSelector);
-
- // Switch to settings tab
- $activeInspectorPanel.set("settings");
- };
+ const resetActionIndex = useResetActionIndex();
+ const instances = useStore($instances);
+ const metas = useStore($registeredComponentMetas);
+ const [variableDialog, setVariableDialog] = useState<
+ (DataVariableOption & { action: "rename" | "delete" }) | undefined
+ >();
return (
<>
<CommandGroup
name="dataVariable"
heading={<CommandGroupHeading>Data variables</CommandGroupHeading>}
- actions={["find", "select", "rename", "delete"]}
+ actions={["select", "find usages", "rename", "delete"]}
>
- {options.map((option) => (
- <CommandItem
- key={option.id}
- value={option.id}
- onSelect={() => handleSelect(option)}
- >
- <Text variant="labelsSentenceCase">
- {option.name}{" "}
+ {options.map((option) => {
+ const instance = instances.get(option.instanceId);
+ const meta = instance ? metas.get(instance.component) : undefined;
+ const instanceLabel = instance
+ ? getInstanceLabel(instance, meta)
+ : "";
+
+ return (
+ <CommandItem
+ key={option.id}
+ value={option.id}
+ onSelect={() => {
+ if (action === "select") {
+ showInstance(option.instanceId, "settings");
+ closeCommandPanel();
+ }
+ if (action === "find usages") {
+ $commandContent.set(
+ <DataVariableInstances variableId={option.id} />
+ );
+ }
+ if (action === "rename") {
+ setVariableDialog({ ...option, action: "rename" });
+ }
+ if (action === "delete") {
+ setVariableDialog({ ...option, action: "delete" });
+ }
+ }}
+ >
+ <Text variant="labelsSentenceCase">
+ {option.name}{" "}
+ <Text as="span" color="moreSubtle">
+ {option.usages === 0
+ ? "unused"
+ : `${option.usages} ${option.usages === 1 ? "usage" : "usages"}`}
+ </Text>
+ </Text>
<Text as="span" color="moreSubtle">
- {option.usages === 0
- ? "unused"
- : `${option.usages} ${option.usages === 1 ? "usage" : "usages"}`}
+ {instanceLabel}
</Text>
- </Text>
- </CommandItem>
- ))}
+ </CommandItem>
+ );
+ })}
</CommandGroup>
<RenameDataVariableDialog
- variable={variableToRename}
+ variable={
+ variableDialog?.action === "rename" ? variableDialog : undefined
+ }
onClose={() => {
- setVariableToRename(undefined);
+ setVariableDialog(undefined);
+ resetActionIndex();
+ focusCommandPanel();
}}
onConfirm={(_variableId, newName) => {
toast.success(
- `Variable renamed from "${variableToRename?.name}" to "${newName}"`
+ `Variable renamed from "${variableDialog?.name}" to "${newName}"`
);
- setVariableToRename(undefined);
+ setVariableDialog(undefined);
}}
/>
<DeleteDataVariableDialog
- variable={variableToDelete}
+ variable={
+ variableDialog?.action === "delete" ? variableDialog : undefined
+ }
onClose={() => {
- setVariableToDelete(undefined);
+ setVariableDialog(undefined);
+ resetActionIndex();
+ focusCommandPanel();
}}
onConfirm={(variableId) => {
updateWebstudioData((data) => {
deleteVariableMutable(data, variableId);
});
- toast.success(`Variable "${variableToDelete?.name}" deleted`);
- setVariableToDelete(undefined);
+ toast.success(`Variable "${variableDialog?.name}" deleted`);
+ setVariableDialog(undefined);
}}
/>
</>
diff --git a/apps/builder/app/builder/features/command-panel/groups/index.ts b/apps/builder/app/builder/features/command-panel/groups/index.ts
index c9a43cba9a..e4f0e08a00 100644
--- a/apps/builder/app/builder/features/command-panel/groups/index.ts
+++ b/apps/builder/app/builder/features/command-panel/groups/index.ts
@@ -22,6 +22,11 @@ import {
DataVariablesGroup,
type DataVariableOption,
} from "./data-variables-group";
+import {
+ $cssVariableOptions,
+ CssVariablesGroup,
+ type CssVariableOption,
+} from "./css-variables-group";
export type Option =
| ComponentOption
@@ -30,7 +35,8 @@ export type Option =
| PageOption
| CommandOption
| TokenOption
- | DataVariableOption;
+ | DataVariableOption
+ | CssVariableOption;
export type OptionByType<T extends Option["type"]> = Extract<
Option,
@@ -46,6 +52,7 @@ export const $allOptions = computed(
$commandOptions,
$tokenOptions,
$dataVariableOptions,
+ $cssVariableOptions,
],
(
componentOptions,
@@ -54,7 +61,8 @@ export const $allOptions = computed(
pageOptions,
commandOptions,
tokenOptions,
- dataVariableOptions
+ dataVariableOptions,
+ cssVariableOptions
) => [
...componentOptions,
...tagOptions,
@@ -63,6 +71,7 @@ export const $allOptions = computed(
...commandOptions,
...tokenOptions,
...dataVariableOptions,
+ ...cssVariableOptions,
]
);
@@ -80,6 +89,7 @@ export const groups: {
command: CommandsGroup,
token: TokensGroup,
dataVariable: DataVariablesGroup,
+ cssVariable: CssVariablesGroup,
};
export type {
@@ -90,6 +100,7 @@ export type {
CommandOption,
TokenOption,
DataVariableOption,
+ CssVariableOption,
};
export {
@@ -100,4 +111,5 @@ export {
CommandsGroup,
TokensGroup,
DataVariablesGroup,
+ CssVariablesGroup,
};
diff --git a/apps/builder/app/builder/features/command-panel/groups/tokens-group.tsx b/apps/builder/app/builder/features/command-panel/groups/tokens-group.tsx
index e3663fd13c..6099ea3e7d 100644
--- a/apps/builder/app/builder/features/command-panel/groups/tokens-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/tokens-group.tsx
@@ -8,6 +8,7 @@ import {
Text,
toast,
useSelectedAction,
+ useResetActionIndex,
} from "@webstudio-is/design-system";
import type { Instance, StyleSource } from "@webstudio-is/sdk";
import { $selectedStyleSources, $styleSources } from "~/shared/nano-states";
@@ -17,11 +18,12 @@ import {
RenameStyleSourceDialog,
$styleSourceUsages,
} from "~/builder/shared/style-source-utils";
-import { findInstanceById } from "../shared/instance-utils";
-import { InstanceList } from "../shared/instance-list";
-import { $instances, $pages } from "~/shared/nano-states";
-import { $awareness } from "~/shared/awareness";
-import { $commandContent } from "../command-state";
+import { InstanceList, showInstance } from "../shared/instance-list";
+import {
+ $commandContent,
+ closeCommandPanel,
+ focusCommandPanel,
+} from "../command-state";
import type { BaseOption } from "../shared/types";
export type TokenOption = BaseOption & {
@@ -53,26 +55,10 @@ const selectToken = (
instanceId: Instance["id"],
tokenId: StyleSource["id"]
) => {
- const instances = $instances.get();
- const pagesData = $pages.get();
- if (pagesData === undefined) {
- return;
- }
- const pages = [pagesData.homePage, ...pagesData.pages];
- for (const page of pages) {
- const instanceSelector = findInstanceById(
- instances,
- [page.rootInstanceId],
- instanceId
- );
- if (instanceSelector) {
- $awareness.set({ pageId: page.id, instanceSelector });
- const selectedStyleSources = new Map($selectedStyleSources.get());
- selectedStyleSources.set(instanceId, tokenId);
- $selectedStyleSources.set(selectedStyleSources);
- break;
- }
- }
+ showInstance(instanceId, "style");
+ const selectedStyleSources = new Map($selectedStyleSources.get());
+ selectedStyleSources.set(instanceId, tokenId);
+ $selectedStyleSources.set(selectedStyleSources);
};
const TokenInstances = ({ tokenId }: { tokenId: StyleSource["id"] }) => {
@@ -82,17 +68,23 @@ const TokenInstances = ({ tokenId }: { tokenId: StyleSource["id"] }) => {
return (
<InstanceList
instanceIds={usedInInstanceIds}
- onSelect={(instanceId) => selectToken(instanceId, tokenId)}
+ onSelect={(instanceId) => {
+ selectToken(instanceId, tokenId);
+ closeCommandPanel();
+ }}
/>
);
};
export const TokensGroup = ({ options }: { options: TokenOption[] }) => {
const action = useSelectedAction();
- const [tokenToRename, setTokenToRename] =
- useState<Extract<StyleSource, { type: "token" }>>();
- const [tokenToDelete, setTokenToDelete] =
- useState<Extract<StyleSource, { type: "token" }>>();
+ const resetActionIndex = useResetActionIndex();
+ const [tokenDialog, setTokenDialog] = useState<
+ | (Extract<StyleSource, { type: "token" }> & {
+ action: "rename" | "delete";
+ })
+ | undefined
+ >();
return (
<>
@@ -108,17 +100,13 @@ export const TokensGroup = ({ options }: { options: TokenOption[] }) => {
value={token.id}
onSelect={() => {
if (action === "find") {
- if (usages > 0) {
- $commandContent.set(<TokenInstances tokenId={token.id} />);
- } else {
- toast.error("Token is not used in any instance");
- }
+ $commandContent.set(<TokenInstances tokenId={token.id} />);
}
if (action === "rename") {
- setTokenToRename(token);
+ setTokenDialog({ ...token, action: "rename" });
}
if (action === "delete") {
- setTokenToDelete(token);
+ setTokenDialog({ ...token, action: "delete" });
}
}}
>
@@ -134,26 +122,30 @@ export const TokensGroup = ({ options }: { options: TokenOption[] }) => {
))}
</CommandGroup>
<RenameStyleSourceDialog
- styleSource={tokenToRename}
+ styleSource={tokenDialog?.action === "rename" ? tokenDialog : undefined}
onClose={() => {
- setTokenToRename(undefined);
+ setTokenDialog(undefined);
+ resetActionIndex();
+ focusCommandPanel();
}}
onConfirm={(_styleSourceId, newName) => {
toast.success(
- `Token renamed from "${tokenToRename?.name}" to "${newName}"`
+ `Token renamed from "${tokenDialog?.name}" to "${newName}"`
);
- setTokenToRename(undefined);
+ setTokenDialog(undefined);
}}
/>
<DeleteStyleSourceDialog
- styleSource={tokenToDelete}
+ styleSource={tokenDialog?.action === "delete" ? tokenDialog : undefined}
onClose={() => {
- setTokenToDelete(undefined);
+ setTokenDialog(undefined);
+ resetActionIndex();
+ focusCommandPanel();
}}
onConfirm={(styleSourceId) => {
deleteStyleSource(styleSourceId);
- toast.success(`Token "${tokenToDelete?.name}" deleted`);
- setTokenToDelete(undefined);
+ toast.success(`Token "${tokenDialog?.name}" deleted`);
+ setTokenDialog(undefined);
}}
/>
</>
diff --git a/apps/builder/app/builder/features/command-panel/shared/instance-list.tsx b/apps/builder/app/builder/features/command-panel/shared/instance-list.tsx
index 849701dbde..0f0577d735 100644
--- a/apps/builder/app/builder/features/command-panel/shared/instance-list.tsx
+++ b/apps/builder/app/builder/features/command-panel/shared/instance-list.tsx
@@ -19,9 +19,9 @@ import {
$registeredComponentMetas,
} from "~/shared/nano-states";
import { getInstanceLabel } from "~/builder/shared/instance-label";
-import { $awareness } from "~/shared/awareness";
-import { $commandContent, closeCommandPanel } from "../command-state";
-import { findInstanceById } from "../shared/instance-utils";
+import { $awareness, findAwarenessByInstanceId } from "~/shared/awareness";
+import { $commandContent } from "../command-state";
+import { $activeInspectorPanel } from "~/builder/shared/nano-states";
export type InstanceOption = {
label: string;
@@ -92,7 +92,6 @@ export const InstanceList = ({ instanceIds, onSelect }: InstanceListProps) => {
value={id}
onSelect={() => {
onSelect(id);
- closeCommandPanel();
}}
>
<Text variant="labelsTitleCase">{label}</Text>
@@ -114,22 +113,18 @@ export const InstanceList = ({ instanceIds, onSelect }: InstanceListProps) => {
);
};
-export const selectInstance = (instanceId: Instance["id"]) => {
+export const showInstance = (
+ instanceId: Instance["id"],
+ panel?: "style" | "settings"
+) => {
const instances = $instances.get();
const pagesData = $pages.get();
if (pagesData === undefined) {
return;
}
- const pages = [pagesData.homePage, ...pagesData.pages];
- for (const page of pages) {
- const instanceSelector = findInstanceById(
- instances,
- [page.rootInstanceId],
- instanceId
- );
- if (instanceSelector) {
- $awareness.set({ pageId: page.id, instanceSelector });
- break;
- }
+ const awareness = findAwarenessByInstanceId(pagesData, instances, instanceId);
+ $awareness.set(awareness);
+ if (panel !== undefined) {
+ $activeInspectorPanel.set(panel);
}
};
diff --git a/apps/builder/app/builder/features/command-panel/shared/instance-utils.ts b/apps/builder/app/builder/features/command-panel/shared/instance-utils.ts
deleted file mode 100644
index c0fb8ed3db..0000000000
--- a/apps/builder/app/builder/features/command-panel/shared/instance-utils.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import type { Instance, Instances } from "@webstudio-is/sdk";
-import type { InstanceSelector } from "~/shared/tree-utils";
-
-/**
- * Very loose selector finder
- * Will not work properly with collections
- */
-export const findInstanceById = (
- instances: Instances,
- instanceSelector: InstanceSelector,
- targetId: Instance["id"]
-): undefined | InstanceSelector => {
- const [instanceId] = instanceSelector;
- if (instanceId === targetId) {
- return instanceSelector;
- }
- const instance = instances.get(instanceId);
- if (instance) {
- for (const child of instance.children) {
- if (child.type === "id") {
- const matched = findInstanceById(
- instances,
- [child.value, ...instanceSelector],
- targetId
- );
- if (matched) {
- return matched;
- }
- }
- }
- }
-};
diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.ts
index 7986ae5c76..6995f6d522 100644
--- a/apps/builder/app/builder/shared/commands.ts
+++ b/apps/builder/app/builder/shared/commands.ts
@@ -59,6 +59,7 @@ import { reactPropsToStandardAttributes } from "@webstudio-is/react-sdk";
import { isSyncIdle } from "./sync/sync-server";
import { openDeleteUnusedTokensDialog } from "~/builder/shared/style-source-utils";
import { openDeleteUnusedDataVariablesDialog } from "~/builder/shared/data-variable-utils";
+import { openDeleteUnusedCssVariablesDialog } from "~/builder/shared/css-variable-utils";
export const $styleSourceInputElement = atom<HTMLInputElement | undefined>();
@@ -677,5 +678,13 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
openDeleteUnusedDataVariablesDialog();
},
},
+
+ {
+ name: "deleteUnusedCssVariables",
+ label: "Delete unused CSS variables",
+ handler: () => {
+ openDeleteUnusedCssVariablesDialog();
+ },
+ },
],
});
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 8f77054b89..21c3725e5e 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
@@ -36,6 +36,8 @@ import {
} from "~/builder/features/style-panel/shared/use-style-data";
import { $availableVariables } from "~/builder/features/style-panel/shared/model";
import { parseStyleInput } from "./parse-style-input";
+import { validateCssVariableName } from "~/builder/shared/css-variable-utils";
+import { toast } from "@webstudio-is/design-system";
type SearchItem = {
property: string;
@@ -227,6 +229,18 @@ export const AddStyleInput = forwardRef<
const handleEnter = (event: KeyboardEvent) => {
if (event.key === "Enter") {
+ const property = item.property.split(":")[0].trim();
+
+ // Validate CSS variable names before creating them
+ if (property.startsWith("--")) {
+ const error = validateCssVariableName(property);
+ if (error) {
+ // Show error via toast
+ toast.error(error.message);
+ return;
+ }
+ }
+
clear();
onSubmit(item.property);
}
diff --git a/apps/builder/app/builder/shared/css-variable-utils.test.tsx b/apps/builder/app/builder/shared/css-variable-utils.test.tsx
new file mode 100644
index 0000000000..2e9cdfffaf
--- /dev/null
+++ b/apps/builder/app/builder/shared/css-variable-utils.test.tsx
@@ -0,0 +1,952 @@
+import { test, expect, describe } from "vitest";
+import { atom } from "nanostores";
+import { $styles } from "~/shared/nano-states";
+import {
+ findCssVariableUsagesByInstance,
+ validateCssVariableName,
+ performCssVariableRename,
+ updateVarReferencesInProps,
+} from "./css-variable-utils";
+import type { StyleDecl, Styles, Prop } from "@webstudio-is/sdk";
+import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";
+import { parseCssValue } from "@webstudio-is/css-data";
+
+// Mock the nano-states module
+const mockStyles = atom<Styles>(new Map());
+
+// Replace the actual store with our mock
+Object.defineProperty($styles, "get", {
+ value: () => mockStyles.get(),
+});
+
+// Helper to create a StyleDecl
+const createStyleDecl = (
+ styleSourceId: string,
+ breakpointId: string,
+ property: string,
+ value: string
+): StyleDecl => ({
+ styleSourceId,
+ breakpointId,
+ property: property as StyleProperty,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ value: parseCssValue(property as any, value),
+});
+
+describe("validateCssVariableName", () => {
+ test("returns required error for empty name", () => {
+ mockStyles.set(new Map());
+
+ const error = validateCssVariableName("");
+ expect(error).toEqual({
+ type: "required",
+ message: "CSS variable name cannot be empty",
+ });
+ });
+
+ test("returns required error for whitespace-only name", () => {
+ mockStyles.set(new Map());
+
+ const error = validateCssVariableName(" ");
+ expect(error).toEqual({
+ type: "required",
+ message: "CSS variable name cannot be empty",
+ });
+ });
+
+ test("returns invalid error for name without --", () => {
+ mockStyles.set(new Map());
+
+ const error = validateCssVariableName("my-color");
+ expect(error).toEqual({
+ type: "invalid",
+ message: 'CSS variable name must start with "--"',
+ });
+ });
+
+ test("returns undefined for valid unique name", () => {
+ const styles = new Map([
+ [
+ "local1:base:--existing::",
+ createStyleDecl("local1", "base", "--existing", "red"),
+ ],
+ ]);
+ mockStyles.set(styles);
+
+ const error = validateCssVariableName("--new-color");
+ expect(error).toBeUndefined();
+ });
+
+ test("returns duplicate error for existing name", () => {
+ const styles = new Map([
+ [
+ "local1:base:--my-color::",
+ createStyleDecl("local1", "base", "--my-color", "red"),
+ ],
+ ]);
+ mockStyles.set(styles);
+
+ const error = validateCssVariableName("--my-color");
+ expect(error).toEqual({
+ type: "duplicate",
+ message: 'CSS variable "--my-color" already exists',
+ });
+ });
+
+ test("allows renaming variable to same name", () => {
+ const styles = new Map([
+ [
+ "local1:base:--my-color::",
+ createStyleDecl("local1", "base", "--my-color", "red"),
+ ],
+ ]);
+ mockStyles.set(styles);
+
+ const error = validateCssVariableName("--my-color", "--my-color");
+ expect(error).toBeUndefined();
+ });
+});
+
+describe("findCssVariableUsagesByInstance", () => {
+ test("does not track definitions", () => {
+ const styleSourceSelections = new Map([
+ [
+ "box1",
+ {
+ instanceId: "box1",
+ values: ["local1"],
+ },
+ ],
+ ]);
+
+ const styles = new Map([
+ [
+ "local1:base:--my-color::",
+ createStyleDecl("local1", "base", "--my-color", "red"),
+ ],
+ ]);
+
+ const { counts, instances } = findCssVariableUsagesByInstance({
+ styleSourceSelections,
+ styles,
+ props: new Map(),
+ });
+
+ // Should not track definitions, only var() references
+ expect(counts.size).toBe(0);
+ expect(instances.size).toBe(0);
+ });
+
+ test("tracks var() references", () => {
+ const styleSourceSelections = new Map([
+ [
+ "box1",
+ {
+ instanceId: "box1",
+ values: ["local1"],
+ },
+ ],
+ [
+ "box2",
+ {
+ instanceId: "box2",
+ values: ["local2"],
+ },
+ ],
+ ]);
+
+ const styles = new Map([
+ [
+ "local1:base:--primary-color::",
+ createStyleDecl("local1", "base", "--primary-color", "blue"),
+ ],
+ [
+ "local2:base:color::",
+ createStyleDecl("local2", "base", "color", "var(--primary-color)"),
+ ],
+ ]);
+
+ const { counts, instances } = findCssVariableUsagesByInstance({
+ styleSourceSelections,
+ styles,
+ props: new Map(),
+ });
+
+ expect(counts.size).toBe(1);
+ expect(counts.get("--primary-color")).toBe(1);
+ expect(instances.get("--primary-color")).toEqual(new Set(["box2"]));
+ });
+
+ test("tracks only var() references not definitions", () => {
+ const styleSourceSelections = new Map([
+ [
+ "box1",
+ {
+ instanceId: "box1",
+ values: ["local1"],
+ },
+ ],
+ [
+ "box2",
+ {
+ instanceId: "box2",
+ values: ["local2"],
+ },
+ ],
+ [
+ "box3",
+ {
+ instanceId: "box3",
+ values: ["local3"],
+ },
+ ],
+ ]);
+
+ const styles = new Map([
+ // box1 defines --color
+ [
+ "local1:base:--color::",
+ createStyleDecl("local1", "base", "--color", "red"),
+ ],
+ // box2 uses --color
+ [
+ "local2:base:backgroundColor::",
+ createStyleDecl("local2", "base", "backgroundColor", "var(--color)"),
+ ],
+ // box3 defines and uses --color
+ [
+ "local3:base:--color::",
+ createStyleDecl("local3", "base", "--color", "blue"),
+ ],
+ [
+ "local3:base:color::",
+ createStyleDecl("local3", "base", "color", "var(--color)"),
+ ],
+ ]);
+
+ const { counts, instances } = findCssVariableUsagesByInstance({
+ styleSourceSelections,
+ styles,
+ props: new Map(),
+ });
+
+ expect(counts.size).toBe(1);
+ expect(counts.get("--color")).toBe(2);
+ // Only box2 and box3 use var(--color), box1 only defines it
+ expect(instances.get("--color")).toEqual(new Set(["box2", "box3"]));
+ });
+
+ test("handles multiple variables", () => {
+ const styleSourceSelections = new Map([
+ [
+ "box1",
+ {
+ instanceId: "box1",
+ values: ["local1"],
+ },
+ ],
+ ]);
+
+ const styles = new Map([
+ [
+ "local1:base:--color::",
+ createStyleDecl("local1", "base", "--color", "red"),
+ ],
+ [
+ "local1:base:--size::",
+ createStyleDecl("local1", "base", "--size", "16px"),
+ ],
+ [
+ "local1:base:fontSize::",
+ createStyleDecl("local1", "base", "fontSize", "var(--size)"),
+ ],
+ ]);
+
+ const { counts, instances } = findCssVariableUsagesByInstance({
+ styleSourceSelections,
+ styles,
+ props: new Map(),
+ });
+
+ expect(counts.size).toBe(1);
+ // --color is only defined, not used
+ expect(counts.get("--color")).toBeUndefined();
+ // --size is used via var()
+ expect(counts.get("--size")).toBe(1);
+ expect(instances.get("--size")).toEqual(new Set(["box1"]));
+ });
+
+ test("distinguishes between definition and usage", () => {
+ const styleSourceSelections = new Map([
+ [
+ "definer",
+ {
+ instanceId: "definer",
+ values: ["definerLocal"],
+ },
+ ],
+ [
+ "user",
+ {
+ instanceId: "user",
+ values: ["userLocal"],
+ },
+ ],
+ ]);
+
+ const styles = new Map([
+ // definer instance defines the variable
+ [
+ "definerLocal:base:--theme-color::",
+ createStyleDecl("definerLocal", "base", "--theme-color", "blue"),
+ ],
+ // user instance uses the variable
+ [
+ "userLocal:base:color::",
+ createStyleDecl("userLocal", "base", "color", "var(--theme-color)"),
+ ],
+ ]);
+
+ const { counts, instances } = findCssVariableUsagesByInstance({
+ styleSourceSelections,
+ styles,
+ props: new Map(),
+ });
+
+ expect(counts.size).toBe(1);
+ expect(counts.get("--theme-color")).toBe(1);
+ // Should only track the user, not the definer
+ expect(instances.get("--theme-color")).toEqual(new Set(["user"]));
+ expect(instances.get("--theme-color")?.has("definer")).toBe(false);
+ });
+
+ test("counts multiple references on same instance", () => {
+ const styleSourceSelections = new Map([
+ [
+ "box1",
+ {
+ instanceId: "box1",
+ values: ["local1"],
+ },
+ ],
+ ]);
+
+ const styles = new Map([
+ [
+ "local1:base:--spacing::",
+ createStyleDecl("local1", "base", "--spacing", "16px"),
+ ],
+ // Same instance uses the variable three times
+ [
+ "local1:base:marginTop::",
+ createStyleDecl("local1", "base", "marginTop", "var(--spacing)"),
+ ],
+ [
+ "local1:base:marginBottom::",
+ createStyleDecl("local1", "base", "marginBottom", "var(--spacing)"),
+ ],
+ [
+ "local1:base:padding::",
+ createStyleDecl("local1", "base", "padding", "var(--spacing)"),
+ ],
+ ]);
+
+ const { counts, instances } = findCssVariableUsagesByInstance({
+ styleSourceSelections,
+ styles,
+ props: new Map(),
+ });
+
+ expect(counts.size).toBe(1);
+ // Should count all 3 usages, not just 1
+ expect(counts.get("--spacing")).toBe(3);
+ // But only 1 instance
+ expect(instances.get("--spacing")).toEqual(new Set(["box1"]));
+ });
+
+ test("handles unparsed values with var()", () => {
+ const styleSourceSelections = new Map([
+ [
+ "box1",
+ {
+ instanceId: "box1",
+ values: ["local1"],
+ },
+ ],
+ ]);
+
+ // parseCssValue returns unparsed type for calc() expressions
+ // We don't track var() inside unparsed strings since they're not structured
+ const styles = new Map([
+ [
+ "local1:base:--spacing::",
+ createStyleDecl("local1", "base", "--spacing", "16px"),
+ ],
+ [
+ "local1:base:width::",
+ createStyleDecl("local1", "base", "width", "calc(var(--spacing) * 2)"),
+ ],
+ ]);
+
+ const { counts, instances } = findCssVariableUsagesByInstance({
+ styleSourceSelections,
+ styles,
+ props: new Map(),
+ });
+
+ // Unparsed values are treated as opaque strings, so var() references inside
+ // are not tracked. This is expected behavior.
+ expect(counts.size).toBe(0);
+ expect(instances.size).toBe(0);
+ });
+
+ test("tracks var() in HTML Embed code", () => {
+ const styleSourceSelections = new Map([
+ [
+ "box1",
+ {
+ instanceId: "box1",
+ values: ["local1"],
+ },
+ ],
+ ]);
+
+ const styles = new Map();
+
+ const props = new Map([
+ [
+ "prop1",
+ {
+ id: "prop1",
+ instanceId: "box1",
+ type: "string" as const,
+ name: "code",
+ value: `<style>
+ .my-class {
+ color: var(--primary-color);
+ background: var(--bg-color);
+ }
+ </style>`,
+ },
+ ],
+ ]);
+
+ const { counts, instances } = findCssVariableUsagesByInstance({
+ styleSourceSelections,
+ styles,
+ props,
+ });
+
+ expect(counts.get("--primary-color")).toBe(1);
+ expect(counts.get("--bg-color")).toBe(1);
+ expect(instances.get("--primary-color")?.has("box1")).toBe(true);
+ expect(instances.get("--bg-color")?.has("box1")).toBe(true);
+ });
+});
+
+describe("performCssVariableRename", () => {
+ test("updates property declarations", () => {
+ const styles = new Map<string, StyleDecl>([
+ [
+ "styleSourceId:base:--my-color",
+ {
+ breakpointId: "base",
+ styleSourceId: "styleSourceId",
+ property: "--my-color" as StyleProperty,
+ value: { type: "keyword", value: "red" },
+ },
+ ],
+ ]);
+
+ const result = performCssVariableRename(
+ styles,
+ "--my-color",
+ "--new-color"
+ );
+
+ expect(result.size).toBe(1);
+ const [decl] = Array.from(result.values());
+ expect(decl.property).toBe("--new-color");
+ expect(decl.value).toEqual({ type: "keyword", value: "red" });
+ });
+
+ test("updates var() references", () => {
+ const styles = new Map<string, StyleDecl>([
+ [
+ "styleSourceId:base:--my-color",
+ {
+ breakpointId: "base",
+ styleSourceId: "styleSourceId",
+ property: "--my-color" as StyleProperty,
+ value: { type: "keyword", value: "red" },
+ },
+ ],
+ [
+ "styleSourceId:base:color",
+ {
+ breakpointId: "base",
+ styleSourceId: "styleSourceId",
+ property: "color" as StyleProperty,
+ value: { type: "var", value: "my-color" },
+ },
+ ],
+ ]);
+
+ const result = performCssVariableRename(
+ styles,
+ "--my-color",
+ "--new-color"
+ );
+
+ expect(result.size).toBe(2);
+ const colorDecl = Array.from(result.values()).find(
+ (d) => d.property === "color"
+ );
+ expect(colorDecl?.value).toEqual({ type: "var", value: "new-color" });
+ });
+
+ test("updates nested var() references", () => {
+ const styles = new Map<string, StyleDecl>([
+ [
+ "styleSourceId:base:transform",
+ {
+ breakpointId: "base",
+ styleSourceId: "styleSourceId",
+ property: "transform" as StyleProperty,
+ value: {
+ type: "function",
+ name: "rotate",
+ args: {
+ type: "var",
+ value: "rotation-angle",
+ },
+ } as StyleValue,
+ },
+ ],
+ ]);
+
+ const result = performCssVariableRename(
+ styles,
+ "--rotation-angle",
+ "--angle"
+ );
+
+ const transformDecl = Array.from(result.values())[0];
+ expect(transformDecl.value).toMatchObject({
+ type: "function",
+ name: "rotate",
+ args: {
+ type: "var",
+ value: "angle",
+ },
+ });
+ });
+
+ test("updates array of var() references", () => {
+ const styles = new Map<string, StyleDecl>([
+ [
+ "styleSourceId:base:boxShadow",
+ {
+ breakpointId: "base",
+ styleSourceId: "styleSourceId",
+ property: "boxShadow" as StyleProperty,
+ value: {
+ type: "tuple",
+ value: [
+ { type: "var", value: "shadow-x" },
+ { type: "var", value: "shadow-y" },
+ { type: "var", value: "shadow-color" },
+ ],
+ },
+ },
+ ],
+ ]);
+
+ const result = performCssVariableRename(
+ styles,
+ "--shadow-color",
+ "--color-shadow"
+ );
+
+ const shadowDecl = Array.from(result.values())[0];
+ expect(shadowDecl.value).toMatchObject({
+ type: "tuple",
+ value: [
+ { type: "var", value: "shadow-x" },
+ { type: "var", value: "shadow-y" },
+ { type: "var", value: "color-shadow" },
+ ],
+ });
+ });
+
+ test("handles multiple declarations of same variable", () => {
+ const styles = new Map<string, StyleDecl>([
+ [
+ "styleSourceId1:base:--my-var",
+ {
+ breakpointId: "base",
+ styleSourceId: "styleSourceId1",
+ property: "--my-var" as StyleProperty,
+ value: { type: "keyword", value: "value1" },
+ },
+ ],
+ [
+ "styleSourceId2:base:--my-var",
+ {
+ breakpointId: "base",
+ styleSourceId: "styleSourceId2",
+ property: "--my-var" as StyleProperty,
+ value: { type: "keyword", value: "value2" },
+ },
+ ],
+ ]);
+
+ const result = performCssVariableRename(styles, "--my-var", "--renamed");
+
+ expect(result.size).toBe(2);
+ const decls = Array.from(result.values());
+ expect(decls.every((d) => d.property === "--renamed")).toBe(true);
+ });
+
+ test("does not modify unrelated variables", () => {
+ const styles = new Map<string, StyleDecl>([
+ [
+ "styleSourceId:base:--my-color",
+ {
+ breakpointId: "base",
+ styleSourceId: "styleSourceId",
+ property: "--my-color" as StyleProperty,
+ value: { type: "keyword", value: "red" },
+ },
+ ],
+ [
+ "styleSourceId:base:--other-color",
+ {
+ breakpointId: "base",
+ styleSourceId: "styleSourceId",
+ property: "--other-color" as StyleProperty,
+ value: { type: "keyword", value: "blue" },
+ },
+ ],
+ [
+ "styleSourceId:base:color",
+ {
+ breakpointId: "base",
+ styleSourceId: "styleSourceId",
+ property: "color" as StyleProperty,
+ value: { type: "var", value: "other-color" },
+ },
+ ],
+ ]);
+
+ const result = performCssVariableRename(
+ styles,
+ "--my-color",
+ "--new-color"
+ );
+
+ expect(result.size).toBe(3);
+ const otherColorDecl = Array.from(result.values()).find(
+ (d) => d.property === "--other-color"
+ );
+ expect(otherColorDecl?.property).toBe("--other-color");
+
+ const colorDecl = Array.from(result.values()).find(
+ (d) => d.property === "color"
+ );
+ expect(colorDecl?.value).toEqual({ type: "var", value: "other-color" });
+ });
+
+ test("handles values with no references", () => {
+ const styles = new Map<string, StyleDecl>([
+ [
+ "styleSourceId:base:--my-color",
+ {
+ breakpointId: "base",
+ styleSourceId: "styleSourceId",
+ property: "--my-color" as StyleProperty,
+ value: { type: "keyword", value: "red" },
+ },
+ ],
+ [
+ "styleSourceId:base:fontSize",
+ {
+ breakpointId: "base",
+ styleSourceId: "styleSourceId",
+ property: "fontSize" as StyleProperty,
+ value: { type: "unit", value: 16, unit: "px" },
+ },
+ ],
+ ]);
+
+ const result = performCssVariableRename(
+ styles,
+ "--my-color",
+ "--new-color"
+ );
+
+ expect(result.size).toBe(2);
+ const fontSizeDecl = Array.from(result.values()).find(
+ (d) => d.property === "fontSize"
+ );
+ // Value should be unchanged
+ expect(fontSizeDecl?.value).toEqual({
+ type: "unit",
+ value: 16,
+ unit: "px",
+ });
+ });
+});
+
+describe("renameCssVariable", () => {
+ test("updates var() references in HTML Embed code", () => {
+ const props = new Map([
+ [
+ "prop1",
+ {
+ id: "prop1",
+ instanceId: "embed1",
+ name: "code",
+ type: "string" as const,
+ value: `<style>
+ .custom {
+ color: var(--theme-color);
+ background: var(--theme-color, blue);
+ }
+</style>`,
+ },
+ ],
+ ]);
+
+ const oldProperty = "--theme-color";
+ const newProperty = "--brand-color";
+
+ // Simulate the rename logic for props
+ const regex = new RegExp(
+ `var\\(\\s*${oldProperty.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`,
+ "g"
+ );
+ const prop = props.get("prop1");
+ const updatedValue = prop!.value.replace(regex, `var(${newProperty}`);
+
+ // Verify both occurrences were replaced
+ expect(updatedValue).toContain("var(--brand-color)");
+ expect(updatedValue).not.toContain("var(--theme-color)");
+ expect(updatedValue).toContain("var(--brand-color, blue)");
+
+ // Verify the original had the old name
+ expect(prop!.value).toContain("var(--theme-color)");
+ });
+});
+
+describe("updateVarReferencesInProps", () => {
+ test("updates single var() reference in HTML Embed code", () => {
+ const props = new Map<string, Prop>([
+ [
+ "prop1",
+ {
+ id: "prop1",
+ instanceId: "instance1",
+ name: "code",
+ type: "string",
+ value: '<div style="color: var(--primary)">Text</div>',
+ },
+ ],
+ ]);
+
+ const result = updateVarReferencesInProps(
+ props,
+ "--primary",
+ "--main-color"
+ );
+ const prop = result.get("prop1");
+
+ expect(prop!.value).toBe(
+ '<div style="color: var(--main-color)">Text</div>'
+ );
+ expect(prop!.value).not.toContain("--primary");
+ });
+
+ test("updates multiple occurrences in same prop", () => {
+ const props = new Map<string, Prop>([
+ [
+ "prop1",
+ {
+ id: "prop1",
+ instanceId: "instance1",
+ name: "code",
+ type: "string",
+ value: "var(--color) and var(--color, red)",
+ },
+ ],
+ ]);
+
+ const result = updateVarReferencesInProps(props, "--color", "--new-color");
+ const prop = result.get("prop1");
+
+ expect(prop!.value).toBe("var(--new-color) and var(--new-color, red)");
+ expect(prop!.value).not.toContain("var(--color");
+ });
+
+ test("preserves fallback values", () => {
+ const props = new Map<string, Prop>([
+ [
+ "prop1",
+ {
+ id: "prop1",
+ instanceId: "instance1",
+ name: "code",
+ type: "string",
+ value: "var(--bg, #fff)",
+ },
+ ],
+ ]);
+
+ const result = updateVarReferencesInProps(props, "--bg", "--background");
+ const prop = result.get("prop1");
+
+ expect(prop!.value).toBe("var(--background, #fff)");
+ });
+
+ test("handles special regex characters in variable name", () => {
+ const props = new Map<string, Prop>([
+ [
+ "prop1",
+ {
+ id: "prop1",
+ instanceId: "instance1",
+ name: "code",
+ type: "string",
+ value: "var(--color-$special)",
+ },
+ ],
+ ]);
+
+ const result = updateVarReferencesInProps(
+ props,
+ "--color-$special",
+ "--normal"
+ );
+ const prop = result.get("prop1");
+
+ expect(prop!.value).toBe("var(--normal)");
+ });
+
+ test("does not update when no matches found", () => {
+ const props = new Map<string, Prop>([
+ [
+ "prop1",
+ {
+ id: "prop1",
+ instanceId: "instance1",
+ name: "code",
+ type: "string",
+ value: "var(--other)",
+ },
+ ],
+ ]);
+
+ const result = updateVarReferencesInProps(props, "--primary", "--main");
+ const prop = result.get("prop1");
+
+ expect(prop!.value).toBe("var(--other)");
+ });
+
+ test("ignores non-code props", () => {
+ const props = new Map<string, Prop>([
+ [
+ "prop1",
+ {
+ id: "prop1",
+ instanceId: "instance1",
+ name: "className",
+ type: "string",
+ value: "var(--color)",
+ },
+ ],
+ ]);
+
+ const result = updateVarReferencesInProps(props, "--color", "--new-color");
+ const prop = result.get("prop1");
+
+ // Should not be updated because name is not "code"
+ expect(prop!.value).toBe("var(--color)");
+ });
+
+ test("handles empty props map", () => {
+ const props = new Map<string, Prop>();
+
+ const result = updateVarReferencesInProps(props, "--primary", "--main");
+
+ expect(result.size).toBe(0);
+ });
+
+ test("handles prop with empty value", () => {
+ const props = new Map<string, Prop>([
+ [
+ "prop1",
+ {
+ id: "prop1",
+ instanceId: "instance1",
+ name: "code",
+ type: "string",
+ value: "",
+ },
+ ],
+ ]);
+
+ const result = updateVarReferencesInProps(props, "--color", "--new-color");
+ const prop = result.get("prop1");
+
+ expect(prop!.value).toBe("");
+ });
+
+ test("handles whitespace variations in var()", () => {
+ const props = new Map<string, Prop>([
+ [
+ "prop1",
+ {
+ id: "prop1",
+ instanceId: "instance1",
+ name: "code",
+ type: "string",
+ value: "var( --spacing ) and var( --spacing, 10px)",
+ },
+ ],
+ ]);
+
+ const result = updateVarReferencesInProps(
+ props,
+ "--spacing",
+ "--new-spacing"
+ );
+ const prop = result.get("prop1");
+
+ // Note: The replacement pattern matches "var(\s*--spacing" so whitespace before the old name is consumed
+ // This results in normalized whitespace: "var(--new-spacing"
+ expect(prop!.value).toBe(
+ "var(--new-spacing ) and var(--new-spacing, 10px)"
+ );
+ });
+
+ test("uses lookahead to avoid partial matches", () => {
+ const props = new Map<string, Prop>([
+ [
+ "prop1",
+ {
+ id: "prop1",
+ instanceId: "instance1",
+ name: "code",
+ type: "string",
+ value: "var(--color) and var(--color-dark)",
+ },
+ ],
+ ]);
+
+ const result = updateVarReferencesInProps(props, "--color", "--primary");
+ const prop = result.get("prop1");
+
+ // Only --color should be updated, not --color-dark (lookahead ensures complete match)
+ expect(prop!.value).toBe("var(--primary) and var(--color-dark)");
+ });
+});
diff --git a/apps/builder/app/builder/shared/css-variable-utils.tsx b/apps/builder/app/builder/shared/css-variable-utils.tsx
new file mode 100644
index 0000000000..f394fd27b2
--- /dev/null
+++ b/apps/builder/app/builder/shared/css-variable-utils.tsx
@@ -0,0 +1,670 @@
+import { useState, useEffect } from "react";
+import { atom, computed } from "nanostores";
+import { useStore } from "@nanostores/react";
+import {
+ Dialog,
+ DialogContent,
+ DialogTitle,
+ DialogClose,
+ Button,
+ Text,
+ Flex,
+ theme,
+ InputField,
+ toast,
+} from "@webstudio-is/design-system";
+import type {
+ Instance,
+ StyleDecl,
+ StyleSourceSelections,
+ Props,
+} from "@webstudio-is/sdk";
+import type {
+ StyleValue,
+ StyleProperty,
+ CssProperty,
+} from "@webstudio-is/css-engine";
+import { $styles, $styleSourceSelections, $props } from "~/shared/nano-states";
+import { serverSyncStore } from "~/shared/sync";
+import { getStyleDeclKey } from "@webstudio-is/sdk";
+import { createBatchUpdate } from "~/builder/features/style-panel/shared/use-style-data";
+
+const $isDeleteUnusedCssVariablesDialogOpen = atom(false);
+
+export const openDeleteUnusedCssVariablesDialog = () => {
+ $isDeleteUnusedCssVariablesDialogOpen.set(true);
+};
+
+// Traverse a StyleValue to find all var() references
+const findVarReferences = (
+ value: StyleValue,
+ callback: (varName: string) => void
+) => {
+ if (value.type === "var") {
+ callback(`--${value.value}`);
+ }
+
+ // Recursively traverse all properties that might contain StyleValue
+ for (const key in value) {
+ const prop = value[key as keyof typeof value];
+ if (prop == null) {
+ continue;
+ }
+ // Handle nested StyleValue
+ if (typeof prop === "object" && "type" in prop) {
+ findVarReferences(prop as StyleValue, callback);
+ }
+ // Handle arrays of StyleValue (tuple, layers)
+ else if (Array.isArray(prop)) {
+ for (const item of prop) {
+ if (typeof item === "object" && item !== null && "type" in item) {
+ findVarReferences(item as StyleValue, callback);
+ }
+ }
+ }
+ }
+};
+
+// Find var() references in HTML/CSS strings (for HTML Embed code prop)
+const findVarReferencesInString = (
+ code: string,
+ callback: (varName: string) => void
+) => {
+ // Match var(--name) or var(--name, fallback) patterns
+ const matches = code.matchAll(/var\(\s*(--[\w-]+)/g);
+ for (const match of matches) {
+ callback(match[1]);
+ }
+};
+
+// Find all CSS variable references in HTML Embed code props
+const findVarReferencesInProps = (
+ props: Props,
+ callback: (varName: string) => void
+) => {
+ for (const prop of props.values()) {
+ if (prop.type === "string" && prop.name === "code" && prop.value) {
+ findVarReferencesInString(prop.value, callback);
+ }
+ }
+};
+
+// Find CSS variable usage counts (how many times each variable is referenced via var())
+export const findCssVariableUsagesByInstance = ({
+ styleSourceSelections,
+ styles,
+ props,
+}: {
+ styleSourceSelections: StyleSourceSelections;
+ styles: Map<string, StyleDecl>;
+ props: Props;
+}): {
+ counts: Map<string, number>;
+ instances: Map<string, Set<Instance["id"]>>;
+} => {
+ const usageCounts = new Map<string, number>();
+ const usageInstances = new Map<string, Set<Instance["id"]>>();
+
+ // Track which style sources belong to which instances
+ const instancesByStyleSource = new Map<string, Instance["id"]>();
+ for (const { instanceId, values } of styleSourceSelections.values()) {
+ for (const styleSourceId of values) {
+ instancesByStyleSource.set(styleSourceId, instanceId);
+ }
+ }
+
+ // Helper to add a var reference
+ const addVarReference = (varName: string, instanceId: Instance["id"]) => {
+ const count = usageCounts.get(varName) ?? 0;
+ usageCounts.set(varName, count + 1);
+
+ let instances = usageInstances.get(varName);
+ if (instances === undefined) {
+ instances = new Set();
+ usageInstances.set(varName, instances);
+ }
+ instances.add(instanceId);
+ };
+
+ // Track CSS variable references in StyleDecl values
+ for (const styleDecl of styles.values()) {
+ const instanceId = instancesByStyleSource.get(styleDecl.styleSourceId);
+ if (!instanceId) {
+ continue;
+ }
+
+ // Track CSS variable references (var(--name) in values)
+ // Note: We don't track definitions here, only actual usages
+ // Each reference counts as a usage, even if on the same instance
+ findVarReferences(styleDecl.value, (varName) => {
+ addVarReference(varName, instanceId);
+ });
+ }
+
+ // Track CSS variable references in HTML Embed code props
+ for (const prop of props.values()) {
+ if (prop.type === "string" && prop.name === "code" && prop.value) {
+ findVarReferencesInString(prop.value, (varName) => {
+ addVarReference(varName, prop.instanceId);
+ });
+ }
+ }
+
+ return { counts: usageCounts, instances: usageInstances };
+};
+
+const $cssVariableUsageData = computed(
+ [$styleSourceSelections, $styles, $props],
+ (styleSourceSelections, styles, props) => {
+ return findCssVariableUsagesByInstance({
+ styleSourceSelections,
+ styles,
+ props,
+ });
+ }
+);
+
+export const $usedCssVariablesInInstances = computed(
+ $cssVariableUsageData,
+ (data) => data.counts
+);
+
+export const $cssVariableInstancesByVariable = computed(
+ $cssVariableUsageData,
+ (data) => data.instances
+);
+
+// Get all defined CSS variables (unique properties that start with --)
+export const $definedCssVariables = computed($styles, (styles) => {
+ const definedVariables = new Set<string>();
+ for (const styleDecl of styles.values()) {
+ if (styleDecl.property.startsWith("--")) {
+ definedVariables.add(styleDecl.property);
+ }
+ }
+ return definedVariables;
+});
+
+// Map CSS variables to the instances where they are defined
+export const $cssVariableDefinitionsByVariable = computed(
+ [$styleSourceSelections, $styles],
+ (styleSourceSelections, styles) => {
+ const definitionsByVariable = new Map<string, Set<Instance["id"]>>();
+
+ // Build map of styleSourceId to instanceId
+ const instancesByStyleSource = new Map<string, Instance["id"]>();
+ for (const { instanceId, values } of styleSourceSelections.values()) {
+ for (const styleSourceId of values) {
+ instancesByStyleSource.set(styleSourceId, instanceId);
+ }
+ }
+
+ // Find all CSS variable definitions
+ for (const styleDecl of styles.values()) {
+ if (styleDecl.property.startsWith("--")) {
+ const instanceId = instancesByStyleSource.get(styleDecl.styleSourceId);
+ if (instanceId) {
+ let instances = definitionsByVariable.get(styleDecl.property);
+ if (instances === undefined) {
+ instances = new Set();
+ definitionsByVariable.set(styleDecl.property, instances);
+ }
+ instances.add(instanceId);
+ }
+ }
+ }
+
+ return definitionsByVariable;
+ }
+);
+
+// Get all referenced CSS variables (from both styles and HTML Embed code props)
+export const $referencedCssVariables = computed(
+ [$styles, $props],
+ (styles, props) => {
+ const referencedVariables = new Set<string>();
+ for (const styleDecl of styles.values()) {
+ findVarReferences(styleDecl.value, (varName) => {
+ referencedVariables.add(varName);
+ });
+ }
+ findVarReferencesInProps(props, (varName) => {
+ referencedVariables.add(varName);
+ });
+ return referencedVariables;
+ }
+);
+
+export type CssVariableError =
+ | { type: "required"; message: string }
+ | { type: "invalid"; message: string }
+ | { type: "duplicate"; message: string };
+
+export const validateCssVariableName = (
+ name: string,
+ currentProperty?: string
+): CssVariableError | undefined => {
+ // Check if name is required
+ if (name.trim().length === 0) {
+ return {
+ type: "required",
+ message: "CSS variable name cannot be empty",
+ };
+ }
+
+ // Ensure name starts with --
+ if (!name.startsWith("--")) {
+ return {
+ type: "invalid",
+ message: 'CSS variable name must start with "--"',
+ };
+ }
+
+ // Check for duplicates within the same style source + breakpoint + state
+ const styles = $styles.get();
+ for (const styleDecl of styles.values()) {
+ if (
+ styleDecl.property === name &&
+ styleDecl.property !== currentProperty &&
+ styleDecl.property.startsWith("--")
+ ) {
+ return {
+ type: "duplicate",
+ message: `CSS variable "${name}" already exists`,
+ };
+ }
+ }
+};
+
+// Update all var() references in a StyleValue
+const updateVarReferences = (
+ value: StyleValue,
+ oldProperty: string,
+ newProperty: string
+): StyleValue => {
+ if (value.type === "var") {
+ const currentVarName = `--${value.value}`;
+ if (currentVarName === oldProperty) {
+ value = {
+ ...value,
+ value: newProperty.slice(2), // Remove -- prefix
+ };
+ }
+ }
+
+ // Recursively update all properties that might contain StyleValue
+ const result = { ...value } as Record<string, unknown>;
+ for (const key in value) {
+ const prop = value[key as keyof typeof value];
+ if (prop == null || key === "type") {
+ continue;
+ }
+ // Handle nested StyleValue
+ if (typeof prop === "object" && "type" in prop) {
+ result[key] = updateVarReferences(
+ prop as StyleValue,
+ oldProperty,
+ newProperty
+ );
+ }
+ // Handle arrays of StyleValue (tuple, layers)
+ else if (Array.isArray(prop)) {
+ result[key] = prop.map((item) => {
+ if (typeof item === "object" && item !== null && "type" in item) {
+ return updateVarReferences(
+ item as StyleValue,
+ oldProperty,
+ newProperty
+ );
+ }
+ return item;
+ });
+ }
+ }
+ return result as StyleValue;
+};
+
+// Core rename logic without transaction wrapper (for testing)
+export const performCssVariableRename = (
+ styles: Map<string, StyleDecl>,
+ oldProperty: string,
+ newProperty: string
+): Map<string, StyleDecl> => {
+ const updatedStyles = new Map(styles);
+
+ // Update all StyleDecl with the old property name
+ const styleDeclsToUpdate: Array<{ key: string; decl: StyleDecl }> = [];
+ for (const [key, styleDecl] of updatedStyles) {
+ if (styleDecl.property === oldProperty) {
+ styleDeclsToUpdate.push({ key, decl: styleDecl });
+ }
+ }
+
+ for (const { key, decl } of styleDeclsToUpdate) {
+ updatedStyles.delete(key);
+ const newDecl = { ...decl, property: newProperty as StyleProperty };
+ updatedStyles.set(getStyleDeclKey(newDecl), newDecl);
+ }
+
+ // Update all var() references in StyleValue
+ const styleDeclsToUpdateRefs: Array<{ key: string; decl: StyleDecl }> = [];
+ for (const [key, styleDecl] of updatedStyles) {
+ styleDeclsToUpdateRefs.push({ key, decl: styleDecl });
+ }
+
+ for (const { key, decl } of styleDeclsToUpdateRefs) {
+ const newValue = updateVarReferences(decl.value, oldProperty, newProperty);
+ if (newValue !== decl.value) {
+ updatedStyles.set(key, { ...decl, value: newValue });
+ }
+ }
+
+ return updatedStyles;
+};
+
+// Update var() references in HTML Embed code props (pure function for testing)
+export const updateVarReferencesInProps = (
+ props: Props,
+ oldProperty: string,
+ newProperty: string
+): Props => {
+ const updatedProps = new Map(props);
+ // Match var( followed by optional whitespace, the old property name, and then either:
+ // - closing paren )
+ // - comma (for fallback values)
+ // - whitespace
+ const regex = new RegExp(
+ `var\\(\\s*${oldProperty.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?=[\\s,)])`,
+ "g"
+ );
+
+ for (const [key, prop] of updatedProps) {
+ if (prop.type === "string" && prop.name === "code" && prop.value) {
+ const updatedValue = prop.value.replace(regex, `var(${newProperty}`);
+ if (updatedValue !== prop.value) {
+ updatedProps.set(key, { ...prop, value: updatedValue });
+ }
+ }
+ }
+
+ return updatedProps;
+};
+
+export const renameCssVariable = (
+ oldProperty: string,
+ newProperty: string
+): CssVariableError | undefined => {
+ const validationError = validateCssVariableName(newProperty, oldProperty);
+ if (validationError) {
+ return validationError;
+ }
+
+ serverSyncStore.createTransaction([$styles, $props], (styles, props) => {
+ const updatedStyles = performCssVariableRename(
+ styles,
+ oldProperty,
+ newProperty
+ );
+
+ // Clear and repopulate the styles map
+ styles.clear();
+ for (const [key, value] of updatedStyles) {
+ styles.set(key, value);
+ }
+
+ // Update var() references in HTML Embed code props
+ const updatedProps = updateVarReferencesInProps(
+ props,
+ oldProperty,
+ newProperty
+ );
+ props.clear();
+ for (const [key, value] of updatedProps) {
+ props.set(key, value);
+ }
+ });
+
+ return undefined;
+};
+
+export const deleteUnusedCssVariables = () => {
+ const definedVariables = $definedCssVariables.get();
+ const referencedVariables = $referencedCssVariables.get();
+
+ // Find unused variables (defined but not referenced)
+ const unusedVariables: string[] = [];
+ for (const varName of definedVariables) {
+ if (!referencedVariables.has(varName)) {
+ unusedVariables.push(varName);
+ }
+ }
+
+ if (unusedVariables.length === 0) {
+ return 0;
+ }
+
+ const batch = createBatchUpdate();
+ for (const varName of unusedVariables) {
+ batch.deleteProperty(varName as CssProperty);
+ }
+ batch.publish();
+
+ return unusedVariables.length;
+};
+
+type DeleteCssVariableDialogProps = {
+ cssVariable?: { property: string };
+ onClose: () => void;
+ onConfirm: (property: string) => void;
+};
+
+export const DeleteCssVariableDialog = ({
+ cssVariable,
+ onClose,
+ onConfirm,
+}: DeleteCssVariableDialogProps) => {
+ return (
+ <Dialog
+ open={cssVariable !== undefined}
+ onOpenChange={(isOpen) => {
+ if (isOpen === false) {
+ onClose();
+ }
+ }}
+ >
+ <DialogContent
+ onKeyDown={(event) => {
+ // Prevent command panel from handling keyboard events
+ event.stopPropagation();
+ }}
+ >
+ <DialogTitle>Delete confirmation</DialogTitle>
+ <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>
+ <Text>{`Delete CSS variable "${cssVariable?.property}" from the project?`}</Text>
+ <Flex direction="rowReverse" gap="2">
+ <Button
+ color="destructive"
+ onClick={() => {
+ onConfirm(cssVariable!.property);
+ onClose();
+ }}
+ >
+ Delete
+ </Button>
+ <DialogClose>
+ <Button color="ghost">Cancel</Button>
+ </DialogClose>
+ </Flex>
+ </Flex>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+type RenameCssVariableDialogProps = {
+ cssVariable?: { property: string };
+ onClose: () => void;
+ onConfirm: (oldProperty: string, newProperty: string) => void;
+};
+
+export const RenameCssVariableDialog = ({
+ cssVariable,
+ onClose,
+ onConfirm,
+}: RenameCssVariableDialogProps) => {
+ const [name, setName] = useState("");
+ const [error, setError] = useState<string>();
+
+ // Reset name and clear error when cssVariable changes
+ useEffect(() => {
+ if (cssVariable?.property !== undefined) {
+ setName(cssVariable.property);
+ setError(undefined);
+ }
+ }, [cssVariable?.property]);
+
+ const handleConfirm = () => {
+ const renameError = renameCssVariable(cssVariable!.property, name);
+ if (renameError) {
+ setError(renameError.message);
+ return;
+ }
+ onConfirm(cssVariable!.property, name);
+ onClose();
+ };
+
+ return (
+ <Dialog
+ open={cssVariable !== undefined}
+ onOpenChange={(isOpen) => {
+ if (isOpen === false) {
+ onClose();
+ }
+ }}
+ >
+ <DialogContent
+ onKeyDown={(event) => {
+ // Prevent command panel from handling keyboard events
+ event.stopPropagation();
+ if (event.key === "Enter" && !error) {
+ handleConfirm();
+ }
+ }}
+ >
+ <DialogTitle>Rename CSS Variable</DialogTitle>
+ <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>
+ <Flex direction="column" gap="1">
+ <InputField
+ value={name}
+ onChange={(event) => {
+ setName(event.target.value);
+ setError(undefined);
+ }}
+ color={error ? "error" : undefined}
+ />
+ {error && (
+ <Text color="destructive" variant="monoBold">
+ {error}
+ </Text>
+ )}
+ </Flex>
+ <Flex direction="rowReverse" gap="2">
+ <Button color="primary" onClick={handleConfirm}>
+ Rename
+ </Button>
+ <DialogClose>
+ <Button color="ghost">Cancel</Button>
+ </DialogClose>
+ </Flex>
+ </Flex>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+export const DeleteUnusedCssVariablesDialog = () => {
+ const open = useStore($isDeleteUnusedCssVariablesDialogOpen);
+ const definedVariables = useStore($definedCssVariables);
+ const referencedVariables = useStore($referencedCssVariables);
+
+ const handleClose = () => {
+ $isDeleteUnusedCssVariablesDialogOpen.set(false);
+ };
+
+ // Find unused variables (defined but not referenced)
+ const unusedVariables: string[] = [];
+ for (const varName of definedVariables) {
+ if (!referencedVariables.has(varName)) {
+ unusedVariables.push(varName);
+ }
+ }
+
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(isOpen) => {
+ if (isOpen === false) {
+ handleClose();
+ }
+ }}
+ >
+ <DialogContent
+ onKeyDown={(event) => {
+ event.stopPropagation();
+ }}
+ >
+ <DialogTitle>Delete unused CSS variables</DialogTitle>
+ <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>
+ {unusedVariables.length === 0 ? (
+ <Text>There are no unused CSS variables to delete.</Text>
+ ) : (
+ <>
+ <Text>
+ Delete {unusedVariables.length} unused CSS{" "}
+ {unusedVariables.length === 1 ? "variable" : "variables"} from
+ the project?
+ </Text>
+ <Text
+ variant="mono"
+ css={{
+ maxHeight: 200,
+ overflowY: "auto",
+ backgroundColor: theme.colors.backgroundPanel,
+ borderRadius: theme.borderRadius[4],
+ wordBreak: "break-word",
+ }}
+ >
+ {unusedVariables.join(", ")}
+ </Text>
+ </>
+ )}
+ <Flex direction="rowReverse" gap="2">
+ {unusedVariables.length > 0 && (
+ <Button
+ color="destructive"
+ onClick={() => {
+ const deletedCount = deleteUnusedCssVariables();
+ handleClose();
+ if (deletedCount === 0) {
+ toast.info("No unused CSS variables to delete");
+ } else {
+ toast.success(
+ `Deleted ${deletedCount} unused CSS ${deletedCount === 1 ? "variable" : "variables"}`
+ );
+ }
+ }}
+ >
+ Delete
+ </Button>
+ )}
+ <DialogClose>
+ <Button color="ghost">
+ {unusedVariables.length > 0 ? "Cancel" : "Close"}
+ </Button>
+ </DialogClose>
+ </Flex>
+ </Flex>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsx
index b55cb80884..f285328f47 100644
--- a/apps/builder/app/canvas/canvas.tsx
+++ b/apps/builder/app/canvas/canvas.tsx
@@ -66,7 +66,6 @@ import { subscribeCommands } from "~/canvas/shared/commands";
import { updateCollaborativeInstanceRect } from "./collaborative-instance";
import { initCanvasApi } from "~/shared/canvas-api";
import { subscribeFontLoadingDone } from "./shared/font-weight-support";
-import { useDebounceEffect } from "~/shared/hook-utils/use-debounce-effect";
import { subscribeSelected } from "./instance-selected";
import { subscribeScrollNewInstanceIntoView } from "./shared/scroll-new-instance-into-view";
import { $selectedPage } from "~/shared/awareness";
@@ -74,6 +73,7 @@ import { createInstanceElement } from "./elements";
import { subscribeScrollbarSize } from "./scrollbar-width";
import { compareMedia } from "@webstudio-is/css-engine";
import { builderApi } from "~/shared/builder-api";
+import { useDebounceEffect } from "@webstudio-is/design-system";
registerContainers();
diff --git a/apps/builder/app/shared/hook-utils/use-debounce-effect.ts b/apps/builder/app/shared/hook-utils/use-debounce-effect.ts
deleted file mode 100644
index 776ed01813..0000000000
--- a/apps/builder/app/shared/hook-utils/use-debounce-effect.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { useCallback, useEffect, useState } from "react";
-
-/**
- * Debounce callback execution until useEffect
- * Example:
- * const scheduleEffect = useDebounceEffect();
- * scheduleEffect(() => { ... })
- */
-export const useDebounceEffect = () => {
- const [updateCallback, setUpdateCallback] = useState(() => () => {
- /* empty */
- });
-
- useEffect(() => {
- // Because of how our styles works we need to update after React render to be sure that
- // all styles are applied
- updateCallback();
- }, [updateCallback]);
-
- return useCallback((callback: () => void) => {
- setUpdateCallback(() => callback);
- }, []);
-};
diff --git a/packages/design-system/src/components/command.tsx b/packages/design-system/src/components/command.tsx
index 50340e926e..7f65c1b6fa 100644
--- a/packages/design-system/src/components/command.tsx
+++ b/packages/design-system/src/components/command.tsx
@@ -1,6 +1,5 @@
import {
createContext,
- useCallback,
useContext,
useEffect,
useRef,
@@ -28,6 +27,7 @@ import { Text, textVariants } from "./text";
import { Button } from "./button";
import { Popover, PopoverContent, PopoverTrigger } from "./popover";
import { Kbd } from "./kbd";
+import { useDebounceEffect } from "../utilities";
const panelWidth = "400px";
const itemHeight = "32px";
@@ -85,6 +85,13 @@ export const useSelectedAction = () => {
return state.actions[state.actionIndex];
};
+export const useResetActionIndex = () => {
+ const [, setState] = useContext(CommandContext);
+ return () => {
+ setState((prev) => ({ ...prev, actionIndex: 0 }));
+ };
+};
+
export const Command = (props: CommandProps) => {
const state = useState<CommandState>({
highlightedGroup: "",
@@ -93,7 +100,12 @@ export const Command = (props: CommandProps) => {
});
return (
<CommandContext.Provider value={state}>
- <StyledCommand loop={true} filter={lowerCasedFilter} {...props} />
+ <StyledCommand
+ disablePointerSelection
+ loop={true}
+ filter={lowerCasedFilter}
+ {...props}
+ />
</CommandContext.Provider>
);
};
@@ -194,20 +206,6 @@ export const CommandInput = (
const ActionsCommand = styled(CommandPrimitive, {});
-const useDebounceEffect = () => {
- const [updateCallback, setUpdateCallback] = useState(() => () => {
- /* empty */
- });
- useEffect(() => {
- // Because of how our styles works we need to update after React render to be sure that
- // all styles are applied
- updateCallback();
- }, [updateCallback]);
- return useCallback((callback: () => void) => {
- setUpdateCallback(() => callback);
- }, []);
-};
-
export const CommandFooter = () => {
const [isActionOpen, setIsActionOpen] = useState(false);
const scheduleEffect = useDebounceEffect();
@@ -273,7 +271,7 @@ export const CommandFooter = () => {
}
}}
>
- <ActionsCommand>
+ <ActionsCommand disablePointerSelection loop>
<CommandInputContainer>
<CommandInputField placeholder="Choose action..." />
</CommandInputContainer>
@@ -281,6 +279,7 @@ export const CommandFooter = () => {
{state.actions.map((action, actionIndex) => (
<CommandItem
key={action}
+ allowSingleClick
onSelect={() => {
setState((prev) => ({ ...prev, actionIndex }));
setIsActionOpen(false);
@@ -331,6 +330,76 @@ export const CommandGroup = ({
);
};
+export const CommandItem = ({
+ onSelect,
+ allowSingleClick,
+ ...props
+}: ComponentPropsWithoutRef<typeof CommandItemStyled> & {
+ onSelect?: () => void;
+ allowSingleClick?: boolean;
+}) => {
+ const doubleClickedRef = useRef(false);
+ const selectTimeoutRef = useRef<ReturnType<typeof setTimeout>>();
+ const pointerDownRef = useRef(false);
+
+ const handleSelect = () => {
+ // Actions menu mode - execute immediately
+ if (allowSingleClick) {
+ onSelect?.();
+ return;
+ }
+
+ // Default mode
+ if (selectTimeoutRef.current) {
+ clearTimeout(selectTimeoutRef.current);
+ }
+
+ // If double-click already happened, skip (it already executed)
+ if (doubleClickedRef.current) {
+ doubleClickedRef.current = false;
+ return;
+ }
+
+ // If triggered by Enter key (no pointer down), execute immediately
+ if (!pointerDownRef.current) {
+ onSelect?.();
+ return;
+ }
+
+ // For mouse clicks, delay to detect double-click
+ selectTimeoutRef.current = setTimeout(() => {
+ // Reset pointer flag after delay
+ pointerDownRef.current = false;
+ }, 300);
+ };
+
+ return (
+ <CommandItemStyled
+ {...props}
+ onPointerDown={
+ allowSingleClick
+ ? undefined
+ : () => {
+ pointerDownRef.current = true;
+ }
+ }
+ onDoubleClick={
+ allowSingleClick
+ ? undefined
+ : () => {
+ // Mark that double-click happened and execute immediately
+ doubleClickedRef.current = true;
+ if (selectTimeoutRef.current) {
+ clearTimeout(selectTimeoutRef.current);
+ }
+ onSelect?.();
+ }
+ }
+ onSelect={handleSelect}
+ />
+ );
+};
+
export const CommandGroupHeading = styled("div", {
...textVariants.titles,
color: theme.colors.foregroundMoreSubtle,
@@ -353,14 +422,17 @@ export const CommandGroupFooter = styled("div", {
borderTop: `1px solid ${theme.colors.borderMain}`,
});
-export const CommandItem = styled(CommandPrimitive.Item, {
+const CommandItemStyled = styled(CommandPrimitive.Item, {
display: "grid",
gridTemplateColumns: `1fr max-content`,
alignItems: "center",
minHeight: itemHeight,
paddingInline: theme.spacing[9],
+ "&:hover": {
+ backgroundColor: theme.colors.backgroundItemMenuItemHover,
+ },
"&[aria-selected=true]": {
- backgroundColor: theme.colors.backgroundHover,
+ backgroundColor: theme.colors.backgroundItemCurrent,
},
});
diff --git a/packages/design-system/src/utilities.ts b/packages/design-system/src/utilities.ts
index 26d237fcec..950a0dbe35 100644
--- a/packages/design-system/src/utilities.ts
+++ b/packages/design-system/src/utilities.ts
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import warnOnce from "warn-once";
import type { CSS } from "./stitches.config";
@@ -147,3 +147,17 @@ export const truncate = (): CSS => ({
textOverflow: "ellipsis",
overflow: "hidden",
});
+
+export const useDebounceEffect = () => {
+ const [updateCallback, setUpdateCallback] = useState(() => () => {
+ /* empty */
+ });
+ useEffect(() => {
+ // Because of how our styles works we need to update after React render to be sure that
+ // all styles are applied
+ updateCallback();
+ }, [updateCallback]);
+ return useCallback((callback: () => void) => {
+ setUpdateCallback(() => callback);
+ }, []);
+};