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.

Add utilities generator to sdk (#2098)

Bogdan Chadkinb8a7a40dd514
diff --git a/packages/jest-config/index.js b/packages/jest-config/index.js
index 9132f2cf1f..a81058a635 100644
--- a/packages/jest-config/index.js
+++ b/packages/jest-config/index.js
@@ -15,4 +15,5 @@ module.exports = {
"^~/(.*)$": "<rootDir>/src/$1",
},
extensionsToTreatAsEsm: [".ts", ".tsx"],
+ prettierPath: null,
};
diff --git a/packages/react-sdk/src/component-renderer.tsx b/packages/react-sdk/src/component-renderer.tsx
index 5b01bda671..edb76f512e 100644
--- a/packages/react-sdk/src/component-renderer.tsx
+++ b/packages/react-sdk/src/component-renderer.tsx
@@ -111,30 +111,35 @@ export const renderComponentTemplate = ({
]),
},
}}
- executeComputingExpressions={(values) => {
- const expressions = new Map<string, string>();
- for (const dataSource of data.dataSources) {
- const name = encodeDataSourceVariable(dataSource.id);
- if (dataSource.type === "expression") {
- expressions.set(name, dataSource.code);
+ utils={{
+ indexesWithinAncestors: getIndexesWithinAncestors(
+ metas,
+ new Map(instances),
+ ["root"]
+ ),
+ executeComputingExpressions: (values) => {
+ const expressions = new Map<string, string>();
+ for (const dataSource of data.dataSources) {
+ const name = encodeDataSourceVariable(dataSource.id);
+ if (dataSource.type === "expression") {
+ expressions.set(name, dataSource.code);
+ }
}
- }
- return decodeVariablesMap(
- executeComputingExpressions(expressions, encodeVariablesMap(values))
- );
- }}
- executeEffectfulExpression={(code, args, values) => {
- return decodeVariablesMap(
- executeEffectfulExpression(code, args, encodeVariablesMap(values))
- );
+ return decodeVariablesMap(
+ executeComputingExpressions(
+ expressions,
+ encodeVariablesMap(values)
+ )
+ );
+ },
+ executeEffectfulExpression: (code, args, values) => {
+ return decodeVariablesMap(
+ executeEffectfulExpression(code, args, encodeVariablesMap(values))
+ );
+ },
}}
Component={WebstudioComponent}
components={new Map(Object.entries(components))}
- indexesWithinAncestors={getIndexesWithinAncestors(
- metas,
- new Map(instances),
- ["root"]
- )}
/>
</>
);
diff --git a/packages/react-sdk/src/generator.test.ts b/packages/react-sdk/src/generator.test.ts
new file mode 100644
index 0000000000..2c59fb9f22
--- /dev/null
+++ b/packages/react-sdk/src/generator.test.ts
@@ -0,0 +1,169 @@
+import { expect, test } from "@jest/globals";
+import { generateUtilsExport } from "./generator";
+
+test("generates utils", () => {
+ expect(
+ generateUtilsExport({
+ page: {
+ id: "",
+ path: "",
+ name: "",
+ title: "",
+ meta: {},
+ rootInstanceId: "tabs",
+ },
+ metas: new Map([
+ ["Tabs", { type: "container", label: "", icon: "" }],
+ [
+ "TabsContent",
+ {
+ type: "container",
+ label: "",
+ icon: "",
+ indexWithinAncestor: "Tabs",
+ },
+ ],
+ ]),
+ instances: new Map([
+ [
+ "tabs",
+ {
+ id: "tabs",
+ type: "instance",
+ component: "Tabs",
+ children: [
+ { type: "id", value: "content1" },
+ { type: "id", value: "content2" },
+ ],
+ },
+ ],
+
+ [
+ "content1",
+ {
+ id: "content1",
+ type: "instance",
+ component: "TabsContent",
+ children: [],
+ },
+ ],
+
+ [
+ "content2",
+ {
+ id: "content2",
+ type: "instance",
+ component: "TabsContent",
+ children: [],
+ },
+ ],
+ ]),
+ props: new Map([
+ [
+ "open",
+ {
+ type: "dataSource",
+ id: "open",
+ instanceId: "tabs",
+ name: "open",
+ value: "tabsOpen",
+ },
+ ],
+
+ [
+ "onOpenChange",
+ {
+ type: "action",
+ id: "onOpenChange",
+ instanceId: "tabs",
+ name: "onOpenChange",
+ value: [
+ {
+ type: "execute",
+ args: ["open"],
+ code: `$ws$dataSource$tabsOpen = open`,
+ },
+ ],
+ },
+ ],
+ ]),
+ dataSources: new Map([
+ [
+ "tabsOpen",
+ {
+ id: "tabsOpen",
+ name: "tabsOpen",
+ scopeInstanceId: "tabs",
+ type: "variable",
+ value: { type: "string", value: "0" },
+ },
+ ],
+ ]),
+ })
+ ).toMatchInlineSnapshot(`
+"
+ /* eslint-disable */
+
+ const indexesWithinAncestors = new Map<string, number>([
+ ["content1", 0],
+["content2", 1],
+
+ ]);
+
+ const rawExecuteComputingExpressions = (
+ _variables: Map<string, unknown>
+ ): Map<string, unknown> => {
+ return new Map([
+]);
+ };
+ const executeComputingExpressions = (variables: Map<string, unknown>) => {
+ const encodedvariables = sdk.encodeVariablesMap(variables);
+ const encodedResult = rawExecuteComputingExpressions(encodedvariables);
+ return sdk.decodeVariablesMap(encodedResult);
+ };
+
+ const generatedEffectfulExpressions = new Map<
+ string,
+ (args: Map<string, any>, variables: Map<string, any>) => Map<string, unknown>
+ >([
+ ["$ws$dataSource$tabsOpen = open", (_args: Map<string, any>, _variables: Map<string, any>) => { let open = _args.get('open');
+let $ws$dataSource$tabsOpen;
+$ws$dataSource$tabsOpen = open;
+return new Map([
+ ['$ws$dataSource$tabsOpen', $ws$dataSource$tabsOpen],
+]); })],
+
+ ]);
+
+ const rawExecuteEffectfulExpression = (
+ code: string,
+ args: Map<string, unknown>,
+ variables: Map<string, unknown>
+ ): Map<string, unknown> => {
+ if(generatedEffectfulExpressions.has(code)) {
+ return generatedEffectfulExpressions.get(code)!(args, variables);
+ }
+ console.error("Effectful expression not found", code);
+ throw new Error("Effectful expression not found");
+ };
+
+ const executeEffectfulExpression = (
+ code: string,
+ args: Map<string, unknown>,
+ variables: Map<string, unknown>
+ ) => {
+ const encodedvariables = sdk.encodeVariablesMap(variables);
+ const encodedResult = rawExecuteEffectfulExpression(code, args, encodedvariables);
+ return sdk.decodeVariablesMap(encodedResult);
+ };
+
+ export const utils = {
+ indexesWithinAncestors,
+ executeComputingExpressions,
+ executeEffectfulExpression,
+ };
+
+ /* eslint-enable */
+ "
+`);
+});
diff --git a/packages/react-sdk/src/generator.ts b/packages/react-sdk/src/generator.ts
new file mode 100644
index 0000000000..a73845e8f4
--- /dev/null
+++ b/packages/react-sdk/src/generator.ts
@@ -0,0 +1,147 @@
+import type {
+ DataSources,
+ Instance,
+ Instances,
+ Page,
+ Props,
+} from "@webstudio-is/project-build";
+import type { WsComponentMeta } from "./components/component-meta";
+import {
+ getIndexesWithinAncestors,
+ type IndexesWithinAncestors,
+} from "./instance-utils";
+import {
+ encodeDataSourceVariable,
+ generateComputingExpressions,
+ generateEffectfulExpression,
+} from "./expression";
+import type { DataSourceValues } from "./context";
+
+type PageData = {
+ page: Page;
+ metas: Map<Instance["component"], WsComponentMeta>;
+ instances: Instances;
+ props: Props;
+ dataSources: DataSources;
+};
+
+export type GeneratedUtils = {
+ indexesWithinAncestors: IndexesWithinAncestors;
+ executeComputingExpressions: (values: DataSourceValues) => DataSourceValues;
+ executeEffectfulExpression: (
+ expression: string,
+ args: DataSourceValues,
+ values: DataSourceValues
+ ) => DataSourceValues;
+};
+
+/**
+ * Generates data based utilities at build time
+ * Requires this import statement in scope
+ * import * as sdk from "@webstudio-is/react-sdk";
+ */
+export const generateUtilsExport = (siteData: PageData) => {
+ const indexesWithinAncestors = getIndexesWithinAncestors(
+ siteData.metas,
+ siteData.instances,
+ [siteData.page.rootInstanceId]
+ );
+ let indexesWithinAncestorsEntries = "";
+ for (const [key, value] of indexesWithinAncestors) {
+ const keyString = JSON.stringify(key);
+ const valueString = JSON.stringify(value);
+ indexesWithinAncestorsEntries += `[${keyString}, ${valueString}],\n`;
+ }
+ const generatedIndexesWithinAncestors = `
+ const indexesWithinAncestors = new Map<string, number>([
+ ${indexesWithinAncestorsEntries}
+ ]);
+ `;
+
+ const variables = new Set<string>();
+ const expressions = new Map<string, string>();
+ for (const dataSource of siteData.dataSources.values()) {
+ if (dataSource.type === "variable") {
+ variables.add(encodeDataSourceVariable(dataSource.id));
+ }
+ if (dataSource.type === "expression") {
+ expressions.set(encodeDataSourceVariable(dataSource.id), dataSource.code);
+ }
+ }
+ const generatedExecuteComputingExpressions = `
+ const rawExecuteComputingExpressions = (
+ _variables: Map<string, unknown>
+ ): Map<string, unknown> => {
+ ${generateComputingExpressions(expressions, variables)}
+ };
+ const executeComputingExpressions = (variables: Map<string, unknown>) => {
+ const encodedvariables = sdk.encodeVariablesMap(variables);
+ const encodedResult = rawExecuteComputingExpressions(encodedvariables);
+ return sdk.decodeVariablesMap(encodedResult);
+ };
+ `;
+
+ let effectfulExpressionsEntries = "";
+ for (const prop of siteData.props.values()) {
+ if (prop.type === "action") {
+ for (const executableValue of prop.value) {
+ const codeString = JSON.stringify(executableValue.code);
+ const generatedCode = generateEffectfulExpression(
+ executableValue.code,
+ new Set(executableValue.args),
+ variables
+ );
+ const generatedFunction = `(_args: Map<string, any>, _variables: Map<string, any>) => { ${generatedCode} })`;
+
+ effectfulExpressionsEntries += `[${codeString}, ${generatedFunction}],\n`;
+ }
+ }
+ }
+ const generatedExecuteEffectfulExpression = `const generatedEffectfulExpressions = new Map<
+ string,
+ (args: Map<string, any>, variables: Map<string, any>) => Map<string, unknown>
+ >([
+ ${effectfulExpressionsEntries}
+ ]);
+
+ const rawExecuteEffectfulExpression = (
+ code: string,
+ args: Map<string, unknown>,
+ variables: Map<string, unknown>
+ ): Map<string, unknown> => {
+ if(generatedEffectfulExpressions.has(code)) {
+ return generatedEffectfulExpressions.get(code)!(args, variables);
+ }
+ console.error("Effectful expression not found", code);
+ throw new Error("Effectful expression not found");
+ };
+
+ const executeEffectfulExpression = (
+ code: string,
+ args: Map<string, unknown>,
+ variables: Map<string, unknown>
+ ) => {
+ const encodedvariables = sdk.encodeVariablesMap(variables);
+ const encodedResult = rawExecuteEffectfulExpression(code, args, encodedvariables);
+ return sdk.decodeVariablesMap(encodedResult);
+ };
+ `;
+
+ return `
+ /* eslint-disable */
+
+ ${generatedIndexesWithinAncestors.trim()}
+
+ ${generatedExecuteComputingExpressions.trim()}
+
+ ${generatedExecuteEffectfulExpression.trim()}
+
+ export const utils = {
+ indexesWithinAncestors,
+ executeComputingExpressions,
+ executeEffectfulExpression,
+ };
+
+ /* eslint-enable */
+ `;
+};
diff --git a/packages/react-sdk/src/tree/root.ts b/packages/react-sdk/src/tree/root.ts
index fbb1214c53..ddca8b1b6c 100644
--- a/packages/react-sdk/src/tree/root.ts
+++ b/packages/react-sdk/src/tree/root.ts
@@ -21,7 +21,7 @@ import {
import { getPropsByInstanceId } from "../props";
import type { Components } from "../components/components-utils";
import type { Params, DataSourceValues } from "../context";
-import type { IndexesWithinAncestors } from "../instance-utils";
+import type { GeneratedUtils } from "../generator";
export type Data = {
page: Page;
@@ -37,13 +37,7 @@ export type RootPropsData = Omit<Data, "build"> & {
type RootProps = {
data: RootPropsData;
- indexesWithinAncestors: IndexesWithinAncestors;
- executeComputingExpressions: (values: DataSourceValues) => DataSourceValues;
- executeEffectfulExpression: (
- expression: string,
- args: DataSourceValues,
- values: DataSourceValues
- ) => DataSourceValues;
+ utils: GeneratedUtils;
Component?: ForwardRefExoticComponent<
WebstudioComponentProps & RefAttributes<HTMLElement>
>;
@@ -53,13 +47,16 @@ type RootProps = {
export const InstanceRoot = ({
data,
- indexesWithinAncestors,
- executeComputingExpressions,
- executeEffectfulExpression,
+ utils,
Component,
components,
scripts,
}: RootProps): JSX.Element | null => {
+ const {
+ indexesWithinAncestors,
+ executeComputingExpressions,
+ executeEffectfulExpression,
+ } = utils;
const dataSourceVariablesStoreRef = useRef<
undefined | WritableAtom<DataSourceValues>
>(undefined);