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
insert instance using transactions #8
Oleg Isonenc2eee7222604
diff --git a/app/canvas/canvas.tsx b/app/canvas/canvas.tsxindex f7fd7b3cab..eed3c05b70 100644--- a/app/canvas/canvas.tsx+++ b/app/canvas/canvas.tsx@@ -83,11 +83,10 @@ type DesignModeProps = {};const DesignMode = ({ treeId }: DesignModeProps) => {- const { instanceInsertionSpec, instanceReparentingSpec } =- useDragDropHandlers();+ const { instanceReparentingSpec } = useDragDropHandlers();useUpdateInstanceStyle();usePublishSelectedInstance({ treeId });- useInsertInstance({ instanceInsertionSpec });+ useInsertInstance();useReparentInstance({ instanceReparentingSpec });useDeleteInstance();usePublishRootInstance();diff --git a/app/canvas/shared/tree.ts b/app/canvas/shared/tree.tsindex 8d5b415b92..683414bc40 100644--- a/app/canvas/shared/tree.ts+++ b/app/canvas/shared/tree.ts@@ -1,21 +1,22 @@import { useEffect, useRef } from "react";import { type Instance, type Tree } from "@webstudio-is/sdk";import {- type InstanceInsertionSpec,type InstanceReparentingSpec,- insertInstance,reparentInstance,deleteInstanceMutable,+ populateInstance,+ findParentInstance,+ findClosestSiblingInstance,+ insertInstanceMutable,} from "~/shared/tree-utils";+import { createTransaction } from "~/lib/sync-engine";+import { DropData } from "~/shared/component";import {rootInstanceContainer,useRootInstance,useSelectedInstance,} from "./nano-values";import { useSubscribe } from "./pubsub";-import { createTransaction } from "~/lib/sync-engine";-import { findParentInstance } from "~/shared/tree-utils/find-parent-instance";-import { findClosestSiblingInstance } from "~/shared/tree-utils/find-closest-sibling-instance";export const usePopulateRootInstance = (tree: Tree) => {const [, setRootInstance] = useRootInstance();@@ -24,38 +25,30 @@ export const usePopulateRootInstance = (tree: Tree) => {}, [tree, setRootInstance]);};-export const useInsertInstance = ({- instanceInsertionSpec,-}: {- instanceInsertionSpec?: InstanceInsertionSpec;-}) => {- const [rootInstance, setRootInstance] = useRootInstance();- const [, setSelectedInstance] = useSelectedInstance();- const previousInstanceInsertionSpecRef = useRef<InstanceInsertionSpec>();+export const useInsertInstance = () => {+ const [selectedInstance, setSelectedInstance] = useSelectedInstance();- useEffect(() => {- if (instanceInsertionSpec === undefined || rootInstance === undefined) {- return;- }- // Preventing an infinite insertion loop- if (previousInstanceInsertionSpecRef.current === instanceInsertionSpec) {- return;- }- previousInstanceInsertionSpecRef.current = instanceInsertionSpec;- const { instance: updatedRoot, insertedInstance } = insertInstance(- instanceInsertionSpec,- rootInstance- );- setRootInstance(updatedRoot);- if (insertedInstance !== undefined) {- setSelectedInstance(insertedInstance);+ useSubscribe<"insertInstance", { instance: Instance; dropData?: DropData }>(+ "insertInstance",+ ({ instance, dropData }) => {+ createTransaction([rootInstanceContainer], (rootInstance) => {+ if (rootInstance === undefined) return;+ const populatedInstance = populateInstance(instance);+ const hasInserted = insertInstanceMutable(+ rootInstance,+ populatedInstance,+ {+ parentId:+ dropData?.instance.id ?? selectedInstance?.id ?? rootInstance.id,+ position: dropData?.position || "end",+ }+ );+ if (hasInserted) {+ setSelectedInstance(instance);+ }+ });}- }, [- instanceInsertionSpec,- rootInstance,- setRootInstance,- setSelectedInstance,- ]);+ );};export const useReparentInstance = ({diff --git a/app/canvas/shared/use-drag-drop-handlers.ts b/app/canvas/shared/use-drag-drop-handlers.tsindex ba3c7705c9..09692e01d2 100644--- a/app/canvas/shared/use-drag-drop-handlers.ts+++ b/app/canvas/shared/use-drag-drop-handlers.ts@@ -4,7 +4,6 @@ import { type Instance } from "@webstudio-is/sdk";import { type DragData, type DropData } from "~/shared/component";import {findInstanceById,- type InstanceInsertionSpec,type InstanceReparentingSpec,} from "~/shared/tree-utils";import {@@ -28,13 +27,10 @@ const getBoundingClientRect = memoize((element) =>const getComputedStyle = memoize((element) => window.getComputedStyle(element));export const useDragDropHandlers = (): {- instanceInsertionSpec?: InstanceInsertionSpec;instanceReparentingSpec?: InstanceReparentingSpec;} => {const [rootInstance] = useRootInstance();- const [selectedInstance, setSelectedInstance] = useSelectedInstance();- const [instanceInsertionSpec, setInstanceInsertionSpec] =- useState<InstanceInsertionSpec>();+ const [, setSelectedInstance] = useSelectedInstance();const [instanceReparentingSpec, setInstanceReparentingSpec] =useState<InstanceReparentingSpec>();const [dropData, setDropData] = useDropData();@@ -65,9 +61,12 @@ export const useDragDropHandlers = (): {findInstanceById(rootInstance, dragData.instance.id) === undefined;if (isNew) {- publish<"insertInstance", Instance>({+ publish<"insertInstance", { instance: Instance; dropData?: DropData }>({type: "insertInstance",- payload: dragData.instance,+ payload: {+ instance: dragData.instance,+ dropData,+ },});return;}@@ -124,19 +123,5 @@ export const useDragDropHandlers = (): {});});- useSubscribe<"insertInstance", Instance>("insertInstance", (instance) => {- if (rootInstance === undefined) return;- const instanceInsertionSpec = {- instance,- parentId: selectedInstance?.id ?? rootInstance.id,- position: dropData?.position || "end",- };- setInstanceInsertionSpec(instanceInsertionSpec);- publish<"syncInstanceInsertion", InstanceInsertionSpec>({- type: "syncInstanceInsertion",- payload: instanceInsertionSpec,- });- });-- return { instanceInsertionSpec, instanceReparentingSpec };+ return { instanceReparentingSpec };};diff --git a/app/designer/features/sidebar-left/panels/components.tsx b/app/designer/features/sidebar-left/panels/components.tsxindex 93e8efc03b..791871ba25 100644--- a/app/designer/features/sidebar-left/panels/components.tsx+++ b/app/designer/features/sidebar-left/panels/components.tsx@@ -109,9 +109,9 @@ export const TabContent = ({label={primitives[component].label}onClick={() => {onSetActiveTab("none");- publish<"insertInstance", Instance>({+ publish<"insertInstance", { instance: Instance }>({type: "insertInstance",- payload: createInstance({ component }),+ payload: { instance: createInstance({ component }) },});}}onDragChange={handleDragChange}diff --git a/app/designer/features/sync/use-sync.ts b/app/designer/features/sync/use-sync.tsindex 802bfd6bff..d61da63a4b 100644--- a/app/designer/features/sync/use-sync.ts+++ b/app/designer/features/sync/use-sync.ts@@ -7,10 +7,7 @@ import {type Project,} from "@webstudio-is/sdk";import type { Config } from "~/config";-import type {- InstanceInsertionSpec,- InstanceReparentingSpec,-} from "~/shared/tree-utils";+import type { InstanceReparentingSpec } from "~/shared/tree-utils";import type { StyleUpdates } from "~/shared/component";import { useSubscribe } from "~/designer/features/canvas-iframe";import { enqueue } from "./queue";@@ -21,18 +18,6 @@ import { type SyncItem } from "~/lib/sync-engine";// and backend fetches and updates big objects, so if we send quickly,// we end up overwriting thingsexport const useSync = ({ project }: { config: Config; project: Project }) => {- useSubscribe<"syncInstanceInsertion", InstanceInsertionSpec>(- "syncInstanceInsertion",- (instanceInsertionSpec) => {- enqueue(() =>- fetch(`/rest/insert-instance/${project.devTreeId}`, {- method: "post",- body: JSON.stringify(instanceInsertionSpec),- })- );- }- );-useSubscribe<"syncInstanceReparenting", InstanceReparentingSpec>("syncInstanceReparenting",(instanceReparentingSpec) => {diff --git a/app/designer/features/tree-preview/tree-preview.tsx b/app/designer/features/tree-preview/tree-preview.tsxindex e367756056..8ea018bcc9 100644--- a/app/designer/features/tree-preview/tree-preview.tsx+++ b/app/designer/features/tree-preview/tree-preview.tsx@@ -1,4 +1,5 @@import { Instance, useSubscribe } from "@webstudio-is/sdk";+import produce from "immer";import { useState } from "react";import { useRootInstance } from "~/designer/shared/nano-values";import { Tree } from "~/designer/shared/tree";@@ -7,7 +8,7 @@ import { Flex } from "~/shared/design-system";import {findInstanceById,getInstancePath,- insertInstance,+ insertInstanceMutable,reparentInstance,} from "~/shared/tree-utils";@@ -26,16 +27,13 @@ export const TreePrevew = () => {findInstanceById(rootInstance, dragData.instance.id) === undefined;if (isNew) {- const instanceInsertionSpec = {- instance: dragData.instance,- parentId: dropData.instance.id,- position: dropData.position,- };- const { instance } = insertInstance(- instanceInsertionSpec,- rootInstance- );- setDraftRootInstance(instance);+ const updatedRootInstance = produce((rootInstanceDraft) => {+ insertInstanceMutable(rootInstanceDraft, dragData.instance, {+ parentId: dropData.instance.id,+ position: dropData.position,+ });+ })(rootInstance);+ setDraftRootInstance(updatedRootInstance);return;}diff --git a/app/routes/rest/insert-instance.$treeId.ts b/app/routes/rest/insert-instance.$treeId.tsdeleted file mode 100644index d614c970de..0000000000--- a/app/routes/rest/insert-instance.$treeId.ts+++ /dev/null@@ -1,9 +0,0 @@-import { type ActionFunction } from "remix";-import * as db from "~/shared/db";--export const action: ActionFunction = async ({ request, params }) => {- if (params.treeId === undefined) return { errors: "Tree id required" };- const instanceInsertionSpec = await request.json();- await db.tree.insert(params.treeId, instanceInsertionSpec);- return { status: "ok" };-};diff --git a/app/routes/rest/patch.$treeId.ts b/app/routes/rest/patch.$treeId.tsindex 05b4e1821a..b14b3aec23 100644--- a/app/routes/rest/patch.$treeId.ts+++ b/app/routes/rest/patch.$treeId.ts@@ -15,9 +15,10 @@ export const action: ActionFunction = async ({ request, params }) => {for await (const transaction of transactions) {for await (const change of transaction.changes) {const { namespace, patches } = change;- if (namespace in updaters) {- await updaters[namespace as UpdaterKey](params.treeId, patches);+ if (namespace in updaters === false) {+ return { errors: `Unknown namespace "${namespace}"` };}+ await updaters[namespace as UpdaterKey](params.treeId, patches);}}return { status: "ok" };diff --git a/app/shared/db/tree.server.ts b/app/shared/db/tree.server.tsindex 19fc9b8fdf..ce4daaf0c1 100644--- a/app/shared/db/tree.server.ts+++ b/app/shared/db/tree.server.ts@@ -7,12 +7,10 @@ import {import { applyPatches, type Patch } from "immer";import { prisma } from "./prisma.server";import {- insertInstance,reparentInstance,setInstanceStyle,setInstanceChildren,createInstance,- type InstanceInsertionSpec,type InstanceReparentingSpec,} from "~/shared/tree-utils";import type { StyleUpdates } from "~/shared/component";@@ -93,21 +91,6 @@ export const loadByProject = async (return await loadById(treeId);};-export const insert = async (- id: string,- instanceInsertionSpec: InstanceInsertionSpec-) => {- // @todo insert without loading the entire tree- const tree = await loadById(id);- const { instance: root } = insertInstance(instanceInsertionSpec, tree.root, {- populate: false,- });- await prisma.tree.update({- data: { root },- where: { id },- });-};-export const reparent = async (id: string,instanceReparentingSpec: InstanceReparentingSpecdiff --git a/app/shared/tree-utils/__snapshots__/insert-instance.test.ts.snap b/app/shared/tree-utils/__snapshots__/insert-instance.test.ts.snapindex 0615b3556f..a99eea03ea 100644--- a/app/shared/tree-utils/__snapshots__/insert-instance.test.ts.snap+++ b/app/shared/tree-utils/__snapshots__/insert-instance.test.ts.snap@@ -2,201 +2,89 @@exports[`Insert instance after a nested div using "end": div 1 > div 2, [div 3] 1`] = `Object {- "insertedInstance": Object {- "children": Array [],- "component": "Box",- "id": "3",- "style": Object {- "boxSizing": Object {- "type": "keyword",- "value": "border-box",- },- "minHeight": Object {- "type": "unit",- "unit": "px",- "value": 100,- },+ "children": Array [+ Object {+ "children": Array [],+ "component": "Box",+ "id": "2",+ "style": Object {},},- },- "instance": Object {- "children": Array [- Object {- "children": Array [],- "component": "Box",- "id": "2",- "style": Object {},- },- Object {- "children": Array [],- "component": "Box",- "id": "3",- "style": Object {- "boxSizing": Object {- "type": "keyword",- "value": "border-box",- },- "minHeight": Object {- "type": "unit",- "unit": "px",- "value": 100,- },- },- },- ],- "component": "Box",- "id": "1",- "style": Object {},- },+ Object {+ "children": Array [],+ "component": "Box",+ "id": "3",+ "style": Object {},+ },+ ],+ "component": "Box",+ "id": "1",+ "style": Object {},}`;exports[`Insert instance after a nested div using index: div 1 > div 2, [div 3] 1`] = `Object {- "insertedInstance": Object {- "children": Array [],- "component": "Box",- "id": "3",- "style": Object {- "boxSizing": Object {- "type": "keyword",- "value": "border-box",- },- "minHeight": Object {- "type": "unit",- "unit": "px",- "value": 100,- },+ "children": Array [+ Object {+ "children": Array [],+ "component": "Box",+ "id": "2",+ "style": Object {},},- },- "instance": Object {- "children": Array [- Object {- "children": Array [],- "component": "Box",- "id": "2",- "style": Object {},- },- Object {- "children": Array [],- "component": "Box",- "id": "3",- "style": Object {- "boxSizing": Object {- "type": "keyword",- "value": "border-box",- },- "minHeight": Object {- "type": "unit",- "unit": "px",- "value": 100,- },- },- },- ],- "component": "Box",- "id": "1",- "style": Object {},- },+ Object {+ "children": Array [],+ "component": "Box",+ "id": "3",+ "style": Object {},+ },+ ],+ "component": "Box",+ "id": "1",+ "style": Object {},}`;exports[`Insert instance before a nested div using index: div 1 > [div 3], div 2 1`] = `Object {- "insertedInstance": Object {- "children": Array [],- "component": "Box",- "id": "3",- "style": Object {- "boxSizing": Object {- "type": "keyword",- "value": "border-box",- },- "minHeight": Object {- "type": "unit",- "unit": "px",- "value": 100,- },+ "children": Array [+ Object {+ "children": Array [],+ "component": "Box",+ "id": "3",+ "style": Object {},},- },- "instance": Object {- "children": Array [- Object {- "children": Array [],- "component": "Box",- "id": "3",- "style": Object {- "boxSizing": Object {- "type": "keyword",- "value": "border-box",- },- "minHeight": Object {- "type": "unit",- "unit": "px",- "value": 100,- },- },- },- Object {- "children": Array [],- "component": "Box",- "id": "2",- "style": Object {},- },- ],- "component": "Box",- "id": "1",- "style": Object {},- },+ Object {+ "children": Array [],+ "component": "Box",+ "id": "2",+ "style": Object {},+ },+ ],+ "component": "Box",+ "id": "1",+ "style": Object {},}`;exports[`Insert instance inside a nested div using "end": div 1 > div 2 > [div 3] 1`] = `Object {- "insertedInstance": Object {- "children": Array [],- "component": "Box",- "id": "3",- "style": Object {- "boxSizing": Object {- "type": "keyword",- "value": "border-box",- },- "minHeight": Object {- "type": "unit",- "unit": "px",- "value": 100,- },+ "children": Array [+ Object {+ "children": Array [+ Object {+ "children": Array [],+ "component": "Box",+ "id": "3",+ "style": Object {},+ },+ ],+ "component": "Box",+ "id": "2",+ "style": Object {},},- },- "instance": Object {- "children": Array [- Object {- "children": Array [- Object {- "children": Array [],- "component": "Box",- "id": "3",- "style": Object {- "boxSizing": Object {- "type": "keyword",- "value": "border-box",- },- "minHeight": Object {- "type": "unit",- "unit": "px",- "value": 100,- },- },- },- ],- "component": "Box",- "id": "2",- "style": Object {},- },- ],- "component": "Box",- "id": "1",- "style": Object {},- },+ ],+ "component": "Box",+ "id": "1",+ "style": Object {},}`;diff --git a/app/shared/tree-utils/index.ts b/app/shared/tree-utils/index.tsindex 98920d7582..7a2beedb99 100644--- a/app/shared/tree-utils/index.ts+++ b/app/shared/tree-utils/index.ts@@ -8,3 +8,5 @@ export * from "./set-instance-style";export * from "./set-instance-children";export * from "./reparent-instance";export * from "./get-instance-path";+export * from "./find-closest-sibling-instance";+export * from "./find-parent-instance";diff --git a/app/shared/tree-utils/insert-instance.test.ts b/app/shared/tree-utils/insert-instance.test.tsindex b77ebe91a5..4b6c3a112b 100644--- a/app/shared/tree-utils/insert-instance.test.ts+++ b/app/shared/tree-utils/insert-instance.test.ts@@ -1,5 +1,5 @@import { type Instance } from "@webstudio-is/sdk";-import { insertInstance, type InstanceInsertionSpec } from "./insert-instance";+import { insertInstanceMutable } from "./insert-instance";import { createInstance } from "./create-instance";const instance = createInstance({ id: "3", component: "Box" });@@ -19,13 +19,13 @@ describe("Insert instance", () => {},],};- const instanceInsertionSpec: InstanceInsertionSpec = {- instance,++ const hasInserted = insertInstanceMutable(rootInstance, instance, {parentId: "2",position: "end",- };- const result = insertInstance(instanceInsertionSpec, rootInstance);- expect(result).toMatchSnapshot();+ });+ expect(hasInserted).toBeTruthy();+ expect(rootInstance).toMatchSnapshot();});test("after a nested div using index: div 1 > div 2, [div 3]", () => {@@ -42,13 +42,13 @@ describe("Insert instance", () => {},],};- const instanceInsertionSpec: InstanceInsertionSpec = {- instance,++ const hasInserted = insertInstanceMutable(rootInstance, instance, {parentId: "1",position: 1,- };- const result = insertInstance(instanceInsertionSpec, rootInstance);- expect(result).toMatchSnapshot();+ });+ expect(hasInserted).toBeTruthy();+ expect(rootInstance).toMatchSnapshot();});test("before a nested div using index: div 1 > [div 3], div 2", () => {@@ -65,13 +65,12 @@ describe("Insert instance", () => {},],};- const instanceInsertionSpec: InstanceInsertionSpec = {- instance,+ const hasInserted = insertInstanceMutable(rootInstance, instance, {parentId: "1",position: 0,- };- const result = insertInstance(instanceInsertionSpec, rootInstance);- expect(result).toMatchSnapshot();+ });+ expect(hasInserted).toBeTruthy();+ expect(rootInstance).toMatchSnapshot();});test(`after a nested div using "end": div 1 > div 2, [div 3]`, () => {@@ -88,12 +87,12 @@ describe("Insert instance", () => {},],};- const instanceInsertionSpec: InstanceInsertionSpec = {- instance,++ const hasInserted = insertInstanceMutable(rootInstance, instance, {parentId: "1",position: "end",- };- const result = insertInstance(instanceInsertionSpec, rootInstance);- expect(result).toMatchSnapshot();+ });+ expect(hasInserted).toBeTruthy();+ expect(rootInstance).toMatchSnapshot();});});diff --git a/app/shared/tree-utils/insert-instance.ts b/app/shared/tree-utils/insert-instance.tsindex c16bd703ca..d801ab452f 100644--- a/app/shared/tree-utils/insert-instance.ts+++ b/app/shared/tree-utils/insert-instance.ts@@ -1,9 +1,6 @@-import produce from "immer";import { type Instance } from "@webstudio-is/sdk";-import { populateInstance } from "./populate";export type InstanceInsertionSpec = {- instance: Instance;parentId: Instance["id"];position: number | "end";};@@ -11,7 +8,7 @@ export type InstanceInsertionSpec = {export const insertInstanceMutable = (rootInstance: Instance,instance: Instance,- spec: Pick<InstanceInsertionSpec, "parentId" | "position">+ spec: InstanceInsertionSpec): boolean => {if (spec.parentId !== rootInstance.id) {for (const child of rootInstance.children) {@@ -36,22 +33,3 @@ export const insertInstanceMutable = (return true;};--export const insertInstance = (- spec: InstanceInsertionSpec,- rootInstance: Instance,- options: { populate?: boolean } = { populate: true }-) => {- const populatedInstance = options.populate- ? populateInstance(spec.instance)- : spec.instance;-- const updatedInstance = produce(rootInstance, (draftRootInstance) => {- insertInstanceMutable(draftRootInstance, populatedInstance, spec);- });-- return {- instance: updatedInstance,- insertedInstance: populatedInstance,- };-};