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 data source expressions (#1882)

Bogdan Chadkin114817c26626
diff --git a/apps/builder/app/builder/features/props-panel/props-panel.tsx b/apps/builder/app/builder/features/props-panel/props-panel.tsx
index 9f25f39d52..9ac71dd627 100644
--- a/apps/builder/app/builder/features/props-panel/props-panel.tsx
+++ b/apps/builder/app/builder/features/props-panel/props-panel.tsx
@@ -18,6 +18,7 @@ import {
import type { Publish } from "~/shared/pubsub";
import {
dataSourceValuesStore,
+ dataSourceVariablesStore,
dataSourcesStore,
propsIndexStore,
propsStore,
@@ -208,6 +209,22 @@ export const PropsPanel = (props: PropsPanelProps) => {
);
};
+const getPropTypeAndValue = (value: unknown) => {
+ if (typeof value === "boolean") {
+ return { type: "boolean", value } as const;
+ }
+ if (typeof value === "number") {
+ return { type: "number", value } as const;
+ }
+ if (typeof value === "string") {
+ return { type: "string", value } as const;
+ }
+ if (Array.isArray(value)) {
+ return { type: "string[]", value } as const;
+ }
+ throw Error(`Unexpected prop value ${value}`);
+};
+
export const PropsPanelContainer = ({
selectedInstance: instance,
publish,
@@ -249,11 +266,8 @@ export const PropsPanelContainer = ({
instanceId: prop.instanceId,
name: prop.name,
required: prop.required,
- type: dataSource.type,
- // temporary suppression for simplification
- // will be refactored once data sources ui is ready
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- value: (dataSourceValue ?? dataSource?.value) as any,
+ // infer type from value
+ ...getPropTypeAndValue(dataSourceValue),
} satisfies Prop,
];
}) ?? [];
@@ -268,9 +282,9 @@ export const PropsPanelContainer = ({
// update data source instead when real prop has data source type
if (prop?.type === "dataSource") {
const dataSourceId = prop.value;
- const dataSourceValues = new Map(dataSourceValuesStore.get());
- dataSourceValues.set(dataSourceId, update.value);
- dataSourceValuesStore.set(dataSourceValues);
+ const dataSourceVariables = new Map(dataSourceVariablesStore.get());
+ dataSourceVariables.set(dataSourceId, update.value);
+ dataSourceVariablesStore.set(dataSourceVariables);
} else {
store.createTransaction([propsStore], (props) => {
props.set(update.id, update);
diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsx
index 3eb46435f5..76607883ff 100644
--- a/apps/builder/app/canvas/canvas.tsx
+++ b/apps/builder/app/canvas/canvas.tsx
@@ -1,7 +1,7 @@
import { useMemo, useEffect } from "react";
import { useStore } from "@nanostores/react";
import { computed } from "nanostores";
-import type { DataSource, Instances, Page } from "@webstudio-is/project-build";
+import type { Instances, Page } from "@webstudio-is/project-build";
import {
type Params,
type Components,
@@ -33,7 +33,7 @@ import {
registerComponentMetas,
registerComponentPropsMetas,
dataSourceValuesStore,
- dataSourcesStore,
+ dataSourceVariablesStore,
} from "~/shared/nano-states";
import { useDragAndDrop } from "./shared/use-drag-drop";
import { useCopyPaste } from "~/shared/copy-paste";
@@ -105,23 +105,11 @@ const useElementsTree = (components: Components, params: Params) => {
propsByInstanceIdStore,
assetsStore,
pagesStore: pagesMapStore,
- dataSourceValuesStore: computed(
- [dataSourcesStore, dataSourceValuesStore],
- (dataSources, dataSourceValues) => {
- const newValues = new Map<DataSource["id"], unknown>();
- for (const [dataSourceId, dataSource] of dataSources) {
- newValues.set(dataSourceId, dataSource.value);
- }
- for (const [dataSourceId, dataSourceValue] of dataSourceValues) {
- newValues.set(dataSourceId, dataSourceValue);
- }
- return newValues;
- }
- ),
+ dataSourceValuesStore,
onDataSourceUpdate: (dataSourceId, value) => {
- const dataSourceValues = new Map(dataSourceValuesStore.get());
- dataSourceValues.set(dataSourceId, value);
- dataSourceValuesStore.set(dataSourceValues);
+ const dataSourceVariables = new Map(dataSourceVariablesStore.get());
+ dataSourceVariables.set(dataSourceId, value);
+ dataSourceVariablesStore.set(dataSourceVariables);
},
Component: WebstudioComponentDev,
components,
diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.ts
index 21542c161a..007a66b045 100644
--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts
@@ -22,7 +22,7 @@ import {
assetsStore,
projectStore,
registeredComponentMetasStore,
- dataSourcesStore,
+ dataSourceValuesStore,
} from "../nano-states";
import {
type InstanceSelector,
@@ -143,6 +143,22 @@ const getAssetsUsedInProps = (props: Prop[], foundAssetsIds = new Set()) => {
return foundAssetsIds;
};
+const getPropTypeAndValue = (value: unknown) => {
+ if (typeof value === "boolean") {
+ return { type: "boolean", value } as const;
+ }
+ if (typeof value === "number") {
+ return { type: "number", value } as const;
+ }
+ if (typeof value === "string") {
+ return { type: "string", value } as const;
+ }
+ if (Array.isArray(value)) {
+ return { type: "string[]", value } as const;
+ }
+ throw Error(`Unexpected prop value ${value}`);
+};
+
const getTreeData = (targetInstanceSelector: InstanceSelector) => {
// @todo tell user they can't copy or cut root
if (targetInstanceSelector.length === 1) {
@@ -161,22 +177,20 @@ const getTreeData = (targetInstanceSelector: InstanceSelector) => {
// first item is guaranteed root of copied tree
const treeInstances = getMapValuesByKeysSet(instances, treeInstanceIds);
- const dataSources = dataSourcesStore.get();
+ const dataSourceValues = dataSourceValuesStore.get();
const treeProps = getMapValuesBy(propsStore.get(), (prop) =>
treeInstanceIds.has(prop.instanceId)
).map((prop) => {
// unbind data source from prop
+ // @todo improve the logic and allow to copy data sources for scoped components
if (prop.type === "dataSource") {
- const dataSource = dataSources.get(prop.value);
- if (dataSource) {
- const { id, name, ...rest } = dataSource;
- return {
- id: prop.id,
- instanceId: prop.instanceId,
- name: prop.name,
- ...rest,
- } satisfies Prop;
- }
+ const value = dataSourceValues.get(prop.value);
+ return {
+ id: prop.id,
+ instanceId: prop.instanceId,
+ name: prop.name,
+ ...getPropTypeAndValue(value),
+ } satisfies Prop;
}
return prop;
});
diff --git a/apps/builder/app/shared/nano-states/nano-states.ts b/apps/builder/app/shared/nano-states/nano-states.ts
index aa1e650999..9e266f8e04 100644
--- a/apps/builder/app/shared/nano-states/nano-states.ts
+++ b/apps/builder/app/shared/nano-states/nano-states.ts
@@ -20,6 +20,11 @@ import type {
StyleSourceSelection,
StyleSourceSelections,
} from "@webstudio-is/project-build";
+import {
+ executeExpressions,
+ encodeDataSourceVariable,
+ decodeDataSourceVariable,
+} from "@webstudio-is/react-sdk";
import type { Style } from "@webstudio-is/css-data";
import type { DragStartPayload } from "~/canvas/shared/use-drag-drop";
import { useSyncInitializeOnce } from "../hook-utils";
@@ -62,7 +67,7 @@ export const rootInstanceStore = computed(
);
export const dataSourcesStore = atom<DataSources>(new Map());
-export const dataSourceValuesStore = atom<Map<DataSource["id"], unknown>>(
+export const dataSourceVariablesStore = atom<Map<DataSource["id"], unknown>>(
new Map()
);
export const useSetDataSources = (
@@ -72,6 +77,39 @@ export const useSetDataSources = (
dataSourcesStore.set(new Map(dataSources));
});
};
+export const dataSourceValuesStore = computed(
+ [dataSourcesStore, dataSourceVariablesStore],
+ (dataSources, dataSourceVariables) => {
+ 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 =
+ dataSourceVariables.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 const propsStore = atom<Props>(new Map());
export const propsIndexStore = computed(propsStore, (props) => {
diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.ts
index b036b8b211..e0ed8f1596 100644
--- a/apps/builder/app/shared/sync/sync-stores.ts
+++ b/apps/builder/app/shared/sync/sync-stores.ts
@@ -28,7 +28,7 @@ import {
synchronizedBreakpointsStores,
selectedStyleSourceSelectorStore,
synchronizedComponentsMetaStores,
- dataSourceValuesStore,
+ dataSourceVariablesStore,
} from "~/shared/nano-states";
enableMapSet();
@@ -73,7 +73,7 @@ export const registerContainers = () => {
store.register("assets", assetsStore);
// synchronize whole states
clientStores.set("project", projectStore);
- clientStores.set("dataSourceValues", dataSourceValuesStore);
+ clientStores.set("dataSourceVariables", dataSourceVariablesStore);
clientStores.set("selectedPageId", selectedPageIdStore);
clientStores.set("selectedPageHash", selectedPageHashStore);
clientStores.set("selectedInstanceSelector", selectedInstanceSelectorStore);
diff --git a/packages/project-build/src/schema/data-sources.ts b/packages/project-build/src/schema/data-sources.ts
index 18bd67e051..41947ac07f 100644
--- a/packages/project-build/src/schema/data-sources.ts
+++ b/packages/project-build/src/schema/data-sources.ts
@@ -2,19 +2,38 @@ import { z } from "zod";
const DataSourceId = z.string();
+export const DataSourceVariableValue = z.union([
+ z.object({
+ type: z.literal("number"),
+ // initial value of variable store
+ value: z.number(),
+ }),
+ z.object({
+ type: z.literal("string"),
+ value: z.string(),
+ }),
+ z.object({
+ type: z.literal("boolean"),
+ value: z.boolean(),
+ }),
+ z.object({
+ type: z.literal("string[]"),
+ value: z.array(z.string()),
+ }),
+]);
+
export const DataSource = z.union([
z.object({
+ type: z.literal("variable"),
id: DataSourceId,
name: z.string(),
- type: z.literal("string"),
- // initial value of data source store
- value: z.string(),
+ value: DataSourceVariableValue,
}),
z.object({
+ type: z.literal("expression"),
id: DataSourceId,
name: z.string(),
- type: z.literal("boolean"),
- value: z.boolean(),
+ code: z.string(),
}),
]);
diff --git a/packages/react-sdk/src/embed-template.test.ts b/packages/react-sdk/src/embed-template.test.ts
index 5d66ee928c..c5b75a4f5e 100644
--- a/packages/react-sdk/src/embed-template.test.ts
+++ b/packages/react-sdk/src/embed-template.test.ts
@@ -2,7 +2,7 @@ import { expect, test } from "@jest/globals";
import { generateDataFromEmbedTemplate } from "./embed-template";
import { showAttribute } from "./tree";
-const expectString = expect.any(String) as unknown as string;
+const expectString = expect.any(String);
const defaultBreakpointId = "base";
@@ -213,7 +213,7 @@ test("generate data for embedding from styles", () => {
});
});
-test("generate data for embedding from props bound to data sources", () => {
+test("generate data for embedding from props bound to data source variables", () => {
expect(
generateDataFromEmbedTemplate(
[
@@ -224,8 +224,11 @@ test("generate data for embedding from props bound to data sources", () => {
{
type: "boolean",
name: "showOtherBox",
- dataSourceRef: "showOtherBoxDataSource",
value: false,
+ dataSourceRef: {
+ type: "variable",
+ name: "showOtherBoxDataSource",
+ },
},
],
children: [],
@@ -237,8 +240,11 @@ test("generate data for embedding from props bound to data sources", () => {
{
type: "boolean",
name: showAttribute,
- dataSourceRef: "showOtherBoxDataSource",
value: false,
+ dataSourceRef: {
+ type: "variable",
+ name: "showOtherBoxDataSource",
+ },
},
],
children: [],
@@ -273,10 +279,101 @@ test("generate data for embedding from props bound to data sources", () => {
],
dataSources: [
{
+ type: "variable",
id: expectString,
name: "showOtherBoxDataSource",
- type: "boolean",
- value: false,
+ value: {
+ type: "boolean",
+ value: false,
+ },
+ },
+ ],
+ styleSourceSelections: [],
+ styleSources: [],
+ styles: [],
+ });
+});
+
+test("generate data for embedding from props bound to data source expressions", () => {
+ expect(
+ generateDataFromEmbedTemplate(
+ [
+ {
+ type: "instance",
+ component: "Box1",
+ props: [
+ {
+ type: "string",
+ name: "state",
+ value: "initial",
+ dataSourceRef: {
+ type: "variable",
+ name: "boxState",
+ },
+ },
+ ],
+ children: [],
+ },
+ {
+ type: "instance",
+ component: "Box2",
+ props: [
+ {
+ type: "boolean",
+ name: showAttribute,
+ value: false,
+ dataSourceRef: {
+ type: "expression",
+ name: "boxStateSuccess",
+ code: `boxState === 'success'`,
+ },
+ },
+ ],
+ children: [],
+ },
+ ],
+ defaultBreakpointId
+ )
+ ).toEqual({
+ children: [
+ { type: "id", value: expectString },
+ { type: "id", value: expectString },
+ ],
+ instances: [
+ { type: "instance", id: expectString, component: "Box1", children: [] },
+ { type: "instance", id: expectString, component: "Box2", children: [] },
+ ],
+ props: [
+ {
+ id: expectString,
+ instanceId: expectString,
+ type: "dataSource",
+ name: "state",
+ value: expectString,
+ },
+ {
+ id: expectString,
+ instanceId: expectString,
+ type: "dataSource",
+ name: showAttribute,
+ value: expectString,
+ },
+ ],
+ dataSources: [
+ {
+ type: "variable",
+ id: expectString,
+ name: "boxState",
+ value: {
+ type: "string",
+ value: "initial",
+ },
+ },
+ {
+ type: "expression",
+ id: expectString,
+ name: "boxStateSuccess",
+ code: expect.stringMatching(/\$ws\$dataSource\$\w+ === 'success'/),
},
],
styleSourceSelections: [],
diff --git a/packages/react-sdk/src/embed-template.ts b/packages/react-sdk/src/embed-template.ts
index dc4b6d8537..f1b47a7761 100644
--- a/packages/react-sdk/src/embed-template.ts
+++ b/packages/react-sdk/src/embed-template.ts
@@ -12,6 +12,7 @@ import {
} from "@webstudio-is/project-build";
import { StyleValue, type StyleProperty } from "@webstudio-is/css-data";
import type { Simplify } from "type-fest";
+import { encodeDataSourceVariable, validateExpression } from "./expression";
const EmbedTemplateText = z.object({
type: z.literal("text"),
@@ -20,29 +21,41 @@ const EmbedTemplateText = z.object({
type EmbedTemplateText = z.infer<typeof EmbedTemplateText>;
+const DataSourceRef = z.union([
+ z.object({
+ type: z.literal("variable"),
+ name: z.string(),
+ }),
+ z.object({
+ type: z.literal("expression"),
+ name: z.string(),
+ code: z.string(),
+ }),
+]);
+
const EmbedTemplateProp = z.union([
z.object({
type: z.literal("number"),
name: z.string(),
- dataSourceRef: z.optional(z.string()),
+ dataSourceRef: z.optional(DataSourceRef),
value: z.number(),
}),
z.object({
type: z.literal("string"),
name: z.string(),
- dataSourceRef: z.optional(z.string()),
+ dataSourceRef: z.optional(DataSourceRef),
value: z.string(),
}),
z.object({
type: z.literal("boolean"),
name: z.string(),
- dataSourceRef: z.optional(z.string()),
+ dataSourceRef: z.optional(DataSourceRef),
value: z.boolean(),
}),
z.object({
type: z.literal("string[]"),
name: z.string(),
- dataSourceRef: z.optional(z.string()),
+ dataSourceRef: z.optional(DataSourceRef),
value: z.array(z.string()),
}),
]);
@@ -115,18 +128,30 @@ const createInstancesFromTemplate = (
props.push({ id: propId, instanceId, ...prop });
continue;
}
- let dataSource = dataSourceByRef.get(prop.dataSourceRef);
+ let dataSource = dataSourceByRef.get(prop.dataSourceRef.name);
if (dataSource === undefined) {
const id = nanoid();
- const { name: propName, dataSourceRef: name, ...rest } = prop;
- if (rest.type === "boolean" || rest.type === "string") {
- dataSource = { id, name, ...rest };
+ const { name: propName, dataSourceRef, ...rest } = prop;
+ if (dataSourceRef.type === "variable") {
+ dataSource = {
+ type: "variable",
+ id,
+ name: dataSourceRef.name,
+ value: rest,
+ };
+ dataSourceByRef.set(dataSourceRef.name, dataSource);
+ } else if (dataSourceRef.type === "expression") {
+ dataSource = {
+ type: "expression",
+ id,
+ name: dataSourceRef.name,
+ code: dataSourceRef.code,
+ };
+ dataSourceByRef.set(dataSourceRef.name, dataSource);
} else {
- // ensure only number and string[] are not mapped to data sources
- rest.type satisfies "number" | "string[]";
+ dataSourceRef satisfies never;
continue;
}
- dataSourceByRef.set(name, dataSource);
}
props.push({
id: propId,
@@ -217,11 +242,24 @@ export const generateDataFromEmbedTemplate = (
styles,
defaultBreakpointId
);
+
+ // replace all references with variable names
+ const dataSources: DataSource[] = [];
+ for (const dataSource of dataSourceByRef.values()) {
+ if (dataSource.type === "expression") {
+ dataSource.code = validateExpression(dataSource.code, (ref) => {
+ const id = dataSourceByRef.get(ref)?.id ?? ref;
+ return encodeDataSourceVariable(id);
+ });
+ }
+ dataSources.push(dataSource);
+ }
+
return {
children,
instances,
props,
- dataSources: Array.from(dataSourceByRef.values()),
+ dataSources,
styleSourceSelections,
styleSources,
styles,
diff --git a/packages/react-sdk/src/expression.test.ts b/packages/react-sdk/src/expression.test.ts
index 5bf9655ccb..34d7f8caa6 100644
--- a/packages/react-sdk/src/expression.test.ts
+++ b/packages/react-sdk/src/expression.test.ts
@@ -1,5 +1,10 @@
import { expect, test } from "@jest/globals";
-import { executeExpression, validateExpression } from "./expression";
+import {
+ decodeDataSourceVariable,
+ encodeDataSourceVariable,
+ executeExpressions,
+ validateExpression,
+} from "./expression";
test("allow literals and array expressions", () => {
expect(
@@ -53,13 +58,17 @@ test("transform identifiers", () => {
test("execute expression", () => {
const variables = new Map();
const expressions = new Map([["exp1", "1 + 1"]]);
- expect(executeExpression("exp1", variables, expressions)).toEqual(2);
+ expect(executeExpressions(variables, expressions)).toEqual(
+ new Map([["exp1", 2]])
+ );
});
test("execute expression dependent on variables", () => {
const variables = new Map([["var1", 5]]);
const expressions = new Map([["exp1", "var1 + 1"]]);
- expect(executeExpression("exp1", variables, expressions)).toEqual(6);
+ expect(executeExpressions(variables, expressions)).toEqual(
+ new Map([["exp1", 6]])
+ );
});
test("execute expression dependent on other expressions", () => {
@@ -68,7 +77,12 @@ test("execute expression dependent on other expressions", () => {
["exp1", "exp0 + 1"],
["exp0", "var1 + 2"],
]);
- expect(executeExpression("exp1", variables, expressions)).toEqual(6);
+ expect(executeExpressions(variables, expressions)).toEqual(
+ new Map([
+ ["exp1", 6],
+ ["exp0", 5],
+ ])
+ );
});
test("forbid circular expressions", () => {
@@ -79,7 +93,7 @@ test("forbid circular expressions", () => {
["exp2", "exp1 + 3"],
]);
expect(() => {
- executeExpression("exp1", variables, expressions);
+ executeExpressions(variables, expressions);
}).toThrowError(/exp2 is not defined/);
});
@@ -87,6 +101,16 @@ test("make sure dependency exists", () => {
const variables = new Map();
const expressions = new Map([["exp1", "var1 + 1"]]);
expect(() => {
- executeExpression("exp1", variables, expressions);
+ executeExpressions(variables, expressions);
}).toThrowError(/Unknown dependency "var1"/);
});
+
+test("encode/decode variable names", () => {
+ expect(encodeDataSourceVariable("my--id")).toEqual(
+ "$ws$dataSource$my__DASH____DASH__id"
+ );
+ expect(decodeDataSourceVariable(encodeDataSourceVariable("my--id"))).toEqual(
+ "my--id"
+ );
+ expect(decodeDataSourceVariable("myVarName")).toEqual(undefined);
+});
diff --git a/packages/react-sdk/src/expression.ts b/packages/react-sdk/src/expression.ts
index 4b5cf129bb..9d9ddff19d 100644
--- a/packages/react-sdk/src/expression.ts
+++ b/packages/react-sdk/src/expression.ts
@@ -109,8 +109,7 @@ export const validateExpression = (
return generateCode(expression, true, transformIdentifier);
};
-export const executeExpression = (
- expressionId: string,
+export const executeExpressions = (
variables: Map<string, unknown>,
expressions: Map<string, string>
) => {
@@ -145,6 +144,9 @@ export const executeExpression = (
for (const [id, value] of variables) {
header += `const ${id} = ${JSON.stringify(value)};\n`;
}
+
+ const values = new Map<string, unknown>();
+
for (const id of sortedExpressions) {
const code = expressions.get(id);
if (code === undefined) {
@@ -153,8 +155,27 @@ export const executeExpression = (
const executeFn = new Function(`${header}\nreturn (${code});`);
const value = executeFn();
header += `const ${id} = ${JSON.stringify(value)};\n`;
- if (id === expressionId) {
- return value;
- }
+ values.set(id, value);
+ }
+
+ return values;
+};
+
+const dataSourceVariablePrefix = "$ws$dataSource$";
+
+// data source id is generated with nanoid which has "-" in alphabeta
+// here "-" is encoded with "__DASH__' in variable name
+// https://github.com/ai/nanoid/blob/047686abad8f15aff05f3a2eeedb7c98b6847392/url-alphabet/index.js
+
+export const encodeDataSourceVariable = (id: string) => {
+ const encoded = id.replaceAll("-", "__DASH__");
+ return `${dataSourceVariablePrefix}${encoded}`;
+};
+
+export const decodeDataSourceVariable = (name: string) => {
+ if (name.startsWith(dataSourceVariablePrefix)) {
+ const encoded = name.slice(dataSourceVariablePrefix.length);
+ return encoded.replaceAll("__DASH__", "-");
}
+ return;
};
diff --git a/packages/react-sdk/src/index.ts b/packages/react-sdk/src/index.ts
index 676b13309d..785c2f53e0 100644
--- a/packages/react-sdk/src/index.ts
+++ b/packages/react-sdk/src/index.ts
@@ -20,4 +20,9 @@ export {
getInstanceIdFromComponentProps,
} from "./props";
export { type Params, ReactSdkContext } from "./context";
-export { validateExpression, executeExpression } from "./expression";
+export {
+ validateExpression,
+ executeExpressions,
+ encodeDataSourceVariable,
+ decodeDataSourceVariable,
+} from "./expression";
diff --git a/packages/react-sdk/src/tree/root.ts b/packages/react-sdk/src/tree/root.ts
index f333529b4e..adc8d5525f 100644
--- a/packages/react-sdk/src/tree/root.ts
+++ b/packages/react-sdk/src/tree/root.ts
@@ -1,12 +1,56 @@
import { useRef, type ComponentProps } from "react";
-import { atom, type WritableAtom } from "nanostores";
-import type { Build, DataSource, Page } from "@webstudio-is/project-build";
+import {
+ atom,
+ computed,
+ type ReadableAtom,
+ type WritableAtom,
+} from "nanostores";
+import { type Build, type Page, DataSource } from "@webstudio-is/project-build";
import type { Asset } from "@webstudio-is/asset-uploader";
import { createElementsTree } from "./create-elements-tree";
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;
@@ -31,21 +75,33 @@ export const InstanceRoot = ({
Component,
components,
}: RootProps): JSX.Element | null => {
- const dataSourceValuesStoreRef = useRef<
+ const dataSourceVariablesStoreRef = useRef<
undefined | WritableAtom<Map<DataSource["id"], unknown>>
>(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);
+ }
+ const dataSourceVariablesStore = dataSourceVariablesStoreRef.current;
+
+ const dataSourceValuesStoreRef = useRef<
+ undefined | ReadableAtom<Map<DataSource["id"], unknown>>
+ >(undefined);
+ // initialize store with default data source values
if (dataSourceValuesStoreRef.current === undefined) {
- dataSourceValuesStoreRef.current = atom(
- new Map(
- data.build.dataSources.map(([dataSourceId, dataSource]) => [
- dataSourceId,
- dataSource.value,
- ])
- )
+ dataSourceValuesStoreRef.current = computed(
+ dataSourceVariablesStore,
+ (dataSourceVariables) => {
+ return computeExpressions(data.build.dataSources, dataSourceVariables);
+ }
);
}
const dataSourceValuesStore = dataSourceValuesStoreRef.current;
+
return createElementsTree({
imageBaseUrl: data.params?.imageBaseUrl ?? "/",
assetBaseUrl: data.params?.assetBaseUrl ?? "/",
@@ -58,9 +114,9 @@ export const InstanceRoot = ({
pagesStore: atom(new Map(data.pages.map((page) => [page.id, page]))),
dataSourceValuesStore,
onDataSourceUpdate: (dataSourceId, value) => {
- const dataSourceValues = new Map(dataSourceValuesStore.get());
- dataSourceValues.set(dataSourceId, value);
- dataSourceValuesStore.set(dataSourceValues);
+ const dataSourceVariables = new Map(dataSourceVariablesStore.get());
+ dataSourceVariables.set(dataSourceId, value);
+ dataSourceVariablesStore.set(dataSourceVariables);
},
Component: Component ?? WebstudioComponent,
components,
diff --git a/packages/sdk-size-test/package.json b/packages/sdk-size-test/package.json
index 64ea68b00d..a75c40dd19 100644
--- a/packages/sdk-size-test/package.json
+++ b/packages/sdk-size-test/package.json
@@ -15,7 +15,7 @@
},
{
"path": "functions/*.js",
- "limit": "217 kB",
+ "limit": "229 kB",
"gzip": false
}
],
diff --git a/packages/tsconfig/base.json b/packages/tsconfig/base.json
index ac06217cca..8ec8fc59ed 100644
--- a/packages/tsconfig/base.json
+++ b/packages/tsconfig/base.json
@@ -3,7 +3,7 @@
"display": "Default",
"compilerOptions": {
"module": "ES2022",
- "target": "ES2020",
+ "target": "ES2021",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"inlineSources": false,