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 insertInstance with instances index (#978)
Bogdan Chadkin0a5a9dc7c167
diff --git a/apps/designer/app/canvas/canvas.tsx b/apps/designer/app/canvas/canvas.tsxindex 45530178ea..1e81d1e5b6 100644--- a/apps/designer/app/canvas/canvas.tsx+++ b/apps/designer/app/canvas/canvas.tsx@@ -15,10 +15,7 @@ import { publish } from "~/shared/pubsub";import { registerContainers, useCanvasStore } from "~/shared/sync";import { useSharedShortcuts } from "~/shared/shortcuts";import { useShortcuts } from "./shared/use-shortcuts";-import {- useInsertInstance,- usePublishTextEditingInstanceId,-} from "./shared/instance";+import { usePublishTextEditingInstanceId } from "./shared/instance";import { useManageDesignModeStyles, GlobalStyles } from "./shared/styles";import { useTrackSelectedElement } from "./shared/use-track-selected-element";import { WrapperComponentDev } from "./features/wrapper-component";@@ -87,7 +84,6 @@ const useElementsTree = () => {const DesignMode = () => {useManageDesignModeStyles();- useInsertInstance();useTrackSelectedElement();usePublishScrollState();useSubscribeScrollState();diff --git a/apps/designer/app/canvas/shared/instance.ts b/apps/designer/app/canvas/shared/instance.tsindex 05019cc382..384e6cac9c 100644--- a/apps/designer/app/canvas/shared/instance.ts+++ b/apps/designer/app/canvas/shared/instance.ts@@ -1,37 +1,14 @@import { useEffect } from "react";-import store from "immerhin";import type { Instance } from "@webstudio-is/project-build";-import { utils } from "@webstudio-is/project";-import { useSubscribe } from "~/shared/pubsub";-import {- rootInstanceContainer,- selectedInstanceIdStore,- useTextEditingInstanceId,-} from "~/shared/nano-states";+import { useTextEditingInstanceId } from "~/shared/nano-states";import { publish } from "~/shared/pubsub";declare module "~/shared/pubsub" {export interface PubsubMap {textEditingInstanceId?: Instance["id"];- insertInstance: {- instance: Instance;- dropTarget?: { parentId: Instance["id"]; position: number | "end" };- };}}-export const useInsertInstance = () => {- useSubscribe("insertInstance", ({ instance, dropTarget }) => {- store.createTransaction([rootInstanceContainer], (rootInstance) => {- if (rootInstance === undefined) {- return;- }- utils.tree.insertInstanceMutable(rootInstance, instance, dropTarget);- });- selectedInstanceIdStore.set(instance.id);- });-};-export const usePublishTextEditingInstanceId = () => {const [editingInstanceId] = useTextEditingInstanceId();useEffect(() => {diff --git a/apps/designer/app/canvas/shared/use-drag-drop.ts b/apps/designer/app/canvas/shared/use-drag-drop.tsindex fe7638ebb0..3cb48a89e2 100644--- a/apps/designer/app/canvas/shared/use-drag-drop.ts+++ b/apps/designer/app/canvas/shared/use-drag-drop.ts@@ -23,7 +23,7 @@ import {getInstanceIdFromElement,} from "~/shared/dom-utils";import { publish, useSubscribe } from "~/shared/pubsub";-import { reparentInstance } from "~/shared/instance-utils";+import { insertInstance, reparentInstance } from "~/shared/instance-utils";declare module "~/shared/pubsub" {export interface PubsubMap {@@ -285,15 +285,9 @@ export const useDragAndDrop = () => {component: dragItem.component,});- publish({- type: "insertInstance",- payload: {- instance,- dropTarget: {- parentId: dropTarget.data.id,- position: dropTarget.indexWithinChildren,- },- },+ insertInstance(instance, {+ parentId: dropTarget.data.id,+ position: dropTarget.indexWithinChildren,});}diff --git a/apps/designer/app/designer/features/sidebar-left/panels/components/components.tsx b/apps/designer/app/designer/features/sidebar-left/panels/components/components.tsxindex f9464952b1..12f325fe7f 100644--- a/apps/designer/app/designer/features/sidebar-left/panels/components/components.tsx+++ b/apps/designer/app/designer/features/sidebar-left/panels/components/components.tsx@@ -16,6 +16,7 @@ import {} from "~/shared/nano-states";import { useSubscribe, type Publish } from "~/shared/pubsub";import { useCanvasRect, useZoom } from "~/designer/shared/nano-states";+import { insertInstance } from "~/shared/instance-utils";import type { TabName } from "../../types";import { Header, CloseButton } from "../../header";import { ComponentThumb } from "./component-thumb";@@ -177,10 +178,7 @@ export const TabContent = ({ publish, onSetActiveTab }: TabContentProps) => {instancesIndexStore.get(),selectedInstanceIdStore.get());- publish({- type: "insertInstance",- payload: { instance, dropTarget },- });+ insertInstance(instance, dropTarget);}}/>))}diff --git a/apps/designer/app/designer/features/tree-preview/tree-preview.tsx b/apps/designer/app/designer/features/tree-preview/tree-preview.tsxindex 7f40238de1..db6b9e29db 100644--- a/apps/designer/app/designer/features/tree-preview/tree-preview.tsx+++ b/apps/designer/app/designer/features/tree-preview/tree-preview.tsx@@ -7,6 +7,7 @@ import { useRootInstance, useDragAndDropState } from "~/shared/nano-states";import { InstanceTreeNode } from "~/designer/shared/tree";import {createInstancesIndex,+ insertInstanceMutable,reparentInstanceMutable,} from "~/shared/tree-utils";@@ -35,8 +36,8 @@ export const TreePrevew = () => {const instance: Instance = produce<Instance>((draft) => {const instancesIndex = createInstancesIndex(draft);if (isNew) {- utils.tree.insertInstanceMutable(- draft,+ insertInstanceMutable(+ instancesIndex,utils.tree.createInstance({ component: dragItemInstance.component }),{parentId: dropTargetInstanceId,diff --git a/apps/designer/app/shared/copy-paste/copy-paste-instance.ts b/apps/designer/app/shared/copy-paste/copy-paste-instance.tsindex 8d003974cd..c69ebbb496 100644--- a/apps/designer/app/shared/copy-paste/copy-paste-instance.ts+++ b/apps/designer/app/shared/copy-paste/copy-paste-instance.ts@@ -8,7 +8,6 @@ import {StyleSource,StyleSourceSelection,} from "@webstudio-is/project-build";-import { utils } from "@webstudio-is/project";import {rootInstanceContainer,propsStore,@@ -24,9 +23,11 @@ import {cloneStyles,cloneStyleSources,cloneStyleSourceSelections,+ createInstancesIndex,findClosestDroppableTarget,findSubtree,findSubtreeLocalStyleSources,+ insertInstanceMutable,} from "../tree-utils";import { deleteInstance } from "../instance-utils";import { startCopyPaste } from "./copy-paste";@@ -103,12 +104,8 @@ const pasteInstance = (data: InstanceData) => {stylesStore,],(rootInstance, props, styleSourceSelections, styleSources, styles) => {- if (rootInstance === undefined) {- return;- }- utils.tree.insertInstanceMutable(rootInstance, data.instance, dropTarget);- // append without checking existing- // because all data already cloned with new ids+ const instancesIndex = createInstancesIndex(rootInstance);+ insertInstanceMutable(instancesIndex, data.instance, dropTarget);for (const prop of data.props) {props.set(prop.id, prop);}diff --git a/apps/designer/app/shared/instance-utils.ts b/apps/designer/app/shared/instance-utils.tsindex d0a5198af7..0bceaab6ed 100644--- a/apps/designer/app/shared/instance-utils.ts+++ b/apps/designer/app/shared/instance-utils.ts@@ -13,10 +13,22 @@ import {DroppableTarget,findSubtree,findSubtreeLocalStyleSources,+ insertInstanceMutable,reparentInstanceMutable,} from "./tree-utils";import { removeByMutable } from "./array-utils";+export const insertInstance = (+ instance: Instance,+ dropTarget?: DroppableTarget+) => {+ store.createTransaction([rootInstanceContainer], (rootInstance) => {+ const instancesIndex = createInstancesIndex(rootInstance);+ insertInstanceMutable(instancesIndex, instance, dropTarget);+ });+ selectedInstanceIdStore.set(instance.id);+};+export const reparentInstance = (targetInstanceId: Instance["id"],dropTarget: DroppableTargetdiff --git a/apps/designer/app/shared/tree-utils.test.ts b/apps/designer/app/shared/tree-utils.test.tsindex 9f729eed9c..bf157d1eb9 100644--- a/apps/designer/app/shared/tree-utils.test.ts+++ b/apps/designer/app/shared/tree-utils.test.ts@@ -16,6 +16,7 @@ import {findClosestDroppableTarget,findSubtree,findSubtreeLocalStyleSources,+ insertInstanceMutable,reparentInstanceMutable,} from "./tree-utils";@@ -122,6 +123,67 @@ test("find closest droppable target", () => {});});+test("insert instance into target", () => {+ const rootInstance = createInstance("root", "Body", [+ createInstance("box1", "Box", [+ createInstance("box11", "Box", []),+ createInstance("box12", "Box", []),+ createInstance("box13", "Box", []),+ ]),+ ]);++ let instancesIndex = createInstancesIndex(rootInstance);+ insertInstanceMutable(+ instancesIndex,+ createInstance("inserted1", "Box", [+ createInstance("inserted2", "Box", []),+ ]),+ {+ parentId: "box1",+ position: 1,+ }+ );+ expect(rootInstance).toEqual(+ createInstance("root", "Body", [+ createInstance("box1", "Box", [+ createInstance("box11", "Box", []),+ createInstance("inserted1", "Box", [+ createInstance("inserted2", "Box", []),+ ]),+ createInstance("box12", "Box", []),+ createInstance("box13", "Box", []),+ ]),+ ])+ );++ instancesIndex = createInstancesIndex(rootInstance);+ insertInstanceMutable(+ instancesIndex,+ createInstance("inserted3", "Box", [+ createInstance("inserted4", "Box", []),+ ]),+ {+ parentId: "box1",+ position: "end",+ }+ );+ expect(rootInstance).toEqual(+ createInstance("root", "Body", [+ createInstance("box1", "Box", [+ createInstance("box11", "Box", []),+ createInstance("inserted1", "Box", [+ createInstance("inserted2", "Box", []),+ ]),+ createInstance("box12", "Box", []),+ createInstance("box13", "Box", []),+ createInstance("inserted3", "Box", [+ createInstance("inserted4", "Box", []),+ ]),+ ]),+ ])+ );+});+test("reparent instance into target", () => {const rootInstance = createInstance("root", "Body", [createInstance("target", "Box", []),@@ -132,6 +194,7 @@ test("reparent instance into target", () => {]),createInstance("box2", "Box", []),]);+let instancesIndex = createInstancesIndex(rootInstance);reparentInstanceMutable(instancesIndex, "target", {parentId: "box1",diff --git a/apps/designer/app/shared/tree-utils.ts b/apps/designer/app/shared/tree-utils.tsindex 8e8ac2bbe6..225f5c6945 100644--- a/apps/designer/app/shared/tree-utils.ts+++ b/apps/designer/app/shared/tree-utils.ts@@ -101,6 +101,26 @@ export const findClosestDroppableTarget = (};};+export const insertInstanceMutable = (+ instancesIndex: InstancesIndex,+ instance: Instance,+ dropTarget?: DroppableTarget+) => {+ if (dropTarget === undefined) {+ return;+ }+ const parentInstance = instancesIndex.instancesById.get(dropTarget.parentId);+ if (parentInstance === undefined) {+ return;+ }+ const { position } = dropTarget;+ if (position === "end") {+ parentInstance.children.push(instance);+ } else {+ parentInstance.children.splice(position, 0, instance);+ }+};+export const reparentInstanceMutable = (instancesIndex: InstancesIndex,instanceId: Instance["id"],diff --git a/packages/project/src/index.ts b/packages/project/src/index.tsindex a5a08fd3e8..bb45c86fb1 100644--- a/packages/project/src/index.ts+++ b/packages/project/src/index.ts@@ -11,5 +11,4 @@ export const utils = {export * from "./shared/styles";export * from "./shared/schema";export * from "./shared/canvas-components";-export type { InstanceInsertionSpec } from "./shared/tree-utils";export type { ProjectRouter } from "./trpc";diff --git a/packages/project/src/shared/tree-utils/__snapshots__/insert-instance.test.ts.snap b/packages/project/src/shared/tree-utils/__snapshots__/insert-instance.test.ts.snapdeleted file mode 100644index eb33b25040..0000000000--- a/packages/project/src/shared/tree-utils/__snapshots__/insert-instance.test.ts.snap+++ /dev/null@@ -1,90 +0,0 @@-// Jest Snapshot v1, https://goo.gl/fbAQLP--exports[`Insert instance after a nested div using "end": div 1 > div 2, [div 3] 1`] = `-{- "children": [- {- "children": [],- "component": "Box",- "id": "2",- "type": "instance",- },- {- "children": [],- "component": "Box",- "id": "3",- "type": "instance",- },- ],- "component": "Box",- "id": "1",- "type": "instance",-}-`;--exports[`Insert instance after a nested div using index: div 1 > div 2, [div 3] 1`] = `-{- "children": [- {- "children": [],- "component": "Box",- "id": "2",- "type": "instance",- },- {- "children": [],- "component": "Box",- "id": "3",- "type": "instance",- },- ],- "component": "Box",- "id": "1",- "type": "instance",-}-`;--exports[`Insert instance before a nested div using index: div 1 > [div 3], div 2 1`] = `-{- "children": [- {- "children": [],- "component": "Box",- "id": "3",- "type": "instance",- },- {- "children": [],- "component": "Box",- "id": "2",- "type": "instance",- },- ],- "component": "Box",- "id": "1",- "type": "instance",-}-`;--exports[`Insert instance inside a nested div using "end": div 1 > div 2 > [div 3] 1`] = `-{- "children": [- {- "children": [- {- "children": [],- "component": "Box",- "id": "3",- "type": "instance",- },- ],- "component": "Box",- "id": "2",- "type": "instance",- },- ],- "component": "Box",- "id": "1",- "type": "instance",-}-`;diff --git a/packages/project/src/shared/tree-utils/find-closest-sibling-instance.test.ts b/packages/project/src/shared/tree-utils/find-closest-sibling-instance.test.tsdeleted file mode 100644index a3c7cbf50a..0000000000--- a/packages/project/src/shared/tree-utils/find-closest-sibling-instance.test.ts+++ /dev/null@@ -1,43 +0,0 @@-import { describe, test, expect } from "@jest/globals";-import type { Instance } from "@webstudio-is/project-build";-import { findClosestSiblingInstance } from "./find-closest-sibling-instance";--describe("Find closest sibling instance", () => {- test("find", () => {- const rootInstance: Instance = {- type: "instance",- component: "Box",- id: "1",- children: [- {- type: "instance",- component: "Box",- id: "3",- children: [],- },- { type: "text", value: "a" },- {- type: "instance",- component: "Box",- id: "4",- children: [],- },- { type: "text", value: "b" },- {- type: "instance",- component: "Box",- id: "5",- children: [],- },- ],- };-- expect(- findClosestSiblingInstance(rootInstance, "notFound")- ).toBeUndefined();- expect(findClosestSiblingInstance(rootInstance, "1")).toBeUndefined();- expect(findClosestSiblingInstance(rootInstance, "3")?.id).toBe("4");- expect(findClosestSiblingInstance(rootInstance, "4")?.id).toBe("5");- expect(findClosestSiblingInstance(rootInstance, "5")?.id).toBe("4");- });-});diff --git a/packages/project/src/shared/tree-utils/find-closest-sibling-instance.ts b/packages/project/src/shared/tree-utils/find-closest-sibling-instance.tsdeleted file mode 100644index f1c2017ee7..0000000000--- a/packages/project/src/shared/tree-utils/find-closest-sibling-instance.ts+++ /dev/null@@ -1,23 +0,0 @@-import type { Instance } from "@webstudio-is/project-build";--export const findClosestSiblingInstance = (- instance: Instance,- instanceId: Instance["id"]-): Instance | undefined => {- if (instance.children.length === 0) {- return;- }- const children = instance.children.filter(- (child): child is Instance => child.type === "instance"- );- const index = children.findIndex((instance) => instance.id === instanceId);- if (index === -1) {- return;- }- const nextInstance = children[index + 1];- if (nextInstance !== undefined) {- return nextInstance;- }- const previousInstance = children[index - 1];- return previousInstance;-};diff --git a/packages/project/src/shared/tree-utils/index.ts b/packages/project/src/shared/tree-utils/index.tsindex 1bbf3f56c1..a9582ab4f6 100644--- a/packages/project/src/shared/tree-utils/index.ts+++ b/packages/project/src/shared/tree-utils/index.ts@@ -1,8 +1,6 @@export * from "./create-instance";-export * from "./insert-instance";export * from "./find-instance";export * from "./get-instance-path";-export * from "./find-closest-sibling-instance";export * from "./find-closest-non-inline-parent";export * from "./set-instance-children";export * from "./find-instance";diff --git a/packages/project/src/shared/tree-utils/insert-instance.test.ts b/packages/project/src/shared/tree-utils/insert-instance.test.tsdeleted file mode 100644index 438db05cb1..0000000000--- a/packages/project/src/shared/tree-utils/insert-instance.test.ts+++ /dev/null@@ -1,99 +0,0 @@-import { describe, test, expect } from "@jest/globals";-import type { Instance } from "@webstudio-is/project-build";-import { insertInstanceMutable } from "./insert-instance";-import { createInstance } from "./create-instance";--const instance = createInstance({ id: "3", component: "Box" });--describe("Insert instance", () => {- test(`inside a nested div using "end": div 1 > div 2 > [div 3]`, () => {- const rootInstance: Instance = {- type: "instance",- component: "Box",- id: "1",- children: [- {- type: "instance",- component: "Box",- id: "2",- children: [],- },- ],- };-- const hasInserted = insertInstanceMutable(rootInstance, instance, {- parentId: "2",- position: "end",- });- expect(hasInserted).toBeTruthy();- expect(rootInstance).toMatchSnapshot();- });-- test("after a nested div using index: div 1 > div 2, [div 3]", () => {- const rootInstance: Instance = {- type: "instance",- component: "Box",- id: "1",- children: [- {- type: "instance",- component: "Box",- id: "2",- children: [],- },- ],- };-- const hasInserted = insertInstanceMutable(rootInstance, instance, {- parentId: "1",- position: 1,- });- expect(hasInserted).toBeTruthy();- expect(rootInstance).toMatchSnapshot();- });-- test("before a nested div using index: div 1 > [div 3], div 2", () => {- const rootInstance: Instance = {- type: "instance",- component: "Box",- id: "1",- children: [- {- type: "instance",- component: "Box",- id: "2",- children: [],- },- ],- };- const hasInserted = insertInstanceMutable(rootInstance, instance, {- parentId: "1",- position: 0,- });- expect(hasInserted).toBeTruthy();- expect(rootInstance).toMatchSnapshot();- });-- test(`after a nested div using "end": div 1 > div 2, [div 3]`, () => {- const rootInstance: Instance = {- type: "instance",- component: "Box",- id: "1",- children: [- {- type: "instance",- component: "Box",- id: "2",- children: [],- },- ],- };-- const hasInserted = insertInstanceMutable(rootInstance, instance, {- parentId: "1",- position: "end",- });- expect(hasInserted).toBeTruthy();- expect(rootInstance).toMatchSnapshot();- });-});diff --git a/packages/project/src/shared/tree-utils/insert-instance.ts b/packages/project/src/shared/tree-utils/insert-instance.tsdeleted file mode 100644index 2dd55f73fd..0000000000--- a/packages/project/src/shared/tree-utils/insert-instance.ts+++ /dev/null@@ -1,42 +0,0 @@-import type { Instance } from "@webstudio-is/project-build";--export type InstanceInsertionSpec = {- parentId: Instance["id"];- position: number | "end";-};--export const insertInstanceMutable = (- rootInstance: Instance,- instance: Instance,- spec: undefined | InstanceInsertionSpec-): boolean => {- if (spec === undefined) {- return false;- }- if (spec.parentId !== rootInstance.id) {- for (const child of rootInstance.children) {- if (child.type === "text") {- continue;- }- const hasInserted = insertInstanceMutable(child, instance, spec);- if (hasInserted === true) {- return true;- }- }- return false;- }-- // Inserting inside the selected/hovered instance.- if (typeof spec.position === "number") {- rootInstance.children.splice(spec.position, 0, instance);- return true;- }-- // Inserting after all children- if (spec.position === "end") {- rootInstance.children.push(instance);- return true;- }-- return true;-};