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.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
fix: prevent data variable creation crash (#5815)
Oleg Isonen8764b57a49fe
diff --git a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx b/apps/builder/app/builder/features/settings-panel/variable-popover.tsxindex 6852d651e7..4709542ad9 100644--- a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx+++ b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx@@ -303,7 +303,16 @@ const ParameterForm = forwardRef<});ParameterForm.displayName = "ParameterForm";-const saveVariable = (variable: undefined | DataSource, formData: FormData) => {+type ValueVariableType = Extract<+ VariableType,+ "string" | "number" | "boolean" | "json"+>;++const saveVariable = (+ variable: undefined | DataSource,+ type: ValueVariableType,+ formData: FormData+) => {const dataSourceId = variable?.id ?? nanoid();// preserve existing instance scope when editconst scopeInstanceId =@@ -311,7 +320,6 @@ const saveVariable = (variable: undefined | DataSource, formData: FormData) => {if (scopeInstanceId === undefined) {return;}- const type = z.string().parse(formData.get("type"));const name = z.string().parse(formData.get("name"));const value = z.string().nullable().parse(formData.get("value"));let variableValue: Extract<DataSource, { type: "variable" }>["value"];@@ -349,13 +357,15 @@ const saveVariable = (variable: undefined | DataSource, formData: FormData) => {const useValuePanelRef = ({ref,variable,+ type,}: {ref: Ref<undefined | PanelApi>;variable?: DataSource;+ type: ValueVariableType;}) => {useImperativeHandle(ref, () => ({save: (formData) => {- saveVariable(variable, formData);+ saveVariable(variable, type, formData);},}));};@@ -369,7 +379,7 @@ const StringForm = forwardRef<}>(({ variable, value: unknownValue, onChange }, ref) => {const value = typeof unknownValue === "string" ? unknownValue : "";- useValuePanelRef({ ref, variable });+ useValuePanelRef({ ref, variable, type: "string" });const valueId = useId();return (<Flex direction="column" css={{ gap: theme.spacing[3] }}>@@ -429,7 +439,7 @@ const NumberForm = forwardRef<valueRef.current?.setCustomValidity(validateNumberValue(value));setValueError("");}, [value]);- useValuePanelRef({ ref, variable });+ useValuePanelRef({ ref, variable, type: "number" });const valueId = useId();return (<>@@ -465,7 +475,7 @@ const BooleanForm = forwardRef<}>(({ variable, value: unknownValue, onChange }, ref) => {const value = typeof unknownValue === "boolean" ? unknownValue : false;- useValuePanelRef({ ref, variable });+ useValuePanelRef({ ref, variable, type: "boolean" });const valueId = useId();return (<>@@ -515,7 +525,7 @@ const JsonForm = forwardRef<valueRef.current?.setCustomValidity(validateJsonValue(value));setValueError("");}, [value]);- useValuePanelRef({ ref, variable });+ useValuePanelRef({ ref, variable, type: "json" });return (<><input@@ -728,6 +738,7 @@ const VariablePreview = ({css={{ position: "absolute", inset: 0 }}><Button+ type="button"color="neutral"disabled={hasPendingResources}onClick={onLoadData}@@ -908,6 +919,7 @@ const VariablePopoverContent = ({variableType === "graphql-resource") && (<Tooltip content="Copy resource as cURL command" side="bottom"><Button+ type="button"aria-label="Copy resource as cURL command"prefix={<CopyIcon />}color="ghost"@@ -920,6 +932,7 @@ const VariablePopoverContent = ({variableType === "system-resource") && (<Tooltip content="Refresh resource data" side="bottom"><Button+ type="button"aria-label="Refresh resource data"prefix={<RefreshIcon />}color="ghost"diff --git a/apps/builder/app/builder/features/settings-panel/variables-section.tsx b/apps/builder/app/builder/features/settings-panel/variables-section.tsxindex 044e09cb0d..ff35e930f4 100644--- a/apps/builder/app/builder/features/settings-panel/variables-section.tsx+++ b/apps/builder/app/builder/features/settings-panel/variables-section.tsx@@ -107,7 +107,9 @@ const EmptyVariables = () => {</Flex><Flex justify="center" align="center"><VariablePopoverTrigger>- <Button prefix={<PlusIcon />}>Create data variable</Button>+ <Button type="button" prefix={<PlusIcon />}>+ Create data variable+ </Button></VariablePopoverTrigger></Flex></Flex>@@ -279,6 +281,7 @@ export const VariablesSection = () => {suffix={<VariablePopoverTrigger><SectionTitleButton+ type="button"prefix={<PlusIcon />}// open panel when add new varableonClick={() => {diff --git a/apps/builder/app/builder/shared/expression-editor.test.ts b/apps/builder/app/builder/shared/expression-editor.test.tsindex dbf8e733a1..5d843def78 100644--- a/apps/builder/app/builder/shared/expression-editor.test.ts+++ b/apps/builder/app/builder/shared/expression-editor.test.ts@@ -5,6 +5,7 @@ import { javascript } from "@codemirror/lang-javascript";import { allowedArrayMethods, allowedStringMethods } from "@webstudio-is/sdk";import {completionPath,+ formatValue,generateCompletionOptions,getCompletionTarget,getCompletionReplacement,@@ -75,6 +76,19 @@ const getCompletionPath = (value: string) => {return completionPath(new CompletionContext(state, value.length, true));};+describe("formatValue", () => {+ test("formats missing preview values as an empty editor string", () => {+ expect(formatValue(undefined)).toEqual("");+ expect(typeof formatValue(undefined)).toEqual("string");+ });++ test("always returns a string for editor values", () => {+ expect(formatValue(() => {})).toEqual("");+ expect(formatValue("text")).toEqual('"text"');+ expect(formatValue(0)).toEqual("0");+ });+});+describe("generateCompletionOptions", () => {describe("object properties", () => {test("returns object properties with preview values", () => {diff --git a/apps/builder/app/builder/shared/expression-editor.tsx b/apps/builder/app/builder/shared/expression-editor.tsxindex 013c4865c8..40c7799faa 100644--- a/apps/builder/app/builder/shared/expression-editor.tsx+++ b/apps/builder/app/builder/shared/expression-editor.tsx@@ -50,8 +50,11 @@ import {export type { EditorApi };-export const formatValue = (value: unknown) => {+export const formatValue = (value: unknown): string => {try {+ if (value === undefined) {+ return "";+ }if (Array.isArray(value)) {// format arrays as multilinereturn JSON.stringify(value, null, 2);@@ -61,7 +64,7 @@ export const formatValue = (value: unknown) => {// syntax highlighting as expression instead of blockreturn `(${JSON.stringify(value, null, 2)})`;}- return JSON.stringify(value);+ return JSON.stringify(value) ?? "";} catch {// show nothing when value is invalidreturn "";diff --git a/packages/project/src/db/build-patch.test.ts b/packages/project/src/db/build-patch.test.tsindex bc2906e051..a014e7b077 100644--- a/packages/project/src/db/build-patch.test.ts+++ b/packages/project/src/db/build-patch.test.ts@@ -249,6 +249,55 @@ describe("patchBuild", () => {).toBe("/company");});+ test("applies data source variable additions", async () => {+ const result = await createBuildPatchUpdate({+ build: buildRow,+ clientVersion: 3,+ transactions: [+ transaction({+ payload: [+ {+ namespace: "dataSources",+ patches: [+ {+ op: "add",+ path: ["variable-1"],+ value: {+ id: "variable-1",+ scopeInstanceId: "body-1",+ name: "title",+ type: "variable",+ value: { type: "string", value: "" },+ },+ },+ ],+ },+ ],+ }),+ ],+ });++ expect(result).toMatchObject({+ status: "ok",+ nextVersion: 4,+ update: {+ lastTransactionId: "tx-1",+ version: 4,+ },+ });+ if (result.status === "ok") {+ expect(JSON.parse(result.update?.dataSources ?? "")).toEqual([+ {+ id: "variable-1",+ scopeInstanceId: "body-1",+ name: "title",+ type: "variable",+ value: { type: "string", value: "" },+ },+ ]);+ }+ });+test("returns ok when retrying a transaction already saved by the server", async () => {let didPatch = false;server.use(