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: Fix expression binding editing (#5811)
Oleg Isonenf52545a2e9e7
diff --git a/apps/builder/app/shared/code-editor-base.test.ts b/apps/builder/app/shared/code-editor-base.test.tsnew file mode 100644index 0000000000..3d1ca7e2be--- /dev/null+++ b/apps/builder/app/shared/code-editor-base.test.ts@@ -0,0 +1,37 @@+import { EditorSelection } from "@codemirror/state";+import { expect, test } from "vitest";+import { clampEditorSelection } from "./code-editor-base";++test("clampEditorSelection preserves selection within document length", () => {+ const selection = EditorSelection.create([+ EditorSelection.cursor(3),+ EditorSelection.range(6, 8),+ ]);++ const clampedSelection = clampEditorSelection(selection, 10);++ expect(+ clampedSelection.ranges.map((range) => [range.anchor, range.head])+ ).toEqual([+ [3, 3],+ [6, 8],+ ]);+ expect(clampedSelection.mainIndex).toBe(selection.mainIndex);+});++test("clampEditorSelection clamps selection to document length", () => {+ const selection = EditorSelection.create(+ [EditorSelection.range(1, 3), EditorSelection.range(8, 12)],+ 1+ );++ const clampedSelection = clampEditorSelection(selection, 5);++ expect(+ clampedSelection.ranges.map((range) => [range.anchor, range.head])+ ).toEqual([+ [1, 3],+ [5, 5],+ ]);+ expect(clampedSelection.mainIndex).toBe(selection.mainIndex);+});diff --git a/apps/builder/app/shared/code-editor-base.tsx b/apps/builder/app/shared/code-editor-base.tsxindex 22c01bdd27..d435d09636 100644--- a/apps/builder/app/shared/code-editor-base.tsx+++ b/apps/builder/app/shared/code-editor-base.tsx@@ -9,6 +9,7 @@ import {} from "react";import {Annotation,+ EditorSelection,EditorState,StateEffect,type Extension,@@ -55,6 +56,21 @@ const minHeightVar = "--ws-code-editor-min-height";const maxHeightVar = "--ws-code-editor-max-height";const maximizeIconVisibilityVar = "--ws-code-editor-maximize-icon-visibility";+export const clampEditorSelection = (+ selection: EditorSelection,+ length: number+) => {+ return EditorSelection.create(+ selection.ranges.map((range) =>+ EditorSelection.range(+ Math.min(range.anchor, length),+ Math.min(range.head, length)+ )+ ),+ selection.mainIndex+ );+};+export const getCodeEditorCssVars = ({minHeight,maxHeight,@@ -377,6 +393,7 @@ export const EditorContent = ({view.dispatch({changes: { from: 0, to: view.state.doc.length, insert: value },+ selection: clampEditorSelection(view.state.selection, value.length),annotations: [ExternalChange.of(true)],});}, [value]);diff --git a/apps/builder/app/shared/data-variables.test.tsx b/apps/builder/app/shared/data-variables.test.tsxindex 9583c2c71f..65efbbbc9e 100644--- a/apps/builder/app/shared/data-variables.test.tsx+++ b/apps/builder/app/shared/data-variables.test.tsx@@ -160,6 +160,24 @@ test("restore expression variables", () => {).toEqual("$ws$dataSource$myId + missingVariable");});+test("roundtrip system variable in assignment expression", () => {+ const expression = `system.origin = 123 ? 'test' : "bla"`;+ const restoredExpression = restoreExpressionVariables({+ expression,+ maskedIdByName: new Map([["system", SYSTEM_VARIABLE_ID]]),+ });++ expect(restoredExpression).toEqual(+ `$ws$system.origin = 123 ? 'test' : "bla"`+ );+ expect(+ unsetExpressionVariables({+ expression: restoredExpression,+ unsetNameById: new Map([[SYSTEM_VARIABLE_ID, "system"]]),+ })+ ).toEqual(expression);+});+test("replace data source ids in expression", () => {expect(replaceDataSourcesInExpression(diff --git a/packages/sdk/src/expression.test.ts b/packages/sdk/src/expression.test.tsindex 111762fda6..0aa421acd7 100644--- a/packages/sdk/src/expression.test.ts+++ b/packages/sdk/src/expression.test.ts@@ -1,4 +1,5 @@import { describe, expect, test } from "vitest";+import { parseExpressionAt } from "acorn";import {type Diagnostic,decodeDataVariableId,@@ -128,6 +129,76 @@ describe("lint expression", () => {).toEqual([]);});+ test("lint member assignment targets", () => {+ expect(+ lintExpression({+ expression: ` a[b].c = d`,+ allowAssignment: true,+ availableVariables: new Set(["a", "b", "d"]),+ })+ ).toEqual([]);+ expect(+ lintExpression({+ expression: ` a.b = c`,+ allowAssignment: true,+ availableVariables: new Set(["c"]),+ })+ ).toEqual([warn(1, 2, `"a" is not defined in the scope`)]);+ });++ test("lint assignment operators and targets", () => {+ const assignmentExpressions = [+ ` a = b`,+ ` a += b`,+ ` a -= b`,+ ` a *= b`,+ ` a /= b`,+ ` a %= b`,+ ` a **= b`,+ ` a ||= b`,+ ` a &&= b`,+ ` a ??= b`,+ ` a.b = c`,+ ` a[b] = c`,+ ` a[b].c = d`,+ ` a.b[c.d].e ??= f.g`,+ ];++ for (const expression of assignmentExpressions) {+ expect(+ lintExpression({+ expression,+ allowAssignment: true,+ availableVariables: new Set(["a", "b", "c", "d", "f"]),+ })+ ).toEqual([]);+ }+ });++ test("forbid destructuring assignment", () => {+ expect(+ lintExpression({+ expression: ` ({ a } = b)`,+ allowAssignment: true,+ availableVariables: new Set(["b"]),+ })+ ).toEqual([error(2, 7, "Destructuring assignment is not supported")]);+ expect(+ lintExpression({+ expression: ` [a] = b`,+ allowAssignment: true,+ availableVariables: new Set(["b"]),+ })+ ).toEqual([error(1, 4, "Destructuring assignment is not supported")]);+ expect(+ lintExpression({+ expression: ` ({ nested: a } = b)`,+ allowAssignment: true,+ availableVariables: new Set(["b"]),+ })+ ).toEqual([error(2, 15, "Destructuring assignment is not supported")]);+ });+test("forbid unavailable variables", () => {expect(lintExpression({ expression: ` a = b + 1`, allowAssignment: true })@@ -411,6 +482,15 @@ describe("get expression identifiers", () => {);});+ test("find identifiers in assignment targets", () => {+ expect(getExpressionIdentifiers("a[b].c = d.e")).toEqual(+ new Set(["a", "b", "d"])+ );+ expect(getExpressionIdentifiers("a.b[c.d].e ??= f.g")).toEqual(+ new Set(["a", "c", "f"])+ );+ });+test("deduplicate identifiers", () => {expect(getExpressionIdentifiers("a = a + b")).toEqual(new Set(["a", "b"]));});@@ -454,6 +534,57 @@ describe("transpile expression", () => {).toEqual("a?.['b']?.c");});+ test("skip optional chaining in assignment targets", () => {+ expect(+ transpileExpression({ expression: "a.b = c.d", executable: true })+ ).toEqual("a.b = c?.d");+ expect(+ transpileExpression({ expression: "a[b.c].d = e.f", executable: true })+ ).toEqual("a[b?.c].d = e?.f");+ });++ test("skip optional chaining in assignment targets for all assignment operators", () => {+ const operators = [+ "=",+ "+=",+ "-=",+ "*=",+ "/=",+ "%=",+ "**=",+ "||=",+ "&&=",+ "??=",+ ];++ for (const operator of operators) {+ const expression = `a.b ${operator} c.d`;+ const transpiled = transpileExpression({ expression, executable: true });+ expect(transpiled).toEqual(`a.b ${operator} c?.d`);+ expect(() =>+ parseExpressionAt(transpiled, 0, { ecmaVersion: "latest" })+ ).not.toThrow();+ }+ });++ test("transpile executable assignment expressions", () => {+ const cases = [+ ["a.b = c.d", "a.b = c?.d"],+ ["a[b] = c.d", "a[b] = c?.d"],+ ["a[b.c] = d.e", "a[b?.c] = d?.e"],+ ["a[b.c].d = e.f", "a[b?.c].d = e?.f"],+ ["a.b[c.d].e ??= f.g", "a.b[c?.d].e ??= f?.g"],+ ] as const;++ for (const [expression, expected] of cases) {+ const transpiled = transpileExpression({ expression, executable: true });+ expect(transpiled).toEqual(expected);+ expect(() =>+ parseExpressionAt(transpiled, 0, { ecmaVersion: "latest" })+ ).not.toThrow();+ }+ });+test("replace variable", () => {expect(transpileExpression({@@ -483,15 +614,27 @@ describe("transpile expression", () => {});test("inform identifier is an assignee", () => {- expect(- transpileExpression({- expression: "a = b",- replaceVariable: (identifier, assignee) => {- const suffix = assignee ? "_assignee" : "_assigner";- return identifier + suffix;- },- })- ).toEqual("a_assignee = b_assigner");+ const replaceVariable = (identifier: string, assignee: boolean) => {+ const suffix = assignee ? "_assignee" : "_assigner";+ return identifier + suffix;+ };++ const cases = [+ ["a = b", "a_assignee = b_assigner"],+ ["a += b", "a_assignee += b_assigner"],+ ["a ||= b", "a_assignee ||= b_assigner"],+ ["a ??= b", "a_assignee ??= b_assigner"],+ ["a.b = c", "a_assignee.b = c_assigner"],+ ["a[b] = c", "a_assignee[b_assigner] = c_assigner"],+ ["a[b].c = d", "a_assignee[b_assigner].c = d_assigner"],+ ["a.b[c.d].e ??= f.g", "a_assignee.b[c_assigner.d].e ??= f_assigner.g"],+ ] as const;++ for (const [expression, expected] of cases) {+ expect(transpileExpression({ expression, replaceVariable })).toEqual(+ expected+ );+ }});test("transpile object literal without changes", () => {diff --git a/packages/sdk/src/expression.ts b/packages/sdk/src/expression.tsindex 90f6048d41..87293e0521 100644--- a/packages/sdk/src/expression.ts+++ b/packages/sdk/src/expression.ts@@ -1,6 +1,8 @@import {type Expression,type Identifier,+ type MemberExpression,+ type Pattern,parse,parseExpressionAt,} from "acorn";@@ -29,6 +31,35 @@ type ExpressionVisitor = {[K in Expression["type"]]: (node: Extract<Expression, { type: K }>) => void;};+type AssignmentTargetKind = "binding" | "memberObject";++const walkAssignmentTarget = (+ node: Pattern,+ visitor: {+ Identifier?: (node: Identifier, kind: AssignmentTargetKind) => void;+ MemberExpression?: (node: MemberExpression) => void;+ UnsupportedPattern?: (node: Pattern) => void;+ }+) => {+ if (node.type === "Identifier") {+ visitor.Identifier?.(node, "binding");+ return;+ }++ if (node.type === "MemberExpression") {+ visitor.MemberExpression?.(node);+ const { object } = node;+ if (object.type === "Identifier") {+ visitor.Identifier?.(object, "memberObject");+ } else if (object.type === "MemberExpression") {+ walkAssignmentTarget(object, visitor);+ }+ return;+ }++ visitor.UnsupportedPattern?.(node);+};+export type VariableValues =| ReadonlyMap<Identifier["name"], unknown>| Readonly<Record<Identifier["name"], unknown>>;@@ -245,7 +276,7 @@ export const lintExpression = ({message: string,severity: "error" | "warning" = "error") => {- return (node: Expression) => {+ return (node: { start: number; end: number }) => {diagnostics.push({// tune error position after wrapping expression with parenthesesfrom: node.start - 1,@@ -299,8 +330,11 @@ export const lintExpression = ({addMessage("Assignment is supported only inside actions")(node);return;}- simple(node.left, {- Identifier(node) {+ walkAssignmentTarget(node.left, {+ Identifier(node, kind) {+ if (kind !== "binding") {+ return;+ }if (availableVariables.has(node.name) === false) {addMessage(`"${node.name}" is not defined in the scope`,@@ -308,6 +342,9 @@ export const lintExpression = ({)(node);}},+ UnsupportedPattern: addMessage(+ "Destructuring assignment is not supported"+ ),});},// parser forbids to yield inside module@@ -417,7 +454,7 @@ export const getExpressionIdentifiers = (expression: string) => {simple(root, {Identifier: (node) => identifiers.add(node.name),AssignmentExpression(node) {- simple(node.left, {+ walkAssignmentTarget(node.left, {Identifier: (node) => identifiers.add(node.name),});},@@ -456,17 +493,49 @@ export const transpileExpression = ({// throw new error to trace error in our code instead of acornthrow Error(`${message} in ${JSON.stringify(expression)}`);}+ const assignmentTargetMemberRanges: [start: number, end: number][] = [];+ if (executable) {+ simple(root, {+ AssignmentExpression(node) {+ walkAssignmentTarget(node.left, {+ MemberExpression(node) {+ assignmentTargetMemberRanges.push([node.start, node.end]);+ },+ });+ },+ });+ }const replacements: [start: number, end: number, fragment: string][] = [];+ const replacementIndexByRange = new Map<string, number>();+ const addReplacement = (+ start: number,+ end: number,+ fragment: string,+ { replaceExisting = false }: { replaceExisting?: boolean } = {}+ ) => {+ const range = `${start}:${end}`;+ const existingIndex = replacementIndexByRange.get(range);+ if (existingIndex !== undefined) {+ if (replaceExisting) {+ replacements[existingIndex] = [start, end, fragment];+ }+ return;+ }+ replacementIndexByRange.set(range, replacements.length);+ replacements.push([start, end, fragment]);+ };const replaceIdentifier = (node: Identifier, assignee: boolean) => {const newName = replaceVariable?.(node.name, assignee);if (newName) {- replacements.push([node.start, node.end, newName]);+ addReplacement(node.start, node.end, newName, {+ replaceExisting: assignee,+ });}};simple(root, {Identifier: (node) => replaceIdentifier(node, false),AssignmentExpression(node) {- simple(node.left, {+ walkAssignmentTarget(node.left, {Identifier: (node) => replaceIdentifier(node, true),});},@@ -474,15 +543,22 @@ export const transpileExpression = ({if (executable === false || node.optional) {return;}+ if (+ assignmentTargetMemberRanges.some(+ ([start, end]) => start === node.start && end === node.end+ )+ ) {+ return;+ }// a . b -> a ?. bif (node.computed === false) {const dotIndex = expression.indexOf(".", node.object.end);- replacements.push([dotIndex, dotIndex, "?"]);+ addReplacement(dotIndex, dotIndex, "?");}// a [b] -> a ?.[b]if (node.computed === true) {const dotIndex = expression.indexOf("[", node.object.end);- replacements.push([dotIndex, dotIndex, "?."]);+ addReplacement(dotIndex, dotIndex, "?.");}},CallExpression(node) {@@ -494,7 +570,7 @@ export const transpileExpression = ({// Find the opening parenthesis after the method nameconst openParenIndex = expression.indexOf("(", node.callee.end);if (openParenIndex !== -1) {- replacements.push([openParenIndex, openParenIndex, "?."]);+ addReplacement(openParenIndex, openParenIndex, "?.");}}},