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.

Support generating expressions code (#1894)

Bogdan Chadkinc5a580950193
diff --git a/packages/react-sdk/src/expression.test.ts b/packages/react-sdk/src/expression.test.ts
index f680e433c6..98cede6fef 100644
--- a/packages/react-sdk/src/expression.test.ts
+++ b/packages/react-sdk/src/expression.test.ts
@@ -3,6 +3,7 @@ import {
decodeDataSourceVariable,
encodeDataSourceVariable,
executeExpressions,
+ generateExpressionsComputation,
validateExpression,
} from "./expression";
@@ -61,6 +62,30 @@ test("transform identifiers", () => {
);
});
+test("generate expressions computation", () => {
+ const variables = new Set(["var0"]);
+ const expressions = new Map([
+ ["exp3", "exp2 + exp1"],
+ ["exp1", "var0"],
+ ["exp2", "exp1"],
+ ["exp4", "exp2"],
+ ]);
+ expect(generateExpressionsComputation(variables, expressions))
+ .toMatchInlineSnapshot(`
+ "const var0 = _variables.get('var0');
+ const exp1 = (var0);
+ const exp2 = (exp1);
+ const exp3 = (exp2 + exp1);
+ const exp4 = (exp2);
+ return new Map([
+ ['exp1', exp1],
+ ['exp2', exp2],
+ ['exp3', exp3],
+ ['exp4', exp4],
+ ]);"
+ `);
+});
+
test("execute expression", () => {
const variables = new Map();
const expressions = new Map([["exp1", "1 + 1"]]);
@@ -77,7 +102,7 @@ test("execute expression dependent on variables", () => {
);
});
-test("execute expression dependent on other expressions", () => {
+test("execute expression dependent on another expressions", () => {
const variables = new Map([["var1", 3]]);
const expressions = new Map([
["exp1", "exp0 + 1"],
@@ -100,7 +125,7 @@ test("forbid circular expressions", () => {
]);
expect(() => {
executeExpressions(variables, expressions);
- }).toThrowError(/exp2 is not defined/);
+ }).toThrowError(/Cannot access 'exp0' before initialization/);
});
test("make sure dependency exists", () => {
diff --git a/packages/react-sdk/src/expression.ts b/packages/react-sdk/src/expression.ts
index 4586df559d..bda360b363 100644
--- a/packages/react-sdk/src/expression.ts
+++ b/packages/react-sdk/src/expression.ts
@@ -111,15 +111,42 @@ export const validateExpression = (
return generateCode(expression, true, transformIdentifier);
};
-export const executeExpressions = (
- variables: Map<string, unknown>,
+const sortTopologically = (
+ list: Set<string>,
+ depsById: Map<string, Set<string>>,
+ explored = new Set<string>(),
+ sorted: string[] = []
+) => {
+ for (const id of list) {
+ if (explored.has(id)) {
+ continue;
+ }
+ explored.add(id);
+ const deps = depsById.get(id);
+ if (deps) {
+ sortTopologically(deps, depsById, explored, sorted);
+ }
+ sorted.push(id);
+ }
+ return sorted;
+};
+
+/**
+ * Generates a function body expecting map as _variables argument
+ * and outputing map of results
+ */
+export const generateExpressionsComputation = (
+ variables: Set<string>,
expressions: Map<string, string>
) => {
const depsById = new Map<string, Set<string>>();
for (const [id, code] of expressions) {
const deps = new Set<string>();
validateExpression(code, (identifier) => {
- if (variables.has(identifier) || expressions.has(identifier)) {
+ if (variables.has(identifier)) {
+ return identifier;
+ }
+ if (expressions.has(identifier)) {
deps.add(identifier);
return identifier;
}
@@ -128,38 +155,45 @@ export const executeExpressions = (
depsById.set(id, deps);
}
- // sort topologically
- const sortedExpressions = Array.from(expressions.keys()).sort(
- (left, right) => {
- if (depsById.get(left)?.has(right)) {
- return 1;
- }
- if (depsById.get(right)?.has(left)) {
- return -1;
- }
- return 0;
- }
+ const sortedExpressions = sortTopologically(
+ new Set(expressions.keys()),
+ depsById
);
- // execute chain of expressions
- let header = "";
- for (const [id, value] of variables) {
- header += `const ${id} = ${JSON.stringify(value)};\n`;
- }
+ // generate code computing all expressions
+ let generatedCode = "";
- const values = new Map<string, unknown>();
+ for (const id of variables) {
+ generatedCode += `const ${id} = _variables.get('${id}');\n`;
+ }
for (const id of sortedExpressions) {
const code = expressions.get(id);
if (code === undefined) {
continue;
}
- const executeFn = new Function(`${header}\nreturn (${code});`);
- const value = executeFn();
- header += `const ${id} = ${JSON.stringify(value)};\n`;
- values.set(id, value);
+ generatedCode += `const ${id} = (${code});\n`;
}
+ generatedCode += `return new Map([\n`;
+ for (const id of sortedExpressions) {
+ generatedCode += ` ['${id}', ${id}],\n`;
+ }
+ generatedCode += `]);`;
+
+ return generatedCode;
+};
+
+export const executeExpressions = (
+ variables: Map<string, unknown>,
+ expressions: Map<string, string>
+) => {
+ const generatedCode = generateExpressionsComputation(
+ new Set(variables.keys()),
+ expressions
+ );
+ const executeFn = new Function("_variables", generatedCode);
+ const values = executeFn(variables) as Map<string, unknown>;
return values;
};
diff --git a/packages/react-sdk/src/index.ts b/packages/react-sdk/src/index.ts
index 785c2f53e0..f8d2b90101 100644
--- a/packages/react-sdk/src/index.ts
+++ b/packages/react-sdk/src/index.ts
@@ -22,6 +22,7 @@ export {
export { type Params, ReactSdkContext } from "./context";
export {
validateExpression,
+ generateExpressionsComputation,
executeExpressions,
encodeDataSourceVariable,
decodeDataSourceVariable,
diff --git a/packages/react-sdk/src/tree/root.ts b/packages/react-sdk/src/tree/root.ts
index adc8d5525f..4c626c0fa7 100644
--- a/packages/react-sdk/src/tree/root.ts
+++ b/packages/react-sdk/src/tree/root.ts
@@ -12,45 +12,6 @@ import { WebstudioComponent } from "./webstudio-component";
import { getPropsByInstanceId } from "../props";
import type { Components } from "../components/components-utils";
import type { Params } from "../context";
-import {
- executeExpressions,
- encodeDataSourceVariable,
- decodeDataSourceVariable,
-} from "../expression";
-
-const computeExpressions = (
- dataSources: [DataSource["id"], DataSource][],
- dataSourceValues: Map<DataSource["id"], unknown>
-) => {
- const outputValues = new Map<DataSource["id"], unknown>();
- const variables = new Map<string, unknown>();
- const expressions = new Map<string, string>();
- for (const [dataSourceId, dataSource] of dataSources) {
- const name = encodeDataSourceVariable(dataSourceId);
- if (dataSource.type === "variable") {
- const value =
- dataSourceValues.get(dataSourceId) ?? dataSource.value.value;
- variables.set(name, value);
- outputValues.set(dataSourceId, value);
- }
- if (dataSource.type === "expression") {
- expressions.set(name, dataSource.code);
- }
- }
- try {
- const outputVariables = executeExpressions(variables, expressions);
- for (const [name, value] of outputVariables) {
- const id = decodeDataSourceVariable(name);
- if (id !== undefined) {
- outputValues.set(id, value);
- }
- }
- } catch (error) {
- // eslint-disable-next-line no-console
- console.error(error);
- }
- return outputValues;
-};
export type Data = {
page: Page;
@@ -64,39 +25,58 @@ export type RootPropsData = Omit<Data, "build"> & {
build: Pick<Data["build"], "instances" | "props" | "dataSources">;
};
+type DataSourceValues = Map<DataSource["id"], unknown>;
+
type RootProps = {
data: RootPropsData;
+ computeExpressions: (values: DataSourceValues) => DataSourceValues;
Component?: (props: ComponentProps<typeof WebstudioComponent>) => JSX.Element;
components: Components;
};
export const InstanceRoot = ({
data,
+ computeExpressions,
Component,
components,
}: RootProps): JSX.Element | null => {
const dataSourceVariablesStoreRef = useRef<
- undefined | WritableAtom<Map<DataSource["id"], unknown>>
+ undefined | WritableAtom<DataSourceValues>
>(undefined);
- // initialize store with default data source values
if (dataSourceVariablesStoreRef.current === undefined) {
- const dataSourceVariables = new Map<DataSource["id"], unknown>();
- for (const [dataSourceId, dataSource] of data.build.dataSources) {
- dataSourceVariables.set(dataSourceId, dataSource);
- }
- dataSourceVariablesStoreRef.current = atom(dataSourceVariables);
+ dataSourceVariablesStoreRef.current = atom(new Map());
}
const dataSourceVariablesStore = dataSourceVariablesStoreRef.current;
const dataSourceValuesStoreRef = useRef<
- undefined | ReadableAtom<Map<DataSource["id"], unknown>>
+ undefined | ReadableAtom<DataSourceValues>
>(undefined);
- // initialize store with default data source values
if (dataSourceValuesStoreRef.current === undefined) {
dataSourceValuesStoreRef.current = computed(
dataSourceVariablesStore,
(dataSourceVariables) => {
- return computeExpressions(data.build.dataSources, dataSourceVariables);
+ // set vriables with defaults
+ const dataSourceValues: DataSourceValues = new Map();
+ for (const [dataSourceId, dataSource] of data.build.dataSources) {
+ if (dataSource.type === "variable") {
+ const value =
+ dataSourceVariables.get(dataSourceId) ?? dataSource.value.value;
+ dataSourceValues.set(dataSourceId, value);
+ }
+ }
+
+ // set expression values
+ try {
+ const result = computeExpressions(dataSourceValues);
+ for (const [id, value] of result) {
+ dataSourceValues.set(id, value);
+ }
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.error(error);
+ }
+
+ return dataSourceValues;
}
);
}