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: support parameter data source for collection item (#2671)

Bogdan Chadkin61d664fc87d0
diff --git a/apps/builder/app/builder/features/settings-panel/controls/combined.tsx b/apps/builder/app/builder/features/settings-panel/controls/combined.tsx
index 020470555b..aa961cff91 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/combined.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/combined.tsx
@@ -30,6 +30,10 @@ export const renderControl = ({
return;
}
+ if (meta.control === "json" && (prop === undefined || prop.type === "json")) {
+ return <JsonControl meta={meta} prop={prop} {...rest} />;
+ }
+
if (
meta.control === "text" &&
(prop === undefined || prop.type === "string")
diff --git a/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts
index ffd53533d8..ab5c8bb778 100644
--- a/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts
+++ b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts
@@ -199,7 +199,7 @@ export const usePropsLogic = ({
const potentialVariableId = decodeDataSourceVariable(prop.value);
return (
potentialVariableId === undefined ||
- dataSources.has(potentialVariableId) === false
+ dataSources.get(potentialVariableId)?.type !== "variable"
);
};
diff --git a/apps/builder/app/builder/features/settings-panel/variables.tsx b/apps/builder/app/builder/features/settings-panel/variables.tsx
index 3d7f6dad47..2dfd797e88 100644
--- a/apps/builder/app/builder/features/settings-panel/variables.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variables.tsx
@@ -33,22 +33,22 @@ import {
import type { DataSource, Prop } from "@webstudio-is/sdk";
import {
PropMeta,
+ collectionComponent,
decodeDataSourceVariable,
encodeDataSourceVariable,
validateExpression,
} from "@webstudio-is/react-sdk";
import {
- dataSourcesStore,
- propsStore,
- selectedInstanceSelectorStore,
+ $dataSources,
+ $instances,
+ $props,
+ $selectedInstanceSelector,
} from "~/shared/nano-states";
import { serverSyncStore } from "~/shared/sync";
import { CodeEditor } from "./code-editor";
import type { PropValue } from "./shared";
import { getStartingValue } from "./props-section/use-props-logic";
-type VariableDataSource = Extract<DataSource, { type: "variable" }>;
-
/**
* convert value expression to js value
* validating out accessing any identifier
@@ -82,6 +82,12 @@ const parseVariableValue = (code: string) => {
return result;
};
+const renameVariable = (variable: DataSource, name: string) => {
+ serverSyncStore.createTransaction([$dataSources], (dataSources) => {
+ dataSources.set(variable.id, { ...variable, name });
+ });
+};
+
const saveVariable = (
dataSourceId: string = nanoid(),
name: string,
@@ -92,13 +98,16 @@ const saveVariable = (
return { error };
}
- const instanceSelector = selectedInstanceSelectorStore.get();
+ const instanceSelector = $selectedInstanceSelector.get();
if (instanceSelector === undefined) {
return;
}
const [instanceId] = instanceSelector;
- serverSyncStore.createTransaction([dataSourcesStore], (dataSources) => {
- let variableValue: VariableDataSource["value"] = { type: "json", value };
+ serverSyncStore.createTransaction([$dataSources], (dataSources) => {
+ let variableValue: Extract<DataSource, { type: "variable" }>["value"] = {
+ type: "json",
+ value,
+ };
if (typeof value === "string") {
variableValue = { type: "string", value };
}
@@ -124,7 +133,7 @@ const VariablePanel = ({
variable,
onBack,
}: {
- variable?: VariableDataSource;
+ variable?: DataSource;
onBack: () => void;
}) => {
// variable value cannot have an access to other variables
@@ -133,7 +142,9 @@ const VariablePanel = ({
const [name, setName] = useState(variable?.name ?? "");
const [nameErrors, setNameErrors] = useState<undefined | string[]>();
const [value, setValue] = useState(
- JSON.stringify(variable?.value.value ?? "")
+ JSON.stringify(
+ variable?.type === "variable" ? variable?.value.value ?? "" : ""
+ )
);
const [valueErrors, setValueErrors] = useState<undefined | string[]>();
@@ -177,18 +188,21 @@ const VariablePanel = ({
/>
</InputErrorsTooltip>
</Flex>
- <Flex direction="column" css={{ gap: theme.spacing[3] }}>
- <Label>Value</Label>
- <InputErrorsTooltip errors={valueErrors}>
- <div>
- <CodeEditor
- variables={variables}
- defaultValue={value}
- onChange={setValue}
- />
- </div>
- </InputErrorsTooltip>
- </Flex>
+ {/* only value variables (new and existing) can have value field */}
+ {(variable === undefined || variable.type === "variable") && (
+ <Flex direction="column" css={{ gap: theme.spacing[3] }}>
+ <Label>Value</Label>
+ <InputErrorsTooltip errors={valueErrors}>
+ <div>
+ <CodeEditor
+ variables={variables}
+ defaultValue={value}
+ onChange={setValue}
+ />
+ </div>
+ </InputErrorsTooltip>
+ </Flex>
+ )}
<Flex justify="end" css={{ gap: theme.spacing[5] }}>
<Button color="neutral" onClick={onBack}>
Cancel
@@ -199,11 +213,18 @@ const VariablePanel = ({
setNameErrors([`Variable name is required`]);
return;
}
- const result = saveVariable(variable?.id, name, value);
- if (result?.error !== undefined) {
- setValueErrors([result.error]);
+ if (variable === undefined || variable.type === "variable") {
+ const result = saveVariable(variable?.id, name, value);
+ if (result?.error !== undefined) {
+ setValueErrors([result.error]);
+ return;
+ }
+ onBack();
return;
}
+
+ // only rename any other type of variable
+ renameVariable(variable, name);
onBack();
}}
>
@@ -216,15 +237,24 @@ const VariablePanel = ({
};
const $selectedInstanceVariables = computed(
- [selectedInstanceSelectorStore, dataSourcesStore],
- (instanceSelector, dataSources) => {
- const matchedVariables: VariableDataSource[] = [];
+ [$selectedInstanceSelector, $dataSources, $instances],
+ (instanceSelector, dataSources, instances) => {
+ const matchedVariables: DataSource[] = [];
if (instanceSelector === undefined) {
return matchedVariables;
}
for (const dataSource of dataSources.values()) {
+ const [instanceId] = instanceSelector;
+ // prevent showing "item" parameter on collection component
+ // to avoid circular undefined variable runtime error
+ if (
+ dataSource.type === "parameter" &&
+ instanceId === dataSource.scopeInstanceId &&
+ instances.get(instanceId)?.component === collectionComponent
+ ) {
+ continue;
+ }
if (
- dataSource.type === "variable" &&
dataSource.scopeInstanceId !== undefined &&
instanceSelector.includes(dataSource.scopeInstanceId)
) {
@@ -250,7 +280,7 @@ const EmptyList = ({ onAdd }: { onAdd: () => void }) => {
);
};
-const $usedVariables = computed([propsStore], (props) => {
+const $usedVariables = computed([$props], (props) => {
const usedVariables = new Set<DataSource["id"]>();
for (const prop of props.values()) {
if (prop.type === "expression") {
@@ -290,8 +320,8 @@ const $usedVariables = computed([propsStore], (props) => {
return usedVariables;
});
-const deleteVariable = (variable: VariableDataSource) => {
- serverSyncStore.createTransaction([dataSourcesStore], (dataSources) => {
+const deleteVariable = (variable: DataSource) => {
+ serverSyncStore.createTransaction([$dataSources], (dataSources) => {
dataSources.delete(variable.id);
});
};
@@ -307,15 +337,17 @@ const ListItem = ({
index: number;
selected: boolean;
deletable: boolean;
- variable: VariableDataSource;
+ variable: DataSource;
onSelect: (variableId: DataSource["id"]) => void;
- onEdit: (variable: VariableDataSource) => void;
+ onEdit: (variable: DataSource) => void;
}) => {
return (
<CssValueListItem
label={
<Label truncate>
- {variable.name}: {JSON.stringify(variable.value.value)}
+ {variable.type === "variable"
+ ? `${variable.name}: ${JSON.stringify(variable.value.value)}`
+ : variable.name}
</Label>
}
id={variable.id}
@@ -349,7 +381,7 @@ const ListItem = ({
};
const getExpressionVariables = (expression: string) => {
- const variableIds = new Set<VariableDataSource["id"]>();
+ const variableIds = new Set<DataSource["id"]>();
if (expression === "") {
return variableIds;
}
@@ -374,13 +406,13 @@ const setPropValue = ({
propName: Prop["name"];
propValue: PropValue;
}) => {
- const instanceSelector = selectedInstanceSelectorStore.get();
+ const instanceSelector = $selectedInstanceSelector.get();
if (instanceSelector === undefined) {
return;
}
const [instanceId] = instanceSelector;
- serverSyncStore.createTransaction([propsStore], (props) => {
+ serverSyncStore.createTransaction([$props], (props) => {
let prop = propId === undefined ? undefined : props.get(propId);
// create new prop or update existing one
if (prop === undefined) {
@@ -400,7 +432,7 @@ const ListPanel = ({
}: {
prop: undefined | Prop;
onAdd: () => void;
- onEdit: (variable: VariableDataSource) => void;
+ onEdit: (variable: DataSource) => void;
onChange: (value: undefined | PropValue) => void;
}) => {
const matchedVariables = useStore($selectedInstanceVariables);
@@ -440,7 +472,10 @@ const ListPanel = ({
variable={variable}
// mark all variables used in expression as selected
selected={exoressionVariables.has(variable.id)}
- deletable={usedVariables.has(variable.id) === false}
+ deletable={
+ variable.type === "variable" &&
+ usedVariables.has(variable.id) === false
+ }
onSelect={() =>
// convert variable to expression
onChange({
@@ -512,7 +547,7 @@ export const VariablesPanel = ({
const prop = useStore(
useMemo(
() =>
- computed(propsStore, (props) => {
+ computed($props, (props) => {
if (propId) {
return props.get(propId);
}
@@ -522,9 +557,7 @@ export const VariablesPanel = ({
);
const [view, setView] = useState<
- | { name: "list" }
- | { name: "add" }
- | { name: "edit"; variable: VariableDataSource }
+ { name: "list" } | { name: "add" } | { name: "edit"; variable: DataSource }
>({ name: "list" });
if (view.name === "add") {
return (
@@ -560,7 +593,7 @@ export const VariablesPanel = ({
});
} else if (propId !== undefined) {
// delete prop when not possible to infer default value from meta
- serverSyncStore.createTransaction([propsStore], (props) => {
+ serverSyncStore.createTransaction([$props], (props) => {
props.delete(propId);
});
}
diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts b/apps/builder/app/shared/copy-paste/plugin-instance.test.ts
index d9faeda311..d659b2cde3 100644
--- a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-instance.test.ts
@@ -371,7 +371,7 @@ describe("data sources", () => {
);
});
- test("copy parameter prop with new data source", () => {
+ test.only("copy parameter prop with new data source", () => {
const instances: Instances = toMap([
createInstance("body", "Body", [{ type: "id", value: "list" }]),
createInstance("list", collectionComponent, []),
@@ -380,9 +380,8 @@ describe("data sources", () => {
{
id: "itemDataSource",
scopeInstanceId: "list",
- type: "variable",
+ type: "parameter",
name: "item",
- value: { type: "json", value: {} },
},
] satisfies DataSource[]);
const props: Props = toMap([
@@ -427,9 +426,8 @@ describe("data sources", () => {
{
id: itemDataSourceId,
scopeInstanceId: collectionId,
- type: "variable",
+ type: "parameter",
name: "item",
- value: { type: "json", value: {} },
},
],
])
diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.ts
index 7143785ccb..b9d3eb08bd 100644
--- a/apps/builder/app/shared/instance-utils.ts
+++ b/apps/builder/app/shared/instance-utils.ts
@@ -768,8 +768,7 @@ const inlineUnavailableDataSources = ({
if (dataSource?.type === "variable") {
return JSON.stringify(dataSource.value.value);
}
- dataSource?.type satisfies undefined;
- return identifier;
+ return "";
},
});
return { code: newCode, isDiscarded };
diff --git a/apps/builder/app/shared/nano-states/props.test.ts b/apps/builder/app/shared/nano-states/props.test.ts
index 9b9e0a4f07..2f85291d20 100644
--- a/apps/builder/app/shared/nano-states/props.test.ts
+++ b/apps/builder/app/shared/nano-states/props.test.ts
@@ -276,9 +276,8 @@ test("compute expression from collection items", () => {
toMap([
{
id: "itemId",
- type: "variable",
+ type: "parameter",
name: "item",
- value: { type: "json", value: {} },
},
])
);
diff --git a/packages/react-sdk/src/component-generator.test.ts b/packages/react-sdk/src/component-generator.test.ts
index 34f39deccb..f4d5deb2a7 100644
--- a/packages/react-sdk/src/component-generator.test.ts
+++ b/packages/react-sdk/src/component-generator.test.ts
@@ -640,9 +640,8 @@ test("avoid generating collection parameter variable as state", () => {
createDataSourcePair({
id: "dataSourceItem",
scopeInstanceId: "list",
- type: "variable",
+ type: "parameter",
name: "element",
- value: { type: "json", value: `` },
}),
]),
props: new Map([
diff --git a/packages/react-sdk/src/core-components.ts b/packages/react-sdk/src/core-components.ts
index 0a1f90bd9b..b12c08cf4b 100644
--- a/packages/react-sdk/src/core-components.ts
+++ b/packages/react-sdk/src/core-components.ts
@@ -14,13 +14,11 @@ const collectionMeta: WsComponentMeta = {
type: "container",
label: "Collection",
icon: ListIcon,
+ stylable: false,
template: [
{
type: "instance",
component: collectionComponent,
- variables: {
- collectionItem: { initialValue: "" },
- },
props: [
{
name: "data",
diff --git a/packages/react-sdk/src/embed-template.test.ts b/packages/react-sdk/src/embed-template.test.ts
index 8a23352f59..f32ebae3c8 100644
--- a/packages/react-sdk/src/embed-template.test.ts
+++ b/packages/react-sdk/src/embed-template.test.ts
@@ -490,9 +490,6 @@ test("generate data for embedding from parameter props", () => {
{
type: "instance",
component: "Box",
- variables: {
- parameterName: { initialValue: "" },
- },
props: [
{
type: "parameter",
@@ -529,11 +526,10 @@ test("generate data for embedding from parameter props", () => {
],
dataSources: [
{
- type: "variable",
+ type: "parameter",
id: variableId,
scopeInstanceId: instanceId,
name: "parameterName",
- value: { type: "string", value: "" },
},
],
styleSourceSelections: [],
diff --git a/packages/react-sdk/src/embed-template.ts b/packages/react-sdk/src/embed-template.ts
index 68356cc3f9..c1c8c1a65c 100644
--- a/packages/react-sdk/src/embed-template.ts
+++ b/packages/react-sdk/src/embed-template.ts
@@ -230,10 +230,14 @@ const createInstancesFromTemplate = (
}
if (prop.type === "parameter") {
- const dataSourceId = dataSourceByRef.get(prop.variableName)?.id;
- if (dataSourceId === undefined) {
- continue;
- }
+ const dataSourceId = generateId();
+ // generate data sources implicitly
+ dataSourceByRef.set(prop.variableName, {
+ type: "parameter",
+ id: dataSourceId,
+ scopeInstanceId: instanceId,
+ name: prop.variableName,
+ });
props.push({
id: propId,
instanceId,
diff --git a/packages/react-sdk/src/expression.test.ts b/packages/react-sdk/src/expression.test.ts
index 04d24dff97..3eeb8af9e7 100644
--- a/packages/react-sdk/src/expression.test.ts
+++ b/packages/react-sdk/src/expression.test.ts
@@ -7,6 +7,9 @@ import {
} from "./expression";
import { createScope } from "@webstudio-is/sdk";
+const toMap = <T extends { id: string }>(list: T[]) =>
+ new Map(list.map((item) => [item.id, item]));
+
test("allow literals and array expressions", () => {
expect(
validateExpression(`["", '', 0, true, false, null, undefined]`)
@@ -293,3 +296,29 @@ test("generate function for empty action", () => {
expect(generated.variables).toEqual(new Map());
expect(generated.output).toEqual(new Map([["prop1", "onChange"]]));
});
+
+test("prevent generating parameter variables", () => {
+ const generated = generateDataSources({
+ scope: createScope(),
+ dataSources: toMap([
+ {
+ id: "dataSourceid",
+ scopeInstanceId: "instanceId",
+ type: "parameter",
+ name: "myParameter",
+ },
+ ]),
+ props: toMap([
+ {
+ id: "propId",
+ instanceId: "instanceId",
+ type: "expression",
+ name: "value",
+ value: "$ws$dataSource$dataSourceId",
+ },
+ ]),
+ });
+ expect(generated.body).toEqual("");
+ expect(generated.variables).toEqual(new Map());
+ expect(generated.output).toEqual(new Map());
+});
diff --git a/packages/react-sdk/src/expression.ts b/packages/react-sdk/src/expression.ts
index a6d604964f..dce5b22aa9 100644
--- a/packages/react-sdk/src/expression.ts
+++ b/packages/react-sdk/src/expression.ts
@@ -249,11 +249,6 @@ export const generateDataSources = ({
}
for (const prop of props.values()) {
- // prevent generating parameter variables as component state
- if (prop.type === "parameter") {
- output.delete(prop.value);
- variables.delete(prop.value);
- }
// generate actions assigning variables and invoking their setters
if (prop.type === "action") {
const name = scope.getName(prop.id, prop.name);
diff --git a/packages/sdk/src/schema/data-sources.ts b/packages/sdk/src/schema/data-sources.ts
index 819be05de2..e9f9556e44 100644
--- a/packages/sdk/src/schema/data-sources.ts
+++ b/packages/sdk/src/schema/data-sources.ts
@@ -34,7 +34,12 @@ export const DataSource = z.union([
name: z.string(),
value: DataSourceVariableValue,
}),
- z.never(),
+ z.object({
+ type: z.literal("parameter"),
+ id: DataSourceId,
+ scopeInstanceId: z.optional(z.string()),
+ name: z.string(),
+ }),
]);
export type DataSource = z.infer<typeof DataSource>;