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: Expression Editor cursor position jumps to wrong place (#4242)
Ivan Starkov369e101eb8e7
diff --git a/apps/builder/app/builder/shared/code-editor-base.tsx b/apps/builder/app/builder/shared/code-editor-base.tsxindex b3bf77a121..f8eea9a59a 100644--- a/apps/builder/app/builder/shared/code-editor-base.tsx+++ b/apps/builder/app/builder/shared/code-editor-base.tsx@@ -112,6 +112,10 @@ const editorContentStyle = css({minHeight: `var(${minHeightVar}, auto)`,maxHeight: `var(${maxHeightVar}, none)`,},+ ".cm-lintRange-error": {+ textDecoration: "underline wavy red",+ backgroundColor: "rgba(255, 0, 0, 0.1)",+ },});// https://thememirror.net/cloudsdiff --git a/apps/builder/app/builder/shared/expression-editor.tsx b/apps/builder/app/builder/shared/expression-editor.tsxindex a0aab6c903..b91903a004 100644--- a/apps/builder/app/builder/shared/expression-editor.tsx+++ b/apps/builder/app/builder/shared/expression-editor.tsx@@ -7,7 +7,7 @@ import {} from "react";import { matchSorter } from "match-sorter";import type { SyntaxNode } from "@lezer/common";-import { Facet } from "@codemirror/state";+import { EditorState, Facet } from "@codemirror/state";import {type DecorationSet,type ViewUpdate,@@ -20,6 +20,7 @@ import {tooltips,} from "@codemirror/view";import { bracketMatching, syntaxTree } from "@codemirror/language";+import { linter, type Diagnostic } from "@codemirror/lint";import {type Completion,type CompletionSource,@@ -351,6 +352,105 @@ const wrapperStyle = css({"--ws-code-editor-max-height": "320px",});+/**+ * Replaces variables with their IDs, e.g., someVar -> $ws$dataSource$321+ */+const replaceWithWsVariables = EditorState.transactionFilter.of((tr) => {+ if (!tr.docChanged) {+ return tr;+ }++ const state = tr.startState;+ const [{ aliases }] = state.facet(VariablesData);++ const aliasesByName = mapGroupBy(Array.from(aliases), ([_id, name]) => name);++ // The idea of cursor preservation is simple:+ // There are 2 cases we are handling:+ // 1. A variable is replaced while typing its name. In this case, we preserve the cursor position from the end of the text.+ // 2. A variable is replaced when an operation makes the expression valid. For example, ('' b) -> ('' + b).+ // In this case, we preserve the cursor position from the start of the text.+ // This does not cover cases like (a b) -> (a + b). We are not handling it because I haven't found a way to enter such a case into real input.+ // We can improve it if issues arise.++ const cursorPos = tr.selection?.main.head ?? 0;+ const cursorPosFromEnd = tr.newDoc.length - cursorPos;++ const content = tr.newDoc.toString();+ const originalContent = tr.startState.doc.toString();++ let updatedContent = content;++ try {+ updatedContent = transpileExpression({+ expression: content,+ replaceVariable: (identifier) => {+ if (decodeDataSourceVariable(identifier) && aliases.has(identifier)) {+ return;+ }+ // prevent matching variables by unambiguous name+ const matchedAliases = aliasesByName.get(identifier);+ if (matchedAliases && matchedAliases.length === 1) {+ const [id, _name] = matchedAliases[0];++ return id;+ }+ },+ });+ } catch {+ // empty block+ }++ if (updatedContent !== content) {+ return [+ {+ changes: {+ from: 0,+ to: originalContent.length,+ insert: updatedContent,+ },+ selection: {+ anchor:+ updatedContent.slice(0, cursorPos) === content.slice(0, cursorPos)+ ? cursorPos+ : updatedContent.length - cursorPosFromEnd,+ },+ },+ ];+ }++ return tr;+});++const variableLinter = linter((view) => {+ const diagnostics: Diagnostic[] = [];+ syntaxTree(view.state)+ .cursor()+ .iterate((node) => {+ if (node.name === "VariableName") {+ const identifier = view.state.doc.sliceString(node.from, node.to);+ const [{ aliases }] = view.state.facet(VariablesData);++ const trimmedIdentifier = identifier.trim();++ if (+ decodeDataSourceVariable(trimmedIdentifier) &&+ aliases.has(trimmedIdentifier)+ ) {+ return;+ }++ diagnostics.push({+ from: node.from,+ to: node.to,+ severity: "error",+ message: `"${identifier}" is not defined`,+ });+ }+ });+ return diagnostics;+});+export const ExpressionEditor = ({editorApiRef,scope = emptyScope,@@ -384,10 +484,13 @@ export const ExpressionEditor = ({bracketMatching(),closeBrackets(),javascript({}),+VariablesData.of({ scope, aliases }),+ replaceWithWsVariables,// render autocomplete in body// to prevent popover scroll overflowtooltips({ parent: document.body }),+autocompletion({override: [scopeCompletionSource],icons: false,@@ -395,6 +498,9 @@ export const ExpressionEditor = ({}),variables,keymap.of([...closeBracketsKeymap, ...completionKeymap]),++ variableLinter,+EditorView.domEventHandlers({drop() {lastChangeIsPasteOrDrop.current = true;@@ -434,43 +540,7 @@ export const ExpressionEditor = ({readOnly={readOnly}autoFocus={autoFocus}value={value}- onChange={(value) => {- const aliasesByName = mapGroupBy(- Array.from(aliases),- ([_id, name]) => name- );- try {- // replace unknown webstudio variables with undefined- // to prevent invalid compilation- value = transpileExpression({- expression: value,- replaceVariable: (identifier) => {- if (- decodeDataSourceVariable(identifier) &&- aliases.has(identifier)- ) {- return;- }- // prevent matching variables by unambiguous name- const matchedAliases = aliasesByName.get(identifier);- if (matchedAliases && matchedAliases.length === 1) {- const [id, _name] = matchedAliases[0];- return id;- }- // replace variable with undefined- // only after paste or drop- // to avoid replacing with undefined while user is typing- if (lastChangeIsPasteOrDrop.current) {- return `undefined`;- }- },- });- } catch {- // empty block- }- lastChangeIsPasteOrDrop.current = false;- onChange(value);- }}+ onChange={onChange}onBlur={onBlur}/></div>diff --git a/apps/builder/package.json b/apps/builder/package.jsonindex de8594a04c..da2bf8ecc0 100644--- a/apps/builder/package.json+++ b/apps/builder/package.json@@ -24,6 +24,7 @@"@codemirror/lang-javascript": "^6.2.2","@codemirror/lang-markdown": "^6.2.5","@codemirror/language": "^6.10.2",+ "@codemirror/lint": "^6.8.2","@codemirror/state": "^6.4.1","@codemirror/view": "^6.30.0","@floating-ui/dom": "^1.6.5",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e4b88e59d4..8b808a9811 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -145,6 +145,9 @@ importers:'@codemirror/language':specifier: ^6.10.2version: 6.10.2+ '@codemirror/lint':+ specifier: ^6.8.2+ version: 6.8.2'@codemirror/state':specifier: ^6.4.1version: 6.4.1@@ -2707,8 +2710,8 @@ packages:'@codemirror/[email protected]':resolution: {integrity: sha512-kgbTYTo0Au6dCSc/TFy7fK3fpJmgHDv1sG1KNQKJXVi+xBTEeBPY/M30YXiU6mMXeH+YIDLsbrT4ZwNRdtF+SA==}- '@codemirror/[email protected]':- resolution: {integrity: sha512-wzRkluWb1ptPKdzlsrbwwjYCPLgzU6N88YBAmlZi8WFyuiEduSd05MnJYNogzyc8rPK7pj6m95ptUApc8sHKVA==}+ '@codemirror/[email protected]':+ resolution: {integrity: sha512-PDFG5DjHxSEjOXk9TQYYVjZDqlZTFaDBfhQixHnQOEVDDNHUbEh/hstAjcQJaA6FQdZTD1hquXTK0rVBLADR1g==}'@codemirror/[email protected]':resolution: {integrity: sha512-QkEyUiLhsJoZkbumGZlswmAhA7CBU02Wrz7zvH4SrcifbsqwlXShVXg65f3v/ts57W3dqyamEriMhij1Z3Zz4A==}@@ -10354,7 +10357,7 @@ snapshots:dependencies:'@codemirror/autocomplete': 6.18.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])'@codemirror/language': 6.10.2- '@codemirror/lint': 6.4.2+ '@codemirror/lint': 6.8.2'@codemirror/state': 6.4.1'@codemirror/view': 6.30.0'@lezer/common': 1.2.1@@ -10379,7 +10382,7 @@ snapshots:'@lezer/lr': 1.3.14style-mod: 4.1.0- '@codemirror/[email protected]':+ '@codemirror/[email protected]':dependencies:'@codemirror/state': 6.4.1'@codemirror/view': 6.30.0