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: New token conflict resolution logic (#5524)
Oleg Isonen11ba996f1366
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsxindex 97d4e10bed..a13d8229e1 100644--- a/apps/builder/app/builder/builder.tsx+++ b/apps/builder/app/builder/builder.tsx@@ -57,10 +57,11 @@ import { migrateWebstudioDataMutable } from "~/shared/webstudio-data-migrator";import { Loading, LoadingBackground } from "./shared/loading";import { mergeRefs } from "@react-aria/utils";import { CommandPanel } from "./features/command-panel";-import { DeleteUnusedTokensDialog } from "~/builder/shared/style-source-utils";+import { DeleteUnusedTokensDialog } from "~/builder/shared/style-source-actions";import { DeleteUnusedDataVariablesDialog } from "~/builder/shared/data-variable-utils";import { DeleteUnusedCssVariablesDialog } from "~/builder/shared/css-variable-utils";import { KeyboardShortcutsDialog } from "./features/keyboard-shortcuts-dialog";+import { TokenConflictDialog } from "~/shared/token-conflict-dialog";import {initCopyPaste,@@ -465,6 +466,7 @@ export const Builder = ({<DeleteUnusedDataVariablesDialog /><DeleteUnusedCssVariablesDialog /><KeyboardShortcutsDialog />+ <TokenConflictDialog /><RemoteDialog /></div></TooltipProvider>diff --git a/apps/builder/app/builder/features/command-panel/command-panel.tsx b/apps/builder/app/builder/features/command-panel/command-panel.tsxindex 332addf7c9..6d74bbd605 100644--- a/apps/builder/app/builder/features/command-panel/command-panel.tsx+++ b/apps/builder/app/builder/features/command-panel/command-panel.tsx@@ -14,6 +14,7 @@ import {$commandContent,$isCommandPanelOpen,$commandSearch,+ $commandContentKey,closeCommandPanel,} from "./command-state";import { $allOptions, groups, type Option } from "./groups";@@ -64,13 +65,14 @@ const CommandDialogContent = () => {export const CommandPanel = () => {const isOpen = useStore($isCommandPanelOpen);const commandContent = useStore($commandContent);+ const contentKey = useStore($commandContentKey);return (<CommandDialogopen={isOpen}onOpenChange={() => closeCommandPanel({ restoreFocus: true })}>- <Command shouldFilter={false}>+ <Command key={contentKey} shouldFilter={false}>{commandContent ?? <CommandDialogContent />}</Command></CommandDialog>diff --git a/apps/builder/app/builder/features/command-panel/command-state.ts b/apps/builder/app/builder/features/command-panel/command-state.tsindex f85d4e4a5f..455da45774 100644--- a/apps/builder/app/builder/features/command-panel/command-state.ts+++ b/apps/builder/app/builder/features/command-panel/command-state.ts@@ -41,6 +41,9 @@ export const closeCommandPanel = ({export const $commandContent = atom<ReactNode>();+// Counter to force Command component remount when content changes+export const $commandContentKey = atom(0);+export const $commandSearch = atom("");export const focusCommandPanel = () => {diff --git a/apps/builder/app/builder/features/command-panel/groups/duplicate-tokens-group.tsx b/apps/builder/app/builder/features/command-panel/groups/duplicate-tokens-group.tsxnew file mode 100644index 0000000000..a2c171ee03--- /dev/null+++ b/apps/builder/app/builder/features/command-panel/groups/duplicate-tokens-group.tsx@@ -0,0 +1,352 @@+import { useState } from "react";+import { computed } from "nanostores";+import { useStore } from "@nanostores/react";+import { matchSorter } from "match-sorter";+import {+ CommandGroup,+ CommandGroupHeading,+ CommandGroupFooter,+ CommandFooter,+ CommandItem,+ CommandInput,+ CommandList,+ Text,+ Flex,+ ScrollArea,+ toast,+ useSelectedAction,+} from "@webstudio-is/design-system";+import type { Instance, StyleSource } from "@webstudio-is/sdk";+import {+ $styleSources,+ $styles,+ $breakpoints,+} from "~/shared/sync/data-stores";+import { $selectedStyleSources } from "~/shared/nano-states";+import { findDuplicateTokens } from "~/shared/style-source-utils";+import { $styleSourceUsages } from "~/builder/shared/style-source-actions";+import { InstanceList, showInstance } from "../shared/instance-list";+import {+ $commandContent,+ $commandContentKey,+ closeCommandPanel,+ openCommandPanel,+} from "../command-state";+import type { BaseOption } from "../shared/types";+import { formatUsageCount, getUsageSearchTerms } from "../shared/usage-utils";+import { BackButton } from "../shared/back-button";++export type DuplicateTokenOption = BaseOption & {+ type: "duplicateToken";+ token: Extract<StyleSource, { type: "token" }>;+ duplicates: StyleSource["id"][];+ usages: number;+};++export const $duplicateTokenOptions = computed(+ [$styleSources, $styles, $breakpoints, $styleSourceUsages],+ (styleSources, styles, breakpoints, styleSourceUsages) => {+ const duplicateTokenOptions: DuplicateTokenOption[] = [];++ const duplicatesMap = findDuplicateTokens({+ styleSources,+ styles,+ breakpoints,+ });++ for (const [tokenId, duplicateIds] of duplicatesMap) {+ const styleSource = styleSources.get(tokenId);+ if (styleSource?.type !== "token") {+ continue;+ }+ const usages = styleSourceUsages.get(tokenId)?.size ?? 0;+ duplicateTokenOptions.push({+ terms: [+ "duplicate tokens",+ "duplicates",+ styleSource.name,+ ...getUsageSearchTerms(usages),+ ],+ type: "duplicateToken",+ token: styleSource,+ duplicates: duplicateIds,+ usages,+ });+ }+ return duplicateTokenOptions;+ }+);++/**+ * Show the duplicate tokens view in the command panel+ */+export const showDuplicateTokensView = () => {+ const options = $duplicateTokenOptions.get();+ if (options.length === 0) {+ toast.info("No duplicate tokens found");+ return;+ }+ openCommandPanel();+ $commandContent.set(<DuplicateTokensGroup options={options} />);+};++const selectToken = (+ instanceId: Instance["id"],+ tokenId: StyleSource["id"]+) => {+ showInstance(instanceId, "style");+ const selectedStyleSources = new Map($selectedStyleSources.get());+ selectedStyleSources.set(instanceId, tokenId);+ $selectedStyleSources.set(selectedStyleSources);+};++const DuplicateTokensList = ({+ duplicateIds,+ tokenName,+}: {+ duplicateIds: StyleSource["id"][];+ tokenName: string;+}) => {+ const styleSources = useStore($styleSources);+ const usages = useStore($styleSourceUsages);+ const duplicateTokenOptions = $duplicateTokenOptions.get();+ const action = useSelectedAction();+ const [search, setSearch] = useState("");++ // Build options for search+ const options = duplicateIds+ .map((duplicateId) => {+ const duplicate = styleSources.get(duplicateId);+ if (duplicate?.type !== "token") {+ return null;+ }+ const duplicateUsages = usages.get(duplicateId)?.size ?? 0;+ return {+ id: duplicateId,+ token: duplicate,+ usages: duplicateUsages,+ terms: [duplicate.name, ...getUsageSearchTerms(duplicateUsages)],+ };+ })+ .filter((opt): opt is NonNullable<typeof opt> => opt !== null);++ let matches = options;+ // 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: ["terms"],+ });+ }+ }++ return (+ <>+ <CommandInput+ placeholder="Search duplicates..."+ value={search}+ onValueChange={(value) => setSearch(value)}+ onKeyDown={(event) => {+ if (event.key === "Backspace" && search === "") {+ event.preventDefault();+ // Go back to duplicate tokens view+ $commandContentKey.set($commandContentKey.get() + 1);+ $commandContent.set(+ <DuplicateTokensGroup options={duplicateTokenOptions} />+ );+ }+ }}+ />+ <Flex direction="column" css={{ maxHeight: 300 }}>+ <ScrollArea>+ <CommandList key={tokenName}>+ <CommandGroup+ name="duplicates"+ heading={+ <CommandGroupHeading>+ Duplicates of {tokenName}+ </CommandGroupHeading>+ }+ actions={["show duplicates", "show instances"]}+ >+ {matches.map(({ id, token, usages: duplicateUsages }) => (+ <CommandItem+ key={id}+ value={id}+ onSelect={() => {+ if (action === "show duplicates" || !action) {+ // Show duplicates of this duplicate token+ const allDuplicates = duplicateTokenOptions.find(+ (opt) => opt.token.id === id+ )?.duplicates;+ if (allDuplicates) {+ $commandContentKey.set($commandContentKey.get() + 1);+ $commandContent.set(+ <DuplicateTokensList+ duplicateIds={allDuplicates}+ tokenName={token.name}+ />+ );+ }+ }+ if (+ action === "show instances" ||+ action === "find instances" ||+ action === "find"+ ) {+ $commandContentKey.set($commandContentKey.get() + 1);+ $commandContent.set(<TokenInstances tokenId={id} />);+ }+ }}+ >+ <Text variant="labelsTitleCase">+ {token.name}{" "}+ <Text as="span" color="moreSubtle">+ {formatUsageCount(duplicateUsages)}+ </Text>+ </Text>+ </CommandItem>+ ))}+ </CommandGroup>+ </CommandList>+ </ScrollArea>+ </Flex>+ <CommandGroupFooter>+ <Flex align="center" justify="between" css={{ width: "100%" }}>+ <BackButton+ onClick={() => {+ // Go back to duplicate tokens view+ $commandContentKey.set($commandContentKey.get() + 1);+ $commandContent.set(+ <DuplicateTokensGroup options={duplicateTokenOptions} />+ );+ }}+ />+ <CommandFooter />+ </Flex>+ </CommandGroupFooter>+ </>+ );+};++const TokenInstances = ({ tokenId }: { tokenId: StyleSource["id"] }) => {+ const usages = useStore($styleSourceUsages);+ const usedInInstanceIds = usages.get(tokenId) ?? new Set();+ const duplicateTokenOptions = $duplicateTokenOptions.get();++ return (+ <InstanceList+ instanceIds={usedInInstanceIds}+ onSelect={(instanceId) => {+ selectToken(instanceId, tokenId);+ closeCommandPanel();+ }}+ onBack={() => {+ // Go back to duplicate tokens view+ $commandContentKey.set($commandContentKey.get() + 1);+ $commandContent.set(+ <DuplicateTokensGroup options={duplicateTokenOptions} />+ );+ }}+ />+ );+};++export const DuplicateTokensGroup = ({+ options,+}: {+ options: DuplicateTokenOption[];+}) => {+ const action = useSelectedAction();+ const [search, setSearch] = useState("");++ let matches = options;+ // 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: ["terms"],+ });+ }+ }++ return (+ <>+ <CommandInput+ placeholder="Search duplicate tokens..."+ value={search}+ onValueChange={(value) => setSearch(value)}+ onKeyDown={(event) => {+ if (event.key === "Backspace" && search === "") {+ event.preventDefault();+ // Go back to main command panel+ $commandContentKey.set($commandContentKey.get() + 1);+ $commandContent.set(undefined);+ }+ }}+ />+ <Flex direction="column" css={{ maxHeight: 300 }}>+ <ScrollArea>+ <CommandList key="duplicate-tokens-main">+ <CommandGroup+ name="duplicateToken"+ heading={+ <CommandGroupHeading>Duplicate tokens</CommandGroupHeading>+ }+ actions={["show duplicates", "show instances"]}+ >+ {matches.map(({ token, duplicates, usages }) => (+ <CommandItem+ key={token.id}+ // preserve selected state when rerender+ value={token.id}+ onSelect={() => {+ if (action === "show duplicates" || !action) {+ $commandContentKey.set($commandContentKey.get() + 1);+ $commandContent.set(+ <DuplicateTokensList+ duplicateIds={duplicates}+ tokenName={token.name}+ />+ );+ }+ if (+ action === "show instances" ||+ action === "find instances" ||+ action === "find"+ ) {+ $commandContentKey.set($commandContentKey.get() + 1);+ $commandContent.set(+ <TokenInstances tokenId={token.id} />+ );+ }+ }}+ >+ <Text variant="labelsTitleCase">+ {token.name}{" "}+ <Text as="span" color="moreSubtle">+ {formatUsageCount(usages)} · {duplicates.length} duplicate+ {duplicates.length !== 1 ? "s" : ""}+ </Text>+ </Text>+ </CommandItem>+ ))}+ </CommandGroup>+ </CommandList>+ </ScrollArea>+ </Flex>+ <CommandGroupFooter>+ <Flex align="center" justify="between" css={{ width: "100%" }}>+ <BackButton+ onClick={() => {+ // Go back to main command panel+ $commandContentKey.set($commandContentKey.get() + 1);+ $commandContent.set(undefined);+ }}+ />+ <CommandFooter />+ </Flex>+ </CommandGroupFooter>+ </>+ );+};diff --git a/apps/builder/app/builder/features/command-panel/groups/index.ts b/apps/builder/app/builder/features/command-panel/groups/index.tsindex e4f0e08a00..6c57465dad 100644--- a/apps/builder/app/builder/features/command-panel/groups/index.ts+++ b/apps/builder/app/builder/features/command-panel/groups/index.ts@@ -17,6 +17,10 @@ import {type CommandOption,} from "./commands-group";import { $tokenOptions, TokensGroup, type TokenOption } from "./tokens-group";+import {+ DuplicateTokensGroup,+ type DuplicateTokenOption,+} from "./duplicate-tokens-group";import {$dataVariableOptions,DataVariablesGroup,@@ -35,6 +39,7 @@ export type Option =| PageOption| CommandOption| TokenOption+ | DuplicateTokenOption| DataVariableOption| CssVariableOption;@@ -88,6 +93,7 @@ export const groups: {page: PagesGroup,command: CommandsGroup,token: TokensGroup,+ duplicateToken: DuplicateTokensGroup,dataVariable: DataVariablesGroup,cssVariable: CssVariablesGroup,};@@ -99,6 +105,7 @@ export type {PageOption,CommandOption,TokenOption,+ DuplicateTokenOption,DataVariableOption,CssVariableOption,};@@ -110,6 +117,7 @@ export {PagesGroup,CommandsGroup,TokensGroup,+ DuplicateTokensGroup,DataVariablesGroup,CssVariablesGroup,};diff --git a/apps/builder/app/builder/features/command-panel/groups/tokens-group.tsx b/apps/builder/app/builder/features/command-panel/groups/tokens-group.tsxindex 1d05aaa2d2..15536ed676 100644--- a/apps/builder/app/builder/features/command-panel/groups/tokens-group.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/tokens-group.tsx@@ -18,7 +18,7 @@ import {DeleteStyleSourceDialog,RenameStyleSourceDialog,$styleSourceUsages,-} from "~/builder/shared/style-source-utils";+} from "~/builder/shared/style-source-actions";import { InstanceList, showInstance } from "../shared/instance-list";import {$commandContent,@@ -98,7 +98,7 @@ export const TokensGroup = ({ options }: { options: TokenOption[] }) => {<CommandGroupname="token"heading={<CommandGroupHeading>Tokens</CommandGroupHeading>}- actions={["find", "rename", "delete"]}+ actions={["show instances", "rename", "delete"]}>{options.map(({ token, usages }) => (<CommandItem@@ -106,7 +106,11 @@ export const TokensGroup = ({ options }: { options: TokenOption[] }) => {// preserve selected state when rerendervalue={token.id}onSelect={() => {- if (action === "find") {+ if (+ action === "show instances" ||+ action === "find instances" ||+ action === "find"+ ) {$commandContent.set(<TokenInstances tokenId={token.id} />);}if (action === "rename") {diff --git a/apps/builder/app/builder/features/command-panel/shared/back-button.tsx b/apps/builder/app/builder/features/command-panel/shared/back-button.tsxindex b9f992ec0f..91672be209 100644--- a/apps/builder/app/builder/features/command-panel/shared/back-button.tsx+++ b/apps/builder/app/builder/features/command-panel/shared/back-button.tsx@@ -1,13 +1,17 @@import { Button, Kbd } from "@webstudio-is/design-system";import { $commandContent } from "../command-state";-export const BackButton = () => {+export const BackButton = ({ onClick }: { onClick?: () => void }) => {return (<ButtontabIndex={-1}color="ghost"onClick={() => {- $commandContent.set(undefined);+ if (onClick) {+ onClick();+ } else {+ $commandContent.set(undefined);+ }}}><Kbd value={["backspace"]} /> Backdiff --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 76b1ddab6f..9bbcf53fff 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@@ -28,9 +28,14 @@ export type InstanceOption = {type InstanceListProps = {instanceIds: Set<Instance["id"]>;onSelect: (instanceId: Instance["id"]) => void;+ onBack?: () => void;};-export const InstanceList = ({ instanceIds, onSelect }: InstanceListProps) => {+export const InstanceList = ({+ instanceIds,+ onSelect,+ onBack,+}: InstanceListProps) => {const instances = $instances.get();const pages = $pages.get();const usedInInstances: InstanceOption[] = [];@@ -49,7 +54,11 @@ export const InstanceList = ({ instanceIds, onSelect }: InstanceListProps) => {const [search, setSearch] = useState("");const goBack = () => {- $commandContent.set(undefined);+ if (onBack) {+ onBack();+ } else {+ $commandContent.set(undefined);+ }};let matches = usedInInstances;diff --git a/apps/builder/app/builder/features/style-panel/style-source-section.tsx b/apps/builder/app/builder/features/style-panel/style-source-section.tsxindex 73fbb3c6a7..cae93bdeff 100644--- a/apps/builder/app/builder/features/style-panel/style-source-section.tsx+++ b/apps/builder/app/builder/features/style-panel/style-source-section.tsx@@ -18,7 +18,7 @@ import {type RenameStyleSourceError,deleteStyleSource,DeleteStyleSourceDialog,-} from "~/builder/shared/style-source-utils";+} from "~/builder/shared/style-source-actions";import {$registeredComponentMetas,$selectedInstanceStatesByStyleSourceId,diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.tsindex 12cdf3493f..11b35f3fb1 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts@@ -10,6 +10,7 @@ import {insertInstanceChildrenMutable,insertWebstudioFragmentCopy,updateWebstudioData,+ insertFragmentWithConflictResolution,} from "~/shared/instance-utils";import {$instances,@@ -142,7 +143,7 @@ export const insertListItemAt = (listItemSelector: InstanceSelector) => {});};-export const insertTemplateAt = (+export const insertTemplateAt = async (templateSelector: InstanceSelector,anchor: InstanceSelector,insertBefore: boolean@@ -175,52 +176,62 @@ export const insertTemplateAt = (position,};- updateWebstudioData((data) => {- const { newInstanceIds } = insertWebstudioFragmentCopy({- data,+ try {+ const conflictResolution = await insertFragmentWithConflictResolution({fragment,- availableVariables: findAvailableVariables({- ...data,- startingInstanceId: target.parentSelector[0],- }),- projectId: project.id,});- const newRootInstanceId = newInstanceIds.get(fragment.instances[0].id);- if (newRootInstanceId === undefined) {- return;- }- const children: Instance["children"] = [- { type: "id", value: newRootInstanceId },- ];- insertInstanceChildrenMutable(data, children, target);+ updateWebstudioData((data) => {+ const { newInstanceIds } = insertWebstudioFragmentCopy({+ data,+ fragment,+ availableVariables: findAvailableVariables({+ ...data,+ startingInstanceId: target.parentSelector[0],+ }),+ projectId: project.id,+ conflictResolution,+ });+ const newRootInstanceId = newInstanceIds.get(fragment.instances[0].id);+ if (newRootInstanceId === undefined) {+ return;+ }+ const children: Instance["children"] = [+ { type: "id", value: newRootInstanceId },+ ];++ insertInstanceChildrenMutable(data, children, target);++ const selectedInstanceSelector = [+ newRootInstanceId,+ ...target.parentSelector,+ ];++ const selectors: InstanceSelector[] = [];++ findAllEditableInstanceSelector({+ instanceSelector: selectedInstanceSelector,+ instances: data.instances,+ props: data.props,+ metas: $registeredComponentMetas.get(),+ results: selectors,+ });- const selectedInstanceSelector = [- newRootInstanceId,- ...target.parentSelector,- ];+ const editableInstanceSelector = selectors[0];- const selectors: InstanceSelector[] = [];+ if (editableInstanceSelector) {+ $textEditingInstanceSelector.set({+ selector: editableInstanceSelector,+ reason: "new",+ });+ } else {+ $textEditingInstanceSelector.set(undefined);+ }- findAllEditableInstanceSelector({- instanceSelector: selectedInstanceSelector,- instances: data.instances,- props: data.props,- metas: $registeredComponentMetas.get(),- results: selectors,+ selectInstance([newRootInstanceId, ...target.parentSelector]);});-- const editableInstanceSelector = selectors[0];-- if (editableInstanceSelector) {- $textEditingInstanceSelector.set({- selector: editableInstanceSelector,- reason: "new",- });- } else {- $textEditingInstanceSelector.set(undefined);- }-- selectInstance([newRootInstanceId, ...target.parentSelector]);- });+ } catch {+ // User cancelled the operation+ return;+ }};diff --git a/apps/builder/app/builder/shared/calc-canvas-width.ts b/apps/builder/app/builder/shared/calc-canvas-width.tsindex 27aaf809f7..617e7f4848 100644--- a/apps/builder/app/builder/shared/calc-canvas-width.ts+++ b/apps/builder/app/builder/shared/calc-canvas-width.ts@@ -5,7 +5,7 @@ import {groupBreakpoints,isBaseBreakpoint,minCanvasWidth,-} from "~/shared/breakpoints";+} from "~/shared/breakpoints-utils";import { $workspaceRect, $canvasWidth } from "~/builder/shared/nano-states";import {$breakpoints,diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.tsindex b089edd776..a5564a3aa3 100644--- a/apps/builder/app/builder/shared/commands.ts+++ b/apps/builder/app/builder/shared/commands.ts@@ -45,7 +45,7 @@ import { generateFragmentFromHtml } from "~/shared/html";import { generateFragmentFromTailwind } from "~/shared/tailwind/tailwind";import { denormalizeSrcProps } from "~/shared/copy-paste/asset-upload";import { isSyncIdle } from "~/shared/sync/project-queue";-import { openDeleteUnusedTokensDialog } from "~/builder/shared/style-source-utils";+import { openDeleteUnusedTokensDialog } from "~/builder/shared/style-source-actions";import { openDeleteUnusedDataVariablesDialog } from "~/builder/shared/data-variable-utils";import { openDeleteUnusedCssVariablesDialog } from "~/builder/shared/css-variable-utils";import { openKeyboardShortcutsDialog } from "~/builder/features/keyboard-shortcuts-dialog";@@ -502,6 +502,20 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({},},+ {+ name: "findDuplicateTokens",+ label: "Find duplicate tokens",+ description: "Find tokens with identical styles or names",+ handler: () => {+ // Import needed to avoid circular dependency+ import(+ "~/builder/features/command-panel/groups/duplicate-tokens-group"+ ).then(({ showDuplicateTokensView }) => {+ showDuplicateTokensView();+ });+ },+ },+{name: "deleteUnusedDataVariables",label: "Delete unused data variables",diff --git a/apps/builder/app/builder/shared/style-source-utils.tsx b/apps/builder/app/builder/shared/style-source-actions.tsxsimilarity index 79%rename from apps/builder/app/builder/shared/style-source-utils.tsxrename to apps/builder/app/builder/shared/style-source-actions.tsxindex 2c7f565f94..a9f93fce07 100644--- a/apps/builder/app/builder/shared/style-source-utils.tsx+++ b/apps/builder/app/builder/shared/style-source-actions.tsx@@ -21,10 +21,20 @@ import {$selectedStyleSources,$selectedStyleState,} from "~/shared/nano-states";-import { removeByMutable } from "~/shared/array-utils";+import {+ deleteStyleSourceMutable,+ findUnusedTokens,+ deleteStyleSourcesMutable,+ validateAndRenameStyleSource,+ renameStyleSourceMutable,+ type RenameStyleSourceError,+} from "~/shared/style-source-utils";import { serverSyncStore } from "~/shared/sync/sync-stores";import { $selectedInstance } from "~/shared/awareness";+// Re-export the type for convenience+export type { RenameStyleSourceError };+const $isDeleteUnusedTokensDialogOpen = atom(false);export const openDeleteUnusedTokensDialog = () => {@@ -66,20 +76,12 @@ export const deleteStyleSource = (styleSourceId: StyleSource["id"]) => {serverSyncStore.createTransaction([$styleSources, $styleSourceSelections, $styles],(styleSources, styleSourceSelections, styles) => {- styleSources.delete(styleSourceId);- for (const styleSourceSelection of styleSourceSelections.values()) {- if (styleSourceSelection.values.includes(styleSourceId)) {- removeByMutable(- styleSourceSelection.values,- (item) => item === styleSourceId- );- }- }- for (const [styleDeclKey, styleDecl] of styles) {- if (styleDecl.styleSourceId === styleSourceId) {- styles.delete(styleDeclKey);- }- }+ deleteStyleSourceMutable({+ styleSourceId,+ styleSources,+ styleSourceSelections,+ styles,+ });});// reset selected style source if necessary@@ -89,16 +91,7 @@ export const deleteStyleSource = (styleSourceId: StyleSource["id"]) => {export const deleteUnusedTokens = () => {const styleSources = $styleSources.get();const styleSourceUsages = $styleSourceUsages.get();- const unusedTokenIds: StyleSource["id"][] = [];-- for (const styleSource of styleSources.values()) {- if (styleSource.type === "token") {- const usages = styleSourceUsages.get(styleSource.id);- if (usages === undefined || usages.size === 0) {- unusedTokenIds.push(styleSource.id);- }- }- }+ const unusedTokenIds = findUnusedTokens({ styleSources, styleSourceUsages });if (unusedTokenIds.length === 0) {return 0;@@ -107,54 +100,33 @@ export const deleteUnusedTokens = () => {serverSyncStore.createTransaction([$styleSources, $styleSourceSelections, $styles],(styleSources, styleSourceSelections, styles) => {- for (const styleSourceId of unusedTokenIds) {- styleSources.delete(styleSourceId);- for (const styleSourceSelection of styleSourceSelections.values()) {- if (styleSourceSelection.values.includes(styleSourceId)) {- removeByMutable(- styleSourceSelection.values,- (item) => item === styleSourceId- );- }- }- for (const [styleDeclKey, styleDecl] of styles) {- if (styleDecl.styleSourceId === styleSourceId) {- styles.delete(styleDeclKey);- }- }- }+ deleteStyleSourcesMutable({+ styleSourceIds: unusedTokenIds,+ styleSources,+ styleSourceSelections,+ styles,+ });});return unusedTokenIds.length;};-export type RenameStyleSourceError =- | { type: "minlength"; id: StyleSource["id"] }- | { type: "duplicate"; id: StyleSource["id"] };-export const renameStyleSource = (id: StyleSource["id"],name: string): RenameStyleSourceError | undefined => {const styleSources = $styleSources.get();- if (name.trim().length === 0) {- return { type: "minlength", id };- }- for (const styleSource of styleSources.values()) {- if (- styleSource.type === "token" &&- styleSource.name === name &&- styleSource.id !== id- ) {- return { type: "duplicate", id };- }+ const validationError = validateAndRenameStyleSource({+ id,+ name,+ styleSources,+ });+ if (validationError) {+ return validationError;}serverSyncStore.createTransaction([$styleSources], (styleSources) => {- const styleSource = styleSources.get(id);- if (styleSource?.type === "token") {- styleSource.name = name;- }+ renameStyleSourceMutable({ id, name, styleSources });});};@@ -301,15 +273,15 @@ export const DeleteUnusedTokensDialog = () => {$isDeleteUnusedTokensDialogOpen.set(false);};- const unusedTokens: Array<{ id: string; name: string }> = [];- for (const styleSource of styleSources.values()) {- if (styleSource.type === "token") {- const usages = styleSourceUsages.get(styleSource.id);- if (usages === undefined || usages.size === 0) {- unusedTokens.push({ id: styleSource.id, name: styleSource.name });- }- }- }+ const unusedTokenIds = findUnusedTokens({ styleSources, styleSourceUsages });+ const unusedTokens: Array<{ id: string; name: string }> = unusedTokenIds+ .map((id) => {+ const styleSource = styleSources.get(id);+ return styleSource?.type === "token"+ ? { id, name: styleSource.name }+ : null;+ })+ .filter((token): token is { id: string; name: string } => token !== null);return (<Dialogdiff --git a/apps/builder/app/shared/breakpoints-utils.test.ts b/apps/builder/app/shared/breakpoints-utils.test.tsnew file mode 100644index 0000000000..6dacf0d43b--- /dev/null+++ b/apps/builder/app/shared/breakpoints-utils.test.ts@@ -0,0 +1,220 @@+import { describe, test, expect } from "vitest";+import {+ isBaseBreakpoint,+ groupBreakpoints,+ buildMergedBreakpointIds,+} from "./breakpoints-utils";+import type { Breakpoint, Breakpoints } from "@webstudio-is/sdk";++describe("isBaseBreakpoint", () => {+ test("returns true for breakpoint without min or max width", () => {+ expect(isBaseBreakpoint({})).toBe(true);+ expect(isBaseBreakpoint({ minWidth: undefined, maxWidth: undefined })).toBe(+ true+ );+ });++ test("returns false for breakpoint with min width", () => {+ expect(isBaseBreakpoint({ minWidth: 768 })).toBe(false);+ });++ test("returns false for breakpoint with max width", () => {+ expect(isBaseBreakpoint({ maxWidth: 991 })).toBe(false);+ });++ test("returns false for breakpoint with both min and max width", () => {+ expect(isBaseBreakpoint({ minWidth: 768, maxWidth: 991 })).toBe(false);+ });+});++describe("groupBreakpoints", () => {+ test("groups breakpoints in UI order: min-width (desc), base, max-width (desc)", () => {+ const initial = [+ { minWidth: 1920 },+ { minWidth: 1440 },+ { minWidth: 1280 },+ {},+ { maxWidth: 991 },+ { maxWidth: 767 },+ { maxWidth: 479 },+ ];+ const grouped = [+ { minWidth: 1920 },+ { minWidth: 1440 },+ { minWidth: 1280 },+ {},+ { maxWidth: 991 },+ { maxWidth: 767 },+ { maxWidth: 479 },+ ];+ expect(groupBreakpoints(initial)).toStrictEqual(grouped);+ });++ test("handles unsorted input", () => {+ const initial = [+ { maxWidth: 479 },+ { minWidth: 1920 },+ {},+ { maxWidth: 991 },+ { minWidth: 1280 },+ ];+ const grouped = [+ { minWidth: 1920 },+ { minWidth: 1280 },+ {},+ { maxWidth: 991 },+ { maxWidth: 479 },+ ];+ expect(groupBreakpoints(initial)).toStrictEqual(grouped);+ });++ test("handles only min-width breakpoints", () => {+ const initial = [{ minWidth: 768 }, { minWidth: 1024 }];+ const grouped = [{ minWidth: 1024 }, { minWidth: 768 }];+ expect(groupBreakpoints(initial)).toStrictEqual(grouped);+ });++ test("handles only max-width breakpoints", () => {+ const initial = [{ maxWidth: 991 }, { maxWidth: 479 }];+ const grouped = [{ maxWidth: 991 }, { maxWidth: 479 }];+ expect(groupBreakpoints(initial)).toStrictEqual(grouped);+ });++ test("handles only base breakpoint", () => {+ const initial = [{}];+ const grouped = [{}];+ expect(groupBreakpoints(initial)).toStrictEqual(grouped);+ });++ test("handles empty array", () => {+ expect(groupBreakpoints([])).toStrictEqual([]);+ });+});++describe("buildMergedBreakpointIds", () => {+ test("merges breakpoints with matching minWidth, maxWidth, and label", () => {+ const fragmentBreakpoints: Breakpoint[] = [+ { id: "frag-1", minWidth: 768, label: "Tablet" },+ { id: "frag-2", maxWidth: 479, label: "Mobile" },+ { id: "frag-3", minWidth: 1024, label: "Desktop" },+ ];++ const existingBreakpoints: Breakpoints = new Map([+ ["exist-1", { id: "exist-1", minWidth: 768, label: "Tablet" }],+ ["exist-2", { id: "exist-2", maxWidth: 991, label: "Small Desktop" }],+ ["exist-3", { id: "exist-3", maxWidth: 479, label: "Mobile" }],+ ]);++ const result = buildMergedBreakpointIds(+ fragmentBreakpoints,+ existingBreakpoints+ );++ expect(result.size).toBe(2);+ expect(result.get("frag-1")).toBe("exist-1"); // Tablet matches+ expect(result.get("frag-2")).toBe("exist-3"); // Mobile matches+ expect(result.has("frag-3")).toBe(false); // Desktop doesn't match+ });++ test("returns empty map when no matches found", () => {+ const fragmentBreakpoints: Breakpoint[] = [+ { id: "frag-1", minWidth: 1440, label: "Large Desktop" },+ ];++ const existingBreakpoints: Breakpoints = new Map([+ ["exist-1", { id: "exist-1", minWidth: 768, label: "Tablet" }],+ ]);++ const result = buildMergedBreakpointIds(+ fragmentBreakpoints,+ existingBreakpoints+ );++ expect(result.size).toBe(0);+ });++ test("matches base breakpoints (no min/max)", () => {+ const fragmentBreakpoints: Breakpoint[] = [+ { id: "frag-base", label: "Base" },+ ];++ const existingBreakpoints: Breakpoints = new Map([+ ["exist-base", { id: "exist-base", label: "Base" }],+ ]);++ const result = buildMergedBreakpointIds(+ fragmentBreakpoints,+ existingBreakpoints+ );++ expect(result.size).toBe(1);+ expect(result.get("frag-base")).toBe("exist-base");+ });++ test("handles empty fragment breakpoints", () => {+ const fragmentBreakpoints: Breakpoint[] = [];+ const existingBreakpoints: Breakpoints = new Map([+ ["exist-1", { id: "exist-1", minWidth: 768, label: "Tablet" }],+ ]);++ const result = buildMergedBreakpointIds(+ fragmentBreakpoints,+ existingBreakpoints+ );++ expect(result.size).toBe(0);+ });++ test("handles empty existing breakpoints", () => {+ const fragmentBreakpoints: Breakpoint[] = [+ { id: "frag-1", minWidth: 768, label: "Tablet" },+ ];+ const existingBreakpoints: Breakpoints = new Map();++ const result = buildMergedBreakpointIds(+ fragmentBreakpoints,+ existingBreakpoints+ );++ expect(result.size).toBe(0);+ });++ test("merges only first matching breakpoint", () => {+ const fragmentBreakpoints: Breakpoint[] = [+ { id: "frag-1", minWidth: 768, label: "Tablet" },+ ];++ const existingBreakpoints: Breakpoints = new Map([+ ["exist-1", { id: "exist-1", minWidth: 768, label: "Tablet" }],+ ["exist-2", { id: "exist-2", minWidth: 768, label: "Tablet" }],+ ]);++ const result = buildMergedBreakpointIds(+ fragmentBreakpoints,+ existingBreakpoints+ );++ expect(result.size).toBe(1);+ expect(result.get("frag-1")).toBe("exist-1"); // Should match first one+ });++ test("does not merge breakpoints with different labels", () => {+ const fragmentBreakpoints: Breakpoint[] = [+ { id: "frag-1", minWidth: 768, label: "Tablet" },+ ];++ const existingBreakpoints: Breakpoints = new Map([+ ["exist-1", { id: "exist-1", minWidth: 768, label: "iPad" }],+ ]);++ const result = buildMergedBreakpointIds(+ fragmentBreakpoints,+ existingBreakpoints+ );++ // equalMedia only checks minWidth/maxWidth, not labels+ // So breakpoints with same dimensions but different labels will still merge+ expect(result.size).toBe(1);+ expect(result.get("frag-1")).toBe("exist-1");+ });+});diff --git a/apps/builder/app/shared/breakpoints-utils.ts b/apps/builder/app/shared/breakpoints-utils.tsnew file mode 100644index 0000000000..44c54fe990--- /dev/null+++ b/apps/builder/app/shared/breakpoints-utils.ts@@ -0,0 +1,55 @@+import { compareMedia, equalMedia } from "@webstudio-is/css-engine";+import type { Breakpoint, Breakpoints } from "@webstudio-is/sdk";++/**+ * Check if a breakpoint is the base breakpoint (no min or max width).+ */+export const isBaseBreakpoint = (breakpoint: {+ minWidth?: number;+ maxWidth?: number;+}) => breakpoint.minWidth === undefined && breakpoint.maxWidth === undefined;++/**+ * Group breakpoints into three categories: min-width, base (no min/max), and max-width.+ * Returns them in UI display order: min-width (largest to smallest), base, max-width (largest to smallest).+ */+export const groupBreakpoints = <+ T extends { minWidth?: number; maxWidth?: number },+>(+ breakpoints: Array<T>+): Array<T> => {+ const sorted = [...breakpoints].sort(compareMedia);+ const maxs = sorted.filter((breakpoint) => breakpoint.maxWidth !== undefined);+ const mins = sorted+ .filter((breakpoint) => breakpoint.minWidth !== undefined)+ .reverse();+ const base = sorted.filter(isBaseBreakpoint);+ return [...mins, ...base, ...maxs];+};++/**+ * Build a map of merged breakpoint IDs from fragment breakpoints to existing breakpoints.+ * Breakpoints are merged when they have matching minWidth, maxWidth, and label.+ *+ * @param fragmentBreakpoints - Breakpoints from the fragment being inserted+ * @param existingBreakpoints - Existing breakpoints in the project+ * @returns Map of fragment breakpoint IDs to existing breakpoint IDs+ */+export const buildMergedBreakpointIds = (+ fragmentBreakpoints: Breakpoint[],+ existingBreakpoints: Breakpoints+): Map<Breakpoint["id"], Breakpoint["id"]> => {+ const mergedBreakpointIds = new Map<Breakpoint["id"], Breakpoint["id"]>();+ for (const newBreakpoint of fragmentBreakpoints) {+ for (const breakpoint of existingBreakpoints.values()) {+ if (equalMedia(breakpoint, newBreakpoint)) {+ mergedBreakpointIds.set(newBreakpoint.id, breakpoint.id);+ break;+ }+ }+ }+ return mergedBreakpointIds;+};++// Doesn't make sense to allow resizing the canvas lower than this.+export const minCanvasWidth = 240;diff --git a/apps/builder/app/shared/breakpoints/constants.ts b/apps/builder/app/shared/breakpoints/constants.tsdeleted file mode 100644index 0ee84b4ccd..0000000000--- a/apps/builder/app/shared/breakpoints/constants.ts+++ /dev/null@@ -1,2 +0,0 @@-// Doesn't make sense to allow resizing the canvas lower than this.-export const minCanvasWidth = 240;diff --git a/apps/builder/app/shared/breakpoints/group-breakpoints.test.ts b/apps/builder/app/shared/breakpoints/group-breakpoints.test.tsdeleted file mode 100644index f213f7bbeb..0000000000--- a/apps/builder/app/shared/breakpoints/group-breakpoints.test.ts+++ /dev/null@@ -1,26 +0,0 @@-import { describe, test, expect } from "vitest";-import { groupBreakpoints } from "./group-breakpoints";--describe("Group breakpoints", () => {- test("for ui", () => {- const initial = [- { minWidth: 1920 },- { minWidth: 1440 },- { minWidth: 1280 },- {},- { maxWidth: 991 },- { maxWidth: 767 },- { maxWidth: 479 },- ];- const grouped = [- { minWidth: 1920 },- { minWidth: 1440 },- { minWidth: 1280 },- {},- { maxWidth: 991 },- { maxWidth: 767 },- { maxWidth: 479 },- ];- expect(groupBreakpoints(initial)).toStrictEqual(grouped);- });-});diff --git a/apps/builder/app/shared/breakpoints/group-breakpoints.ts b/apps/builder/app/shared/breakpoints/group-breakpoints.tsdeleted file mode 100644index 6f8601ccc6..0000000000--- a/apps/builder/app/shared/breakpoints/group-breakpoints.ts+++ /dev/null@@ -1,17 +0,0 @@-import { compareMedia } from "@webstudio-is/css-engine";-import { isBaseBreakpoint } from "../nano-states";--// We group in 3 groups: min-width, base (no min/max), max-width conditions-export const groupBreakpoints = <- Breakpoint extends { minWidth?: number; maxWidth?: number },->(- breakpoints: Array<Breakpoint>-) => {- const sorted = [...breakpoints].sort(compareMedia);- const maxs = sorted.filter((breakpoint) => breakpoint.maxWidth !== undefined);- const mins = sorted- .filter((breakpoint) => breakpoint.minWidth !== undefined)- .reverse();- const base = sorted.filter(isBaseBreakpoint);- return [...mins, ...base, ...maxs];-};diff --git a/apps/builder/app/shared/breakpoints/index.ts b/apps/builder/app/shared/breakpoints/index.tsindex 0f2d89b0af..753170937d 100644--- a/apps/builder/app/shared/breakpoints/index.ts+++ b/apps/builder/app/shared/breakpoints/index.ts@@ -1,5 +1,8 @@-export { isBaseBreakpoint } from "~/shared/nano-states/breakpoints";+export {+ isBaseBreakpoint,+ groupBreakpoints,+ buildMergedBreakpointIds,+ minCanvasWidth,+} from "../breakpoints-utils";export * from "./select-breakpoint-by-order";-export * from "./group-breakpoints";-export * from "./constants";export * from "./stores";diff --git a/apps/builder/app/shared/breakpoints/select-breakpoint-by-order.ts b/apps/builder/app/shared/breakpoints/select-breakpoint-by-order.tsindex e285f2a320..ff5af737b2 100644--- a/apps/builder/app/shared/breakpoints/select-breakpoint-by-order.ts+++ b/apps/builder/app/shared/breakpoints/select-breakpoint-by-order.ts@@ -1,4 +1,4 @@-import { groupBreakpoints } from "./group-breakpoints";+import { groupBreakpoints } from "../breakpoints-utils";import { $selectedBreakpointId, $breakpoints } from "../nano-states";import { setCanvasWidth } from "~/builder/shared/calc-canvas-width";diff --git a/apps/builder/app/shared/builder-api.ts b/apps/builder/app/shared/builder-api.tsindex 8a533b8f1d..c502c929fe 100644--- a/apps/builder/app/shared/builder-api.ts+++ b/apps/builder/app/shared/builder-api.ts@@ -2,6 +2,7 @@ import { createRecursiveProxy } from "@trpc/server/shared";import invariant from "tiny-invariant";import { toast } from "@webstudio-is/design-system";import { uploadAssets } from "~/builder/shared/assets/use-assets";+import { showTokenConflictDialog } from "./token-conflict-dialog";const apiWindowNamespace = "__webstudio__$__builderApi";@@ -23,6 +24,7 @@ const _builderApi = {return new Map([...urlToIds.entries()].map(([url, id]) => [url.href, id]));},+ showTokenConflictDialog,};declare global {diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts b/apps/builder/app/shared/copy-paste/plugin-instance.test.tsindex 75935d2570..c1cb1bd3ed 100644--- a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts+++ b/apps/builder/app/shared/copy-paste/plugin-instance.test.ts@@ -1,4 +1,4 @@-import { describe, test, expect } from "vitest";+import { describe, test, expect, vi, beforeAll } from "vitest";import { enableMapSet } from "immer";import type {Instance,@@ -28,12 +28,21 @@ import {import { instanceText } from "./plugin-instance";import { createDefaultPages } from "@webstudio-is/project-build";import { $awareness, selectInstance } from "../awareness";+import * as instanceUtils from "../instance-utils";const expectString = expect.any(String) as unknown as string;enableMapSet();registerContainers();+// Mock insertFragmentWithConflictResolution to always return "theirs"+beforeAll(() => {+ vi.spyOn(+ instanceUtils,+ "insertFragmentWithConflictResolution"+ ).mockResolvedValue("theirs");+});+$registeredComponentMetas.set(new Map(Object.entries({ ...baseComponentMetas, ...coreMetas })));@@ -93,12 +102,12 @@ describe("paste target", () => {createInstance("box2", "Box", []),] satisfies Instance[]);- test("is inside selected instance", () => {+ test("is inside selected instance", async () => {$instances.set(instances);selectInstance(["box1", "body0"]);const clipboardData = instanceText.onCopy?.() ?? "";selectInstance(["box2", "body0"]);- instanceText.onPaste?.(clipboardData);+ await instanceText.onPaste?.(clipboardData);const instancesDifference = getMapDifference(instances, $instances.get());const [newBox1] = instancesDifference.keys();@@ -110,10 +119,10 @@ describe("paste target", () => {);});- test("is after selected instance when same as copied", () => {+ test("is after selected instance when same as copied", async () => {$instances.set(instances);selectInstance(["box1", "body0"]);- instanceText.onPaste?.(instanceText.onCopy?.() ?? "");+ await instanceText.onPaste?.(instanceText.onCopy?.() ?? "");const instancesDifference = getMapDifference(instances, $instances.get());const [newBox1] = instancesDifference.keys();@@ -185,14 +194,14 @@ describe("data sources", () => {},] satisfies Prop[]);- test("are copy pasted when scoped to copied instances", () => {+ test("are copy pasted when scoped to copied instances", async () => {$instances.set(instances);$dataSources.set(dataSources);$props.set(props);selectInstance(["box1", "body0"]);const clipboardData = instanceText.onCopy?.() ?? "";selectInstance(["body0"]);- instanceText.onPaste?.(clipboardData);+ await instanceText.onPaste?.(clipboardData);const instancesDifference = getMapDifference(instances, $instances.get());const [newBox1, newBox2] = instancesDifference.keys();@@ -254,14 +263,14 @@ describe("data sources", () => {);});- test("preserve data sources outside of scope when pasted within their scope", () => {+ test("preserve data sources outside of scope when pasted within their scope", async () => {$instances.set(instances);$props.set(props);$dataSources.set(dataSources);selectInstance(["box2", "box1", "body0"]);const clipboardData = instanceText.onCopy?.() ?? "";selectInstance(["box1", "body0"]);- instanceText.onPaste?.(clipboardData);+ await instanceText.onPaste?.(clipboardData);const instancesDifference = getMapDifference(instances, $instances.get());const [newBox2] = instancesDifference.keys();@@ -307,7 +316,7 @@ describe("data sources", () => {);});- test("copy parameter prop with new data source", () => {+ test("copy parameter prop with new data source", async () => {const instances: Instances = toMap([createInstance("body", "Body", [{ type: "id", value: "list" }]),createInstance("list", collectionComponent, []),@@ -342,7 +351,7 @@ describe("data sources", () => {selectInstance(["list", "body"]);const clipboardData = instanceText.onCopy?.() ?? "";selectInstance(["body"]);- instanceText.onPaste?.(clipboardData);+ await instanceText.onPaste?.(clipboardData);const instancesDifference = getMapDifference(instances, $instances.get());const [collectionId] = instancesDifference.keys();@@ -389,7 +398,7 @@ describe("data sources", () => {});});-test("when paste into copied instance insert after it", () => {+test("when paste into copied instance insert after it", async () => {$instances.set(toMap([createInstance("body", "Body", [{ type: "id", value: "box" }]),@@ -398,7 +407,7 @@ test("when paste into copied instance insert after it", () => {);selectInstance(["box", "body"]);const clipboardData = instanceText.onCopy?.() ?? "";- instanceText.onPaste?.(clipboardData);+ await instanceText.onPaste?.(clipboardData);expect($instances.get()).toEqual(toMap([@@ -412,7 +421,7 @@ test("when paste into copied instance insert after it", () => {);});-test("prevent pasting portal into own descendants", () => {+test("prevent pasting portal into own descendants", async () => {const instances = toMap([createInstance("body", "Body", [{ type: "id", value: "portal" }]),createInstance("portal", portalComponent, [@@ -424,12 +433,12 @@ test("prevent pasting portal into own descendants", () => {$instances.set(instances);selectInstance(["portal", "body"]);const clipboardData = instanceText.onCopy?.() ?? "";- selectInstance(["box", "fragment", "portal", "body"]);- instanceText.onPaste?.(clipboardData);+ selectInstance(["fragment", "portal", "body"]);+ await instanceText.onPaste?.(clipboardData);expect($instances.get()).toEqual(instances);});-test("prevent pasting portal into copy of it", () => {+test("prevent pasting portal into copy of it", async () => {const instances = toMap([createInstance("body", "Body", [{ type: "id", value: "portal1" },@@ -444,14 +453,14 @@ test("prevent pasting portal into copy of it", () => {createInstance("fragment", "Fragment", []),]);$instances.set(instances);- selectInstance(["portal1", "body"]);+ selectInstance(["box", "body"]);const clipboardData = instanceText.onCopy?.() ?? "";- selectInstance(["portal2", "body"]);- instanceText.onPaste?.(clipboardData);+ selectInstance(["portal", "body"]);+ await instanceText.onPaste?.(clipboardData);expect($instances.get()).toEqual(instances);});-test("insert portal into its sibling", () => {+test("insert portal into its sibling", async () => {$instances.set(toMap([createInstance("body", "Body", [@@ -468,7 +477,7 @@ test("insert portal into its sibling", () => {selectInstance(["portal", "body"]);const clipboardData = instanceText.onCopy?.() ?? "";selectInstance(["sibling", "body"]);- instanceText.onPaste?.(clipboardData);+ await instanceText.onPaste?.(clipboardData);expect($instances.get()).toEqual(toMap([@@ -488,7 +497,7 @@ test("insert portal into its sibling", () => {);});-test("insert into portal fragment when portal is a target", () => {+test("insert into portal fragment when portal is a target", async () => {$instances.set(toMap([createInstance("body", "Body", [@@ -505,7 +514,7 @@ test("insert into portal fragment when portal is a target", () => {// fragment not existsconst prevInstances = $instances.get();- instanceText.onPaste?.(clipboardData);+ await instanceText.onPaste?.(clipboardData);const [boxId, fragmentId] = getMapDifference(prevInstances,$instances.get()@@ -526,7 +535,7 @@ test("insert into portal fragment when portal is a target", () => {);// fragment already exists- instanceText.onPaste?.(clipboardData);+ await instanceText.onPaste?.(clipboardData);expect($instances.get()).toEqual(toMap([createInstance("body", "Body", [diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.tsindex 6d13ede37d..3b6115acbf 100644--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts@@ -23,6 +23,7 @@ import {getWebstudioData,insertInstanceChildrenMutable,findClosestInsertable,+ insertFragmentWithConflictResolution,type Insertable,} from "../instance-utils";import { $selectedInstancePath } from "../awareness";@@ -121,6 +122,10 @@ const findPasteTarget = (data: InstanceData): undefined | Insertable => {return;}+ if (data.instances.length === 0) {+ return;+ }+const newInstances: Instances = new Map();for (const instance of data.instances) {newInstances.set(instance.id, instance);@@ -155,7 +160,7 @@ const findPasteTarget = (data: InstanceData): undefined | Insertable => {return insertable;};-const onPaste = (clipboardData: string) => {+const onPaste = async (clipboardData: string) => {const project = $project.get();const fragment = parse(clipboardData);if (fragment === undefined || project === undefined) {@@ -167,25 +172,34 @@ const onPaste = (clipboardData: string) => {return false;}- updateWebstudioData((data) => {- const { newInstanceIds } = insertWebstudioFragmentCopy({- data,+ try {+ const conflictResolution = await insertFragmentWithConflictResolution({fragment,- availableVariables: findAvailableVariables({- ...data,- startingInstanceId: pasteTarget.parentSelector[0],- }),- projectId: project.id,});- const newRootInstanceId = newInstanceIds.get(fragment.instances[0].id);- if (newRootInstanceId === undefined) {- return;- }- const children: Instance["children"] = [- { type: "id", value: newRootInstanceId },- ];- insertInstanceChildrenMutable(data, children, pasteTarget);- });+ updateWebstudioData((data) => {+ const { newInstanceIds } = insertWebstudioFragmentCopy({+ data,+ fragment,+ availableVariables: findAvailableVariables({+ ...data,+ startingInstanceId: pasteTarget.parentSelector[0],+ }),+ projectId: project.id,+ conflictResolution,+ });+ const newRootInstanceId = newInstanceIds.get(fragment.instances[0].id);+ if (newRootInstanceId === undefined) {+ return;+ }+ const children: Instance["children"] = [+ { type: "id", value: newRootInstanceId },+ ];+ insertInstanceChildrenMutable(data, children, pasteTarget);+ });+ } catch (error) {+ // User cancelled+ return false;+ }return true;};diff --git a/apps/builder/app/shared/instance-utils.test.tsx b/apps/builder/app/shared/instance-utils.test.tsxindex 2a0b6b938c..e8e0b703e1 100644--- a/apps/builder/app/shared/instance-utils.test.tsx+++ b/apps/builder/app/shared/instance-utils.test.tsx@@ -27,6 +27,7 @@ import {coreMetas,portalComponent,elementComponent,+ ROOT_INSTANCE_ID,} from "@webstudio-is/sdk";import { showAttribute } from "@webstudio-is/react-sdk";import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";@@ -1371,51 +1372,718 @@ describe("insert webstudio fragment copy", () => {]);});- test("insert missing tokens and use merged breakpoint ids", () => {+ // Case 2: Same styles AND same name -> reuse existing token+ test("token with same styles and same name reuses existing token", () => {const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);const styleSources = toMap<StyleSource>([- { id: "token1", type: "token", name: "oldLabel" },+ { id: "existingToken", type: "token", name: "primaryColor" },]);- const data = getWebstudioDataStub({ breakpoints, styleSources });+ const styles = new Map([+ createStyleDeclPair("existingToken", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDeclPair("existingToken", "base", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });+insertWebstudioFragmentCopy({data,fragment: {...emptyFragment,- breakpoints: [{ id: "new_base", label: "Base" }],+ breakpoints: [{ id: "base", label: "base" }],styleSources: [- { id: "token1", type: "token", name: "newLabel" },- { id: "token2", type: "token", name: "myToken" },+ // Same name "primaryColor", same styles, different id+ { id: "newToken", type: "token", name: "primaryColor" },],styles: [{- styleSourceId: "token1",- breakpointId: "new_base",+ styleSourceId: "newToken",+ breakpointId: "base",property: "color",value: { type: "keyword", value: "red" },},{- styleSourceId: "token2",- breakpointId: "new_base",- property: "color",- value: { type: "keyword", value: "green" },+ styleSourceId: "newToken",+ breakpointId: "base",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },},],},availableVariables: [],projectId: "",});++ // Should reuse existing token, not create a new oneexpect(Array.from(data.styleSources.values())).toEqual([- { id: "token1", type: "token", name: "oldLabel" },- { id: "token2", type: "token", name: "myToken" },+ { id: "existingToken", type: "token", name: "primaryColor" },]);+ // No new styles should be addedexpect(Array.from(data.styles.values())).toEqual([{- styleSourceId: "token2",+ styleSourceId: "existingToken",breakpointId: "base",property: "color",- value: { type: "keyword", value: "green" },+ value: { type: "keyword", value: "red" },},+ {+ styleSourceId: "existingToken",+ breakpointId: "base",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ },+ ]);+ });++ // Case 3: Same styles but different name -> insert new token with original name+ test("token with same styles but different name inserts new token", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "token1", type: "token", name: "primaryColor" },+ ]);+ const styles = new Map([+ createStyleDeclPair("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ breakpoints: [{ id: "base", label: "base" }],+ styleSources: [+ // Different name "accentColor", same styles+ { id: "token2", type: "token", name: "accentColor" },+ ],+ styles: [+ {+ styleSourceId: "token2",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should insert new token with its original name+ const tokens = Array.from(data.styleSources.values());+ expect(tokens).toHaveLength(2);+ expect(tokens[0]).toEqual({+ id: "token1",+ type: "token",+ name: "primaryColor",+ });+ expect(tokens[1]).toMatchObject({ type: "token", name: "accentColor" });+ expect(tokens[1].id).not.toBe("token2"); // Should have new ID++ const tokenStyles = Array.from(data.styles.values());+ expect(tokenStyles).toHaveLength(2);+ expect(tokenStyles[0]).toEqual({+ styleSourceId: "token1",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ expect(tokenStyles[1]).toMatchObject({+ styleSourceId: tokens[1].id, // Should reference new token ID+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ });++ // Case 4: Different styles but same name -> add counter suffix+ test("token with different styles but same name adds counter suffix", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "token1", type: "token", name: "myToken" },+ ]);+ const styles = new Map([+ createStyleDeclPair("token1", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ breakpoints: [{ id: "base", label: "base" }],+ styleSources: [+ // Same name "myToken", different styles+ { id: "token2", type: "token", name: "myToken" },+ ],+ styles: [+ {+ styleSourceId: "token2",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should add counter suffix to the new token+ const tokens = Array.from(data.styleSources.values());+ expect(tokens).toHaveLength(2);+ expect(tokens[0]).toEqual({ id: "token1", type: "token", name: "myToken" });+ expect(tokens[1]).toMatchObject({ type: "token", name: "myToken-1" });+ expect(tokens[1].id).not.toBe("token2"); // Should have new ID++ const tokenStyles = Array.from(data.styles.values());+ expect(tokenStyles).toHaveLength(2);+ expect(tokenStyles[0]).toEqual({+ styleSourceId: "token1",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "blue" },+ });+ expect(tokenStyles[1]).toMatchObject({+ styleSourceId: tokens[1].id,+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ });++ // Case 4b: Multiple counter suffixes+ test("token with name conflict increments counter correctly", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "token1", type: "token", name: "myToken" },+ { id: "token2", type: "token", name: "myToken-1" },+ { id: "token3", type: "token", name: "myToken-2" },+ ]);+ const styles = new Map([+ createStyleDeclPair("token1", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ createStyleDeclPair("token2", "base", "color", {+ type: "keyword",+ value: "green",+ }),+ createStyleDeclPair("token3", "base", "color", {+ type: "keyword",+ value: "yellow",+ }),+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ breakpoints: [{ id: "base", label: "base" }],+ styleSources: [{ id: "token4", type: "token", name: "myToken" }],+ styles: [+ {+ styleSourceId: "token4",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should use counter 3+ const tokens = Array.from(data.styleSources.values());+ expect(tokens).toHaveLength(4);+ expect(tokens[0]).toEqual({ id: "token1", type: "token", name: "myToken" });+ expect(tokens[1]).toEqual({+ id: "token2",+ type: "token",+ name: "myToken-1",+ });+ expect(tokens[2]).toEqual({+ id: "token3",+ type: "token",+ name: "myToken-2",+ });+ expect(tokens[3]).toMatchObject({ type: "token", name: "myToken-3" });+ expect(tokens[3].id).not.toBe("token4"); // Should have new ID+ });++ // Case 6: Different styles and different name -> insert as-is+ test("token with different styles and different name inserts normally", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "token1", type: "token", name: "primaryColor" },+ ]);+ const styles = new Map([+ createStyleDeclPair("token1", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ breakpoints: [{ id: "base", label: "base" }],+ styleSources: [{ id: "token2", type: "token", name: "secondaryColor" }],+ styles: [+ {+ styleSourceId: "token2",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should insert new token normally+ const tokens = Array.from(data.styleSources.values());+ expect(tokens).toHaveLength(2);+ expect(tokens[0]).toEqual({+ id: "token1",+ type: "token",+ name: "primaryColor",+ });+ expect(tokens[1]).toMatchObject({ type: "token", name: "secondaryColor" });+ expect(tokens[1].id).not.toBe("token2"); // Should have new ID++ const tokenStyles = Array.from(data.styles.values());+ expect(tokenStyles).toHaveLength(2);+ expect(tokenStyles[0]).toEqual({+ styleSourceId: "token1",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "blue" },+ });+ expect(tokenStyles[1]).toMatchObject({+ styleSourceId: tokens[1].id,+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ });++ // Test that instance with matching token gets the token reference updated+ test("instance with reused token updates styleSourceSelection to existing token id", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "existingToken", type: "token", name: "primaryColor" },+ ]);+ const styles = new Map([+ createStyleDeclPair("existingToken", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ instances: [+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ breakpoints: [{ id: "base", label: "base" }],+ styleSources: [+ // Same name and same styles as existingToken+ { id: "newToken", type: "token", name: "primaryColor" },+ ],+ styleSourceSelections: [{ instanceId: "box", values: ["newToken"] }],+ styles: [+ {+ styleSourceId: "newToken",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should reuse existing token+ expect(Array.from(data.styleSources.values())).toEqual([+ { id: "existingToken", type: "token", name: "primaryColor" },+ ]);++ // The instance should reference the existing token, not the new one+ const newBoxId = Array.from(data.instances.keys())[0];+ expect(data.styleSourceSelections.get(newBoxId)).toEqual({+ instanceId: newBoxId,+ values: ["existingToken"], // Should use existing token id, not "newToken"+ });+ });++ // Case 3 safeguard: Same styles but different name gets suffix when name conflicts+ test("token with same styles but different name adds suffix when name already exists", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "token1", type: "token", name: "primaryColor" },+ { id: "token2", type: "token", name: "accentColor" }, // This name is taken+ ]);+ const styles = new Map([+ createStyleDeclPair("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDeclPair("token2", "base", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ breakpoints: [{ id: "base", label: "base" }],+ styleSources: [+ // Same styles as token1, but wants to use name "accentColor" which is already taken+ { id: "token3", type: "token", name: "accentColor" },+ ],+ styles: [+ {+ styleSourceId: "token3",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should add counter suffix to prevent duplicate name+ const tokens = Array.from(data.styleSources.values());+ expect(tokens).toHaveLength(3);+ expect(tokens[0]).toEqual({+ id: "token1",+ type: "token",+ name: "primaryColor",+ });+ expect(tokens[1]).toEqual({+ id: "token2",+ type: "token",+ name: "accentColor",+ });+ expect(tokens[2]).toMatchObject({ type: "token", name: "accentColor-1" });+ expect(tokens[2].id).not.toBe("token3"); // Should have new ID++ const tokenStyles = Array.from(data.styles.values());+ expect(tokenStyles).toHaveLength(3);+ expect(tokenStyles[0]).toEqual({+ styleSourceId: "token1",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ expect(tokenStyles[1]).toEqual({+ styleSourceId: "token2",+ breakpointId: "base",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ });+ expect(tokenStyles[2]).toMatchObject({+ styleSourceId: tokens[2].id,+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ });++ // Case 6 safeguard: Different styles and different name gets suffix when name conflicts+ test("token with different styles and name adds suffix when name already exists", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "token1", type: "token", name: "primaryColor" },+ { id: "token2", type: "token", name: "secondaryColor" }, // This name is taken+ ]);+ const styles = new Map([+ createStyleDeclPair("token1", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ createStyleDeclPair("token2", "base", "color", {+ type: "keyword",+ value: "green",+ }),+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ breakpoints: [{ id: "base", label: "base" }],+ styleSources: [+ // Different styles from both existing tokens, but wants name "secondaryColor"+ { id: "token3", type: "token", name: "secondaryColor" },+ ],+ styles: [+ {+ styleSourceId: "token3",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should add counter suffix to prevent duplicate name+ const tokens = Array.from(data.styleSources.values());+ expect(tokens).toHaveLength(3);+ expect(tokens[0]).toEqual({+ id: "token1",+ type: "token",+ name: "primaryColor",+ });+ expect(tokens[1]).toEqual({+ id: "token2",+ type: "token",+ name: "secondaryColor",+ });+ expect(tokens[2]).toMatchObject({+ type: "token",+ name: "secondaryColor-1",+ });+ expect(tokens[2].id).not.toBe("token3"); // Should have new ID++ const tokenStyles = Array.from(data.styles.values());+ expect(tokenStyles).toHaveLength(3);+ expect(tokenStyles[0]).toEqual({+ styleSourceId: "token1",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "blue" },+ });+ expect(tokenStyles[1]).toEqual({+ styleSourceId: "token2",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "green" },+ });+ expect(tokenStyles[2]).toMatchObject({+ styleSourceId: tokens[2].id,+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ });++ // Test that existing token with same styles but different name stays untouched+ test("existing token with matching styles but different name stays untouched when inserting new token", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "existingToken", type: "token", name: "primaryColor" },+ ]);+ const styles = new Map([+ createStyleDeclPair("existingToken", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDeclPair("existingToken", "base", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ breakpoints: [{ id: "base", label: "base" }],+ styleSources: [+ // Different name "accentColor", same styles as existingToken+ { id: "newToken", type: "token", name: "accentColor" },+ ],+ styles: [+ {+ styleSourceId: "newToken",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ styleSourceId: "newToken",+ breakpointId: "base",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should insert new token with its own name, leaving existing one untouched+ const tokens = Array.from(data.styleSources.values());+ expect(tokens).toHaveLength(2);+ expect(tokens[0]).toEqual({+ id: "existingToken",+ type: "token",+ name: "primaryColor",+ });+ expect(tokens[1]).toMatchObject({ type: "token", name: "accentColor" });+ expect(tokens[1].id).not.toBe("newToken"); // Should have new ID++ // Both tokens should have their own styles+ const tokenStyles = Array.from(data.styles.values());+ expect(tokenStyles).toHaveLength(4);+ expect(tokenStyles[0]).toEqual({+ styleSourceId: "existingToken",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ expect(tokenStyles[1]).toEqual({+ styleSourceId: "existingToken",+ breakpointId: "base",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ });+ expect(tokenStyles[2]).toMatchObject({+ styleSourceId: tokens[1].id,+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ expect(tokenStyles[3]).toMatchObject({+ styleSourceId: tokens[1].id,+ breakpointId: "base",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ });+ });++ // Critical test: inserting base name when suffixed version exists+ test("inserting token 'bbb' when 'bbb-1' with same styles exists inserts both tokens", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "existingToken", type: "token", name: "bbb-1" },+ ]);+ const styles = new Map([+ createStyleDeclPair("existingToken", "base", "color", {+ type: "keyword",+ value: "blue",+ }),]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });++ // Add an instance that uses the existing token+ const existingInstance = createInstance("existingInstance", "Box", []);+ data.instances.set("existingInstance", existingInstance);+ data.styleSourceSelections.set("existingInstance", {+ instanceId: "existingInstance",+ values: ["existingToken"],+ });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ instances: [+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ breakpoints: [{ id: "base", label: "base" }],+ styleSources: [+ // Inserting "bbb" with same styles as "bbb-1"+ { id: "newToken", type: "token", name: "bbb" },+ ],+ styleSourceSelections: [{ instanceId: "box", values: ["newToken"] }],+ styles: [+ {+ styleSourceId: "newToken",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "blue" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Both tokens should exist+ const tokens = Array.from(data.styleSources.values());+ expect(tokens).toHaveLength(2);+ expect(tokens[0]).toEqual({+ id: "existingToken",+ type: "token",+ name: "bbb-1",+ });+ expect(tokens[1]).toMatchObject({ type: "token", name: "bbb" }); // Different name, so inserted as-is+ expect(tokens[1].id).not.toBe("newToken"); // Should have new ID++ // Both should have their own styles+ const tokenStyles = Array.from(data.styles.values());+ expect(tokenStyles).toHaveLength(2);+ expect(tokenStyles[0]).toEqual({+ styleSourceId: "existingToken",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "blue" },+ });+ expect(tokenStyles[1]).toMatchObject({+ styleSourceId: tokens[1].id,+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "blue" },+ });++ // The EXISTING instance should still reference "bbb-1" (existingToken)+ expect(data.styleSourceSelections.get("existingInstance")).toEqual({+ instanceId: "existingInstance",+ values: ["existingToken"],+ });++ // The new instance should reference the new token "bbb" (tokens[1].id)+ const newBoxId = Array.from(data.instances.keys()).find(+ (id) => id !== "existingInstance"+ );+ expect(data.styleSourceSelections.get(newBoxId!)).toEqual({+ instanceId: newBoxId,+ values: [tokens[1].id],+ });});test("insert local styles with new ids and use merged breakpoint ids", () => {@@ -1538,6 +2206,369 @@ describe("insert webstudio fragment copy", () => {},]);});++ test("merge local styles into existing ROOT_INSTANCE_ID local source", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "existingLocal", type: "local" },+ ]);+ const styleSourceSelections = new Map([+ [+ ROOT_INSTANCE_ID,+ { instanceId: ROOT_INSTANCE_ID, values: ["existingLocal"] },+ ],+ ]);+ const styles = new Map([+ createStyleDeclPair("existingLocal", "base", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ]);+ const data = getWebstudioDataStub({+ breakpoints,+ styleSources,+ styleSourceSelections,+ styles,+ });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ instances: [+ {+ type: "instance",+ id: ROOT_INSTANCE_ID,+ component: "Body",+ children: [],+ },+ ],+ breakpoints: [{ id: "base", label: "base" }],+ styleSourceSelections: [+ { instanceId: ROOT_INSTANCE_ID, values: ["newLocal"] },+ ],+ styleSources: [{ id: "newLocal", type: "local" }],+ styles: [+ {+ styleSourceId: "newLocal",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should merge into existing local source+ expect(Array.from(data.styleSources.values())).toEqual([+ { id: "existingLocal", type: "local" },+ ]);+ expect(data.styleSourceSelections.get(ROOT_INSTANCE_ID)).toEqual({+ instanceId: ROOT_INSTANCE_ID,+ values: ["existingLocal"],+ });+ // Both styles should be present under the same source+ expect(Array.from(data.styles.values())).toEqual([+ {+ styleSourceId: "existingLocal",+ breakpointId: "base",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ },+ {+ styleSourceId: "existingLocal",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+ });++ test("insert instances with new ids and update child references", () => {+ const data = getWebstudioDataStub();+ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ instances: [+ {+ type: "instance",+ id: "parent",+ component: "Box",+ children: [+ { type: "id", value: "child1" },+ { type: "id", value: "child2" },+ ],+ },+ {+ type: "instance",+ id: "child1",+ component: "Text",+ children: [],+ },+ {+ type: "instance",+ id: "child2",+ component: "Text",+ children: [],+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ const newInstances = Array.from(data.instances.values());+ expect(newInstances).toHaveLength(3);++ const parentInstance = newInstances.find((i) => i.component === "Box");+ const childInstances = newInstances.filter((i) => i.component === "Text");++ expect(parentInstance).toBeDefined();+ expect(childInstances).toHaveLength(2);++ // Verify parent's children reference the new child ids+ expect(parentInstance?.children).toEqual([+ { type: "id", value: childInstances[0].id },+ { type: "id", value: childInstances[1].id },+ ]);++ // Verify new ids were generated (not same as original)+ expect(parentInstance?.id).not.toBe("parent");+ expect(childInstances[0].id).not.toBe("child1");+ expect(childInstances[1].id).not.toBe("child2");+ });++ test("skip portal content that already exists", () => {+ const instances = new Map([+ [+ "existingPortalContent",+ {+ type: "instance" as const,+ id: "existingPortalContent",+ component: "Box",+ children: [{ type: "text" as const, value: "existing" }],+ },+ ],+ ]);+ const data = getWebstudioDataStub({ instances });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ instances: [+ {+ type: "instance",+ id: "portal",+ component: portalComponent,+ children: [{ type: "id", value: "existingPortalContent" }],+ },+ {+ type: "instance",+ id: "existingPortalContent",+ component: "Box",+ children: [{ type: "text", value: "new version" }],+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should preserve existing portal content+ const existingInstance = data.instances.get("existingPortalContent");+ expect(existingInstance?.children).toEqual([+ { type: "text", value: "existing" },+ ]);+ });++ test("insert instance with expression child and update variable references", () => {+ const data = getWebstudioDataStub();++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ instances: [+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [{ type: "expression", value: "$ws$dataSource$oldVar" }],+ },+ ],+ dataSources: [+ {+ id: "oldVar",+ scopeInstanceId: "box",+ type: "variable",+ name: "myVar",+ value: { type: "string", value: "hello" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ const newBoxId = Array.from(data.instances.keys())[0];+ const newBox = data.instances.get(newBoxId);+ const newVarId = Array.from(data.dataSources.keys())[0];++ // Verify the expression was updated with the new variable id+ expect(newBox?.children[0].type).toBe("expression");+ if (newBox?.children[0].type === "expression") {+ // The encoding replaces - with __DASH__+ const encodedId = newVarId.replace(/-/g, "__DASH__");+ expect(newBox.children[0].value).toBe(`$ws$dataSource$${encodedId}`);+ }+ expect(newVarId).not.toBe("oldVar");+ });++ test("skip global variables that already exist by id", () => {+ const dataSources = new Map([+ [+ "globalVar1",+ {+ id: "globalVar1",+ scopeInstanceId: ROOT_INSTANCE_ID,+ type: "variable" as const,+ name: "Global Var",+ value: { type: "string" as const, value: "existing" },+ },+ ],+ ]);+ const data = getWebstudioDataStub({ dataSources });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ dataSources: [+ {+ id: "globalVar1",+ scopeInstanceId: ROOT_INSTANCE_ID,+ type: "variable",+ name: "Global Var",+ value: { type: "string", value: "new value" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should preserve existing global variable+ const existingVar = data.dataSources.get("globalVar1");+ expect(existingVar?.type).toBe("variable");+ if (existingVar?.type === "variable") {+ expect(existingVar.value).toEqual({+ type: "string",+ value: "existing",+ });+ }+ });++ test("skip global variables that have conflicting names with availableVariables", () => {+ const data = getWebstudioDataStub();++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ dataSources: [+ {+ id: "newGlobal",+ scopeInstanceId: ROOT_INSTANCE_ID,+ type: "variable",+ name: "conflictingName",+ value: { type: "string", value: "value" },+ },+ ],+ },+ availableVariables: [+ {+ id: "existingId",+ scopeInstanceId: ROOT_INSTANCE_ID,+ type: "variable",+ name: "conflictingName",+ value: { type: "string", value: "existing" },+ },+ ],+ projectId: "",+ });++ // Should not insert the global variable due to name conflict+ expect(data.dataSources.has("newGlobal")).toBe(false);+ });++ test("handle mixed token and local style sources in styleSourceSelections", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "existingToken", type: "token", name: "Primary" },+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ instances: [+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ breakpoints: [{ id: "base", label: "base" }],+ styleSourceSelections: [+ {+ instanceId: "box",+ values: ["localStyle1", "existingToken", "localStyle2"],+ },+ ],+ styleSources: [+ { id: "localStyle1", type: "local" },+ { id: "localStyle2", type: "local" },+ ],+ styles: [+ {+ styleSourceId: "localStyle1",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ styleSourceId: "localStyle2",+ breakpointId: "base",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ const newBoxId = Array.from(data.instances.keys())[0];+ const selection = data.styleSourceSelections.get(newBoxId);++ expect(selection?.values).toHaveLength(3);+ expect(selection?.values[1]).toBe("existingToken"); // Token preserved+ expect(selection?.values[0]).not.toBe("localStyle1"); // Local regenerated+ expect(selection?.values[2]).not.toBe("localStyle2"); // Local regenerated++ // Verify both local styles were created with new ids+ const localStyles = Array.from(data.styleSources.values()).filter(+ (s) => s.type === "local"+ );+ expect(localStyles).toHaveLength(2);+ });});describe("find closest insertable", () => {diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.tsindex 3c9c1f773d..2bb0330a76 100644--- a/apps/builder/app/shared/instance-utils.ts+++ b/apps/builder/app/shared/instance-utils.ts@@ -2,20 +2,16 @@ import { current, isDraft } from "immer";import { nanoid } from "nanoid";import { toast } from "@webstudio-is/design-system";import { builderApi } from "~/shared/builder-api";-import { equalMedia, type StyleValue } from "@webstudio-is/css-engine";+import type { StyleValue } from "@webstudio-is/css-engine";import { showAttribute } from "@webstudio-is/react-sdk";import {type Instances,- type StyleSource,type Instance,- type StyleSourceSelection,type StyleDecl,type Asset,- type StyleSources,type Breakpoints,type DataSources,type DataSource,- type Breakpoint,type WebstudioFragment,type WebstudioData,type Resource,@@ -37,6 +33,9 @@ import {blockTemplateComponent,isComponentDetachable,} from "@webstudio-is/sdk";+import { detectTokenConflicts } from "./style-source-utils";+import { type ConflictResolution } from "./token-conflict-dialog";+import { buildMergedBreakpointIds } from "./breakpoints-utils";import {$props,$styles,@@ -64,6 +63,13 @@ import {getInstanceOrCreateFragmentIfNecessary,wrapEditableChildrenAroundDropTargetMutable,} from "./tree-utils";+import {+ insertStyleSources,+ insertPortalLocalStyleSources,+ insertLocalStyleSourcesWithNewIds,+ deleteLocalStyleSourcesMutable,+ collectStyleSourcesFromInstances,+} from "./style-source-utils";import { removeByMutable } from "./array-utils";import { serverSyncStore } from "./sync/sync-stores";import { setDifference, setUnion } from "./shim";@@ -609,14 +615,11 @@ export const deleteInstanceMutable = (for (const instanceId of instanceIds) {styleSourceSelections.delete(instanceId);}- for (const styleSourceId of localStyleSourceIds) {- styleSources.delete(styleSourceId);- }- for (const [styleDeclKey, styleDecl] of styles) {- if (localStyleSourceIds.has(styleDecl.styleSourceId)) {- styles.delete(styleDeclKey);- }- }+ deleteLocalStyleSourcesMutable({+ localStyleSourceIds,+ styleSources,+ styles,+ });return true;};@@ -1116,43 +1119,32 @@ export const extractWebstudioFragment = (// collect the instance by id and all its descendants including portal instancesconst fragmentInstanceIds = findTreeInstanceIds(instances, rootInstanceId);let fragmentInstances: Instance[] = [];- const fragmentStyleSourceSelections: StyleSourceSelection[] = [];- const fragmentStyleSources: StyleSources = new Map();++ // Collect style sources and selections from instances+ const {+ styleSourceSelectionsArray: fragmentStyleSourceSelections,+ styleSourcesMap: fragmentStyleSources,+ stylesArray: fragmentStyles,+ } = collectStyleSourcesFromInstances({+ instanceIds: fragmentInstanceIds,+ styleSourceSelections,+ styleSources,+ styles,+ });+for (const instanceId of fragmentInstanceIds) {const instance = instances.get(instanceId);if (instance) {fragmentInstances.push(instance);}-- // collect all style sources bound to these instances- const styleSourceSelection = styleSourceSelections.get(instanceId);- if (styleSourceSelection) {- fragmentStyleSourceSelections.push(styleSourceSelection);- for (const styleSourceId of styleSourceSelection.values) {- if (fragmentStyleSources.has(styleSourceId)) {- continue;- }- const styleSource = styleSources.get(styleSourceId);- if (styleSource === undefined) {- continue;- }- fragmentStyleSources.set(styleSourceId, styleSource);- }- }}const fragmentAssetIds = new Set<Asset["id"]>();const fragmentFontFamilies = new Set<string>();- // collect styles bound to these style sources- const fragmentStyles: StyleDecl[] = [];+ // collect breakpoints and assets from stylesconst fragmentBreapoints: Breakpoints = new Map();- for (const styleDecl of styles.values()) {- if (fragmentStyleSources.has(styleDecl.styleSourceId) === false) {- continue;- }- fragmentStyles.push(styleDecl);-+ for (const styleDecl of fragmentStyles) {// collect breakpointsif (fragmentBreapoints.has(styleDecl.breakpointId) === false) {const breakpoint = breakpoints.get(styleDecl.breakpointId);@@ -1331,11 +1323,13 @@ export const insertWebstudioFragmentCopy = ({fragment,availableVariables,projectId,+ conflictResolution = "theirs",}: {data: Omit<WebstudioData, "pages">;fragment: WebstudioFragment;availableVariables: DataSource[];projectId: Project["id"];+ conflictResolution?: ConflictResolution;}) => {const newInstanceIds = new Map<Instance["id"], Instance["id"]>();const newDataSourceIds = new Map<DataSource["id"], DataSource["id"]>();@@ -1393,39 +1387,44 @@ export const insertWebstudioFragmentCopy = ({// merge breakpoints- const mergedBreakpointIds = new Map<Breakpoint["id"], Breakpoint["id"]>();+ const mergedBreakpointIds = buildMergedBreakpointIds(+ fragment.breakpoints,+ breakpoints+ );for (const newBreakpoint of fragment.breakpoints) {- let matched = false;- for (const breakpoint of breakpoints.values()) {- if (equalMedia(breakpoint, newBreakpoint)) {- matched = true;- mergedBreakpointIds.set(newBreakpoint.id, breakpoint.id);- break;- }- }- if (matched === false) {+ if (mergedBreakpointIds.has(newBreakpoint.id) === false) {breakpoints.set(newBreakpoint.id, newBreakpoint);}}// insert tokens with their styles- const tokenStyleSourceIds = new Set<StyleSource["id"]>();- for (const styleSource of fragment.styleSources) {- // prevent inserting styles when token is already present- if (styleSource.type === "local" || styleSources.has(styleSource.id)) {- continue;- }- styleSource.type satisfies "token";- tokenStyleSourceIds.add(styleSource.id);- styleSources.set(styleSource.id, styleSource);+ const { styleSourceIds, styleSourceIdMap, updatedStyleSources } =+ insertStyleSources({+ fragmentStyleSources: fragment.styleSources,+ fragmentStyles: fragment.styles,+ existingStyleSources: styleSources,+ existingStyles: styles,+ breakpoints,+ mergedBreakpointIds,+ conflictResolution,+ });++ // Update styleSources map with the new tokens+ for (const [id, styleSource] of updatedStyleSources) {+ styleSources.set(id, styleSource);}+for (const styleDecl of fragment.styles) {- if (tokenStyleSourceIds.has(styleDecl.styleSourceId)) {+ if (styleSourceIds.has(styleDecl.styleSourceId)) {const { breakpointId } = styleDecl;const newStyleDecl: StyleDecl = {...styleDecl,breakpointId: mergedBreakpointIds.get(breakpointId) ?? breakpointId,+ // Remap the styleSourceId to the new token ID+ styleSourceId:+ styleSourceIdMap.get(styleDecl.styleSourceId) ??+ styleDecl.styleSourceId,};styles.set(getStyleDeclKey(newStyleDecl), newStyleDecl);}@@ -1484,37 +1483,16 @@ export const insertWebstudioFragmentCopy = ({// insert local style sources with their styles- const instanceStyleSourceIds = new Set<StyleSource["id"]>();- for (const styleSourceSelection of fragment.styleSourceSelections) {- const { instanceId } = styleSourceSelection;- if (instanceIds.has(instanceId) === false) {- continue;- }- styleSourceSelections.set(instanceId, styleSourceSelection);- for (const styleSourceId of styleSourceSelection.values) {- instanceStyleSourceIds.add(styleSourceId);- }- }- const localStyleSourceIds = new Set<StyleSource["id"]>();- for (const styleSource of fragment.styleSources) {- if (- styleSource.type === "local" &&- instanceStyleSourceIds.has(styleSource.id)- ) {- localStyleSourceIds.add(styleSource.id);- styleSources.set(styleSource.id, styleSource);- }- }- for (const styleDecl of fragment.styles) {- if (localStyleSourceIds.has(styleDecl.styleSourceId)) {- const { breakpointId } = styleDecl;- const newStyleDecl: StyleDecl = {- ...styleDecl,- breakpointId: mergedBreakpointIds.get(breakpointId) ?? breakpointId,- };- styles.set(getStyleDeclKey(newStyleDecl), newStyleDecl);- }- }+ insertPortalLocalStyleSources({+ fragmentStyleSources: fragment.styleSources,+ fragmentStyleSourceSelections: fragment.styleSourceSelections,+ fragmentStyles: fragment.styles,+ instanceIds,+ styleSources,+ styleSourceSelections,+ styles,+ mergedBreakpointIds,+ });}/**@@ -1667,68 +1645,18 @@ export const insertWebstudioFragmentCopy = ({// insert local styles with new ids- const newLocalStyleSources = new Map();- for (const styleSource of fragment.styleSources) {- if (styleSource.type === "local") {- newLocalStyleSources.set(styleSource.id, styleSource);- }- }-- const newLocalStyleSourceIds = new Map<- StyleSource["id"],- StyleSource["id"]- >();- for (const { instanceId, values } of fragment.styleSourceSelections) {- if (fragmentInstanceIds.has(instanceId) === false) {- continue;- }-- const existingStyleSourceIds =- styleSourceSelections.get(instanceId)?.values ?? [];- let existingLocalStyleSource;- for (const styleSourceId of existingStyleSourceIds) {- const styleSource = styleSources.get(styleSourceId);- if (styleSource?.type === "local") {- existingLocalStyleSource = styleSource;- }- }- const newStyleSourceIds = [];- for (let styleSourceId of values) {- const newLocalStyleSource = newLocalStyleSources.get(styleSourceId);- if (newLocalStyleSource) {- // merge only :root styles and duplicate others- if (instanceId === ROOT_INSTANCE_ID && existingLocalStyleSource) {- // write local styles into existing local style source- styleSourceId = existingLocalStyleSource.id;- } else {- // create new local styles- const newId = nanoid();- styleSources.set(newId, { ...newLocalStyleSource, id: newId });- styleSourceId = newId;- }- newLocalStyleSourceIds.set(newLocalStyleSource.id, styleSourceId);- }- newStyleSourceIds.push(styleSourceId);- }- const newInstanceId = newInstanceIds.get(instanceId) ?? instanceId;- styleSourceSelections.set(newInstanceId, {- instanceId: newInstanceId,- values: newStyleSourceIds,- });- }-- for (const styleDecl of fragment.styles) {- const { breakpointId, styleSourceId } = styleDecl;- if (newLocalStyleSourceIds.has(styleDecl.styleSourceId)) {- const newStyleDecl: StyleDecl = {- ...styleDecl,- styleSourceId:- newLocalStyleSourceIds.get(styleSourceId) ?? styleSourceId,- breakpointId: mergedBreakpointIds.get(breakpointId) ?? breakpointId,- };- styles.set(getStyleDeclKey(newStyleDecl), newStyleDecl);- }- }+ insertLocalStyleSourcesWithNewIds({+ fragmentStyleSources: fragment.styleSources,+ fragmentStyleSourceSelections: fragment.styleSourceSelections,+ fragmentStyles: fragment.styles,+ fragmentInstanceIds,+ newInstanceIds,+ styleSourceIdMap,+ styleSources,+ styleSourceSelections,+ styles,+ mergedBreakpointIds,+ });return newDataIds;};@@ -1856,3 +1784,43 @@ export const buildInstancePath = (.slice(0, -1) // Remove the instance itself (last element after reverse), keep only ancestors.map(({ instance }) => getInstanceLabel(instance));};++/**+ * Detects token conflicts and shows resolution dialog if needed.+ * Returns the conflict resolution strategy to use.+ *+ * @param fragment - The fragment to check for conflicts+ * @returns Promise that resolves with "theirs" (keep incoming) or "ours" (use existing), or rejects if user cancels+ */+export const insertFragmentWithConflictResolution = async ({+ fragment,+}: {+ fragment: WebstudioFragment;+}): Promise<ConflictResolution> => {+ const data = getWebstudioData();+ if (data === undefined) {+ throw new Error("No webstudio data available");+ }++ const mergedBreakpointIds = buildMergedBreakpointIds(+ fragment.breakpoints,+ data.breakpoints+ );++ const conflicts = detectTokenConflicts({+ fragmentStyleSources: fragment.styleSources,+ fragmentStyles: fragment.styles,+ existingStyleSources: data.styleSources,+ existingStyles: data.styles,+ breakpoints: data.breakpoints,+ mergedBreakpointIds,+ });++ if (conflicts.length === 0) {+ // No conflicts, use theirs (doesn't matter which since there are no conflicts)+ return "theirs";+ }++ // Show conflict dialog and wait for user choice+ return await builderApi.showTokenConflictDialog(conflicts);+};diff --git a/apps/builder/app/shared/nano-states/breakpoints.ts b/apps/builder/app/shared/nano-states/breakpoints.tsindex 7b8ff3035f..043dddc181 100644--- a/apps/builder/app/shared/nano-states/breakpoints.ts+++ b/apps/builder/app/shared/nano-states/breakpoints.ts@@ -1,14 +1,11 @@import { atom, computed } from "nanostores";import type { Breakpoint } from "@webstudio-is/sdk";import { $breakpoints } from "../sync/data-stores";+import { isBaseBreakpoint } from "../breakpoints-utils";// Re-export for backward compatibilityexport { $breakpoints };--export const isBaseBreakpoint = (breakpoint: {- minWidth?: number;- maxWidth?: number;-}) => breakpoint.minWidth === undefined && breakpoint.maxWidth === undefined;+export { isBaseBreakpoint };export const $selectedBreakpointId = atom<undefined | Breakpoint["id"]>(undefineddiff --git a/apps/builder/app/shared/pubsub/create.test.ts b/apps/builder/app/shared/pubsub/create.test.tsindex 320fc5745e..e21dc3d390 100644--- a/apps/builder/app/shared/pubsub/create.test.ts+++ b/apps/builder/app/shared/pubsub/create.test.ts@@ -6,8 +6,9 @@ type TestPublishMap = {noPayloadAction: undefined;numberAction: number;storybook: string;- command: { source: string; name: string };+ command: { source: string; name: string; [key: string]: unknown };"command:testCommand": undefined;+ "command:commandWithPayload": { data: string; count: number };"command:anotherCommand": undefined;};@@ -548,7 +549,10 @@ describe("createPubsub", () => {// Wait for requestAnimationFrame callbackawait new Promise((resolve) => setTimeout(resolve, 10));- expect(handler).toHaveBeenCalledWith(undefined);+ expect(handler).toHaveBeenCalledWith({+ source: "builder",+ name: "testCommand",+ });});test("should only call handler for matching command", async () => {@@ -622,7 +626,10 @@ describe("createPubsub", () => {source: "builder",name: "testCommand",});- expect(specificHandler).toHaveBeenCalledWith(undefined);+ expect(specificHandler).toHaveBeenCalledWith({+ source: "builder",+ name: "testCommand",+ });});test("should unsubscribe from specific command", async () => {@@ -689,8 +696,55 @@ describe("createPubsub", () => {await new Promise((resolve) => setTimeout(resolve, 10));- expect(handler1).toHaveBeenCalledWith(undefined);- expect(handler2).toHaveBeenCalledWith(undefined);+ expect(handler1).toHaveBeenCalledWith({+ source: "builder",+ name: "testCommand",+ });+ expect(handler2).toHaveBeenCalledWith({+ source: "builder",+ name: "testCommand",+ });+ });++ test("should pass payload to command-specific subscribers", async () => {+ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ const localAddEventListenerSpy = vi.fn();+ global.window.addEventListener = localAddEventListenerSpy;++ const pubsub = createPubsub<TestPublishMap>();++ const handler = vi.fn();+ pubsub.subscribe("command:commandWithPayload", handler);++ const messageHandler = localAddEventListenerSpy.mock.calls[0][1];++ const mockEvent = {+ data: {+ action: {+ type: "command",+ payload: {+ source: "builder",+ name: "commandWithPayload",+ data: "test-data",+ count: 42,+ },+ },+ token: "development-token",+ },+ };++ messageHandler(mockEvent);++ await new Promise((resolve) => setTimeout(resolve, 10));++ expect(handler).toHaveBeenCalledWith({+ source: "builder",+ name: "commandWithPayload",+ data: "test-data",+ count: 42,+ });});});});diff --git a/apps/builder/app/shared/pubsub/create.ts b/apps/builder/app/shared/pubsub/create.tsindex 7955491c5c..9badabb3fe 100644--- a/apps/builder/app/shared/pubsub/create.ts+++ b/apps/builder/app/shared/pubsub/create.ts@@ -113,7 +113,11 @@ export const createPubsub = <PublishMap>() => {"name" in action.payload) {const commandName = (action.payload as { name: string }).name;- emitter.emit(`command:${commandName}` as keyof PublishMap, undefined);+ // Pass the full payload to command-specific subscribers+ emitter.emit(+ `command:${commandName}` as keyof PublishMap,+ action.payload+ );}});};diff --git a/apps/builder/app/shared/pubsub/index.ts b/apps/builder/app/shared/pubsub/index.tsindex c7288e65a6..55cdcc3c38 100644--- a/apps/builder/app/shared/pubsub/index.ts+++ b/apps/builder/app/shared/pubsub/index.ts@@ -1,52 +1,20 @@import { atom } from "nanostores";import { createPubsub } from "./create";-/**- * Module augmentation pattern for type-safe command subscriptions.- *- * This pattern allows each module to declare their own commands without- * creating a central list that knows about every command in the application.- *- * Usage:- *- * 1. Declare your command in the module where it's used:- *- * declare module "~/shared/pubsub" {- * interface CommandRegistry {- * myCommand: undefined;- * commandWithPayload: { data: string };- * }- * }- *- * 2. Subscribe to the command with full type safety:- *- * subscribe("command:myCommand", () => {- * // handler receives no payload (undefined)- * });- *- * subscribe("command:commandWithPayload", (payload) => {- * // payload is typed as { data: string }- * });- *- * 3. TypeScript will prevent subscribing to non-existent commands:- *- * subscribe("command:typo", ...) // Type error!- */-+// Allow commands to declare their types// eslint-disable-next-line @typescript-eslint/no-empty-object-type-export interface CommandRegistry {- // Base is empty - modules augment this-}+export interface CommandRegistry {}-// Create a mapped type for command-specific subscriptions-type CommandSubscriptions = {+// Generate namespaced command types from CommandRegistry+type NamespacedCommands = {[K in keyof CommandRegistry as `command:${K & string}`]: CommandRegistry[K];};-export interface PubsubMap extends CommandSubscriptions {+export interface PubsubMap extends NamespacedCommands {command: {source: string;name: string;+ [key: string]: unknown;};}diff --git a/apps/builder/app/shared/share-project/share-project.stories.tsx b/apps/builder/app/shared/share-project/share-project.stories.tsxindex 10921c0e3c..8ded655173 100644--- a/apps/builder/app/shared/share-project/share-project.stories.tsx+++ b/apps/builder/app/shared/share-project/share-project.stories.tsx@@ -6,6 +6,7 @@ import {PopoverTrigger,} from "@webstudio-is/design-system";import { useEffect, useState } from "react";+import { nanoid } from "nanoid";import { type LinkOptions, ShareProject } from "./share-project";export default {@@ -15,7 +16,7 @@ export default {const initialLinks: Array<LinkOptions> = [{- token: crypto.randomUUID(),+ token: nanoid(),name: "View Only",relation: "viewers",canClone: false,@@ -23,7 +24,7 @@ const initialLinks: Array<LinkOptions> = [canPublish: false,},{- token: crypto.randomUUID(),+ token: nanoid(),name: "View and Edit",relation: "editors",canClone: false,@@ -31,7 +32,7 @@ const initialLinks: Array<LinkOptions> = [canPublish: false,},{- token: crypto.randomUUID(),+ token: nanoid(),name: "Build",relation: "builders",canClone: false,@@ -62,7 +63,7 @@ const useShareProject = (setLinks([...links,{- token: crypto.randomUUID(),+ token: nanoid(),name: "Custom Link",relation: "viewers",canClone: false,diff --git a/apps/builder/app/shared/style-source-utils.test.tsx b/apps/builder/app/shared/style-source-utils.test.tsxnew file mode 100644index 0000000000..20f9bfe3a9--- /dev/null+++ b/apps/builder/app/shared/style-source-utils.test.tsx@@ -0,0 +1,3066 @@+import { enableMapSet } from "immer";+import { describe, test, expect } from "vitest";+import type {+ Breakpoint,+ StyleDecl,+ StyleSource,+ StyleSources,+ StyleSourceSelection,+ StyleSourceSelections,+ Styles,+} from "@webstudio-is/sdk";+import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";+import {+ getStyleSourceStylesSignature,+ insertStyleSources,+ insertPortalLocalStyleSources,+ insertLocalStyleSourcesWithNewIds,+ deleteStyleSourceMutable,+ findUnusedTokens,+ deleteStyleSourcesMutable,+ validateAndRenameStyleSource,+ renameStyleSourceMutable,+ deleteLocalStyleSourcesMutable,+ collectStyleSourcesFromInstances,+ findDuplicateTokens,+ findTokenWithMatchingStyles,+ detectTokenConflicts,+} from "./style-source-utils";++enableMapSet();++const getIdValuePair = <T extends { id: string }>(item: T) =>+ [item.id, item] as const;++const toMap = <T extends { id: string }>(list: T[]) =>+ new Map(list.map(getIdValuePair));++const createStyleDecl = (+ styleSourceId: string,+ breakpointId: string,+ property: StyleProperty,+ value: StyleValue | string+): StyleDecl => ({+ styleSourceId,+ breakpointId,+ property,+ value: typeof value === "string" ? { type: "unparsed", value } : value,+});++describe("getStyleSourceStylesSignature", () => {+ test("generates consistent signature for token styles", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styles: StyleDecl[] = [+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("token1", "base", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ];++ const signature = getStyleSourceStylesSignature(+ "token1",+ styles,+ breakpoints,+ new Map()+ );++ expect(signature).toBeTruthy();+ expect(typeof signature).toBe("string");+ });++ test("generates same signature for same styles in different order", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styles1: StyleDecl[] = [+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("token1", "base", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ];+ const styles2: StyleDecl[] = [+ createStyleDecl("token1", "base", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ];++ const signature1 = getStyleSourceStylesSignature(+ "token1",+ styles1,+ breakpoints,+ new Map()+ );+ const signature2 = getStyleSourceStylesSignature(+ "token1",+ styles2,+ breakpoints,+ new Map()+ );++ expect(signature1).toBe(signature2);+ });++ test("generates different signature for different styles", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styles1: StyleDecl[] = [+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ];+ const styles2: StyleDecl[] = [+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ];++ const signature1 = getStyleSourceStylesSignature(+ "token1",+ styles1,+ breakpoints,+ new Map()+ );+ const signature2 = getStyleSourceStylesSignature(+ "token2",+ styles2,+ breakpoints,+ new Map()+ );++ expect(signature1).not.toBe(signature2);+ });++ test("handles different breakpoints correctly", () => {+ const breakpoints = toMap<Breakpoint>([+ { id: "base", label: "base" },+ { id: "tablet", label: "tablet", minWidth: 768 },+ ]);+ const styles1: StyleDecl[] = [+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ];+ const styles2: StyleDecl[] = [+ createStyleDecl("token2", "tablet", "color", {+ type: "keyword",+ value: "red",+ }),+ ];++ const signature1 = getStyleSourceStylesSignature(+ "token1",+ styles1,+ breakpoints,+ new Map()+ );+ const signature2 = getStyleSourceStylesSignature(+ "token2",+ styles2,+ breakpoints,+ new Map()+ );++ expect(signature1).not.toBe(signature2);+ });++ test("handles pseudo states correctly", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styles1: StyleDecl[] = [+ {+ styleSourceId: "token1",+ breakpointId: "base",+ property: "color" as StyleProperty,+ value: { type: "keyword", value: "red" },+ },+ ];+ const styles2: StyleDecl[] = [+ {+ styleSourceId: "token2",+ breakpointId: "base",+ property: "color" as StyleProperty,+ state: ":hover",+ value: { type: "keyword", value: "red" },+ },+ ];++ const signature1 = getStyleSourceStylesSignature(+ "token1",+ styles1,+ breakpoints,+ new Map()+ );+ const signature2 = getStyleSourceStylesSignature(+ "token2",+ styles2,+ breakpoints,+ new Map()+ );++ expect(signature1).not.toBe(signature2);+ });++ test("handles merged breakpoints correctly", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "existing", label: "base" }]);+ const mergedBreakpointIds = new Map([["fragment", "existing"]]);+ const styles1: StyleDecl[] = [+ createStyleDecl("token1", "existing", "color", {+ type: "keyword",+ value: "red",+ }),+ ];+ const styles2: StyleDecl[] = [+ createStyleDecl("token2", "fragment", "color", {+ type: "keyword",+ value: "red",+ }),+ ];++ const signature1 = getStyleSourceStylesSignature(+ "token1",+ styles1,+ breakpoints,+ new Map()+ );+ const signature2 = getStyleSourceStylesSignature(+ "token2",+ styles2,+ breakpoints,+ mergedBreakpointIds+ );++ // Should be the same because fragment breakpoint maps to existing+ expect(signature1).toBe(signature2);+ });++ test("handles complex multi-property multi-breakpoint styles", () => {+ const breakpoints = toMap<Breakpoint>([+ { id: "base", label: "base" },+ { id: "tablet", label: "tablet", minWidth: 768 },+ { id: "desktop", label: "desktop", minWidth: 1200 },+ ]);+ const styles1: StyleDecl[] = [+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("token1", "tablet", "color", {+ type: "keyword",+ value: "blue",+ }),+ createStyleDecl("token1", "desktop", "fontSize", {+ type: "unit",+ value: 20,+ unit: "px",+ }),+ ];+ // Same styles but in different order+ const styles2: StyleDecl[] = [+ createStyleDecl("token2", "desktop", "fontSize", {+ type: "unit",+ value: 20,+ unit: "px",+ }),+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("token2", "tablet", "color", {+ type: "keyword",+ value: "blue",+ }),+ ];++ const signature1 = getStyleSourceStylesSignature(+ "token1",+ styles1,+ breakpoints,+ new Map()+ );+ const signature2 = getStyleSourceStylesSignature(+ "token2",+ styles2,+ breakpoints,+ new Map()+ );++ expect(signature1).toBe(signature2);+ });+});++describe("insertStyleSources", () => {+ // Case 2: Same styles AND same name -> reuse existing token+ test("token with same styles and same name reuses existing token", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const existingStyleSources = toMap<StyleSource>([+ { id: "existingToken", type: "token", name: "primaryColor" },+ ]);+ const existingStyles = new Map<string, StyleDecl>([+ [+ "existingToken:base:color:",+ createStyleDecl("existingToken", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ [+ "existingToken:base:fontSize:",+ createStyleDecl("existingToken", "base", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ],+ ]);++ const fragmentStyleSources: StyleSource[] = [+ { id: "newToken", type: "token", name: "primaryColor" },+ ];+ const fragmentStyles: StyleDecl[] = [+ createStyleDecl("newToken", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("newToken", "base", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ];++ const { styleSourceIdMap, updatedStyleSources } = insertStyleSources({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources,+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ // Should reuse existing token, not create a new one+ expect(Array.from(updatedStyleSources.values())).toEqual([+ { id: "existingToken", type: "token", name: "primaryColor" },+ ]);+ // Should map newToken -> existingToken+ expect(styleSourceIdMap.get("newToken")).toBe("existingToken");+ });++ // Case 3: Same styles but different name -> insert new token with original name+ test("token with same styles but different name inserts new token", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const existingStyleSources = toMap<StyleSource>([+ { id: "token1", type: "token", name: "primaryColor" },+ ]);+ const existingStyles = new Map<string, StyleDecl>([+ [+ "token1:base:color:",+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ ]);++ const fragmentStyleSources: StyleSource[] = [+ { id: "token2", type: "token", name: "accentColor" },+ ];+ const fragmentStyles: StyleDecl[] = [+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ];++ const { styleSourceIds, styleSourceIdMap, updatedStyleSources } =+ insertStyleSources({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources,+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ // Should insert new token with its original name+ const tokens = Array.from(updatedStyleSources.values());+ expect(tokens).toHaveLength(2);+ expect(tokens[0]).toEqual({+ id: "token1",+ type: "token",+ name: "primaryColor",+ });+ expect(tokens[1]).toMatchObject({ type: "token", name: "accentColor" });+ expect(tokens[1].id).not.toBe("token2"); // Should have new ID+ expect(styleSourceIds.has("token2")).toBe(true);+ expect(styleSourceIdMap.get("token2")).toBe(tokens[1].id);+ });++ // Case 4: Different styles but same name -> add counter suffix+ test("token with different styles but same name adds counter suffix", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const existingStyleSources = toMap<StyleSource>([+ { id: "token1", type: "token", name: "myToken" },+ ]);+ const existingStyles = new Map<string, StyleDecl>([+ [+ "token1:base:color:",+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ],+ ]);++ const fragmentStyleSources: StyleSource[] = [+ { id: "token2", type: "token", name: "myToken" },+ ];+ const fragmentStyles: StyleDecl[] = [+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ];++ const { styleSourceIds, styleSourceIdMap, updatedStyleSources } =+ insertStyleSources({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources,+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ // Should add counter suffix to the new token+ const tokens = Array.from(updatedStyleSources.values());+ expect(tokens).toHaveLength(2);+ expect(tokens[0]).toEqual({ id: "token1", type: "token", name: "myToken" });+ expect(tokens[1]).toMatchObject({ type: "token", name: "myToken-1" });+ expect(tokens[1].id).not.toBe("token2"); // Should have new ID+ expect(styleSourceIds.has("token2")).toBe(true);+ expect(styleSourceIdMap.get("token2")).toBe(tokens[1].id);+ });++ // Case 4b: Multiple counter suffixes+ test("token with name conflict increments counter correctly", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const existingStyleSources = toMap<StyleSource>([+ { id: "token1", type: "token", name: "myToken" },+ { id: "token2", type: "token", name: "myToken-1" },+ { id: "token3", type: "token", name: "myToken-2" },+ ]);+ const existingStyles = new Map<string, StyleDecl>([+ [+ "token1:base:color:",+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ],+ [+ "token2:base:color:",+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "green",+ }),+ ],+ [+ "token3:base:color:",+ createStyleDecl("token3", "base", "color", {+ type: "keyword",+ value: "yellow",+ }),+ ],+ ]);++ const fragmentStyleSources: StyleSource[] = [+ { id: "token4", type: "token", name: "myToken" },+ ];+ const fragmentStyles: StyleDecl[] = [+ createStyleDecl("token4", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ];++ const { updatedStyleSources } = insertStyleSources({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources,+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ // Should use counter 3+ const tokens = Array.from(updatedStyleSources.values());+ expect(tokens).toHaveLength(4);+ expect(tokens[0]).toEqual({ id: "token1", type: "token", name: "myToken" });+ expect(tokens[1]).toEqual({+ id: "token2",+ type: "token",+ name: "myToken-1",+ });+ expect(tokens[2]).toEqual({+ id: "token3",+ type: "token",+ name: "myToken-2",+ });+ expect(tokens[3]).toMatchObject({ type: "token", name: "myToken-3" });+ expect(tokens[3].id).not.toBe("token4"); // Should have new ID+ });++ // Case 6: Different styles and different name -> insert as-is+ test("token with different styles and different name inserts normally", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const existingStyleSources = toMap<StyleSource>([+ { id: "token1", type: "token", name: "primaryColor" },+ ]);+ const existingStyles = new Map<string, StyleDecl>([+ [+ "token1:base:color:",+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ],+ ]);++ const fragmentStyleSources: StyleSource[] = [+ { id: "token2", type: "token", name: "secondaryColor" },+ ];+ const fragmentStyles: StyleDecl[] = [+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ];++ const { styleSourceIds, styleSourceIdMap, updatedStyleSources } =+ insertStyleSources({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources,+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ // Should insert new token normally+ const tokens = Array.from(updatedStyleSources.values());+ expect(tokens).toHaveLength(2);+ expect(tokens[0]).toEqual({+ id: "token1",+ type: "token",+ name: "primaryColor",+ });+ expect(tokens[1]).toMatchObject({ type: "token", name: "secondaryColor" });+ expect(tokens[1].id).not.toBe("token2"); // Should have new ID+ expect(styleSourceIds.has("token2")).toBe(true);+ expect(styleSourceIdMap.get("token2")).toBe(tokens[1].id);+ });++ // Case 3 safeguard: Same styles but different name gets suffix when name conflicts+ test("token with same styles but different name adds suffix when name already exists", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const existingStyleSources = toMap<StyleSource>([+ { id: "token1", type: "token", name: "primaryColor" },+ { id: "token2", type: "token", name: "accentColor" }, // This name is taken+ ]);+ const existingStyles = new Map<string, StyleDecl>([+ [+ "token1:base:color:",+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ [+ "token2:base:fontSize:",+ createStyleDecl("token2", "base", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ],+ ]);++ const fragmentStyleSources: StyleSource[] = [+ { id: "token3", type: "token", name: "accentColor" },+ ];+ const fragmentStyles: StyleDecl[] = [+ createStyleDecl("token3", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ];++ const { updatedStyleSources } = insertStyleSources({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources,+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ // Should add counter suffix to prevent duplicate name+ const tokens = Array.from(updatedStyleSources.values());+ expect(tokens).toHaveLength(3);+ expect(tokens[0]).toEqual({+ id: "token1",+ type: "token",+ name: "primaryColor",+ });+ expect(tokens[1]).toEqual({+ id: "token2",+ type: "token",+ name: "accentColor",+ });+ expect(tokens[2]).toMatchObject({ type: "token", name: "accentColor-1" });+ expect(tokens[2].id).not.toBe("token3"); // Should have new ID+ });++ // Case 6 safeguard: Different styles and different name gets suffix when name conflicts+ test("token with different styles and name adds suffix when name already exists", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const existingStyleSources = toMap<StyleSource>([+ { id: "token1", type: "token", name: "primaryColor" },+ { id: "token2", type: "token", name: "secondaryColor" }, // This name is taken+ ]);+ const existingStyles = new Map<string, StyleDecl>([+ [+ "token1:base:color:",+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ],+ [+ "token2:base:color:",+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "green",+ }),+ ],+ ]);++ const fragmentStyleSources: StyleSource[] = [+ { id: "token3", type: "token", name: "secondaryColor" },+ ];+ const fragmentStyles: StyleDecl[] = [+ createStyleDecl("token3", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ];++ const { updatedStyleSources } = insertStyleSources({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources,+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ // Should add counter suffix to prevent duplicate name+ const tokens = Array.from(updatedStyleSources.values());+ expect(tokens).toHaveLength(3);+ expect(tokens[0]).toEqual({+ id: "token1",+ type: "token",+ name: "primaryColor",+ });+ expect(tokens[1]).toEqual({+ id: "token2",+ type: "token",+ name: "secondaryColor",+ });+ expect(tokens[2]).toMatchObject({+ type: "token",+ name: "secondaryColor-1",+ });+ expect(tokens[2].id).not.toBe("token3"); // Should have new ID+ });++ // Test that existing token with same styles but different name stays untouched+ test("existing token with matching styles but different name stays untouched when inserting new token", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const existingStyleSources = toMap<StyleSource>([+ { id: "existingToken", type: "token", name: "primaryColor" },+ ]);+ const existingStyles = new Map<string, StyleDecl>([+ [+ "existingToken:base:color:",+ createStyleDecl("existingToken", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ [+ "existingToken:base:fontSize:",+ createStyleDecl("existingToken", "base", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ],+ ]);++ const fragmentStyleSources: StyleSource[] = [+ { id: "newToken", type: "token", name: "accentColor" },+ ];+ const fragmentStyles: StyleDecl[] = [+ createStyleDecl("newToken", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("newToken", "base", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ];++ const { updatedStyleSources } = insertStyleSources({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources,+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ // Should insert new token with its own name, leaving existing one untouched+ const tokens = Array.from(updatedStyleSources.values());+ expect(tokens).toHaveLength(2);+ expect(tokens[0]).toEqual({+ id: "existingToken",+ type: "token",+ name: "primaryColor",+ });+ expect(tokens[1]).toMatchObject({ type: "token", name: "accentColor" });+ expect(tokens[1].id).not.toBe("newToken"); // Should have new ID+ });++ // Critical test: inserting base name when suffixed version exists+ test("inserting token 'bbb' when 'bbb-1' with same styles exists inserts both tokens", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const existingStyleSources = toMap<StyleSource>([+ { id: "existingToken", type: "token", name: "bbb-1" },+ ]);+ const existingStyles = new Map<string, StyleDecl>([+ [+ "existingToken:base:color:",+ createStyleDecl("existingToken", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ],+ ]);++ const fragmentStyleSources: StyleSource[] = [+ { id: "newToken", type: "token", name: "bbb" },+ ];+ const fragmentStyles: StyleDecl[] = [+ createStyleDecl("newToken", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ];++ const { styleSourceIdMap, updatedStyleSources } = insertStyleSources({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources,+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ // Both tokens should exist+ const tokens = Array.from(updatedStyleSources.values());+ expect(tokens).toHaveLength(2);+ expect(tokens[0]).toEqual({+ id: "existingToken",+ type: "token",+ name: "bbb-1",+ });+ expect(tokens[1]).toMatchObject({ type: "token", name: "bbb" }); // Different name, so inserted as-is+ expect(tokens[1].id).not.toBe("newToken"); // Should have new ID+ expect(styleSourceIdMap.get("newToken")).toBe(tokens[1].id);+ });++ // Test merge conflict resolution+ test('token with different styles and same name merges when conflictResolution="merge"', () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const existingStyleSources = toMap<StyleSource>([+ { id: "existingToken", type: "token", name: "primaryColor" },+ ]);+ const existingStyles = new Map<string, StyleDecl>([+ [+ "existingToken:base:color:",+ createStyleDecl("existingToken", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ],+ [+ "existingToken:base:fontSize:",+ createStyleDecl("existingToken", "base", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ],+ ]);++ const fragmentStyleSources: StyleSource[] = [+ { id: "newToken", type: "token", name: "primaryColor" },+ ];+ const fragmentStyles: StyleDecl[] = [+ createStyleDecl("newToken", "base", "color", {+ type: "keyword",+ value: "red", // Different color - should override+ }),+ createStyleDecl("newToken", "base", "fontWeight", {+ type: "keyword",+ value: "bold", // Additional property - should be added+ }),+ ];++ const { styleSourceIds, styleSourceIdMap, updatedStyleSources } =+ insertStyleSources({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources,+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ conflictResolution: "merge",+ });++ // Should keep existing token (no new token created)+ const tokens = Array.from(updatedStyleSources.values());+ expect(tokens).toHaveLength(1);+ expect(tokens[0]).toEqual({+ id: "existingToken",+ type: "token",+ name: "primaryColor",+ });++ // Should map the fragment token to the existing token+ expect(styleSourceIdMap.get("newToken")).toBe("existingToken");++ // Should mark the fragment token for style insertion+ // This tells insertWebstudioFragment to insert these styles, which will:+ // - Override existing "color" from blue to red+ // - Keep existing "fontSize" at 16px+ // - Add new "fontWeight" bold+ expect(styleSourceIds.has("newToken")).toBe(true);+ });+});++// Tests for insertPortalLocalStyleSources++describe("insertPortalLocalStyleSources", () => {+ test("inserts local style sources and styles for portal content", () => {+ const fragmentStyleSources: StyleSource[] = [+ { type: "local", id: "local1" },+ { type: "token", id: "token1", name: "myToken" },+ ];+ const fragmentStyleSourceSelections: StyleSourceSelection[] = [+ { instanceId: "instance1", values: ["local1", "token1"] },+ { instanceId: "instance2", values: ["local1"] },+ ];+ const fragmentStyles: StyleDecl[] = [+ {+ breakpointId: "bp1",+ styleSourceId: "local1",+ property: "width",+ value: { type: "unit", value: 100, unit: "px" },+ },+ {+ breakpointId: "bp2",+ styleSourceId: "local1",+ property: "height",+ value: { type: "unit", value: 50, unit: "px" },+ },+ ];+ const instanceIds = new Set(["instance1"]);+ const styleSources: StyleSources = new Map();+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map();+ const mergedBreakpointIds = new Map([["bp2", "bp2-merged"]]);++ insertPortalLocalStyleSources({+ fragmentStyleSources,+ fragmentStyleSourceSelections,+ fragmentStyles,+ instanceIds,+ styleSources,+ styleSourceSelections,+ styles,+ mergedBreakpointIds,+ });++ // Should only insert for instance1 (in instanceIds set)+ expect(styleSourceSelections.has("instance1")).toBe(true);+ expect(styleSourceSelections.has("instance2")).toBe(false);++ // Should insert local style source+ expect(styleSources.get("local1")).toEqual({ type: "local", id: "local1" });++ // Should insert styles with merged breakpoint IDs+ expect(styles.size).toBe(2);+ const stylesArray = Array.from(styles.values());+ expect(stylesArray).toContainEqual({+ breakpointId: "bp1",+ styleSourceId: "local1",+ property: "width",+ value: { type: "unit", value: 100, unit: "px" },+ });+ expect(stylesArray).toContainEqual({+ breakpointId: "bp2-merged",+ styleSourceId: "local1",+ property: "height",+ value: { type: "unit", value: 50, unit: "px" },+ });+ });++ test("preserves original IDs for portal content", () => {+ const fragmentStyleSources: StyleSource[] = [+ { type: "local", id: "portal-local-123" },+ ];+ const fragmentStyleSourceSelections: StyleSourceSelection[] = [+ { instanceId: "portal-instance", values: ["portal-local-123"] },+ ];+ const fragmentStyles: StyleDecl[] = [+ {+ breakpointId: "bp1",+ styleSourceId: "portal-local-123",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ];+ const instanceIds = new Set(["portal-instance"]);+ const styleSources: StyleSources = new Map();+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map();+ const mergedBreakpointIds = new Map();++ insertPortalLocalStyleSources({+ fragmentStyleSources,+ fragmentStyleSourceSelections,+ fragmentStyles,+ instanceIds,+ styleSources,+ styleSourceSelections,+ styles,+ mergedBreakpointIds,+ });++ // IDs should be preserved exactly+ expect(styleSources.get("portal-local-123")).toEqual({+ type: "local",+ id: "portal-local-123",+ });+ expect(styleSourceSelections.get("portal-instance")).toEqual({+ instanceId: "portal-instance",+ values: ["portal-local-123"],+ });+ });++ test("skips instances not in instanceIds set", () => {+ const fragmentStyleSources: StyleSource[] = [+ { type: "local", id: "local1" },+ ];+ const fragmentStyleSourceSelections: StyleSourceSelection[] = [+ { instanceId: "included", values: ["local1"] },+ { instanceId: "excluded", values: ["local1"] },+ ];+ const fragmentStyles: StyleDecl[] = [+ {+ breakpointId: "bp1",+ styleSourceId: "local1",+ property: "width",+ value: { type: "unit", value: 100, unit: "px" },+ },+ ];+ const instanceIds = new Set(["included"]);+ const styleSources: StyleSources = new Map();+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map();+ const mergedBreakpointIds = new Map();++ insertPortalLocalStyleSources({+ fragmentStyleSources,+ fragmentStyleSourceSelections,+ fragmentStyles,+ instanceIds,+ styleSources,+ styleSourceSelections,+ styles,+ mergedBreakpointIds,+ });++ expect(styleSourceSelections.has("included")).toBe(true);+ expect(styleSourceSelections.has("excluded")).toBe(false);+ });+});++// Tests for insertLocalStyleSourcesWithNewIds++describe("insertLocalStyleSourcesWithNewIds", () => {+ test("generates new IDs for local style sources", () => {+ const fragmentStyleSources: StyleSource[] = [+ { type: "local", id: "old-local-1" },+ ];+ const fragmentStyleSourceSelections: StyleSourceSelection[] = [+ { instanceId: "old-instance", values: ["old-local-1"] },+ ];+ const fragmentStyles: StyleDecl[] = [+ {+ breakpointId: "bp1",+ styleSourceId: "old-local-1",+ property: "marginTop" as StyleProperty,+ value: { type: "unit", value: 10, unit: "px" },+ },+ ];+ const fragmentInstanceIds = new Set(["old-instance"]);+ const newInstanceIds = new Map([["old-instance", "new-instance"]]);+ const styleSourceIdMap = new Map();+ const styleSources: StyleSources = new Map();+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map();+ const mergedBreakpointIds = new Map();++ insertLocalStyleSourcesWithNewIds({+ fragmentStyleSources,+ fragmentStyleSourceSelections,+ fragmentStyles,+ fragmentInstanceIds,+ newInstanceIds,+ styleSourceIdMap,+ styleSources,+ styleSourceSelections,+ styles,+ mergedBreakpointIds,+ });++ // Should create new local style source with different ID+ expect(styleSources.size).toBe(1);+ const newLocalStyleSource = Array.from(styleSources.values())[0];+ expect(newLocalStyleSource.type).toBe("local");+ expect(newLocalStyleSource.id).not.toBe("old-local-1");++ // Should map to new instance ID+ expect(styleSourceSelections.has("new-instance")).toBe(true);+ expect(styleSourceSelections.has("old-instance")).toBe(false);++ // Should create style with new style source ID+ expect(styles.size).toBe(1);+ const newStyle = Array.from(styles.values())[0];+ expect(newStyle.styleSourceId).toBe(newLocalStyleSource.id);+ });++ test("merges local styles into existing ROOT_INSTANCE_ID local source", async () => {+ const { ROOT_INSTANCE_ID } = await import("@webstudio-is/sdk");++ const fragmentStyleSources: StyleSource[] = [+ { type: "local", id: "fragment-local" },+ ];+ const fragmentStyleSourceSelections: StyleSourceSelection[] = [+ { instanceId: ROOT_INSTANCE_ID, values: ["fragment-local"] },+ ];+ const fragmentStyles: StyleDecl[] = [+ {+ breakpointId: "bp1",+ styleSourceId: "fragment-local",+ property: "fontFamily",+ value: { type: "fontFamily", value: ["Arial"] },+ },+ ];+ const fragmentInstanceIds = new Set([ROOT_INSTANCE_ID]);+ const newInstanceIds = new Map();+ const styleSourceIdMap = new Map();++ // Existing ROOT local style source+ const existingRootLocal: StyleSource = {+ type: "local",+ id: "existing-root-local",+ };+ const styleSources: StyleSources = new Map([+ ["existing-root-local", existingRootLocal],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map([+ [+ ROOT_INSTANCE_ID,+ { instanceId: ROOT_INSTANCE_ID, values: ["existing-root-local"] },+ ],+ ]);+ const styles: Styles = new Map();+ const mergedBreakpointIds = new Map();++ insertLocalStyleSourcesWithNewIds({+ fragmentStyleSources,+ fragmentStyleSourceSelections,+ fragmentStyles,+ fragmentInstanceIds,+ newInstanceIds,+ styleSourceIdMap,+ styleSources,+ styleSourceSelections,+ styles,+ mergedBreakpointIds,+ });++ // Should reuse existing ROOT local style source, not create new one+ expect(styleSources.size).toBe(1);+ expect(styleSources.get("existing-root-local")).toBe(existingRootLocal);++ // Style should use existing local style source ID+ expect(styles.size).toBe(1);+ const style = Array.from(styles.values())[0];+ expect(style.styleSourceId).toBe("existing-root-local");+ });++ test("creates new local source for non-ROOT instances even if local exists", () => {+ const fragmentStyleSources: StyleSource[] = [+ { type: "local", id: "fragment-local" },+ ];+ const fragmentStyleSourceSelections: StyleSourceSelection[] = [+ { instanceId: "regular-instance", values: ["fragment-local"] },+ ];+ const fragmentStyles: StyleDecl[] = [+ {+ breakpointId: "bp1",+ styleSourceId: "fragment-local",+ property: "paddingTop" as StyleProperty,+ value: { type: "unit", value: 20, unit: "px" },+ },+ ];+ const fragmentInstanceIds = new Set(["regular-instance"]);+ const newInstanceIds = new Map();+ const styleSourceIdMap = new Map();++ // Existing local style source for this instance+ const existingLocal: StyleSource = { type: "local", id: "existing-local" };+ const styleSources: StyleSources = new Map([+ ["existing-local", existingLocal],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map([+ [+ "regular-instance",+ { instanceId: "regular-instance", values: ["existing-local"] },+ ],+ ]);+ const styles: Styles = new Map();+ const mergedBreakpointIds = new Map();++ insertLocalStyleSourcesWithNewIds({+ fragmentStyleSources,+ fragmentStyleSourceSelections,+ fragmentStyles,+ fragmentInstanceIds,+ newInstanceIds,+ styleSourceIdMap,+ styleSources,+ styleSourceSelections,+ styles,+ mergedBreakpointIds,+ });++ // Should create NEW local style source (not merge)+ expect(styleSources.size).toBe(2);+ const newLocalId = Array.from(styleSources.keys()).find(+ (id) => id !== "existing-local"+ );+ expect(newLocalId).toBeDefined();++ // Style should use new local style source ID+ const style = Array.from(styles.values())[0];+ expect(style.styleSourceId).toBe(newLocalId);+ });++ test("handles token remapping in styleSourceIdMap", () => {+ const fragmentStyleSources: StyleSource[] = [+ { type: "local", id: "local1" },+ { type: "token", id: "old-token", name: "oldToken" },+ ];+ const fragmentStyleSourceSelections: StyleSourceSelection[] = [+ { instanceId: "instance1", values: ["local1", "old-token"] },+ ];+ const fragmentStyles: StyleDecl[] = [+ {+ breakpointId: "bp1",+ styleSourceId: "local1",+ property: "color",+ value: { type: "keyword", value: "blue" },+ },+ ];+ const fragmentInstanceIds = new Set(["instance1"]);+ const newInstanceIds = new Map();++ // Token was already mapped to existing token+ const styleSourceIdMap = new Map([["old-token", "existing-token"]]);++ const styleSources: StyleSources = new Map();+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map();+ const mergedBreakpointIds = new Map();++ insertLocalStyleSourcesWithNewIds({+ fragmentStyleSources,+ fragmentStyleSourceSelections,+ fragmentStyles,+ fragmentInstanceIds,+ newInstanceIds,+ styleSourceIdMap,+ styleSources,+ styleSourceSelections,+ styles,+ mergedBreakpointIds,+ });++ // styleSourceSelection should reference the mapped token ID+ const selection = styleSourceSelections.get("instance1");+ expect(selection?.values).toContain("existing-token");+ expect(selection?.values).not.toContain("old-token");+ });++ test("applies merged breakpoint IDs to styles", () => {+ const fragmentStyleSources: StyleSource[] = [+ { type: "local", id: "local1" },+ ];+ const fragmentStyleSourceSelections: StyleSourceSelection[] = [+ { instanceId: "instance1", values: ["local1"] },+ ];+ const fragmentStyles: StyleDecl[] = [+ {+ breakpointId: "old-bp",+ styleSourceId: "local1",+ property: "display",+ value: { type: "keyword", value: "flex" },+ },+ ];+ const fragmentInstanceIds = new Set(["instance1"]);+ const newInstanceIds = new Map();+ const styleSourceIdMap = new Map();+ const styleSources: StyleSources = new Map();+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map();+ const mergedBreakpointIds = new Map([["old-bp", "merged-bp"]]);++ insertLocalStyleSourcesWithNewIds({+ fragmentStyleSources,+ fragmentStyleSourceSelections,+ fragmentStyles,+ fragmentInstanceIds,+ newInstanceIds,+ styleSourceIdMap,+ styleSources,+ styleSourceSelections,+ styles,+ mergedBreakpointIds,+ });++ // Style should use merged breakpoint ID+ const style = Array.from(styles.values())[0];+ expect(style.breakpointId).toBe("merged-bp");+ });+});++describe("deleteStyleSourceMutable", () => {+ test("deletes style source from styleSources map", () => {+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Primary Color" } as StyleSource,+ ],+ [+ "token2",+ { type: "token", id: "token2", name: "Secondary Color" } as StyleSource,+ ],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map();++ deleteStyleSourceMutable({+ styleSourceId: "token1",+ styleSources,+ styleSourceSelections,+ styles,+ });++ expect(styleSources.has("token1")).toBe(false);+ expect(styleSources.has("token2")).toBe(true);+ });++ test("removes style source from style source selections", () => {+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Primary Color" } as StyleSource,+ ],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map([+ ["instance1", { instanceId: "instance1", values: ["token1", "local1"] }],+ ["instance2", { instanceId: "instance2", values: ["token1"] }],+ ["instance3", { instanceId: "instance3", values: ["local2"] }],+ ]);+ const styles: Styles = new Map();++ deleteStyleSourceMutable({+ styleSourceId: "token1",+ styleSources,+ styleSourceSelections,+ styles,+ });++ const selection1 = styleSourceSelections.get("instance1");+ expect(selection1?.values).toEqual(["local1"]);++ const selection2 = styleSourceSelections.get("instance2");+ expect(selection2?.values).toEqual([]);++ const selection3 = styleSourceSelections.get("instance3");+ expect(selection3?.values).toEqual(["local2"]);+ });++ test("deletes all styles associated with the style source", () => {+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Primary Color" } as StyleSource,+ ],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map([+ [+ "token1:base:color",+ {+ breakpointId: "base",+ styleSourceId: "token1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ [+ "token1:base:fontSize",+ {+ breakpointId: "base",+ styleSourceId: "token1",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ },+ ],+ [+ "local1:base:display",+ {+ breakpointId: "base",+ styleSourceId: "local1",+ property: "display",+ value: { type: "keyword", value: "flex" },+ },+ ],+ ]);++ deleteStyleSourceMutable({+ styleSourceId: "token1",+ styleSources,+ styleSourceSelections,+ styles,+ });++ expect(styles.has("token1:base:color")).toBe(false);+ expect(styles.has("token1:base:fontSize")).toBe(false);+ expect(styles.has("local1:base:display")).toBe(true);+ expect(styles.size).toBe(1);+ });++ test("handles deletion of non-existent style source gracefully", () => {+ const styleSources: StyleSources = new Map();+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map();++ expect(() => {+ deleteStyleSourceMutable({+ styleSourceId: "non-existent",+ styleSources,+ styleSourceSelections,+ styles,+ });+ }).not.toThrow();+ });+});++describe("findUnusedTokens", () => {+ test("identifies tokens with no usages", () => {+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Used Token" } as StyleSource,+ ],+ [+ "token2",+ { type: "token", id: "token2", name: "Unused Token" } as StyleSource,+ ],+ [+ "token3",+ { type: "token", id: "token3", name: "Another Unused" } as StyleSource,+ ],+ ["local1", { type: "local", id: "local1" } as StyleSource],+ ]);+ const styleSourceUsages = new Map<string, Set<string>>([+ ["token1", new Set(["instance1", "instance2"])],+ ["token2", new Set()],+ ["local1", new Set(["instance3"])],+ ]);++ const unusedTokens = findUnusedTokens({ styleSources, styleSourceUsages });++ expect(unusedTokens).toContain("token2");+ expect(unusedTokens).toContain("token3");+ expect(unusedTokens).not.toContain("token1");+ expect(unusedTokens).not.toContain("local1");+ expect(unusedTokens.length).toBe(2);+ });++ test("returns empty array when all tokens are used", () => {+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Used Token 1" } as StyleSource,+ ],+ [+ "token2",+ { type: "token", id: "token2", name: "Used Token 2" } as StyleSource,+ ],+ ]);+ const styleSourceUsages = new Map([+ ["token1", new Set(["instance1"])],+ ["token2", new Set(["instance2"])],+ ]);++ const unusedTokens = findUnusedTokens({ styleSources, styleSourceUsages });++ expect(unusedTokens).toEqual([]);+ });++ test("ignores local style sources", () => {+ const styleSources: StyleSources = new Map([+ ["local1", { type: "local", id: "local1" } as StyleSource],+ ["local2", { type: "local", id: "local2" } as StyleSource],+ ]);+ const styleSourceUsages = new Map();++ const unusedTokens = findUnusedTokens({ styleSources, styleSourceUsages });++ expect(unusedTokens).toEqual([]);+ });++ test("treats undefined usages as unused", () => {+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Unused Token" } as StyleSource,+ ],+ ]);+ const styleSourceUsages = new Map();++ const unusedTokens = findUnusedTokens({ styleSources, styleSourceUsages });++ expect(unusedTokens).toEqual(["token1"]);+ });+});++describe("deleteStyleSourcesMutable", () => {+ test("deletes multiple style sources", () => {+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Token 1" } as StyleSource,+ ],+ [+ "token2",+ { type: "token", id: "token2", name: "Token 2" } as StyleSource,+ ],+ [+ "token3",+ { type: "token", id: "token3", name: "Token 3" } as StyleSource,+ ],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map();++ deleteStyleSourcesMutable({+ styleSourceIds: ["token1", "token3"],+ styleSources,+ styleSourceSelections,+ styles,+ });++ expect(styleSources.has("token1")).toBe(false);+ expect(styleSources.has("token2")).toBe(true);+ expect(styleSources.has("token3")).toBe(false);+ });++ test("removes deleted style sources from all selections", () => {+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Token 1" } as StyleSource,+ ],+ [+ "token2",+ { type: "token", id: "token2", name: "Token 2" } as StyleSource,+ ],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map([+ [+ "instance1",+ { instanceId: "instance1", values: ["token1", "token2", "local1"] },+ ],+ ["instance2", { instanceId: "instance2", values: ["token1"] }],+ ]);+ const styles: Styles = new Map();++ deleteStyleSourcesMutable({+ styleSourceIds: ["token1", "token2"],+ styleSources,+ styleSourceSelections,+ styles,+ });++ const selection1 = styleSourceSelections.get("instance1");+ expect(selection1?.values).toEqual(["local1"]);++ const selection2 = styleSourceSelections.get("instance2");+ expect(selection2?.values).toEqual([]);+ });++ test("deletes all associated styles", () => {+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Token 1" } as StyleSource,+ ],+ [+ "token2",+ { type: "token", id: "token2", name: "Token 2" } as StyleSource,+ ],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map([+ [+ "token1:base:color",+ {+ breakpointId: "base",+ styleSourceId: "token1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ [+ "token2:base:fontSize",+ {+ breakpointId: "base",+ styleSourceId: "token2",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ },+ ],+ [+ "local1:base:display",+ {+ breakpointId: "base",+ styleSourceId: "local1",+ property: "display",+ value: { type: "keyword", value: "flex" },+ },+ ],+ ]);++ deleteStyleSourcesMutable({+ styleSourceIds: ["token1", "token2"],+ styleSources,+ styleSourceSelections,+ styles,+ });++ expect(styles.has("token1:base:color")).toBe(false);+ expect(styles.has("token2:base:fontSize")).toBe(false);+ expect(styles.has("local1:base:display")).toBe(true);+ expect(styles.size).toBe(1);+ });++ test("handles empty array of style source IDs", () => {+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Token 1" } as StyleSource,+ ],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map();++ deleteStyleSourcesMutable({+ styleSourceIds: [],+ styleSources,+ styleSourceSelections,+ styles,+ });++ expect(styleSources.has("token1")).toBe(true);+ });+});++describe("validateAndRenameStyleSource", () => {+ test("returns undefined for valid rename", () => {+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Old Name" } as StyleSource,+ ],+ [+ "token2",+ { type: "token", id: "token2", name: "Other Token" } as StyleSource,+ ],+ ]);++ const error = validateAndRenameStyleSource({+ id: "token1",+ name: "New Name",+ styleSources,+ });++ expect(error).toBeUndefined();+ });++ test("returns minlength error for empty name", () => {+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Old Name" } as StyleSource,+ ],+ ]);++ const error = validateAndRenameStyleSource({+ id: "token1",+ name: "",+ styleSources,+ });++ expect(error).toEqual({ type: "minlength", id: "token1" });+ });++ test("returns minlength error for whitespace-only name", () => {+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Old Name" } as StyleSource,+ ],+ ]);++ const error = validateAndRenameStyleSource({+ id: "token1",+ name: " ",+ styleSources,+ });++ expect(error).toEqual({ type: "minlength", id: "token1" });+ });++ test("returns duplicate error when name already exists", () => {+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Primary Color" } as StyleSource,+ ],+ [+ "token2",+ {+ type: "token",+ id: "token2",+ name: "Secondary Color",+ } as StyleSource,+ ],+ ]);++ const error = validateAndRenameStyleSource({+ id: "token1",+ name: "Secondary Color",+ styleSources,+ });++ expect(error).toEqual({ type: "duplicate", id: "token1" });+ });++ test("allows renaming to same name (no change)", () => {+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Primary Color" } as StyleSource,+ ],+ ]);++ const error = validateAndRenameStyleSource({+ id: "token1",+ name: "Primary Color",+ styleSources,+ });++ expect(error).toBeUndefined();+ });++ test("ignores local style sources when checking duplicates", () => {+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Primary Color" } as StyleSource,+ ],+ ["local1", { type: "local", id: "local1" } as StyleSource],+ ]);++ const error = validateAndRenameStyleSource({+ id: "token1",+ name: "Some Name",+ styleSources,+ });++ expect(error).toBeUndefined();+ });+});++describe("renameStyleSourceMutable", () => {+ test("renames a token style source", () => {+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Old Name" } as StyleSource,+ ],+ ]);++ renameStyleSourceMutable({+ id: "token1",+ name: "New Name",+ styleSources,+ });++ const styleSource = styleSources.get("token1");+ expect(styleSource?.type).toBe("token");+ if (styleSource?.type === "token") {+ expect(styleSource.name).toBe("New Name");+ }+ });++ test("does not rename local style source", () => {+ const styleSources: StyleSources = new Map([+ ["local1", { type: "local", id: "local1" } as StyleSource],+ ]);++ renameStyleSourceMutable({+ id: "local1",+ name: "New Name",+ styleSources,+ });++ const styleSource = styleSources.get("local1");+ expect(styleSource?.type).toBe("local");+ });++ test("handles non-existent style source gracefully", () => {+ const styleSources: StyleSources = new Map();++ expect(() => {+ renameStyleSourceMutable({+ id: "non-existent",+ name: "New Name",+ styleSources,+ });+ }).not.toThrow();+ });++ test("preserves other properties of the style source", () => {+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Old Name" } as StyleSource,+ ],+ ]);++ renameStyleSourceMutable({+ id: "token1",+ name: "New Name",+ styleSources,+ });++ const styleSource = styleSources.get("token1");+ expect(styleSource?.id).toBe("token1");+ expect(styleSource?.type).toBe("token");+ });+});++describe("deleteLocalStyleSourcesMutable", () => {+ test("deletes local style sources from styleSources map", () => {+ const localStyleSourceIds = new Set(["local1", "local2"]);+ const styleSources: StyleSources = new Map([+ ["local1", { type: "local", id: "local1" } as StyleSource],+ ["local2", { type: "local", id: "local2" } as StyleSource],+ ["local3", { type: "local", id: "local3" } as StyleSource],+ ["token1", { type: "token", id: "token1", name: "Token" } as StyleSource],+ ]);+ const styles: Styles = new Map();++ deleteLocalStyleSourcesMutable({+ localStyleSourceIds,+ styleSources,+ styles,+ });++ expect(styleSources.has("local1")).toBe(false);+ expect(styleSources.has("local2")).toBe(false);+ expect(styleSources.has("local3")).toBe(true);+ expect(styleSources.has("token1")).toBe(true);+ });++ test("deletes styles associated with local style sources", () => {+ const localStyleSourceIds = new Set(["local1", "local2"]);+ const styleSources: StyleSources = new Map([+ ["local1", { type: "local", id: "local1" } as StyleSource],+ ["local2", { type: "local", id: "local2" } as StyleSource],+ ]);+ const styles: Styles = new Map([+ [+ "local1:base:color",+ {+ breakpointId: "base",+ styleSourceId: "local1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ [+ "local2:base:fontSize",+ {+ breakpointId: "base",+ styleSourceId: "local2",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ },+ ],+ [+ "local3:base:display",+ {+ breakpointId: "base",+ styleSourceId: "local3",+ property: "display",+ value: { type: "keyword", value: "flex" },+ },+ ],+ ]);++ deleteLocalStyleSourcesMutable({+ localStyleSourceIds,+ styleSources,+ styles,+ });++ expect(styles.has("local1:base:color")).toBe(false);+ expect(styles.has("local2:base:fontSize")).toBe(false);+ expect(styles.has("local3:base:display")).toBe(true);+ expect(styles.size).toBe(1);+ });++ test("handles empty set of local style source IDs", () => {+ const localStyleSourceIds = new Set<string>();+ const styleSources: StyleSources = new Map([+ ["local1", { type: "local", id: "local1" } as StyleSource],+ ]);+ const styles: Styles = new Map();++ deleteLocalStyleSourcesMutable({+ localStyleSourceIds,+ styleSources,+ styles,+ });++ expect(styleSources.has("local1")).toBe(true);+ });+});++describe("collectStyleSourcesFromInstances", () => {+ test("collects style sources and selections from instances", () => {+ const instanceIds = new Set(["instance1", "instance2"]);+ const styleSourceSelections: StyleSourceSelections = new Map([+ ["instance1", { instanceId: "instance1", values: ["local1", "token1"] }],+ ["instance2", { instanceId: "instance2", values: ["local2"] }],+ ["instance3", { instanceId: "instance3", values: ["local3"] }],+ ]);+ const styleSources: StyleSources = new Map([+ ["local1", { type: "local", id: "local1" } as StyleSource],+ ["local2", { type: "local", id: "local2" } as StyleSource],+ ["local3", { type: "local", id: "local3" } as StyleSource],+ [+ "token1",+ { type: "token", id: "token1", name: "Token 1" } as StyleSource,+ ],+ ]);+ const styles: Styles = new Map([+ [+ "local1:base:color",+ {+ breakpointId: "base",+ styleSourceId: "local1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ [+ "local2:base:fontSize",+ {+ breakpointId: "base",+ styleSourceId: "local2",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ },+ ],+ [+ "local3:base:display",+ {+ breakpointId: "base",+ styleSourceId: "local3",+ property: "display",+ value: { type: "keyword", value: "flex" },+ },+ ],+ [+ "token1:base:backgroundColor",+ {+ breakpointId: "base",+ styleSourceId: "token1",+ property: "backgroundColor",+ value: { type: "keyword", value: "blue" },+ },+ ],+ ]);++ const result = collectStyleSourcesFromInstances({+ instanceIds,+ styleSourceSelections,+ styleSources,+ styles,+ });++ expect(result.styleSourceSelectionsArray).toHaveLength(2);+ expect(result.styleSourceSelectionsArray[0].instanceId).toBe("instance1");+ expect(result.styleSourceSelectionsArray[1].instanceId).toBe("instance2");++ expect(result.styleSourcesMap.size).toBe(3);+ expect(result.styleSourcesMap.has("local1")).toBe(true);+ expect(result.styleSourcesMap.has("local2")).toBe(true);+ expect(result.styleSourcesMap.has("token1")).toBe(true);+ expect(result.styleSourcesMap.has("local3")).toBe(false);++ expect(result.stylesArray).toHaveLength(3);+ expect(+ result.stylesArray.find((s) => s.styleSourceId === "local1")+ ).toBeDefined();+ expect(+ result.stylesArray.find((s) => s.styleSourceId === "local2")+ ).toBeDefined();+ expect(+ result.stylesArray.find((s) => s.styleSourceId === "token1")+ ).toBeDefined();+ expect(+ result.stylesArray.find((s) => s.styleSourceId === "local3")+ ).toBeUndefined();+ });++ test("returns empty arrays when instances have no style sources", () => {+ const instanceIds = new Set(["instance1", "instance2"]);+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styleSources: StyleSources = new Map();+ const styles: Styles = new Map();++ const result = collectStyleSourcesFromInstances({+ instanceIds,+ styleSourceSelections,+ styleSources,+ styles,+ });++ expect(result.styleSourceSelectionsArray).toHaveLength(0);+ expect(result.styleSourcesMap.size).toBe(0);+ expect(result.stylesArray).toHaveLength(0);+ });++ test("handles missing style sources gracefully", () => {+ const instanceIds = new Set(["instance1"]);+ const styleSourceSelections: StyleSourceSelections = new Map([+ [+ "instance1",+ { instanceId: "instance1", values: ["local1", "missing-source"] },+ ],+ ]);+ const styleSources: StyleSources = new Map([+ ["local1", { type: "local", id: "local1" } as StyleSource],+ ]);+ const styles: Styles = new Map([+ [+ "local1:base:color",+ {+ breakpointId: "base",+ styleSourceId: "local1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ ]);++ const result = collectStyleSourcesFromInstances({+ instanceIds,+ styleSourceSelections,+ styleSources,+ styles,+ });++ expect(result.styleSourceSelectionsArray).toHaveLength(1);+ expect(result.styleSourcesMap.size).toBe(1);+ expect(result.styleSourcesMap.has("local1")).toBe(true);+ expect(result.styleSourcesMap.has("missing-source")).toBe(false);+ });++ test("deduplicates style sources from multiple instances", () => {+ const instanceIds = new Set(["instance1", "instance2"]);+ const styleSourceSelections: StyleSourceSelections = new Map([+ ["instance1", { instanceId: "instance1", values: ["token1"] }],+ ["instance2", { instanceId: "instance2", values: ["token1"] }],+ ]);+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Shared Token" } as StyleSource,+ ],+ ]);+ const styles: Styles = new Map([+ [+ "token1:base:color",+ {+ breakpointId: "base",+ styleSourceId: "token1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ ]);++ const result = collectStyleSourcesFromInstances({+ instanceIds,+ styleSourceSelections,+ styleSources,+ styles,+ });++ expect(result.styleSourceSelectionsArray).toHaveLength(2);+ expect(result.styleSourcesMap.size).toBe(1);+ expect(result.stylesArray).toHaveLength(1);+ });+});++describe("findDuplicateTokens", () => {+ test("finds tokens with identical styles", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Primary Red" } as StyleSource,+ ],+ [+ "token2",+ { type: "token", id: "token2", name: "Accent Red" } as StyleSource,+ ],+ ["token3", { type: "token", id: "token3", name: "Blue" } as StyleSource],+ ["local1", { type: "local", id: "local1" } as StyleSource],+ ]);+ const styles: Styles = new Map([+ [+ "token1:base:color",+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ [+ "token2:base:color",+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ [+ "token3:base:color",+ createStyleDecl("token3", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ],+ ]);++ const duplicates = findDuplicateTokens({+ styleSources,+ styles,+ breakpoints,+ });++ expect(duplicates.size).toBe(2);+ expect(duplicates.get("token1")).toEqual(["token2"]);+ expect(duplicates.get("token2")).toEqual(["token1"]);+ expect(duplicates.has("token3")).toBe(false);+ expect(duplicates.has("local1")).toBe(false);+ });++ test("finds tokens with same name", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Primary" } as StyleSource,+ ],+ [+ "token2",+ { type: "token", id: "token2", name: "Primary" } as StyleSource,+ ],+ [+ "token3",+ { type: "token", id: "token3", name: "Secondary" } as StyleSource,+ ],+ ]);+ const styles: Styles = new Map([+ [+ "token1:base:color",+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ [+ "token2:base:color",+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ],+ [+ "token3:base:color",+ createStyleDecl("token3", "base", "color", {+ type: "keyword",+ value: "green",+ }),+ ],+ ]);++ const duplicates = findDuplicateTokens({+ styleSources,+ styles,+ breakpoints,+ });++ expect(duplicates.size).toBe(2);+ expect(duplicates.get("token1")).toEqual(["token2"]);+ expect(duplicates.get("token2")).toEqual(["token1"]);+ expect(duplicates.has("token3")).toBe(false);+ });++ test("finds tokens with same name AND same styles without duplicating", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Primary" } as StyleSource,+ ],+ [+ "token2",+ { type: "token", id: "token2", name: "Primary" } as StyleSource,+ ],+ ]);+ const styles: Styles = new Map([+ [+ "token1:base:color",+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ [+ "token2:base:color",+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ ]);++ const duplicates = findDuplicateTokens({+ styleSources,+ styles,+ breakpoints,+ });++ expect(duplicates.size).toBe(2);+ // Should list each token only once, not twice (once for name, once for styles)+ expect(duplicates.get("token1")).toEqual(["token2"]);+ expect(duplicates.get("token2")).toEqual(["token1"]);+ });++ test("finds mixed duplicates: some by style, some by name", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources: StyleSources = new Map([+ ["token1", { type: "token", id: "token1", name: "Red A" } as StyleSource],+ ["token2", { type: "token", id: "token2", name: "Red B" } as StyleSource],+ [+ "token3",+ { type: "token", id: "token3", name: "Duplicate Name" } as StyleSource,+ ],+ [+ "token4",+ { type: "token", id: "token4", name: "Duplicate Name" } as StyleSource,+ ],+ ]);+ const styles: Styles = new Map([+ [+ "token1:base:color",+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ [+ "token2:base:color",+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ [+ "token3:base:color",+ createStyleDecl("token3", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ],+ [+ "token4:base:color",+ createStyleDecl("token4", "base", "color", {+ type: "keyword",+ value: "green",+ }),+ ],+ ]);++ const duplicates = findDuplicateTokens({+ styleSources,+ styles,+ breakpoints,+ });++ expect(duplicates.size).toBe(4);+ expect(duplicates.get("token1")).toEqual(["token2"]);+ expect(duplicates.get("token2")).toEqual(["token1"]);+ expect(duplicates.get("token3")).toEqual(["token4"]);+ expect(duplicates.get("token4")).toEqual(["token3"]);+ });++ test("finds multiple groups of duplicates", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources: StyleSources = new Map([+ ["token1", { type: "token", id: "token1", name: "Red 1" } as StyleSource],+ ["token2", { type: "token", id: "token2", name: "Red 2" } as StyleSource],+ [+ "token3",+ { type: "token", id: "token3", name: "Blue 1" } as StyleSource,+ ],+ [+ "token4",+ { type: "token", id: "token4", name: "Blue 2" } as StyleSource,+ ],+ [+ "token5",+ { type: "token", id: "token5", name: "Blue 3" } as StyleSource,+ ],+ ]);+ const styles: Styles = new Map([+ [+ "token1:base:color",+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ [+ "token2:base:color",+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ [+ "token3:base:color",+ createStyleDecl("token3", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ],+ [+ "token4:base:color",+ createStyleDecl("token4", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ],+ [+ "token5:base:color",+ createStyleDecl("token5", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ],+ ]);++ const duplicates = findDuplicateTokens({+ styleSources,+ styles,+ breakpoints,+ });++ expect(duplicates.size).toBe(5);+ expect(duplicates.get("token1")).toEqual(["token2"]);+ expect(duplicates.get("token2")).toEqual(["token1"]);+ expect(duplicates.get("token3")).toEqual(["token4", "token5"]);+ expect(duplicates.get("token4")).toEqual(["token3", "token5"]);+ expect(duplicates.get("token5")).toEqual(["token3", "token4"]);+ });++ test("returns empty map when no duplicates exist", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources: StyleSources = new Map([+ ["token1", { type: "token", id: "token1", name: "Red" } as StyleSource],+ ["token2", { type: "token", id: "token2", name: "Blue" } as StyleSource],+ ]);+ const styles: Styles = new Map([+ [+ "token1:base:color",+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ [+ "token2:base:color",+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ],+ ]);++ const duplicates = findDuplicateTokens({+ styleSources,+ styles,+ breakpoints,+ });++ expect(duplicates.size).toBe(0);+ });++ test("compares tokens across breakpoints and states", () => {+ const breakpoints = toMap<Breakpoint>([+ { id: "base", label: "base" },+ { id: "tablet", label: "tablet", minWidth: 768 },+ ]);+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Token 1" } as StyleSource,+ ],+ [+ "token2",+ { type: "token", id: "token2", name: "Token 2" } as StyleSource,+ ],+ ]);+ const styles: Styles = new Map([+ [+ "token1:base:color",+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ [+ "token1:tablet:color",+ {+ ...createStyleDecl("token1", "tablet", "color", {+ type: "keyword",+ value: "blue",+ }),+ state: ":hover",+ },+ ],+ [+ "token2:base:color",+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ [+ "token2:tablet:color",+ {+ ...createStyleDecl("token2", "tablet", "color", {+ type: "keyword",+ value: "blue",+ }),+ state: ":hover",+ },+ ],+ ]);++ const duplicates = findDuplicateTokens({+ styleSources,+ styles,+ breakpoints,+ });++ expect(duplicates.size).toBe(2);+ expect(duplicates.get("token1")).toEqual(["token2"]);+ expect(duplicates.get("token2")).toEqual(["token1"]);+ });++ test("ignores local style sources", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources: StyleSources = new Map([+ ["local1", { type: "local", id: "local1" } as StyleSource],+ ["local2", { type: "local", id: "local2" } as StyleSource],+ ]);+ const styles: Styles = new Map([+ [+ "local1:base:color",+ createStyleDecl("local1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ [+ "local2:base:color",+ createStyleDecl("local2", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ ]);++ const duplicates = findDuplicateTokens({+ styleSources,+ styles,+ breakpoints,+ });++ expect(duplicates.size).toBe(0);+ });++ test("handles tokens with no styles", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources: StyleSources = new Map([+ [+ "token1",+ { type: "token", id: "token1", name: "Empty 1" } as StyleSource,+ ],+ [+ "token2",+ { type: "token", id: "token2", name: "Empty 2" } as StyleSource,+ ],+ [+ "token3",+ { type: "token", id: "token3", name: "With Styles" } as StyleSource,+ ],+ ]);+ const styles: Styles = new Map([+ [+ "token3:base:color",+ createStyleDecl("token3", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ ]);++ const duplicates = findDuplicateTokens({+ styleSources,+ styles,+ breakpoints,+ });++ // Empty tokens should be considered duplicates of each other+ expect(duplicates.size).toBe(2);+ expect(duplicates.get("token1")).toEqual(["token2"]);+ expect(duplicates.get("token2")).toEqual(["token1"]);+ expect(duplicates.has("token3")).toBe(false);+ });+});++describe("findTokenWithMatchingStyles", () => {+ const breakpoints = new Map<Breakpoint["id"], Breakpoint>([+ ["base", { id: "base", label: "Base" }],+ ]);++ test("returns no conflict when token name doesn't exist", () => {+ const existingTokens: StyleSource[] = [+ { type: "token", id: "existing1", name: "PrimaryColor" },+ ];++ const result = findTokenWithMatchingStyles({+ tokenName: "SecondaryColor",+ tokenStyles: [],+ existingTokens,+ existingStyles: [],+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ expect(result.hasConflict).toBe(false);+ expect(result.matchingToken).toBeUndefined();+ });++ test("returns matching token when name and styles match", () => {+ const existingToken: Extract<StyleSource, { type: "token" }> = {+ type: "token",+ id: "existing1",+ name: "PrimaryColor",+ };++ const existingStyles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "existing1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ];++ const tokenStyles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "fragment1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ];++ const result = findTokenWithMatchingStyles({+ tokenName: "PrimaryColor",+ tokenStyles,+ existingTokens: [existingToken],+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ expect(result.hasConflict).toBe(false);+ expect(result.matchingToken).toBeDefined();+ expect(result.matchingToken?.id).toBe("existing1");+ });++ test("returns conflict when name matches but styles differ", () => {+ const existingToken: Extract<StyleSource, { type: "token" }> = {+ type: "token",+ id: "existing1",+ name: "PrimaryColor",+ };++ const existingStyles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "existing1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ];++ const tokenStyles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "fragment1",+ property: "color",+ value: { type: "keyword", value: "blue" }, // Different color+ },+ ];++ const result = findTokenWithMatchingStyles({+ tokenName: "PrimaryColor",+ tokenStyles,+ existingTokens: [existingToken],+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ expect(result.hasConflict).toBe(true);+ expect(result.matchingToken).toBeUndefined();+ });++ test("matches token with multiple style properties", () => {+ const existingToken: Extract<StyleSource, { type: "token" }> = {+ type: "token",+ id: "existing1",+ name: "ButtonStyle",+ };++ const existingStyles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "existing1",+ property: "color",+ value: { type: "keyword", value: "white" },+ },+ {+ breakpointId: "base",+ styleSourceId: "existing1",+ property: "backgroundColor",+ value: { type: "keyword", value: "blue" },+ },+ {+ breakpointId: "base",+ styleSourceId: "existing1",+ property: "paddingTop",+ value: { type: "unit", value: 10, unit: "px" },+ },+ ];++ const tokenStyles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "fragment1",+ property: "paddingTop",+ value: { type: "unit", value: 10, unit: "px" },+ },+ {+ breakpointId: "base",+ styleSourceId: "fragment1",+ property: "backgroundColor",+ value: { type: "keyword", value: "blue" },+ },+ {+ breakpointId: "base",+ styleSourceId: "fragment1",+ property: "color",+ value: { type: "keyword", value: "white" },+ },+ ];++ const result = findTokenWithMatchingStyles({+ tokenName: "ButtonStyle",+ tokenStyles,+ existingTokens: [existingToken],+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ expect(result.hasConflict).toBe(false);+ expect(result.matchingToken?.id).toBe("existing1");+ });++ test("detects conflict when one style property differs", () => {+ const existingToken: Extract<StyleSource, { type: "token" }> = {+ type: "token",+ id: "existing1",+ name: "ButtonStyle",+ };++ const existingStyles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "existing1",+ property: "color",+ value: { type: "keyword", value: "white" },+ },+ {+ breakpointId: "base",+ styleSourceId: "existing1",+ property: "backgroundColor",+ value: { type: "keyword", value: "blue" },+ },+ ];++ const tokenStyles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "fragment1",+ property: "color",+ value: { type: "keyword", value: "white" },+ },+ {+ breakpointId: "base",+ styleSourceId: "fragment1",+ property: "backgroundColor",+ value: { type: "keyword", value: "red" }, // Different!+ },+ ];++ const result = findTokenWithMatchingStyles({+ tokenName: "ButtonStyle",+ tokenStyles,+ existingTokens: [existingToken],+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ expect(result.hasConflict).toBe(true);+ expect(result.matchingToken).toBeUndefined();+ });++ test("handles empty token styles", () => {+ const existingToken: Extract<StyleSource, { type: "token" }> = {+ type: "token",+ id: "existing1",+ name: "EmptyToken",+ };++ const result = findTokenWithMatchingStyles({+ tokenName: "EmptyToken",+ tokenStyles: [],+ existingTokens: [existingToken],+ existingStyles: [],+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ expect(result.hasConflict).toBe(false);+ expect(result.matchingToken?.id).toBe("existing1");+ });+});++describe("detectTokenConflicts", () => {+ const breakpoints = new Map<Breakpoint["id"], Breakpoint>([+ ["base", { id: "base", label: "Base" }],+ ]);++ test("returns empty array when no conflicts exist", () => {+ const fragmentStyleSources: StyleSource[] = [+ { type: "token", id: "frag1", name: "NewToken" },+ ];++ const fragmentStyles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "frag1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ];++ const existingStyleSources = new Map<string, StyleSource>([+ ["exist1", { type: "token", id: "exist1", name: "ExistingToken" }],+ ]);++ const existingStyles = new Map<string, StyleDecl>([+ [+ "exist1:base:color",+ {+ breakpointId: "base",+ styleSourceId: "exist1",+ property: "color",+ value: { type: "keyword", value: "blue" },+ },+ ],+ ]);++ const conflicts = detectTokenConflicts({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources,+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ expect(conflicts).toHaveLength(0);+ });++ test("detects conflict when token name exists with different styles", () => {+ const fragmentStyleSources: StyleSource[] = [+ { type: "token", id: "frag1", name: "PrimaryColor" },+ ];++ const fragmentStyles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "frag1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ];++ const existingStyleSources = new Map<string, StyleSource>([+ ["exist1", { type: "token", id: "exist1", name: "PrimaryColor" }],+ ]);++ const existingStyles = new Map<string, StyleDecl>([+ [+ "exist1:base:color",+ {+ breakpointId: "base",+ styleSourceId: "exist1",+ property: "color",+ value: { type: "keyword", value: "blue" }, // Different color+ },+ ],+ ]);++ const conflicts = detectTokenConflicts({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources,+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ expect(conflicts).toHaveLength(1);+ expect(conflicts[0].tokenName).toBe("PrimaryColor");+ expect(conflicts[0].fragmentTokenId).toBe("frag1");+ expect(conflicts[0].existingToken.id).toBe("exist1");+ });++ test("detects multiple conflicts", () => {+ const fragmentStyleSources: StyleSource[] = [+ { type: "token", id: "frag1", name: "PrimaryColor" },+ { type: "token", id: "frag2", name: "SecondaryColor" },+ ];++ const fragmentStyles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "frag1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ breakpointId: "base",+ styleSourceId: "frag2",+ property: "color",+ value: { type: "keyword", value: "green" },+ },+ ];++ const existingStyleSources = new Map<string, StyleSource>([+ ["exist1", { type: "token", id: "exist1", name: "PrimaryColor" }],+ ["exist2", { type: "token", id: "exist2", name: "SecondaryColor" }],+ ]);++ const existingStyles = new Map<string, StyleDecl>([+ [+ "exist1:base:color",+ {+ breakpointId: "base",+ styleSourceId: "exist1",+ property: "color",+ value: { type: "keyword", value: "blue" },+ },+ ],+ [+ "exist2:base:color",+ {+ breakpointId: "base",+ styleSourceId: "exist2",+ property: "color",+ value: { type: "keyword", value: "yellow" },+ },+ ],+ ]);++ const conflicts = detectTokenConflicts({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources,+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ expect(conflicts).toHaveLength(2);+ expect(conflicts[0].tokenName).toBe("PrimaryColor");+ expect(conflicts[1].tokenName).toBe("SecondaryColor");+ });++ test("ignores local style sources", () => {+ const fragmentStyleSources: StyleSource[] = [+ { type: "local", id: "frag1" },+ { type: "token", id: "frag2", name: "SomeToken" },+ ];++ const fragmentStyles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "frag1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ breakpointId: "base",+ styleSourceId: "frag2",+ property: "color",+ value: { type: "keyword", value: "blue" },+ },+ ];++ const existingStyleSources = new Map<string, StyleSource>();+ const existingStyles = new Map<string, StyleDecl>();++ const conflicts = detectTokenConflicts({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources,+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ expect(conflicts).toHaveLength(0);+ });++ test("no conflict when token name matches and styles match", () => {+ const fragmentStyleSources: StyleSource[] = [+ { type: "token", id: "frag1", name: "SharedToken" },+ ];++ const fragmentStyles: StyleDecl[] = [+ {+ breakpointId: "base",+ styleSourceId: "frag1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ];++ const existingStyleSources = new Map<string, StyleSource>([+ ["exist1", { type: "token", id: "exist1", name: "SharedToken" }],+ ]);++ const existingStyles = new Map<string, StyleDecl>([+ [+ "exist1:base:color",+ {+ breakpointId: "base",+ styleSourceId: "exist1",+ property: "color",+ value: { type: "keyword", value: "red" }, // Same color+ },+ ],+ ]);++ const conflicts = detectTokenConflicts({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources,+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ expect(conflicts).toHaveLength(0);+ });++ test("handles tokens with no styles", () => {+ const fragmentStyleSources: StyleSource[] = [+ { type: "token", id: "frag1", name: "EmptyToken" },+ ];++ const fragmentStyles: StyleDecl[] = [];++ const existingStyleSources = new Map<string, StyleSource>([+ ["exist1", { type: "token", id: "exist1", name: "EmptyToken" }],+ ]);++ const existingStyles = new Map<string, StyleDecl>();++ const conflicts = detectTokenConflicts({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources,+ existingStyles,+ breakpoints,+ mergedBreakpointIds: new Map(),+ });++ expect(conflicts).toHaveLength(0);+ });++ test("uses merged breakpoint IDs when comparing", () => {+ const fragmentStyleSources: StyleSource[] = [+ { type: "token", id: "frag1", name: "ResponsiveToken" },+ ];++ const fragmentStyles: StyleDecl[] = [+ {+ breakpointId: "tablet-frag",+ styleSourceId: "frag1",+ property: "fontSize",+ value: { type: "unit", value: 18, unit: "px" },+ },+ ];++ const breakpointsMap = new Map<Breakpoint["id"], Breakpoint>([+ ["base", { id: "base", label: "Base" }],+ ["tablet-exist", { id: "tablet-exist", minWidth: 768, label: "Tablet" }],+ ]);++ const mergedBreakpointIds = new Map([["tablet-frag", "tablet-exist"]]);++ const existingStyleSources = new Map<string, StyleSource>([+ ["exist1", { type: "token", id: "exist1", name: "ResponsiveToken" }],+ ]);++ const existingStyles = new Map<string, StyleDecl>([+ [+ "exist1:tablet-exist:fontSize",+ {+ breakpointId: "tablet-exist",+ styleSourceId: "exist1",+ property: "fontSize",+ value: { type: "unit", value: 18, unit: "px" },+ },+ ],+ ]);++ const conflicts = detectTokenConflicts({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources,+ existingStyles,+ breakpoints: breakpointsMap,+ mergedBreakpointIds,+ });++ // Should be no conflict since the breakpoints are merged and styles match+ expect(conflicts).toHaveLength(0);+ });+});diff --git a/apps/builder/app/shared/style-source-utils.ts b/apps/builder/app/shared/style-source-utils.tsnew file mode 100644index 0000000000..3a5b9c083d--- /dev/null+++ b/apps/builder/app/shared/style-source-utils.ts@@ -0,0 +1,786 @@+import { nanoid } from "nanoid";+import type {+ Breakpoint,+ Instance,+ StyleDecl,+ StyleSource,+ StyleSourceSelection,+ Styles,+ StyleSources,+ StyleSourceSelections,+} from "@webstudio-is/sdk";+import { getStyleDeclKey, ROOT_INSTANCE_ID } from "@webstudio-is/sdk";+import { toValue } from "@webstudio-is/css-engine";+import type { ConflictResolution } from "./token-conflict-dialog";+import { removeByMutable } from "./array-utils";++/**+ * Generates a normalized CSS string for comparing style source styles.+ * This creates a deterministic signature based on breakpoint, state, property, and value.+ * The signature is normalized by sorting to ensure order-independent comparison.+ */+export const getStyleSourceStylesSignature = (+ styleSourceId: StyleSource["id"],+ styles: StyleDecl[],+ breakpoints: Map<Breakpoint["id"], Breakpoint>,+ mergedBreakpointIds: Map<Breakpoint["id"], Breakpoint["id"]>+): string => {+ const tokenStyles = styles+ .filter((decl) => decl.styleSourceId === styleSourceId)+ .map((decl) => {+ // Get merged breakpoint id to ensure consistent comparison+ const breakpointId =+ mergedBreakpointIds.get(decl.breakpointId) ?? decl.breakpointId;+ const breakpoint = breakpoints.get(breakpointId);+ const breakpointKey = breakpoint+ ? JSON.stringify({ minWidth: breakpoint.minWidth })+ : "base";+ const state = decl.state ?? "";+ return `${breakpointKey}|${state}|${decl.property}:${toValue(decl.value)}`;+ })+ .sort()+ .join(";");+ return tokenStyles;+};++/**+ * Check if a token with the same name and matching styles already exists.+ * Returns the existing token if found, undefined otherwise.+ */+export const findTokenWithMatchingStyles = ({+ tokenName,+ tokenStyles,+ existingTokens,+ existingStyles,+ breakpoints,+ mergedBreakpointIds,+}: {+ tokenName: string;+ tokenStyles: StyleDecl[];+ existingTokens: StyleSource[];+ existingStyles: StyleDecl[];+ breakpoints: Map<Breakpoint["id"], Breakpoint>;+ mergedBreakpointIds: Map<Breakpoint["id"], Breakpoint["id"]>;+}):+ | {+ hasConflict: false;+ matchingToken: Extract<StyleSource, { type: "token" }>;+ }+ | { hasConflict: true; matchingToken: undefined }+ | { hasConflict: false; matchingToken: undefined } => {+ // Find tokens with the same name+ const tokensWithSameName = existingTokens.filter(+ (token) => token.type === "token" && token.name === tokenName+ );++ if (tokensWithSameName.length === 0) {+ return { hasConflict: false, matchingToken: undefined };+ }++ // Get the signature of the token we're checking+ // Use a temporary ID since we're just comparing styles+ const tempId = "temp";+ const signature = getStyleSourceStylesSignature(+ tempId,+ tokenStyles.map((style) => ({ ...style, styleSourceId: tempId })),+ breakpoints,+ mergedBreakpointIds+ );++ // Check if any existing token with the same name has matching styles+ for (const existing of tokensWithSameName) {+ if (existing.type !== "token") {+ continue;+ }+ const existingSignature = getStyleSourceStylesSignature(+ existing.id,+ existingStyles,+ breakpoints,+ mergedBreakpointIds+ );+ if (existingSignature === signature) {+ return { hasConflict: false, matchingToken: existing };+ }+ }++ // Same name but different styles = conflict+ return { hasConflict: true, matchingToken: undefined };+};++export type TokenConflict = {+ tokenName: string;+ fragmentTokenId: StyleSource["id"];+ fragmentToken: Extract<StyleSource, { type: "token" }>;+ existingToken: Extract<StyleSource, { type: "token" }>;+};++/**+ * Detect all token conflicts before insertion.+ * Returns an array of conflicts where fragment tokens have the same name but different styles than existing tokens.+ */+export const detectTokenConflicts = ({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources,+ existingStyles,+ breakpoints,+ mergedBreakpointIds,+}: {+ fragmentStyleSources: StyleSource[];+ fragmentStyles: StyleDecl[];+ existingStyleSources: StyleSources;+ existingStyles: Styles;+ breakpoints: Map<Breakpoint["id"], Breakpoint>;+ mergedBreakpointIds: Map<Breakpoint["id"], Breakpoint["id"]>;+}): TokenConflict[] => {+ const conflicts: TokenConflict[] = [];+ const existingTokens = Array.from(existingStyleSources.values());+ const existingStylesArray = Array.from(existingStyles.values());++ for (const styleSource of fragmentStyleSources) {+ if (styleSource.type !== "token") {+ continue;+ }++ const result = findTokenWithMatchingStyles({+ tokenName: styleSource.name,+ tokenStyles: fragmentStyles.filter(+ (decl) => decl.styleSourceId === styleSource.id+ ),+ existingTokens,+ existingStyles: existingStylesArray,+ breakpoints,+ mergedBreakpointIds,+ });++ if (result.hasConflict) {+ // Find the first existing token with the same name for display purposes+ const existingToken = existingTokens.find(+ (token) => token.type === "token" && token.name === styleSource.name+ );+ if (existingToken && existingToken.type === "token") {+ conflicts.push({+ tokenName: styleSource.name,+ fragmentTokenId: styleSource.id,+ fragmentToken: styleSource,+ existingToken,+ });+ }+ }+ }++ return conflicts;+};++/**+ * Style Source Conflict Resolution Rules:+ *+ * When inserting a fragment with style sources (tokens), the following rules determine whether to reuse,+ * rename, or create new style sources:+ *+ * 1. Same name + Same styles → Reuse existing style source (no new style source created)+ * 2. Same name + Different styles → Add counter suffix (e.g., "myToken-1", "myToken-2") OR use existing based on onConflict+ * 3. Different name + Same styles → Insert as new style source with its own name+ * 4. Different name + Different styles → Insert as new style source normally+ * 5. Name collision safeguard → Always add counter suffix if name already exists+ * 6. Style comparison → Only compares CSS signatures when style source names match+ *+ * All new style sources receive a fresh UUID to prevent ID collisions. The styleSourceIdMap tracks+ * originalFragmentStyleSourceId → newStyleSourceId (or existingStyleSourceId if reused) to ensure all+ * references (styles, styleSourceSelections) are updated correctly.+ */+export const insertStyleSources = ({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources,+ existingStyles,+ breakpoints,+ mergedBreakpointIds,+ conflictResolution = "theirs",+}: {+ fragmentStyleSources: StyleSource[];+ fragmentStyles: StyleDecl[];+ existingStyleSources: StyleSources;+ existingStyles: Styles;+ breakpoints: Map<Breakpoint["id"], Breakpoint>;+ mergedBreakpointIds: Map<Breakpoint["id"], Breakpoint["id"]>;+ /** How to handle conflicts: "theirs" = add suffix (keep incoming), "ours" = use existing token, "merge" = merge styles (theirs overrides ours) */+ conflictResolution?: ConflictResolution;+}): {+ styleSourceIds: Set<StyleSource["id"]>;+ styleSourceIdMap: Map<StyleSource["id"], StyleSource["id"]>;+ updatedStyleSources: StyleSources;+} => {+ // Build a map of existing tokens by name+ const existingTokensByName = new Map<string, StyleSource[]>();++ for (const styleSource of existingStyleSources.values()) {+ if (styleSource.type !== "token") {+ continue;+ }+ const tokensWithName = existingTokensByName.get(styleSource.name) ?? [];+ tokensWithName.push(styleSource);+ existingTokensByName.set(styleSource.name, tokensWithName);+ }++ const styleSourceIds = new Set<StyleSource["id"]>();+ const styleSourceIdMap = new Map<StyleSource["id"], StyleSource["id"]>(); // old id -> new id+ const updatedStyleSources = new Map(existingStyleSources);++ for (const styleSource of fragmentStyleSources) {+ if (styleSource.type === "local") {+ continue;+ }+ styleSource.type satisfies "token";++ const originalFragmentTokenId = styleSource.id;+ const newTokenId = nanoid();++ // Check if there's an existing token with the same name+ const tokensWithSameName = existingTokensByName.get(styleSource.name);++ if (tokensWithSameName && tokensWithSameName.length > 0) {+ // Same name exists - compare styles to decide if we can reuse+ const result = findTokenWithMatchingStyles({+ tokenName: styleSource.name,+ tokenStyles: fragmentStyles.filter(+ (decl) => decl.styleSourceId === originalFragmentTokenId+ ),+ existingTokens: tokensWithSameName,+ existingStyles: Array.from(existingStyles.values()),+ breakpoints,+ mergedBreakpointIds,+ });++ if (result.matchingToken) {+ // Same name AND same styles -> reuse existing token+ styleSourceIdMap.set(originalFragmentTokenId, result.matchingToken.id);+ continue; // Don't insert, reuse existing+ }++ if (result.hasConflict) {+ // Same name but different styles+ if (conflictResolution === "ours") {+ // Use the existing token instead of creating a new one+ const existingToken = tokensWithSameName[0];+ if (existingToken.type !== "token") {+ continue;+ }+ styleSourceIdMap.set(originalFragmentTokenId, existingToken.id);+ continue; // Don't insert, use existing+ } else if (conflictResolution === "merge") {+ // Merge: keep existing token name/id, but merge styles (theirs overrides ours)+ const existingToken = tokensWithSameName[0];+ if (existingToken.type !== "token") {+ continue;+ }++ // Map the fragment token to the existing token+ styleSourceIdMap.set(originalFragmentTokenId, existingToken.id);++ // Mark the existing token for style insertion+ // This will allow the fragment styles to be added/merged+ styleSourceIds.add(originalFragmentTokenId);+ continue;+ } else {+ // Default: add counter suffix+ let maxCounter = 0;+ const baseNamePattern = new RegExp(+ `^${styleSource.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:-(\\d+))?$`+ );+ for (const existing of updatedStyleSources.values()) {+ if (existing.type !== "token") {+ continue;+ }+ const match = existing.name.match(baseNamePattern);+ if (match) {+ const counter = match[1] ? parseInt(match[1], 10) : 0;+ maxCounter = Math.max(maxCounter, counter);+ }+ }+ const newName = `${styleSource.name}-${maxCounter + 1}`;+ const newStyleSource = {+ ...styleSource,+ id: newTokenId,+ name: newName,+ };+ styleSourceIds.add(originalFragmentTokenId);+ updatedStyleSources.set(newTokenId, newStyleSource);+ styleSourceIdMap.set(originalFragmentTokenId, newTokenId);++ // Add to tracking maps+ const tokensWithNewName = existingTokensByName.get(newName) ?? [];+ tokensWithNewName.push(newStyleSource);+ existingTokensByName.set(newName, tokensWithNewName);+ continue;+ }+ }+ }++ // Different name (or no existing tokens) -> insert with new ID+ const newStyleSource = { ...styleSource, id: newTokenId };+ styleSourceIds.add(originalFragmentTokenId);+ updatedStyleSources.set(newTokenId, newStyleSource);+ styleSourceIdMap.set(originalFragmentTokenId, newTokenId);++ // Add to tracking maps+ const tokensWithName = existingTokensByName.get(styleSource.name) ?? [];+ tokensWithName.push(newStyleSource);+ existingTokensByName.set(styleSource.name, tokensWithName);+ }++ return {+ styleSourceIds,+ styleSourceIdMap,+ updatedStyleSources,+ };+};++/**+ * Insert local style sources for portal content without changing IDs.+ * Portal content IDs are preserved to avoid data bloat.+ */+export const insertPortalLocalStyleSources = ({+ fragmentStyleSources,+ fragmentStyleSourceSelections,+ fragmentStyles,+ instanceIds,+ styleSources,+ styleSourceSelections,+ styles,+ mergedBreakpointIds,+}: {+ fragmentStyleSources: StyleSource[];+ fragmentStyleSourceSelections: StyleSourceSelection[];+ fragmentStyles: StyleDecl[];+ instanceIds: Set<Instance["id"]>;+ styleSources: StyleSources;+ styleSourceSelections: StyleSourceSelections;+ styles: Styles;+ mergedBreakpointIds: Map<Breakpoint["id"], Breakpoint["id"]>;+}): void => {+ const instanceStyleSourceIds = new Set<StyleSource["id"]>();+ for (const styleSourceSelection of fragmentStyleSourceSelections) {+ const { instanceId } = styleSourceSelection;+ if (instanceIds.has(instanceId) === false) {+ continue;+ }+ styleSourceSelections.set(instanceId, styleSourceSelection);+ for (const styleSourceId of styleSourceSelection.values) {+ instanceStyleSourceIds.add(styleSourceId);+ }+ }+ const localStyleSourceIds = new Set<StyleSource["id"]>();+ for (const styleSource of fragmentStyleSources) {+ if (+ styleSource.type === "local" &&+ instanceStyleSourceIds.has(styleSource.id)+ ) {+ localStyleSourceIds.add(styleSource.id);+ styleSources.set(styleSource.id, styleSource);+ }+ }+ for (const styleDecl of fragmentStyles) {+ if (localStyleSourceIds.has(styleDecl.styleSourceId)) {+ const { breakpointId } = styleDecl;+ const newStyleDecl: StyleDecl = {+ ...styleDecl,+ breakpointId: mergedBreakpointIds.get(breakpointId) ?? breakpointId,+ };+ styles.set(getStyleDeclKey(newStyleDecl), newStyleDecl);+ }+ }+};++/**+ * Insert local style sources with new IDs for regular (non-portal) content.+ * Handles merging :root styles and token remapping.+ */+export const insertLocalStyleSourcesWithNewIds = ({+ fragmentStyleSources,+ fragmentStyleSourceSelections,+ fragmentStyles,+ fragmentInstanceIds,+ newInstanceIds,+ styleSourceIdMap,+ styleSources,+ styleSourceSelections,+ styles,+ mergedBreakpointIds,+}: {+ fragmentStyleSources: StyleSource[];+ fragmentStyleSourceSelections: StyleSourceSelection[];+ fragmentStyles: StyleDecl[];+ fragmentInstanceIds: Set<Instance["id"]>;+ newInstanceIds: Map<Instance["id"], Instance["id"]>;+ styleSourceIdMap: Map<StyleSource["id"], StyleSource["id"]>;+ styleSources: StyleSources;+ styleSourceSelections: StyleSourceSelections;+ styles: Styles;+ mergedBreakpointIds: Map<Breakpoint["id"], Breakpoint["id"]>;+}): void => {+ const newLocalStyleSources = new Map();+ for (const styleSource of fragmentStyleSources) {+ if (styleSource.type === "local") {+ newLocalStyleSources.set(styleSource.id, styleSource);+ }+ }++ const newLocalStyleSourceIds = new Map<+ StyleSource["id"],+ StyleSource["id"]+ >();+ for (const { instanceId, values } of fragmentStyleSourceSelections) {+ if (fragmentInstanceIds.has(instanceId) === false) {+ continue;+ }++ const existingStyleSourceIds =+ styleSourceSelections.get(instanceId)?.values ?? [];+ let existingLocalStyleSource;+ for (const styleSourceId of existingStyleSourceIds) {+ const styleSource = styleSources.get(styleSourceId);+ if (styleSource?.type === "local") {+ existingLocalStyleSource = styleSource;+ }+ }+ const newStyleSourceIds = [];+ for (let styleSourceId of values) {+ const newLocalStyleSource = newLocalStyleSources.get(styleSourceId);+ if (newLocalStyleSource) {+ // merge only :root styles and duplicate others+ if (instanceId === ROOT_INSTANCE_ID && existingLocalStyleSource) {+ // write local styles into existing local style source+ styleSourceId = existingLocalStyleSource.id;+ } else {+ // create new local styles+ const newId = nanoid();+ styleSources.set(newId, { ...newLocalStyleSource, id: newId });+ styleSourceId = newId;+ }+ newLocalStyleSourceIds.set(newLocalStyleSource.id, styleSourceId);+ } else {+ // Check if this is a token that was mapped to an existing token+ const mappedTokenId = styleSourceIdMap.get(styleSourceId);+ if (mappedTokenId) {+ styleSourceId = mappedTokenId;+ }+ }+ newStyleSourceIds.push(styleSourceId);+ }+ const newInstanceId = newInstanceIds.get(instanceId) ?? instanceId;+ styleSourceSelections.set(newInstanceId, {+ instanceId: newInstanceId,+ values: newStyleSourceIds,+ });+ }++ for (const styleDecl of fragmentStyles) {+ const { breakpointId, styleSourceId } = styleDecl;+ if (newLocalStyleSourceIds.has(styleDecl.styleSourceId)) {+ const newStyleDecl: StyleDecl = {+ ...styleDecl,+ styleSourceId:+ newLocalStyleSourceIds.get(styleSourceId) ?? styleSourceId,+ breakpointId: mergedBreakpointIds.get(breakpointId) ?? breakpointId,+ };+ styles.set(getStyleDeclKey(newStyleDecl), newStyleDecl);+ }+ }+};++/**+ * Delete a style source and all its associated styles and selections.+ * This is a mutable operation designed to be used within a transaction.+ */+export const deleteStyleSourceMutable = ({+ styleSourceId,+ styleSources,+ styleSourceSelections,+ styles,+}: {+ styleSourceId: StyleSource["id"];+ styleSources: StyleSources;+ styleSourceSelections: StyleSourceSelections;+ styles: Styles;+}): void => {+ styleSources.delete(styleSourceId);+ for (const styleSourceSelection of styleSourceSelections.values()) {+ if (styleSourceSelection.values.includes(styleSourceId)) {+ removeByMutable(+ styleSourceSelection.values,+ (item) => item === styleSourceId+ );+ }+ }+ for (const [styleDeclKey, styleDecl] of styles) {+ if (styleDecl.styleSourceId === styleSourceId) {+ styles.delete(styleDeclKey);+ }+ }+};++/**+ * Find all unused tokens in the style sources.+ * A token is considered unused if it has no usages in any instance.+ */+export const findUnusedTokens = ({+ styleSources,+ styleSourceUsages,+}: {+ styleSources: StyleSources;+ styleSourceUsages: Map<StyleSource["id"], Set<Instance["id"]>>;+}): StyleSource["id"][] => {+ const unusedTokenIds: StyleSource["id"][] = [];+ for (const styleSource of styleSources.values()) {+ if (styleSource.type === "token") {+ const usages = styleSourceUsages.get(styleSource.id);+ if (usages === undefined || usages.size === 0) {+ unusedTokenIds.push(styleSource.id);+ }+ }+ }+ return unusedTokenIds;+};++/**+ * Delete multiple style sources (used for bulk unused token deletion).+ * This is a mutable operation designed to be used within a transaction.+ */+export const deleteStyleSourcesMutable = ({+ styleSourceIds,+ styleSources,+ styleSourceSelections,+ styles,+}: {+ styleSourceIds: StyleSource["id"][];+ styleSources: StyleSources;+ styleSourceSelections: StyleSourceSelections;+ styles: Styles;+}): void => {+ for (const styleSourceId of styleSourceIds) {+ deleteStyleSourceMutable({+ styleSourceId,+ styleSources,+ styleSourceSelections,+ styles,+ });+ }+};++export type RenameStyleSourceError =+ | { type: "minlength"; id: StyleSource["id"] }+ | { type: "duplicate"; id: StyleSource["id"] };++/**+ * Validate and perform a style source rename.+ * Returns an error if validation fails, undefined on success.+ */+export const validateAndRenameStyleSource = ({+ id,+ name,+ styleSources,+}: {+ id: StyleSource["id"];+ name: string;+ styleSources: StyleSources;+}): RenameStyleSourceError | undefined => {+ if (name.trim().length === 0) {+ return { type: "minlength", id };+ }+ for (const styleSource of styleSources.values()) {+ if (+ styleSource.type === "token" &&+ styleSource.name === name &&+ styleSource.id !== id+ ) {+ return { type: "duplicate", id };+ }+ }+ return undefined;+};++/**+ * Rename a style source (token).+ * This is a mutable operation designed to be used within a transaction.+ */+export const renameStyleSourceMutable = ({+ id,+ name,+ styleSources,+}: {+ id: StyleSource["id"];+ name: string;+ styleSources: StyleSources;+}): void => {+ const styleSource = styleSources.get(id);+ if (styleSource?.type === "token") {+ styleSource.name = name;+ }+};++/**+ * Delete local style sources and their associated styles for a set of instances.+ * This is typically used when deleting instances to clean up their local styles.+ * This is a mutable operation designed to be used within a transaction.+ */+export const deleteLocalStyleSourcesMutable = ({+ localStyleSourceIds,+ styleSources,+ styles,+}: {+ localStyleSourceIds: Set<StyleSource["id"]>;+ styleSources: StyleSources;+ styles: Styles;+}): void => {+ for (const styleSourceId of localStyleSourceIds) {+ styleSources.delete(styleSourceId);+ }+ for (const [styleDeclKey, styleDecl] of styles) {+ if (localStyleSourceIds.has(styleDecl.styleSourceId)) {+ styles.delete(styleDeclKey);+ }+ }+};++/**+ * Collect all style sources and their selections from a set of instances.+ * Returns the style sources, their selections, and the styles associated with them.+ * This is typically used when extracting a fragment of instances.+ */+export const collectStyleSourcesFromInstances = ({+ instanceIds,+ styleSourceSelections,+ styleSources,+ styles,+}: {+ instanceIds: Set<Instance["id"]>;+ styleSourceSelections: StyleSourceSelections;+ styleSources: StyleSources;+ styles: Styles;+}): {+ styleSourceSelectionsArray: StyleSourceSelection[];+ styleSourcesMap: StyleSources;+ stylesArray: StyleDecl[];+} => {+ const styleSourceSelectionsArray: StyleSourceSelection[] = [];+ const styleSourcesMap: StyleSources = new Map();++ // Collect all style sources bound to these instances+ for (const instanceId of instanceIds) {+ const styleSourceSelection = styleSourceSelections.get(instanceId);+ if (styleSourceSelection) {+ styleSourceSelectionsArray.push(styleSourceSelection);+ for (const styleSourceId of styleSourceSelection.values) {+ if (styleSourcesMap.has(styleSourceId)) {+ continue;+ }+ const styleSource = styleSources.get(styleSourceId);+ if (styleSource === undefined) {+ continue;+ }+ styleSourcesMap.set(styleSourceId, styleSource);+ }+ }+ }++ // Collect styles bound to these style sources+ const stylesArray: StyleDecl[] = [];+ for (const styleDecl of styles.values()) {+ if (styleSourcesMap.has(styleDecl.styleSourceId)) {+ stylesArray.push(styleDecl);+ }+ }++ return {+ styleSourceSelectionsArray,+ styleSourcesMap,+ stylesArray,+ };+};++/**+ * Find tokens that have duplicates based on:+ * 1. Identical styles (same CSS signature)+ * 2. Same token name+ *+ * Returns a map where keys are token IDs and values are arrays of duplicate token IDs.+ * Only includes tokens that have at least one duplicate.+ */+export const findDuplicateTokens = ({+ styleSources,+ styles,+ breakpoints,+}: {+ styleSources: StyleSources;+ styles: Styles;+ breakpoints: Map<Breakpoint["id"], Breakpoint>;+}): Map<StyleSource["id"], StyleSource["id"][]> => {+ const duplicatesMap = new Map<StyleSource["id"], StyleSource["id"][]>();+ const stylesArray = Array.from(styles.values());+ const tokens = Array.from(styleSources.values()).filter(+ (source): source is Extract<StyleSource, { type: "token" }> =>+ source.type === "token"+ );++ // Build a map of signature -> token IDs+ const signatureToTokenIds = new Map<string, StyleSource["id"][]>();+ // Build a map of name -> token IDs+ const nameToTokenIds = new Map<string, StyleSource["id"][]>();++ for (const token of tokens) {+ // Group by signature (identical styles)+ const signature = getStyleSourceStylesSignature(+ token.id,+ stylesArray,+ breakpoints,+ new Map()+ );++ if (!signatureToTokenIds.has(signature)) {+ signatureToTokenIds.set(signature, []);+ }+ signatureToTokenIds.get(signature)!.push(token.id);++ // Group by name (same token name)+ if (!nameToTokenIds.has(token.name)) {+ nameToTokenIds.set(token.name, []);+ }+ nameToTokenIds.get(token.name)!.push(token.id);+ }++ // Build the duplicates map - include tokens with signature OR name duplicates+ const processedTokens = new Set<StyleSource["id"]>();++ for (const [_signature, tokenIds] of signatureToTokenIds) {+ if (tokenIds.length > 1) {+ for (const tokenId of tokenIds) {+ if (!duplicatesMap.has(tokenId)) {+ duplicatesMap.set(tokenId, []);+ }+ const duplicates = tokenIds.filter((id) => id !== tokenId);+ duplicatesMap.get(tokenId)!.push(...duplicates);+ processedTokens.add(tokenId);+ }+ }+ }++ for (const [_name, tokenIds] of nameToTokenIds) {+ if (tokenIds.length > 1) {+ for (const tokenId of tokenIds) {+ if (!duplicatesMap.has(tokenId)) {+ duplicatesMap.set(tokenId, []);+ }+ const duplicates = tokenIds.filter((id) => id !== tokenId);+ // Avoid adding the same duplicate twice+ for (const duplicate of duplicates) {+ if (!duplicatesMap.get(tokenId)!.includes(duplicate)) {+ duplicatesMap.get(tokenId)!.push(duplicate);+ }+ }+ }+ }+ }++ return duplicatesMap;+};diff --git a/apps/builder/app/shared/token-conflict-dialog.tsx b/apps/builder/app/shared/token-conflict-dialog.tsxnew file mode 100644index 0000000000..e10f6110fd--- /dev/null+++ b/apps/builder/app/shared/token-conflict-dialog.tsx@@ -0,0 +1,223 @@+import { useState } from "react";+import { atom } from "nanostores";+import { useStore } from "@nanostores/react";+import {+ Dialog,+ DialogContent,+ DialogTitle,+ DialogDescription,+ DialogActions,+ Button,+ Flex,+ Text,+ theme,+ RadioGroup,+ Radio,+ Label,+} from "@webstudio-is/design-system";+import type { TokenConflict } from "./style-source-utils";++export type ConflictResolution = "ours" | "theirs" | "merge";++type DialogState =+ | {+ conflicts: TokenConflict[];+ resolve: (resolution: ConflictResolution) => void;+ }+ | undefined;++const $tokenConflictDialogState = atom<DialogState>(undefined);++export const showTokenConflictDialog = (+ conflicts: Array<{+ tokenName: string;+ fragmentTokenId: string;+ }>+): Promise<ConflictResolution> => {+ return new Promise((resolve) => {+ const fullConflicts: TokenConflict[] = conflicts.map((c) => ({+ tokenName: c.tokenName,+ fragmentTokenId: c.fragmentTokenId,+ fragmentToken: {+ type: "token" as const,+ id: c.fragmentTokenId,+ name: c.tokenName,+ },+ existingToken: {+ type: "token" as const,+ id: "existing",+ name: c.tokenName,+ },+ }));++ $tokenConflictDialogState.set({+ conflicts: fullConflicts,+ resolve,+ });+ });+};++export const TokenConflictDialog = () => {+ const dialogState = useStore($tokenConflictDialogState);+ const [resolution, setResolution] = useState<ConflictResolution | undefined>(+ "theirs"+ );++ if (!dialogState) {+ return;+ }++ const { conflicts, resolve } = dialogState;++ const handleClose = () => {+ $tokenConflictDialogState.set(undefined);+ setResolution("theirs");+ };++ const handleResolve = () => {+ if (resolution) {+ resolve(resolution);+ handleClose();+ }+ };++ const handleCancel = () => {+ handleClose();+ };++ if (conflicts.length === 0) {+ return null;+ }++ const conflictCount = conflicts.length;+ const firstConflict = conflicts[0];++ return (+ <Dialog+ open={true}+ onOpenChange={(open) => {+ if (!open) {+ handleCancel();+ }+ }}+ >+ <DialogContent css={{ minWidth: "40ch" }}>+ <DialogTitle>Token conflict detected</DialogTitle>+ <Flex+ direction="column"+ gap="2"+ css={{+ padding: theme.panel.padding,+ }}+ >+ <DialogDescription asChild>+ <Text as="p">+ {conflictCount === 1+ ? `The token "${firstConflict.tokenName}" already exists with different styles.`+ : `${conflictCount} tokens already exist with the same names but different styles.`}+ </Text>+ </DialogDescription>++ <RadioGroup+ value={resolution}+ onValueChange={(value) =>+ setResolution(value as ConflictResolution)+ }+ >+ <Flex direction="column" gap="1">+ <Label>+ <Flex+ gap="2"+ css={{+ padding: theme.spacing[3],+ cursor: "pointer",+ borderRadius: theme.borderRadius[4],+ "&:hover": {+ backgroundColor: theme.colors.backgroundHover,+ },+ }}+ >+ <Radio value="theirs" />+ <Flex direction="column" gap="1">+ <Text variant="labelsTitleCase">Theirs</Text>+ <Text color="subtle">+ Keep incoming tokens with a suffix added to their names+ (e.g., "primary-color-1")+ </Text>+ </Flex>+ </Flex>+ </Label>++ <Label>+ <Flex+ gap="2"+ css={{+ padding: theme.spacing[3],+ cursor: "pointer",+ borderRadius: theme.borderRadius[4],+ "&:hover": {+ backgroundColor: theme.colors.backgroundHover,+ },+ }}+ >+ <Radio value="ours" />+ <Flex direction="column" gap="1">+ <Text variant="labelsTitleCase">Ours</Text>+ <Text color="subtle">+ Discard incoming tokens and use your existing project+ tokens instead+ </Text>+ </Flex>+ </Flex>+ </Label>++ <Label>+ <Flex+ gap="2"+ css={{+ padding: theme.spacing[3],+ cursor: "pointer",+ borderRadius: theme.borderRadius[4],+ "&:hover": {+ backgroundColor: theme.colors.backgroundHover,+ },+ }}+ >+ <Radio value="merge" />+ <Flex direction="column" gap="1">+ <Text variant="labelsTitleCase">Merge</Text>+ <Text color="subtle">+ Combine both into your existing token (incoming styles+ override existing ones)+ </Text>+ </Flex>+ </Flex>+ </Label>+ </Flex>+ </RadioGroup>++ <Flex as="details" direction="column" gap="1">+ <Text as="summary">Show conflicting tokens</Text>+ <Text+ color="subtle"+ css={{+ maxHeight: 150,+ overflow: "auto",+ }}+ >+ {conflicts.map((conflict) => conflict.tokenName).join(", ")}+ </Text>+ </Flex>+ </Flex>+ <DialogActions>+ <Button color="positive" onClick={handleResolve}>+ Continue+ </Button>+ <Button color="ghost" onClick={handleCancel}>+ Cancel+ </Button>+ </DialogActions>+ </DialogContent>+ </Dialog>+ );+};diff --git a/packages/design-system/src/__generated__/figma-design-tokens.ts b/packages/design-system/src/__generated__/figma-design-tokens.tsindex 97b4e01569..40367790b1 100644--- a/packages/design-system/src/__generated__/figma-design-tokens.ts+++ b/packages/design-system/src/__generated__/figma-design-tokens.ts@@ -98,7 +98,6 @@ export const typography = {fontSize: "12px",lineHeight: "16px",letterSpacing: "0.01em",- textTransform: "capitalize",textDecoration: "none",textIndent: "0px",},diff --git a/packages/design-system/src/components/command.tsx b/packages/design-system/src/components/command.tsxindex 45560b3bf1..7f3276cad5 100644--- a/packages/design-system/src/components/command.tsx+++ b/packages/design-system/src/components/command.tsx@@ -406,7 +406,7 @@ export const CommandItem = ({};export const CommandGroupHeading = styled("div", {- ...textVariants.titles,+ ...textVariants.labelsSentenceCase,color: theme.colors.foregroundMoreSubtle,display: "flex",gap: theme.spacing[5],@@ -416,7 +416,7 @@ export const CommandGroupHeading = styled("div", {});export const CommandGroupFooter = styled("div", {- ...textVariants.titles,+ ...textVariants.labelsSentenceCase,color: theme.colors.foregroundMoreSubtle,display: "flex",gap: theme.spacing[5],diff --git a/packages/design-system/src/components/dialog.tsx b/packages/design-system/src/components/dialog.tsxindex b915608514..5d000cbc1e 100644--- a/packages/design-system/src/components/dialog.tsx+++ b/packages/design-system/src/components/dialog.tsx@@ -684,7 +684,7 @@ export const DialogTitleActions = ({ children }: { children: ReactNode }) => {export const DialogActions = ({ children }: { children: ReactNode }) => {return (<Flex- gap="1"+ gap="2"css={{padding: theme.panel.padding,// Making sure the tab order is the last item first.