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.

feat: autocomplete computed member expression (#2866)

Bogdan Chadkin4f7dbce2f3f8
diff --git a/apps/builder/app/builder/shared/expression-editor.stories.tsx b/apps/builder/app/builder/shared/expression-editor.stories.tsx
index 523591573c..9336f4b52e 100644
--- a/apps/builder/app/builder/shared/expression-editor.stories.tsx
+++ b/apps/builder/app/builder/shared/expression-editor.stories.tsx
@@ -9,16 +9,33 @@ export default {
const scope = {
$ws$dataSource$123: {
- world: "!s fb skffsjdfksjdlkjslkkjlkj sjf lsdjsskljl kjsf",
- hello: [],
- aa: 0,
- b: true,
+ long: "!s fb skffsjdfksjdlkjslkkjlkj sjf lsdjsskljl kjsf",
+ array: [],
+ number: 0,
+ boolean: true,
+ object: { param: "value" },
},
$ws$dataSource$321: { my: "god" },
+ $ws$dataSource$computed: [
+ // 0-11 keys
+ { "with space": 0 },
+ { "0_numeric": 0 },
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ ],
};
const aliases = new Map<string, string>([
["$ws$dataSource$123", "Hello world"],
["$ws$dataSource$321", "oh"],
+ ["$ws$dataSource$computed", "computed"],
]);
const ExpressionStory = () => {
diff --git a/apps/builder/app/builder/shared/expression-editor.tsx b/apps/builder/app/builder/shared/expression-editor.tsx
index a73ae3ad97..99561f03eb 100644
--- a/apps/builder/app/builder/shared/expression-editor.tsx
+++ b/apps/builder/app/builder/shared/expression-editor.tsx
@@ -1,5 +1,6 @@
import { useMemo } from "react";
import { matchSorter } from "match-sorter";
+import type { SyntaxNode } from "@lezer/common";
import { Facet } from "@codemirror/state";
import {
type DecorationSet,
@@ -19,6 +20,7 @@ import {
bracketMatching,
defaultHighlightStyle,
syntaxHighlighting,
+ syntaxTree,
} from "@codemirror/language";
import {
type Completion,
@@ -28,8 +30,11 @@ import {
closeBrackets,
closeBracketsKeymap,
completionKeymap,
+ CompletionContext,
+ insertCompletionText,
+ pickedCompletion,
} from "@codemirror/autocomplete";
-import { completionPath, javascript } from "@codemirror/lang-javascript";
+import { javascript } from "@codemirror/lang-javascript";
import { theme, textVariants, css } from "@webstudio-is/design-system";
import { CodeEditor } from "./code-editor";
@@ -80,13 +85,95 @@ const VariablesData = Facet.define<{
// completion based on
// https://github.com/codemirror/lang-javascript/blob/4dcee95aee9386fd2c8ad55f93e587b39d968489/src/complete.ts
+const Identifier = /^[\p{L}$][\p{L}\p{N}$]*$/u;
+
+const pathFor = (
+ read: (node: SyntaxNode) => string,
+ member: SyntaxNode,
+ name: string
+) => {
+ const path: string[] = [];
+ // traverse from current node to the root variable
+ for (;;) {
+ const object = member.firstChild;
+ if (object?.name === "VariableName") {
+ path.push(read(object));
+ return { path: path.reverse(), name };
+ }
+ if (object?.name === "MemberExpression") {
+ // MemberExpression(SyntaxNode PropertyName)
+ if (object.lastChild?.name === "PropertyName") {
+ path.push(read(object.lastChild!));
+ member = object;
+ continue;
+ }
+ // MemberExpression(SyntaxNode [ SyntaxNode ])
+ if (object.lastChild?.name === "]") {
+ const computed = object.lastChild.prevSibling;
+ if (computed?.name === "Number") {
+ path.push(read(computed));
+ member = object;
+ continue;
+ }
+ if (computed?.name === "String") {
+ // trim quotes from string literal
+ path.push(read(computed).slice(1, -1));
+ member = object;
+ continue;
+ }
+ }
+ }
+ // unexpected case
+ break;
+ }
+};
+
+/// Helper function for defining JavaScript completion sources. It
+/// returns the completable name and object path for a completion
+/// context, or undefined if no name/property completion should happen at
+/// that position. For example, when completing after `a.b.c` it will
+/// return `{path: ["a", "b"], name: "c"}`. When completing after `x`
+/// it will return `{path: [], name: "x"}`. When not in a property or
+/// name, it will return undefined if `context.explicit` is false, and
+/// `{path: [], name: ""}` otherwise.
+const completionPath = (
+ context: CompletionContext
+): { path: string[]; name: string } | undefined => {
+ const read = (node: SyntaxNode) =>
+ context.state.doc.sliceString(node.from, node.to);
+ const inner = syntaxTree(context.state).resolveInner(context.pos, -1);
+ // suggest global variable name when user start completion explicitly
+ if (inner.name === "Script") {
+ if (context.explicit) {
+ return { path: [], name: "" };
+ }
+ return;
+ }
+ // complete variable name when start entering
+ if (inner.name === "VariableName") {
+ return { path: [], name: read(inner) };
+ }
+ // suggest property name when enter `object.`
+ if (inner.name === "." && inner.parent?.name === "MemberExpression") {
+ return pathFor(read, inner.parent, "");
+ }
+ // complete property when enter "object.prope"
+ if (
+ inner.name === "PropertyName" &&
+ inner.parent?.name === "MemberExpression"
+ ) {
+ return pathFor(read, inner.parent, read(inner));
+ }
+ return;
+};
+
// Defines a completion source that completes from the given scope
// object (for example `globalThis`). Will enter properties
// of the object when completing properties on a directly-named path.
const scopeCompletionSource: CompletionSource = (context) => {
const [{ scope, aliases }] = context.state.facet(VariablesData);
const path = completionPath(context);
- if (path === null) {
+ if (path === undefined) {
return null;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -103,9 +190,46 @@ const scopeCompletionSource: CompletionSource = (context) => {
label: name,
displayLabel: aliases.get(name),
detail: formatValuePreview(value),
+ apply: (view, completion, from, to) => {
+ if (Identifier.test(name)) {
+ // complete with dot
+ view.dispatch({
+ ...insertCompletionText(view.state, name, from, to),
+ annotations: pickedCompletion.of(completion),
+ });
+ } else {
+ // complete with computed member expression
+ view.dispatch({
+ ...insertCompletionText(
+ view.state,
+ // `param with spaces` -> ["param with spaces"]
+ // `0` -> [0]
+ `[${/^\d+$/.test(name) ? name : JSON.stringify(name)}]`,
+ // remove dot when autocomplete computed member expression
+ // variable.
+ // variable["name"]
+ from - 1,
+ to
+ ),
+ annotations: pickedCompletion.of(completion),
+ });
+ }
+ },
}));
options = matchSorter(options, path.name, {
keys: [(option) => option.displayLabel ?? option.label],
+ baseSort: (left, right) => {
+ const leftName = left.item.label;
+ const rightName = right.item.label;
+ const leftIndex = Number(leftName);
+ const rightIndex = Number(rightName);
+ // sort string fields
+ if (Number.isNaN(leftIndex) || Number.isNaN(rightIndex)) {
+ return leftName.localeCompare(rightName);
+ }
+ // sort indexes if both numbers
+ return leftIndex - rightIndex;
+ },
});
}
return {
diff --git a/apps/builder/package.json b/apps/builder/package.json
index ee80fc4063..b827986401 100644
--- a/apps/builder/package.json
+++ b/apps/builder/package.json
@@ -36,6 +36,7 @@
"@lexical/react": "^0.12.2",
"@lexical/selection": "^0.12.2",
"@lexical/utils": "^0.12.2",
+ "@lezer/common": "^1.2.1",
"@nanostores/react": "^0.7.1",
"@radix-ui/react-select": "^2.0.0",
"@radix-ui/react-tooltip": "^1.0.7",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c270e55451..746d117348 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -63,7 +63,7 @@ importers:
dependencies:
'@codemirror/autocomplete':
specifier: ^6.11.1
- version: 6.11.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
+ version: 6.11.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
'@codemirror/commands':
specifier: ^6.3.2
version: 6.3.2
@@ -109,6 +109,9 @@ importers:
'@lexical/utils':
specifier: ^0.12.2
version: 0.12.2([email protected])
+ '@lezer/common':
+ specifier: ^1.2.1
+ version: 1.2.1
'@nanostores/react':
specifier: ^0.7.1
@@ -3303,7 +3306,7 @@ packages:
resolution: {integrity: sha512-0FRcsz7Ea3jT+gc5gKPIYciykm1bbAaTpygdzpCwGt0RL+V83zWnYN30NWDW4rIHj/FHtz+MIuBKS61C8l7AzQ==}
patched: true
- /@codemirror/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected]):
+ /@codemirror/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected]):
resolution: {integrity: sha512-L5UInv8Ffd6BPw0P3EF7JLYAMeEbclY7+6Q11REt8vhih8RuLreKtPy/xk8wPxs4EQgYqzI7cdgpiYwWlbS/ow==}
peerDependencies:
'@codemirror/language': ^6.0.0
@@ -3314,7 +3317,7 @@ packages:
'@codemirror/language': 6.9.3
'@codemirror/state': 6.3.3
'@codemirror/view': 6.22.3
- '@lezer/common': 1.1.2
+ '@lezer/common': 1.2.1
dev: false
/@codemirror/[email protected]:
@@ -3323,16 +3326,16 @@ packages:
'@codemirror/language': 6.9.3
'@codemirror/state': 6.3.3
'@codemirror/view': 6.22.3
- '@lezer/common': 1.1.2
+ '@lezer/common': 1.2.1
dev: false
/@codemirror/[email protected](@codemirror/[email protected]):
resolution: {integrity: sha512-/UNWDNV5Viwi/1lpr/dIXJNWiwDxpw13I4pTUAsNxZdg6E0mI2kTQb0P2iHczg1Tu+H4EBgJR+hYhKiHKko7qg==}
dependencies:
- '@codemirror/autocomplete': 6.11.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
+ '@codemirror/autocomplete': 6.11.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
'@codemirror/language': 6.9.3
'@codemirror/state': 6.3.3
- '@lezer/common': 1.1.2
+ '@lezer/common': 1.2.1
'@lezer/css': 1.1.4
transitivePeerDependencies:
- '@codemirror/view'
@@ -3341,13 +3344,13 @@ packages:
/@codemirror/[email protected]:
resolution: {integrity: sha512-y9hWSSO41XlcL4uYwWyk0lEgTHcelWWfRuqmvcAmxfCs0HNWZdriWo/EU43S63SxEZpc1Hd50Itw7ktfQvfkUg==}
dependencies:
- '@codemirror/autocomplete': 6.11.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
+ '@codemirror/autocomplete': 6.11.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
'@codemirror/lang-css': 6.2.1(@codemirror/[email protected])
'@codemirror/lang-javascript': 6.2.1
'@codemirror/language': 6.9.3
'@codemirror/state': 6.3.3
'@codemirror/view': 6.22.3
- '@lezer/common': 1.1.2
+ '@lezer/common': 1.2.1
'@lezer/css': 1.1.4
'@lezer/html': 1.3.7
dev: false
@@ -3355,12 +3358,12 @@ packages:
/@codemirror/[email protected]:
resolution: {integrity: sha512-jlFOXTejVyiQCW3EQwvKH0m99bUYIw40oPmFjSX2VS78yzfe0HELZ+NEo9Yfo1MkGRpGlj3Gnu4rdxV1EnAs5A==}
dependencies:
- '@codemirror/autocomplete': 6.11.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
+ '@codemirror/autocomplete': 6.11.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
'@codemirror/language': 6.9.3
'@codemirror/lint': 6.4.2
'@codemirror/state': 6.3.3
'@codemirror/view': 6.22.3
- '@lezer/common': 1.1.2
+ '@lezer/common': 1.2.1
'@lezer/javascript': 1.4.10
dev: false
@@ -3369,7 +3372,7 @@ packages:
dependencies:
'@codemirror/state': 6.3.3
'@codemirror/view': 6.22.3
- '@lezer/common': 1.1.2
+ '@lezer/common': 1.2.1
'@lezer/highlight': 1.2.0
'@lezer/lr': 1.3.14
style-mod: 4.1.0
@@ -4878,8 +4881,8 @@ packages:
yjs: 13.5.52
dev: false
- resolution: {integrity: sha512-V+GqBsga5+cQJMfM0GdnHmg4DgWvLzgMWjbldBg0+jC3k9Gu6nJNZDLJxXEBT1Xj8KhRN4jmbC5CY7SIL++sVw==}
+ resolution: {integrity: sha512-yemX0ZD2xS/73llMZIK6KplkjIjf2EvAHcinDi/TfJ9hS25G0388+ClHt6/3but0oOxinTcQHJLDXh6w1crzFQ==}
dev: false
@@ -4892,13 +4895,13 @@ packages:
resolution: {integrity: sha512-WrS5Mw51sGrpqjlh3d4/fOwpEV2Hd3YOkp9DBt4k8XZQcoTHZFB7sx030A6OcahF4J1nDQAa3jXlTVVYH50IFA==}
dependencies:
- '@lezer/common': 1.1.2
+ '@lezer/common': 1.2.1
dev: false
resolution: {integrity: sha512-Wo+rZ5UjLP0VqUTyXjzgmTYRW5bvTJUFn4Uw0K3HCQjX2/+f+zRo9GLN5BCAojwHQISPvaQk8BWSv2SSKx/UcQ==}
dependencies:
- '@lezer/common': 1.1.2
+ '@lezer/common': 1.2.1
'@lezer/highlight': 1.2.0
'@lezer/lr': 1.3.14
dev: false
@@ -4913,7 +4916,7 @@ packages:
resolution: {integrity: sha512-z5mY4LStlA3yL7aHT/rqgG614cfcvklS+8oFRFBYrs4YaWLJyKKM4+nN6KopToX0o9Hj6zmH6M5kinOYuy06ug==}
dependencies:
- '@lezer/common': 1.1.2
+ '@lezer/common': 1.2.1
dev: false