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
Support copy pasting of data sources (#1963)
Bogdan Chadkinb226343599df
diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts b/apps/builder/app/shared/copy-paste/plugin-instance.test.tsnew file mode 100644index 0000000000..645c6b89cf--- /dev/null+++ b/apps/builder/app/shared/copy-paste/plugin-instance.test.ts@@ -0,0 +1,230 @@+import { describe, test, expect } from "@jest/globals";+import { enableMapSet } from "immer";+import type {+ Instance,+ Instances,+ Prop,+ Props,+ DataSource,+ DataSources,+ Page,+} from "@webstudio-is/project-build";+import type { Project } from "@webstudio-is/project";+import { encodeDataSourceVariable } from "@webstudio-is/react-sdk";+import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";+import { registerContainers } from "../sync";+import {+ dataSourcesStore,+ instancesStore,+ pagesStore,+ projectStore,+ propsStore,+ registeredComponentMetasStore,+ selectedInstanceSelectorStore,+ selectedPageIdStore,+} from "../nano-states";+import { onCopy, onPaste } from "./plugin-instance";++enableMapSet();+registerContainers();++registeredComponentMetasStore.set(new Map(Object.entries(baseComponentMetas)));+projectStore.set({ id: "my-project" } as Project);+pagesStore.set({+ homePage: { id: "home-page", rootInstanceId: "body0" } as Page,+ pages: [],+});+selectedPageIdStore.set("home-page");++const createInstance = (+ id: Instance["id"],+ component: string,+ children: Instance["children"]+): Instance => {+ return { type: "instance", id, component, children };+};++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 getMapDifference = <Type extends Map<unknown, unknown>>(+ left: Type,+ right: Type+): Type => {+ const leftSet = new Set(left.keys());+ const rightSet = new Set(right.keys());+ const difference = new Map() as Type;+ for (const [key, value] of left) {+ if (rightSet.has(key) === false) {+ difference.set(key, value);+ }+ }+ for (const [key, value] of right) {+ if (leftSet.has(key) === false) {+ difference.set(key, value);+ }+ }+ return difference;+};++describe("data sources", () => {+ // body0+ // box1+ // box2+ const instances: Instances = toMap([+ createInstance("body0", "Body", [{ type: "id", value: "box1" }]),+ createInstance("box1", "Box", [{ type: "id", value: "box2" }]),+ createInstance("box2", "Box", []),+ ] satisfies Instance[]);+ const dataSources: DataSources = toMap([+ {+ id: "box1$state",+ scopeInstanceId: "box1",+ type: "variable",+ name: "state",+ value: { type: "string", value: "initial" },+ },+ {+ id: "box2$stateInitial",+ scopeInstanceId: "box2",+ type: "expression",+ name: "stateInitial",+ code: `$ws$dataSource$box1$state === 'initial'`,+ },+ ] satisfies DataSource[]);+ const props: Props = toMap([+ {+ id: "box1$state",+ instanceId: "box1",+ type: "dataSource",+ name: "state",+ value: "box1$state",+ },+ {+ id: "box2$state",+ instanceId: "box2",+ type: "dataSource",+ name: "state",+ value: "box1$state",+ },+ {+ id: "box2$show",+ instanceId: "box2",+ type: "dataSource",+ name: "show",+ value: "box2$stateInitial",+ },+ ] satisfies Prop[]);++ test("are copy pasted when scoped to copied instances", () => {+ instancesStore.set(instances);+ propsStore.set(props);+ dataSourcesStore.set(dataSources);+ selectedInstanceSelectorStore.set(["box1", "body0"]);+ const clipboardData = onCopy() ?? "";+ selectedInstanceSelectorStore.set(["body0"]);+ onPaste(clipboardData);++ const instancesDifference = getMapDifference(+ instances,+ instancesStore.get()+ );+ const [newBox1, newBox2] = instancesDifference.keys();++ const dataSourcesDifference = getMapDifference(+ dataSources,+ dataSourcesStore.get()+ );+ const [newDataSource1, newDataSource2] = dataSourcesDifference.keys();+ expect(dataSourcesDifference).toEqual(+ toMap([+ {+ ...dataSources.get("box1$state"),+ id: newDataSource1,+ scopeInstanceId: newBox1,+ },+ {+ ...dataSources.get("box2$stateInitial"),+ id: newDataSource2,+ scopeInstanceId: newBox2,+ code: `${encodeDataSourceVariable(newDataSource1)} === 'initial'`,+ },+ ])+ );++ const propsDifference = getMapDifference(props, propsStore.get());+ const [newProp1, newProp2, newProp3] = propsDifference.keys();+ expect(propsDifference).toEqual(+ toMap([+ {+ ...props.get("box1$state"),+ id: newProp1,+ instanceId: newBox1,+ value: newDataSource1,+ },+ {+ ...props.get("box2$state"),+ id: newProp2,+ instanceId: newBox2,+ value: newDataSource1,+ },+ {+ ...props.get("box2$show"),+ id: newProp3,+ instanceId: newBox2,+ value: newDataSource2,+ },+ ])+ );+ });++ test("are inlined into props when not scoped to copied instances or depends on not scoped data source", () => {+ instancesStore.set(instances);+ propsStore.set(props);+ dataSourcesStore.set(dataSources);+ selectedInstanceSelectorStore.set(["box2", "box1", "body0"]);+ const clipboardData = onCopy() ?? "";+ selectedInstanceSelectorStore.set(["body0"]);+ onPaste(clipboardData);++ const instancesDifference = getMapDifference(+ instances,+ instancesStore.get()+ );+ const [newBox2] = instancesDifference.keys();++ const dataSourcesDifference = getMapDifference(+ dataSources,+ dataSourcesStore.get()+ );+ expect(dataSourcesDifference).toEqual(new Map());++ const propsDifference = getMapDifference(props, propsStore.get());+ const [newProp1, newProp2] = propsDifference.keys();+ expect(propsDifference).toEqual(+ toMap([+ {+ id: newProp1,+ instanceId: newBox2,+ type: "string",+ name: "state",+ value: "initial",+ },+ {+ id: newProp2,+ instanceId: newBox2,+ type: "boolean",+ name: "show",+ value: true,+ },+ ])+ );+ });++ test.todo(+ "preserve data sources not scoped to new instances within same scope"+ );+});diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.tsindex b10eb982f5..88b5203cd4 100644--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts@@ -1,7 +1,9 @@+import { nanoid } from "nanoid";import store from "immerhin";import { z } from "zod";import {Breakpoint,+ DataSource,findTreeInstanceIds,Instance,Prop,@@ -10,6 +12,13 @@ import {StyleSourceSelection,StyleSourceSelections,} from "@webstudio-is/project-build";+import { Asset } from "@webstudio-is/asset-uploader";+import {+ encodeDataSourceVariable,+ validateExpression,+ decodeDataSourceVariable,+ computeExpressionsDependencies,+} from "@webstudio-is/react-sdk";import {propsStore,stylesStore,@@ -23,6 +32,7 @@ import {projectStore,registeredComponentMetasStore,dataSourceValuesStore,+ dataSourcesStore,} from "../nano-states";import {type InstanceSelector,@@ -40,7 +50,6 @@ import {findClosestDroppableTarget,} from "../instance-utils";import { getMapValuesBy, getMapValuesByKeysSet } from "../array-utils";-import { Asset } from "@webstudio-is/asset-uploader";const version = "@webstudio/instance/v0.1";@@ -48,6 +57,7 @@ const InstanceData = z.object({breakpoints: z.array(Breakpoint),instances: z.array(Instance),props: z.array(Prop),+ dataSources: z.array(DataSource),styleSourceSelections: z.array(StyleSourceSelection),styleSources: z.array(StyleSource),styles: z.array(StyleDecl),@@ -182,14 +192,61 @@ const getTreeData = (targetInstanceSelector: InstanceSelector) => {// first item is guaranteed root of copied treeconst treeInstances = getMapValuesByKeysSet(instances, treeInstanceIds);+ const dataSources = dataSourcesStore.get();+ const expressions = new Map<string, string>();+ for (const dataSource of dataSources.values()) {+ if (dataSource.type === "expression") {+ expressions.set(encodeDataSourceVariable(dataSource.id), dataSource.code);+ }+ }+ const dependencies = computeExpressionsDependencies(expressions);++ const treeDataSources = getMapValuesBy(dataSources, (dataSource) => {+ if (dataSource.type === "expression") {+ const expressionDeps = dependencies.get(+ encodeDataSourceVariable(dataSource.id)+ );+ if (expressionDeps) {+ for (const dependency of expressionDeps) {+ const dataSourceId = decodeDataSourceVariable(dependency);+ if (dataSourceId === undefined) {+ continue;+ }+ const dataSource = dataSources.get(dataSourceId);+ if (dataSource === undefined) {+ continue;+ }+ if (+ dataSource.scopeInstanceId === undefined ||+ treeInstanceIds.has(dataSource.scopeInstanceId) === false+ ) {+ return false;+ }+ }+ }+ }+ return (+ dataSource.scopeInstanceId !== undefined &&+ treeInstanceIds.has(dataSource.scopeInstanceId)+ );+ });+ const treeDataSourceIds = new Set(+ treeDataSources.map((dataSource) => dataSource.id)+ );+const dataSourceValues = dataSourceValuesStore.get();const treeProps = getMapValuesBy(propsStore.get(), (prop) =>treeInstanceIds.has(prop.instanceId)).map((prop) => {- // unbind data source from prop- // @todo improve the logic and allow to copy data sources for scoped componentsif (prop.type === "dataSource") {- const value = dataSourceValues.get(prop.value);+ const dataSourceId = prop.value;+ // copy data source if scoped to one of copied instances+ if (treeDataSourceIds.has(dataSourceId)) {+ return prop;+ }+ // convert data source prop to typed prop+ // when data source is not scoped to one of copied instances+ const value = dataSourceValues.get(dataSourceId);return {id: prop.id,instanceId: prop.instanceId,@@ -232,6 +289,7 @@ const getTreeData = (targetInstanceSelector: InstanceSelector) => {breakpoints: treeBreapoints,instances: treeInstances,styleSources: treeStyleSources,+ dataSources: treeDataSources,props: treeProps,styleSourceSelections: treeStyleSourceSelections,styles: treeStyles,@@ -293,6 +351,7 @@ export const onPaste = (clipboardData: string): boolean => {[breakpointsStore,instancesStore,+ dataSourcesStore,styleSourcesStore,propsStore,styleSourceSelectionsStore,@@ -302,6 +361,7 @@ export const onPaste = (clipboardData: string): boolean => {(breakpoints,instances,+ dataSources,styleSources,props,styleSourceSelections,@@ -329,6 +389,49 @@ export const onPaste = (clipboardData: string): boolean => {dropTarget);+ const copiedDataSourceIds = new Map<DataSource["id"], DataSource["id"]>();+ for (const dataSource of data.dataSources) {+ copiedDataSourceIds.set(dataSource.id, nanoid());+ }++ for (const dataSource of data.dataSources) {+ let { scopeInstanceId } = dataSource;+ if (scopeInstanceId !== undefined) {+ scopeInstanceId = copiedInstanceIds.get(scopeInstanceId);+ }+ const newId = copiedDataSourceIds.get(dataSource.id);+ if (newId === undefined) {+ continue;+ }+ if (dataSource.type === "variable") {+ dataSources.set(newId, {+ ...dataSource,+ id: newId,+ scopeInstanceId,+ });+ }+ if (dataSource.type === "expression") {+ dataSources.set(newId, {+ ...dataSource,+ id: newId,+ scopeInstanceId,+ code: validateExpression(dataSource.code, {+ transformIdentifier: (id) => {+ const dataSourceId = decodeDataSourceVariable(id);+ if (dataSourceId === undefined) {+ return id;+ }+ const newId = copiedDataSourceIds.get(dataSourceId);+ if (newId === undefined) {+ return id;+ }+ return encodeDataSourceVariable(newId);+ },+ }),+ });+ }+ }+const localStyleSourceIds = findLocalStyleSourcesWithinInstances(data.styleSources,data.styleSourceSelections,@@ -341,7 +444,12 @@ export const onPaste = (clipboardData: string): boolean => {localStyleSourceIds);- insertPropsCopyMutable(props, data.props, copiedInstanceIds);+ insertPropsCopyMutable(+ props,+ data.props,+ copiedInstanceIds,+ copiedDataSourceIds+ );insertStyleSourceSelectionsCopyMutable(styleSourceSelections,data.styleSourceSelections,diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.tsindex 311ca78ac3..d25d8b32c9 100644--- a/apps/builder/app/shared/instance-utils.ts+++ b/apps/builder/app/shared/instance-utils.ts@@ -257,7 +257,7 @@ export const insertTemplateData = (children,dropTarget);- insertPropsCopyMutable(props, insertedProps, new Map());+ insertPropsCopyMutable(props, insertedProps, new Map(), new Map());for (const dataSource of insertedDataSources) {dataSources.set(dataSource.id, dataSource);}diff --git a/apps/builder/app/shared/tree-utils.test.ts b/apps/builder/app/shared/tree-utils.test.tsindex a31bfbe4c1..5344d15754 100644--- a/apps/builder/app/shared/tree-utils.test.ts+++ b/apps/builder/app/shared/tree-utils.test.ts@@ -867,7 +867,7 @@ test("insert props copy with new ids and apply new instance ids", () => {const clonedInstanceIds = new Map<Instance["id"], Instance["id"]>([["instance2", "newInstance2"],]);- insertPropsCopyMutable(props, copiedProps, clonedInstanceIds);+ insertPropsCopyMutable(props, copiedProps, clonedInstanceIds, new Map());expect(Array.from(props.entries())).toEqual([["prop1", createProp("prop1", "instance1")],["prop2", createProp("prop2", "instance2")],diff --git a/apps/builder/app/shared/tree-utils.ts b/apps/builder/app/shared/tree-utils.tsindex d43cc06d1b..2489661a56 100644--- a/apps/builder/app/shared/tree-utils.ts+++ b/apps/builder/app/shared/tree-utils.ts@@ -2,6 +2,7 @@ import { nanoid } from "nanoid";import {Breakpoint,Breakpoints,+ DataSource,findTreeInstanceIds,findTreeInstanceIdsExcludingSlotDescendants,getStyleDeclKey,@@ -490,7 +491,8 @@ export const insertStyleSourcesCopyMutable = (export const insertPropsCopyMutable = (props: Props,copiedProps: Prop[],- copiedInstanceIds: Map<Instance["id"], Instance["id"]>+ copiedInstanceIds: Map<Instance["id"], Instance["id"]>,+ copiedDataSourceIds: Map<DataSource["id"], DataSource["id"]>) => {for (const prop of copiedProps) {const newInstanceId = copiedInstanceIds.get(prop.instanceId);@@ -505,11 +507,20 @@ export const insertPropsCopyMutable = (// copy prop before insertingconst newPropId = nanoid();- props.set(newPropId, {- ...prop,- id: newPropId,- instanceId: newInstanceId,- });+ if (prop.type === "dataSource") {+ props.set(newPropId, {+ ...prop,+ id: newPropId,+ instanceId: newInstanceId,+ value: copiedDataSourceIds.get(prop.value) ?? prop.value,+ });+ } else {+ props.set(newPropId, {+ ...prop,+ id: newPropId,+ instanceId: newInstanceId,+ });+ }}};diff --git a/apps/builder/package.json b/apps/builder/package.jsonindex 1fa790c694..af71d8d93c 100644--- a/apps/builder/package.json+++ b/apps/builder/package.json@@ -64,7 +64,7 @@"downshift": "^6.1.7","hyphenate-style-name": "^1.0.4","immer": "^9.0.12",- "immerhin": "^0.5.0",+ "immerhin": "^0.6.1","jose": "^4.11.2","lexical": "^0.11.1","match-sorter": "^6.3.1",diff --git a/apps/builder/remix.config.js b/apps/builder/remix.config.jsindex 6456f3a24f..468d0c8391 100644--- a/apps/builder/remix.config.js+++ b/apps/builder/remix.config.js@@ -28,6 +28,7 @@ module.exports = {/mdast-/,"unist-util-stringify-position","node-fetch",+ "immerhin",],// appDirectory: "app",// assetsBuildDirectory: "public/build",diff --git a/packages/react-sdk/src/expression.test.ts b/packages/react-sdk/src/expression.test.tsindex 2b7ed7ff2f..fcda7a7906 100644--- a/packages/react-sdk/src/expression.test.ts+++ b/packages/react-sdk/src/expression.test.ts@@ -4,6 +4,7 @@ import {encodeDataSourceVariable,executeComputingExpressions,executeEffectfulExpression,+ computeExpressionsDependencies,generateComputingExpressions,generateEffectfulExpression,validateExpression,@@ -239,3 +240,33 @@ test("execute effectful expression", () => {new Map([["var0", 5]]));});++test("compute expressions dependencies", () => {+ const expressions = new Map([+ ["exp1", `var1`],+ ["exp2", `exp1 + exp1`],+ ["exp3", `exp1 + exp2`],+ ["exp4", `var1 + exp1`],+ ]);+ expect(computeExpressionsDependencies(expressions)).toEqual(+ new Map([+ ["exp4", new Set(["var1", "exp1"])],+ ["exp3", new Set(["var1", "exp1", "exp2"])],+ ["exp2", new Set(["var1", "exp1"])],+ ["exp1", new Set(["var1"])],+ ])+ );+});++test("handle cyclic dependencies", () => {+ const expressions = new Map([+ ["exp1", `exp2 + var1`],+ ["exp2", `exp1 + var1`],+ ]);+ expect(computeExpressionsDependencies(expressions)).toEqual(+ new Map([+ ["exp2", new Set(["var1", "exp1", "exp2"])],+ ["exp1", new Set(["var1", "exp1", "exp2"])],+ ])+ );+});diff --git a/packages/react-sdk/src/expression.ts b/packages/react-sdk/src/expression.tsindex 36c995386b..d1aa465cae 100644--- a/packages/react-sdk/src/expression.ts+++ b/packages/react-sdk/src/expression.ts@@ -307,6 +307,50 @@ export const executeEffectfulExpression = (return values;};+const computeExpressionDependencies = (+ expressions: Map<string, string>,+ expressionId: string,+ dependencies: Map<string, Set<string>>+) => {+ // prevent recalculating expressions over again+ const depsById = dependencies.get(expressionId);+ if (depsById) {+ return depsById;+ }+ const parentDeps = new Set<string>();+ const code = expressions.get(expressionId);+ if (code === undefined) {+ return parentDeps;+ }+ // write before recursive call to avoid infinite cycle+ dependencies.set(expressionId, parentDeps);+ validateExpression(code, {+ transformIdentifier: (id) => {+ parentDeps.add(id);+ const childDeps = computeExpressionDependencies(+ expressions,+ id,+ dependencies+ );+ for (const depId of childDeps) {+ parentDeps.add(depId);+ }+ return id;+ },+ });+ return parentDeps;+};++export const computeExpressionsDependencies = (+ expressions: Map<string, string>+) => {+ const dependencies = new Map<string, Set<string>>();+ for (const id of expressions.keys()) {+ computeExpressionDependencies(expressions, id, dependencies);+ }+ return dependencies;+};+type Values = Map<string, unknown>;const dataSourceVariablePrefix = "$ws$dataSource$";diff --git a/packages/react-sdk/src/index.ts b/packages/react-sdk/src/index.tsindex 8c8078b678..5c9f5eb979 100644--- a/packages/react-sdk/src/index.ts+++ b/packages/react-sdk/src/index.ts@@ -26,6 +26,7 @@ export {executeComputingExpressions,generateEffectfulExpression,executeEffectfulExpression,+ computeExpressionsDependencies,encodeDataSourceVariable,encodeVariablesMap,decodeDataSourceVariable,diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8a6a35b1ff..7b8e7e72ec 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -190,8 +190,8 @@ importers:specifier: ^9.0.12version: 9.0.15immerhin:- specifier: ^0.5.0- version: 0.5.0+ specifier: ^0.6.1+ version: 0.6.1jose:specifier: ^4.11.2version: 4.11.2@@ -11925,8 +11925,8 @@ packages:resolution: {integrity: sha512-2eB/sswms9AEUSkOm4SbV5Y7Vmt/bKRwByd52jfLkW4OLYeaTP3EEiJ9agqU0O/tq6Dk62Zfj+TJSqfm1rLVGQ==}dev: false- resolution: {integrity: sha512-s0MJ45StYo4mChJmQiz/hcw9a5nQD9VHrQCGj1+FiS1TK62X+AA/7XFUR8YbP9b735mS841aKx5tXQNTmOpUJA==}+ resolution: {integrity: sha512-HQUPluF2Mx7n/EAj1HHG3NQDyl1aHnxxWHIpWije2oHO1wEjkUlwHoHMPEjkgGu/zMamV8gfkMiQtrGCOmdOOw==}dependencies:immer: 9.0.15nanoid: 3.3.6