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.

fix: replace unknown variables on paste (#2945)

Bogdan Chadkin1fe3a842b0a8
diff --git a/apps/builder/app/builder/shared/expression-editor.tsx b/apps/builder/app/builder/shared/expression-editor.tsx
index eb38e1be76..255f2bf803 100644
--- a/apps/builder/app/builder/shared/expression-editor.tsx
+++ b/apps/builder/app/builder/shared/expression-editor.tsx
@@ -36,6 +36,10 @@ import {
} from "@codemirror/autocomplete";
import { javascript } from "@codemirror/lang-javascript";
import { theme, textVariants, css } from "@webstudio-is/design-system";
+import {
+ decodeDataSourceVariable,
+ validateExpression,
+} from "@webstudio-is/react-sdk";
import { CodeEditor } from "./code-editor";
export const formatValue = (value: unknown) => {
@@ -417,7 +421,34 @@ export const ExpressionEditor = ({
readOnly={readOnly}
autoFocus={autoFocus}
value={value}
- onChange={onChange}
+ onChange={(value) => {
+ try {
+ let hasReplacements = false;
+ // replace unknown webstudio variables with undefined
+ // to prevent invalid compilation
+ const newExpression = validateExpression(value, {
+ effectful: true,
+ transformIdentifier: (identifier) => {
+ if (
+ decodeDataSourceVariable(identifier) &&
+ aliases.has(identifier) === false
+ ) {
+ hasReplacements = true;
+ return `undefined`;
+ }
+ return identifier;
+ },
+ });
+ // reformat only when something is replaced
+ // to break user interaction
+ if (hasReplacements) {
+ value = newExpression;
+ }
+ } catch {
+ // empty block
+ }
+ onChange(value);
+ }}
onBlur={onBlur}
/>
</div>
diff --git a/packages/react-sdk/src/expression.ts b/packages/react-sdk/src/expression.ts
index 83e1057f81..9150939dc1 100644
--- a/packages/react-sdk/src/expression.ts
+++ b/packages/react-sdk/src/expression.ts
@@ -8,6 +8,8 @@ import type {
import type { ObjectExpression, Property } from "@jsep-plugin/object";
import type { DataSources, Scope } from "@webstudio-is/sdk";
+jsep.literals["undefined"] = "undefined";
+
jsep.plugins.register(jsepAssignment);
jsep.plugins.register(jsepObject);