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.

refactor: simplify template format (#4607)

Bogdan Chadkinb1b607e9c473
diff --git a/apps/builder/app/shared/matcher.test.tsx b/apps/builder/app/shared/matcher.test.tsx
index 910061729d..b9a4617071 100644
--- a/apps/builder/app/shared/matcher.test.tsx
+++ b/apps/builder/app/shared/matcher.test.tsx
@@ -1,10 +1,14 @@
import { describe, expect, test, vi } from "vitest";
-import type { JSX } from "react";
-import { renderJsx, $, ExpressionValue } from "@webstudio-is/template";
+import {
+ renderJsx,
+ $,
+ ExpressionValue,
+ renderTemplate,
+} from "@webstudio-is/template";
import { coreMetas } from "@webstudio-is/react-sdk";
import * as baseMetas from "@webstudio-is/sdk-components-react/metas";
import type { WsComponentMeta } from "@webstudio-is/react-sdk";
-import type { Matcher, WebstudioFragment } from "@webstudio-is/sdk";
+import type { Matcher } from "@webstudio-is/sdk";
import {
findClosestNonTextualContainer,
findClosestInstanceMatchingFragment,
@@ -754,23 +758,6 @@ describe("is tree matching", () => {
});
describe("find closest instance matching fragment", () => {
- const createFragment = (element: JSX.Element): WebstudioFragment => {
- const { instances } = renderJsx(element);
- const instancesArray = Array.from(instances.values());
- return {
- children: instancesArray[0].children,
- instances: instancesArray,
- styleSourceSelections: [],
- styleSources: [],
- breakpoints: [],
- styles: [],
- dataSources: [],
- resources: [],
- props: [],
- assets: [],
- };
- };
-
test("finds closest list with list item fragment", () => {
const { instances } = renderJsx(
<$.Body ws:id="body">
@@ -779,12 +766,7 @@ describe("find closest instance matching fragment", () => {
</$.List>
</$.Body>
);
- const fragment = createFragment(
- // only children are tested
- <>
- <$.ListItem ws:id="new"></$.ListItem>
- </>
- );
+ const fragment = renderTemplate(<$.ListItem ws:id="new"></$.ListItem>);
expect(
findClosestInstanceMatchingFragment({
metas,
@@ -818,12 +800,7 @@ describe("find closest instance matching fragment", () => {
<$.Button ws:id="button"></$.Button>
</$.Body>
);
- const fragment = createFragment(
- // only children are tested
- <>
- <$.Button ws:id="new"></$.Button>
- </>
- );
+ const fragment = renderTemplate(<$.Button ws:id="new"></$.Button>);
expect(
findClosestInstanceMatchingFragment({
metas,
@@ -840,8 +817,7 @@ describe("find closest instance matching fragment", () => {
<$.Button ws:id="button"></$.Button>
</$.Body>
);
- const fragment = createFragment(
- // only children are tested
+ const fragment = renderTemplate(
<>
<$.Button ws:id="new-button"></$.Button>
<$.Text ws:id="new-text"></$.Text>
@@ -860,12 +836,7 @@ describe("find closest instance matching fragment", () => {
test("report first error", () => {
const onError = vi.fn();
const { instances } = renderJsx(<$.Body ws:id="body"></$.Body>);
- const fragment = createFragment(
- // only children are tested
- <>
- <$.ListItem ws:id="listitem"></$.ListItem>
- </>
- );
+ const fragment = renderTemplate(<$.ListItem ws:id="listitem"></$.ListItem>);
findClosestInstanceMatchingFragment({
metas,
instances,
diff --git a/apps/builder/app/shared/matcher.ts b/apps/builder/app/shared/matcher.ts
index 73ae06102f..9780781503 100644
--- a/apps/builder/app/shared/matcher.ts
+++ b/apps/builder/app/shared/matcher.ts
@@ -244,7 +244,8 @@ export const findClosestInstanceMatchingFragment = ({
instances: Instances;
metas: Map<string, WsComponentMeta>;
instanceSelector: InstanceSelector;
- fragment: WebstudioFragment;
+ // require only subset of fragment
+ fragment: Pick<WebstudioFragment, "children" | "instances">;
onError?: (message: string) => void;
}) => {
const mergedInstances = new Map(instances);
diff --git a/packages/template/src/jsx.test.tsx b/packages/template/src/jsx.test.tsx
index 9221b91307..4936ec5708 100644
--- a/packages/template/src/jsx.test.tsx
+++ b/packages/template/src/jsx.test.tsx
@@ -5,164 +5,148 @@ import {
ExpressionValue,
PageValue,
ParameterValue,
- renderJsx,
+ renderTemplate,
} from "./jsx";
test("render jsx into instances with generated id", () => {
- const { instances } = renderJsx(
+ const { instances } = renderTemplate(
<$.Body>
<$.Box></$.Box>
<$.Box></$.Box>
</$.Body>
);
- expect(instances).toEqual(
- new Map([
- [
- "0",
- {
- type: "instance",
- id: "0",
- component: "Body",
- children: [
- { type: "id", value: "1" },
- { type: "id", value: "2" },
- ],
- },
- ],
- [
- "1",
- {
- type: "instance",
- id: "1",
- component: "Box",
- children: [],
- },
- ],
- [
- "2",
- {
- type: "instance",
- id: "2",
- component: "Box",
- children: [],
- },
- ],
- ])
- );
+ expect(instances).toEqual([
+ {
+ type: "instance",
+ id: "0",
+ component: "Body",
+ children: [
+ { type: "id", value: "1" },
+ { type: "id", value: "2" },
+ ],
+ },
+ {
+ type: "instance",
+ id: "1",
+ component: "Box",
+ children: [],
+ },
+ {
+ type: "instance",
+ id: "2",
+ component: "Box",
+ children: [],
+ },
+ ]);
});
test("override generated ids with ws:id prop", () => {
- const { instances } = renderJsx(
+ const { instances } = renderTemplate(
<$.Body ws:id="custom1">
<$.Box ws:id="custom2">
<$.Span ws:id="custom3"></$.Span>
</$.Box>
</$.Body>
);
- expect(instances).toEqual(
- new Map([
- [
- "custom1",
- {
- type: "instance",
- id: "custom1",
- component: "Body",
- children: [{ type: "id", value: "custom2" }],
- },
- ],
- [
- "custom2",
- {
- type: "instance",
- id: "custom2",
- component: "Box",
- children: [{ type: "id", value: "custom3" }],
- },
- ],
- [
- "custom3",
- {
- type: "instance",
- id: "custom3",
- component: "Span",
- children: [],
- },
- ],
- ])
- );
+ expect(instances).toEqual([
+ {
+ type: "instance",
+ id: "custom1",
+ component: "Body",
+ children: [{ type: "id", value: "custom2" }],
+ },
+ {
+ type: "instance",
+ id: "custom2",
+ component: "Box",
+ children: [{ type: "id", value: "custom3" }],
+ },
+ {
+ type: "instance",
+ id: "custom3",
+ component: "Span",
+ children: [],
+ },
+ ]);
});
test("render text children", () => {
- const { instances } = renderJsx(<$.Body>children</$.Body>);
- expect(instances).toEqual(
- new Map([
- [
- "0",
- {
- type: "instance",
- id: "0",
- component: "Body",
- children: [{ type: "text", value: "children" }],
- },
- ],
- ])
+ const { instances } = renderTemplate(<$.Body>children</$.Body>);
+ expect(instances).toEqual([
+ {
+ type: "instance",
+ id: "0",
+ component: "Body",
+ children: [{ type: "text", value: "children" }],
+ },
+ ]);
+});
+
+test("render template children with top level instance", () => {
+ const { children } = renderTemplate(<$.Box></$.Box>);
+ expect(children).toEqual([{ type: "id", value: "0" }]);
+});
+
+test("render template children with multiple instances from fragment", () => {
+ const { children, instances } = renderTemplate(
+ <>
+ <$.Box></$.Box>
+ <$.Text></$.Text>
+ <$.Button></$.Button>
+ </>
);
+ expect(children).toEqual([
+ { type: "id", value: "0" },
+ { type: "id", value: "1" },
+ { type: "id", value: "2" },
+ ]);
+ expect(instances).toEqual([
+ { type: "instance", id: "0", component: "Box", children: [] },
+ { type: "instance", id: "1", component: "Text", children: [] },
+ { type: "instance", id: "2", component: "Button", children: [] },
+ ]);
});
test("render literal props", () => {
- const { props } = renderJsx(
+ const { props } = renderTemplate(
<$.Body data-string="string" data-number={0}>
<$.Box data-bool={true} data-json={{ param: "value" }}></$.Box>
</$.Body>
);
- expect(props).toEqual(
- new Map([
- [
- "0:data-number",
- {
- id: "0:data-number",
- instanceId: "0",
- name: "data-number",
- type: "number",
- value: 0,
- },
- ],
- [
- "0:data-string",
- {
- id: "0:data-string",
- instanceId: "0",
- name: "data-string",
- type: "string",
- value: "string",
- },
- ],
- [
- "1:data-bool",
- {
- id: "1:data-bool",
- instanceId: "1",
- name: "data-bool",
- type: "boolean",
- value: true,
- },
- ],
- [
- "1:data-json",
- {
- id: "1:data-json",
- instanceId: "1",
- name: "data-json",
- type: "json",
- value: { param: "value" },
- },
- ],
- ])
- );
+ expect(props).toEqual([
+ {
+ id: "0:data-string",
+ instanceId: "0",
+ name: "data-string",
+ type: "string",
+ value: "string",
+ },
+ {
+ id: "0:data-number",
+ instanceId: "0",
+ name: "data-number",
+ type: "number",
+ value: 0,
+ },
+ {
+ id: "1:data-bool",
+ instanceId: "1",
+ name: "data-bool",
+ type: "boolean",
+ value: true,
+ },
+ {
+ id: "1:data-json",
+ instanceId: "1",
+ name: "data-json",
+ type: "json",
+ value: { param: "value" },
+ },
+ ]);
});
test("render defined props", () => {
- const { props } = renderJsx(
+ const { props } = renderTemplate(
<$.Body
data-expression={new ExpressionValue("1 + 1")}
data-parameter={new ParameterValue("parameterId")}
@@ -174,58 +158,41 @@ test("render defined props", () => {
></$.Box>
</$.Body>
);
- expect(props).toEqual(
- new Map([
- [
- "0:data-expression",
- {
- id: "0:data-expression",
- instanceId: "0",
- name: "data-expression",
- type: "expression",
- value: "1 + 1",
- },
- ],
- [
- "0:data-parameter",
- {
- id: "0:data-parameter",
- instanceId: "0",
- name: "data-parameter",
- type: "parameter",
- value: "parameterId",
- },
- ],
- [
- "1:data-asset",
- {
- id: "1:data-asset",
- instanceId: "1",
- name: "data-asset",
- type: "asset",
- value: "assetId",
- },
- ],
- [
- "1:data-page",
- {
- id: "1:data-page",
- instanceId: "1",
- name: "data-page",
- type: "page",
- value: "pageId",
- },
- ],
- [
- "1:data-instance",
- {
- id: "1:data-instance",
- instanceId: "1",
- name: "data-instance",
- type: "page",
- value: { pageId: "pageId", instanceId: "instanceId" },
- },
- ],
- ])
- );
+ expect(props).toEqual([
+ {
+ id: "0:data-expression",
+ instanceId: "0",
+ name: "data-expression",
+ type: "expression",
+ value: "1 + 1",
+ },
+ {
+ id: "0:data-parameter",
+ instanceId: "0",
+ name: "data-parameter",
+ type: "parameter",
+ value: "parameterId",
+ },
+ {
+ id: "1:data-asset",
+ instanceId: "1",
+ name: "data-asset",
+ type: "asset",
+ value: "assetId",
+ },
+ {
+ id: "1:data-page",
+ instanceId: "1",
+ name: "data-page",
+ type: "page",
+ value: "pageId",
+ },
+ {
+ id: "1:data-instance",
+ instanceId: "1",
+ name: "data-instance",
+ type: "page",
+ value: { pageId: "pageId", instanceId: "instanceId" },
+ },
+ ]);
});
diff --git a/packages/template/src/jsx.ts b/packages/template/src/jsx.ts
index 67cbca9d77..076f9164bd 100644
--- a/packages/template/src/jsx.ts
+++ b/packages/template/src/jsx.ts
@@ -1,43 +1,43 @@
-import type { JSX, ReactNode } from "react";
-import type { Instances, Props } from "@webstudio-is/sdk";
+import { Fragment, type JSX, type ReactNode } from "react";
+import type { Instance, Instances, Prop, Props } from "@webstudio-is/sdk";
export class ExpressionValue {
- value;
+ value: string;
constructor(expression: string) {
this.value = expression;
}
}
export class ParameterValue {
- value;
- constructor(dataSourceID: string) {
- this.value = dataSourceID;
+ value: string;
+ constructor(dataSourceId: string) {
+ this.value = dataSourceId;
}
}
export class ResourceValue {
- value;
+ value: string;
constructor(resourceId: string) {
this.value = resourceId;
}
}
export class ActionValue {
- value;
+ value: { type: "execute"; args: string[]; code: string };
constructor(args: string[], code: string) {
- this.value = { type: "execute" as const, args, code };
+ this.value = { type: "execute", args, code };
}
}
export class AssetValue {
- value;
+ value: string;
constructor(assetId: string) {
this.value = assetId;
}
}
export class PageValue {
- value;
+ value: string | { pageId: string; instanceId: string };
constructor(pageId: string, instanceId?: string) {
if (instanceId) {
this.value = { pageId, instanceId };
@@ -49,14 +49,31 @@ export class PageValue {
const traverseJsx = (
element: JSX.Element,
- callback: (element: JSX.Element, children: JSX.Element[]) => void
+ callback: (
+ element: JSX.Element,
+ children: JSX.Element[]
+ ) => Instance["children"][number]
) => {
const children = Array.isArray(element.props?.children)
? element.props?.children
: element.props?.children
? [element.props?.children]
: [];
- callback(element, children);
+ const result: Instance["children"] = [];
+ if (element.type === Fragment) {
+ for (const child of children) {
+ if (typeof child === "string") {
+ continue;
+ }
+ if (child instanceof ExpressionValue) {
+ continue;
+ }
+ result.push(...traverseJsx(child, callback));
+ }
+ return result;
+ }
+ const child = callback(element, children);
+ result.push(child);
for (const child of children) {
if (typeof child === "string") {
continue;
@@ -66,12 +83,19 @@ const traverseJsx = (
}
traverseJsx(child, callback);
}
+ return result;
};
-export const renderJsx = (root: JSX.Element) => {
+type WebstudioTemplate = {
+ children: Instance["children"];
+ instances: Instance[];
+ props: Prop[];
+};
+
+export const renderTemplate = (root: JSX.Element): WebstudioTemplate => {
let lastId = -1;
- const instances: Instances = new Map();
- const props: Props = new Map();
+ const instances: Instance[] = [];
+ const props: Prop[] = [];
const ids = new Map<unknown, string>();
const getId = (key: unknown) => {
let id = ids.get(key);
@@ -82,7 +106,7 @@ export const renderJsx = (root: JSX.Element) => {
}
return id;
};
- traverseJsx(root, (element, children) => {
+ const children = traverseJsx(root, (element, children) => {
const instanceId = element.props?.["ws:id"] ?? getId(element);
for (const [name, value] of Object.entries({ ...element.props })) {
if (name === "ws:id" || name === "ws:label" || name === "children") {
@@ -91,45 +115,45 @@ export const renderJsx = (root: JSX.Element) => {
const propId = `${instanceId}:${name}`;
const base = { id: propId, instanceId, name };
if (value instanceof ExpressionValue) {
- props.set(propId, { ...base, type: "expression", value: value.value });
+ props.push({ ...base, type: "expression", value: value.value });
continue;
}
if (value instanceof ParameterValue) {
- props.set(propId, { ...base, type: "parameter", value: value.value });
+ props.push({ ...base, type: "parameter", value: value.value });
continue;
}
if (value instanceof ResourceValue) {
- props.set(propId, { ...base, type: "resource", value: value.value });
+ props.push({ ...base, type: "resource", value: value.value });
continue;
}
if (value instanceof ActionValue) {
- props.set(propId, { ...base, type: "action", value: [value.value] });
+ props.push({ ...base, type: "action", value: [value.value] });
continue;
}
if (value instanceof AssetValue) {
- props.set(propId, { ...base, type: "asset", value: value.value });
+ props.push({ ...base, type: "asset", value: value.value });
continue;
}
if (value instanceof PageValue) {
- props.set(propId, { ...base, type: "page", value: value.value });
+ props.push({ ...base, type: "page", value: value.value });
continue;
}
if (typeof value === "string") {
- props.set(propId, { ...base, type: "string", value });
+ props.push({ ...base, type: "string", value });
continue;
}
if (typeof value === "number") {
- props.set(propId, { ...base, type: "number", value });
+ props.push({ ...base, type: "number", value });
continue;
}
if (typeof value === "boolean") {
- props.set(propId, { ...base, type: "boolean", value });
+ props.push({ ...base, type: "boolean", value });
continue;
}
- props.set(propId, { ...base, type: "json", value });
+ props.push({ ...base, type: "json", value });
}
const component = element.type.displayName;
- instances.set(instanceId, {
+ const instance: Instance = {
type: "instance",
id: instanceId,
component,
@@ -143,14 +167,32 @@ export const renderJsx = (root: JSX.Element) => {
? { type: "expression", value: child.value }
: { type: "id", value: child.props?.["ws:id"] ?? getId(child) }
),
- });
+ };
+ instances.push(instance);
+ return { type: "id", value: instance.id };
});
return {
+ children,
instances,
props,
};
};
+export const renderJsx = (
+ root: JSX.Element
+): {
+ instances: Instances;
+ props: Props;
+} => {
+ const fragment = renderTemplate(root);
+ return {
+ instances: new Map(
+ fragment.instances.map((instance) => [instance.id, instance])
+ ),
+ props: new Map(fragment.props.map((prop) => [prop.id, prop])),
+ };
+};
+
type ComponentProps = Record<string, unknown> &
Record<`${string}:expression`, string> & {
"ws:id"?: string;
@@ -175,6 +217,6 @@ export const createProxy = (prefix: string): Record<string, Component> => {
);
};
-export const $ = createProxy("");
+export const $: Record<string, Component> = createProxy("");
-export const ws = createProxy("ws:");
+export const ws: Record<string, Component> = createProxy("ws:");
diff --git a/packages/template/tsconfig.json b/packages/template/tsconfig.json
index d2e5040f8f..9648eaf0a1 100644
--- a/packages/template/tsconfig.json
+++ b/packages/template/tsconfig.json
@@ -1,3 +1,6 @@
{
- "extends": "@webstudio-is/tsconfig/base.json"
+ "extends": "@webstudio-is/tsconfig/base.json",
+ "compilerOptions": {
+ "isolatedDeclarations": true
+ }
}