Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
fix: Fix delete unused css vars and unused detection (#5505)
Oleg Isonenf712740b9421
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.tsxindex 2e0cd31e23..de47531817 100644--- 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@@ -15,9 +15,9 @@ import type { CssProperty } from "@webstudio-is/css-engine";import {DeleteCssVariableDialog,RenameCssVariableDialog,- $usedCssVariablesInInstances,$cssVariableInstancesByVariable,$cssVariableDefinitionsByVariable,+ $unusedCssVariables,} from "~/builder/shared/css-variable-utils";import { deleteProperty } from "~/builder/features/style-panel/shared/use-style-data";import { InstanceList, showInstance } from "../shared/instance-list";@@ -38,14 +38,14 @@ export type CssVariableOption = BaseOption & {};export const $cssVariableOptions = computed(- [$cssVariableDefinitionsByVariable, $usedCssVariablesInInstances],- (definitionsByVariable, usedVariablesInInstances) => {+ [$cssVariableDefinitionsByVariable, $unusedCssVariables],+ (definitionsByVariable, unusedVariables) => {const cssVariableOptions: CssVariableOption[] = [];// Create options for each defined CSS variable on each instancefor (const [property, instanceIds] of definitionsByVariable) {for (const instanceId of instanceIds) {- const usages = usedVariablesInInstances.get(property) ?? 0;+ const usages = unusedVariables.has(property) ? 0 : 1; // 0 if unused, 1+ otherwisecssVariableOptions.push({terms: ["css variables",@@ -130,7 +130,12 @@ export const CssVariablesGroup = ({{formatUsageCount(usages)}</Text></Text>- <Text as="span" color="moreSubtle">+ <Text+ as="span"+ css={{ maxWidth: "20ch" }}+ truncate+ color="moreSubtle"+ >{getInstanceLabel(instanceId)}</Text></CommandItem>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.tsxindex 804802c48c..213630df58 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@@ -13,19 +13,17 @@ import {Kbd,} from "@webstudio-is/design-system";import type { Instance } from "@webstudio-is/sdk";-import {- $instances,- $pages,- $registeredComponentMetas,-} from "~/shared/nano-states";+import { $instances, $pages } from "~/shared/nano-states";import { getInstanceLabel } from "~/builder/shared/instance-label";import { $awareness, findAwarenessByInstanceId } from "~/shared/awareness";+import { buildInstancePath } from "~/shared/instance-utils";import { $commandContent } from "../command-state";import { $activeInspectorPanel } from "~/builder/shared/nano-states";export type InstanceOption = {label: string;id: string;+ path: string[];};type InstanceListProps = {@@ -35,17 +33,19 @@ type InstanceListProps = {export const InstanceList = ({ instanceIds, onSelect }: InstanceListProps) => {const instances = $instances.get();- const metas = $registeredComponentMetas.get();+ const pages = $pages.get();const usedInInstances: InstanceOption[] = [];for (const instanceId of instanceIds) {const instance = instances.get(instanceId);- const meta = metas.get(instance?.component ?? "");- if (instance && meta) {- usedInInstances.push({- label: getInstanceLabel(instance),- id: instance.id,- });+ if (!instance || !pages) {+ continue;}+ const path = buildInstancePath(instanceId, pages, instances);+ usedInInstances.push({+ label: getInstanceLabel(instance),+ id: instance.id,+ path,+ });}const [search, setSearch] = useState("");@@ -86,7 +86,7 @@ export const InstanceList = ({ instanceIds, onSelect }: InstanceListProps) => {<Text color="subtle">No instances found</Text></Flex>) : (- matches.map(({ id, label }) => (+ matches.map(({ id, label, path }) => (<CommandItemkey={id}value={id}@@ -95,6 +95,13 @@ export const InstanceList = ({ instanceIds, onSelect }: InstanceListProps) => {}}><Text variant="labelsTitleCase">{label}</Text>+ <Text+ color="moreSubtle"+ truncate+ css={{ maxWidth: "30ch" }}+ >+ /{path.join("/")}+ </Text></CommandItem>)))}@@ -105,7 +112,7 @@ export const InstanceList = ({ instanceIds, onSelect }: InstanceListProps) => {<CommandGroupFooter><Flex grow><Button tabIndex={-1} color="ghost" onClick={goBack}>- Back <Kbd value={["backspace"]} />+ <Kbd value={["backspace"]} /> Back</Button></Flex></CommandGroupFooter>diff --git a/apps/builder/app/builder/shared/css-variable-utils.test.tsx b/apps/builder/app/builder/shared/css-variable-utils.test.tsxindex 2e9cdfffaf..dce290078a 100644--- a/apps/builder/app/builder/shared/css-variable-utils.test.tsx+++ b/apps/builder/app/builder/shared/css-variable-utils.test.tsx@@ -1,5 +1,8 @@import { test, expect, describe } from "vitest";import { atom } from "nanostores";+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";import { $styles } from "~/shared/nano-states";import {findCssVariableUsagesByInstance,@@ -7,9 +10,6 @@ import {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 moduleconst mockStyles = atom<Styles>(new Map());@@ -376,7 +376,7 @@ describe("findCssVariableUsagesByInstance", () => {]);// parseCssValue returns unparsed type for calc() expressions- // We don't track var() inside unparsed strings since they're not structured+ // Now we DO track var() inside unparsed stringsconst styles = new Map([["local1:base:--spacing::",@@ -394,13 +394,13 @@ describe("findCssVariableUsagesByInstance", () => {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);+ // Should track var() references inside unparsed calc() expressions+ expect(counts.size).toBe(1);+ expect(counts.get("--spacing")).toBe(1);+ expect(instances.get("--spacing")).toEqual(new Set(["box1"]));});- test("tracks var() in HTML Embed code", () => {+ test("tracks var() inside calc() function", () => {const styleSourceSelections = new Map([["box1",@@ -411,542 +411,3065 @@ describe("findCssVariableUsagesByInstance", () => {],]);- const styles = new Map();-- const props = new Map([+ const styles = 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>`,- },+ "local1:base:--test1::",+ createStyleDecl("local1", "base", "--test1", "10px"),+ ],+ [+ "local1:base:width::",+ createStyleDecl("local1", "base", "width", "calc(var(--test1))"),],]);const { counts, instances } = findCssVariableUsagesByInstance({styleSourceSelections,styles,- props,+ props: new Map(),});- 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);+ // Should track var() references inside calc() expressions+ expect(counts.size).toBe(1);+ expect(counts.get("--test1")).toBe(1);+ expect(instances.get("--test1")).toEqual(new Set(["box1"]));});-});-describe("performCssVariableRename", () => {- test("updates property declarations", () => {- const styles = new Map<string, StyleDecl>([+ test("tracks var() inside complex calc() with multiple variables", () => {+ const styleSourceSelections = new Map([[- "styleSourceId:base:--my-color",+ "box1",{- breakpointId: "base",- styleSourceId: "styleSourceId",- property: "--my-color" as StyleProperty,- value: { type: "keyword", value: "red" },+ instanceId: "box1",+ values: ["local1"],},],]);- const result = performCssVariableRename(+ const styles = new Map([+ [+ "local1:base:--spacing::",+ createStyleDecl("local1", "base", "--spacing", "10px"),+ ],+ [+ "local1:base:--multiplier::",+ createStyleDecl("local1", "base", "--multiplier", "2"),+ ],+ [+ "local1:base:width::",+ createStyleDecl(+ "local1",+ "base",+ "width",+ "calc(var(--spacing) * var(--multiplier))"+ ),+ ],+ ]);++ const { counts, instances } = findCssVariableUsagesByInstance({+ styleSourceSelections,styles,- "--my-color",- "--new-color"- );+ props: new Map(),+ });- 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" });+ expect(counts.size).toBe(2);+ expect(counts.get("--spacing")).toBe(1);+ expect(counts.get("--multiplier")).toBe(1);+ expect(instances.get("--spacing")).toEqual(new Set(["box1"]));+ expect(instances.get("--multiplier")).toEqual(new Set(["box1"]));});- test("updates var() references", () => {- const styles = new Map<string, StyleDecl>([+ test("tracks var() with fallback values", () => {+ const styleSourceSelections = new Map([[- "styleSourceId:base:--my-color",+ "box1",{- breakpointId: "base",- styleSourceId: "styleSourceId",- property: "--my-color" as StyleProperty,- value: { type: "keyword", value: "red" },+ instanceId: "box1",+ values: ["local1"],},],+ ]);++ const styles = new Map([[- "styleSourceId:base:color",- {- breakpointId: "base",- styleSourceId: "styleSourceId",- property: "color" as StyleProperty,- value: { type: "var", value: "my-color" },- },+ "local1:base:--primary-color::",+ createStyleDecl("local1", "base", "--primary-color", "red"),+ ],+ [+ "local1:base:color::",+ createStyleDecl(+ "local1",+ "base",+ "color",+ "var(--primary-color, blue)"+ ),],]);- const result = performCssVariableRename(+ const { counts, instances } = findCssVariableUsagesByInstance({+ styleSourceSelections,styles,- "--my-color",- "--new-color"- );+ props: new Map(),+ });- 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" });+ expect(counts.get("--primary-color")).toBe(1);+ expect(instances.get("--primary-color")).toEqual(new Set(["box1"]));});- test("updates nested var() references", () => {- const styles = new Map<string, StyleDecl>([+ test("tracks var() with nested fallbacks", () => {+ const styleSourceSelections = new Map([[- "styleSourceId:base:transform",+ "box1",{- breakpointId: "base",- styleSourceId: "styleSourceId",- property: "transform" as StyleProperty,- value: {- type: "function",- name: "rotate",- args: {- type: "var",- value: "rotation-angle",- },- } as StyleValue,+ instanceId: "box1",+ values: ["local1"],},],]);- const result = performCssVariableRename(- styles,- "--rotation-angle",- "--angle"- );+ const styles = new Map([+ [+ "local1:base:--primary::",+ createStyleDecl("local1", "base", "--primary", "blue"),+ ],+ [+ "local1:base:--secondary::",+ createStyleDecl("local1", "base", "--secondary", "green"),+ ],+ [+ "local1:base:color::",+ createStyleDecl(+ "local1",+ "base",+ "color",+ "var(--primary, var(--secondary, red))"+ ),+ ],+ ]);- const transformDecl = Array.from(result.values())[0];- expect(transformDecl.value).toMatchObject({- type: "function",- name: "rotate",- args: {- type: "var",- value: "angle",- },+ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),});++ expect(counts.get("--primary")).toBe(1);+ expect(counts.get("--secondary")).toBe(1);});- test("updates array of var() references", () => {- const styles = new Map<string, StyleDecl>([+ test("tracks var() with CSS variable as fallback (var(--primary, --fallback))", () => {+ const styleSourceSelections = new Map([[- "styleSourceId:base:boxShadow",+ "box1",{- 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" },- ],- },+ instanceId: "box1",+ values: ["local1"],},],]);- 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" },+ const styles = new Map([+ [+ "local1:base:--primary::",+ createStyleDecl("local1", "base", "--primary", "blue"),],- });- });-- 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" },- },+ "local1:base:--fallback::",+ createStyleDecl("local1", "base", "--fallback", "red"),],[- "styleSourceId2:base:--my-var",- {- breakpointId: "base",- styleSourceId: "styleSourceId2",- property: "--my-var" as StyleProperty,- value: { type: "keyword", value: "value2" },- },+ "local1:base:color::",+ createStyleDecl(+ "local1",+ "base",+ "color",+ "var(--primary, --fallback)"+ ),],]);- const result = performCssVariableRename(styles, "--my-var", "--renamed");+ const { counts, instances } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });- expect(result.size).toBe(2);- const decls = Array.from(result.values());- expect(decls.every((d) => d.property === "--renamed")).toBe(true);+ // Both the primary and fallback variable should be tracked+ expect(counts.get("--primary")).toBe(1);+ expect(counts.get("--fallback")).toBe(1);+ expect(instances.get("--primary")).toEqual(new Set(["box1"]));+ expect(instances.get("--fallback")).toEqual(new Set(["box1"]));});- test("does not modify unrelated variables", () => {- const styles = new Map<string, StyleDecl>([+ test("tracks multiple var() with variable fallbacks in same value", () => {+ const styleSourceSelections = new Map([[- "styleSourceId:base:--my-color",+ "box1",{- breakpointId: "base",- styleSourceId: "styleSourceId",- property: "--my-color" as StyleProperty,- value: { type: "keyword", value: "red" },+ instanceId: "box1",+ values: ["local1"],},],+ ]);++ const styles = new Map([[- "styleSourceId:base:--other-color",- {- breakpointId: "base",- styleSourceId: "styleSourceId",- property: "--other-color" as StyleProperty,- value: { type: "keyword", value: "blue" },- },+ "local1:base:--color1::",+ createStyleDecl("local1", "base", "--color1", "red"),],[- "styleSourceId:base:color",- {- breakpointId: "base",- styleSourceId: "styleSourceId",- property: "color" as StyleProperty,- value: { type: "var", value: "other-color" },- },+ "local1:base:--color2::",+ createStyleDecl("local1", "base", "--color2", "blue"),+ ],+ [+ "local1:base:--fallback1::",+ createStyleDecl("local1", "base", "--fallback1", "yellow"),+ ],+ [+ "local1:base:--fallback2::",+ createStyleDecl("local1", "base", "--fallback2", "green"),+ ],+ [+ "local1:base:background::",+ createStyleDecl(+ "local1",+ "base",+ "background",+ "linear-gradient(var(--color1, --fallback1), var(--color2, --fallback2))"+ ),],]);- const result = performCssVariableRename(+ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,styles,- "--my-color",- "--new-color"- );-+ props: new Map(),+ });++ expect(counts.get("--color1")).toBe(1);+ expect(counts.get("--color2")).toBe(1);+ expect(counts.get("--fallback1")).toBe(1);+ expect(counts.get("--fallback2")).toBe(1);+ });++ test("tracks deeply nested var() with variable fallbacks", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--first::",+ createStyleDecl("local1", "base", "--first", "value"),+ ],+ [+ "local1:base:--second::",+ createStyleDecl("local1", "base", "--second", "value"),+ ],+ [+ "local1:base:--third::",+ createStyleDecl("local1", "base", "--third", "value"),+ ],+ [+ "local1:base:color::",+ createStyleDecl(+ "local1",+ "base",+ "color",+ "var(--first, var(--second, --third))"+ ),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--first")).toBe(1);+ expect(counts.get("--second")).toBe(1);+ expect(counts.get("--third")).toBe(1);+ });++ test("tracks variables in gradient", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--angle::",+ createStyleDecl("local1", "base", "--angle", "45deg"),+ ],+ [+ "local1:base:--color1::",+ createStyleDecl("local1", "base", "--color1", "red"),+ ],+ [+ "local1:base:--color2::",+ createStyleDecl("local1", "base", "--color2", "blue"),+ ],+ [+ "local1:base:backgroundImage::",+ createStyleDecl(+ "local1",+ "base",+ "backgroundImage",+ "linear-gradient(var(--angle), var(--color1), var(--color2))"+ ),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--angle")).toBe(1);+ expect(counts.get("--color1")).toBe(1);+ expect(counts.get("--color2")).toBe(1);+ });++ test("tracks variables with hyphens and numbers", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--spacing-level-1::",+ createStyleDecl("local1", "base", "--spacing-level-1", "10px"),+ ],+ [+ "local1:base:padding::",+ createStyleDecl("local1", "base", "padding", "var(--spacing-level-1)"),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--spacing-level-1")).toBe(1);+ });++ test("does not track variable definitions as usages", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--primary-color::",+ createStyleDecl("local1", "base", "--primary-color", "blue"),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ // Defining --primary-color should not count as using it+ expect(counts.size).toBe(0);+ });++ test("tracks var() in HTML Embed code", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--primary-color::",+ createStyleDecl("local1", "base", "--primary-color", "blue"),+ ],+ [+ "local1:base:--bg-color::",+ createStyleDecl("local1", "base", "--bg-color", "white"),+ ],+ ]);++ 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("updates var() with keyword fallback (fallback unchanged)", () => {+ const styles = new Map<string, StyleDecl>([+ [+ "styleSourceId:base:color",+ {+ breakpointId: "base",+ styleSourceId: "styleSourceId",+ property: "color" as StyleProperty,+ value: {+ type: "var",+ value: "primary",+ fallback: { type: "keyword", value: "blue" },+ },+ },+ ],+ ]);++ const result = performCssVariableRename(+ styles,+ "--primary",+ "--primary-color"+ );++ const colorDecl = Array.from(result.values())[0];+ expect(colorDecl.value).toMatchObject({+ type: "var",+ value: "primary-color",+ fallback: { type: "keyword", value: "blue" },+ });+ });++ test("updates primary variable when it has a fallback", () => {+ const styles = new Map<string, StyleDecl>([+ [+ "styleSourceId:base:color",+ {+ breakpointId: "base",+ styleSourceId: "styleSourceId",+ property: "color" as StyleProperty,+ value: {+ type: "var",+ value: "old-primary",+ fallback: { type: "keyword", value: "blue" },+ } as StyleValue,+ },+ ],+ ]);++ const result = performCssVariableRename(+ styles,+ "--old-primary",+ "--new-primary"+ );++ const colorDecl = Array.from(result.values())[0];+ expect(colorDecl.value).toMatchObject({+ type: "var",+ value: "new-primary",+ fallback: { type: "keyword", value: "blue" },+ });+ });++ test("updates var() primary value when it has a keyword fallback", () => {+ const styles = new Map<string, StyleDecl>([+ [+ "styleSourceId:base:color",+ {+ breakpointId: "base",+ styleSourceId: "styleSourceId",+ property: "color" as StyleProperty,+ value: {+ type: "var",+ value: "theme-color",+ fallback: { type: "keyword", value: "blue" },+ },+ },+ ],+ ]);++ const result = performCssVariableRename(+ styles,+ "--theme-color",+ "--brand-color"+ );++ const colorDecl = Array.from(result.values())[0];+ expect(colorDecl.value).toMatchObject({+ type: "var",+ value: "brand-color",+ fallback: { type: "keyword", value: "blue" },+ });+ });++ 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");+ 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("updates var() with CSS variable fallback", () => {+ const props = new Map<string, Prop>([+ [+ "prop1",+ {+ id: "prop1",+ instanceId: "instance1",+ name: "code",+ type: "string",+ value: "color: var(--primary, --fallback);",+ },+ ],+ ]);++ const result = updateVarReferencesInProps(props, "--fallback", "--default");+ const prop = result.get("prop1");++ expect(prop!.value).toBe("color: var(--primary, --default);");+ });++ test("updates primary in var() with CSS variable fallback", () => {+ const props = new Map<string, Prop>([+ [+ "prop1",+ {+ id: "prop1",+ instanceId: "instance1",+ name: "code",+ type: "string",+ value: "color: var(--primary, --fallback);",+ },+ ],+ ]);++ const result = updateVarReferencesInProps(props, "--primary", "--main");+ const prop = result.get("prop1");++ expect(prop!.value).toBe("color: var(--main, --fallback);");+ });++ test("updates multiple variables in var() with multiple fallbacks", () => {+ const props = new Map<string, Prop>([+ [+ "prop1",+ {+ id: "prop1",+ instanceId: "instance1",+ name: "code",+ type: "string",+ value:+ "background: linear-gradient(var(--color1, --fb1), var(--color2, --fb2));",+ },+ ],+ ]);++ const result = updateVarReferencesInProps(props, "--color1", "--primary");+ const prop = result.get("prop1");++ expect(prop!.value).toBe(+ "background: linear-gradient(var(--primary, --fb1), var(--color2, --fb2));"+ );+ });++ test("updates nested var() with variable fallbacks", () => {+ const props = new Map<string, Prop>([+ [+ "prop1",+ {+ id: "prop1",+ instanceId: "instance1",+ name: "code",+ type: "string",+ value: "color: var(--first, var(--second, --third));",+ },+ ],+ ]);++ const result = updateVarReferencesInProps(props, "--second", "--backup");+ const prop = result.get("prop1");++ expect(prop!.value).toBe("color: var(--first, var(--backup, --third));");+ });++ 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");++ // Simple regex replacement preserves whitespace+ 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)");+ });+});++describe("findCssVariableUsagesByInstance - edge cases and malformed syntax", () => {+ test("tracks variables with extra whitespace", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--spacing::",+ createStyleDecl("local1", "base", "--spacing", "10px"),+ ],+ [+ "local1:base:padding::",+ createStyleDecl("local1", "base", "padding", "var( --spacing )"),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--spacing")).toBe(1);+ });++ test("tracks variables without spaces after var(", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--color::",+ createStyleDecl("local1", "base", "--color", "red"),+ ],+ [+ "local1:base:backgroundColor::",+ createStyleDecl("local1", "base", "backgroundColor", "var(--color)"),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--color")).toBe(1);+ });++ test("tracks variables in uppercase VAR()", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--size::",+ createStyleDecl("local1", "base", "--size", "20px"),+ ],+ [+ "local1:base:width::",+ createStyleDecl("local1", "base", "width", "VAR(--size)"),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--size")).toBe(1);+ });++ test("tracks variables with underscores", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--my_variable::",+ createStyleDecl("local1", "base", "--my_variable", "value"),+ ],+ [+ "local1:base:color::",+ createStyleDecl("local1", "base", "color", "var(--my_variable)"),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--my_variable")).toBe(1);+ });++ test("tracks variables in nested calc expressions", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--base::",+ createStyleDecl("local1", "base", "--base", "10px"),+ ],+ [+ "local1:base:--multiplier::",+ createStyleDecl("local1", "base", "--multiplier", "2"),+ ],+ [+ "local1:base:width::",+ createStyleDecl(+ "local1",+ "base",+ "width",+ "calc(calc(var(--base) * var(--multiplier)) + 5px)"+ ),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--base")).toBe(1);+ expect(counts.get("--multiplier")).toBe(1);+ });++ test("tracks variables in clamp()", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--min::",+ createStyleDecl("local1", "base", "--min", "10px"),+ ],+ [+ "local1:base:--preferred::",+ createStyleDecl("local1", "base", "--preferred", "5vw"),+ ],+ [+ "local1:base:--max::",+ createStyleDecl("local1", "base", "--max", "50px"),+ ],+ [+ "local1:base:fontSize::",+ createStyleDecl(+ "local1",+ "base",+ "fontSize",+ "clamp(var(--min), var(--preferred), var(--max))"+ ),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--min")).toBe(1);+ expect(counts.get("--preferred")).toBe(1);+ expect(counts.get("--max")).toBe(1);+ });++ test("tracks variables in min() and max()", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--size-a::",+ createStyleDecl("local1", "base", "--size-a", "100px"),+ ],+ [+ "local1:base:--size-b::",+ createStyleDecl("local1", "base", "--size-b", "50vw"),+ ],+ [+ "local1:base:width::",+ createStyleDecl(+ "local1",+ "base",+ "width",+ "min(var(--size-a), var(--size-b))"+ ),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--size-a")).toBe(1);+ expect(counts.get("--size-b")).toBe(1);+ });++ test("tracks variables in rgba()", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--red::",+ createStyleDecl("local1", "base", "--red", "255"),+ ],+ [+ "local1:base:--alpha::",+ createStyleDecl("local1", "base", "--alpha", "0.5"),+ ],+ [+ "local1:base:color::",+ createStyleDecl(+ "local1",+ "base",+ "color",+ "rgba(var(--red), 0, 0, var(--alpha))"+ ),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--red")).toBe(1);+ expect(counts.get("--alpha")).toBe(1);+ });++ test("tracks variables in transform functions", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--rotate::",+ createStyleDecl("local1", "base", "--rotate", "45deg"),+ ],+ [+ "local1:base:--scale::",+ createStyleDecl("local1", "base", "--scale", "1.5"),+ ],+ [+ "local1:base:transform::",+ createStyleDecl(+ "local1",+ "base",+ "transform",+ "rotate(var(--rotate)) scale(var(--scale))"+ ),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--rotate")).toBe(1);+ expect(counts.get("--scale")).toBe(1);+ });++ test("tracks variables in filter functions", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--blur-amount::",+ createStyleDecl("local1", "base", "--blur-amount", "5px"),+ ],+ [+ "local1:base:filter::",+ createStyleDecl("local1", "base", "filter", "blur(var(--blur-amount))"),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--blur-amount")).toBe(1);+ });++ test("tracks variables in url() with concatenation", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--image-path::",+ createStyleDecl("local1", "base", "--image-path", "/images/bg.jpg"),+ ],+ [+ "local1:base:backgroundImage::",+ createStyleDecl(+ "local1",+ "base",+ "backgroundImage",+ "url(var(--image-path))"+ ),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--image-path")).toBe(1);+ });++ test("tracks variables with very long names", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const longVarName =+ "--this-is-a-very-long-variable-name-with-many-hyphens-and-words";++ const styles = new Map([+ [+ `local1:base:${longVarName}::`,+ createStyleDecl("local1", "base", longVarName, "value"),+ ],+ [+ "local1:base:color::",+ createStyleDecl("local1", "base", "color", `var(${longVarName})`),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get(longVarName)).toBe(1);+ });++ test("tracks variables in custom properties with var()", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--base-color::",+ createStyleDecl("local1", "base", "--base-color", "blue"),+ ],+ [+ "local1:base:--derived-color::",+ createStyleDecl(+ "local1",+ "base",+ "--derived-color",+ "var(--base-color)"+ ),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--base-color")).toBe(1);+ });++ test("tracks same variable used multiple times in one value", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--spacing::",+ createStyleDecl("local1", "base", "--spacing", "10px"),+ ],+ [+ "local1:base:padding::",+ createStyleDecl(+ "local1",+ "base",+ "padding",+ "var(--spacing) var(--spacing) var(--spacing) var(--spacing)"+ ),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ // Should count as 1 usage since it's the same property+ expect(counts.get("--spacing")).toBe(1);+ });++ test("handles variables that look like numbers", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--100::",+ createStyleDecl("local1", "base", "--100", "value"),+ ],+ [+ "local1:base:color::",+ createStyleDecl("local1", "base", "color", "var(--100)"),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--100")).toBe(1);+ });++ test("tracks variables with emoji (technically valid CSS)", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--😀::",+ createStyleDecl("local1", "base", "--😀", "happy"),+ ],+ [+ "local1:base:content::",+ createStyleDecl("local1", "base", "content", "var(--😀)"),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--😀")).toBe(1);+ });++ test("tracks variables in grid-template-* properties", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--col-width::",+ createStyleDecl("local1", "base", "--col-width", "1fr"),+ ],+ [+ "local1:base:gridTemplateColumns::",+ createStyleDecl(+ "local1",+ "base",+ "gridTemplateColumns",+ "var(--col-width) var(--col-width) var(--col-width)"+ ),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--col-width")).toBe(1);+ });++ test("tracks variables in animation properties", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--duration::",+ createStyleDecl("local1", "base", "--duration", "2s"),+ ],+ [+ "local1:base:animationDuration::",+ createStyleDecl(+ "local1",+ "base",+ "animationDuration",+ "var(--duration)"+ ),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--duration")).toBe(1);+ });++ test("tracks variables in box-shadow with multiple shadows", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--shadow-color::",+ createStyleDecl("local1", "base", "--shadow-color", "rgba(0,0,0,0.2)"),+ ],+ [+ "local1:base:boxShadow::",+ createStyleDecl(+ "local1",+ "base",+ "boxShadow",+ "0 2px 4px var(--shadow-color), 0 4px 8px var(--shadow-color)"+ ),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--shadow-color")).toBe(1);+ });++ test("tracks variables in incorrect syntax (missing closing paren)", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--color::",+ createStyleDecl("local1", "base", "--color", "red"),+ ],+ [+ "local1:base:backgroundColor::",+ // Malformed - missing closing paren+ createStyleDecl("local1", "base", "backgroundColor", "var(--color"),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ // Should still track it because we're just searching for the string+ expect(counts.get("--color")).toBe(1);+ });++ test("tracks variables in string concatenation syntax (invalid but user might try)", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--prefix::",+ createStyleDecl("local1", "base", "--prefix", "hello"),+ ],+ [+ "local1:base:content::",+ // Invalid syntax but user might try it+ createStyleDecl("local1", "base", "content", "var(--prefix) + world"),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--prefix")).toBe(1);+ });++ test("tracks variables with spaces in names (technically invalid)", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--my color::",+ createStyleDecl("local1", "base", "--my color", "red"),+ ],+ [+ "local1:base:color::",+ createStyleDecl("local1", "base", "color", "var(--my color)"),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ // Should track it even though it's invalid CSS+ expect(counts.get("--my color")).toBe(1);+ });++ test("distinguishes between similar variable names", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--color::",+ createStyleDecl("local1", "base", "--color", "red"),+ ],+ [+ "local1:base:--color-dark::",+ createStyleDecl("local1", "base", "--color-dark", "darkred"),+ ],+ [+ "local1:base:--color-darker::",+ createStyleDecl("local1", "base", "--color-darker", "maroon"),+ ],+ [+ "local1:base:backgroundColor::",+ createStyleDecl("local1", "base", "backgroundColor", "var(--color)"),+ ],+ [+ "local1:base:color::",+ createStyleDecl("local1", "base", "color", "var(--color-dark)"),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--color")).toBe(1);+ expect(counts.get("--color-dark")).toBe(1);+ expect(counts.get("--color-darker")).toBeUndefined();+ });+});++describe("Word boundary edge cases - no-space contexts", () => {+ test("tracks variable followed by percentage without space", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--opacity::",+ createStyleDecl("local1", "base", "--opacity", "50"),+ ],+ [+ "local1:base:background::",+ createStyleDecl(+ "local1",+ "base",+ "background",+ "linear-gradient(90deg, red var(--opacity)%)"+ ),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--opacity")).toBe(1);+ });++ test("tracks variable in tight arithmetic without spaces", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--size::",+ createStyleDecl("local1", "base", "--size", "100px"),+ ],+ [+ "local1:base:width::",+ createStyleDecl("local1", "base", "width", "calc(var(--size)-10px)"),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--size")).toBe(1);+ });++ test("tracks variable followed by closing paren then another function", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--blur::",+ createStyleDecl("local1", "base", "--blur", "5px"),+ ],+ [+ "local1:base:--brightness::",+ createStyleDecl("local1", "base", "--brightness", "1.2"),+ ],+ [+ "local1:base:filter::",+ createStyleDecl(+ "local1",+ "base",+ "filter",+ "blur(var(--blur))brightness(var(--brightness))"+ ),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--blur")).toBe(1);+ expect(counts.get("--brightness")).toBe(1);+ });++ test("tracks variable in malformed concatenation", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--value::",+ createStyleDecl("local1", "base", "--value", "10"),+ ],+ [+ "local1:base:content::",+ // Malformed but user might try it+ createStyleDecl("local1", "base", "content", "var(--value)px"),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--value")).toBe(1);+ });+});++describe("Renaming with potential interference", () => {+ test("renames --color to --color-new without breaking", () => {+ const styles = new Map<string, StyleDecl>([+ [+ "styleSourceId:base:--color",+ {+ breakpointId: "base",+ styleSourceId: "styleSourceId",+ property: "--color" as StyleProperty,+ value: { type: "keyword", value: "red" },+ },+ ],+ [+ "styleSourceId:base:backgroundColor",+ {+ breakpointId: "base",+ styleSourceId: "styleSourceId",+ property: "backgroundColor" as StyleProperty,+ value: { type: "var", value: "color" },+ },+ ],+ ]);++ const result = performCssVariableRename(styles, "--color", "--color-new");++ const bgDecl = Array.from(result.values()).find(+ (d) => d.property === "backgroundColor"+ );+ expect(bgDecl?.value).toEqual({ type: "var", value: "color-new" });++ const colorDef = Array.from(result.values()).find(+ (d) => d.property === "--color-new"+ );+ expect(colorDef).toBeDefined();+ expect(colorDef?.value).toEqual({ type: "keyword", value: "red" });+ });++ test("renames --x to --xx without affecting --xxx", () => {+ const styles = new Map<string, StyleDecl>([+ [+ "styleSourceId:base:--x",+ {+ breakpointId: "base",+ styleSourceId: "styleSourceId",+ property: "--x" as StyleProperty,+ value: { type: "keyword", value: "value1" },+ },+ ],+ [+ "styleSourceId:base:--xxx",+ {+ breakpointId: "base",+ styleSourceId: "styleSourceId",+ property: "--xxx" as StyleProperty,+ value: { type: "keyword", value: "value2" },+ },+ ],+ [+ "styleSourceId:base:width",+ {+ breakpointId: "base",+ styleSourceId: "styleSourceId",+ property: "width" as StyleProperty,+ value: { type: "var", value: "x" },+ },+ ],+ [+ "styleSourceId:base:height",+ {+ breakpointId: "base",+ styleSourceId: "styleSourceId",+ property: "height" as StyleProperty,+ value: { type: "var", value: "xxx" },+ },+ ],+ ]);++ const result = performCssVariableRename(styles, "--x", "--xx");++ const widthDecl = Array.from(result.values()).find(+ (d) => d.property === "width"+ );+ expect(widthDecl?.value).toEqual({ type: "var", value: "xx" });++ const heightDecl = Array.from(result.values()).find(+ (d) => d.property === "height"+ );+ // Should NOT be affected+ expect(heightDecl?.value).toEqual({ type: "var", value: "xxx" });+ });++ test("handles variable in both var type and unparsed string", () => {+ const styles = new Map<string, StyleDecl>([+ [+ "styleSourceId:base:--spacing",+ {+ breakpointId: "base",+ styleSourceId: "styleSourceId",+ property: "--spacing" as StyleProperty,+ value: { type: "keyword", value: "10px" },+ },+ ],+ [+ "styleSourceId:base:padding",+ {+ breakpointId: "base",+ styleSourceId: "styleSourceId",+ property: "padding" as StyleProperty,+ value: { type: "var", value: "spacing" },+ },+ ],+ [+ "styleSourceId:base:width",+ {+ breakpointId: "base",+ styleSourceId: "styleSourceId",+ property: "width" as StyleProperty,+ value: {+ type: "unparsed",+ value: "calc(100% - var(--spacing))",+ },+ },+ ],+ ]);++ const result = performCssVariableRename(+ styles,+ "--spacing",+ "--new-spacing"+ );++ const paddingDecl = Array.from(result.values()).find(+ (d) => (d.property as string) === "padding"+ );+ expect(paddingDecl?.value).toEqual({ type: "var", value: "new-spacing" });++ const widthDecl = Array.from(result.values()).find(+ (d) => (d.property as string) === "width"+ );+ expect(widthDecl?.value).toEqual({+ type: "unparsed",+ value: "calc(100% - var(--new-spacing))",+ });+ });+});++describe("HTML Embed edge cases", () => {+ test("tracks variables in minified CSS", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--primary::",+ createStyleDecl("local1", "base", "--primary", "blue"),+ ],+ [+ "local1:base:--secondary::",+ createStyleDecl("local1", "base", "--secondary", "red"),+ ],+ ]);++ const props = new Map([+ [+ "prop1",+ {+ id: "prop1",+ instanceId: "box1",+ type: "string" as const,+ name: "code",+ value:+ "<style>.a{color:var(--primary);background:var(--secondary)}</style>",+ },+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props,+ });++ expect(counts.get("--primary")).toBe(1);+ expect(counts.get("--secondary")).toBe(1);+ });++ test("tracks variables in inline styles within HTML", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--text-color::",+ createStyleDecl("local1", "base", "--text-color", "navy"),+ ],+ [+ "local1:base:--bg-color::",+ createStyleDecl("local1", "base", "--bg-color", "white"),+ ],+ ]);++ const props = new Map([+ [+ "prop1",+ {+ id: "prop1",+ instanceId: "box1",+ type: "string" as const,+ name: "code",+ value: `+ <div style="color: var(--text-color)">+ <span style="background: var(--bg-color)">Text</span>+ </div>+ `,+ },+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props,+ });++ expect(counts.get("--text-color")).toBe(1);+ expect(counts.get("--bg-color")).toBe(1);+ });++ test("tracks variables with multiple HTML elements", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--spacing::",+ createStyleDecl("local1", "base", "--spacing", "1rem"),+ ],+ ]);++ const props = new Map([+ [+ "prop1",+ {+ id: "prop1",+ instanceId: "box1",+ type: "string" as const,+ name: "code",+ value: `+ <div style="margin: var(--spacing)">+ <p style="padding: var(--spacing)">Content</p>+ <span style="gap: var(--spacing)">More</span>+ </div>+ `,+ },+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props,+ });++ // Should count as 1 usage (same instance, even if multiple occurrences)+ expect(counts.get("--spacing")).toBe(1);+ });++ test("updates variables in minified CSS", () => {+ const props = new Map<string, Prop>([+ [+ "prop1",+ {+ id: "prop1",+ instanceId: "instance1",+ name: "code",+ type: "string",+ value: ".x{color:var(--old);background:var(--old)}",+ },+ ],+ ]);++ const result = updateVarReferencesInProps(props, "--old", "--new");+ const prop = result.get("prop1");++ expect(prop!.value).toBe(".x{color:var(--new);background:var(--new)}");+ });++ test("updates variables in inline styles", () => {+ const props = new Map<string, Prop>([+ [+ "prop1",+ {+ id: "prop1",+ instanceId: "instance1",+ name: "code",+ type: "string",+ value:+ '<div style="color: var(--theme)"><span style="background: var(--theme)">Text</span></div>',+ },+ ],+ ]);++ const result = updateVarReferencesInProps(props, "--theme", "--brand");+ const prop = result.get("prop1");++ expect(prop!.value).toBe(+ '<div style="color: var(--brand)"><span style="background: var(--brand)">Text</span></div>'+ );+ });+});- const colorDecl = Array.from(result.values()).find(- (d) => d.property === "color"+describe("Deeply nested structures", () => {+ test("preserves deeply nested var in layers > function > tuple", () => {+ const styles = new Map<string, StyleDecl>([+ [+ "styleSourceId:base:filter",+ {+ breakpointId: "base",+ styleSourceId: "styleSourceId",+ property: "filter" as StyleProperty,+ value: {+ type: "layers",+ value: [+ {+ type: "function",+ name: "drop-shadow",+ args: {+ type: "tuple",+ value: [+ { type: "unit", value: 0, unit: "px" },+ { type: "unit", value: 0, unit: "px" },+ { type: "var", value: "shadow-blur" },+ { type: "var", value: "shadow-color" },+ ],+ },+ } as StyleValue,+ ],+ } as StyleValue,+ },+ ],+ ]);++ const result = performCssVariableRename(+ styles,+ "--shadow-blur",+ "--blur-amount");- expect(colorDecl?.value).toEqual({ type: "var", value: "other-color" });++ const filterDecl = Array.from(result.values())[0];+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const filterValue = filterDecl.value as any;++ expect(filterValue.type).toBe("layers");+ expect(filterValue.value[0].type).toBe("function");+ expect(filterValue.value[0].args.type).toBe("tuple");+ expect(filterValue.value[0].args.value[2]).toEqual({+ type: "var",+ value: "blur-amount",+ });+ expect(filterValue.value[0].args.value[3]).toEqual({+ type: "var",+ value: "shadow-color",+ });});- test("handles values with no references", () => {+ test("handles shadow with var in all fields", () => {const styles = new Map<string, StyleDecl>([[- "styleSourceId:base:--my-color",+ "styleSourceId:base:boxShadow",{breakpointId: "base",styleSourceId: "styleSourceId",- property: "--my-color" as StyleProperty,- value: { type: "keyword", value: "red" },+ property: "boxShadow" as StyleProperty,+ value: {+ type: "layers",+ value: [+ {+ type: "shadow",+ offsetX: { type: "var", value: "offset-x" },+ offsetY: { type: "var", value: "offset-y" },+ blur: { type: "var", value: "blur-size" },+ spread: { type: "var", value: "spread-size" },+ color: { type: "var", value: "shadow-color" },+ },+ ],+ } as StyleValue,},],+ ]);++ // Test renaming each field independently+ let result = performCssVariableRename(styles, "--offset-x", "--x");+ let shadowDecl = Array.from(result.values())[0];+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ let shadowValue = (shadowDecl.value as any).value[0];+ expect(shadowValue.offsetX).toEqual({ type: "var", value: "x" });++ result = performCssVariableRename(styles, "--blur-size", "--blur");+ shadowDecl = Array.from(result.values())[0];+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ shadowValue = (shadowDecl.value as any).value[0];+ expect(shadowValue.blur).toEqual({ type: "var", value: "blur" });++ result = performCssVariableRename(styles, "--shadow-color", "--color");+ shadowDecl = Array.from(result.values())[0];+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ shadowValue = (shadowDecl.value as any).value[0];+ expect(shadowValue.color).toEqual({ type: "var", value: "color" });+ });++ test("preserves 5-level nested structure", () => {+ const styles = new Map<string, StyleDecl>([[- "styleSourceId:base:fontSize",+ "styleSourceId:base:filter",{breakpointId: "base",styleSourceId: "styleSourceId",- property: "fontSize" as StyleProperty,- value: { type: "unit", value: 16, unit: "px" },+ property: "filter" as StyleProperty,+ value: {+ type: "layers",+ value: [+ {+ type: "function",+ name: "drop-shadow",+ args: {+ type: "tuple",+ value: [+ {+ type: "function",+ name: "calc",+ args: {+ type: "unparsed",+ value: "var(--deep-var) * 2",+ },+ } as StyleValue,+ ],+ },+ } as StyleValue,+ ],+ } as StyleValue,},],]);const result = performCssVariableRename(styles,- "--my-color",- "--new-color"+ "--deep-var",+ "--renamed-deep");- expect(result.size).toBe(2);- const fontSizeDecl = Array.from(result.values()).find(- (d) => d.property === "fontSize"+ const filterDecl = Array.from(result.values())[0];+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const filterValue = filterDecl.value as any;++ expect(filterValue.value[0].args.value[0].args.value).toBe(+ "var(--renamed-deep) * 2");- // 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([+describe("Special character variable names", () => {+ test("handles variables with special regex chars in complex values", () => {+ const styleSourceSelections = new Map([[- "prop1",+ "box1",{- id: "prop1",- instanceId: "embed1",- name: "code",- type: "string" as const,- value: `<style>- .custom {- color: var(--theme-color);- background: var(--theme-color, blue);- }-</style>`,+ instanceId: "box1",+ values: ["local1"],},],]);- const oldProperty = "--theme-color";- const newProperty = "--brand-color";+ const styles = new Map([+ [+ "local1:base:--color-$special::",+ createStyleDecl("local1", "base", "--color-$special", "red"),+ ],+ [+ "local1:base:width::",+ createStyleDecl(+ "local1",+ "base",+ "width",+ "calc(var(--color-$special) * 2)"+ ),+ ],+ ]);- // Simulate the rename logic for props- const regex = new RegExp(- `var\\(\\s*${oldProperty.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`,- "g"+ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--color-$special")).toBe(1);+ });++ test("renames variables with special regex chars", () => {+ const styles = new Map<string, StyleDecl>([+ [+ "styleSourceId:base:--var-$test",+ {+ breakpointId: "base",+ styleSourceId: "styleSourceId",+ property: "--var-$test" as StyleProperty,+ value: { type: "keyword", value: "value" },+ },+ ],+ [+ "styleSourceId:base:color",+ {+ breakpointId: "base",+ styleSourceId: "styleSourceId",+ property: "color" as StyleProperty,+ value: { type: "var", value: "var-$test" },+ },+ ],+ ]);++ const result = performCssVariableRename(+ styles,+ "--var-$test",+ "--var-$new");- 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)");+ const colorDecl = Array.from(result.values()).find(+ (d) => d.property === "color"+ );+ expect(colorDecl?.value).toEqual({ type: "var", value: "var-$new" });+ });- // Verify the original had the old name- expect(prop!.value).toContain("var(--theme-color)");+ test("handles variables with dots", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--version-1.0::",+ createStyleDecl("local1", "base", "--version-1.0", "value"),+ ],+ [+ "local1:base:color::",+ createStyleDecl("local1", "base", "color", "var(--version-1.0)"),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ expect(counts.get("--version-1.0")).toBe(1);+ });++ test("handles variables with parentheses in name", () => {+ const styles = new Map<string, StyleDecl>([+ [+ "styleSourceId:base:--var(test)",+ {+ breakpointId: "base",+ styleSourceId: "styleSourceId",+ property: "--var(test)" as StyleProperty,+ value: { type: "keyword", value: "value" },+ },+ ],+ [+ "styleSourceId:base:color",+ {+ breakpointId: "base",+ styleSourceId: "styleSourceId",+ property: "color" as StyleProperty,+ value: { type: "var", value: "var(test)" },+ },+ ],+ ]);++ const result = performCssVariableRename(+ styles,+ "--var(test)",+ "--var-test"+ );++ const colorDecl = Array.from(result.values()).find(+ (d) => d.property === "color"+ );+ expect(colorDecl?.value).toEqual({ type: "var", value: "var-test" });});});-describe("updateVarReferencesInProps", () => {- test("updates single var() reference in HTML Embed code", () => {- const props = new Map<string, Prop>([+describe("Performance and optimization validation", () => {+ test("only tracks defined variables, not undefined ones", () => {+ const styleSourceSelections = new Map([+ [+ "box1",+ {+ instanceId: "box1",+ values: ["local1"],+ },+ ],+ ]);++ const styles = new Map([+ [+ "local1:base:--defined::",+ createStyleDecl("local1", "base", "--defined", "value"),+ ],+ [+ "local1:base:color::",+ // References undefined variable+ createStyleDecl("local1", "base", "color", "var(--undefined)"),+ ],+ ]);++ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ // Should not track --undefined since it's not defined+ expect(counts.get("--undefined")).toBeUndefined();+ expect(counts.size).toBe(0);+ });++ test("breaks early when finding referenced variables", () => {+ // This test validates the optimization in $referencedCssVariables+ const styleSourceSelections = new Map([[- "prop1",+ "box1",{- id: "prop1",- instanceId: "instance1",- name: "code",- type: "string",- value: '<div style="color: var(--primary)">Text</div>',+ instanceId: "box1",+ values: ["local1"],},],]);- const result = updateVarReferencesInProps(- props,- "--primary",- "--main-color"- );- const prop = result.get("prop1");+ const styles = new Map([+ [+ "local1:base:--used::",+ createStyleDecl("local1", "base", "--used", "value"),+ ],+ [+ "local1:base:color1::",+ createStyleDecl("local1", "base", "color1", "var(--used)"),+ ],+ [+ "local1:base:color2::",+ // Another reference to same variable - should not increase processing+ createStyleDecl("local1", "base", "color2", "var(--used)"),+ ],+ ]);- expect(prop!.value).toBe(- '<div style="color: var(--main-color)">Text</div>'- );- expect(prop!.value).not.toContain("--primary");+ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ // Both usages should be counted+ expect(counts.get("--used")).toBe(2);});+});- test("updates multiple occurrences in same prop", () => {- const props = new Map<string, Prop>([+describe("$unusedCssVariables and deleteUnusedCssVariables", () => {+ test("identifies unused variables correctly", () => {+ const styleSourceSelections = new Map([[- "prop1",+ "root",{- id: "prop1",- instanceId: "instance1",- name: "code",- type: "string",- value: "var(--color) and var(--color, red)",+ instanceId: "root",+ values: ["local1"],},],]);- const result = updateVarReferencesInProps(props, "--color", "--new-color");- const prop = result.get("prop1");+ const styles = new Map([+ [+ "local1:base:--used::",+ createStyleDecl("local1", "base", "--used", "red"),+ ],+ [+ "local1:base:--unused::",+ createStyleDecl("local1", "base", "--unused", "blue"),+ ],+ [+ "local1:base:color::",+ createStyleDecl("local1", "base", "color", "var(--used)"),+ ],+ ]);- expect(prop!.value).toBe("var(--new-color) and var(--new-color, red)");- expect(prop!.value).not.toContain("var(--color");+ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ // --used should have 1 usage, --unused should have 0+ expect(counts.get("--used")).toBe(1);+ expect(counts.get("--unused")).toBeUndefined();});- test("preserves fallback values", () => {- const props = new Map<string, Prop>([+ test("only considers variables associated with instances", () => {+ const styleSourceSelections = new Map([[- "prop1",+ "root",{- id: "prop1",- instanceId: "instance1",- name: "code",- type: "string",- value: "var(--bg, #fff)",+ instanceId: "root",+ values: ["local1"],},],]);- const result = updateVarReferencesInProps(props, "--bg", "--background");- const prop = result.get("prop1");+ // orphaned-source is not in styleSourceSelections+ const styles = new Map([+ [+ "local1:base:--visible::",+ createStyleDecl("local1", "base", "--visible", "red"),+ ],+ [+ "orphaned-source:base:--orphaned::",+ createStyleDecl("orphaned-source", "base", "--orphaned", "blue"),+ ],+ ]);- expect(prop!.value).toBe("var(--background, #fff)");+ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ // --visible should be tracked (no usages, so undefined)+ // --orphaned should not be tracked at all+ expect(counts.has("--visible")).toBe(false);+ expect(counts.has("--orphaned")).toBe(false);});- test("handles special regex characters in variable name", () => {- const props = new Map<string, Prop>([+ test("detects variables used in HTML Embed code props", () => {+ const styleSourceSelections = new Map([[- "prop1",+ "root",{- id: "prop1",- instanceId: "instance1",- name: "code",- type: "string",- value: "var(--color-$special)",+ instanceId: "root",+ values: ["local1"],+ },+ ],+ [+ "embed",+ {+ instanceId: "embed",+ values: ["local2"],},],]);- const result = updateVarReferencesInProps(- props,- "--color-$special",- "--normal"- );- const prop = result.get("prop1");-- expect(prop!.value).toBe("var(--normal)");- });+ const styles = new Map([+ [+ "local1:base:--used-in-embed::",+ createStyleDecl("local1", "base", "--used-in-embed", "red"),+ ],+ [+ "local1:base:--unused::",+ createStyleDecl("local1", "base", "--unused", "blue"),+ ],+ ]);- test("does not update when no matches found", () => {- const props = new Map<string, Prop>([+ const props = new Map([[- "prop1",+ "embed-code",{- id: "prop1",- instanceId: "instance1",+ id: "embed-code",+ instanceId: "embed",+ type: "string" as const,name: "code",- type: "string",- value: "var(--other)",+ value: "<style>.test { color: var(--used-in-embed); }</style>",},],]);- const result = updateVarReferencesInProps(props, "--primary", "--main");- const prop = result.get("prop1");+ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props,+ });- expect(prop!.value).toBe("var(--other)");+ // --used-in-embed should have 1 usage+ expect(counts.get("--used-in-embed")).toBe(1);+ expect(counts.get("--unused")).toBeUndefined();});- test("ignores non-code props", () => {- const props = new Map<string, Prop>([+ test("handles variables on root instance", () => {+ const styleSourceSelections = new Map([[- "prop1",+ "root",{- id: "prop1",- instanceId: "instance1",- name: "className",- type: "string",- value: "var(--color)",+ instanceId: "root",+ values: ["root-local"],+ },+ ],+ [+ "child",+ {+ instanceId: "child",+ values: ["child-local"],},],]);- 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 styles = new Map([+ [+ "root-local:base:--root-var::",+ createStyleDecl("root-local", "base", "--root-var", "red"),+ ],+ [+ "child-local:base:color::",+ createStyleDecl("child-local", "base", "color", "var(--root-var)"),+ ],+ ]);- const result = updateVarReferencesInProps(props, "--primary", "--main");+ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });- expect(result.size).toBe(0);+ // --root-var should be used by child+ expect(counts.get("--root-var")).toBe(1);});- test("handles prop with empty value", () => {- const props = new Map<string, Prop>([+ test("distinguishes between similar variable names", () => {+ const styleSourceSelections = new Map([[- "prop1",+ "root",{- id: "prop1",- instanceId: "instance1",- name: "code",- type: "string",- value: "",+ instanceId: "root",+ values: ["local1"],},],]);- const result = updateVarReferencesInProps(props, "--color", "--new-color");- const prop = result.get("prop1");+ const styles = new Map([+ [+ "local1:base:--color::",+ createStyleDecl("local1", "base", "--color", "red"),+ ],+ [+ "local1:base:--color-dark::",+ createStyleDecl("local1", "base", "--color-dark", "darkred"),+ ],+ [+ "local1:base:background::",+ // Uses --color but not --color-dark+ createStyleDecl("local1", "base", "background", "var(--color)"),+ ],+ ]);- expect(prop!.value).toBe("");+ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ // --color should be used, --color-dark should not+ expect(counts.get("--color")).toBe(1);+ expect(counts.get("--color-dark")).toBeUndefined();});- test("handles whitespace variations in var()", () => {- const props = new Map<string, Prop>([+ test("handles multiple instances defining the same variable", () => {+ const styleSourceSelections = new Map([[- "prop1",+ "instance1",{- id: "prop1",instanceId: "instance1",- name: "code",- type: "string",- value: "var( --spacing ) and var( --spacing, 10px)",+ values: ["local1"],+ },+ ],+ [+ "instance2",+ {+ instanceId: "instance2",+ values: ["local2"],},],]);- const result = updateVarReferencesInProps(- props,- "--spacing",- "--new-spacing"- );- const prop = result.get("prop1");+ const styles = new Map([+ [+ "local1:base:--shared::",+ createStyleDecl("local1", "base", "--shared", "value1"),+ ],+ [+ "local2:base:--shared::",+ createStyleDecl("local2", "base", "--shared", "value2"),+ ],+ [+ "local1:base:color::",+ createStyleDecl("local1", "base", "color", "var(--shared)"),+ ],+ ]);- // 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)"- );+ const { counts, instances } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ // --shared should be used once+ expect(counts.get("--shared")).toBe(1);+ // Usage is from instance1+ expect(instances.get("--shared")).toEqual(new Set(["instance1"]));});- test("uses lookahead to avoid partial matches", () => {- const props = new Map<string, Prop>([+ test("variables used only within same instance are counted", () => {+ const styleSourceSelections = new Map([[- "prop1",+ "instance1",{- id: "prop1",instanceId: "instance1",- name: "code",- type: "string",- value: "var(--color) and var(--color-dark)",+ values: ["local1"],},],]);- const result = updateVarReferencesInProps(props, "--color", "--primary");- const prop = result.get("prop1");+ const styles = new Map([+ [+ "local1:base:--primary::",+ createStyleDecl("local1", "base", "--primary", "blue"),+ ],+ [+ "local1:base:color::",+ createStyleDecl("local1", "base", "color", "var(--primary)"),+ ],+ ]);- // Only --color should be updated, not --color-dark (lookahead ensures complete match)- expect(prop!.value).toBe("var(--primary) and var(--color-dark)");+ const { counts } = findCssVariableUsagesByInstance({+ styleSourceSelections,+ styles,+ props: new Map(),+ });++ // Variable defined and used in same instance+ expect(counts.get("--primary")).toBe(1);});});diff --git a/apps/builder/app/builder/shared/css-variable-utils.tsx b/apps/builder/app/builder/shared/css-variable-utils.tsxindex f394fd27b2..c5dfbd41ae 100644--- a/apps/builder/app/builder/shared/css-variable-utils.tsx+++ b/apps/builder/app/builder/shared/css-variable-utils.tsx@@ -22,12 +22,12 @@ import type {import type {StyleValue,StyleProperty,- CssProperty,+ CustomProperty,} from "@webstudio-is/css-engine";+import { toValue } 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);@@ -35,58 +35,36 @@ 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}`);- }+// Utility: Escape regex special characters+const escapeRegex = (str: string): string => {+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+};- // 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);- }- }- }- }+// Utility: Create regex to match variable name with word boundary+// This avoids matching --color inside --color-dark+// Uses negative lookahead (?![\\w-]) to ensure variable name doesn't continue+// with word characters or hyphens, preventing partial matches.+const createVarNameRegex = (varName: string): RegExp => {+ return new RegExp(`${escapeRegex(varName)}(?![\\w-])`, "g");};-// 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]);- }+// Traverse a StyleValue to find all var() references+const findVarReferences = (value: StyleValue, varName: string): boolean => {+ const valueStr = toValue(value);+ return createVarNameRegex(varName).test(valueStr);};// Find all CSS variable references in HTML Embed code props-const findVarReferencesInProps = (- props: Props,- callback: (varName: string) => void-) => {+const findVarReferencesInProps = (props: Props, varName: string): boolean => {+ const regex = createVarNameRegex(varName);for (const prop of props.values()) {if (prop.type === "string" && prop.name === "code" && prop.value) {- findVarReferencesInString(prop.value, callback);+ if (regex.test(prop.value)) {+ return true;+ }}}+ return false;};// Find CSS variable usage counts (how many times each variable is referenced via var())@@ -126,6 +104,17 @@ export const findCssVariableUsagesByInstance = ({instances.add(instanceId);};+ // Collect all defined variables+ // Performance optimization: Only check variables that are defined+ // instead of searching for all possible var() patterns.+ // This is O(defined_vars × styles) instead of O(all_patterns × styles).+ const definedVariables = new Set<string>();+ for (const styleDecl of styles.values()) {+ if (styleDecl.property.startsWith("--")) {+ definedVariables.add(styleDecl.property);+ }+ }+// Track CSS variable references in StyleDecl valuesfor (const styleDecl of styles.values()) {const instanceId = instancesByStyleSource.get(styleDecl.styleSourceId);@@ -133,20 +122,26 @@ export const findCssVariableUsagesByInstance = ({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);- });+ // Check each defined variable if it's used in this style+ for (const varName of definedVariables) {+ if (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);- });+ for (const varName of definedVariables) {+ if (findVarReferencesInProps(props, varName)) {+ // Find which instance this belongs to+ for (const prop of props.values()) {+ if (prop.type === "string" && prop.name === "code" && prop.value) {+ const regex = createVarNameRegex(varName);+ if (regex.test(prop.value)) {+ addVarReference(varName, prop.instanceId);+ }+ }+ }}}@@ -176,10 +171,10 @@ export const $cssVariableInstancesByVariable = computed(// Get all defined CSS variables (unique properties that start with --)export const $definedCssVariables = computed($styles, (styles) => {- const definedVariables = new Set<string>();+ const definedVariables = new Set<CustomProperty>();for (const styleDecl of styles.values()) {if (styleDecl.property.startsWith("--")) {- definedVariables.add(styleDecl.property);+ definedVariables.add(styleDecl.property as CustomProperty);}}return definedVariables;@@ -223,18 +218,54 @@ export const $referencedCssVariables = computed([$styles, $props],(styles, props) => {const referencedVariables = new Set<string>();++ // Collect all defined variables first+ const definedVariables = new Set<string>();for (const styleDecl of styles.values()) {- findVarReferences(styleDecl.value, (varName) => {+ if (styleDecl.property.startsWith("--")) {+ definedVariables.add(styleDecl.property);+ }+ }++ // Check which defined variables are referenced+ for (const varName of definedVariables) {+ // Check in styles+ // Performance optimization: We only need to know IF a variable is used (boolean),+ // not HOW MANY times, so we break on first match.+ for (const styleDecl of styles.values()) {+ if (findVarReferences(styleDecl.value, varName)) {+ referencedVariables.add(varName);+ break;+ }+ }++ // Check in props if not already found+ if (+ !referencedVariables.has(varName) &&+ findVarReferencesInProps(props, varName)+ ) {referencedVariables.add(varName);- });+ }}- findVarReferencesInProps(props, (varName) => {- referencedVariables.add(varName);- });+return referencedVariables;});+// Get all unused CSS variables (defined in instances but not referenced)+export const $unusedCssVariables = computed(+ [$cssVariableDefinitionsByVariable, $referencedCssVariables],+ (definitionsByVariable, referencedVariables) => {+ const unusedVariables = new Set<string>();+ for (const varName of definitionsByVariable.keys()) {+ if (!referencedVariables.has(varName)) {+ unusedVariables.add(varName);+ }+ }+ return unusedVariables;+ }+);+export type CssVariableError =| { type: "required"; message: string }| { type: "invalid"; message: string }@@ -282,46 +313,38 @@ const updateVarReferences = (oldProperty: string,newProperty: string): StyleValue => {- if (value.type === "var") {- const currentVarName = `--${value.value}`;- if (currentVarName === oldProperty) {- value = {- ...value,- value: newProperty.slice(2), // Remove -- prefix- };- }- }+ // For simple replacement, use JSON stringify/parse approach+ // since toValue produces CSS string which is harder to parse back+ let valueStr = JSON.stringify(value);++ // Handle two patterns:+ // 1. In var type objects: "value":"variable-name" (without --)+ // StyleValue stores var without -- prefix in "value" field+ // 2. In literal strings: "--variable-name" (with --)+ // Unparsed strings contain full --variable-name syntax+ // Both patterns are needed because StyleValue can contain both structured+ // var types and unparsed CSS strings with var() references++ // Strip -- prefix for var type replacement+ const oldVarName = oldProperty.startsWith("--")+ ? oldProperty.slice(2)+ : oldProperty;+ const newVarName = newProperty.startsWith("--")+ ? newProperty.slice(2)+ : newProperty;++ // Replace in var type value fields: "value":"old-name" -> "value":"new-name"+ // Use word boundary to avoid replacing "color" in "color-dark"+ const varTypeRegex = new RegExp(+ `("value":")${escapeRegex(oldVarName)}(?![\\w-])`,+ "g"+ );+ valueStr = valueStr.replace(varTypeRegex, `$1${newVarName}`);- // 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;+ // Also replace literal --variable-name in unparsed strings+ valueStr = valueStr.replace(createVarNameRegex(oldProperty), newProperty);++ return JSON.parse(valueStr) as StyleValue;};// Core rename logic without transaction wrapper (for testing)@@ -369,18 +392,11 @@ export const updateVarReferencesInProps = (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"- );+ const regex = createVarNameRegex(oldProperty);for (const [key, prop] of updatedProps) {if (prop.type === "string" && prop.name === "code" && prop.value) {- const updatedValue = prop.value.replace(regex, `var(${newProperty}`);+ const updatedValue = prop.value.replace(regex, newProperty);if (updatedValue !== prop.value) {updatedProps.set(key, { ...prop, value: updatedValue });}@@ -428,28 +444,28 @@ export const renameCssVariable = (};export const deleteUnusedCssVariables = () => {- const definedVariables = $definedCssVariables.get();- const referencedVariables = $referencedCssVariables.get();+ const unusedVariables = $unusedCssVariables.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) {+ if (unusedVariables.size === 0) {return 0;}- const batch = createBatchUpdate();- for (const varName of unusedVariables) {- batch.deleteProperty(varName as CssProperty);- }- batch.publish();+ // Delete all unused variable declarations+ serverSyncStore.createTransaction([$styles], (styles) => {+ const keysToDelete: string[] = [];- return unusedVariables.length;+ for (const [key, styleDecl] of styles) {+ if (unusedVariables.has(styleDecl.property)) {+ keysToDelete.push(key);+ }+ }++ for (const key of keysToDelete) {+ styles.delete(key);+ }+ });++ return unusedVariables.size;};type DeleteCssVariableDialogProps = {@@ -584,20 +600,14 @@ export const RenameCssVariableDialog = ({export const DeleteUnusedCssVariablesDialog = () => {const open = useStore($isDeleteUnusedCssVariablesDialogOpen);- const definedVariables = useStore($definedCssVariables);- const referencedVariables = useStore($referencedCssVariables);+ const unusedVariables = useStore($unusedCssVariables);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);- }- }+ // Convert Set to Array for display+ const unusedVariablesArray = Array.from(unusedVariables);return (<Dialog@@ -609,20 +619,21 @@ export const DeleteUnusedCssVariablesDialog = () => {}}><DialogContent+ width={400}onKeyDown={(event) => {event.stopPropagation();}}><DialogTitle>Delete unused CSS variables</DialogTitle><Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>- {unusedVariables.length === 0 ? (+ {unusedVariablesArray.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?+ Delete {unusedVariablesArray.length} unused CSS{" "}+ {unusedVariablesArray.length === 1 ? "variable" : "variables"}{" "}+ from the project?</Text><Textvariant="mono"@@ -634,12 +645,12 @@ export const DeleteUnusedCssVariablesDialog = () => {wordBreak: "break-word",}}>- {unusedVariables.join(", ")}+ {unusedVariablesArray.join(", ")}</Text></>)}<Flex direction="rowReverse" gap="2">- {unusedVariables.length > 0 && (+ {unusedVariablesArray.length > 0 && (<Buttoncolor="destructive"onClick={() => {@@ -659,7 +670,7 @@ export const DeleteUnusedCssVariablesDialog = () => {)}<DialogClose><Button color="ghost">- {unusedVariables.length > 0 ? "Cancel" : "Close"}+ {unusedVariablesArray.length > 0 ? "Cancel" : "Close"}</Button></DialogClose></Flex>diff --git a/apps/builder/app/shared/instance-utils.test.tsx b/apps/builder/app/shared/instance-utils.test.tsxindex 4b6a71d162..3713b4ffa4 100644--- a/apps/builder/app/shared/instance-utils.test.tsx+++ b/apps/builder/app/shared/instance-utils.test.tsx@@ -35,6 +35,7 @@ import {findClosestInsertable,insertWebstudioFragmentAt,insertWebstudioElementAt,+ buildInstancePath,} from "./instance-utils";import {$assets,@@ -1605,3 +1606,90 @@ describe("find closest insertable", () => {test("get undefined instead of instance path when no instances found", () => {expect(getInstancePath(["boxId"], new Map())).toEqual(undefined);});++describe("buildInstancePath", () => {+ const createPages = () =>+ createDefaultPages({+ homePageId: "homePageId",+ rootInstanceId: "rootId",+ systemDataSourceId: "systemId",+ });++ test("returns empty array when instance has no selector", () => {+ const pages = createPages();+ const instances = new Map();++ const result = buildInstancePath("nonexistent", pages, instances);+ expect(result).toEqual([]);+ });++ test("returns empty array for root instance (no ancestors)", () => {+ const { instances } = renderData(+ <$.Body ws:id="rootId">+ <$.Box ws:id="boxId"></$.Box>+ </$.Body>+ );+ const pages = createPages();++ const result = buildInstancePath("rootId", pages, instances);+ expect(result).toEqual([]);+ });++ test("builds path for single-level nesting", () => {+ const { instances } = renderData(+ <$.Body ws:id="rootId">+ <$.Box ws:id="boxId"></$.Box>+ </$.Body>+ );+ const pages = createPages();++ const result = buildInstancePath("boxId", pages, instances);+ expect(result).toEqual(["Body"]);+ });++ test("builds path for multi-level nesting", () => {+ const { instances } = renderData(+ <$.Body ws:id="rootId">+ <$.Box ws:id="containerId">+ <$.Heading ws:id="headingId"></$.Heading>+ </$.Box>+ </$.Body>+ );+ const pages = createPages();++ const result = buildInstancePath("headingId", pages, instances);+ expect(result).toEqual(["Body", "Box"]);+ });++ test("builds path for deeply nested instance", () => {+ const { instances } = renderData(+ <$.Body ws:id="rootId">+ <$.Box ws:id="sectionId">+ <$.Box ws:id="articleId">+ <$.Box ws:id="divId">+ <$.Text ws:id="textId"></$.Text>+ </$.Box>+ </$.Box>+ </$.Box>+ </$.Body>+ );+ const pages = createPages();++ const result = buildInstancePath("textId", pages, instances);+ expect(result).toEqual(["Body", "Box", "Box", "Box"]);+ });++ test("handles instances with custom labels", () => {+ const { instances } = renderData(+ <$.Body ws:id="rootId" ws:label="Main Body">+ <$.Box ws:id="navId" ws:label="Navigation">+ <$.Link ws:id="linkId" ws:label="Home Link"></$.Link>+ </$.Box>+ </$.Body>+ );+ const pages = createPages();++ const result = buildInstancePath("linkId", pages, instances);+ expect(result).toEqual(["Main Body", "Navigation"]);+ });+});diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.tsindex 6b3af0f2a6..b0dea5db60 100644--- a/apps/builder/app/shared/instance-utils.ts+++ b/apps/builder/app/shared/instance-utils.ts@@ -18,6 +18,7 @@ import {type WebstudioData,type Resource,type WsComponentMeta,+ type Pages,getStyleDeclKey,findTreeInstanceIds,findTreeInstanceIdsExcludingSlotDescendants,@@ -63,6 +64,7 @@ import {$awareness,$selectedInstancePath,$selectedPage,+ findAwarenessByInstanceId,getInstancePath,selectInstance,type InstancePath,@@ -1384,3 +1386,35 @@ export const findClosestInsertable = (position: lastChildPosition + 1,};};++/**+ * Build the ancestor path array for an instance.+ * Returns an array of labels for all ancestors from root to parent.+ */+export const buildInstancePath = (+ instanceId: Instance["id"],+ pages: Pages,+ instances: Instances+): string[] => {+ const awareness = findAwarenessByInstanceId(pages, instances, instanceId);+ if (!awareness.instanceSelector) {+ return [];+ }++ const instancePath = getInstancePath(+ awareness.instanceSelector,+ instances,+ undefined,+ undefined+ );++ if (!instancePath) {+ return [];+ }++ return instancePath+ .slice()+ .reverse()+ .slice(0, -1) // Remove the instance itself (last element after reverse), keep only ancestors+ .map(({ instance }) => getInstanceLabel(instance));+};diff --git a/packages/design-system/src/components/command.tsx b/packages/design-system/src/components/command.tsxindex 7f65c1b6fa..594690213a 100644--- a/packages/design-system/src/components/command.tsx+++ b/packages/design-system/src/components/command.tsx@@ -29,7 +29,7 @@ import { Popover, PopoverContent, PopoverTrigger } from "./popover";import { Kbd } from "./kbd";import { useDebounceEffect } from "../utilities";-const panelWidth = "400px";+const panelWidth = "500px";const itemHeight = "32px";const inputBorderBottomSize = "--command-input-border-bottom-width";diff --git a/packages/design-system/src/components/dialog.test.ts b/packages/design-system/src/components/dialog.test.tsnew file mode 100644index 0000000000..d407fee6e4--- /dev/null+++ b/packages/design-system/src/components/dialog.test.ts@@ -0,0 +1,287 @@+import { describe, test, expect } from "vitest";+import { __testing__ } from "./dialog";++const {+ calculateInset,+ calculateCenteredPosition,+ calculateDialogStyle,+ applyBoundaries,+} = __testing__;++describe("calculateInset", () => {+ test("calculates inset for centered boundary", () => {+ const bounds = { x: 100, y: 50, width: 800, height: 600 };+ const result = calculateInset(bounds, 1920, 1080);+ expect(result).toBe("50px 1020px 430px 100px");+ });++ test("calculates inset for full viewport", () => {+ const bounds = { x: 0, y: 0, width: 1920, height: 1080 };+ const result = calculateInset(bounds, 1920, 1080);+ expect(result).toBe("0px 0px 0px 0px");+ });++ test("calculates inset for small boundary", () => {+ const bounds = { x: 500, y: 300, width: 400, height: 300 };+ const result = calculateInset(bounds, 1920, 1080);+ expect(result).toBe("300px 1020px 480px 500px");+ });+});++describe("calculateCenteredPosition", () => {+ test("centers dialog in boundary", () => {+ const bounds = { x: 0, y: 0, width: 1000, height: 800 };+ const result = calculateCenteredPosition(bounds, 400, 300);+ expect(result).toEqual({ top: 250, left: 300 });+ });++ test("centers dialog with offset boundary", () => {+ const bounds = { x: 100, y: 50, width: 800, height: 600 };+ const result = calculateCenteredPosition(bounds, 400, 300);+ expect(result).toEqual({ top: 200, left: 300 });+ });++ test("handles dialog larger than boundary", () => {+ const bounds = { x: 0, y: 0, width: 200, height: 150 };+ const result = calculateCenteredPosition(bounds, 400, 300);+ // Should clamp to bounds.y/x (0, 0) when dialog is too large+ expect(result).toEqual({ top: 0, left: 0 });+ });++ test("handles undefined dimensions", () => {+ const bounds = { x: 100, y: 50, width: 800, height: 600 };+ const result = calculateCenteredPosition(bounds);+ expect(result).toEqual({ top: 350, left: 500 });+ });+});++describe("calculateDialogStyle", () => {+ test("maximized dialog fills boundary", () => {+ const bounds = { x: 100, y: 50, width: 800, height: 600 };+ const style = calculateDialogStyle(bounds, {+ isMaximized: true,+ windowWidth: 1920,+ windowHeight: 1080,+ });++ expect(style).toEqual({+ top: 50,+ left: 100,+ width: 800,+ height: 600,+ });+ });++ test("dialog with both width and height uses centered positioning", () => {+ const bounds = { x: 0, y: 0, width: 1000, height: 800 };+ const style = calculateDialogStyle(bounds, {+ isMaximized: false,+ width: 400,+ height: 300,+ windowWidth: 1920,+ windowHeight: 1080,+ });++ expect(style).toMatchObject({+ top: 250,+ left: 300,+ width: 400,+ height: 300,+ });+ });++ test("dialog with only width uses inset centering", () => {+ const bounds = { x: 100, y: 50, width: 800, height: 600 };+ const style = calculateDialogStyle(bounds, {+ isMaximized: false,+ width: 400,+ windowWidth: 1920,+ windowHeight: 1080,+ });++ expect(style).toMatchObject({+ inset: "50px 1020px 430px 100px",+ margin: "auto",+ width: 400,+ maxWidth: 800,+ maxHeight: 600,+ });+ });++ test("dialog with no dimensions uses inset centering", () => {+ const bounds = { x: 100, y: 50, width: 800, height: 600 };+ const style = calculateDialogStyle(bounds, {+ isMaximized: false,+ windowWidth: 1920,+ windowHeight: 1080,+ });++ expect(style).toMatchObject({+ inset: "50px 1020px 430px 100px",+ margin: "auto",+ maxWidth: 800,+ maxHeight: 600,+ });+ });++ test("applies minWidth and minHeight", () => {+ const bounds = { x: 0, y: 0, width: 1000, height: 800 };+ const style = calculateDialogStyle(bounds, {+ isMaximized: false,+ width: 400,+ height: 300,+ minWidth: 200,+ minHeight: 150,+ windowWidth: 1920,+ windowHeight: 1080,+ });++ expect(style.minWidth).toBe(200);+ expect(style.minHeight).toBe(150);+ });++ test("handles edge case: zero-sized boundary", () => {+ const bounds = { x: 0, y: 0, width: 0, height: 0 };+ const style = calculateDialogStyle(bounds, {+ isMaximized: false,+ width: 400,+ height: 300,+ windowWidth: 1920,+ windowHeight: 1080,+ });++ expect(style).toMatchObject({+ top: 0,+ left: 0,+ width: 400,+ height: 300,+ });+ });+});++describe("applyBoundaries", () => {+ test("constrains dialog within bounds", () => {+ const bounds = { x: 0, y: 0, width: 1000, height: 800 };+ const result = applyBoundaries(100, 50, 400, 300, bounds);++ expect(result).toEqual({+ x: 100,+ y: 50,+ width: 400,+ height: 300,+ });+ });++ test("constrains dialog that exceeds right boundary", () => {+ const bounds = { x: 0, y: 0, width: 1000, height: 800 };+ const result = applyBoundaries(800, 50, 400, 300, bounds);++ expect(result).toEqual({+ x: 600, // 1000 - 400+ y: 50,+ width: 400,+ height: 300,+ });+ });++ test("constrains dialog that exceeds bottom boundary", () => {+ const bounds = { x: 0, y: 0, width: 1000, height: 800 };+ const result = applyBoundaries(100, 700, 400, 300, bounds);++ expect(result).toEqual({+ x: 100,+ y: 500, // 800 - 300+ width: 400,+ height: 300,+ });+ });++ test("constrains dialog with negative position", () => {+ const bounds = { x: 0, y: 0, width: 1000, height: 800 };+ const result = applyBoundaries(-50, -20, 400, 300, bounds);++ expect(result).toEqual({+ x: 0,+ y: 0,+ width: 400,+ height: 300,+ });+ });++ test("constrains dialog larger than bounds", () => {+ const bounds = { x: 0, y: 0, width: 500, height: 400 };+ const result = applyBoundaries(0, 0, 800, 600, bounds);++ expect(result).toEqual({+ x: 0,+ y: 0,+ width: 500, // Constrained to bounds width+ height: 400, // Constrained to bounds height+ });+ });++ test("applies horizontal tolerance", () => {+ const bounds = { x: 0, y: 0, width: 1000, height: 800 };+ const tolerance = { horizontal: 50 };+ const result = applyBoundaries(-60, 50, 400, 300, bounds, tolerance);++ expect(result).toEqual({+ x: -50, // Allowed to go 50px outside on left+ y: 50,+ width: 400,+ height: 300,+ });+ });++ test("applies vertical tolerance", () => {+ const bounds = { x: 0, y: 0, width: 1000, height: 800 };+ const tolerance = { vertical: 30 };+ const result = applyBoundaries(100, -40, 400, 300, bounds, tolerance);++ expect(result).toEqual({+ x: 100,+ y: -30, // Allowed to go 30px outside on top+ width: 400,+ height: 300,+ });+ });++ test("applies both horizontal and vertical tolerance", () => {+ const bounds = { x: 0, y: 0, width: 1000, height: 800 };+ const tolerance = { horizontal: 50, vertical: 30 };+ const result = applyBoundaries(1100, 900, 400, 300, bounds, tolerance);++ expect(result).toEqual({+ x: 650, // 1000 + 50 - 400+ y: 530, // 800 + 30 - 300+ width: 400,+ height: 300,+ });+ });++ test("handles offset boundary with tolerance", () => {+ const bounds = { x: 100, y: 50, width: 800, height: 600 };+ const tolerance = { horizontal: 20, vertical: 10 };+ const result = applyBoundaries(90, 45, 400, 300, bounds, tolerance);++ expect(result).toEqual({+ x: 90, // Within tolerance (100 - 20 = 80)+ y: 45, // Within tolerance (50 - 10 = 40)+ width: 400,+ height: 300,+ });+ });++ test("increases allowed size with tolerance", () => {+ const bounds = { x: 0, y: 0, width: 500, height: 400 };+ const tolerance = { horizontal: 100, vertical: 50 };+ const result = applyBoundaries(0, 0, 800, 600, bounds, tolerance);++ expect(result).toEqual({+ x: -100, // Can go 100px outside on left+ y: -50, // Can go 50px outside on top+ width: 700, // 500 + 100*2+ height: 500, // 400 + 50*2+ });+ });+});diff --git a/packages/design-system/src/components/dialog.tsx b/packages/design-system/src/components/dialog.tsxindex d4f28703cf..b915608514 100644--- a/packages/design-system/src/components/dialog.tsx+++ b/packages/design-system/src/components/dialog.tsx@@ -139,6 +139,132 @@ type Point = { x: number; y: number };type Size = { width: number; height: number };type Rect = Point & Size;+type Tolerance = {+ horizontal?: number;+ vertical?: number;+};++// Utility: Calculate inset CSS string from boundary rect+const calculateInset = (+ bounds: Rect,+ windowWidth: number,+ windowHeight: number+): string => {+ return `${bounds.y}px ${windowWidth - bounds.x - bounds.width}px ${windowHeight - bounds.y - bounds.height}px ${bounds.x}px`;+};++// Utility: Calculate centered dialog position+const calculateCenteredPosition = (+ bounds: Rect,+ width?: number,+ height?: number+): { top: number; left: number } => {+ return {+ top: Math.max(bounds.y, bounds.y + bounds.height / 2 - (height ?? 0) / 2),+ left: Math.max(bounds.x, bounds.x + bounds.width / 2 - (width ?? 0) / 2),+ };+};++// Utility: Calculate dialog style based on positioning mode+const calculateDialogStyle = (+ bounds: Rect,+ options: {+ isMaximized: boolean;+ width?: number;+ height?: number;+ minWidth?: number;+ minHeight?: number;+ windowWidth: number;+ windowHeight: number;+ }+): CSSProperties => {+ const {+ isMaximized,+ width,+ height,+ minWidth,+ minHeight,+ windowWidth,+ windowHeight,+ } = options;++ if (isMaximized) {+ return {+ top: bounds.y,+ left: bounds.x,+ width: bounds.width,+ height: bounds.height,+ };+ }++ // If both width and height are specified, use centered positioning+ if (width && height) {+ const centered = calculateCenteredPosition(bounds, width, height);+ return {+ top: centered.top,+ left: centered.left,+ width,+ height,+ ...(minWidth && { minWidth }),+ ...(minHeight && { minHeight }),+ };+ }++ // Otherwise use inset-based centering with margin: auto+ const style: CSSProperties = {+ inset: calculateInset(bounds, windowWidth, windowHeight),+ margin: "auto",+ maxWidth: bounds.width,+ maxHeight: bounds.height,+ };++ if (width !== undefined) {+ style.width = width;+ }+ if (height !== undefined) {+ style.height = height;+ }+ if (minWidth !== undefined) {+ style.minWidth = minWidth;+ }+ if (minHeight !== undefined) {+ style.minHeight = minHeight;+ }++ return style;+};++// Utility: Apply boundary constraints to dialog position and size+const applyBoundaries = (+ x: number,+ y: number,+ width: number,+ height: number,+ bounds: Rect,+ tolerance?: Tolerance+): Rect => {+ const horizontalTolerance = tolerance?.horizontal ?? 0;+ const verticalTolerance = tolerance?.vertical ?? 0;++ const minX = bounds.x - horizontalTolerance;+ const minY = bounds.y - verticalTolerance;+ const maxWidth = bounds.width + horizontalTolerance * 2;+ const maxHeight = bounds.height + verticalTolerance * 2;++ const constrainedWidth = Math.min(width, maxWidth);+ const constrainedHeight = Math.min(height, maxHeight);++ const maxX = bounds.x + bounds.width + horizontalTolerance - constrainedWidth;+ const maxY = bounds.y + bounds.height + verticalTolerance - constrainedHeight;++ return {+ x: Math.max(minX, Math.min(x, maxX)),+ y: Math.max(minY, Math.min(y, maxY)),+ width: constrainedWidth,+ height: constrainedHeight,+ };+};+const useBoundary = () => {const [boundaryRect, setBoundaryRect] = useState<Rect | undefined>(undefined);@@ -192,49 +318,6 @@ type UseDraggableProps = {boundaryTolerance?: { horizontal?: number; vertical?: number };} & Partial<Rect>;-const applyBoundaries = (- x: number,- y: number,- width: number,- height: number,- bounds: Rect,- tolerance?: { horizontal?: number; vertical?: number }-) => {- const horizontalTolerance = tolerance?.horizontal ?? 0;- const verticalTolerance = tolerance?.vertical ?? 0;-- // Constrain width and height to fit within bounds- const constrainedWidth = Math.min(- width,- bounds.width + horizontalTolerance * 2- );- const constrainedHeight = Math.min(- height,- bounds.height + verticalTolerance * 2- );-- // Constrain X axis within bounds (with tolerance)- let constrainedX = Math.max(bounds.x - horizontalTolerance, x);- constrainedX = Math.min(- bounds.x + bounds.width + horizontalTolerance - constrainedWidth,- constrainedX- );-- // Constrain Y axis within bounds (with tolerance)- let constrainedY = Math.max(bounds.y - verticalTolerance, y);- constrainedY = Math.min(- bounds.y + bounds.height + verticalTolerance - constrainedHeight,- constrainedY- );-- return {- x: constrainedX,- y: constrainedY,- width: constrainedWidth,- height: constrainedHeight,- };-};-const useDraggable = ({width,height,@@ -259,36 +342,15 @@ const useDraggable = ({const ref = useRef<HTMLDivElement | null>(null);const calcStyle = useCallback(() => {- const availableWidth = bounds.width;- const availableHeight = bounds.height;-- const style: CSSProperties = isMaximized- ? {- top: bounds.y,- left: bounds.x,- width: availableWidth,- height: availableHeight,- }- : !width || !height- ? {- top: bounds.y,- left: bounds.x,- maxWidth: availableWidth,- maxHeight: availableHeight,- }- : {- top: Math.max(bounds.y, bounds.y + bounds.height / 2 - height / 2),- left: Math.max(bounds.x, bounds.x + bounds.width / 2 - width / 2),- width,- height,- };-- if (minWidth !== undefined) {- style.minWidth = minWidth;- }- if (minHeight !== undefined) {- style.minHeight = minHeight;- }+ const style = calculateDialogStyle(bounds, {+ isMaximized,+ width,+ height,+ minWidth,+ minHeight,+ windowWidth: window.innerWidth,+ windowHeight: window.innerHeight,+ });if (isMaximized === false) {if (x !== undefined && y !== undefined) {@@ -365,8 +427,8 @@ const useDraggable = ({style.margin = 0;} else {// Only apply max constraints when not positioned- style.maxWidth = availableWidth;- style.maxHeight = availableHeight;+ style.maxWidth = bounds.width;+ style.maxHeight = bounds.height;}}@@ -664,3 +726,11 @@ const contentStyle = css(panelStyle, {},},});++// Export utilities for testing+export const __testing__ = {+ calculateInset,+ calculateCenteredPosition,+ calculateDialogStyle,+ applyBoundaries,+};diff --git a/packages/design-system/src/index.ts b/packages/design-system/src/index.tsindex 80a822d619..83628c588f 100644--- a/packages/design-system/src/index.ts+++ b/packages/design-system/src/index.ts@@ -16,7 +16,17 @@ export * from "./components/dropdown-menu";export * from "./components/context-menu";export * from "./components/icon-button"; // mostly aligned, but needs a demo and to use tokensexport * from "./components/toggle-button";-export * from "./components/dialog";+export {+ Dialog,+ DialogTrigger,+ DialogDescription,+ DialogClose,+ DialogMaximize,+ DialogContent,+ DialogTitle,+ DialogTitleActions,+ DialogActions,+} from "./components/dialog";export * from "./components/floating-panel";export * from "./components/popover";export {diff --git a/packages/design-system/vitest.config.ts b/packages/design-system/vitest.config.tsnew file mode 100644index 0000000000..fd63d166f1--- /dev/null+++ b/packages/design-system/vitest.config.ts@@ -0,0 +1,16 @@+import { defineConfig } from "vitest/config";++export default defineConfig({+ resolve: {+ conditions: ["webstudio", "browser", "development|production"],+ },+ // resolve webstudio condition in tests+ ssr: {+ resolve: {+ conditions: ["webstudio", "node", "development|production"],+ },+ },+ test: {+ environment: "jsdom",+ },+});