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
refactor: move insert instance children logic into utility (#2931)
Bogdan Chadkin9e37075e7d13
diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.tsindex d7cac6ec16..b071415481 100644--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts@@ -14,12 +14,7 @@ import {$registeredComponentMetas,$instances,} from "../nano-states";-import {- type InstanceSelector,- type DroppableTarget,- getInstanceOrCreateFragmentIfNecessary,- wrapEditableChildrenAroundDropTargetMutable,-} from "../tree-utils";+import type { InstanceSelector, DroppableTarget } from "../tree-utils";import {computeInstancesConstraints,deleteInstanceMutable,@@ -30,6 +25,7 @@ import {isInstanceDetachable,updateWebstudioData,getWebstudioData,+ insertInstanceChildrenMutable,} from "../instance-utils";import { portalComponent } from "@webstudio-is/react-sdk";@@ -171,7 +167,6 @@ export const onPaste = (clipboardData: string): boolean => {const selectedPage = $selectedPage.get();const project = $project.get();- const metas = $registeredComponentMetas.get();if (fragment === undefined ||@@ -204,32 +199,10 @@ export const onPaste = (clipboardData: string): boolean => {if (newRootInstanceId === undefined) {return;}- let dropTarget = pasteTarget;- dropTarget =- getInstanceOrCreateFragmentIfNecessary(data.instances, dropTarget) ??- dropTarget;- dropTarget =- wrapEditableChildrenAroundDropTargetMutable(- data.instances,- data.props,- metas,- dropTarget- ) ?? dropTarget;- const [parentId] = dropTarget.parentSelector;- const parentInstance = data.instances.get(parentId);- if (parentInstance === undefined) {- return;- }- const child: Instance["children"][number] = {- type: "id",- value: newRootInstanceId,- };- const { position } = dropTarget;- if (position === "end") {- parentInstance.children.push(child);- } else {- parentInstance.children.splice(position, 0, child);- }+ const children: Instance["children"] = [+ { type: "id", value: newRootInstanceId },+ ];+ insertInstanceChildrenMutable(data, children, pasteTarget);});return true;diff --git a/apps/builder/app/shared/instance-utils.test.ts b/apps/builder/app/shared/instance-utils.test.tsindex a2d561ac06..c7838a277a 100644--- a/apps/builder/app/shared/instance-utils.test.ts+++ b/apps/builder/app/shared/instance-utils.test.ts@@ -33,6 +33,7 @@ import {insertWebstudioFragmentCopy,reparentInstance,getWebstudioData,+ insertInstanceChildrenMutable,} from "./instance-utils";import {$assets,@@ -58,6 +59,7 @@ registerContainers();$pages.set(createDefaultPages({ rootInstanceId: "" }));const defaultMetasMap = new Map(Object.entries(defaultMetas));+$registeredComponentMetas.set(defaultMetasMap);const createFakeComponentMetas = (itemMeta: Partial<WsComponentMeta>,@@ -437,6 +439,221 @@ describe("find closest droppable target", () => {});});+describe("insert instance children", () => {+ test("insert instance children into empty target", () => {+ const instances = toMap([createInstance("body", "Body", [])]);+ const data = getWebstudioDataStub({ instances });+ insertInstanceChildrenMutable(data, [{ type: "id", value: "box" }], {+ parentSelector: ["body"],+ position: "end",+ });+ expect(data.instances).toEqual(+ toMap([createInstance("body", "Body", [{ type: "id", value: "box" }])])+ );+ });++ test("insert instance children into the end of target", () => {+ const instances = toMap([+ createInstance("body", "Body", [{ type: "id", value: "text" }]),+ ]);+ const data = getWebstudioDataStub({ instances });+ insertInstanceChildrenMutable(data, [{ type: "id", value: "box" }], {+ parentSelector: ["body"],+ position: "end",+ });+ expect(data.instances).toEqual(+ toMap([+ createInstance("body", "Body", [+ { type: "id", value: "text" },+ { type: "id", value: "box" },+ ]),+ ])+ );+ });++ test("insert instance children into the start of target", () => {+ const instances = toMap([+ createInstance("body", "Body", [{ type: "id", value: "text" }]),+ ]);+ const data = getWebstudioDataStub({ instances });+ insertInstanceChildrenMutable(data, [{ type: "id", value: "box" }], {+ parentSelector: ["body"],+ position: 0,+ });+ expect(data.instances).toEqual(+ toMap([+ createInstance("body", "Body", [+ { type: "id", value: "box" },+ { type: "id", value: "text" },+ ]),+ ])+ );+ });++ test("insert instance children at the start of text", () => {+ const instances = toMap([+ createInstance("body", "Body", [{ type: "id", value: "text" }]),+ createInstance("text", "Text", [{ type: "text", value: "text" }]),+ ]);+ const data = getWebstudioDataStub({ instances });+ insertInstanceChildrenMutable(data, [{ type: "id", value: "box" }], {+ parentSelector: ["text", "body"],+ position: 0,+ });+ const [_bodyId, _textId, spanId] = data.instances.keys();+ expect(data.instances).toEqual(+ toMap([+ createInstance("body", "Body", [{ type: "id", value: "text" }]),+ createInstance("text", "Text", [+ { type: "id", value: "box" },+ { type: "id", value: spanId },+ ]),+ createInstance(spanId, "Text", [{ type: "text", value: "text" }]),+ ])+ );+ expect(data.props).toEqual(+ toMap<Prop>([+ {+ id: expect.any(String) as unknown as string,+ instanceId: spanId,+ name: "tag",+ type: "string",+ value: "span",+ },+ ])+ );+ });++ test("insert instance children at the end of text", () => {+ const instances = toMap([+ createInstance("body", "Body", [{ type: "id", value: "text" }]),+ createInstance("text", "Text", [{ type: "text", value: "text" }]),+ ]);+ const data = getWebstudioDataStub({ instances });+ insertInstanceChildrenMutable(data, [{ type: "id", value: "box" }], {+ parentSelector: ["text", "body"],+ position: "end",+ });+ const [_bodyId, _textId, spanId] = data.instances.keys();+ expect(data.instances).toEqual(+ toMap([+ createInstance("body", "Body", [{ type: "id", value: "text" }]),+ createInstance("text", "Text", [+ { type: "id", value: spanId },+ { type: "id", value: "box" },+ ]),+ createInstance(spanId, "Text", [{ type: "text", value: "text" }]),+ ])+ );+ expect(data.props).toEqual(+ toMap<Prop>([+ {+ id: expect.any(String) as unknown as string,+ instanceId: spanId,+ name: "tag",+ type: "string",+ value: "span",+ },+ ])+ );+ });++ test("insert instance children between text children", () => {+ const instances = toMap([+ createInstance("body", "Body", [{ type: "id", value: "text" }]),+ createInstance("text", "Text", [+ { type: "id", value: "bold" },+ { type: "text", value: "text" },+ { type: "id", value: "italic" },+ ]),+ createInstance("bold", "Bold", [{ type: "text", value: "bold" }]),+ createInstance("italic", "Italic", [{ type: "text", value: "italic" }]),+ ]);+ const data = getWebstudioDataStub({ instances });+ insertInstanceChildrenMutable(data, [{ type: "id", value: "box" }], {+ parentSelector: ["text", "body"],+ position: 1,+ });+ const [_bodyId, _textId, _boldId, _italicId, leftSpanId, rightSpanId] =+ data.instances.keys();+ expect(data.instances).toEqual(+ toMap([+ createInstance("body", "Body", [{ type: "id", value: "text" }]),+ createInstance("text", "Text", [+ { type: "id", value: leftSpanId },+ { type: "id", value: "box" },+ { type: "id", value: rightSpanId },+ ]),+ createInstance("bold", "Bold", [{ type: "text", value: "bold" }]),+ createInstance("italic", "Italic", [{ type: "text", value: "italic" }]),+ createInstance(leftSpanId, "Text", [{ type: "id", value: "bold" }]),+ createInstance(rightSpanId, "Text", [+ { type: "text", value: "text" },+ { type: "id", value: "italic" },+ ]),+ ])+ );+ expect(data.props).toEqual(+ toMap<Prop>([+ {+ id: expect.any(String) as unknown as string,+ instanceId: leftSpanId,+ name: "tag",+ type: "string",+ value: "span",+ },+ {+ id: expect.any(String) as unknown as string,+ instanceId: rightSpanId,+ name: "tag",+ type: "string",+ value: "span",+ },+ ])+ );+ });+});++test("insert template data with instances", () => {+ $instances.set(toMap([createInstance("body", "Body", [])]));+ $styleSourceSelections.set(new Map());+ $styleSources.set(toMap([{ type: "token", id: "1", name: "Zero" }]));+ $styles.set(+ new Map([+ [+ "1:base:color:",+ {+ breakpointId: "base",+ styleSourceId: "1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ ])+ );+ insertTemplateData(+ {+ children: [{ type: "id", value: "box" }],+ instances: [createInstance("box", "Box", [])],+ props: [],+ dataSources: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ assets: [],+ resources: [],+ breakpoints: [],+ },+ { parentSelector: ["body"], position: "end" }+ );+ expect($instances.get()).toEqual(+ toMap<Instance>([+ createInstance("body", "Body", [{ type: "id", value: "box" }]),+ createInstance("box", "Box", []),+ ])+ );+});+test("insert template data with only new style sources", () => {$instances.set(new Map([createInstancePair("body", "Body", [])]));$styleSourceSelections.set(new Map());diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.tsindex dbd59dd036..3dd3b7d85e 100644--- a/apps/builder/app/shared/instance-utils.ts+++ b/apps/builder/app/shared/instance-utils.ts@@ -49,10 +49,11 @@ import {type DroppableTarget,type InstanceSelector,findLocalStyleSourcesWithinInstances,- insertInstancesMutable,getAncestorInstanceSelector,insertPropsCopyMutable,getReparentDropTargetMutable,+ getInstanceOrCreateFragmentIfNecessary,+ wrapEditableChildrenAroundDropTargetMutable,} from "./tree-utils";import { removeByMutable } from "./array-utils";import { isBaseBreakpoint } from "./breakpoints";@@ -372,6 +373,35 @@ export const findClosestDroppableTarget = (};};+export const insertInstanceChildrenMutable = (+ data: WebstudioData,+ children: Instance["children"],+ insertTarget: DroppableTarget+) => {+ const metas = $registeredComponentMetas.get();+ insertTarget =+ getInstanceOrCreateFragmentIfNecessary(data.instances, insertTarget) ??+ insertTarget;+ insertTarget =+ wrapEditableChildrenAroundDropTargetMutable(+ data.instances,+ data.props,+ metas,+ insertTarget+ ) ?? insertTarget;+ const [parentInstanceId] = insertTarget.parentSelector;+ const parentInstance = data.instances.get(parentInstanceId);+ if (parentInstance === undefined) {+ return;+ }+ const { position } = insertTarget;+ if (position === "end") {+ parentInstance.children.push(...children);+ } else {+ parentInstance.children.splice(position, 0, ...children);+ }+};+export const insertTemplateData = (templateData: WebstudioFragment,dropTarget: DroppableTarget@@ -383,62 +413,47 @@ export const insertTemplateData = (dataSources: insertedDataSources,} = templateData;const rootInstanceId = insertedInstances[0].id;- serverSyncStore.createTransaction(- [- $instances,- // insert data sources before props to avoid error- // about missing data source when compute data source logic- $dataSources,- $props,- $styleSourceSelections,- $styleSources,- $styles,- ],- (+ updateWebstudioData((data) => {+ const {instances,dataSources,props,styleSourceSelections,styleSources,- styles- ) => {- insertInstancesMutable(- instances,- props,- $registeredComponentMetas.get(),- insertedInstances,- children,- dropTarget- );- insertPropsCopyMutable(props, insertedProps, new Map());- for (const dataSource of insertedDataSources) {- dataSources.set(dataSource.id, dataSource);- }-- // insert only new style sources and their styles to support- // embed template tokens which have persistent id- // so when user changes these styles and then again add component with token- // nothing breaks visually- const insertedStyleSources = new Set<StyleSource["id"]>();- for (const styleSource of templateData.styleSources) {- if (styleSources.has(styleSource.id) === false) {- insertedStyleSources.add(styleSource.id);- styleSources.set(styleSource.id, styleSource);- }- }- for (const styleDecl of templateData.styles) {- if (insertedStyleSources.has(styleDecl.styleSourceId)) {- styles.set(getStyleDeclKey(styleDecl), styleDecl);- }+ styles,+ } = data;+ for (const instance of insertedInstances) {+ instances.set(instance.id, instance);+ }+ insertInstanceChildrenMutable(data, children, dropTarget);+ insertPropsCopyMutable(props, insertedProps, new Map());+ for (const dataSource of insertedDataSources) {+ dataSources.set(dataSource.id, dataSource);+ }++ // insert only new style sources and their styles to support+ // embed template tokens which have persistent id+ // so when user changes these styles and then again add component with token+ // nothing breaks visually+ const insertedStyleSources = new Set<StyleSource["id"]>();+ for (const styleSource of templateData.styleSources) {+ if (styleSources.has(styleSource.id) === false) {+ insertedStyleSources.add(styleSource.id);+ styleSources.set(styleSource.id, styleSource);}- for (const styleSourceSelection of templateData.styleSourceSelections) {- styleSourceSelections.set(- styleSourceSelection.instanceId,- styleSourceSelection- );+ }+ for (const styleDecl of templateData.styles) {+ if (insertedStyleSources.has(styleDecl.styleSourceId)) {+ styles.set(getStyleDeclKey(styleDecl), styleDecl);}}- );+ for (const styleSourceSelection of templateData.styleSourceSelections) {+ styleSourceSelections.set(+ styleSourceSelection.instanceId,+ styleSourceSelection+ );+ }+ });$selectedInstanceSelector.set([rootInstanceId, ...dropTarget.parentSelector]);};diff --git a/apps/builder/app/shared/tree-utils.test.ts b/apps/builder/app/shared/tree-utils.test.tsindex d7940fe0a3..1d16ea6d60 100644--- a/apps/builder/app/shared/tree-utils.test.ts+++ b/apps/builder/app/shared/tree-utils.test.ts@@ -1,4 +1,4 @@-import { test, expect, describe } from "@jest/globals";+import { test, expect } from "@jest/globals";import type {Instance,Prop,@@ -8,41 +8,16 @@ import type {StyleSourceSelection,} from "@webstudio-is/sdk";import { getStyleDeclKey } from "@webstudio-is/sdk";-import * as baseMetas from "@webstudio-is/sdk-components-react/metas";import {type InstanceSelector,cloneStyles,findLocalStyleSourcesWithinInstances,getAncestorInstanceSelector,- insertInstancesMutable,insertPropsCopyMutable,} from "./tree-utils";-const baseMetasMap = new Map(Object.entries(baseMetas));-const expectString = expect.any(String) as unknown as string;-const createInstance = (- id: Instance["id"],- component: string,- children: Instance["children"]-): Instance => {- return {- type: "instance",- id,- component,- children,- };-};--const createInstancePair = (- id: Instance["id"],- component: string,- children: Instance["children"]-): [Instance["id"], Instance] => {- return [id, createInstance(id, component, children)];-};-const createProp = (id: string, instanceId: string, value?: string): Prop => {return {id,@@ -125,246 +100,6 @@ test("get ancestor instance selector", () => {expect(getAncestorInstanceSelector(instanceSelector, "1")).toEqual(["1"]);});-test("insert instances tree into target", () => {- const instances = new Map([- createInstancePair("root", "Body", [{ type: "id", value: "box1" }]),- createInstancePair("box1", "Box", [- { type: "id", value: "box11" },- { type: "id", value: "box12" },- { type: "id", value: "box13" },- ]),- createInstancePair("box11", "Box", []),- createInstancePair("box12", "Box", []),- createInstancePair("box13", "Box", []),- ]);-- insertInstancesMutable(- instances,- new Map(),- baseMetasMap,- [- createInstance("inserted1", "Box", [{ type: "id", value: "inserted2" }]),- createInstance("inserted2", "Box", []),- ],- [{ type: "id", value: "inserted1" }],- {- parentSelector: ["box1", "root"],- position: 1,- }- );- expect(Array.from(instances.entries())).toEqual([- createInstancePair("root", "Body", [{ type: "id", value: "box1" }]),- createInstancePair("box1", "Box", [- { type: "id", value: "box11" },- { type: "id", value: "inserted1" },- { type: "id", value: "box12" },- { type: "id", value: "box13" },- ]),- createInstancePair("box11", "Box", []),- createInstancePair("box12", "Box", []),- createInstancePair("box13", "Box", []),- createInstancePair("inserted1", "Box", [- { type: "id", value: "inserted2" },- ]),- createInstancePair("inserted2", "Box", []),- ]);-- insertInstancesMutable(- instances,- new Map(),- baseMetasMap,- [- createInstance("inserted3", "Box", [{ type: "id", value: "inserted4" }]),- createInstance("inserted4", "Box", []),- ],- [{ type: "id", value: "inserted3" }],- {- parentSelector: ["box1", "root"],- position: "end",- }- );- expect(Array.from(instances.entries())).toEqual([- createInstancePair("root", "Body", [{ type: "id", value: "box1" }]),- createInstancePair("box1", "Box", [- { type: "id", value: "box11" },- { type: "id", value: "inserted1" },- { type: "id", value: "box12" },- { type: "id", value: "box13" },- { type: "id", value: "inserted3" },- ]),- createInstancePair("box11", "Box", []),- createInstancePair("box12", "Box", []),- createInstancePair("box13", "Box", []),- createInstancePair("inserted1", "Box", [- { type: "id", value: "inserted2" },- ]),- createInstancePair("inserted2", "Box", []),- createInstancePair("inserted3", "Box", [- { type: "id", value: "inserted4" },- ]),- createInstancePair("inserted4", "Box", []),- ]);-});--describe("insert instances into container with text or rich text children", () => {- test("insert in the end after text", () => {- const getInstances = () =>- new Map([- createInstancePair("root", "Body", [{ type: "id", value: "box" }]),- createInstancePair("box", "Box", [{ type: "text", value: "text" }]),- ]);-- const instances1 = getInstances();- insertInstancesMutable(- instances1,- new Map(),- baseMetasMap,- [createInstance("inserted", "Box", [])],- [{ type: "id", value: "inserted" }],- {- parentSelector: ["box", "root"],- position: 0,- }- );- expect(Array.from(instances1.entries())).toEqual([- createInstancePair("root", "Body", [{ type: "id", value: "box" }]),- createInstancePair("box", "Box", [- { type: "id", value: "inserted" },- { type: "id", value: expectString },- ]),- createInstancePair(expectString, "Text", [- { type: "text", value: "text" },- ]),- createInstancePair("inserted", "Box", []),- ]);-- const instances2 = getInstances();- insertInstancesMutable(- instances2,- new Map(),- baseMetasMap,- [createInstance("inserted", "Box", [])],- [{ type: "id", value: "inserted" }],- {- parentSelector: ["box", "root"],- position: "end",- }- );- expect(Array.from(instances2.entries())).toEqual([- createInstancePair("root", "Body", [{ type: "id", value: "box" }]),- createInstancePair("box", "Box", [- { type: "id", value: expectString },- { type: "id", value: "inserted" },- ]),- createInstancePair(expectString, "Text", [- { type: "text", value: "text" },- ]),- createInstancePair("inserted", "Box", []),- ]);- });-- test("insert container between rich text children", () => {- const getInstances = () =>- new Map([- createInstancePair("root", "Body", [{ type: "id", value: "box" }]),- createInstancePair("box", "Box", [- { type: "id", value: "bold" },- { type: "text", value: "text" },- { type: "id", value: "italic" },- ]),- createInstancePair("bold", "Bold", [{ type: "text", value: "bold" }]),- createInstancePair("italic", "Italic", [- { type: "text", value: "italic" },- ]),- ]);-- // insert before text- const instances1 = getInstances();- insertInstancesMutable(- instances1,- new Map(),- baseMetasMap,- [createInstance("inserted", "Box", [])],- [{ type: "id", value: "inserted" }],- {- parentSelector: ["box", "root"],- position: 1,- }- );- expect(Array.from(instances1.entries())).toEqual([- createInstancePair("root", "Body", [{ type: "id", value: "box" }]),- createInstancePair("box", "Box", [- { type: "id", value: expectString },- { type: "id", value: "inserted" },- { type: "id", value: expectString },- ]),- createInstancePair("bold", "Bold", [{ type: "text", value: "bold" }]),- createInstancePair("italic", "Italic", [- { type: "text", value: "italic" },- ]),- createInstancePair(expectString, "Text", [{ type: "id", value: "bold" }]),- createInstancePair(expectString, "Text", [- { type: "text", value: "text" },- { type: "id", value: "italic" },- ]),- createInstancePair("inserted", "Box", []),- ]);-- // insert after text- const instances2 = getInstances();- insertInstancesMutable(- instances2,- new Map(),- baseMetasMap,- [createInstance("inserted", "Box", [])],- [{ type: "id", value: "inserted" }],- {- parentSelector: ["box", "root"],- position: 2,- }- );- expect(Array.from(instances2.entries())).toEqual([- createInstancePair("root", "Body", [{ type: "id", value: "box" }]),- createInstancePair("box", "Box", [- { type: "id", value: expectString },- { type: "id", value: "inserted" },- ]),- createInstancePair("bold", "Bold", [{ type: "text", value: "bold" }]),- createInstancePair("italic", "Italic", [- { type: "text", value: "italic" },- ]),- createInstancePair(expectString, "Text", [- { type: "id", value: "bold" },- { type: "text", value: "text" },- { type: "id", value: "italic" },- ]),- createInstancePair("inserted", "Box", []),- ]);- });-- test("insert container without children", () => {- const getInstances = () =>- new Map([createInstancePair("root", "Body", [])]);-- const instances1 = getInstances();- insertInstancesMutable(- instances1,- new Map(),- baseMetasMap,- [createInstance("inserted", "Box", [])],- [{ type: "id", value: "inserted" }],- {- parentSelector: ["root"],- position: 1,- }- );- expect(Array.from(instances1.entries())).toEqual([- createInstancePair("root", "Body", [{ type: "id", value: "inserted" }]),- createInstancePair("inserted", "Box", []),- ]);- });-});-test("insert props copy with new ids and apply new instance ids", () => {const props = new Map([["prop1", createProp("prop1", "instance1")],diff --git a/apps/builder/app/shared/tree-utils.ts b/apps/builder/app/shared/tree-utils.tsindex eaf0ca9958..038a817e41 100644--- a/apps/builder/app/shared/tree-utils.ts+++ b/apps/builder/app/shared/tree-utils.ts@@ -317,48 +317,6 @@ export const findLocalStyleSourcesWithinInstances = (return subtreeLocalStyleSourceIds;};-export const insertInstancesMutable = (- instances: Instances,- props: Props,- metas: Map<string, WsComponentMeta>,- insertedInstances: Instance[],- children: Instance["children"],- dropTarget: DroppableTarget-) => {- dropTarget =- getInstanceOrCreateFragmentIfNecessary(instances, dropTarget) ?? dropTarget;- dropTarget =- wrapEditableChildrenAroundDropTargetMutable(- instances,- props,- metas,- dropTarget- ) ?? dropTarget;- const [parentId] = dropTarget.parentSelector;- const parentInstance = instances.get(parentId);- if (parentInstance === undefined) {- return;- }-- let treeRootInstanceId: undefined | Instance["id"] = undefined;- for (const instance of insertedInstances) {- if (treeRootInstanceId === undefined) {- treeRootInstanceId = instance.id;- }- instances.set(instance.id, instance);- }- if (treeRootInstanceId === undefined) {- return;- }-- const { position } = dropTarget;- if (position === "end") {- parentInstance.children.push(...children);- } else {- parentInstance.children.splice(position, 0, ...children);- }-};-export const insertPropsCopyMutable = (props: Props,copiedProps: Prop[],