Skip to content

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

FEATURE: Show workflow expression references as editable pills (#41442)

Renato Atilio209fb1ac6098
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 66deb697a2e..8e54d5449dd 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
@@ -10,28 +10,36 @@ import {
inputConnectionsForNode,
inputIndexForConnection,
inputSummaryForNode,
- nodeOutputJsonPath,
+ nodeOutputFirstJsonPath,
+ nodeOutputLinkedItemJsonPath,
outputIndexForConnection,
previousNodeForConnection,
+ schemaFieldsForItems,
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";
+import ReferencePropertyPicker from "../variable/reference-property-picker";
+
+const REFERENCE_PICKER_IDENTIFIER = "workflows-reference-picker";
export default class ExpressionInput extends Component {
@service siteSettings;
@service workflowsNodeTypes;
+ @service menu;
@tracked isFocused = false;
@tracked segments = [];
wrapperElement = null;
#focusOutTimer = null;
+ #pickerDismiss = null;
+ #pickerEditorElement = null;
willDestroy() {
super.willDestroy(...arguments);
cancel(this.#focusOutTimer);
+ this.#closeReferencePicker();
}
get displayValue() {
@@ -89,18 +97,23 @@ export default class ExpressionInput extends Component {
prefix: itemPrefix,
});
}
+ // Pinned sample data, falling back to the last run.
const ancestorNodes = node
- ? ancestorOutputNodes(node, graph).map((ancestor) => ({
- node: ancestor.node,
- fields: schemaFieldsForNodeOutput(runData, ancestor.node.name, {
- outputIndex: ancestor.outputIndex,
+ ? ancestorOutputNodes(node, graph).map((ancestor) => {
+ const items =
+ session?.outputItemsForNode(ancestor.node, ancestor.outputIndex) ||
+ [];
+ const prefix =
+ items.length === 1
+ ? nodeOutputFirstJsonPath(ancestor.node.name, {
+ outputIndex: ancestor.outputIndex,
+ })
+ : nodeOutputLinkedItemJsonPath(ancestor.node.name);
+ return {
node: ancestor.node,
- prefix: nodeOutputJsonPath(runData, ancestor.node.name, {
- outputIndex: ancestor.outputIndex,
- node: ancestor.node,
- }),
- }),
- }))
+ fields: schemaFieldsForItems(items, { prefix }),
+ };
+ })
: [];
return buildExpressionExtensions(cmParams, {
@@ -113,9 +126,68 @@ export default class ExpressionInput extends Component {
workflowId: session?.workflowId,
nodeId: node?.id,
onSegmentsResolved: (segs) => (this.segments = segs),
+ onOpenReferencePicker: this.openReferencePicker,
+ });
+ }
+
+ @action
+ openReferencePicker({ trigger, properties, current, onSelect, onEdit }) {
+ this.menu.show(trigger, {
+ identifier: REFERENCE_PICKER_IDENTIFIER,
+ component: ReferencePropertyPicker,
+ placement: "bottom-start",
+ data: {
+ properties,
+ current,
+ onSelect: onSelect
+ ? (name) => {
+ this.#closeReferencePicker();
+ onSelect(name);
+ }
+ : null,
+ onEdit: onEdit
+ ? () => {
+ this.#closeReferencePicker();
+ onEdit();
+ }
+ : null,
+ },
+ });
+ this.#armPickerDismiss();
+ }
+
+ // CodeMirror swallows pointerdowns before float-kit's outside-click detector
+ // sees them, so dismiss on a capture listener instead.
+ #armPickerDismiss() {
+ this.#teardownPickerDismiss();
+ const editor = this.wrapperElement?.querySelector(".cm-editor");
+ if (!editor) {
+ return;
+ }
+ this.#pickerEditorElement = editor;
+ this.#pickerDismiss = () => this.#closeReferencePicker();
+ editor.addEventListener("pointerdown", this.#pickerDismiss, {
+ capture: true,
});
}
+ #teardownPickerDismiss() {
+ if (this.#pickerEditorElement && this.#pickerDismiss) {
+ this.#pickerEditorElement.removeEventListener(
+ "pointerdown",
+ this.#pickerDismiss,
+ { capture: true }
+ );
+ }
+ this.#pickerEditorElement = null;
+ this.#pickerDismiss = null;
+ }
+
+ #closeReferencePicker() {
+ this.menu.close(REFERENCE_PICKER_IDENTIFIER);
+ this.#teardownPickerDismiss();
+ }
+
@action
handleChange(value) {
this.args.field.set(`=${value}`);
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable/reference-property-picker.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable/reference-property-picker.gjs
new file mode 100644
index 00000000000..14509b5b2e0
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable/reference-property-picker.gjs
@@ -0,0 +1,184 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { eq } from "discourse/truth-helpers";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+export default class ReferencePropertyPicker extends Component {
+ @tracked query = "";
+ @tracked activeIndex = 0;
+ listElement;
+
+ constructor() {
+ super(...arguments);
+ const current = this.args.data?.current;
+ const properties = this.args.data?.properties || [];
+ const index = current
+ ? properties.findIndex((property) => property.name === current)
+ : -1;
+ this.activeIndex = index >= 0 ? index : 0;
+ }
+
+ get current() {
+ return this.args.data?.current;
+ }
+
+ get hasProperties() {
+ return (this.args.data?.properties || []).length > 0;
+ }
+
+ get filteredProperties() {
+ const query = this.query.trim().toLowerCase();
+ const properties = this.args.data?.properties || [];
+ if (!query) {
+ return properties;
+ }
+ return properties.filter((property) =>
+ property.name.toLowerCase().includes(query)
+ );
+ }
+
+ @action
+ focusFilter(element) {
+ // Next frame, so focus wins over the editor reclaiming it.
+ requestAnimationFrame(() => {
+ if (!this.isDestroying && !this.isDestroyed) {
+ element.focus();
+ }
+ });
+ }
+
+ @action
+ registerList(element) {
+ this.listElement = element;
+ this.scrollActiveIntoView();
+ }
+
+ @action
+ updateQuery(event) {
+ this.query = event.target.value;
+ this.activeIndex = 0;
+ }
+
+ @action
+ setActive(index) {
+ this.activeIndex = index;
+ }
+
+ @action
+ onKeydown(event) {
+ const lastIndex = this.filteredProperties.length - 1;
+ if (lastIndex < 0) {
+ return;
+ }
+
+ if (event.key === "ArrowDown") {
+ event.preventDefault();
+ this.activeIndex =
+ this.activeIndex >= lastIndex ? 0 : this.activeIndex + 1;
+ this.scrollActiveIntoView();
+ } else if (event.key === "ArrowUp") {
+ event.preventDefault();
+ this.activeIndex =
+ this.activeIndex <= 0 ? lastIndex : this.activeIndex - 1;
+ this.scrollActiveIntoView();
+ } else if (event.key === "Enter") {
+ event.preventDefault();
+ const property = this.filteredProperties[this.activeIndex];
+ if (property) {
+ this.select(property.name);
+ }
+ }
+ }
+
+ scrollActiveIntoView() {
+ this.listElement
+ ?.querySelector(".workflows-reference-picker__option.--active")
+ ?.scrollIntoView({ block: "nearest" });
+ }
+
+ @action
+ select(name) {
+ this.args.data?.onSelect?.(name);
+ }
+
+ @action
+ edit() {
+ this.args.data?.onEdit?.();
+ }
+
+ <template>
+ <div class="workflows-reference-picker">
+ <div class="workflows-reference-picker__header">
+ {{#if this.hasProperties}}
+ <input
+ type="text"
+ class="workflows-reference-picker__filter"
+ placeholder={{i18n
+ "discourse_workflows.reference_pill.filter_placeholder"
+ }}
+ aria-label={{i18n
+ "discourse_workflows.reference_pill.filter_placeholder"
+ }}
+ {{didInsert this.focusFilter}}
+ {{on "input" this.updateQuery}}
+ {{on "keydown" this.onKeydown}}
+ />
+ {{else}}
+ <span class="workflows-reference-picker__unavailable">
+ {{i18n "discourse_workflows.reference_pill.no_properties"}}
+ </span>
+ {{/if}}
+
+ <button
+ type="button"
+ class="workflows-reference-picker__edit"
+ {{on "click" this.edit}}
+ >
+ {{dIcon "code"}}
+ <span>{{i18n
+ "discourse_workflows.reference_pill.edit_as_code"
+ }}</span>
+ </button>
+ </div>
+
+ {{#if this.hasProperties}}
+ <ul
+ class="workflows-reference-picker__list"
+ {{didInsert this.registerList}}
+ >
+ {{#each this.filteredProperties as |property index|}}
+ <li>
+ <button
+ type="button"
+ class={{dConcatClass
+ "workflows-reference-picker__option"
+ (if (eq index this.activeIndex) "--active")
+ (if (eq property.name this.current) "--current")
+ }}
+ {{on "click" (fn this.select property.name)}}
+ {{on "mouseenter" (fn this.setActive index)}}
+ >
+ <span class="workflows-reference-picker__name">
+ {{property.name}}
+ </span>
+ <span class="workflows-reference-picker__type">
+ {{property.type}}
+ </span>
+ </button>
+ </li>
+ {{else}}
+ <li class="workflows-reference-picker__empty">
+ {{i18n "discourse_workflows.reference_pill.no_matches"}}
+ </li>
+ {{/each}}
+ </ul>
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-context.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-context.js
index 973bd91f2a5..c45f95b45dd 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-context.js
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-context.js
@@ -29,6 +29,8 @@ export function resolveVariableId(variable, itemPrefix = "$json") {
const NODE_REF_RE = /^\$\((?:"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)')\)/;
const METHOD_CALL_RE = /^([A-Za-z_$][\w$]*)\((.*)\)$/;
const METHOD_WITH_SUFFIX_RE = /^([A-Za-z_$][\w$]*)\((.*?)\)(.*)$/;
+// A property followed by one or more subscripts, e.g. `items[0]` or `map["k"]`.
+const PROP_WITH_SUFFIX_RE = /^([A-Za-z_$][\w$]*)(\[.+)$/;
const BRACKET_SUFFIX_RE =
/^\[((?:"(?:\\.|[^"\\])*")|(?:'(?:\\.|[^'\\])*')|[^\]]+)\](.*)$/;
@@ -58,7 +60,10 @@ export function walkScope(scope, path) {
}
const parts = path.split(".");
- let target = scope[parts[0]];
+ const rootSuffix = PROP_WITH_SUFFIX_RE.exec(parts[0]);
+ let target = rootSuffix
+ ? resolveBracketSuffix(scope[rootSuffix[1]], rootSuffix[2], scope)
+ : scope[parts[0]];
for (let i = 1; i < parts.length; i++) {
if (target == null) {
return undefined;
@@ -98,6 +103,15 @@ function resolvePathPart(target, part, scope) {
return target[methodCall[1]](...parseMethodArgs(methodCall[2]));
}
+ const propWithSuffix = PROP_WITH_SUFFIX_RE.exec(part);
+ if (propWithSuffix) {
+ return resolveBracketSuffix(
+ target[propWithSuffix[1]],
+ propWithSuffix[2],
+ scope
+ );
+ }
+
return target[part];
}
@@ -326,16 +340,21 @@ export function buildScope({
const $input = buildInputScope($json);
const nodeOutputs = Object.create(null);
+ let triggerJson = null;
for (const ancestor of ancestorNodes) {
const json = buildScopeFromFields(ancestor.fields);
nodeOutputs[ancestor.node.name] = buildNodeOutput(json);
+ if (!triggerJson && ancestor.node.type?.startsWith("trigger:")) {
+ triggerJson = json;
+ }
}
return cleanObject({
$input,
$itemIndex: 0,
$json,
- trigger: $json,
+ // $trigger is the trigger node's output, distinct from $json.
+ $trigger: triggerJson || Object.create(null),
$site_settings: buildSiteSettingsScope(siteSettings),
$current_user: cleanObject({ id: 0, username: "" }),
$vars: buildVarsScope(workflowVars),
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
index f2b87470efb..babbc6ccfa5 100644
--- 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
@@ -13,7 +13,7 @@ const DOLLAR_VAR_DOCS = {
detail: "object",
infoKey: "discourse_workflows.expression_docs.vars.json",
},
- trigger: {
+ $trigger: {
detail: "object",
infoKey: "discourse_workflows.expression_docs.vars.trigger",
},
@@ -46,7 +46,7 @@ export function lookupDollarVarDoc(name) {
export function buildDollarVars(scope, sections) {
const groups = [
{
- names: ["$input", "$json", "$itemIndex", "trigger"],
+ names: ["$input", "$json", "$itemIndex", "$trigger"],
section: sections.recommended,
boost: (name) => (name === "$json" ? 10 : 5),
},
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
index ae496eb2104..a0089766d90 100644
--- 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
@@ -2,68 +2,183 @@ import {
resolveVariableId,
WORKFLOW_VARIABLE_MIME,
} from "../expression-context";
+import { dragSource } from "./drag-source";
+import {
+ listReferenceProperties,
+ propertyAccessor,
+} from "./reference-properties";
-export function buildDragDrop({ cmLanguage, cmView }, { itemPrefix }) {
+export function buildDragDrop(
+ { cmLanguage, cmView },
+ { itemPrefix, scope, onOpenReferencePicker }
+) {
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";
- }
+ const { dropCursor, ViewPlugin } = cmView;
+
+ // An object container isn't a usable value, so open the picker on the pill.
+ function dropWithPicker(view, pos, variableId) {
+ const insert = `{{ ${variableId} }}`;
+ view.dispatch({
+ changes: { from: pos, insert },
+ selection: { anchor: pos, head: pos + insert.length },
+ });
+ view.focus();
+
+ const properties = listReferenceProperties(scope, variableId);
+ if (!properties.length) {
+ return;
+ }
+ const pill = view.dom.querySelector(".cm-wf-reference-pill.--selected");
+ if (!pill) {
+ return;
+ }
+ // Capture the range now; the caret may move while the menu is open.
+ const range = { from: pos, to: pos + insert.length };
+ onOpenReferencePicker({
+ trigger: pill,
+ properties,
+ onSelect: (name) => {
+ const replacement = `{{ ${variableId}${propertyAccessor(name)} }}`;
+ view.dispatch({
+ changes: { from: range.from, to: range.to, insert: replacement },
+ selection: {
+ anchor: range.from,
+ head: range.from + replacement.length,
+ },
+ });
+ view.focus();
},
- drop(event, view) {
- const data = event.dataTransfer.getData(WORKFLOW_VARIABLE_MIME);
- if (!data) {
- return false;
- }
+ onEdit: () => {
+ view.dispatch({
+ selection: { anchor: range.from + 2, head: range.to - 2 },
+ });
+ view.focus();
+ },
+ });
+ }
- event.preventDefault();
+ function handleDragOver(event) {
+ if (event.dataTransfer.types.includes(WORKFLOW_VARIABLE_MIME)) {
+ event.preventDefault();
+ // Dragging an existing pill moves it; dragging from the panel copies.
+ event.dataTransfer.dropEffect = dragSource.current ? "move" : "copy";
+ }
+ }
- let variable;
- try {
- variable = JSON.parse(data);
- } catch {
- return false;
- }
+ function handleDrop(view, event) {
+ const data = event.dataTransfer.getData(WORKFLOW_VARIABLE_MIME);
+ if (!data) {
+ return;
+ }
- const variableId = resolveVariableId(variable, itemPrefix);
+ // Handle it ourselves (capture phase) before CodeMirror's own drop logic.
+ event.preventDefault();
+ event.stopPropagation();
- let pos = view.posAtCoords({ x: event.clientX, y: event.clientY });
- if (pos === null) {
- pos = view.state.doc.length;
- }
+ let variable;
+ try {
+ variable = JSON.parse(data);
+ } catch {
+ return;
+ }
+
+ const variableId = resolveVariableId(variable, itemPrefix);
- 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;
- }
+ let pos = view.posAtCoords({ x: event.clientX, y: event.clientY });
+ if (pos === null) {
+ // Dropped in the empty area below the text — append to the end.
+ 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;
}
- const insert = inside ? variableId : `{{ ${variableId} }}`;
- view.dispatch({
- changes: { from: pos, insert },
- selection: { anchor: pos, head: pos + insert.length },
+ if (inside) {
+ break;
+ }
+ }
+ }
+ const insert = inside ? variableId : `{{ ${variableId} }}`;
+
+ const source = dragSource.current;
+ dragSource.current = null;
+
+ if (source && source.view === view) {
+ if (pos >= source.from && pos <= source.to) {
+ return;
+ }
+ // Same field: one transaction over the pre-change document.
+ const delLen = source.to - source.from;
+ const insertedAt = pos > source.to ? pos - delLen : pos;
+ view.dispatch({
+ changes: [
+ { from: pos, insert },
+ { from: source.from, to: source.to },
+ ],
+ selection: { anchor: insertedAt, head: insertedAt + insert.length },
+ });
+ view.focus();
+ return;
+ }
+
+ if (source) {
+ // The original lives in a different editor, so remove it there.
+ view.dispatch({
+ changes: { from: pos, insert },
+ selection: { anchor: pos, head: pos + insert.length },
+ });
+ source.view.dispatch({
+ changes: { from: source.from, to: source.to },
+ });
+ view.focus();
+ return;
+ }
+
+ if (variable.type === "object" && !inside && onOpenReferencePicker) {
+ dropWithPicker(view, pos, variableId);
+ return;
+ }
+
+ view.dispatch({
+ changes: { from: pos, insert },
+ selection: { anchor: pos, head: pos + insert.length },
+ });
+ view.focus();
+ }
+
+ // On the editor element, not contentDOM, so drops below the last line land;
+ // capture runs before CodeMirror's own handler.
+ const dropListeners = ViewPlugin.fromClass(
+ class {
+ constructor(view) {
+ this.view = view;
+ this.onDragOver = handleDragOver;
+ this.onDrop = (event) => handleDrop(view, event);
+ view.dom.addEventListener("dragover", this.onDragOver, {
+ capture: true,
});
- view.focus();
+ view.dom.addEventListener("drop", this.onDrop, { capture: true });
+ }
- return true;
- },
- }),
- ];
+ destroy() {
+ this.view.dom.removeEventListener("dragover", this.onDragOver, {
+ capture: true,
+ });
+ this.view.dom.removeEventListener("drop", this.onDrop, {
+ capture: true,
+ });
+ }
+ }
+ );
+
+ return [dropCursor(), dropListeners];
}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/drag-source.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/drag-source.js
new file mode 100644
index 00000000000..fb36495c807
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/drag-source.js
@@ -0,0 +1,3 @@
+// The pill being dragged ({ view, from, to }), or null when dragging from the
+// panel. Lets the drop handler move rather than copy.
+export const dragSource = { current: null };
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/focus-empty-area.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/focus-empty-area.js
new file mode 100644
index 00000000000..44e1074b920
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/focus-empty-area.js
@@ -0,0 +1,31 @@
+// Clicks below the last line hit the scroller, which CodeMirror's pointer
+// handling ignores (it's wired to the content element). Listen here instead.
+export function buildFocusEmptyArea({ cmView }) {
+ const { ViewPlugin } = cmView;
+
+ return ViewPlugin.fromClass(
+ class {
+ constructor(view) {
+ this.view = view;
+ this.onMouseDown = (event) => {
+ // Scrollbar clicks also target the scroller, but outside its client box.
+ if (
+ event.target !== view.scrollDOM ||
+ event.offsetX > view.scrollDOM.clientWidth ||
+ event.offsetY > view.scrollDOM.clientHeight
+ ) {
+ return;
+ }
+ event.preventDefault();
+ view.focus();
+ view.dispatch({ selection: { anchor: view.state.doc.length } });
+ };
+ view.scrollDOM.addEventListener("mousedown", this.onMouseDown);
+ }
+
+ destroy() {
+ this.view.scrollDOM.removeEventListener("mousedown", this.onMouseDown);
+ }
+ }
+ );
+}
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
index 8aadcff6934..c90b415be07 100644
--- 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
@@ -5,7 +5,9 @@ import { buildAutoCloseBraces } from "./auto-close-braces";
import { buildCompletions } from "./completions";
import { buildDragDrop } from "./drag-drop";
import { buildExpressionEvaluation } from "./expression-evaluation";
+import { buildFocusEmptyArea } from "./focus-empty-area";
import { buildHoverTooltip } from "./hover-tooltip";
+import { buildReferencePills } from "./reference-pills";
import { buildTheme } from "./theme";
import { buildValidation } from "./validation";
@@ -20,13 +22,16 @@ export default function buildExpressionExtensions(cmParams, domainOpts = {}) {
const scope = buildScope(domainOpts);
const ancestorNodes = domainOpts.ancestorNodes || [];
const completionOpts = { scope, ancestorNodes, sections };
+ const onOpenReferencePicker = domainOpts.onOpenReferencePicker;
return [
cmParams.utils.expressionLanguage(),
buildTheme(cmParams),
buildValidation(cmParams),
buildAutoCloseBraces(cmParams),
- buildDragDrop(cmParams, { itemPrefix }),
+ buildDragDrop(cmParams, { itemPrefix, scope, onOpenReferencePicker }),
+ buildReferencePills(cmParams, { scope, onOpenReferencePicker }),
+ buildFocusEmptyArea(cmParams),
buildCompletions(cmParams, completionOpts),
buildHoverTooltip(cmParams, completionOpts),
buildArgumentInfo(cmParams, completionOpts),
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/reference-label.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/reference-label.js
new file mode 100644
index 00000000000..81cb9732345
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/reference-label.js
@@ -0,0 +1,146 @@
+import { i18n } from "discourse-i18n";
+
+// Parses a "simple reference" into source + path. Anything more involved
+// (operators, arithmetic, multiple refs, method calls) returns null.
+
+// Matches a leading $('Node Name') / $("Node Name") node reference.
+const NODE_REF_RE = /^\$\((?:"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)')\)/;
+
+// An item selector after a node/$input ref: .first(), .item, .itemMatching('x')…
+const SELECTOR_RE =
+ /^(?:\.(?:first|last|all|itemMatching|pairedItem)\([^()]*\)|\.item)/;
+
+// A plain property path: dotted identifiers and numeric/string subscripts.
+const PATH_TOKEN =
+ "[A-Za-z_$][\\w$]*|\\[\\d+\\]|\\['(?:[^'\\\\]|\\\\.)*'\\]|\\[\"(?:[^\"\\\\]|\\\\.)*\"\\]";
+const PLAIN_PATH_RE = new RegExp(
+ `^(?:${PATH_TOKEN})(?:\\.[A-Za-z_$][\\w$]*|\\[\\d+\\]|\\['(?:[^'\\\\]|\\\\.)*'\\]|\\["(?:[^"\\\\]|\\\\.)*"\\])*$`
+);
+
+const ROOT_SOURCES = {
+ $json: "input",
+ $trigger: "trigger",
+ $itemIndex: "item_index",
+ $vars: "variable",
+ $current_user: "current_user",
+ $site_settings: "site_setting",
+ $execution: "execution",
+};
+
+const SOURCE_ICONS = {
+ node: "diagram-project",
+ input: "right-to-bracket",
+ trigger: "play",
+ item_index: "hashtag",
+ variable: "dollar-sign",
+ current_user: "user",
+ site_setting: "gear",
+ execution: "bolt",
+};
+
+function parseNodeReferenceName(match) {
+ const doubleQuoted = match[1] !== undefined;
+ const raw = doubleQuoted ? match[1] : match[2];
+
+ if (doubleQuoted) {
+ try {
+ return JSON.parse(`"${raw}"`);
+ } catch {
+ return raw;
+ }
+ }
+
+ return raw.replace(/\\([\\'])/g, "$1");
+}
+
+function stripLeadingDot(text) {
+ return text.startsWith(".") ? text.slice(1) : text;
+}
+
+function isPlainPath(path) {
+ return path === "" || PLAIN_PATH_RE.test(path);
+}
+
+function firstSeparator(text) {
+ for (let i = 0; i < text.length; i++) {
+ if (text[i] === "." || text[i] === "[") {
+ return i;
+ }
+ }
+ return -1;
+}
+
+// Pulls the path out of a `[selector].json[.path]` tail, or null if not plain.
+function parseJsonTail(rest) {
+ const selector = SELECTOR_RE.exec(rest);
+ if (selector) {
+ rest = rest.slice(selector[0].length);
+ }
+
+ if (!rest.startsWith(".json")) {
+ return null;
+ }
+ rest = rest.slice(".json".length);
+
+ const path = stripLeadingDot(rest);
+ return isPlainPath(path) ? path : null;
+}
+
+export function parseReference(expression) {
+ const text = (expression || "").trim();
+ if (!text) {
+ return null;
+ }
+
+ const nodeRef = NODE_REF_RE.exec(text);
+ if (nodeRef) {
+ const name = parseNodeReferenceName(nodeRef);
+ const path = parseJsonTail(text.slice(nodeRef[0].length));
+ if (!name || path === null) {
+ return null;
+ }
+ return { source: { type: "node", name }, path };
+ }
+
+ const separator = firstSeparator(text);
+ const root = separator === -1 ? text : text.slice(0, separator);
+ const remainder = separator === -1 ? "" : text.slice(separator);
+
+ if (root === "$input") {
+ const path = parseJsonTail(remainder);
+ if (path === null) {
+ return null;
+ }
+ return { source: { type: "input" }, path };
+ }
+
+ const type = ROOT_SOURCES[root];
+ if (!type) {
+ return null;
+ }
+
+ const path = stripLeadingDot(remainder);
+ if (!isPlainPath(path)) {
+ return null;
+ }
+ return { source: { type }, path };
+}
+
+export function referenceLabel(parsed) {
+ if (!parsed) {
+ return null;
+ }
+
+ const { source, path } = parsed;
+ const badge =
+ source.type === "node"
+ ? source.name
+ : i18n(`discourse_workflows.reference_pill.source.${source.type}`);
+
+ return {
+ sourceType: source.type,
+ icon: SOURCE_ICONS[source.type],
+ badge,
+ path,
+ };
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/reference-pills.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/reference-pills.js
new file mode 100644
index 00000000000..f06ecb5a571
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/reference-pills.js
@@ -0,0 +1,446 @@
+import { iconHTML } from "discourse/lib/icon-library";
+import { i18n } from "discourse-i18n";
+import { walkScope, WORKFLOW_VARIABLE_MIME } from "../expression-context";
+import { dragSource } from "./drag-source";
+import { parseReference, referenceLabel } from "./reference-label";
+import { propertyAccessor, referencePickerData } from "./reference-properties";
+
+// "value" means it resolves against authoring data, not a runtime guarantee.
+function referenceState(scope, inner) {
+ const resolved = walkScope(scope, inner);
+ if (resolved === undefined) {
+ return "invalid";
+ }
+ if (
+ resolved !== null &&
+ typeof resolved === "object" &&
+ !Array.isArray(resolved)
+ ) {
+ return "incomplete";
+ }
+ return "value";
+}
+
+// Display layer only: the document still holds the real expression.
+export function buildReferencePills(
+ { cmView, cmLanguage, cmState },
+ { scope, onOpenReferencePicker } = {}
+) {
+ const { Decoration, EditorView, ViewPlugin, WidgetType, keymap } = cmView;
+ const { syntaxTree } = cmLanguage;
+ const { Prec } = cmState;
+
+ function openDropdown(view, range, anchor) {
+ if (!onOpenReferencePicker || !anchor) {
+ return false;
+ }
+ const inner = view.state.doc
+ .sliceString(range.from + 2, range.to - 2)
+ .trim();
+ const data = referencePickerData(scope, inner);
+ onOpenReferencePicker({
+ trigger: anchor,
+ properties: data?.properties || [],
+ current: data?.current ?? null,
+ onSelect: data
+ ? (name) => applyPickedProperty(view, range, data.baseExpr, name)
+ : null,
+ onEdit: () => enterEditMode(view, range),
+ });
+ return true;
+ }
+
+ function selectedPillAnchor(view) {
+ const pill = view.dom.querySelector(".cm-wf-reference-pill.--selected");
+ return pill?.querySelector(".cm-wf-reference-pill__drill") || pill;
+ }
+
+ function applyPickedProperty(view, range, baseExpr, name) {
+ const inner = `${baseExpr}${propertyAccessor(name)}`;
+ const replacement = `{{ ${inner} }}`;
+ view.dispatch({
+ changes: { from: range.from, to: range.to, insert: replacement },
+ selection: { anchor: range.from, head: range.from + replacement.length },
+ });
+ view.focus();
+
+ if (referenceState(scope, inner) === "incomplete") {
+ const newRange = {
+ from: range.from,
+ to: range.from + replacement.length,
+ };
+ // Next frame, so the just-closed menu settles before reopening.
+ requestAnimationFrame(() =>
+ openDropdown(view, newRange, selectedPillAnchor(view))
+ );
+ }
+ }
+
+ function expressionRangeAt(view, pos) {
+ const tree = syntaxTree(view.state);
+ for (const side of [1, -1]) {
+ let node = tree.resolve(pos, side);
+ while (node) {
+ if (node.name === "Expression") {
+ return { from: node.from, to: node.to };
+ }
+ node = node.parent;
+ }
+ }
+ return null;
+ }
+
+ function pillRangeAt(view, pos, dir) {
+ const tree = syntaxTree(view.state);
+ let node = tree.resolve(pos, dir);
+ while (node && node.name !== "Expression") {
+ node = node.parent;
+ }
+ if (!node || (dir === 1 ? node.from !== pos : node.to !== pos)) {
+ return null;
+ }
+ const doc = view.state.doc;
+ if (doc.lineAt(node.from).number !== doc.lineAt(node.to).number) {
+ return null;
+ }
+ const inner = doc.sliceString(node.from + 2, node.to - 2).trim();
+ if (!referenceLabel(parseReference(inner))) {
+ return null;
+ }
+ return { from: node.from, to: node.to };
+ }
+
+ function rangeIsSelected(selection, range) {
+ return selection.from === range.from && selection.to === range.to;
+ }
+
+ function editingPillRange(view) {
+ const selection = view.state.selection.main;
+ const range = expressionRangeAt(view, selection.head);
+ if (
+ !range ||
+ rangeIsSelected(selection, range) ||
+ selection.from < range.from ||
+ selection.to > range.to
+ ) {
+ return null;
+ }
+ const inner = view.state.doc
+ .sliceString(range.from + 2, range.to - 2)
+ .trim();
+ return referenceLabel(parseReference(inner)) ? range : null;
+ }
+
+ function enterEditMode(view, range) {
+ view.dispatch({
+ selection: { anchor: range.from + 2, head: range.to - 2 },
+ });
+ view.focus();
+ }
+
+ class ReferencePillWidget extends WidgetType {
+ constructor(label, raw, inner, selected, state) {
+ super();
+ this.label = label;
+ this.raw = raw;
+ this.inner = inner;
+ this.selected = selected;
+ this.state = state;
+ }
+
+ eq(other) {
+ return (
+ other.raw === this.raw &&
+ other.selected === this.selected &&
+ other.state === this.state
+ );
+ }
+
+ toDOM(view) {
+ const pill = document.createElement("span");
+ pill.className = `cm-wf-reference-pill --source-${this.label.sourceType} --${this.state}${
+ this.selected ? " --selected" : ""
+ }`;
+ pill.title = this.raw;
+
+ // "click" not "mousedown", so preventDefault doesn't cancel a drag.
+ pill.addEventListener("click", (event) => {
+ event.preventDefault();
+ const range = expressionRangeAt(view, view.posAtDOM(pill));
+ if (range) {
+ view.dispatch({
+ selection: { anchor: range.from, head: range.to },
+ });
+ view.focus();
+ }
+ });
+
+ pill.addEventListener("dblclick", (event) => {
+ event.preventDefault();
+ const range = expressionRangeAt(view, view.posAtDOM(pill));
+ if (range) {
+ enterEditMode(view, range);
+ }
+ });
+
+ // Record the source range so the drop handler moves rather than copies.
+ pill.draggable = true;
+ pill.addEventListener("dragstart", (event) => {
+ event.stopPropagation();
+ event.dataTransfer.setData(
+ WORKFLOW_VARIABLE_MIME,
+ JSON.stringify({ id: this.inner })
+ );
+ event.dataTransfer.effectAllowed = "copyMove";
+ const range = expressionRangeAt(view, view.posAtDOM(pill));
+ dragSource.current = range
+ ? { view, from: range.from, to: range.to }
+ : null;
+ document.documentElement.dataset.draggingVariable = "true";
+ });
+ pill.addEventListener("dragend", () => {
+ dragSource.current = null;
+ delete document.documentElement.dataset.draggingVariable;
+ });
+
+ if (this.label.icon) {
+ const icon = document.createElement("span");
+ icon.className = "cm-wf-reference-pill__icon";
+ icon.innerHTML = iconHTML(this.label.icon);
+ pill.appendChild(icon);
+ }
+
+ const badge = document.createElement("span");
+ badge.className = "cm-wf-reference-pill__badge";
+ badge.textContent = this.label.badge;
+ pill.appendChild(badge);
+
+ if (this.label.path) {
+ const path = document.createElement("span");
+ path.className = "cm-wf-reference-pill__path";
+ path.textContent = this.label.path;
+ pill.appendChild(path);
+ }
+
+ if (onOpenReferencePicker) {
+ const drill = document.createElement("button");
+ drill.type = "button";
+ drill.className = "cm-wf-reference-pill__drill";
+ drill.title = i18n("discourse_workflows.reference_pill.pick_property");
+ drill.innerHTML = iconHTML("angle-down");
+ drill.addEventListener("mousedown", (event) => {
+ // mousedown, not click: the editor's selection handling would
+ // otherwise collapse the menu first.
+ event.preventDefault();
+ event.stopPropagation();
+ const range = expressionRangeAt(view, view.posAtDOM(pill));
+ if (range) {
+ openDropdown(view, range, drill);
+ }
+ });
+ drill.addEventListener("click", (event) => event.stopPropagation());
+ pill.appendChild(drill);
+ }
+
+ return pill;
+ }
+ }
+
+ function buildDecorations(view) {
+ const ranges = [];
+ const selection = view.state.selection.main;
+ const tree = syntaxTree(view.state);
+
+ for (const { from, to } of view.visibleRanges) {
+ tree.iterate({
+ from,
+ to,
+ enter(node) {
+ if (node.name !== "Expression") {
+ return undefined;
+ }
+
+ const range = { from: node.from, to: node.to };
+ const selected = rangeIsSelected(selection, range);
+
+ // Caret inside the braces means the user is editing — show raw text.
+ if (
+ !selected &&
+ selection.from < node.to &&
+ selection.to > node.from
+ ) {
+ return false;
+ }
+
+ // A replacing decoration can't span a line break.
+ if (
+ view.state.doc.lineAt(node.from).number !==
+ view.state.doc.lineAt(node.to).number
+ ) {
+ return false;
+ }
+
+ const inner = view.state.doc
+ .sliceString(node.from + 2, node.to - 2)
+ .trim();
+ const label = referenceLabel(parseReference(inner));
+ if (!label) {
+ return false;
+ }
+
+ const raw = view.state.doc.sliceString(node.from, node.to);
+ const state = referenceState(scope, inner);
+ ranges.push(
+ Decoration.replace({
+ widget: new ReferencePillWidget(
+ label,
+ raw,
+ inner,
+ selected,
+ state
+ ),
+ }).range(node.from, node.to)
+ );
+ return false;
+ },
+ });
+ }
+
+ return Decoration.set(ranges, true);
+ }
+
+ const pillPlugin = ViewPlugin.fromClass(
+ class {
+ constructor(view) {
+ this.view = view;
+ this.decorations = buildDecorations(view);
+
+ // DModal and CodeMirror grab Escape on capture and stop propagation,
+ // so cancelling pill-edit mode has to happen on capture too.
+ this.handleEscape = (event) => {
+ if (
+ event.key !== "Escape" ||
+ !view.contentDOM.contains(event.target)
+ ) {
+ return;
+ }
+ const range = editingPillRange(view);
+ if (!range) {
+ return;
+ }
+ event.stopPropagation();
+ event.preventDefault();
+ view.dispatch({ selection: { anchor: range.from, head: range.to } });
+ view.focus();
+ };
+ window.addEventListener("keydown", this.handleEscape, {
+ capture: true,
+ });
+ }
+
+ update(update) {
+ if (
+ update.docChanged ||
+ update.viewportChanged ||
+ update.selectionSet
+ ) {
+ this.decorations = buildDecorations(update.view);
+ }
+ }
+
+ destroy() {
+ window.removeEventListener("keydown", this.handleEscape, {
+ capture: true,
+ });
+ }
+ },
+ {
+ decorations: (plugin) => plugin.decorations,
+ provide: (plugin) =>
+ EditorView.atomicRanges.of(
+ (view) => view.plugin(plugin)?.decorations || Decoration.none
+ ),
+ }
+ );
+
+ // Beat the default Enter/arrow bindings when a pill is involved.
+ const pillKeymap = Prec.high(
+ keymap.of([
+ {
+ key: "Enter",
+ run(view) {
+ const selection = view.state.selection.main;
+ if (selection.empty) {
+ return false;
+ }
+ const range = expressionRangeAt(view, selection.from);
+ if (range && rangeIsSelected(selection, range)) {
+ return openDropdown(view, range, selectedPillAnchor(view));
+ }
+ return false;
+ },
+ },
+ {
+ // Select the adjacent pill; a second press moves past it.
+ key: "ArrowRight",
+ run(view) {
+ const selection = view.state.selection.main;
+ if (selection.empty) {
+ const range = pillRangeAt(view, selection.head, 1);
+ if (range) {
+ view.dispatch({
+ selection: { anchor: range.from, head: range.to },
+ });
+ return true;
+ }
+ return false;
+ }
+ const range = pillRangeAt(view, selection.from, 1);
+ if (range && rangeIsSelected(selection, range)) {
+ view.dispatch({ selection: { anchor: range.to } });
+ return true;
+ }
+ return false;
+ },
+ },
+ {
+ key: "ArrowLeft",
+ run(view) {
+ const selection = view.state.selection.main;
+ if (selection.empty) {
+ const range = pillRangeAt(view, selection.head, -1);
+ if (range) {
+ view.dispatch({
+ selection: { anchor: range.from, head: range.to },
+ });
+ return true;
+ }
+ return false;
+ }
+ const range = pillRangeAt(view, selection.from, 1);
+ if (range && rangeIsSelected(selection, range)) {
+ view.dispatch({ selection: { anchor: range.from } });
+ return true;
+ }
+ return false;
+ },
+ },
+ ])
+ );
+
+ // Input handler, not keymap: "." arrives through the input path, not keydown.
+ const pillInputHandler = EditorView.inputHandler.of(
+ (view, from, to, text) => {
+ if (text !== ".") {
+ return false;
+ }
+ const range = expressionRangeAt(view, from);
+ if (!range || from !== range.from || to !== range.to) {
+ return false;
+ }
+ return openDropdown(view, range, selectedPillAnchor(view));
+ }
+ );
+
+ return [pillPlugin, pillKeymap, pillInputHandler];
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/reference-properties.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/reference-properties.js
new file mode 100644
index 00000000000..065822ecba1
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/reference-properties.js
@@ -0,0 +1,111 @@
+import { walkScope } from "../expression-context";
+
+const PLAIN_IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
+
+// Non-identifier names get bracket access so the expression stays valid.
+export function propertyAccessor(name) {
+ if (PLAIN_IDENTIFIER.test(name)) {
+ return `.${name}`;
+ }
+ const escaped = String(name).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
+ return `["${escaped}"]`;
+}
+
+export function listReferenceProperties(scope, path) {
+ const target = walkScope(scope, path);
+ if (!target || typeof target !== "object") {
+ return [];
+ }
+
+ const properties = [];
+ for (const name of Object.keys(target)) {
+ const value = target[name];
+ if (typeof value === "function") {
+ continue;
+ }
+ properties.push({
+ name,
+ type: Array.isArray(value) ? "array" : typeof value,
+ });
+ }
+ return properties;
+}
+
+// Splits at the last top-level accessor, ignoring dots inside strings/subscripts.
+function splitLastAccessor(expression) {
+ let depth = 0;
+ let quote = null;
+ let index = -1;
+ let isBracket = false;
+
+ for (let i = 0; i < expression.length; i++) {
+ const ch = expression[i];
+ if (quote) {
+ if (ch === "\\") {
+ i++;
+ } else if (ch === quote) {
+ quote = null;
+ }
+ continue;
+ }
+ if (ch === '"' || ch === "'") {
+ quote = ch;
+ } else if (ch === "(" || ch === "[") {
+ if (ch === "[" && depth === 0) {
+ index = i;
+ isBracket = true;
+ }
+ depth++;
+ } else if (ch === ")" || ch === "]") {
+ depth--;
+ } else if (ch === "." && depth === 0) {
+ index = i;
+ isBracket = false;
+ }
+ }
+
+ if (index <= 0) {
+ return null;
+ }
+
+ const parent = expression.slice(0, index);
+ if (!isBracket) {
+ return { parent, current: expression.slice(index + 1) };
+ }
+
+ // Unquote a bracket key so `current` matches the raw property name.
+ let key = expression.slice(index + 1, -1).trim();
+ const q = key[0];
+ if (q === '"' || q === "'") {
+ key = key.slice(1, -1).replace(/\\(.)/g, "$1");
+ }
+ return { parent, current: key };
+}
+
+// Object → drill (append the pick); leaf → switch siblings (replace last).
+export function referencePickerData(scope, expression) {
+ const inner = (expression || "").trim();
+ if (!inner) {
+ return null;
+ }
+
+ const own = listReferenceProperties(scope, inner);
+ if (own.length) {
+ return { baseExpr: inner, properties: own, current: null };
+ }
+
+ const split = splitLastAccessor(inner);
+ if (!split) {
+ return null;
+ }
+ const siblings = listReferenceProperties(scope, split.parent);
+ if (siblings.length) {
+ return {
+ baseExpr: split.parent,
+ properties: siblings,
+ current: split.current,
+ };
+ }
+
+ return null;
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/variable/variable-input.scss b/plugins/discourse-workflows/assets/stylesheets/common/variable/variable-input.scss
index 9afd773d084..6bdb600cb56 100644
--- a/plugins/discourse-workflows/assets/stylesheets/common/variable/variable-input.scss
+++ b/plugins/discourse-workflows/assets/stylesheets/common/variable/variable-input.scss
@@ -1,10 +1,22 @@
.workflows-variable-input {
+ display: flex;
+ flex-direction: column;
width: 100%;
border: 1px solid var(--primary-low-mid);
border-radius: var(--d-border-radius);
background: var(--secondary);
box-sizing: border-box;
+ // Editor and scroller fill the wrapper, so a taller field has no dead strip
+ // below the text where clicks and drops don't register.
+ .cm-editor {
+ flex: 1 1 auto;
+
+ .cm-scroller {
+ flex: 1 1 auto;
+ }
+ }
+
.cm-editor .cm-content {
min-height: 60px;
padding: 0.5em;
@@ -210,6 +222,109 @@
border-radius: 2px;
}
+ .cm-wf-reference-pill {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.25em;
+ max-width: 100%;
+ padding: 1px 0.5em;
+
+ // Inset shadow, not a border: a border would add to the pill's height.
+ box-shadow: inset 0 0 0 1px var(--tertiary-low-mid, var(--tertiary-low));
+ border-radius: 1em;
+ background: var(--tertiary-low);
+ color: var(--tertiary-hover);
+ font-size: var(--font-down-1);
+ line-height: 1.15;
+ white-space: nowrap;
+
+ // Middle, not baseline, so pills with/without a path line up.
+ vertical-align: middle;
+ margin-block: 1px;
+ cursor: grab;
+
+ &:hover {
+ background: color-mix(in srgb, var(--tertiary) 22%, transparent);
+ }
+
+ &:active {
+ cursor: grabbing;
+ }
+
+ &.--selected {
+ background: color-mix(in srgb, var(--tertiary) 30%, transparent);
+ box-shadow: inset 0 0 0 1px var(--tertiary);
+ }
+
+ &.--incomplete {
+ outline: 1px dashed color-mix(in srgb, var(--tertiary) 55%, transparent);
+ outline-offset: -1px;
+ }
+
+ &.--invalid {
+ background: color-mix(in srgb, var(--danger) 12%, transparent);
+ box-shadow: inset 0 0 0 1px var(--danger);
+ color: var(--danger);
+
+ .cm-wf-reference-pill__icon,
+ .cm-wf-reference-pill__drill {
+ color: var(--danger);
+ }
+ }
+
+ &__icon {
+ display: inline-flex;
+ color: var(--tertiary);
+
+ .d-icon {
+ width: 0.85em;
+ height: 0.85em;
+ }
+ }
+
+ &__badge {
+ flex-shrink: 0;
+ max-width: 16ch;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ font-weight: 600;
+ }
+
+ // Not monospace: the browser's monospace-size quirk made these pills
+ // taller than badge-only ones.
+ &__path {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+
+ &::before {
+ content: "›";
+ margin-inline-end: 0.3em;
+ opacity: 0.6;
+ }
+ }
+
+ &__drill {
+ display: inline-flex;
+ align-items: center;
+ padding: 0;
+ margin-inline-start: 0.1em;
+ border: none;
+ background: none;
+ color: var(--tertiary);
+ cursor: pointer;
+
+ .d-icon {
+ width: 0.7em;
+ height: 0.7em;
+ }
+
+ &:hover {
+ color: var(--tertiary-hover);
+ }
+ }
+ }
+
// Drop cursor during variable drag
.cm-dropCursor {
position: absolute;
@@ -335,3 +450,132 @@
color: var(--primary);
}
}
+
+// The picker opens over the node configurator modal, so it must sit above it.
+.fk-d-menu[data-identifier="workflows-reference-picker"] {
+ z-index: z("modal", "tooltip") !important;
+}
+
+.workflows-reference-picker {
+ display: flex;
+ flex-direction: column;
+ min-width: 240px;
+ max-width: 340px;
+ font-size: var(--font-down-1);
+
+ &__header {
+ display: flex;
+ align-items: stretch;
+ border-bottom: 1px solid var(--primary-low);
+ }
+
+ // Scoped under __header (two classes) to out-specify the global
+ // `input[type=text]` border/outline without !important.
+ &__header &__filter {
+ flex: 1 1 auto;
+ min-width: 0;
+ box-sizing: border-box;
+ margin: 0;
+ padding: 0.5em 0.75em;
+ border: 0;
+ border-radius: 0;
+ background: transparent;
+ font-size: var(--font-down-1);
+
+ &:focus {
+ outline: none;
+ box-shadow: none;
+ }
+
+ &:focus-visible {
+ outline: 1px solid var(--tertiary);
+ outline-offset: -1px;
+ }
+ }
+
+ &__list {
+ margin: 0;
+ padding: 0.25em 0;
+ max-height: 280px;
+ overflow-y: auto;
+ list-style: none;
+ }
+
+ &__option {
+ display: flex;
+ align-items: baseline;
+ gap: 0.5em;
+ width: 100%;
+ padding: 0.3em 0.75em;
+ border: none;
+ background: none;
+ text-align: start;
+ cursor: pointer;
+
+ &:hover,
+ &:focus,
+ &.--active {
+ background: var(--tertiary-low);
+ }
+
+ &.--current .workflows-reference-picker__name {
+ font-weight: 700;
+ color: var(--tertiary);
+ }
+ }
+
+ &__name {
+ flex: 1 1 auto;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ font-family: var(--d-font-family--monospace), monospace;
+ }
+
+ &__type {
+ flex: 0 0 auto;
+ color: var(--primary-medium);
+ font-size: var(--font-down-2);
+ }
+
+ &__empty {
+ padding: 0.5em 0.75em;
+ color: var(--primary-medium);
+ font-style: italic;
+ }
+
+ &__unavailable {
+ flex: 1 1 auto;
+ padding: 0.5em 0.75em;
+ color: var(--primary-medium);
+ font-style: italic;
+ }
+
+ &__edit {
+ flex: 0 0 auto;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.3em;
+ padding: 0 0.75em;
+ border: 0;
+ border-inline-start: 1px solid var(--primary-low);
+ background: none;
+ color: var(--primary-high);
+ white-space: nowrap;
+ cursor: pointer;
+
+ .d-icon {
+ color: var(--primary-medium);
+ font-size: var(--font-down-2);
+ }
+
+ &:hover,
+ &:focus {
+ background: var(--tertiary-low);
+ color: var(--tertiary-hover);
+
+ .d-icon {
+ color: var(--tertiary-hover);
+ }
+ }
+ }
+}
diff --git a/plugins/discourse-workflows/config/locales/client.en.yml b/plugins/discourse-workflows/config/locales/client.en.yml
index 22424fc1716..d56287952c7 100644
--- a/plugins/discourse-workflows/config/locales/client.en.yml
+++ b/plugins/discourse-workflows/config/locales/client.en.yml
@@ -535,6 +535,20 @@ en:
invalid: "Invalid JavaScript"
warning: "Missing function call"
pending: "Not resolved yet"
+ reference_pill:
+ source:
+ input: "Input"
+ trigger: "Trigger"
+ item_index: "Item index"
+ variable: "Variable"
+ current_user: "Current user"
+ site_setting: "Site setting"
+ execution: "Execution"
+ filter_placeholder: "Filter properties…"
+ no_properties: "No properties to drill into"
+ no_matches: "No matches"
+ edit_as_code: "Edit code"
+ pick_property: "Pick a property"
expression_docs:
sections:
previous_nodes: "Previous nodes"
@@ -542,7 +556,7 @@ en:
input: "Current node input helpers. Use $input.item, $input.all(), $input.first(), $input.last(), or $input.params."
item_index: "Index of the input item currently being processed."
json: "JSON data of the current input item. Shorthand for $input.item.json."
- trigger: "Alias for $json — the trigger node's output data."
+ trigger: "The trigger node's output data. Example: $trigger.topic.id"
site_settings: "Access Discourse site settings. Example: $site_settings.title"
current_user: "The user who triggered the workflow. Properties: id, username"
workflow_vars: "Workflow variables defined in the admin panel."
diff --git a/plugins/discourse-workflows/plugin.rb b/plugins/discourse-workflows/plugin.rb
index d050d461630..871489559bf 100644
--- a/plugins/discourse-workflows/plugin.rb
+++ b/plugins/discourse-workflows/plugin.rb
@@ -40,6 +40,11 @@ register_svg_icon "palette"
register_svg_icon "reply"
register_svg_icon "triangle-exclamation"
register_svg_icon "clock"
+register_svg_icon "diagram-project"
+register_svg_icon "right-to-bracket"
+register_svg_icon "dollar-sign"
+register_svg_icon "user"
+register_svg_icon "gear"
register_svg_icon "comments"
register_svg_icon "pause"
register_svg_icon "window-maximize"
diff --git a/plugins/discourse-workflows/spec/system/expression_editor_spec.rb b/plugins/discourse-workflows/spec/system/expression_editor_spec.rb
index 8c728c7d2b7..7be8973d3fe 100644
--- a/plugins/discourse-workflows/spec/system/expression_editor_spec.rb
+++ b/plugins/discourse-workflows/spec/system/expression_editor_spec.rb
@@ -61,7 +61,9 @@ RSpec.describe "Workflow Expression Editor" do
end
it "marks unclosed expressions with error decoration" do
- expression_editor.type_in_editor("{{ $json.title")
+ # A non-reference expression so it stays raw text (a simple reference
+ # would render as an atomic pill and backspace would delete it wholesale).
+ expression_editor.type_in_editor("{{ foo.bar")
expression_editor.move_cursor_and_delete(3, 2)
expect(expression_editor).to have_syntax_error
@@ -108,7 +110,9 @@ RSpec.describe "Workflow Expression Editor" do
before { open_expression_editor }
it "shows a tooltip when hovering over a dollar variable" do
- expression_editor.type_in_editor("{{ $json }}")
+ # An expression that stays raw (not a pill) so the $json token is present
+ # to hover; a bare reference would render as a pill.
+ expression_editor.type_in_editor("{{ $json + 1 }}")
expression_editor.hover_variable("$json")
@@ -155,7 +159,9 @@ RSpec.describe "Workflow Expression Editor" do
end
it "highlights invalid expressions in the editor with red background" do
- expression_editor.type_in_editor("{{ $vars. }}")
+ # A raw (non-pill) trailing-dot expression; a $-reference would render as
+ # a pill and carry its own invalid styling instead.
+ expression_editor.type_in_editor("{{ foo. }}")
expect(page).to have_css(".cm-wf-invalid-expression", wait: 10)
end
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/expression-reference-pills-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/expression-reference-pills-test.gjs
new file mode 100644
index 00000000000..c2f00c2db4b
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/expression-reference-pills-test.gjs
@@ -0,0 +1,139 @@
+import { render, waitFor, waitUntil } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import VariableInput from "discourse/plugins/discourse-workflows/admin/components/workflows/variable/input";
+import { buildFocusEmptyArea } from "discourse/plugins/discourse-workflows/admin/lib/workflows/expression-extensions/focus-empty-area";
+import { buildReferencePills } from "discourse/plugins/discourse-workflows/admin/lib/workflows/expression-extensions/reference-pills";
+
+// A scope where `$json` resolves, so simple references classify as valid.
+const SCOPE = { $json: { title: "Hello", value: 1.2345 } };
+
+// Minimal extension set: the expression language (so `{{ ... }}` parses into
+// Expression nodes) plus the pill view plugin under test. Avoids the
+// network-backed builders (completions, evaluation) that the full bundle adds.
+function pillExtensions(cmParams) {
+ return [
+ cmParams.utils.expressionLanguage(),
+ buildReferencePills(cmParams, { scope: SCOPE, onOpenReferencePicker() {} }),
+ ];
+}
+
+function focusExtensions(cmParams) {
+ return [buildFocusEmptyArea(cmParams)];
+}
+
+module(
+ "Integration | Component | Workflows | expression reference pills",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ pretender.get("/admin/plugins/discourse-workflows/variables.json", () =>
+ response(200, { variables: [] })
+ );
+ });
+
+ test("renders a simple reference as a pill, hiding the raw syntax", async function (assert) {
+ const value = "{{ $json.title }}";
+
+ await render(
+ <template>
+ <VariableInput @value={{value}} @extensions={{pillExtensions}} />
+ </template>
+ );
+ await waitFor(".cm-wf-reference-pill");
+
+ const pill = this.element.querySelector(".cm-wf-reference-pill");
+ assert.dom(pill).exists("the reference renders as a pill");
+ assert.true(
+ pill.textContent.includes("title"),
+ "the pill shows the property path"
+ );
+ assert.false(
+ this.element
+ .querySelector(".cm-content")
+ .textContent.includes("$json.title"),
+ "the raw expression syntax is hidden"
+ );
+ });
+
+ test("leaves a complex expression as raw code (no pill)", async function (assert) {
+ const value = "{{ $json.value.toFixed(2) }}";
+
+ await render(
+ <template>
+ <VariableInput @value={{value}} @extensions={{pillExtensions}} />
+ </template>
+ );
+ await waitFor(".cm-editor");
+
+ assert
+ .dom(".cm-wf-reference-pill")
+ .doesNotExist("a method call is not pilled");
+ assert.true(
+ this.element
+ .querySelector(".cm-content")
+ .textContent.includes("toFixed"),
+ "the raw expression stays visible for editing"
+ );
+ });
+
+ test("selecting the expression marks the pill as selected", async function (assert) {
+ const value = "{{ $json.title }}";
+ let editorView;
+ const onSetup = (view) => (editorView = view);
+
+ await render(
+ <template>
+ <VariableInput
+ @value={{value}}
+ @extensions={{pillExtensions}}
+ @onSetup={{onSetup}}
+ />
+ </template>
+ );
+ await waitFor(".cm-wf-reference-pill");
+
+ editorView.dispatch({
+ selection: { anchor: 0, head: editorView.state.doc.length },
+ });
+ await waitUntil(() =>
+ this.element.querySelector(".cm-wf-reference-pill.--selected")
+ );
+
+ assert
+ .dom(".cm-wf-reference-pill.--selected")
+ .exists("the whole-pill selection renders the selected state");
+ });
+
+ test("clicking the empty area below the text focuses the editor and moves the caret to the end", async function (assert) {
+ const value = "{{ $json.title }} more";
+ let editorView;
+ const onSetup = (view) => (editorView = view);
+
+ await render(
+ <template>
+ <VariableInput
+ @value={{value}}
+ @extensions={{focusExtensions}}
+ @onSetup={{onSetup}}
+ />
+ </template>
+ );
+ await waitFor(".cm-editor");
+
+ // Caret at the start, then a mousedown on the empty scroller area.
+ editorView.dispatch({ selection: { anchor: 0 } });
+ this.element
+ .querySelector(".cm-scroller")
+ .dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
+
+ assert.strictEqual(
+ editorView.state.selection.main.anchor,
+ editorView.state.doc.length,
+ "the caret jumps to the end of the document"
+ );
+ });
+ }
+);
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/expression-context-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/expression-context-test.js
index 088dca73bfa..7f811b438e1 100644
--- a/plugins/discourse-workflows/test/javascripts/unit/lib/expression-context-test.js
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/expression-context-test.js
@@ -37,12 +37,31 @@ module("Unit | lib | discourse-workflows | buildScope", function () {
assert.strictEqual(scope.$json.post.raw, "");
});
- test("trigger aliases $json", function (assert) {
+ test("$trigger resolves to the trigger node output, distinct from $json", function (assert) {
const scope = buildScope({
- inputFields: [{ key: "title", type: "string" }],
+ inputFields: [{ key: "current", type: "string" }],
+ ancestorNodes: [
+ {
+ node: { name: "Topic Created", type: "trigger:topic_created" },
+ fields: [{ key: "topic_title", type: "string" }],
+ },
+ ],
});
- assert.strictEqual(scope.trigger, scope.$json);
+ assert.strictEqual(scope.$trigger.topic_title, "");
+ // Distinct from the current input, and the bare `trigger` name is gone.
+ assert.notStrictEqual(scope.$trigger, scope.$json);
+ assert.strictEqual(scope.$json.topic_title, undefined);
+ assert.strictEqual(scope.trigger, undefined);
+ });
+
+ test("$trigger is an empty object when no trigger ancestor is known", function (assert) {
+ const scope = buildScope({
+ inputFields: [{ key: "current", type: "string" }],
+ });
+
+ assert.deepEqual(Object.keys(scope.$trigger), []);
+ assert.strictEqual(scope.trigger, undefined);
});
test("$input.item.json aliases $json", function (assert) {
@@ -313,6 +332,23 @@ module("Unit | lib | discourse-workflows | walkScope", function () {
]);
});
+ test("resolves array subscripts and bracket keys", function (assert) {
+ const scope = {
+ $json: { items: [{ id: 7 }, { id: 9 }], "weird key": "found" },
+ };
+ // Subscript on a nested property (the common array-index case).
+ assert.strictEqual(walkScope(scope, "$json.items[0].id"), 7);
+ assert.strictEqual(walkScope(scope, "$json.items[1].id"), 9);
+ // Bracket key on the root token.
+ assert.strictEqual(walkScope(scope, '$json["weird key"]'), "found");
+ // Known limitation: a bracket key containing a dot is split by the path
+ // parser, so it does not resolve (would need a bracket-aware tokenizer).
+ assert.strictEqual(
+ walkScope({ $json: { "a.b": 1 } }, '$json["a.b"]'),
+ undefined
+ );
+ });
+
test("resolves boolean values", function (assert) {
assert.true(walkScope({ $json: { active: true } }, "$json.active"));
});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/expression-reference-label-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/expression-reference-label-test.js
new file mode 100644
index 00000000000..bfba705259f
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/expression-reference-label-test.js
@@ -0,0 +1,124 @@
+import { module, test } from "qunit";
+import {
+ parseReference,
+ referenceLabel,
+} from "discourse/plugins/discourse-workflows/admin/lib/workflows/expression-extensions/reference-label";
+
+module("Unit | lib | discourse-workflows | parseReference", function () {
+ test("parses a node-reference field path", function (assert) {
+ const parsed = parseReference(
+ '$("Create Intermediate Topic").first().json.topic.id'
+ );
+ assert.deepEqual(parsed, {
+ source: { type: "node", name: "Create Intermediate Topic" },
+ path: "topic.id",
+ });
+ });
+
+ test("parses node references using .item and a branch index", function (assert) {
+ assert.deepEqual(parseReference("$('Fetch').item.json.user.name"), {
+ source: { type: "node", name: "Fetch" },
+ path: "user.name",
+ });
+ assert.deepEqual(parseReference('$("Split").first(1).json.value'), {
+ source: { type: "node", name: "Split" },
+ path: "value",
+ });
+ });
+
+ test("parses current-input ($json / $input) references", function (assert) {
+ assert.deepEqual(parseReference("$json.topic.id"), {
+ source: { type: "input" },
+ path: "topic.id",
+ });
+ assert.deepEqual(parseReference("$input.first().json.title"), {
+ source: { type: "input" },
+ path: "title",
+ });
+ });
+
+ test("parses $trigger and $itemIndex as their own sources", function (assert) {
+ assert.deepEqual(parseReference("$trigger.post.raw"), {
+ source: { type: "trigger" },
+ path: "post.raw",
+ });
+ assert.deepEqual(parseReference("$itemIndex"), {
+ source: { type: "item_index" },
+ path: "",
+ });
+ });
+
+ test("parses the remaining dollar roots", function (assert) {
+ assert.strictEqual(parseReference("$vars.api_key").source.type, "variable");
+ assert.strictEqual(
+ parseReference("$current_user.username").source.type,
+ "current_user"
+ );
+ assert.strictEqual(
+ parseReference("$site_settings.title").source.type,
+ "site_setting"
+ );
+ assert.strictEqual(
+ parseReference("$execution.id").source.type,
+ "execution"
+ );
+ });
+
+ test("supports bracket and numeric subscripts", function (assert) {
+ assert.deepEqual(parseReference("$json.items[0].id"), {
+ source: { type: "input" },
+ path: "items[0].id",
+ });
+ assert.deepEqual(parseReference("$json['weird key'].value"), {
+ source: { type: "input" },
+ path: "['weird key'].value",
+ });
+ });
+
+ test("allows bare references with no trailing path", function (assert) {
+ assert.deepEqual(parseReference("$json"), {
+ source: { type: "input" },
+ path: "",
+ });
+ });
+
+ test("rejects anything that isn't a plain reference", function (assert) {
+ assert.strictEqual(parseReference("$json.a + $json.b"), null);
+ assert.strictEqual(parseReference("$json.count > 5"), null);
+ assert.strictEqual(parseReference("Math.max($json.a, 1)"), null);
+ assert.strictEqual(
+ parseReference('$("Node").first().json.items.map(x)'),
+ null
+ );
+ assert.strictEqual(parseReference("$json.title.toUpperCase()"), null);
+ assert.strictEqual(parseReference(""), null);
+ assert.strictEqual(parseReference(" "), null);
+ });
+});
+
+module("Unit | lib | discourse-workflows | referenceLabel", function () {
+ test("uses the node name as the badge for node references", function (assert) {
+ const label = referenceLabel(
+ parseReference('$("Create Topic").first().json.topic.id')
+ );
+ assert.strictEqual(label.sourceType, "node");
+ assert.strictEqual(label.badge, "Create Topic");
+ assert.strictEqual(label.path, "topic.id");
+ assert.strictEqual(label.icon, "diagram-project");
+ });
+
+ test("labels $trigger and $itemIndex with their own source and icon", function (assert) {
+ const trigger = referenceLabel(parseReference("$trigger.topic.id"));
+ assert.strictEqual(trigger.sourceType, "trigger");
+ assert.strictEqual(trigger.icon, "play");
+ assert.strictEqual(trigger.path, "topic.id");
+
+ const itemIndex = referenceLabel(parseReference("$itemIndex"));
+ assert.strictEqual(itemIndex.sourceType, "item_index");
+ assert.strictEqual(itemIndex.icon, "hashtag");
+ });
+
+ test("returns null for unparseable expressions", function (assert) {
+ assert.strictEqual(referenceLabel(parseReference("$json.a + 1")), null);
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/expression-reference-properties-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/expression-reference-properties-test.js
new file mode 100644
index 00000000000..be2a65dc1f5
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/expression-reference-properties-test.js
@@ -0,0 +1,60 @@
+import { module, test } from "qunit";
+import {
+ propertyAccessor,
+ referencePickerData,
+} from "discourse/plugins/discourse-workflows/admin/lib/workflows/expression-extensions/reference-properties";
+
+module("Unit | lib | discourse-workflows | propertyAccessor", function () {
+ test("uses dotted access for plain identifiers", function (assert) {
+ assert.strictEqual(propertyAccessor("topic"), ".topic");
+ assert.strictEqual(propertyAccessor("topic_id"), ".topic_id");
+ assert.strictEqual(propertyAccessor("$ref"), ".$ref");
+ assert.strictEqual(propertyAccessor("_private"), "._private");
+ });
+
+ test("uses quoted bracket access for non-identifier names", function (assert) {
+ assert.strictEqual(propertyAccessor("product-name"), '["product-name"]');
+ assert.strictEqual(propertyAccessor("order id"), '["order id"]');
+ assert.strictEqual(propertyAccessor("123"), '["123"]');
+ assert.strictEqual(propertyAccessor("a.b"), '["a.b"]');
+ });
+
+ test("escapes quotes and backslashes in bracket access", function (assert) {
+ assert.strictEqual(propertyAccessor('we"ird'), '["we\\"ird"]');
+ assert.strictEqual(propertyAccessor("back\\slash"), '["back\\\\slash"]');
+ });
+});
+
+module("Unit | lib | discourse-workflows | referencePickerData", function () {
+ const scope = {
+ $vars: {
+ topic: { id: 123, title: "Hello", "a.b": "dotted-key" },
+ },
+ };
+
+ test("drills into an object reference", function (assert) {
+ const data = referencePickerData(scope, "$vars.topic");
+ assert.strictEqual(data.baseExpr, "$vars.topic");
+ assert.strictEqual(data.current, null);
+ assert.true(data.properties.some((p) => p.name === "id"));
+ });
+
+ test("switches siblings for a leaf reference", function (assert) {
+ const data = referencePickerData(scope, "$vars.topic.title");
+ assert.strictEqual(data.baseExpr, "$vars.topic");
+ assert.strictEqual(data.current, "title");
+ });
+
+ test("splits on the last top-level accessor, not a dot inside a bracket key", function (assert) {
+ const data = referencePickerData(scope, '$vars.topic["a.b"]');
+ assert.strictEqual(data.baseExpr, "$vars.topic");
+ assert.strictEqual(data.current, "a.b");
+ assert.true(data.properties.some((p) => p.name === "a.b"));
+ });
+
+ test("returns null when nothing can be picked", function (assert) {
+ assert.strictEqual(referencePickerData(scope, ""), null);
+ // No accessor and no resolvable object: nothing to drill or switch.
+ assert.strictEqual(referencePickerData(scope, "unknownRoot"), null);
+ });
+});