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
feat: Manage data variables (#5488)
Oleg Isonenbf6abe7384d0
diff --git a/apps/builder/app/builder/features/command-panel/command-panel.tsx b/apps/builder/app/builder/features/command-panel/command-panel.tsxindex 6fc3c9e9c2..332addf7c9 100644--- a/apps/builder/app/builder/features/command-panel/command-panel.tsx+++ b/apps/builder/app/builder/features/command-panel/command-panel.tsx@@ -16,16 +16,13 @@ import {$commandSearch,closeCommandPanel,} from "./command-state";-import {- $allOptions,- groups,- type ComponentOption,- type TagOption,- type BreakpointOption,- type PageOption,- type CommandOption,- type TokenOption,-} from "./groups";+import { $allOptions, groups, type Option } from "./groups";++const renderGroup = (type: Option["type"], matches: Option[]): JSX.Element => {+ const Group = groups[type];+ // Type assertion is safe here because matches are filtered by type before calling renderGroup+ return <Group key={type} options={matches as never} />;+};const CommandDialogContent = () => {const search = useStore($commandSearch);@@ -40,7 +37,10 @@ const CommandDialogContent = () => {});}}- const matchGroups = mapGroupBy(matches, (match) => match.type);+ const matchGroups = mapGroupBy<Option, Option["type"]>(+ matches,+ (match) => match.type+ );return (<><CommandInput@@ -50,57 +50,9 @@ const CommandDialogContent = () => {<Flex direction="column" css={{ maxHeight: 300 }}><ScrollArea><CommandList>- {Array.from(matchGroups).map(([groupType, matches]) => {- if (groupType === "component") {- return (- <groups.component- key={groupType}- options={matches as ComponentOption[]}- />- );- }- if (groupType === "tag") {- return (- <groups.tag- key={groupType}- options={matches as TagOption[]}- />- );- }- if (groupType === "breakpoint") {- return (- <groups.breakpoint- key={groupType}- options={matches as BreakpointOption[]}- />- );- }- if (groupType === "page") {- return (- <groups.page- key={groupType}- options={matches as PageOption[]}- />- );- }- if (groupType === "command") {- return (- <groups.command- key={groupType}- options={matches as CommandOption[]}- />- );- }- if (groupType === "token") {- return (- <groups.token- key={groupType}- options={matches as TokenOption[]}- />- );- }- groupType satisfies never;- })}+ {Array.from(matchGroups).map(([type, matches]) =>+ renderGroup(type, matches)+ )}</CommandList></ScrollArea></Flex>diff --git a/apps/builder/app/builder/features/command-panel/groups/breakpoint-group.tsx b/apps/builder/app/builder/features/command-panel/groups/breakpoints-group.tsxsimilarity index 89%rename from apps/builder/app/builder/features/command-panel/groups/breakpoint-group.tsxrename to apps/builder/app/builder/features/command-panel/groups/breakpoints-group.tsxindex d9c8adb1f3..c3736907ee 100644--- a/apps/builder/app/builder/features/command-panel/groups/breakpoint-group.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/breakpoints-group.tsx@@ -15,12 +15,12 @@ import {} from "~/shared/nano-states";import { setCanvasWidth } from "~/builder/features/breakpoints";import { closeCommandPanel } from "../command-state";+import type { BaseOption } from "../shared/types";-export type BreakpointOption = {- terms: string[];+export type BreakpointOption = BaseOption & {type: "breakpoint";breakpoint: Breakpoint;- shortcut: string;+ keys: string[];};export const $breakpointOptions = computed(@@ -41,7 +41,7 @@ export const $breakpointOptions = computed(terms: ["breakpoints", breakpoint.label, width],type: "breakpoint",breakpoint,- shortcut: (index + 1).toString(),+ keys: [(index + 1).toString()],});}return breakpointOptions;@@ -59,7 +59,7 @@ const getBreakpointLabel = (breakpoint: Breakpoint) => {return `${breakpoint.label}: ${label}`;};-export const BreakpointGroup = ({+export const BreakpointsGroup = ({options,}: {options: BreakpointOption[];@@ -70,7 +70,7 @@ export const BreakpointGroup = ({heading={<CommandGroupHeading>Breakpoints</CommandGroupHeading>}actions={["select"]}>- {options.map(({ breakpoint, shortcut }) => (+ {options.map(({ breakpoint, keys }) => (<CommandItemkey={breakpoint.id}// preserve selected state when rerender@@ -84,7 +84,7 @@ export const BreakpointGroup = ({<Text variant="labelsTitleCase">{getBreakpointLabel(breakpoint)}</Text>- <Kbd value={[shortcut]} />+ <Kbd value={keys} /></CommandItem>))}</CommandGroup>diff --git a/apps/builder/app/builder/features/command-panel/groups/command-group.tsx b/apps/builder/app/builder/features/command-panel/groups/commands-group.tsxsimilarity index 94%rename from apps/builder/app/builder/features/command-panel/groups/command-group.tsxrename to apps/builder/app/builder/features/command-panel/groups/commands-group.tsxindex 28fb13df84..2d1dfd8534 100644--- a/apps/builder/app/builder/features/command-panel/groups/command-group.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/commands-group.tsx@@ -10,9 +10,9 @@ import { $commandMetas } from "~/shared/commands-emitter";import { emitCommand } from "~/builder/shared/commands";import { humanizeString } from "~/shared/string-utils";import { closeCommandPanel } from "../command-state";+import type { BaseOption } from "../shared/types";-export type CommandOption = {- terms: string[];+export type CommandOption = BaseOption & {type: "command";name: string;label: string;diff --git a/apps/builder/app/builder/features/command-panel/groups/component-group.tsx b/apps/builder/app/builder/features/command-panel/groups/components-group.tsxsimilarity index 96%rename from apps/builder/app/builder/features/command-panel/groups/component-group.tsxrename to apps/builder/app/builder/features/command-panel/groups/components-group.tsxindex 108ce3efd8..57f9aa709c 100644--- a/apps/builder/app/builder/features/command-panel/groups/component-group.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/components-group.tsx@@ -29,9 +29,9 @@ import {InstanceIcon,} from "~/builder/shared/instance-label";import { closeCommandPanel } from "../command-state";+import type { BaseOption } from "../shared/types";-export type ComponentOption = {- terms: string[];+export type ComponentOption = BaseOption & {type: "component";component: string;label: string;@@ -110,7 +110,11 @@ export const $componentOptions = computed(});-export const ComponentGroup = ({ options }: { options: ComponentOption[] }) => {+export const ComponentsGroup = ({+ options,+}: {+ options: ComponentOption[];+}) => {return (<CommandGroupname="component"diff --git a/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx b/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsxnew file mode 100644index 0000000000..99deb21ff3--- /dev/null+++ b/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx@@ -0,0 +1,171 @@+import { useState } from "react";+import { computed } from "nanostores";+import {+ CommandGroup,+ CommandGroupHeading,+ CommandItem,+ Text,+ toast,+ useSelectedAction,+} from "@webstudio-is/design-system";+import { $instances, $dataSources } from "~/shared/nano-states";+import { selectInstance as selectInstanceBySelector } from "~/shared/awareness";+import { $activeInspectorPanel } from "~/builder/shared/nano-states";+import { $commandContent, closeCommandPanel } from "../command-state";+import { InstanceList, selectInstance } from "../shared/instance-list";+import { deleteVariableMutable } from "~/shared/data-variables";+import { updateWebstudioData } from "~/shared/instance-utils";+import {+ DeleteDataVariableDialog,+ RenameDataVariableDialog,+ $usedVariablesInInstances,+} from "~/builder/shared/data-variable-utils";+import type { BaseOption } from "../shared/types";++export type DataVariableOption = BaseOption & {+ type: "dataVariable";+ id: string;+ name: string;+ instanceId: string;+ usages: number;+};++export const $dataVariableOptions = computed(+ [$dataSources, $instances, $usedVariablesInInstances],+ (dataSources, instances, usedInInstances) => {+ const dataVariableOptions: DataVariableOption[] = [];++ for (const dataSource of dataSources.values()) {+ if (+ dataSource.type === "variable" &&+ dataSource.scopeInstanceId !== undefined+ ) {+ const instance = instances.get(dataSource.scopeInstanceId);+ if (instance) {+ const usages = usedInInstances.get(dataSource.id)?.size ?? 0;+ dataVariableOptions.push({+ terms: ["variable", "variables", "data", dataSource.name],+ type: "dataVariable",+ id: dataSource.id,+ name: dataSource.name,+ instanceId: dataSource.scopeInstanceId,+ usages,+ });+ }+ }+ }++ return dataVariableOptions;+ }+);++const DataVariableInstances = ({ variableId }: { variableId: string }) => {+ const usedInInstances = $usedVariablesInInstances.get();+ const instanceIds = usedInInstances.get(variableId) ?? new Set();++ return (+ <InstanceList+ instanceIds={instanceIds}+ onSelect={(instanceId) => {+ selectInstance(instanceId);+ $activeInspectorPanel.set("settings");+ }}+ />+ );+};++export const DataVariablesGroup = ({+ options,+}: {+ options: DataVariableOption[];+}) => {+ const action = useSelectedAction();+ const [variableToRename, setVariableToRename] =+ useState<DataVariableOption>();+ const [variableToDelete, setVariableToDelete] =+ useState<DataVariableOption>();++ const handleSelect = (option: DataVariableOption) => {+ if (action === "find") {+ if (option.usages > 0) {+ $commandContent.set(<DataVariableInstances variableId={option.id} />);+ } else {+ toast.error("Variable is not used in any instance");+ }+ return;+ }++ if (action === "rename") {+ setVariableToRename(option);+ return;+ }++ if (action === "delete") {+ setVariableToDelete(option);+ return;+ }++ closeCommandPanel();++ // Find the instance selector+ const instanceSelector: string[] = [option.instanceId];++ // Select the instance+ selectInstanceBySelector(instanceSelector);++ // Switch to settings tab+ $activeInspectorPanel.set("settings");+ };++ return (+ <>+ <CommandGroup+ name="dataVariable"+ heading={<CommandGroupHeading>Data variables</CommandGroupHeading>}+ actions={["find", "select", "rename", "delete"]}+ >+ {options.map((option) => (+ <CommandItem+ key={option.id}+ value={option.id}+ onSelect={() => handleSelect(option)}+ >+ <Text variant="labelsSentenceCase">+ {option.name}{" "}+ <Text as="span" color="moreSubtle">+ {option.usages === 0+ ? "unused"+ : `${option.usages} ${option.usages === 1 ? "usage" : "usages"}`}+ </Text>+ </Text>+ </CommandItem>+ ))}+ </CommandGroup>+ <RenameDataVariableDialog+ variable={variableToRename}+ onClose={() => {+ setVariableToRename(undefined);+ }}+ onConfirm={(_variableId, newName) => {+ toast.success(+ `Variable renamed from "${variableToRename?.name}" to "${newName}"`+ );+ setVariableToRename(undefined);+ }}+ />+ <DeleteDataVariableDialog+ variable={variableToDelete}+ onClose={() => {+ setVariableToDelete(undefined);+ }}+ onConfirm={(variableId) => {+ updateWebstudioData((data) => {+ deleteVariableMutable(data, variableId);+ });+ toast.success(`Variable "${variableToDelete?.name}" deleted`);+ setVariableToDelete(undefined);+ }}+ />+ </>+ );+};diff --git a/apps/builder/app/builder/features/command-panel/groups/index.ts b/apps/builder/app/builder/features/command-panel/groups/index.tsindex aabfc8d4c3..c9a43cba9a 100644--- a/apps/builder/app/builder/features/command-panel/groups/index.ts+++ b/apps/builder/app/builder/features/command-panel/groups/index.ts@@ -1,22 +1,27 @@import { computed } from "nanostores";import {$componentOptions,- ComponentGroup,+ ComponentsGroup,type ComponentOption,-} from "./component-group";-import { $tagOptions, TagGroup, type TagOption } from "./tag-group";+} from "./components-group";+import { $tagOptions, TagsGroup, type TagOption } from "./tags-group";import {$breakpointOptions,- BreakpointGroup,+ BreakpointsGroup,type BreakpointOption,-} from "./breakpoint-group";-import { $pageOptions, PageGroup, type PageOption } from "./page-group";+} from "./breakpoints-group";+import { $pageOptions, PagesGroup, type PageOption } from "./pages-group";import {$commandOptions,CommandsGroup,type CommandOption,-} from "./command-group";-import { $tokenOptions, TokenGroup, type TokenOption } from "./token-group";+} from "./commands-group";+import { $tokenOptions, TokensGroup, type TokenOption } from "./tokens-group";+import {+ $dataVariableOptions,+ DataVariablesGroup,+ type DataVariableOption,+} from "./data-variables-group";export type Option =| ComponentOption@@ -24,7 +29,13 @@ export type Option =| BreakpointOption| PageOption| CommandOption- | TokenOption;+ | TokenOption+ | DataVariableOption;++export type OptionByType<T extends Option["type"]> = Extract<+ Option,+ { type: T }+>;export const $allOptions = computed([@@ -34,6 +45,7 @@ export const $allOptions = computed($pageOptions,$commandOptions,$tokenOptions,+ $dataVariableOptions,],(componentOptions,@@ -41,7 +53,8 @@ export const $allOptions = computed(breakpointOptions,pageOptions,commandOptions,- tokenOptions+ tokenOptions,+ dataVariableOptions) => [...componentOptions,...tagOptions,@@ -49,17 +62,25 @@ export const $allOptions = computed(...pageOptions,...commandOptions,...tokenOptions,+ ...dataVariableOptions,]);-export const groups = {- component: ComponentGroup,- tag: TagGroup,- breakpoint: BreakpointGroup,- page: PageGroup,+type GroupComponent<T extends Option["type"]> = (props: {+ options: OptionByType<T>[];+}) => JSX.Element;++export const groups: {+ [K in Option["type"]]: GroupComponent<K>;+} = {+ component: ComponentsGroup,+ tag: TagsGroup,+ breakpoint: BreakpointsGroup,+ page: PagesGroup,command: CommandsGroup,- token: TokenGroup,-} as const;+ token: TokensGroup,+ dataVariable: DataVariablesGroup,+};export type {ComponentOption,@@ -68,13 +89,15 @@ export type {PageOption,CommandOption,TokenOption,+ DataVariableOption,};export {- ComponentGroup,- TagGroup,- BreakpointGroup,- PageGroup,+ ComponentsGroup,+ TagsGroup,+ BreakpointsGroup,+ PagesGroup,CommandsGroup,- TokenGroup,+ TokensGroup,+ DataVariablesGroup,};diff --git a/apps/builder/app/builder/features/command-panel/groups/page-group.tsx b/apps/builder/app/builder/features/command-panel/groups/pages-group.tsxsimilarity index 91%rename from apps/builder/app/builder/features/command-panel/groups/page-group.tsxrename to apps/builder/app/builder/features/command-panel/groups/pages-group.tsxindex 2e9ef16c4a..66d6477893 100644--- a/apps/builder/app/builder/features/command-panel/groups/page-group.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/pages-group.tsx@@ -11,9 +11,9 @@ import { $pages, $editingPageId } from "~/shared/nano-states";import { $selectedPage, selectPage } from "~/shared/awareness";import { setActiveSidebarPanel } from "~/builder/shared/nano-states";import { closeCommandPanel } from "../command-state";+import type { BaseOption } from "../shared/types";-export type PageOption = {- terms: string[];+export type PageOption = BaseOption & {type: "page";page: Page;};@@ -38,7 +38,7 @@ export const $pageOptions = computed(});-export const PageGroup = ({ options }: { options: PageOption[] }) => {+export const PagesGroup = ({ options }: { options: PageOption[] }) => {const action = useSelectedAction();return (<CommandGroupdiff --git a/apps/builder/app/builder/features/command-panel/groups/tag-group.tsx b/apps/builder/app/builder/features/command-panel/groups/tags-group.tsxsimilarity index 95%rename from apps/builder/app/builder/features/command-panel/groups/tag-group.tsxrename to apps/builder/app/builder/features/command-panel/groups/tags-group.tsxindex 500ea8de55..58d9858770 100644--- a/apps/builder/app/builder/features/command-panel/groups/tag-group.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/tags-group.tsx@@ -19,9 +19,9 @@ import { $selectedInstancePath } from "~/shared/awareness";import { InstanceIcon } from "~/builder/shared/instance-label";import { isTreeSatisfyingContentModel } from "~/shared/content-model";import { closeCommandPanel } from "../command-state";+import type { BaseOption } from "../shared/types";-export type TagOption = {- terms: string[];+export type TagOption = BaseOption & {type: "tag";tag: string;};@@ -68,7 +68,7 @@ export const $tagOptions = computed(});-export const TagGroup = ({ options }: { options: TagOption[] }) => {+export const TagsGroup = ({ options }: { options: TagOption[] }) => {return (<CommandGroupname="tag"diff --git a/apps/builder/app/builder/features/command-panel/groups/token-group.tsx b/apps/builder/app/builder/features/command-panel/groups/tokens-group.tsxsimilarity index 52%rename from apps/builder/app/builder/features/command-panel/groups/token-group.tsxrename to apps/builder/app/builder/features/command-panel/groups/tokens-group.tsxindex c0665cc6f7..e3663fd13c 100644--- a/apps/builder/app/builder/features/command-panel/groups/token-group.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/tokens-group.tsx@@ -1,43 +1,30 @@import { useState } from "react";-import { matchSorter } from "match-sorter";import { computed } from "nanostores";import { useStore } from "@nanostores/react";import {CommandGroup,CommandGroupHeading,- CommandGroupFooter,- CommandInput,CommandItem,- CommandList,- Flex,- ScrollArea,Text,toast,useSelectedAction,- Button,- Kbd,} from "@webstudio-is/design-system";-import type { Instance, Instances, StyleSource } from "@webstudio-is/sdk";-import {- $instances,- $pages,- $registeredComponentMetas,- $selectedStyleSources,- $styleSources,-} from "~/shared/nano-states";+import type { Instance, StyleSource } from "@webstudio-is/sdk";+import { $selectedStyleSources, $styleSources } from "~/shared/nano-states";import {deleteStyleSource,DeleteStyleSourceDialog,RenameStyleSourceDialog,$styleSourceUsages,} from "~/builder/shared/style-source-utils";-import { getInstanceLabel } from "~/builder/shared/instance-label";-import type { InstanceSelector } from "~/shared/tree-utils";+import { findInstanceById } from "../shared/instance-utils";+import { InstanceList } from "../shared/instance-list";+import { $instances, $pages } from "~/shared/nano-states";import { $awareness } from "~/shared/awareness";-import { $commandContent, closeCommandPanel } from "../command-state";+import { $commandContent } from "../command-state";+import type { BaseOption } from "../shared/types";-export type TokenOption = {- terms: string[];+export type TokenOption = BaseOption & {type: "token";token: Extract<StyleSource, { type: "token" }>;usages: number;@@ -62,36 +49,6 @@ export const $tokenOptions = computed(});-/**- * very loose selector finder- * will not work properly with collections- */-const findInstanceById = (- instances: Instances,- instanceSelector: InstanceSelector,- targetId: Instance["id"]-): undefined | InstanceSelector => {- const [instanceId] = instanceSelector;- if (instanceId === targetId) {- return instanceSelector;- }- const instance = instances.get(instanceId);- if (instance) {- for (const child of instance.children) {- if (child.type === "id") {- const matched = findInstanceById(- instances,- [child.value, ...instanceSelector],- targetId- );- if (matched) {- return matched;- }- }- }- }-};-const selectToken = (instanceId: Instance["id"],tokenId: StyleSource["id"]@@ -118,95 +75,19 @@ const selectToken = (}};-type InstanceOption = {- label: string;- id: string;-};-const TokenInstances = ({ tokenId }: { tokenId: StyleSource["id"] }) => {const usages = useStore($styleSourceUsages);const usedInInstanceIds = usages.get(tokenId) ?? new Set();- const instances = $instances.get();- const metas = $registeredComponentMetas.get();- const usedInInstances: InstanceOption[] = [];- for (const instanceId of usedInInstanceIds) {- const instance = instances.get(instanceId);- const meta = metas.get(instance?.component ?? "");- if (instance && meta) {- usedInInstances.push({- label: getInstanceLabel(instance, meta),- id: instance.id,- });- }- }- const [search, setSearch] = useState("");-- const goBack = () => {- $commandContent.set(undefined);- };- let matches = usedInInstances;- // prevent searching when value is empty- // to preserve original items order- if (search.trim().length > 0) {- for (const word of search.trim().split(/\s+/)) {- matches = matchSorter(matches, word, {- keys: ["label"],- });- }- }return (- <>- <CommandInput- action="select"- value={search}- onValueChange={setSearch}- onKeyDown={(event) => {- if (event.key === "Backspace" && search === "") {- event.preventDefault();- goBack();- }- }}- />- <Flex direction="column" css={{ maxHeight: 300 }}>- <ScrollArea>- <CommandList>- <CommandGroup name="instance" actions={["select"]}>- {matches.length === 0 ? (- <Flex justify="center" align="center" css={{ minHeight: 100 }}>- <Text color="subtle">No instances found</Text>- </Flex>- ) : (- matches.map(({ id, label }) => (- <CommandItem- key={id}- // preserve selected state when rerender- value={id}- onSelect={() => {- selectToken(id, tokenId);- closeCommandPanel();- }}- >- <Text variant="labelsTitleCase">{label}</Text>- </CommandItem>- ))- )}- </CommandGroup>- </CommandList>- </ScrollArea>- </Flex>- <CommandGroupFooter>- <Flex grow>- <Button tabIndex={-1} color="ghost" onClick={goBack}>- Back <Kbd value={["backspace"]} />- </Button>- </Flex>- </CommandGroupFooter>- </>+ <InstanceList+ instanceIds={usedInInstanceIds}+ onSelect={(instanceId) => selectToken(instanceId, tokenId)}+ />);};-export const TokenGroup = ({ options }: { options: TokenOption[] }) => {+export const TokensGroup = ({ options }: { options: TokenOption[] }) => {const action = useSelectedAction();const [tokenToRename, setTokenToRename] =useState<Extract<StyleSource, { type: "token" }>>();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.tsxnew file mode 100644index 0000000000..849701dbde--- /dev/null+++ b/apps/builder/app/builder/features/command-panel/shared/instance-list.tsx@@ -0,0 +1,135 @@+import { useState } from "react";+import { matchSorter } from "match-sorter";+import {+ CommandGroup,+ CommandGroupFooter,+ CommandInput,+ CommandItem,+ CommandList,+ Flex,+ ScrollArea,+ Text,+ Button,+ Kbd,+} from "@webstudio-is/design-system";+import type { Instance } from "@webstudio-is/sdk";+import {+ $instances,+ $pages,+ $registeredComponentMetas,+} from "~/shared/nano-states";+import { getInstanceLabel } from "~/builder/shared/instance-label";+import { $awareness } from "~/shared/awareness";+import { $commandContent, closeCommandPanel } from "../command-state";+import { findInstanceById } from "../shared/instance-utils";++export type InstanceOption = {+ label: string;+ id: string;+};++type InstanceListProps = {+ instanceIds: Set<Instance["id"]>;+ onSelect: (instanceId: Instance["id"]) => void;+};++export const InstanceList = ({ instanceIds, onSelect }: InstanceListProps) => {+ const instances = $instances.get();+ const metas = $registeredComponentMetas.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, meta),+ id: instance.id,+ });+ }+ }+ const [search, setSearch] = useState("");++ const goBack = () => {+ $commandContent.set(undefined);+ };++ let matches = usedInInstances;+ // prevent searching when value is empty+ // to preserve original items order+ if (search.trim().length > 0) {+ for (const word of search.trim().split(/\s+/)) {+ matches = matchSorter(matches, word, {+ keys: ["label"],+ });+ }+ }++ return (+ <>+ <CommandInput+ action="select"+ value={search}+ onValueChange={setSearch}+ onKeyDown={(event) => {+ if (event.key === "Backspace" && search === "") {+ event.preventDefault();+ goBack();+ }+ }}+ />+ <Flex direction="column" css={{ maxHeight: 300 }}>+ <ScrollArea>+ <CommandList>+ <CommandGroup name="instance" actions={["select"]}>+ {matches.length === 0 ? (+ <Flex justify="center" align="center" css={{ minHeight: 100 }}>+ <Text color="subtle">No instances found</Text>+ </Flex>+ ) : (+ matches.map(({ id, label }) => (+ <CommandItem+ key={id}+ value={id}+ onSelect={() => {+ onSelect(id);+ closeCommandPanel();+ }}+ >+ <Text variant="labelsTitleCase">{label}</Text>+ </CommandItem>+ ))+ )}+ </CommandGroup>+ </CommandList>+ </ScrollArea>+ </Flex>+ <CommandGroupFooter>+ <Flex grow>+ <Button tabIndex={-1} color="ghost" onClick={goBack}>+ Back <Kbd value={["backspace"]} />+ </Button>+ </Flex>+ </CommandGroupFooter>+ </>+ );+};++export const selectInstance = (instanceId: Instance["id"]) => {+ const instances = $instances.get();+ const pagesData = $pages.get();+ if (pagesData === undefined) {+ return;+ }+ const pages = [pagesData.homePage, ...pagesData.pages];+ for (const page of pages) {+ const instanceSelector = findInstanceById(+ instances,+ [page.rootInstanceId],+ instanceId+ );+ if (instanceSelector) {+ $awareness.set({ pageId: page.id, instanceSelector });+ break;+ }+ }+};diff --git a/apps/builder/app/builder/features/command-panel/shared/instance-utils.ts b/apps/builder/app/builder/features/command-panel/shared/instance-utils.tsnew file mode 100644index 0000000000..c0fb8ed3db--- /dev/null+++ b/apps/builder/app/builder/features/command-panel/shared/instance-utils.ts@@ -0,0 +1,32 @@+import type { Instance, Instances } from "@webstudio-is/sdk";+import type { InstanceSelector } from "~/shared/tree-utils";++/**+ * Very loose selector finder+ * Will not work properly with collections+ */+export const findInstanceById = (+ instances: Instances,+ instanceSelector: InstanceSelector,+ targetId: Instance["id"]+): undefined | InstanceSelector => {+ const [instanceId] = instanceSelector;+ if (instanceId === targetId) {+ return instanceSelector;+ }+ const instance = instances.get(instanceId);+ if (instance) {+ for (const child of instance.children) {+ if (child.type === "id") {+ const matched = findInstanceById(+ instances,+ [child.value, ...instanceSelector],+ targetId+ );+ if (matched) {+ return matched;+ }+ }+ }+ }+};diff --git a/apps/builder/app/builder/features/command-panel/shared/types.ts b/apps/builder/app/builder/features/command-panel/shared/types.tsnew file mode 100644index 0000000000..9554a832f1--- /dev/null+++ b/apps/builder/app/builder/features/command-panel/shared/types.ts@@ -0,0 +1,4 @@+export type BaseOption = {+ terms: string[];+ type: string;+};diff --git a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx b/apps/builder/app/builder/features/settings-panel/variable-popover.tsxindex df3400bc9e..c671ec1116 100644--- a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx+++ b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx@@ -77,6 +77,7 @@ import {findUnsetVariableNames,rebindTreeVariablesMutable,} from "~/shared/data-variables";+import { validateDataVariableName } from "~/builder/shared/data-variable-utils";import {GraphqlResourceForm,parseResource,@@ -103,27 +104,18 @@ const NameField = ({const ref = useRef<HTMLInputElement>(null);const [error, setError] = useState("");const nameId = useId();+ const scopeInstanceId =+ variable?.scopeInstanceId ?? $selectedInstance.get()?.id;const validateName = useCallback((value: string) => {- // validate same name on variable instance- // and fallback to selected instance for new variables- const scopeInstanceId =- variable?.scopeInstanceId ?? $selectedInstance.get()?.id;- for (const dataSource of $dataSources.get().values()) {- if (- dataSource.scopeInstanceId === scopeInstanceId &&- dataSource.name === value &&- dataSource.id !== variable?.id- ) {- return "Name is already used by another variable on this instance";- }- }- if (value.trim().length === 0) {- return "Name is required";- }- return "";+ const error = validateDataVariableName(+ value,+ variable?.id,+ scopeInstanceId+ );+ return error?.message ?? "";},- [variable]+ [variable, scopeInstanceId]);const [value, setValue] = useState(defaultValue);useEffect(() => {diff --git a/apps/builder/app/builder/features/settings-panel/variables-section.tsx b/apps/builder/app/builder/features/settings-panel/variables-section.tsxindex 454bb0038d..96831d3c9f 100644--- a/apps/builder/app/builder/features/settings-panel/variables-section.tsx+++ b/apps/builder/app/builder/features/settings-panel/variables-section.tsx@@ -6,11 +6,6 @@ import {css,CssValueListArrowFocus,CssValueListItem,- Dialog,- DialogActions,- DialogContent,- DialogDescription,- DialogTitle,DropdownMenu,DropdownMenuContent,DropdownMenuItem,@@ -52,6 +47,7 @@ import {findAvailableVariables,findUsedVariables,} from "~/shared/data-variables";+import { DeleteDataVariableDialog } from "~/builder/shared/data-variable-utils";/*** find variables defined specifically on this selected instance@@ -140,7 +136,11 @@ const VariablesItem = ({}) => {const selectedPage = useStore($selectedPage);const [isMenuOpen, setIsMenuOpen] = useState(false);- const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);+ const [variableToDelete, setVariableToDelete] = useState<{+ id: string;+ name: string;+ usages: number;+ }>();return (<VariablePopoverTrigger key={variable.id} variable={variable}><CssValueListItem@@ -185,13 +185,11 @@ const VariablesItem = ({{source === "local" && variable.type !== "parameter" && (<DropdownMenuItemonSelect={() => {- if (usageCount > 0) {- setIsDeleteDialogOpen(true);- } else {- updateWebstudioData((data) => {- deleteVariableMutable(data, variable.id);- });- }+ setVariableToDelete({+ id: variable.id,+ name: variable.name,+ usages: usageCount,+ });}}>Delete {usageCount > 0 && `(${usageCount} bindings)`}@@ -218,35 +216,18 @@ const VariablesItem = ({</DropdownMenu>)}- <Dialog- open={isDeleteDialogOpen}- onOpenChange={setIsDeleteDialogOpen}- >- <DialogContent>- <DialogTitle>Delete Variable?</DialogTitle>- <DialogDescription- className={css({- paddingInline: theme.panel.paddingInline,- textWrap: "nowrap",- }).toString()}- >- Variable "{variable.name}" is used in {usageCount} - {usageCount === 1 ? "expression" : "expressions"}.- </DialogDescription>- <DialogActions>- <Button- color="destructive"- onClick={() => {- updateWebstudioData((data) => {- deleteVariableMutable(data, variable.id);- });- }}- >- Delete- </Button>- </DialogActions>- </DialogContent>- </Dialog>+ <DeleteDataVariableDialog+ variable={variableToDelete}+ onClose={() => {+ setVariableToDelete(undefined);+ }}+ onConfirm={(variableId) => {+ updateWebstudioData((data) => {+ deleteVariableMutable(data, variableId);+ });+ setVariableToDelete(undefined);+ }}+ /></>}/>diff --git a/apps/builder/app/builder/shared/data-variable-utils.test.tsx b/apps/builder/app/builder/shared/data-variable-utils.test.tsxnew file mode 100644index 0000000000..3c8cdc446d--- /dev/null+++ b/apps/builder/app/builder/shared/data-variable-utils.test.tsx@@ -0,0 +1,145 @@+import { expect, test } from "vitest";+import { atom } from "nanostores";+import { $dataSources } from "~/shared/nano-states";+import { validateDataVariableName } from "./data-variable-utils";+import type { DataSources, DataSource } from "@webstudio-is/sdk";++// Mock the nano-states module+const mockDataSources = atom<DataSources>(new Map());++// Replace the actual store with our mock+Object.defineProperty($dataSources, "get", {+ value: () => mockDataSources.get(),+});++// Helper to create a minimal variable data source for testing+const createVariable = (+ id: string,+ name: string,+ scopeInstanceId?: string+): DataSource => ({+ id,+ scopeInstanceId,+ name,+ type: "variable",+ value: { type: "string", value: "" },+});++test("validateDataVariableName returns required error for empty name", () => {+ mockDataSources.set(new Map());++ const error = validateDataVariableName("");+ expect(error?.type).toBe("required");+ expect(error?.message).toBe("Variable name is required");+});++test("validateDataVariableName returns required error for whitespace-only name", () => {+ mockDataSources.set(new Map());++ const error = validateDataVariableName(" ");+ expect(error?.type).toBe("required");+});++test("validateDataVariableName returns undefined for valid unique name", () => {+ mockDataSources.set(+ new Map([["var1", createVariable("var1", "existingVariable", "instance1")]])+ );++ const error = validateDataVariableName("newVariable");+ expect(error).toBeUndefined();+});++test("validateDataVariableName returns duplicate error when name exists on same instance", () => {+ mockDataSources.set(+ new Map([+ ["var1", createVariable("var1", "myVariable", "instance1")],+ ["var2", createVariable("var2", "otherVariable", "instance1")],+ ])+ );++ // Creating a new variable with existing name on same instance+ const error = validateDataVariableName("myVariable", "var2");+ expect(error?.type).toBe("duplicate");+});++test("validateDataVariableName allows same name on different instances", () => {+ mockDataSources.set(+ new Map([+ ["var1", createVariable("var1", "myVariable", "instance1")],+ ["var2", createVariable("var2", "otherVariable", "instance2")],+ ])+ );++ // Creating a variable on instance2 with name that exists on instance1+ const error = validateDataVariableName("myVariable", "var2");+ expect(error).toBeUndefined();+});++test("validateDataVariableName allows renaming variable to same name", () => {+ mockDataSources.set(+ new Map([["var1", createVariable("var1", "myVariable", "instance1")]])+ );++ // Renaming var1 to its current name+ const error = validateDataVariableName("myVariable", "var1");+ expect(error).toBeUndefined();+});++test("validateDataVariableName returns duplicate error when renaming to existing name on same instance", () => {+ mockDataSources.set(+ new Map([+ ["var1", createVariable("var1", "firstVariable", "instance1")],+ ["var2", createVariable("var2", "secondVariable", "instance1")],+ ])+ );++ // Renaming var2 to var1's name on same instance+ const error = validateDataVariableName("firstVariable", "var2");+ expect(error?.type).toBe("duplicate");+});++test("validateDataVariableName ignores non-variable data sources", () => {+ mockDataSources.set(+ new Map([+ ["var1", createVariable("var1", "myVariable", "instance1")],+ [+ "resource1",+ {+ id: "resource1",+ scopeInstanceId: "instance1",+ name: "myResource",+ type: "resource",+ resourceId: "res1",+ },+ ],+ ])+ );++ // Creating a variable with same name as resource should be allowed+ const error = validateDataVariableName("myResource");+ expect(error).toBeUndefined();+});++test("validateDataVariableName validates for new variables without variableId", () => {+ mockDataSources.set(+ new Map([["var1", createVariable("var1", "existingVariable", "instance1")]])+ );++ // Creating a new variable (no variableId) with existing name on same instance+ const error = validateDataVariableName(+ "existingVariable",+ undefined,+ "instance1"+ );+ expect(error?.type).toBe("duplicate");+});++test("validateDataVariableName handles undefined scopeInstanceId correctly", () => {+ mockDataSources.set(+ new Map([["var1", createVariable("var1", "globalVariable", undefined)]])+ );++ // Creating a variable with same name but undefined scope+ const error = validateDataVariableName("globalVariable");+ expect(error?.type).toBe("duplicate");+});diff --git a/apps/builder/app/builder/shared/data-variable-utils.tsx b/apps/builder/app/builder/shared/data-variable-utils.tsxnew file mode 100644index 0000000000..20b2829f4a--- /dev/null+++ b/apps/builder/app/builder/shared/data-variable-utils.tsx@@ -0,0 +1,234 @@+import { useState, useEffect } from "react";+import { computed } from "nanostores";+import {+ Dialog,+ DialogContent,+ DialogTitle,+ DialogClose,+ Flex,+ Text,+ Button,+ theme,+ InputField,+} from "@webstudio-is/design-system";+import type { DataSource, Instance } from "@webstudio-is/sdk";+import { ROOT_INSTANCE_ID } from "@webstudio-is/sdk";+import {+ $pages,+ $instances,+ $props,+ $dataSources,+ $resources,+} from "~/shared/nano-states";+import { serverSyncStore } from "~/shared/sync";+import { findVariableUsagesByInstance } from "~/shared/data-variables";++export type DataVariableError = {+ type: "required" | "duplicate";+ message: string;+};++/**+ * Computed store that tracks which instances use each variable+ * Returns a Map of variable ID to Set of instance IDs+ */+export const $usedVariablesInInstances = computed(+ [$pages, $instances, $props, $dataSources, $resources],+ (pages, instances, props, dataSources, resources) => {+ return findVariableUsagesByInstance({+ startingInstanceId: ROOT_INSTANCE_ID,+ pages,+ instances,+ props,+ dataSources,+ resources,+ });+ }+);++type DeleteDataVariableDialogProps = {+ variable?: { id: DataSource["id"]; name: string; usages: number };+ onClose: () => void;+ onConfirm: (variableId: DataSource["id"]) => void;+};++export const DeleteDataVariableDialog = ({+ variable,+ onClose,+ onConfirm,+}: DeleteDataVariableDialogProps) => {+ return (+ <Dialog+ open={variable !== undefined}+ onOpenChange={(isOpen) => {+ if (isOpen === false) {+ onClose();+ }+ }}+ >+ <DialogContent+ onKeyDown={(event) => {+ // Prevent command panel from handling keyboard events+ event.stopPropagation();+ }}+ >+ <DialogTitle>Delete confirmation</DialogTitle>+ <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>+ <Text>+ {variable &&+ (variable.usages > 0+ ? `Delete "${variable.name}" variable from the project? It is used in ${variable.usages} ${variable.usages === 1 ? "expression" : "expressions"}.`+ : `Delete "${variable.name}" variable from the project?`)}+ </Text>+ <Flex direction="rowReverse" gap="2">+ <Button+ color="destructive"+ onClick={() => {+ onConfirm(variable!.id);+ onClose();+ }}+ >+ Delete+ </Button>+ <DialogClose>+ <Button color="ghost">Cancel</Button>+ </DialogClose>+ </Flex>+ </Flex>+ </DialogContent>+ </Dialog>+ );+};++export const validateDataVariableName = (+ name: string,+ variableId?: DataSource["id"],+ scopeInstanceId?: Instance["id"]+): DataVariableError | undefined => {+ if (name.trim().length === 0) {+ return {+ type: "required",+ message: "Variable name is required",+ };+ }++ const dataSources = $dataSources.get();+ const currentVariable = variableId ? dataSources.get(variableId) : undefined;+ const actualScopeInstanceId =+ scopeInstanceId ??+ (currentVariable?.type === "variable"+ ? currentVariable.scopeInstanceId+ : undefined);++ for (const dataSource of dataSources.values()) {+ if (+ dataSource.type === "variable" &&+ dataSource.scopeInstanceId === actualScopeInstanceId &&+ dataSource.name === name &&+ dataSource.id !== variableId+ ) {+ return {+ type: "duplicate",+ message: "Name is already used by another variable on this instance",+ };+ }+ }+};++export const renameDataVariable = (+ id: DataSource["id"],+ name: string+): DataVariableError | undefined => {+ const validationError = validateDataVariableName(name, id);+ if (validationError) {+ return validationError;+ }++ serverSyncStore.createTransaction([$dataSources], (dataSources) => {+ const dataSource = dataSources.get(id);+ if (dataSource?.type === "variable") {+ dataSource.name = name;+ }+ });+};++type RenameDataVariableDialogProps = {+ variable?: { id: DataSource["id"]; name: string };+ onClose: () => void;+ onConfirm: (variableId: DataSource["id"], newName: string) => void;+};++export const RenameDataVariableDialog = ({+ variable,+ onClose,+ onConfirm,+}: RenameDataVariableDialogProps) => {+ const [name, setName] = useState("");+ const [error, setError] = useState<string>();++ // Reset name and clear error when variable changes+ useEffect(() => {+ if (variable?.name !== undefined) {+ setName(variable.name);+ setError(undefined);+ }+ }, [variable?.id, variable?.name]);++ const handleConfirm = () => {+ const renameError = renameDataVariable(variable!.id, name);+ if (renameError) {+ setError(renameError.message);+ return;+ }+ onConfirm(variable!.id, name);+ onClose();+ };++ return (+ <Dialog+ open={variable !== undefined}+ onOpenChange={(isOpen) => {+ if (isOpen === false) {+ onClose();+ }+ }}+ >+ <DialogContent+ onKeyDown={(event) => {+ // Prevent command panel from handling keyboard events+ event.stopPropagation();+ if (event.key === "Enter" && !error) {+ handleConfirm();+ }+ }}+ >+ <DialogTitle>Rename Variable</DialogTitle>+ <Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>+ <Flex direction="column" gap="1">+ <InputField+ value={name}+ onChange={(event) => {+ setName(event.target.value);+ setError(undefined);+ }}+ color={error ? "error" : undefined}+ />+ {error && (+ <Text color="destructive" variant="monoBold">+ {error}+ </Text>+ )}+ </Flex>+ <Flex direction="rowReverse" gap="2">+ <Button color="primary" onClick={handleConfirm}>+ Rename+ </Button>+ <DialogClose>+ <Button color="ghost">Cancel</Button>+ </DialogClose>+ </Flex>+ </Flex>+ </DialogContent>+ </Dialog>+ );+};diff --git a/apps/builder/app/shared/data-variables.test.tsx b/apps/builder/app/shared/data-variables.test.tsxindex a34599eff9..5e764c8050 100644--- a/apps/builder/app/shared/data-variables.test.tsx+++ b/apps/builder/app/shared/data-variables.test.tsx@@ -25,6 +25,7 @@ import {unsetExpressionVariables,deleteVariableMutable,findAvailableVariables,+ findVariableUsagesByInstance,} from "./data-variables";test("encode data variable name when necessary", () => {@@ -908,3 +909,134 @@ test("unset global variables in all pages meta when delete", () => {expect(page.meta.custom?.[0].content).toEqual(`globalVariable`);}});++test("find variable usages by instance", () => {+ const bodyVariable = new Variable("bodyVariable", "");+ const boxVariable = new Variable("boxVariable", "");+ const data = {+ pages: createDefaultPages({ rootInstanceId: "bodyId" }),+ ...renderData(+ <$.Body+ ws:id="bodyId"+ vars={expression`${bodyVariable}`}+ data-prop={expression`${bodyVariable} + "test"`}+ >+ <$.Box+ ws:id="boxId"+ vars={expression`${boxVariable}`}+ data-prop={expression`${boxVariable} + ${bodyVariable}`}+ >+ <$.Text ws:id="textId">{expression`${bodyVariable}`}</$.Text>+ </$.Box>+ </$.Body>+ ),+ };+ const bodyVariableId = [...data.dataSources.values()].find(+ (ds) => ds.name === "bodyVariable"+ )?.id;+ const boxVariableId = [...data.dataSources.values()].find(+ (ds) => ds.name === "boxVariable"+ )?.id;++ const usagesByInstance = findVariableUsagesByInstance({+ ...data,+ startingInstanceId: "bodyId",+ });++ expect(usagesByInstance.get(bodyVariableId!)).toEqual(+ new Set(["bodyId", "boxId", "textId"])+ );+ expect(usagesByInstance.get(boxVariableId!)).toEqual(new Set(["boxId"]));+});++test("find variable usages from root includes all pages", () => {+ const globalVariable = new Variable("globalVariable", "");+ const data = {+ pages: createDefaultPages({ rootInstanceId: "homeBodyId" }),+ ...renderData(+ <ws.root ws:id={ROOT_INSTANCE_ID} vars={expression`${globalVariable}`}>+ <$.Body ws:id="homeBodyId">+ <$.Box ws:id="homeBoxId" data-prop={expression`${globalVariable}`} />+ </$.Body>+ <$.Body ws:id="aboutBodyId">+ <$.Box ws:id="aboutBoxId" data-prop={expression`${globalVariable}`} />+ </$.Body>+ </ws.root>+ ),+ };+ data.instances.delete(ROOT_INSTANCE_ID);+ data.pages.pages.push({+ id: "aboutPage",+ name: "About",+ path: "/about",+ title: "",+ meta: {},+ rootInstanceId: "aboutBodyId",+ });++ const [globalVariableId] = data.dataSources.keys();++ const usagesByInstance = findVariableUsagesByInstance({+ ...data,+ startingInstanceId: ROOT_INSTANCE_ID,+ });++ // Global variable is used in expressions on both boxes and the root (where it's defined)+ expect(usagesByInstance.get(globalVariableId)).toEqual(+ new Set([ROOT_INSTANCE_ID, "homeBoxId", "aboutBoxId"])+ );+});++test("find variable usages in page meta", () => {+ const bodyVariable = new Variable("bodyVariable", "");+ const data = {+ pages: createDefaultPages({ rootInstanceId: "bodyId" }),+ ...renderData(+ <$.Body ws:id="bodyId" vars={expression`${bodyVariable}`}></$.Body>+ ),+ };+ const [bodyVariableId] = data.dataSources.keys();+ const bodyIdentifier = encodeDataVariableId(bodyVariableId);++ data.pages.homePage.title = bodyIdentifier;+ data.pages.homePage.meta = {+ description: bodyIdentifier,+ excludePageFromSearch: bodyIdentifier,+ socialImageUrl: bodyIdentifier,+ };++ const usagesByInstance = findVariableUsagesByInstance({+ ...data,+ startingInstanceId: "bodyId",+ });++ // Page meta expressions are attributed to the page's root instance+ expect(usagesByInstance.get(bodyVariableId)).toEqual(new Set(["bodyId"]));+});++test("find variable usages counts unique instances not expressions", () => {+ const bodyVariable = new Variable("bodyVariable", "");+ const data = {+ pages: createDefaultPages({ rootInstanceId: "bodyId" }),+ ...renderData(+ <$.Body+ ws:id="bodyId"+ vars={expression`${bodyVariable}`}+ data-prop1={expression`${bodyVariable}`}+ data-prop2={expression`${bodyVariable}`}+ data-prop3={expression`${bodyVariable}`}+ ></$.Body>+ ),+ };+ const [bodyVariableId] = data.dataSources.keys();++ const usagesByInstance = findVariableUsagesByInstance({+ ...data,+ startingInstanceId: "bodyId",+ });++ // Even though bodyVariable is used 4 times (in 4 different expressions),+ // it should only appear once in the set since it's all on the same instance+ expect(usagesByInstance.get(bodyVariableId)).toEqual(new Set(["bodyId"]));+ expect(usagesByInstance.get(bodyVariableId)?.size).toBe(1);+});diff --git a/apps/builder/app/shared/data-variables.ts b/apps/builder/app/shared/data-variables.tsindex f9a9c49b81..ab0acc0e9f 100644--- a/apps/builder/app/shared/data-variables.ts+++ b/apps/builder/app/shared/data-variables.ts@@ -491,6 +491,45 @@ export const findUsedVariables = ({return usedVariables;};+export const findVariableUsagesByInstance = ({+ startingInstanceId,+ pages,+ instances,+ props,+ dataSources,+ resources,+}: {+ startingInstanceId: Instance["id"];+ pages: undefined | Pages;+ instances: Instances;+ props: Props;+ dataSources: DataSources;+ resources: Resources;+}) => {+ const usedIn = new Map<DataSource["id"], Set<Instance["id"]>>();+ traverseExpressions({+ startingInstanceId,+ pages,+ instances,+ props,+ dataSources,+ resources,+ update: (expression, instanceId) => {+ const identifiers = getExpressionIdentifiers(expression);+ for (const identifier of identifiers) {+ const id = decodeDataVariableId(identifier);+ if (id !== undefined) {+ if (!usedIn.has(id)) {+ usedIn.set(id, new Set());+ }+ usedIn.get(id)?.add(instanceId);+ }+ }+ },+ });+ return usedIn;+};+export const rebindTreeVariablesMutable = ({startingInstanceId,pages,