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: Add token conflict detection and resolution for marketplace templates (#5609)
Oleg Isonend339dc55cfe3
diff --git a/apps/builder/app/builder/features/marketplace/templates.tsx b/apps/builder/app/builder/features/marketplace/templates.tsxindex f8ec624429..e6e2f3a1a4 100644--- a/apps/builder/app/builder/features/marketplace/templates.tsx+++ b/apps/builder/app/builder/features/marketplace/templates.tsx@@ -26,9 +26,12 @@ import { builderUrl } from "~/shared/router-utils";import {extractWebstudioFragment,findClosestInsertable,+ detectFragmentTokenConflicts,+ detectPageTokenConflicts,insertWebstudioFragmentAt,updateWebstudioData,} from "~/shared/instance-utils";+import { builderApi } from "~/shared/builder-api";import { insertPageCopyMutable } from "~/shared/page-utils";import { Card } from "./card";import type { MarketplaceOverviewItem } from "~/shared/marketplace/types";@@ -43,7 +46,7 @@ const isBody = (instance: Instance) =>* - Currently only supports inserting everything from the body* - Could be extended to support children of some other instance e.g. Marketplace Item*/-const insertSection = ({+const insertSection = async ({data,instanceId,}: {@@ -66,22 +69,33 @@ const insertSection = ({if (insertable.position === "end") {insertable.position = "after";}- insertWebstudioFragmentAt(fragment, insertable);+ const conflicts = detectFragmentTokenConflicts({ fragment });+ const conflictResolution =+ conflicts.length > 0+ ? await builderApi.showTokenConflictDialog(conflicts)+ : "theirs";+ insertWebstudioFragmentAt(fragment, insertable, conflictResolution);}};-const insertPage = ({+const insertPage = async ({data: sourceData,pageId,}: {data: WebstudioData;pageId: Page["id"];}) => {+ const conflicts = detectPageTokenConflicts({ sourceData, pageId });+ const conflictResolution =+ conflicts.length > 0+ ? await builderApi.showTokenConflictDialog(conflicts)+ : "theirs";let newPageId: undefined | Page["id"];updateWebstudioData((targetData) => {newPageId = insertPageCopyMutable({source: { data: sourceData, pageId },target: { data: targetData, folderId: ROOT_FOLDER_ID },+ conflictResolution,});});if (newPageId) {@@ -213,6 +227,8 @@ export const Templates = ({insertSection({data,instanceId: templateData.rootInstanceId,+ }).catch(() => {+ // User cancelled conflict dialog});}if (@@ -222,6 +238,8 @@ export const Templates = ({insertPage({data,pageId: templateData.pageId,+ }).catch(() => {+ // User cancelled conflict dialog});}}}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 11b35f3fb1..03d91b2231 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@@ -2,6 +2,7 @@ import type { Instance, Instances } from "@webstudio-is/sdk";import { blockTemplateComponent } from "@webstudio-is/sdk";import { shallowEqual } from "shallow-equal";import { selectInstance } from "~/shared/awareness";+import { builderApi } from "~/shared/builder-api";import { findAvailableVariables } from "~/shared/data-variables";import {extractWebstudioFragment,@@ -10,7 +11,7 @@ import {insertInstanceChildrenMutable,insertWebstudioFragmentCopy,updateWebstudioData,- insertFragmentWithConflictResolution,+ detectFragmentTokenConflicts,} from "~/shared/instance-utils";import {$instances,@@ -177,9 +178,11 @@ export const insertTemplateAt = async (};try {- const conflictResolution = await insertFragmentWithConflictResolution({- fragment,- });+ const conflicts = detectFragmentTokenConflicts({ fragment });+ const conflictResolution =+ conflicts.length > 0+ ? await builderApi.showTokenConflictDialog(conflicts)+ : "theirs";updateWebstudioData((data) => {const { newInstanceIds } = insertWebstudioFragmentCopy({diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts b/apps/builder/app/shared/copy-paste/plugin-instance.test.tsindex c1cb1bd3ed..76e66af3a2 100644--- a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts+++ b/apps/builder/app/shared/copy-paste/plugin-instance.test.ts@@ -35,12 +35,9 @@ const expectString = expect.any(String) as unknown as string;enableMapSet();registerContainers();-// Mock insertFragmentWithConflictResolution to always return "theirs"+// Mock detectFragmentTokenConflicts to always return no conflictsbeforeAll(() => {- vi.spyOn(- instanceUtils,- "insertFragmentWithConflictResolution"- ).mockResolvedValue("theirs");+ vi.spyOn(instanceUtils, "detectFragmentTokenConflicts").mockReturnValue([]);});$registeredComponentMetas.set(diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.tsindex 3b6115acbf..f440dbd23e 100644--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts@@ -23,11 +23,12 @@ import {getWebstudioData,insertInstanceChildrenMutable,findClosestInsertable,- insertFragmentWithConflictResolution,+ detectFragmentTokenConflicts,type Insertable,} from "../instance-utils";import { $selectedInstancePath } from "../awareness";import { findAvailableVariables } from "../data-variables";+import { builderApi } from "../builder-api";import type { Plugin } from "./init-copy-paste";const version = "@webstudio/instance/v0.1";@@ -173,9 +174,11 @@ const onPaste = async (clipboardData: string) => {}try {- const conflictResolution = await insertFragmentWithConflictResolution({- fragment,- });+ const conflicts = detectFragmentTokenConflicts({ fragment });+ const conflictResolution =+ conflicts.length > 0+ ? await builderApi.showTokenConflictDialog(conflicts)+ : "theirs";updateWebstudioData((data) => {const { newInstanceIds } = insertWebstudioFragmentCopy({data,diff --git a/apps/builder/app/shared/instance-utils.test.tsx b/apps/builder/app/shared/instance-utils.test.tsxindex e8e0b703e1..7c7651d70f 100644--- a/apps/builder/app/shared/instance-utils.test.tsx+++ b/apps/builder/app/shared/instance-utils.test.tsx@@ -5,10 +5,12 @@ import { createDefaultPages } from "@webstudio-is/project-build";import {$,ws,+ css,expression,renderTemplate,renderData,ResourceValue,+ token,} from "@webstudio-is/template";import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";import * as radixMetas from "@webstudio-is/sdk-components-react-radix/metas";@@ -49,6 +51,7 @@ import {canConvertInstance,convertInstance,deleteSelectedInstance,+ detectPageTokenConflicts,} from "./instance-utils";import type { InstancePath } from "./awareness";import {@@ -126,6 +129,18 @@ const getIdValuePair = <T extends { id: string }>(item: T) =>const toMap = <T extends { id: string }>(list: T[]) =>new Map(list.map(getIdValuePair));+const setDataStores = (data: Omit<WebstudioData, "pages">) => {+ $instances.set(data.instances);+ $breakpoints.set(data.breakpoints);+ $styleSources.set(data.styleSources);+ $styles.set(data.styles);+ $styleSourceSelections.set(data.styleSourceSelections);+ $dataSources.set(data.dataSources);+ $props.set(data.props);+ $assets.set(data.assets);+ $resources.set(data.resources);+};+const createInstance = (id: Instance["id"],component: string,@@ -3575,3 +3590,446 @@ describe("deleteSelectedInstance", () => {expect($awareness.get()?.instanceSelector).toEqual(["parent", "body"]);});});++describe("insertWebstudioFragmentAt with conflictResolution", () => {+ beforeEach(() => {+ $project.set({ id: "project-id" } as Project);+ });++ test("uses conflictResolution='theirs' by default (creates new token with suffix)", () => {+ // Existing project with a "primary" token (used by existing-box)+ const data = renderData(+ <$.Body ws:id="body">+ <$.Box+ ws:id="existing-box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: blue;+ `+ ),+ ]}+ ></$.Box>+ </$.Body>+ );++ // Create fragment with token that has same name but different styles+ const fragment = renderTemplate(+ <$.Box+ ws:id="box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: red;+ `+ ),+ ]}+ ></$.Box>+ );++ setDataStores(data);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $awareness.set({ pageId: pages.homePage.id });+ selectInstance(["body"]);++ // Insert without explicit conflictResolution (defaults to "theirs")+ insertWebstudioFragmentAt(fragment, {+ parentSelector: ["body"],+ position: "end",+ });++ // The existing token should still have blue color (unchanged)+ const styles = Array.from($styles.get().values());+ const styleSources = Array.from($styleSources.get().values());+ const existingToken = styleSources.find(+ (s) => s.type === "token" && s.name === "primary"+ );+ const existingTokenStyle = styles.find(+ (s) =>+ s.styleSourceId === existingToken?.id &&+ s.property === "color" &&+ s.breakpointId === "base"+ );+ expect(existingTokenStyle?.value).toEqual({+ type: "keyword",+ value: "blue",+ });++ // A new token "primary-1" should be created with red color+ const newToken = styleSources.find(+ (s) => s.type === "token" && s.name === "primary-1"+ );+ expect(newToken).toBeDefined();+ const newTokenStyle = styles.find(+ (s) =>+ s.styleSourceId === newToken?.id &&+ s.property === "color" &&+ s.breakpointId === "base"+ );+ expect(newTokenStyle?.value).toEqual({ type: "keyword", value: "red" });+ });++ test("uses conflictResolution='ours' to keep existing token styles", () => {+ // Existing project with a "primary" token (used by existing-box)+ const data = renderData(+ <$.Body ws:id="body">+ <$.Box+ ws:id="existing-box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: blue;+ `+ ),+ ]}+ ></$.Box>+ </$.Body>+ );++ const fragment = renderTemplate(+ <$.Box+ ws:id="box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: red;+ `+ ),+ ]}+ ></$.Box>+ );++ setDataStores(data);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $awareness.set({ pageId: pages.homePage.id });+ selectInstance(["body"]);++ // Insert with conflictResolution="ours" to keep existing styles+ insertWebstudioFragmentAt(+ fragment,+ {+ parentSelector: ["body"],+ position: "end",+ },+ "ours"+ );++ // The existing token should still have blue color (kept original)+ const styles = Array.from($styles.get().values());+ const styleSources = Array.from($styleSources.get().values());+ const existingToken = styleSources.find(+ (s) => s.type === "token" && s.name === "primary"+ );+ const primaryTokenStyle = styles.find(+ (s) =>+ s.styleSourceId === existingToken?.id &&+ s.property === "color" &&+ s.breakpointId === "base"+ );+ expect(primaryTokenStyle?.value).toEqual({+ type: "keyword",+ value: "blue",+ });++ // No new token should be created+ const newToken = styleSources.find(+ (s) => s.type === "token" && s.name === "primary-1"+ );+ expect(newToken).toBeUndefined();+ });++ test("uses conflictResolution='merge' to merge styles (theirs overrides)", () => {+ // Existing project with a "primary" token that has color and fontSize+ const data = renderData(+ <$.Body ws:id="body">+ <$.Box+ ws:id="existing-box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: blue;+ font-size: 16px;+ `+ ),+ ]}+ ></$.Box>+ </$.Body>+ );++ // Fragment with same "primary" token but different color and new property+ const fragment = renderTemplate(+ <$.Box+ ws:id="box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: red;+ font-weight: bold;+ `+ ),+ ]}+ ></$.Box>+ );++ setDataStores(data);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $awareness.set({ pageId: pages.homePage.id });+ selectInstance(["body"]);++ // Insert with conflictResolution="merge"+ insertWebstudioFragmentAt(+ fragment,+ {+ parentSelector: ["body"],+ position: "end",+ },+ "merge"+ );++ // The existing token should now have red color (overridden by fragment)+ const styles = Array.from($styles.get().values());+ const styleSources = Array.from($styleSources.get().values());+ const existingToken = styleSources.find(+ (s) => s.type === "token" && s.name === "primary"+ );+ const colorStyle = styles.find(+ (s) =>+ s.styleSourceId === existingToken?.id &&+ s.property === "color" &&+ s.breakpointId === "base"+ );+ expect(colorStyle?.value).toEqual({ type: "keyword", value: "red" });++ // fontSize should still be there (not in fragment, so kept)+ const fontSizeStyle = styles.find(+ (s) =>+ s.styleSourceId === existingToken?.id &&+ s.property === "fontSize" &&+ s.breakpointId === "base"+ );+ expect(fontSizeStyle?.value).toEqual({+ type: "unit",+ value: 16,+ unit: "px",+ });++ // fontWeight should be added from fragment+ const fontWeightStyle = styles.find(+ (s) =>+ s.styleSourceId === existingToken?.id &&+ s.property === "fontWeight" &&+ s.breakpointId === "base"+ );+ expect(fontWeightStyle?.value).toEqual({ type: "keyword", value: "bold" });++ // No new token should be created+ const newToken = styleSources.find(+ (s) => s.type === "token" && s.name === "primary-1"+ );+ expect(newToken).toBeUndefined();+ });+});++describe("detectPageTokenConflicts", () => {+ beforeEach(() => {+ $project.set({ id: "project-id" } as Project);+ });++ test("returns empty array when no conflicts exist", () => {+ // Set up target project data (no tokens)+ const targetData = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="existing-box"></$.Box>+ </$.Body>+ );+ setDataStores(targetData);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);++ // Create source data with a token+ const sourceData = renderData(+ <$.Body ws:id="source-body">+ <$.Box+ ws:id="source-box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: red;+ `+ ),+ ]}+ ></$.Box>+ </$.Body>+ );+ const sourcePages = createDefaultPages({ rootInstanceId: "source-body" });+ const sourceWebstudioData: WebstudioData = {+ ...sourceData,+ pages: sourcePages,+ };++ const conflicts = detectPageTokenConflicts({+ sourceData: sourceWebstudioData,+ pageId: sourcePages.homePage.id,+ });++ // No conflicts+ expect(conflicts).toEqual([]);+ });++ test("returns conflicts when token conflicts exist", () => {+ // Set up target project with a "primary" token+ const targetData = renderData(+ <$.Body ws:id="body">+ <$.Box+ ws:id="existing-box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: blue;+ `+ ),+ ]}+ ></$.Box>+ </$.Body>+ );+ setDataStores(targetData);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);++ // Create source data with same "primary" token but different styles+ const sourceData = renderData(+ <$.Body ws:id="source-body">+ <$.Box+ ws:id="source-box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: red;+ `+ ),+ ]}+ ></$.Box>+ </$.Body>+ );+ const sourcePages = createDefaultPages({ rootInstanceId: "source-body" });+ const sourceWebstudioData: WebstudioData = {+ ...sourceData,+ pages: sourcePages,+ };++ const conflicts = detectPageTokenConflicts({+ sourceData: sourceWebstudioData,+ pageId: sourcePages.homePage.id,+ });++ // Should return conflicts+ expect(conflicts.length).toBeGreaterThan(0);+ expect(conflicts[0].tokenName).toBe("primary");+ });++ test("detects conflicts from ROOT_INSTANCE tokens", () => {+ // Set up target project with a "header" token+ const targetData = renderData(+ <$.Body ws:id="body">+ <$.Box+ ws:id="existing-box"+ ws:tokens={[+ token(+ "header",+ css`+ background: white;+ `+ ),+ ]}+ ></$.Box>+ </$.Body>+ );+ setDataStores(targetData);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);++ // Create source data with a ROOT_INSTANCE that has conflicting "header" token+ const sourceBodyData = renderData(+ <$.Body ws:id="source-body">+ <$.Box ws:id="source-box"></$.Box>+ </$.Body>+ );+ // Add a global "header" token with different styles (simulating ROOT_INSTANCE content)+ const headerTokenId = "header-token-id";+ sourceBodyData.styleSources.set(headerTokenId, {+ type: "token",+ id: headerTokenId,+ name: "header",+ });+ const baseBreakpointId = Array.from(+ sourceBodyData.breakpoints.values()+ ).find((b) => b.minWidth === undefined)?.id;+ if (baseBreakpointId) {+ sourceBodyData.styles.set(`${headerTokenId}:base:backgroundColor`, {+ styleSourceId: headerTokenId,+ breakpointId: baseBreakpointId,+ property: "backgroundColor",+ value: { type: "keyword", value: "black" },+ });+ }+ // Add ROOT_INSTANCE with the header token+ sourceBodyData.instances.set(ROOT_INSTANCE_ID, {+ type: "instance",+ id: ROOT_INSTANCE_ID,+ component: "Box",+ children: [],+ });+ sourceBodyData.styleSourceSelections.set(ROOT_INSTANCE_ID, {+ instanceId: ROOT_INSTANCE_ID,+ values: [headerTokenId],+ });++ const sourcePages = createDefaultPages({ rootInstanceId: "source-body" });+ const sourceWebstudioData: WebstudioData = {+ ...sourceBodyData,+ pages: sourcePages,+ };++ const conflicts = detectPageTokenConflicts({+ sourceData: sourceWebstudioData,+ pageId: sourcePages.homePage.id,+ });++ // Should detect conflict from ROOT_INSTANCE token+ expect(conflicts.length).toBeGreaterThan(0);+ expect(conflicts[0].tokenName).toBe("header");+ });++ test("throws error when page not found", () => {+ const targetData = renderData(<$.Body ws:id="body"></$.Body>);+ setDataStores(targetData);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);++ const sourceData = renderData(<$.Body ws:id="source-body"></$.Body>);+ const sourcePages = createDefaultPages({ rootInstanceId: "source-body" });+ const sourceWebstudioData: WebstudioData = {+ ...sourceData,+ pages: sourcePages,+ };++ expect(() =>+ detectPageTokenConflicts({+ sourceData: sourceWebstudioData,+ pageId: "non-existent-page-id",+ })+ ).toThrow("Page not found");+ });+});diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.tsindex 2bb0330a76..22762c9039 100644--- a/apps/builder/app/shared/instance-utils.ts+++ b/apps/builder/app/shared/instance-utils.ts@@ -333,7 +333,8 @@ export const insertWebstudioElementAt = (insertable?: Insertable) => {export const insertWebstudioFragmentAt = (fragment: WebstudioFragment,- insertable?: Insertable+ insertable?: Insertable,+ conflictResolution?: ConflictResolution): boolean => {// cannot insert empty fragmentif (fragment.children.length === 0) {@@ -361,6 +362,7 @@ export const insertWebstudioFragmentAt = (startingInstanceId: instancePath[0].instance.id,}),projectId: project.id,+ conflictResolution,});const children: Instance["children"] = fragment.children.map((child) => {if (child.type === "id") {@@ -1786,28 +1788,24 @@ export const buildInstancePath = (};/**- * Detects token conflicts and shows resolution dialog if needed.- * Returns the conflict resolution strategy to use.+ * Detects token conflicts for a fragment insertion.** @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+ * @returns Array of token conflicts (empty if no conflicts)*/-export const insertFragmentWithConflictResolution = async ({+export const detectFragmentTokenConflicts = ({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({+ return detectTokenConflicts({fragmentStyleSources: fragment.styleSources,fragmentStyles: fragment.styles,existingStyleSources: data.styleSources,@@ -1815,12 +1813,60 @@ export const insertFragmentWithConflictResolution = async ({breakpoints: data.breakpoints,mergedBreakpointIds,});+};++/**+ * Detects token conflicts for a page insertion.+ * Combines fragments from ROOT_INSTANCE and page body for conflict detection.+ *+ * @param sourceData - The source webstudio data containing the page+ * @param pageId - The page ID to check for conflicts+ * @returns Array of token conflicts (empty if no conflicts)+ */+export const detectPageTokenConflicts = ({+ sourceData,+ pageId,+}: {+ sourceData: WebstudioData;+ pageId: string;+}) => {+ const data = getWebstudioData();- if (conflicts.length === 0) {- // No conflicts, use theirs (doesn't matter which since there are no conflicts)- return "theirs";+ const page = sourceData.pages.pages.find((p) => p.id === pageId);+ if (page === undefined && sourceData.pages.homePage.id !== pageId) {+ throw new Error("Page not found");}+ const targetPage = page ?? sourceData.pages.homePage;- // Show conflict dialog and wait for user choice- return await builderApi.showTokenConflictDialog(conflicts);+ // Extract fragments for both ROOT_INSTANCE and page body+ const rootFragment = extractWebstudioFragment(sourceData, ROOT_INSTANCE_ID);+ const pageFragment = extractWebstudioFragment(+ sourceData,+ targetPage.rootInstanceId+ );++ // Combine style sources and styles from both fragments+ const combinedStyleSources = [+ ...rootFragment.styleSources,+ ...pageFragment.styleSources,+ ];+ const combinedStyles = [...rootFragment.styles, ...pageFragment.styles];+ const combinedBreakpoints = [+ ...rootFragment.breakpoints,+ ...pageFragment.breakpoints,+ ];++ const mergedBreakpointIds = buildMergedBreakpointIds(+ combinedBreakpoints,+ data.breakpoints+ );++ return detectTokenConflicts({+ fragmentStyleSources: combinedStyleSources,+ fragmentStyles: combinedStyles,+ existingStyleSources: data.styleSources,+ existingStyles: data.styles,+ breakpoints: data.breakpoints,+ mergedBreakpointIds,+ });};diff --git a/apps/builder/app/shared/page-utils.ts b/apps/builder/app/shared/page-utils.tsindex 6493fa6989..9fc82b96d3 100644--- a/apps/builder/app/shared/page-utils.ts+++ b/apps/builder/app/shared/page-utils.ts@@ -23,6 +23,7 @@ import {unsetExpressionVariables,} from "./data-variables";import { $project } from "./nano-states";+import type { ConflictResolution } from "./token-conflict-dialog";const deduplicateName = (pages: Pages,@@ -94,9 +95,11 @@ const replaceDataSources = (export const insertPageCopyMutable = ({source,target,+ conflictResolution,}: {source: { data: WebstudioData; pageId: Page["id"] };target: { data: WebstudioData; folderId: Folder["id"] };+ conflictResolution?: ConflictResolution;}) => {const project = $project.get();const page = findPageByIdOrPath(source.pageId, source.data.pages);@@ -112,6 +115,7 @@ export const insertPageCopyMutable = ({startingInstanceId: ROOT_INSTANCE_ID,}),projectId: project.id,+ conflictResolution,});const unsetVariables = new Set<DataSource["id"]>();const unsetNameById = new Map<DataSource["id"], DataSource["name"]>();@@ -136,6 +140,7 @@ export const insertPageCopyMutable = ({}),availableVariables,projectId: project.id,+ conflictResolution,});// unwrap page draftconst newPage = structuredClone(unwrap(page));diff --git a/packages/template/src/jsx.test.tsx b/packages/template/src/jsx.test.tsxindex 0bddf27cb6..d1a7a4c88e 100644--- a/packages/template/src/jsx.test.tsx+++ b/packages/template/src/jsx.test.tsx@@ -10,6 +10,7 @@ import {PlaceholderValue,renderTemplate,ResourceValue,+ token,Variable,ws,} from "./jsx";@@ -280,6 +281,196 @@ test("avoid generating style data without styles", () => {expect(styles).toEqual([]);});+test("generate token styles", () => {+ const { breakpoints, styleSources, styleSourceSelections, styles } =+ renderTemplate(+ <$.Body+ ws:id="body"+ ws:tokens={[+ token(+ "primary",+ css`+ color: red;+ `+ ),+ ]}+ ></$.Body>+ );+ expect(breakpoints).toEqual([{ id: "base", label: "" }]);+ expect(styleSources).toEqual([{ id: "0", type: "token", name: "primary" }]);+ expect(styleSourceSelections).toEqual([+ { instanceId: "body", values: ["0"] },+ ]);+ expect(styles).toEqual([+ {+ breakpointId: "base",+ styleSourceId: "0",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+});++test("generate multiple tokens on single instance", () => {+ const { styleSources, styleSourceSelections, styles } = renderTemplate(+ <$.Body+ ws:id="body"+ ws:tokens={[+ token(+ "primary",+ css`+ color: red;+ `+ ),+ token(+ "secondary",+ css`+ font-size: 16px;+ `+ ),+ ]}+ ></$.Body>+ );+ expect(styleSources).toEqual([+ { id: "0", type: "token", name: "primary" },+ { id: "1", type: "token", name: "secondary" },+ ]);+ expect(styleSourceSelections).toEqual([+ { instanceId: "body", values: ["0", "1"] },+ ]);+ expect(styles).toHaveLength(2);+});++test("reuse same token across multiple instances", () => {+ const primary = token(+ "primary",+ css`+ color: red;+ `+ );+ const { styleSources, styleSourceSelections, styles } = renderTemplate(+ <$.Body ws:id="body" ws:tokens={[primary]}>+ <$.Box ws:id="box" ws:tokens={[primary]}></$.Box>+ </$.Body>+ );+ // Token should only be created once+ expect(styleSources).toEqual([{ id: "0", type: "token", name: "primary" }]);+ // Both instances should reference the same token+ expect(styleSourceSelections).toEqual([+ { instanceId: "body", values: ["0"] },+ { instanceId: "box", values: ["0"] },+ ]);+ // Styles should only be created once+ expect(styles).toEqual([+ {+ breakpointId: "base",+ styleSourceId: "0",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+});++test("combine local styles with tokens", () => {+ const { styleSources, styleSourceSelections, styles } = renderTemplate(+ <$.Body+ ws:id="body"+ ws:style={css`+ font-size: 16px;+ `}+ ws:tokens={[+ token(+ "primary",+ css`+ color: red;+ `+ ),+ ]}+ ></$.Body>+ );+ // Both local and token style sources+ expect(styleSources).toEqual([+ { id: "body:ws:style", type: "local" },+ { id: "0", type: "token", name: "primary" },+ ]);+ // Selection should have both local style source and token+ expect(styleSourceSelections).toEqual([+ { instanceId: "body", values: ["body:ws:style", "0"] },+ ]);+ expect(styles).toHaveLength(2);+});++test("generate token with breakpoints", () => {+ const { breakpoints, styles } = renderTemplate(+ <$.Body+ ws:id="body"+ ws:tokens={[+ token(+ "responsive",+ css`+ color: red;+ @media (min-width: 1024px) {+ color: blue;+ }+ `+ ),+ ]}+ ></$.Body>+ );+ expect(breakpoints).toEqual([+ { id: "base", label: "" },+ { id: "0", label: "1024", minWidth: 1024 },+ ]);+ expect(styles).toEqual([+ {+ breakpointId: "base",+ styleSourceId: "0",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ breakpointId: "0",+ styleSourceId: "0",+ property: "color",+ value: { type: "keyword", value: "blue" },+ },+ ]);+});++test("generate token with state", () => {+ const { styles } = renderTemplate(+ <$.Body+ ws:id="body"+ ws:tokens={[+ token(+ "interactive",+ css`+ color: red;+ &:hover {+ color: blue;+ }+ `+ ),+ ]}+ ></$.Body>+ );+ expect(styles).toEqual([+ {+ breakpointId: "base",+ styleSourceId: "0",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ breakpointId: "base",+ styleSourceId: "0",+ state: ":hover",+ property: "color",+ value: { type: "keyword", value: "blue" },+ },+ ]);+});+test("generate breakpoints", () => {const { breakpoints, styleSources, styleSourceSelections, styles } =renderTemplate(diff --git a/packages/template/src/jsx.ts b/packages/template/src/jsx.tsindex 3189da1f9d..2428dcb7f5 100644--- a/packages/template/src/jsx.ts+++ b/packages/template/src/jsx.ts@@ -16,6 +16,19 @@ import { showAttribute } from "@webstudio-is/react-sdk";import type { TemplateStyleDecl } from "./css";import { camelCaseProperty, parseMediaQuery } from "@webstudio-is/css-data";+export class Token {+ name: string;+ styles: TemplateStyleDecl[];+ constructor(name: string, styles: TemplateStyleDecl[]) {+ this.name = name;+ this.styles = styles;+ }+}++export const token = (name: string, styles: TemplateStyleDecl[]): Token => {+ return new Token(name, styles);+};+export class Variable {name: string;initialValue: unknown;@@ -268,6 +281,16 @@ export const renderTemplate = (Instance["id"],TemplateStyleDecl[]>();+ const tokensByInstanceId = new Map<Instance["id"], Token[]>();+ const tokenIdByToken = new Map<Token, string>();+ const getTokenId = (token: Token) => {+ let id = tokenIdByToken.get(token);+ if (id === undefined) {+ id = getIdByKey(token);+ tokenIdByToken.set(token, id);+ }+ return id;+ };const convertElementToInstance = (element: JSX.Element): Instance["children"][number] => {@@ -289,6 +312,12 @@ export const renderTemplate = (localStylesByInstanceId.set(instanceId, localStyles);continue;}+ if (name === "ws:tokens") {+ const tokens = value as Token[];+ // create tokens with breakpoints later to ensure more stable ids+ tokensByInstanceId.set(instanceId, tokens);+ continue;+ }if (name === "ws:show") {name = showAttribute;}@@ -409,6 +438,50 @@ export const renderTemplate = (});}}+ // process tokens and add them to style sources+ const processedTokens = new Set<Token>();+ for (const [instanceId, tokens] of tokensByInstanceId) {+ const tokenIds: string[] = [];+ for (const token of tokens) {+ const tokenId = getTokenId(token);+ tokenIds.push(tokenId);+ // only create style source and styles once per token+ if (processedTokens.has(token)) {+ continue;+ }+ processedTokens.add(token);+ styleSources.push({+ type: "token",+ id: tokenId,+ name: token.name,+ });+ for (const { breakpoint, state, property, value } of token.styles) {+ const breakpointId = getBreakpointId(breakpoint);+ if (breakpointId === undefined) {+ continue;+ }+ styles.push({+ breakpointId,+ styleSourceId: tokenId,+ state,+ property: camelCaseProperty(property),+ value,+ });+ }+ }+ // merge tokens with existing selection (from ws:style) or create new selection+ const existingSelection = styleSourceSelections.find(+ (sel) => sel.instanceId === instanceId+ );+ if (existingSelection) {+ existingSelection.values.push(...tokenIds);+ } else {+ styleSourceSelections.push({+ instanceId,+ values: tokenIds,+ });+ }+ }return {children,instances,