Skip to content

A platform for community discussion. Free, open, simple.

DEV: Split workflows expression editor into per-extension modules (#40715)

Renato Atiliocebc9e34a339
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-input.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-input.gjs
index 20c63162968..66deb697a2e 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-input.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-input.gjs
@@ -5,7 +5,6 @@ import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import { cancel } from "@ember/runloop";
import { service } from "@ember/service";
import discourseLater from "discourse/lib/later";
-import buildWorkflowExtension from "../../../lib/workflows/codemirror-extension";
import {
ancestorOutputNodes,
inputConnectionsForNode,
@@ -17,6 +16,7 @@ import {
schemaFieldsForNodeInput,
schemaFieldsForNodeOutput,
} from "../../../lib/workflows/data-schema";
+import buildExpressionExtensions from "../../../lib/workflows/expression-extensions";
import ExpressionPreview from "../variable/expression-preview";
import VariableInput from "../variable/input";
@@ -103,7 +103,7 @@ export default class ExpressionInput extends Component {
}))
: [];
- return buildWorkflowExtension(cmParams, {
+ return buildExpressionExtensions(cmParams, {
inputFields,
ancestorNodes,
siteSettings: this.siteSettings,
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/codemirror-extension.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/codemirror-extension.js
deleted file mode 100644
index da6f7a9723a..00000000000
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/codemirror-extension.js
+++ /dev/null
@@ -1,938 +0,0 @@
-import { ajax } from "discourse/lib/ajax";
-import { i18n } from "discourse-i18n";
-import {
- buildScope,
- lookupWorkflowMethodDoc,
- resolveVariableId,
- walkScope,
- WORKFLOW_VARIABLE_MIME,
-} from "./expression-context";
-
-// Extends core's generic analyzePropertyAccess with workflow-specific
-// patterns: $('Node Name') references and $-prefixed variables.
-function buildAnalyzeAtCursor({ cmLanguage, utils }) {
- const { syntaxTree } = cmLanguage;
- const { analyzePropertyAccess } = utils;
-
- return function analyzeAtCursor(state, pos) {
- const tree = syntaxTree(state);
- const node = tree.resolveInner(pos, -1);
- const doc = state.doc;
-
- // $(' or $(" — node reference
- const lb = doc.sliceString(Math.max(0, pos - 3), pos);
- if (lb === "$('" || lb === '$("') {
- return { kind: "nodeRef", from: pos, pos };
- }
-
- // $('NodeName') as a complete CallExpression
- let cur = node;
- while (cur) {
- if (cur.name === "CallExpression") {
- const callee = cur.firstChild;
- if (callee && doc.sliceString(callee.from, callee.to) === "$") {
- const argList = cur.getChild("ArgList");
- if (argList && pos > argList.from && pos <= argList.to) {
- return { kind: "nodeRef", from: argList.from + 1, pos };
- }
- }
- }
- cur = cur.parent;
- }
-
- const result = analyzePropertyAccess(state, pos);
-
- if (result.kind === "identifier" && result.partial?.startsWith("$")) {
- return { ...result, kind: "dollar" };
- }
-
- return result;
- };
-}
-
-const DOLLAR_VAR_DOCS = {
- $input: {
- detail: "object",
- infoKey: "discourse_workflows.expression_docs.vars.input",
- },
- $itemIndex: {
- detail: "number",
- infoKey: "discourse_workflows.expression_docs.vars.item_index",
- },
- $json: {
- detail: "object",
- infoKey: "discourse_workflows.expression_docs.vars.json",
- },
- trigger: {
- detail: "object",
- infoKey: "discourse_workflows.expression_docs.vars.trigger",
- },
- $site_settings: {
- detail: "object",
- infoKey: "discourse_workflows.expression_docs.vars.site_settings",
- },
- $current_user: {
- detail: "object",
- infoKey: "discourse_workflows.expression_docs.vars.current_user",
- },
- $vars: {
- detail: "object",
- infoKey: "discourse_workflows.expression_docs.vars.workflow_vars",
- },
- $execution: {
- detail: "object",
- infoKey: "discourse_workflows.expression_docs.vars.execution",
- },
-};
-
-function lookupDollarVarDoc(name) {
- const doc = DOLLAR_VAR_DOCS[name];
- if (!doc) {
- return null;
- }
- return { detail: doc.detail, info: i18n(doc.infoKey) };
-}
-
-function buildDollarVars(scope, sections) {
- const groups = [
- {
- names: ["$input", "$json", "$itemIndex", "trigger"],
- section: sections.recommended,
- boost: (name) => (name === "$json" ? 10 : 5),
- },
- {
- names: ["$site_settings", "$current_user", "$vars", "$execution"],
- section: sections.metadata,
- },
- ];
-
- const dollarVars = [];
- for (const group of groups) {
- for (const name of group.names) {
- if (name in scope) {
- const docs = lookupDollarVarDoc(name) || {};
- const isObject =
- typeof scope[name] === "object" && scope[name] !== null;
- const entry = {
- label: name,
- apply: isObject ? `${name}.` : name,
- type: "variable",
- detail: docs.detail || "object",
- info: docs.info,
- section: group.section,
- };
- if (group.boost) {
- entry.boost = group.boost(name);
- }
- dollarVars.push(entry);
- }
- }
- }
- dollarVars.push({
- label: "$(",
- apply: "$('",
- type: "function",
- detail: "node reference",
- info: i18n("discourse_workflows.expression_docs.vars.node_ref"),
- section: sections.nodes,
- });
- return dollarVars;
-}
-
-const EXPRESSION_TOKEN_NAMES = new Set([
- "VariableName",
- "PropertyName",
- "Number",
- "String",
- "BooleanLiteral",
- ")",
- "]",
- "}",
-]);
-
-function applyMethodCompletion(
- view,
- completion,
- from,
- to,
- { insertCompletionText, pickedCompletion }
-) {
- const afterCursor = view.state.doc.sliceString(to, to + 1);
-
- if (afterCursor === "(") {
- view.dispatch({
- ...insertCompletionText(view.state, completion.label, from, to),
- annotations: pickedCompletion.of(completion),
- });
- return;
- }
-
- const insert = `${completion.label}()`;
- const hasArgs = completion.detail && !completion.detail.startsWith("()");
- const anchor = from + completion.label.length + (hasArgs ? 1 : 2);
- view.dispatch({
- ...insertCompletionText(view.state, insert, from, to),
- selection: { anchor },
- annotations: pickedCompletion.of(completion),
- });
-}
-
-function withMethodApply(option, cmAutocomplete) {
- if (option.type === "method" || option.type === "function") {
- return {
- ...option,
- apply: (view, completion, from, to) =>
- applyMethodCompletion(view, completion, from, to, cmAutocomplete),
- };
- }
- return option;
-}
-
-function escapeQuotedString(value, quote) {
- return String(value).replace(/\\/g, "\\\\").replaceAll(quote, `\\${quote}`);
-}
-
-function buildCompletions(
- cmParams,
- { scope, ancestorNodes, analyzeAtCursor, sections }
-) {
- const { cmAutocomplete, cmLanguage, cmView, utils } = cmParams;
- const { autocompletion, completionKeymap } = cmAutocomplete;
- const { syntaxTree } = cmLanguage;
- const { keymap } = cmView;
- const {
- isInsideExpression,
- globalCompletions,
- globalStaticMethods,
- methodsForType,
- } = utils;
-
- const dollarVars = buildDollarVars(scope, sections);
- const globalOptions = globalCompletions.map((g) =>
- withMethodApply({ ...g, section: sections.globals }, cmAutocomplete)
- );
-
- const completer = (context) => {
- if (!isInsideExpression(context)) {
- return null;
- }
-
- const ctx = analyzeAtCursor(context.state, context.pos);
-
- switch (ctx.kind) {
- case "property": {
- const target = walkScope(scope, ctx.object);
- if (target == null) {
- return null;
- }
-
- const options = [];
-
- const statics = globalStaticMethods[ctx.object];
- if (statics) {
- for (const m of statics) {
- options.push(
- withMethodApply(
- { ...m, section: sections.methods },
- cmAutocomplete
- )
- );
- }
- }
-
- const methods = methodsForType(target);
- for (const m of methods) {
- options.push(
- withMethodApply({ ...m, section: sections.methods }, cmAutocomplete)
- );
- }
-
- if (typeof target === "object" && target !== null) {
- for (const name of Object.keys(target)) {
- const value = target[name];
- if (typeof value === "function") {
- const methodDoc = lookupWorkflowMethodDoc(ctx.object, name);
- options.push(
- withMethodApply(
- {
- label: name,
- type: "method",
- detail: methodDoc?.detail || "()",
- info: methodDoc?.info,
- section: sections.methods,
- },
- cmAutocomplete
- )
- );
- continue;
- }
- options.push({
- label: name,
- type:
- typeof value === "object" && value !== null
- ? "property"
- : "variable",
- detail: Array.isArray(value) ? "array" : typeof value,
- section: sections.properties,
- });
- }
- }
-
- if (!options.length) {
- return null;
- }
- return { from: ctx.from, options, filter: true, validFor: /^[\w$]*$/ };
- }
-
- case "nodeRef": {
- const charBefore = context.state.doc.sliceString(
- ctx.from - 1,
- ctx.from
- );
- const q = charBefore === '"' ? '"' : "'";
- const prefix = charBefore === "'" || charBefore === '"' ? "" : q;
- return {
- from: ctx.from,
- options: ancestorNodes.map((a) => ({
- label: a.node.name,
- apply: `${prefix}${escapeQuotedString(a.node.name, q)}${q})`,
- type: "variable",
- detail: a.node.type,
- section: sections.nodes,
- })),
- filter: true,
- };
- }
-
- case "bracket": {
- const target = walkScope(scope, ctx.object);
- if (!target || typeof target !== "object") {
- return null;
- }
- return {
- from: ctx.from,
- options: Object.keys(target)
- .filter((k) => typeof target[k] !== "function")
- .map((name) => ({
- label: name,
- apply: `'${name.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}']`,
- type: "property",
- section: sections.properties,
- })),
- filter: true,
- };
- }
-
- case "dollar":
- return { from: ctx.from, options: dollarVars, filter: true };
-
- case "identifier": {
- const charBefore = context.state.doc.sliceString(
- Math.max(0, ctx.from - 1),
- ctx.from
- );
- if (charBefore === ".") {
- return null;
- }
- return { from: ctx.from, options: globalOptions, filter: true };
- }
-
- case "blank": {
- if (!context.explicit) {
- return null;
- }
- const prevNode = syntaxTree(context.state).resolveInner(
- ctx.from - 1,
- -1
- );
- if (ctx.from > 0 && EXPRESSION_TOKEN_NAMES.has(prevNode.name)) {
- return null;
- }
- return {
- from: ctx.from,
- options: [...dollarVars, ...globalOptions],
- filter: true,
- };
- }
-
- default:
- return null;
- }
- };
-
- return [
- autocompletion({
- override: [completer],
- activateOnTyping: true,
- // Re-trigger completions after picking $( or any property that
- // ends with "." (e.g. "$json.") so the next level shows immediately.
- // String applies end with "."; function applies (methods) don't match.
- activateOnCompletion: (completion) =>
- completion.label === "$(" || completion.apply?.toString().endsWith("."),
- icons: true,
- }),
- keymap.of(completionKeymap),
- ];
-}
-
-function renderTooltipContent(doc) {
- if (!doc) {
- return null;
- }
-
- if (typeof doc.info === "function") {
- const richContent = doc.info(doc);
- if (richContent) {
- return richContent;
- }
- }
-
- const el = document.createElement("div");
- el.className = "cm-wf-hover-tooltip";
-
- const nameEl = document.createElement("div");
- nameEl.className = "cm-wf-hover-tooltip__name";
- nameEl.textContent = doc.label;
- el.appendChild(nameEl);
-
- if (typeof doc.info === "string") {
- const desc = document.createElement("div");
- desc.className = "cm-wf-hover-tooltip__description";
- desc.textContent = doc.info;
- el.appendChild(desc);
- }
-
- return el;
-}
-
-function makeTooltip(jsNode, content) {
- if (!content) {
- return null;
- }
- return {
- pos: jsNode.from,
- end: jsNode.to,
- above: true,
- create: () => ({ dom: content }),
- };
-}
-
-function buildHoverTooltip({ cmLanguage, cmView, utils }, { scope }) {
- const { syntaxTree } = cmLanguage;
- const { hoverTooltip } = cmView;
- const {
- isInsideExpressionAt,
- resolveNodeValue,
- lookupMethodDoc,
- globalDocs,
- } = utils;
-
- return hoverTooltip(
- (view, pos) => {
- const tree = syntaxTree(view.state);
- const doc = view.state.doc;
-
- if (!isInsideExpressionAt(view.state, pos)) {
- return null;
- }
-
- const jsNode = tree.resolveInner(pos, -1);
- const name = doc.sliceString(jsNode.from, jsNode.to);
-
- if (
- jsNode.name !== "VariableName" &&
- jsNode.name !== "VariableDefinition" &&
- jsNode.name !== "PropertyName"
- ) {
- return null;
- }
-
- if (jsNode.name === "PropertyName") {
- const memberExpr = jsNode.parent;
- if (memberExpr?.name === "MemberExpression") {
- const parentPath = resolveNodeValue(memberExpr.firstChild, doc);
- const parentValue = walkScope(scope, parentPath);
-
- const methodDoc =
- lookupWorkflowMethodDoc(parentPath, name) ||
- lookupMethodDoc(name, parentValue);
- if (methodDoc) {
- return makeTooltip(jsNode, renderTooltipContent(methodDoc));
- }
-
- const path = resolveNodeValue(memberExpr, doc);
- const value = walkScope(scope, path);
- if (value !== undefined) {
- const typeStr = Array.isArray(value) ? "array" : typeof value;
- const label =
- typeStr === "string" && value.length < 60
- ? `${name}: "${value}"`
- : `${name}: ${typeStr}`;
- return makeTooltip(jsNode, renderTooltipContent({ label }));
- }
- }
- }
-
- const varDoc = lookupDollarVarDoc(name);
- if (varDoc) {
- return makeTooltip(
- jsNode,
- renderTooltipContent({ ...varDoc, label: name })
- );
- }
-
- const globalDoc = globalDocs.get(name);
- if (globalDoc) {
- return makeTooltip(jsNode, renderTooltipContent(globalDoc));
- }
-
- return null;
- },
- { hoverTime: 400 }
- );
-}
-
-function buildArgumentInfo(
- { cmAutocomplete, cmLanguage, cmState, cmView, utils },
- { scope }
-) {
- const { completionStatus } = cmAutocomplete;
- const { syntaxTree } = cmLanguage;
- const { StateField } = cmState;
- const { showTooltip } = cmView;
- const { resolveNodeValue, lookupMethodDoc } = utils;
-
- function findCallContext(state, pos) {
- const tree = syntaxTree(state);
- const doc = state.doc;
- let node = tree.resolveInner(pos, -1);
-
- while (node) {
- if (node.name === "ArgList") {
- const call = node.parent;
- if (!call || call.name !== "CallExpression") {
- return null;
- }
-
- const callee = call.firstChild;
- if (!callee) {
- return null;
- }
-
- if (
- callee.name === "VariableName" &&
- doc.sliceString(callee.from, callee.to) === "$"
- ) {
- return null;
- }
-
- let methodName;
- let parentPath;
-
- if (callee.name === "MemberExpression") {
- const prop = callee.lastChild;
- if (prop?.name === "PropertyName") {
- methodName = doc.sliceString(prop.from, prop.to);
- parentPath = resolveNodeValue(callee.firstChild, doc);
- }
- } else if (callee.name === "VariableName") {
- methodName = doc.sliceString(callee.from, callee.to);
- }
-
- if (!methodName) {
- return null;
- }
-
- let argIndex = 0;
- for (let child = node.firstChild; child; child = child.nextSibling) {
- if (child.name === "," && child.to <= pos) {
- argIndex++;
- }
- }
-
- return { methodName, parentPath, argIndex, callFrom: call.from };
- }
- node = node.parent;
- }
- return null;
- }
-
- function buildTooltipForCall(ctx, pos) {
- const parentValue = ctx.parentPath
- ? walkScope(scope, ctx.parentPath)
- : null;
- const doc =
- lookupWorkflowMethodDoc(ctx.parentPath, ctx.methodName) ||
- lookupMethodDoc(ctx.methodName, parentValue);
- if (!doc?.info) {
- return null;
- }
-
- const content = typeof doc.info === "function" ? doc.info(doc) : null;
- if (!content) {
- return null;
- }
-
- return {
- pos,
- above: true,
- strictSide: true,
- create: () => ({ dom: content }),
- };
- }
-
- return StateField.define({
- create: () => ({ tooltip: null, callFrom: null }),
- update(prev, tr) {
- if (!tr.docChanged && !tr.selection) {
- return prev;
- }
-
- if (completionStatus(tr.state) === "active") {
- return { tooltip: null, callFrom: null };
- }
-
- const { head } = tr.state.selection.ranges[0];
- const ctx = findCallContext(tr.state, head);
- if (!ctx) {
- return { tooltip: null, callFrom: null };
- }
-
- if (prev.callFrom === ctx.callFrom) {
- return prev;
- }
-
- return {
- tooltip: buildTooltipForCall(ctx, head),
- callFrom: ctx.callFrom,
- };
- },
- provide: (f) => showTooltip.compute([f], (state) => state.field(f).tooltip),
- });
-}
-
-function buildDragDrop({ cmLanguage, cmView }, { itemPrefix }) {
- const { ensureSyntaxTree } = cmLanguage;
- const { dropCursor, EditorView } = cmView;
-
- return [
- dropCursor(),
- EditorView.domEventHandlers({
- dragover(event) {
- if (event.dataTransfer.types.includes(WORKFLOW_VARIABLE_MIME)) {
- event.preventDefault();
- event.dataTransfer.dropEffect = "copy";
- }
- },
- drop(event, view) {
- const data = event.dataTransfer.getData(WORKFLOW_VARIABLE_MIME);
- if (!data) {
- return false;
- }
-
- event.preventDefault();
-
- let variable;
- try {
- variable = JSON.parse(data);
- } catch {
- return false;
- }
-
- const variableId = resolveVariableId(variable, itemPrefix);
-
- let pos = view.posAtCoords({ x: event.clientX, y: event.clientY });
- if (pos === null) {
- pos = view.state.doc.length;
- }
-
- let inside = false;
- const tree = ensureSyntaxTree(view.state, view.state.doc.length, 100);
- if (tree) {
- for (const side of [-1, 1]) {
- let n = tree.resolve(pos, side);
- while (n) {
- if (n.name === "Expression") {
- inside = pos > n.from + 2 && pos < n.to - 2;
- break;
- }
- n = n.parent;
- }
- if (inside) {
- break;
- }
- }
- }
- const insert = inside ? variableId : `{{ ${variableId} }}`;
- view.dispatch({
- changes: { from: pos, insert },
- selection: { anchor: pos, head: pos + insert.length },
- });
- view.focus();
-
- return true;
- },
- }),
- ];
-}
-
-function buildValidation({ cmLanguage, cmView }) {
- const { syntaxTree } = cmLanguage;
- const { Decoration, ViewPlugin } = cmView;
-
- const errorMark = Decoration.mark({ class: "cm-wf-error" });
-
- return ViewPlugin.fromClass(
- class {
- decorations;
-
- constructor(view) {
- this.decorations = this.build(view.state);
- }
-
- update(update) {
- if (update.docChanged || update.startState.tree !== update.state.tree) {
- this.decorations = this.build(update.state);
- }
- }
-
- build(state) {
- const widgets = [];
- const tree = syntaxTree(state);
- const docLen = state.doc.length;
-
- tree.iterate({
- enter(node) {
- if (node.name === "Expression") {
- const text = state.doc.sliceString(node.from, node.to);
- if (!text.endsWith("}}")) {
- widgets.push(errorMark.range(node.from, docLen));
- }
- }
- },
- });
-
- return Decoration.set(widgets, true);
- }
- },
- { decorations: (v) => v.decorations }
- );
-}
-
-function buildAutoCloseBraces({ cmAutocomplete, cmView }) {
- const { startCompletion } = cmAutocomplete;
- const { EditorView } = cmView;
-
- return EditorView.inputHandler.of((view, from, to, text) => {
- if (text !== "{") {
- return false;
- }
-
- const before = view.state.doc.sliceString(Math.max(0, from - 1), from);
- if (before !== "{") {
- return false;
- }
-
- const after = view.state.doc.sliceString(to, to + 2);
- if (after === "}}") {
- // Already have closing braces — just insert the space and move cursor in
- view.dispatch({
- changes: { from, to, insert: "{ " },
- selection: { anchor: from + 2 },
- });
- } else {
- view.dispatch({
- changes: { from, to, insert: "{ }}" },
- selection: { anchor: from + 2 },
- });
- }
-
- startCompletion(view);
-
- return true;
- });
-}
-
-function buildExpressionDecorations({ cmState, cmView }) {
- const { StateEffect, StateField } = cmState;
- const { Decoration, EditorView } = cmView;
-
- const MARKS = {
- valid: Decoration.mark({ class: "cm-wf-valid-expression" }),
- invalid: Decoration.mark({ class: "cm-wf-invalid-expression" }),
- undefined: Decoration.mark({ class: "cm-wf-invalid-expression" }),
- empty: Decoration.mark({ class: "cm-wf-empty-expression" }),
- warning: Decoration.mark({ class: "cm-wf-warning-expression" }),
- pending: Decoration.mark({ class: "cm-wf-pending-expression" }),
- };
-
- const setSegmentsEffect = StateEffect.define();
-
- const field = StateField.define({
- create() {
- return Decoration.none;
- },
- update(decorations, tr) {
- decorations = decorations.map(tr.changes);
-
- for (const effect of tr.effects) {
- if (effect.is(setSegmentsEffect)) {
- const ranges = effect.value.filter(
- (seg) =>
- seg.kind === "resolved" &&
- seg.from !== undefined &&
- seg.to !== undefined
- );
- decorations = ranges.length
- ? Decoration.set(
- ranges.map(({ from, to, state }) =>
- (MARKS[state] || MARKS.invalid).range(from, to)
- ),
- true
- )
- : Decoration.none;
- }
- }
-
- return decorations;
- },
- provide: (f) => EditorView.decorations.from(f),
- });
-
- return { field, setSegmentsEffect };
-}
-
-function buildTheme({ cmLanguage, lezerHighlight }) {
- const { HighlightStyle, syntaxHighlighting } = cmLanguage;
- const { tags } = lezerHighlight;
-
- return syntaxHighlighting(
- HighlightStyle.define([
- { tag: tags.content, class: "cm-wf-text" },
- { tag: tags.brace, class: "cm-wf-brace" },
- { tag: tags.keyword, class: "cm-wf-keyword" },
- { tag: tags.string, class: "cm-wf-string" },
- { tag: tags.number, class: "cm-wf-number" },
- { tag: tags.bool, class: "cm-wf-bool" },
- { tag: tags.null, class: "cm-wf-null" },
- { tag: tags.variableName, class: "cm-wf-variable" },
- { tag: tags.propertyName, class: "cm-wf-property" },
- { tag: tags.function(tags.variableName), class: "cm-wf-function" },
- { tag: tags.function(tags.propertyName), class: "cm-wf-function" },
- { tag: tags.operator, class: "cm-wf-operator" },
- { tag: tags.punctuation, class: "cm-wf-punctuation" },
- { tag: tags.comment, class: "cm-wf-comment" },
- ])
- );
-}
-
-function buildExpressionValidator(
- { cmView },
- { setSegmentsEffect, workflowId, nodeId, onSegmentsResolved }
-) {
- const { ViewPlugin } = cmView;
-
- return ViewPlugin.fromClass(
- class {
- timeout = null;
- destroyed = false;
-
- constructor(view) {
- this.view = view;
- if (workflowId && nodeId && view.state.doc.toString()) {
- this.evaluate();
- }
- }
-
- update(update) {
- if (update.docChanged) {
- this.scheduleEvaluation();
- } else if (
- update.focusChanged &&
- update.view.hasFocus &&
- update.view.state.doc.toString()
- ) {
- this.evaluate();
- }
- }
-
- scheduleEvaluation() {
- clearTimeout(this.timeout);
- const template = this.view.state.doc.toString();
- if (!template) {
- this.timeout = setTimeout(() => this.dispatch([]), 0);
- return;
- }
- this.timeout = setTimeout(() => this.evaluate(), 500);
- }
-
- async evaluate() {
- const template = this.view.state.doc.toString();
- try {
- const result = await ajax(
- "/admin/plugins/discourse-workflows/expressions/evaluate.json",
- {
- type: "POST",
- data: { template, workflow_id: workflowId, node_id: nodeId },
- }
- );
-
- if (this.destroyed || template !== this.view.state.doc.toString()) {
- return;
- }
-
- this.dispatch(result.segments || []);
- } catch {
- if (this.destroyed) {
- return;
- }
- this.dispatch([]);
- }
- }
-
- dispatch(segments) {
- this.view.dispatch({
- effects: setSegmentsEffect.of(segments),
- });
- onSegmentsResolved?.(segments);
- }
-
- destroy() {
- clearTimeout(this.timeout);
- this.destroyed = true;
- }
- }
- );
-}
-
-export default function workflowExtension(cmParams, domainOpts = {}) {
- const itemPrefix = domainOpts.itemPrefix || "$json";
- const analyzeAtCursor = buildAnalyzeAtCursor(cmParams);
- const SECTION_NODES = cmParams.utils.section("Previous nodes", 1);
- const sections = { ...cmParams.utils.sections, nodes: SECTION_NODES };
-
- const scope = buildScope(domainOpts);
- const ancestorNodes = domainOpts.ancestorNodes || [];
- const completionOpts = { scope, ancestorNodes, analyzeAtCursor, sections };
-
- const { field: decorationsField, setSegmentsEffect } =
- buildExpressionDecorations(cmParams);
-
- return [
- cmParams.utils.expressionLanguage(),
- buildTheme(cmParams),
- buildValidation(cmParams),
- buildAutoCloseBraces(cmParams),
- ...buildDragDrop(cmParams, { itemPrefix }),
- ...buildCompletions(cmParams, completionOpts),
- buildHoverTooltip(cmParams, completionOpts),
- buildArgumentInfo(cmParams, completionOpts),
- decorationsField,
- buildExpressionValidator(cmParams, {
- setSegmentsEffect,
- workflowId: domainOpts.workflowId,
- nodeId: domainOpts.nodeId,
- onSegmentsResolved: domainOpts.onSegmentsResolved,
- }),
- ];
-}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/argument-info.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/argument-info.js
new file mode 100644
index 00000000000..928a1655600
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/argument-info.js
@@ -0,0 +1,120 @@
+import { lookupWorkflowMethodDoc, walkScope } from "../expression-context";
+
+export function buildArgumentInfo(
+ { cmAutocomplete, cmLanguage, cmState, cmView, utils },
+ { scope }
+) {
+ const { completionStatus } = cmAutocomplete;
+ const { syntaxTree } = cmLanguage;
+ const { StateField } = cmState;
+ const { showTooltip } = cmView;
+ const { resolveNodeValue, lookupMethodDoc } = utils;
+
+ function findCallContext(state, pos) {
+ const tree = syntaxTree(state);
+ const doc = state.doc;
+ let node = tree.resolveInner(pos, -1);
+
+ while (node) {
+ if (node.name === "ArgList") {
+ const call = node.parent;
+ if (!call || call.name !== "CallExpression") {
+ return null;
+ }
+
+ const callee = call.firstChild;
+ if (!callee) {
+ return null;
+ }
+
+ if (
+ callee.name === "VariableName" &&
+ doc.sliceString(callee.from, callee.to) === "$"
+ ) {
+ return null;
+ }
+
+ let methodName;
+ let parentPath;
+
+ if (callee.name === "MemberExpression") {
+ const prop = callee.lastChild;
+ if (prop?.name === "PropertyName") {
+ methodName = doc.sliceString(prop.from, prop.to);
+ parentPath = resolveNodeValue(callee.firstChild, doc);
+ }
+ } else if (callee.name === "VariableName") {
+ methodName = doc.sliceString(callee.from, callee.to);
+ }
+
+ if (!methodName) {
+ return null;
+ }
+
+ let argIndex = 0;
+ for (let child = node.firstChild; child; child = child.nextSibling) {
+ if (child.name === "," && child.to <= pos) {
+ argIndex++;
+ }
+ }
+
+ return { methodName, parentPath, argIndex, callFrom: call.from };
+ }
+ node = node.parent;
+ }
+ return null;
+ }
+
+ function buildTooltipForCall(ctx, pos) {
+ const parentValue = ctx.parentPath
+ ? walkScope(scope, ctx.parentPath)
+ : null;
+ const doc =
+ lookupWorkflowMethodDoc(ctx.parentPath, ctx.methodName) ||
+ lookupMethodDoc(ctx.methodName, parentValue);
+ if (!doc?.info) {
+ return null;
+ }
+
+ const content = typeof doc.info === "function" ? doc.info(doc) : null;
+ if (!content) {
+ return null;
+ }
+
+ return {
+ pos,
+ above: true,
+ strictSide: true,
+ create: () => ({ dom: content }),
+ };
+ }
+
+ return StateField.define({
+ create: () => ({ tooltip: null, callFrom: null }),
+ update(prev, tr) {
+ if (!tr.docChanged && !tr.selection) {
+ return prev;
+ }
+
+ if (completionStatus(tr.state) === "active") {
+ return { tooltip: null, callFrom: null };
+ }
+
+ const { head } = tr.state.selection.ranges[0];
+ const ctx = findCallContext(tr.state, head);
+ if (!ctx) {
+ return { tooltip: null, callFrom: null };
+ }
+
+ if (prev.callFrom === ctx.callFrom) {
+ return prev;
+ }
+
+ return {
+ tooltip: buildTooltipForCall(ctx, head),
+ callFrom: ctx.callFrom,
+ };
+ },
+ provide: (f) => showTooltip.compute([f], (state) => state.field(f).tooltip),
+ });
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/auto-close-braces.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/auto-close-braces.js
new file mode 100644
index 00000000000..78682b27298
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/auto-close-braces.js
@@ -0,0 +1,33 @@
+export function buildAutoCloseBraces({ cmAutocomplete, cmView }) {
+ const { startCompletion } = cmAutocomplete;
+ const { EditorView } = cmView;
+
+ return EditorView.inputHandler.of((view, from, to, text) => {
+ if (text !== "{") {
+ return false;
+ }
+
+ const before = view.state.doc.sliceString(Math.max(0, from - 1), from);
+ if (before !== "{") {
+ return false;
+ }
+
+ const after = view.state.doc.sliceString(to, to + 2);
+ if (after === "}}") {
+ // Already have closing braces — just insert the space and move cursor in
+ view.dispatch({
+ changes: { from, to, insert: "{ " },
+ selection: { anchor: from + 2 },
+ });
+ } else {
+ view.dispatch({
+ changes: { from, to, insert: "{ }}" },
+ selection: { anchor: from + 2 },
+ });
+ }
+
+ startCompletion(view);
+
+ return true;
+ });
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/completions.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/completions.js
new file mode 100644
index 00000000000..bddf0a1673f
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/completions.js
@@ -0,0 +1,278 @@
+import { lookupWorkflowMethodDoc, walkScope } from "../expression-context";
+import { buildDollarVars } from "./dollar-vars";
+
+// Extends core's generic analyzePropertyAccess with workflow-specific
+// patterns: $('Node Name') references and $-prefixed variables.
+function buildAnalyzeAtCursor({ cmLanguage, utils }) {
+ const { syntaxTree } = cmLanguage;
+ const { analyzePropertyAccess } = utils;
+
+ return function analyzeAtCursor(state, pos) {
+ const tree = syntaxTree(state);
+ const node = tree.resolveInner(pos, -1);
+ const doc = state.doc;
+
+ // $(' or $(" — node reference
+ const lb = doc.sliceString(Math.max(0, pos - 3), pos);
+ if (lb === "$('" || lb === '$("') {
+ return { kind: "nodeRef", from: pos, pos };
+ }
+
+ // $('NodeName') as a complete CallExpression
+ let cur = node;
+ while (cur) {
+ if (cur.name === "CallExpression") {
+ const callee = cur.firstChild;
+ if (callee && doc.sliceString(callee.from, callee.to) === "$") {
+ const argList = cur.getChild("ArgList");
+ if (argList && pos > argList.from && pos <= argList.to) {
+ return { kind: "nodeRef", from: argList.from + 1, pos };
+ }
+ }
+ }
+ cur = cur.parent;
+ }
+
+ const result = analyzePropertyAccess(state, pos);
+
+ if (result.kind === "identifier" && result.partial?.startsWith("$")) {
+ return { ...result, kind: "dollar" };
+ }
+
+ return result;
+ };
+}
+
+const EXPRESSION_TOKEN_NAMES = new Set([
+ "VariableName",
+ "PropertyName",
+ "Number",
+ "String",
+ "BooleanLiteral",
+ ")",
+ "]",
+ "}",
+]);
+
+function applyMethodCompletion(
+ view,
+ completion,
+ from,
+ to,
+ { insertCompletionText, pickedCompletion }
+) {
+ const afterCursor = view.state.doc.sliceString(to, to + 1);
+
+ if (afterCursor === "(") {
+ view.dispatch({
+ ...insertCompletionText(view.state, completion.label, from, to),
+ annotations: pickedCompletion.of(completion),
+ });
+ return;
+ }
+
+ const insert = `${completion.label}()`;
+ const hasArgs = completion.detail && !completion.detail.startsWith("()");
+ const anchor = from + completion.label.length + (hasArgs ? 1 : 2);
+ view.dispatch({
+ ...insertCompletionText(view.state, insert, from, to),
+ selection: { anchor },
+ annotations: pickedCompletion.of(completion),
+ });
+}
+
+function withMethodApply(option, cmAutocomplete) {
+ if (option.type === "method" || option.type === "function") {
+ return {
+ ...option,
+ apply: (view, completion, from, to) =>
+ applyMethodCompletion(view, completion, from, to, cmAutocomplete),
+ };
+ }
+ return option;
+}
+
+function escapeQuotedString(value, quote) {
+ return String(value).replace(/\\/g, "\\\\").replaceAll(quote, `\\${quote}`);
+}
+
+export function buildCompletions(cmParams, { scope, ancestorNodes, sections }) {
+ const { cmAutocomplete, cmLanguage, cmView, utils } = cmParams;
+ const { autocompletion, completionKeymap } = cmAutocomplete;
+ const { syntaxTree } = cmLanguage;
+ const { keymap } = cmView;
+ const {
+ isInsideExpression,
+ globalCompletions,
+ globalStaticMethods,
+ methodsForType,
+ } = utils;
+
+ const analyzeAtCursor = buildAnalyzeAtCursor(cmParams);
+ const dollarVars = buildDollarVars(scope, sections);
+ const globalOptions = globalCompletions.map((g) =>
+ withMethodApply({ ...g, section: sections.globals }, cmAutocomplete)
+ );
+
+ const completer = (context) => {
+ if (!isInsideExpression(context)) {
+ return null;
+ }
+
+ const ctx = analyzeAtCursor(context.state, context.pos);
+
+ switch (ctx.kind) {
+ case "property": {
+ const target = walkScope(scope, ctx.object);
+ if (target == null) {
+ return null;
+ }
+
+ const options = [];
+
+ const statics = globalStaticMethods[ctx.object];
+ if (statics) {
+ for (const m of statics) {
+ options.push(
+ withMethodApply(
+ { ...m, section: sections.methods },
+ cmAutocomplete
+ )
+ );
+ }
+ }
+
+ const methods = methodsForType(target);
+ for (const m of methods) {
+ options.push(
+ withMethodApply({ ...m, section: sections.methods }, cmAutocomplete)
+ );
+ }
+
+ if (typeof target === "object" && target !== null) {
+ for (const name of Object.keys(target)) {
+ const value = target[name];
+ if (typeof value === "function") {
+ const methodDoc = lookupWorkflowMethodDoc(ctx.object, name);
+ options.push(
+ withMethodApply(
+ {
+ label: name,
+ type: "method",
+ detail: methodDoc?.detail || "()",
+ info: methodDoc?.info,
+ section: sections.methods,
+ },
+ cmAutocomplete
+ )
+ );
+ continue;
+ }
+ options.push({
+ label: name,
+ type:
+ typeof value === "object" && value !== null
+ ? "property"
+ : "variable",
+ detail: Array.isArray(value) ? "array" : typeof value,
+ section: sections.properties,
+ });
+ }
+ }
+
+ if (!options.length) {
+ return null;
+ }
+ return { from: ctx.from, options, filter: true, validFor: /^[\w$]*$/ };
+ }
+
+ case "nodeRef": {
+ const charBefore = context.state.doc.sliceString(
+ ctx.from - 1,
+ ctx.from
+ );
+ const q = charBefore === '"' ? '"' : "'";
+ const prefix = charBefore === "'" || charBefore === '"' ? "" : q;
+ return {
+ from: ctx.from,
+ options: ancestorNodes.map((a) => ({
+ label: a.node.name,
+ apply: `${prefix}${escapeQuotedString(a.node.name, q)}${q})`,
+ type: "variable",
+ detail: a.node.type,
+ section: sections.nodes,
+ })),
+ filter: true,
+ };
+ }
+
+ case "bracket": {
+ const target = walkScope(scope, ctx.object);
+ if (!target || typeof target !== "object") {
+ return null;
+ }
+ return {
+ from: ctx.from,
+ options: Object.keys(target)
+ .filter((k) => typeof target[k] !== "function")
+ .map((name) => ({
+ label: name,
+ apply: `'${name.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}']`,
+ type: "property",
+ section: sections.properties,
+ })),
+ filter: true,
+ };
+ }
+
+ case "dollar":
+ return { from: ctx.from, options: dollarVars, filter: true };
+
+ case "identifier": {
+ const charBefore = context.state.doc.sliceString(
+ Math.max(0, ctx.from - 1),
+ ctx.from
+ );
+ if (charBefore === ".") {
+ return null;
+ }
+ return { from: ctx.from, options: globalOptions, filter: true };
+ }
+
+ case "blank": {
+ if (!context.explicit) {
+ return null;
+ }
+ const prevNode = syntaxTree(context.state).resolveInner(
+ ctx.from - 1,
+ -1
+ );
+ if (ctx.from > 0 && EXPRESSION_TOKEN_NAMES.has(prevNode.name)) {
+ return null;
+ }
+ return {
+ from: ctx.from,
+ options: [...dollarVars, ...globalOptions],
+ filter: true,
+ };
+ }
+
+ default:
+ return null;
+ }
+ };
+
+ return [
+ autocompletion({
+ override: [completer],
+ activateOnTyping: true,
+ // Re-trigger completions after picking $( or any property that
+ // ends with "." (e.g. "$json.") so the next level shows immediately.
+ // String applies end with "."; function applies (methods) don't match.
+ activateOnCompletion: (completion) =>
+ completion.label === "$(" || completion.apply?.toString().endsWith("."),
+ icons: true,
+ }),
+ keymap.of(completionKeymap),
+ ];
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/dollar-vars.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/dollar-vars.js
new file mode 100644
index 00000000000..f2b87470efb
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/dollar-vars.js
@@ -0,0 +1,90 @@
+import { i18n } from "discourse-i18n";
+
+const DOLLAR_VAR_DOCS = {
+ $input: {
+ detail: "object",
+ infoKey: "discourse_workflows.expression_docs.vars.input",
+ },
+ $itemIndex: {
+ detail: "number",
+ infoKey: "discourse_workflows.expression_docs.vars.item_index",
+ },
+ $json: {
+ detail: "object",
+ infoKey: "discourse_workflows.expression_docs.vars.json",
+ },
+ trigger: {
+ detail: "object",
+ infoKey: "discourse_workflows.expression_docs.vars.trigger",
+ },
+ $site_settings: {
+ detail: "object",
+ infoKey: "discourse_workflows.expression_docs.vars.site_settings",
+ },
+ $current_user: {
+ detail: "object",
+ infoKey: "discourse_workflows.expression_docs.vars.current_user",
+ },
+ $vars: {
+ detail: "object",
+ infoKey: "discourse_workflows.expression_docs.vars.workflow_vars",
+ },
+ $execution: {
+ detail: "object",
+ infoKey: "discourse_workflows.expression_docs.vars.execution",
+ },
+};
+
+export function lookupDollarVarDoc(name) {
+ const doc = DOLLAR_VAR_DOCS[name];
+ if (!doc) {
+ return null;
+ }
+ return { detail: doc.detail, info: i18n(doc.infoKey) };
+}
+
+export function buildDollarVars(scope, sections) {
+ const groups = [
+ {
+ names: ["$input", "$json", "$itemIndex", "trigger"],
+ section: sections.recommended,
+ boost: (name) => (name === "$json" ? 10 : 5),
+ },
+ {
+ names: ["$site_settings", "$current_user", "$vars", "$execution"],
+ section: sections.metadata,
+ },
+ ];
+
+ const dollarVars = [];
+ for (const group of groups) {
+ for (const name of group.names) {
+ if (name in scope) {
+ const docs = lookupDollarVarDoc(name) || {};
+ const isObject =
+ typeof scope[name] === "object" && scope[name] !== null;
+ const entry = {
+ label: name,
+ apply: isObject ? `${name}.` : name,
+ type: "variable",
+ detail: docs.detail || "object",
+ info: docs.info,
+ section: group.section,
+ };
+ if (group.boost) {
+ entry.boost = group.boost(name);
+ }
+ dollarVars.push(entry);
+ }
+ }
+ }
+ dollarVars.push({
+ label: "$(",
+ apply: "$('",
+ type: "function",
+ detail: "node reference",
+ info: i18n("discourse_workflows.expression_docs.vars.node_ref"),
+ section: sections.nodes,
+ });
+ return dollarVars;
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/drag-drop.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/drag-drop.js
new file mode 100644
index 00000000000..ae496eb2104
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/drag-drop.js
@@ -0,0 +1,69 @@
+import {
+ resolveVariableId,
+ WORKFLOW_VARIABLE_MIME,
+} from "../expression-context";
+
+export function buildDragDrop({ cmLanguage, cmView }, { itemPrefix }) {
+ const { ensureSyntaxTree } = cmLanguage;
+ const { dropCursor, EditorView } = cmView;
+
+ return [
+ dropCursor(),
+ EditorView.domEventHandlers({
+ dragover(event) {
+ if (event.dataTransfer.types.includes(WORKFLOW_VARIABLE_MIME)) {
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "copy";
+ }
+ },
+ drop(event, view) {
+ const data = event.dataTransfer.getData(WORKFLOW_VARIABLE_MIME);
+ if (!data) {
+ return false;
+ }
+
+ event.preventDefault();
+
+ let variable;
+ try {
+ variable = JSON.parse(data);
+ } catch {
+ return false;
+ }
+
+ const variableId = resolveVariableId(variable, itemPrefix);
+
+ let pos = view.posAtCoords({ x: event.clientX, y: event.clientY });
+ if (pos === null) {
+ pos = view.state.doc.length;
+ }
+
+ let inside = false;
+ const tree = ensureSyntaxTree(view.state, view.state.doc.length, 100);
+ if (tree) {
+ for (const side of [-1, 1]) {
+ let n = tree.resolve(pos, side);
+ while (n) {
+ if (n.name === "Expression") {
+ inside = pos > n.from + 2 && pos < n.to - 2;
+ break;
+ }
+ n = n.parent;
+ }
+ if (inside) {
+ break;
+ }
+ }
+ }
+ const insert = inside ? variableId : `{{ ${variableId} }}`;
+ view.dispatch({
+ changes: { from: pos, insert },
+ selection: { anchor: pos, head: pos + insert.length },
+ });
+ view.focus();
+
+ return true;
+ },
+ }),
+ ];
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/expression-evaluation.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/expression-evaluation.js
new file mode 100644
index 00000000000..381db4d3aac
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/expression-evaluation.js
@@ -0,0 +1,158 @@
+import { ajax } from "discourse/lib/ajax";
+
+// Debounce for the server-side expression preview request. Matches the
+// editor autosave debounce so typing produces at most one request per pause.
+const EXPRESSION_EVALUATE_DEBOUNCE_MS = 750;
+
+export function buildExpressionEvaluation(
+ { cmState, cmView },
+ { workflowId, nodeId, onSegmentsResolved }
+) {
+ const { StateEffect, StateField } = cmState;
+ const { Decoration, EditorView, ViewPlugin } = cmView;
+
+ const MARKS = {
+ valid: Decoration.mark({ class: "cm-wf-valid-expression" }),
+ invalid: Decoration.mark({ class: "cm-wf-invalid-expression" }),
+ undefined: Decoration.mark({ class: "cm-wf-invalid-expression" }),
+ empty: Decoration.mark({ class: "cm-wf-empty-expression" }),
+ warning: Decoration.mark({ class: "cm-wf-warning-expression" }),
+ pending: Decoration.mark({ class: "cm-wf-pending-expression" }),
+ };
+
+ const setSegmentsEffect = StateEffect.define();
+
+ const field = StateField.define({
+ create() {
+ return Decoration.none;
+ },
+ update(decorations, tr) {
+ decorations = decorations.map(tr.changes);
+
+ for (const effect of tr.effects) {
+ if (effect.is(setSegmentsEffect)) {
+ const ranges = effect.value.filter(
+ (seg) =>
+ seg.kind === "resolved" &&
+ seg.from !== undefined &&
+ seg.to !== undefined
+ );
+ decorations = ranges.length
+ ? Decoration.set(
+ ranges.map(({ from, to, state }) =>
+ (MARKS[state] || MARKS.invalid).range(from, to)
+ ),
+ true
+ )
+ : Decoration.none;
+ }
+ }
+
+ return decorations;
+ },
+ provide: (f) => EditorView.decorations.from(f),
+ });
+
+ const viewPlugin = ViewPlugin.fromClass(
+ class {
+ timeout = null;
+ destroyed = false;
+ lastEvaluatedTemplate = null;
+
+ constructor(view) {
+ this.view = view;
+ if (workflowId && nodeId && view.state.doc.toString()) {
+ this.evaluate();
+ }
+ }
+
+ update(update) {
+ if (update.docChanged) {
+ this.scheduleEvaluation();
+ } else if (
+ update.focusChanged &&
+ update.view.hasFocus &&
+ update.view.state.doc.toString()
+ ) {
+ // Focusing a field doesn't change its content, so the dedupe guard
+ // in evaluate() collapses this to a no-op unless it's never been
+ // resolved (e.g. first focus on a freshly-loaded field).
+ this.evaluate();
+ }
+ }
+
+ scheduleEvaluation() {
+ clearTimeout(this.timeout);
+ const template = this.view.state.doc.toString();
+ if (!template) {
+ // Record the empty template so retyping the same value as before
+ // (after clearing) is treated as a change and re-evaluated.
+ this.lastEvaluatedTemplate = "";
+ this.timeout = setTimeout(() => {
+ if (this.destroyed) {
+ return;
+ }
+ this.dispatch([]);
+ }, 0);
+ return;
+ }
+ this.timeout = setTimeout(
+ () => this.evaluate(),
+ EXPRESSION_EVALUATE_DEBOUNCE_MS
+ );
+ }
+
+ async evaluate() {
+ const template = this.view.state.doc.toString();
+
+ // Reuse the previous result when the template is unchanged instead of
+ // re-requesting (e.g. on refocus or a debounce that fired with no net
+ // edit). Keeps a steadily-typed field within the endpoint's limit.
+ if (template === this.lastEvaluatedTemplate) {
+ return;
+ }
+ this.lastEvaluatedTemplate = template;
+
+ try {
+ const result = await ajax(
+ "/admin/plugins/discourse-workflows/expressions/evaluate.json",
+ {
+ type: "POST",
+ data: { template, workflow_id: workflowId, node_id: nodeId },
+ }
+ );
+
+ if (this.destroyed || template !== this.view.state.doc.toString()) {
+ return;
+ }
+
+ this.dispatch(result.segments || []);
+ } catch {
+ // Ignore failures for templates the editor has already moved past; a
+ // newer in-flight request owns the current content.
+ if (this.destroyed || template !== this.view.state.doc.toString()) {
+ return;
+ }
+ // Allow a retry of the current template after a failure (e.g. a
+ // transient 429/network error) rather than caching the failure.
+ this.lastEvaluatedTemplate = null;
+ this.dispatch([]);
+ }
+ }
+
+ dispatch(segments) {
+ this.view.dispatch({
+ effects: setSegmentsEffect.of(segments),
+ });
+ onSegmentsResolved?.(segments);
+ }
+
+ destroy() {
+ clearTimeout(this.timeout);
+ this.destroyed = true;
+ }
+ }
+ );
+
+ return [field, viewPlugin];
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/hover-tooltip.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/hover-tooltip.js
new file mode 100644
index 00000000000..53d15d7f717
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/hover-tooltip.js
@@ -0,0 +1,119 @@
+import { lookupWorkflowMethodDoc, walkScope } from "../expression-context";
+import { lookupDollarVarDoc } from "./dollar-vars";
+
+function renderTooltipContent(doc) {
+ if (!doc) {
+ return null;
+ }
+
+ if (typeof doc.info === "function") {
+ const richContent = doc.info(doc);
+ if (richContent) {
+ return richContent;
+ }
+ }
+
+ const el = document.createElement("div");
+ el.className = "cm-wf-hover-tooltip";
+
+ const nameEl = document.createElement("div");
+ nameEl.className = "cm-wf-hover-tooltip__name";
+ nameEl.textContent = doc.label;
+ el.appendChild(nameEl);
+
+ if (typeof doc.info === "string") {
+ const desc = document.createElement("div");
+ desc.className = "cm-wf-hover-tooltip__description";
+ desc.textContent = doc.info;
+ el.appendChild(desc);
+ }
+
+ return el;
+}
+
+function makeTooltip(jsNode, content) {
+ if (!content) {
+ return null;
+ }
+ return {
+ pos: jsNode.from,
+ end: jsNode.to,
+ above: true,
+ create: () => ({ dom: content }),
+ };
+}
+
+export function buildHoverTooltip({ cmLanguage, cmView, utils }, { scope }) {
+ const { syntaxTree } = cmLanguage;
+ const { hoverTooltip } = cmView;
+ const {
+ isInsideExpressionAt,
+ resolveNodeValue,
+ lookupMethodDoc,
+ globalDocs,
+ } = utils;
+
+ return hoverTooltip(
+ (view, pos) => {
+ const tree = syntaxTree(view.state);
+ const doc = view.state.doc;
+
+ if (!isInsideExpressionAt(view.state, pos)) {
+ return null;
+ }
+
+ const jsNode = tree.resolveInner(pos, -1);
+ const name = doc.sliceString(jsNode.from, jsNode.to);
+
+ if (
+ jsNode.name !== "VariableName" &&
+ jsNode.name !== "VariableDefinition" &&
+ jsNode.name !== "PropertyName"
+ ) {
+ return null;
+ }
+
+ if (jsNode.name === "PropertyName") {
+ const memberExpr = jsNode.parent;
+ if (memberExpr?.name === "MemberExpression") {
+ const parentPath = resolveNodeValue(memberExpr.firstChild, doc);
+ const parentValue = walkScope(scope, parentPath);
+
+ const methodDoc =
+ lookupWorkflowMethodDoc(parentPath, name) ||
+ lookupMethodDoc(name, parentValue);
+ if (methodDoc) {
+ return makeTooltip(jsNode, renderTooltipContent(methodDoc));
+ }
+
+ const path = resolveNodeValue(memberExpr, doc);
+ const value = walkScope(scope, path);
+ if (value !== undefined) {
+ const typeStr = Array.isArray(value) ? "array" : typeof value;
+ const label =
+ typeStr === "string" && value.length < 60
+ ? `${name}: "${value}"`
+ : `${name}: ${typeStr}`;
+ return makeTooltip(jsNode, renderTooltipContent({ label }));
+ }
+ }
+ }
+
+ const varDoc = lookupDollarVarDoc(name);
+ if (varDoc) {
+ return makeTooltip(
+ jsNode,
+ renderTooltipContent({ ...varDoc, label: name })
+ );
+ }
+
+ const globalDoc = globalDocs.get(name);
+ if (globalDoc) {
+ return makeTooltip(jsNode, renderTooltipContent(globalDoc));
+ }
+
+ return null;
+ },
+ { hoverTime: 400 }
+ );
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/index.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/index.js
new file mode 100644
index 00000000000..ab8b563f3aa
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/index.js
@@ -0,0 +1,35 @@
+import { buildScope } from "../expression-context";
+import { buildArgumentInfo } from "./argument-info";
+import { buildAutoCloseBraces } from "./auto-close-braces";
+import { buildCompletions } from "./completions";
+import { buildDragDrop } from "./drag-drop";
+import { buildExpressionEvaluation } from "./expression-evaluation";
+import { buildHoverTooltip } from "./hover-tooltip";
+import { buildTheme } from "./theme";
+import { buildValidation } from "./validation";
+
+export default function buildExpressionExtensions(cmParams, domainOpts = {}) {
+ const itemPrefix = domainOpts.itemPrefix || "$json";
+ const SECTION_NODES = cmParams.utils.section("Previous nodes", 1);
+ const sections = { ...cmParams.utils.sections, nodes: SECTION_NODES };
+
+ const scope = buildScope(domainOpts);
+ const ancestorNodes = domainOpts.ancestorNodes || [];
+ const completionOpts = { scope, ancestorNodes, sections };
+
+ return [
+ cmParams.utils.expressionLanguage(),
+ buildTheme(cmParams),
+ buildValidation(cmParams),
+ buildAutoCloseBraces(cmParams),
+ buildDragDrop(cmParams, { itemPrefix }),
+ buildCompletions(cmParams, completionOpts),
+ buildHoverTooltip(cmParams, completionOpts),
+ buildArgumentInfo(cmParams, completionOpts),
+ buildExpressionEvaluation(cmParams, {
+ workflowId: domainOpts.workflowId,
+ nodeId: domainOpts.nodeId,
+ onSegmentsResolved: domainOpts.onSegmentsResolved,
+ }),
+ ];
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/theme.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/theme.js
new file mode 100644
index 00000000000..5ef4cb26ee8
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/theme.js
@@ -0,0 +1,23 @@
+export function buildTheme({ cmLanguage, lezerHighlight }) {
+ const { HighlightStyle, syntaxHighlighting } = cmLanguage;
+ const { tags } = lezerHighlight;
+
+ return syntaxHighlighting(
+ HighlightStyle.define([
+ { tag: tags.content, class: "cm-wf-text" },
+ { tag: tags.brace, class: "cm-wf-brace" },
+ { tag: tags.keyword, class: "cm-wf-keyword" },
+ { tag: tags.string, class: "cm-wf-string" },
+ { tag: tags.number, class: "cm-wf-number" },
+ { tag: tags.bool, class: "cm-wf-bool" },
+ { tag: tags.null, class: "cm-wf-null" },
+ { tag: tags.variableName, class: "cm-wf-variable" },
+ { tag: tags.propertyName, class: "cm-wf-property" },
+ { tag: tags.function(tags.variableName), class: "cm-wf-function" },
+ { tag: tags.function(tags.propertyName), class: "cm-wf-function" },
+ { tag: tags.operator, class: "cm-wf-operator" },
+ { tag: tags.punctuation, class: "cm-wf-punctuation" },
+ { tag: tags.comment, class: "cm-wf-comment" },
+ ])
+ );
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/validation.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/validation.js
new file mode 100644
index 00000000000..052e4c3de67
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/validation.js
@@ -0,0 +1,42 @@
+export function buildValidation({ cmLanguage, cmView }) {
+ const { syntaxTree } = cmLanguage;
+ const { Decoration, ViewPlugin } = cmView;
+
+ const errorMark = Decoration.mark({ class: "cm-wf-error" });
+
+ return ViewPlugin.fromClass(
+ class {
+ decorations;
+
+ constructor(view) {
+ this.decorations = this.build(view.state);
+ }
+
+ update(update) {
+ if (update.docChanged || update.startState.tree !== update.state.tree) {
+ this.decorations = this.build(update.state);
+ }
+ }
+
+ build(state) {
+ const widgets = [];
+ const tree = syntaxTree(state);
+ const docLen = state.doc.length;
+
+ tree.iterate({
+ enter(node) {
+ if (node.name === "Expression") {
+ const text = state.doc.sliceString(node.from, node.to);
+ if (!text.endsWith("}}")) {
+ widgets.push(errorMark.range(node.from, docLen));
+ }
+ }
+ },
+ });
+
+ return Decoration.set(widgets, true);
+ }
+ },
+ { decorations: (v) => v.decorations }
+ );
+}