Skip to content

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.

update props using transaction

Oleg Isonen17203aa47c52
diff --git a/app/canvas/canvas.tsx b/app/canvas/canvas.tsx
index de60845781..de615a52d5 100644
--- a/app/canvas/canvas.tsx
+++ b/app/canvas/canvas.tsx
@@ -32,6 +32,7 @@ import { WrapperComponentDev } from "./features/wrapper-component";
import { rootInstanceContainer, useRootInstance } from "./shared/nano-values";
import { usePeriodicSync } from "./shared/use-periodic-sync";
import { createTransaction } from "~/lib/sync-engine";
+import { useUpdateProps } from "./shared/props";
const useElementsTree = () => {
const [rootInstance] = useRootInstance();
@@ -81,6 +82,7 @@ type DesignModeProps = {
const DesignMode = ({ treeId }: DesignModeProps) => {
useDragDropHandlers();
useUpdateStyle();
+ useUpdateProps();
usePublishSelectedInstance({ treeId });
useInsertInstance();
useReparentInstance();
diff --git a/app/canvas/shared/props.ts b/app/canvas/shared/props.ts
new file mode 100644
index 0000000000..9a1d7d2792
--- /dev/null
+++ b/app/canvas/shared/props.ts
@@ -0,0 +1,20 @@
+import {
+ type UserPropsUpdates,
+ useSubscribe,
+ allUserPropsContainer,
+} from "@webstudio-is/sdk";
+import { createTransaction, register } from "~/lib/sync-engine";
+import { updateAllUserPropsMutable } from "~/shared/props-utils";
+
+register("props", allUserPropsContainer);
+
+export const useUpdateProps = () => {
+ useSubscribe<"updateProps", UserPropsUpdates>(
+ "updateProps",
+ (userPropsUpdates) => {
+ createTransaction([allUserPropsContainer], (allUserProps) => {
+ updateAllUserPropsMutable(allUserProps, userPropsUpdates);
+ });
+ }
+ );
+};
diff --git a/app/designer/features/sync/use-sync.ts b/app/designer/features/sync/use-sync.ts
index 8f3a227159..9b6868f751 100644
--- a/app/designer/features/sync/use-sync.ts
+++ b/app/designer/features/sync/use-sync.ts
@@ -1,8 +1,4 @@
-import {
- type DeleteProp,
- type UserPropsUpdates,
- type Project,
-} from "@webstudio-is/sdk";
+import { type DeleteProp, type Project } from "@webstudio-is/sdk";
import type { Config } from "~/config";
import { useSubscribe } from "~/designer/features/canvas-iframe";
import { enqueue } from "./queue";
@@ -13,15 +9,6 @@ import { type SyncItem } from "~/lib/sync-engine";
// and backend fetches and updates big objects, so if we send quickly,
// we end up overwriting things
export const useSync = ({ project }: { config: Config; project: Project }) => {
- useSubscribe<"updateProps", UserPropsUpdates>("updateProps", (update) => {
- enqueue(() =>
- fetch(`/rest/props/update`, {
- method: "post",
- body: JSON.stringify(update),
- })
- );
- });
-
useSubscribe<"deleteProp", DeleteProp>(
"deleteProp",
({ propsId, propId }) => {
@@ -34,12 +21,19 @@ export const useSync = ({ project }: { config: Config; project: Project }) => {
}
);
- useSubscribe<"syncChanges", Array<SyncItem>>("syncChanges", (queue) => {
- enqueue(() =>
- fetch(`/rest/patch/${project.devTreeId}`, {
- method: "post",
- body: JSON.stringify(queue),
- })
- );
- });
+ useSubscribe<"syncChanges", Array<SyncItem>>(
+ "syncChanges",
+ (transactions) => {
+ enqueue(() =>
+ fetch(`/rest/patch`, {
+ method: "post",
+ body: JSON.stringify({
+ transactions,
+ treeId: project.devTreeId,
+ projectId: project.id,
+ }),
+ })
+ );
+ }
+ );
};
diff --git a/app/routes/rest/patch.$treeId.ts b/app/routes/rest/patch.ts
similarity index 51%
rename from app/routes/rest/patch.$treeId.ts
rename to app/routes/rest/patch.ts
index b14b3aec23..cb668389ba 100644
--- a/app/routes/rest/patch.$treeId.ts
+++ b/app/routes/rest/patch.ts
@@ -1,14 +1,25 @@
import { type ActionFunction } from "remix";
import * as db from "~/shared/db";
import { type SyncItem } from "~/lib/sync-engine";
+import { type Project, type Tree } from "@webstudio-is/sdk";
-const updaters = { root: db.tree.patchRoot };
+const updaters = {
+ root: db.tree.patchRoot,
+ props: db.props.patch,
+};
type UpdaterKey = keyof typeof updaters;
-export const action: ActionFunction = async ({ request, params }) => {
- if (params.treeId === undefined) return { errors: "Tree id required" };
- const transactions: Array<SyncItem> = await request.json();
+type PatchData = {
+ transactions: Array<SyncItem>;
+ treeId: Tree["id"];
+ projectId: Project["id"];
+};
+
+export const action: ActionFunction = async ({ request }) => {
+ const { treeId, projectId, transactions }: PatchData = await request.json();
+ if (treeId === undefined) return { errors: "Tree id required" };
+ if (projectId === undefined) return { errors: "Project id required" };
// @todo parallelize the updates
// currently not possible because we fetch the entire tree
// and parallelized updates will cause unpredictable side effects
@@ -18,7 +29,7 @@ export const action: ActionFunction = async ({ request, params }) => {
if (namespace in updaters === false) {
return { errors: `Unknown namespace "${namespace}"` };
}
- await updaters[namespace as UpdaterKey](params.treeId, patches);
+ await updaters[namespace as UpdaterKey]({ treeId, projectId }, patches);
}
}
return { status: "ok" };
diff --git a/app/routes/rest/props.update.ts b/app/routes/rest/props.update.ts
deleted file mode 100644
index a10d9132b9..0000000000
--- a/app/routes/rest/props.update.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { type ActionFunction } from "remix";
-import * as db from "~/shared/db";
-
-export const action: ActionFunction = async ({ request }) => {
- // @todo types
- const update = await request.json();
- await db.props.update(update);
- return { status: "ok" };
-};
diff --git a/app/shared/db/props.server.ts b/app/shared/db/props.server.ts
index 5d463330f3..475d61987d 100644
--- a/app/shared/db/props.server.ts
+++ b/app/shared/db/props.server.ts
@@ -5,7 +5,9 @@ import {
type Project,
type InstanceProps,
type Tree,
+ type AllUserProps,
} from "@webstudio-is/sdk";
+import { applyPatches, type Patch } from "immer";
import { prisma, PrismaClientKnownRequestError } from "./prisma.server";
export const loadByProject = async (
@@ -130,3 +132,35 @@ export const clone = async ({
data,
});
};
+
+export const patch = async (
+ { treeId }: { treeId: Tree["id"]; projectId: Project["id"] },
+ patches: Array<Patch>
+) => {
+ const allProps = await loadByTreeId(treeId);
+
+ // We should get rid of this by applying patches on the client to the original
+ // model instead of the instanceId map.
+ // The map is handy for accessing props, but probably should be just cached interface, not the main data structure.
+ const allPropsMapByInstanceId = allProps.reduce((acc, prop) => {
+ acc[prop.instanceId] = prop;
+ return acc;
+ }, {} as AllUserProps);
+ const nextProps = applyPatches<AllUserProps>(
+ allPropsMapByInstanceId,
+ patches
+ );
+
+ await Promise.all(
+ Object.values(nextProps).map(
+ async ({ id, instanceId, treeId, props }) =>
+ await prisma.instanceProps.upsert({
+ where: { id: id },
+ create: { id: id, instanceId, treeId, props },
+ update: {
+ props,
+ },
+ })
+ )
+ );
+};
diff --git a/app/shared/db/tree.server.ts b/app/shared/db/tree.server.ts
index b517efd583..3e0c6244b1 100644
--- a/app/shared/db/tree.server.ts
+++ b/app/shared/db/tree.server.ts
@@ -84,7 +84,10 @@ export const clone = async (id: string) => {
return await create(tree.root);
};
-export const patchRoot = async (treeId: Tree["id"], patches: Array<Patch>) => {
+export const patchRoot = async (
+ { treeId }: { treeId: Tree["id"] },
+ patches: Array<Patch>
+) => {
const tree = await loadById(treeId);
const root = applyPatches(tree.root, patches);
await prisma.tree.update({
diff --git a/app/shared/props-utils/__snapshots__/update-props.test.ts.snap b/app/shared/props-utils/__snapshots__/update-props.test.ts.snap
new file mode 100644
index 0000000000..2c0a5a7ab4
--- /dev/null
+++ b/app/shared/props-utils/__snapshots__/update-props.test.ts.snap
@@ -0,0 +1,80 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`Update props with added prop 1`] = `
+Object {
+ "instanceId": Object {
+ "id": "id",
+ "instanceId": "instanceId",
+ "props": Array [
+ Object {
+ "id": "propId",
+ "prop": "a",
+ "value": "1",
+ },
+ ],
+ "treeId": "treeId",
+ },
+}
+`;
+
+exports[`Update props with deleted props 1`] = `
+Object {
+ "instanceId": Object {
+ "id": "id",
+ "instanceId": "instanceId",
+ "props": Array [
+ Object {
+ "id": "propId",
+ "prop": "a",
+ "value": "1",
+ },
+ ],
+ "treeId": "treeId",
+ },
+}
+`;
+
+exports[`Update props with empty updates 1`] = `
+Object {
+ "instanceId": Object {
+ "id": "id",
+ "instanceId": "instanceId",
+ "props": Array [],
+ "treeId": "treeId",
+ },
+}
+`;
+
+exports[`Update props with renamed prop name 1`] = `
+Object {
+ "instanceId": Object {
+ "id": "id",
+ "instanceId": "instanceId",
+ "props": Array [
+ Object {
+ "id": "propId",
+ "prop": "b",
+ "value": "1",
+ },
+ ],
+ "treeId": "treeId",
+ },
+}
+`;
+
+exports[`Update props with updated prop value 1`] = `
+Object {
+ "instanceId": Object {
+ "id": "id",
+ "instanceId": "instanceId",
+ "props": Array [
+ Object {
+ "id": "propId",
+ "prop": "a",
+ "value": "2",
+ },
+ ],
+ "treeId": "treeId",
+ },
+}
+`;
diff --git a/app/shared/props-utils/index.ts b/app/shared/props-utils/index.ts
new file mode 100644
index 0000000000..234a81bdb5
--- /dev/null
+++ b/app/shared/props-utils/index.ts
@@ -0,0 +1 @@
+export * from "./update-props";
diff --git a/app/shared/props-utils/update-props.test.ts b/app/shared/props-utils/update-props.test.ts
new file mode 100644
index 0000000000..c17b2a80af
--- /dev/null
+++ b/app/shared/props-utils/update-props.test.ts
@@ -0,0 +1,80 @@
+import { type AllUserProps, type UserPropsUpdates } from "@webstudio-is/sdk";
+import { updateAllUserPropsMutable } from "./update-props";
+
+describe("Update props", () => {
+ test("with empty updates", () => {
+ const propsMap: AllUserProps = {
+ instanceId: {
+ id: "id",
+ instanceId: "instanceId",
+ treeId: "treeId",
+ props: [],
+ },
+ };
+ const update: UserPropsUpdates = {
+ propsId: "id",
+ instanceId: "instanceId",
+ treeId: "treeId",
+ updates: [],
+ };
+ updateAllUserPropsMutable(propsMap, update);
+ expect(propsMap).toMatchSnapshot();
+ });
+
+ test("with added prop", () => {
+ const propsMap: AllUserProps = {
+ instanceId: {
+ id: "id",
+ instanceId: "instanceId",
+ treeId: "treeId",
+ props: [],
+ },
+ };
+ const update: UserPropsUpdates = {
+ propsId: "id",
+ instanceId: "instanceId",
+ treeId: "treeId",
+ updates: [{ id: "propId", prop: "a", value: "1" }],
+ };
+ updateAllUserPropsMutable(propsMap, update);
+ expect(propsMap).toMatchSnapshot();
+ });
+
+ test("with updated prop value", () => {
+ const propsMap: AllUserProps = {
+ instanceId: {
+ id: "id",
+ instanceId: "instanceId",
+ treeId: "treeId",
+ props: [{ id: "propId", prop: "a", value: "1" }],
+ },
+ };
+ const update: UserPropsUpdates = {
+ propsId: "id",
+ instanceId: "instanceId",
+ treeId: "treeId",
+ updates: [{ id: "propId", prop: "a", value: "2" }],
+ };
+ updateAllUserPropsMutable(propsMap, update);
+ expect(propsMap).toMatchSnapshot();
+ });
+
+ test("with renamed prop name", () => {
+ const propsMap: AllUserProps = {
+ instanceId: {
+ id: "id",
+ instanceId: "instanceId",
+ treeId: "treeId",
+ props: [{ id: "propId", prop: "a", value: "1" }],
+ },
+ };
+ const update: UserPropsUpdates = {
+ propsId: "id",
+ instanceId: "instanceId",
+ treeId: "treeId",
+ updates: [{ id: "propId", prop: "b", value: "1" }],
+ };
+ updateAllUserPropsMutable(propsMap, update);
+ expect(propsMap).toMatchSnapshot();
+ });
+});
diff --git a/app/shared/props-utils/update-props.ts b/app/shared/props-utils/update-props.ts
new file mode 100644
index 0000000000..63c6ef3d7c
--- /dev/null
+++ b/app/shared/props-utils/update-props.ts
@@ -0,0 +1,25 @@
+import { type AllUserProps, type UserPropsUpdates } from "@webstudio-is/sdk";
+
+export const updateAllUserPropsMutable = (
+ allUserProps: AllUserProps,
+ { instanceId, propsId, treeId, updates }: UserPropsUpdates
+) => {
+ if (instanceId in allUserProps === false) {
+ allUserProps[instanceId] = {
+ id: propsId,
+ instanceId,
+ treeId,
+ props: [],
+ };
+ }
+ const instanceProps = allUserProps[instanceId];
+ for (const update of updates) {
+ const prop = instanceProps.props.find(({ id }) => id === update.id);
+ if (prop === undefined) {
+ instanceProps.props.push(update);
+ } else {
+ prop.prop = update.prop;
+ prop.value = update.value;
+ }
+ }
+};
diff --git a/app/shared/tree-utils/__snapshots__/reparent-instance.test.ts.snap b/app/shared/tree-utils/__snapshots__/reparent-instance.test.ts.snap
deleted file mode 100644
index 7a84f997a5..0000000000
--- a/app/shared/tree-utils/__snapshots__/reparent-instance.test.ts.snap
+++ /dev/null
@@ -1,24 +0,0 @@
-// Jest Snapshot v1, https://goo.gl/fbAQLP
-
-exports[`Reparent instance div 1 > div 2, div 3 => div 1 > div 2 > div 3 1`] = `
-Object {
- "children": Array [
- Object {
- "children": Array [
- Object {
- "children": Array [],
- "component": "Box",
- "id": "3",
- "style": Object {},
- },
- ],
- "component": "Box",
- "id": "2",
- "style": Object {},
- },
- ],
- "component": "Box",
- "id": "1",
- "style": Object {},
-}
-`;