Skip to content

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

FIX: Preserve workflow prompts when dropping variables (#43032)

Renato Atiliob26e51de26d0
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-wrapper.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-wrapper.gjs
index dac70b77c43..8282ca0de8f 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-wrapper.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-wrapper.gjs
@@ -7,6 +7,7 @@ import DSegmentedControl from "discourse/components/d-segmented-control";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import { i18n } from "discourse-i18n";
import {
+ caretOffsetFromPoint,
resolveVariableId,
WORKFLOW_VARIABLE_MIME,
} from "../../../lib/workflows/expression-context";
@@ -238,6 +239,21 @@ export default class ExpressionWrapper extends Component {
this.workflowsNodeTypes.expressionContext.item_prefix || "$json";
const variableId = resolveVariableId(variable, prefix);
+ const control = event.currentTarget.querySelector(
+ "textarea, input[type='text']"
+ );
+ if (control && schemaType(this.args.schema) === "string") {
+ const value = control.value ?? "";
+ const offset =
+ caretOffsetFromPoint(control, event.clientX, event.clientY) ??
+ value.length;
+ const expression = `{{ ${variableId} }}`;
+ this.args.field.set(
+ `=${value.slice(0, offset)}${expression}${value.slice(offset)}`
+ );
+ return;
+ }
+
this.args.field.set(`={{ ${variableId} }}`);
}
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 fb2d66a8711..848c52155ff 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
@@ -32,6 +32,22 @@ export function resolveVariableId(variable, itemPrefix = "$json") {
: `${itemPrefix}.${variable.id}`;
}
+// Null whenever the point does not resolve inside the control, including on
+// engines without caretPositionFromPoint, where callers append instead.
+export function caretOffsetFromPoint(control, x, y) {
+ const position = document.caretPositionFromPoint?.(x, y);
+ if (
+ position?.offsetNode !== control ||
+ !Number.isInteger(position.offset) ||
+ position.offset < 0 ||
+ position.offset > control.value.length
+ ) {
+ return null;
+ }
+
+ return position.offset;
+}
+
// Matches paths like $('Node Name').rest or $("Node Name").rest
export const NODE_REF_RE = /^\$\((?:"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)')\)/;
const METHOD_CALL_RE = /^([A-Za-z_$][\w$]*)\((.*)\)$/;
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator.scss b/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator.scss
index 960d3e148c5..73dd3735e5f 100644
--- a/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator.scss
+++ b/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator.scss
@@ -156,7 +156,8 @@
outline-offset: 2px;
}
- &.is-drag-over input {
+ &.is-drag-over input,
+ &.is-drag-over textarea {
border-color: var(--tertiary) !important;
background: var(--tertiary-50);
}
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-input-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-input-test.gjs
index f371ff1268c..dd896d8ab58 100644
--- a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-input-test.gjs
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-input-test.gjs
@@ -430,6 +430,10 @@ module(
'$("Trigger").item.json.trigger',
"uses a safe linked-item expression when no item count exists"
);
+ assert.false(
+ "text/plain" in dragged,
+ "does not make expression-disabled text controls native drop targets"
+ );
});
test("reuses one declared schema resolution across ancestor sections", async function (assert) {
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
index c2f00c2db4b..49d74130c2b 100644
--- 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
@@ -1,8 +1,9 @@
-import { render, waitFor, waitUntil } from "@ember/test-helpers";
+import { render, triggerEvent, 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 { WORKFLOW_VARIABLE_MIME } from "discourse/plugins/discourse-workflows/admin/lib/workflows/expression-context";
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";
@@ -56,6 +57,24 @@ module(
.textContent.includes("$json.title"),
"the raw expression syntax is hidden"
);
+
+ const dragged = {};
+ await triggerEvent(pill, "dragstart", {
+ dataTransfer: {
+ setData(type, draggedValue) {
+ dragged[type] = draggedValue;
+ },
+ },
+ });
+ assert.strictEqual(
+ JSON.parse(dragged[WORKFLOW_VARIABLE_MIME]).id,
+ "$json.title",
+ "the expression remains available to workflow drop targets"
+ );
+ assert.false(
+ "text/plain" in dragged,
+ "the pill does not become a native plain-text drag source"
+ );
});
test("leaves a complex expression as raw code (no pill)", async function (assert) {
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/expression-wrapper-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/expression-wrapper-test.gjs
index 72483cb0782..55c294051c9 100644
--- a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/expression-wrapper-test.gjs
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/expression-wrapper-test.gjs
@@ -1,9 +1,20 @@
import { tracked } from "@glimmer/tracking";
-import { click, render } from "@ember/test-helpers";
+import { click, find, render, triggerEvent } from "@ember/test-helpers";
import { module, test } from "qunit";
+import Form from "discourse/components/form";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import DefaultInputControl from "discourse/plugins/discourse-workflows/admin/components/workflows/configurators/default-input-control";
import ExpressionWrapper from "discourse/plugins/discourse-workflows/admin/components/workflows/configurators/expression-wrapper";
+import { WORKFLOW_VARIABLE_MIME } from "discourse/plugins/discourse-workflows/admin/lib/workflows/expression-context";
+
+function variableTransfer(variable) {
+ return {
+ types: [WORKFLOW_VARIABLE_MIME],
+ getData: (type) =>
+ type === WORKFLOW_VARIABLE_MIME ? JSON.stringify(variable) : "",
+ };
+}
class TestField {
@tracked value;
@@ -22,10 +33,190 @@ module(
function (hooks) {
setupRenderingTest(hooks);
+ let caretPositionDescriptor;
+
+ // Defined rather than stubbed: the API is absent on some engines.
+ function stubCaretPosition(offsetNode, offset) {
+ Object.defineProperty(document, "caretPositionFromPoint", {
+ configurable: true,
+ value: () => ({ offsetNode, offset }),
+ });
+ }
+
hooks.beforeEach(function () {
pretender.get("/admin/plugins/discourse-workflows/variables.json", () =>
response(200, { variables: [] })
);
+
+ caretPositionDescriptor = Object.getOwnPropertyDescriptor(
+ document,
+ "caretPositionFromPoint"
+ );
+ });
+
+ hooks.afterEach(function () {
+ if (caretPositionDescriptor) {
+ Object.defineProperty(
+ document,
+ "caretPositionFromPoint",
+ caretPositionDescriptor
+ );
+ } else {
+ delete document.caretPositionFromPoint;
+ }
+ });
+
+ test("preserves plain text when dropping a variable into a text control", async function (assert) {
+ const originalValue = "Introduction 😀\n\nالخلاصة";
+ const insertionStart = "Introduction 😀\n".length;
+ this.configuration = { prompt: originalValue };
+ this.schema = { type: "string" };
+
+ await render(
+ <template>
+ <Form @data={{this.configuration}} as |form transientData|>
+ <form.Field
+ @name="prompt"
+ @title="Prompt"
+ @type="textarea"
+ as |field|
+ >
+ <DefaultInputControl
+ @field={{field}}
+ @schema={{this.schema}}
+ @supportsExpression={{true}}
+ />
+ </form.Field>
+ <output data-value={{transientData.prompt}}></output>
+ </Form>
+ </template>
+ );
+
+ const textareaElement = find("textarea");
+ stubCaretPosition(textareaElement, insertionStart);
+
+ await triggerEvent(textareaElement, "dragover", {
+ dataTransfer: variableTransfer({ id: "result" }),
+ clientX: 20,
+ clientY: 30,
+ });
+
+ assert.strictEqual(
+ find("output").dataset.value,
+ originalValue,
+ "dragging over the field does not change its value"
+ );
+
+ await triggerEvent(textareaElement, "drop", {
+ dataTransfer: variableTransfer({ id: "result" }),
+ clientX: 20,
+ clientY: 30,
+ });
+
+ assert.strictEqual(
+ find("output").dataset.value,
+ "=Introduction 😀\n{{ $json.result }}\nالخلاصة",
+ "the original text is preserved around the expression"
+ );
+ assert
+ .dom(".workflows-variable-input")
+ .exists("the field switches to dynamic mode");
+ });
+
+ test("appends a variable when dropping on the mode control", async function (assert) {
+ this.field = new TestField("Existing prompt");
+ this.schema = { type: "string" };
+
+ await render(
+ <template>
+ <ExpressionWrapper
+ @field={{this.field}}
+ @schema={{this.schema}}
+ @supportsExpression={{true}}
+ >
+ <textarea value={{this.field.value}}></textarea>
+ </ExpressionWrapper>
+ </template>
+ );
+
+ const modeControl = find(".workflows-property-engine__mode-control");
+ stubCaretPosition(modeControl, 0);
+
+ await triggerEvent(modeControl, "drop", {
+ dataTransfer: variableTransfer({ id: "result" }),
+ clientX: 20,
+ clientY: 30,
+ });
+
+ assert.strictEqual(
+ this.field.value,
+ "=Existing prompt{{ $json.result }}",
+ "dropping outside the text control preserves and appends to its value"
+ );
+ });
+
+ test("preserves populated single-line text controls", async function (assert) {
+ this.field = new TestField("Existing title");
+ this.schema = { type: "string" };
+
+ await render(
+ <template>
+ <ExpressionWrapper
+ @field={{this.field}}
+ @schema={{this.schema}}
+ @supportsExpression={{true}}
+ >
+ <input type="text" value={{this.field.value}} />
+ </ExpressionWrapper>
+ </template>
+ );
+
+ const inputElement = find("input[type='text']");
+ stubCaretPosition(inputElement, 9);
+
+ await triggerEvent(inputElement, "drop", {
+ dataTransfer: variableTransfer({ id: "result" }),
+ clientX: 20,
+ clientY: 30,
+ });
+
+ assert.strictEqual(
+ this.field.value,
+ "=Existing {{ $json.result }}title",
+ "the expression is inserted without replacing the current title"
+ );
+ });
+
+ test("keeps replacement behavior for string-valued non-text controls", async function (assert) {
+ this.field = new TestField("first");
+ this.schema = { type: "string" };
+
+ await render(
+ <template>
+ <ExpressionWrapper
+ @field={{this.field}}
+ @schema={{this.schema}}
+ @supportsExpression={{true}}
+ >
+ <select class="plain-control">
+ <option value="first">First</option>
+ </select>
+ </ExpressionWrapper>
+ </template>
+ );
+
+ await triggerEvent(".plain-control", "dragover", {
+ dataTransfer: variableTransfer({ id: "result" }),
+ });
+ await triggerEvent(".plain-control", "drop", {
+ dataTransfer: variableTransfer({ id: "result" }),
+ });
+
+ assert.strictEqual(
+ this.field.value,
+ "={{ $json.result }}",
+ "the selected value is replaced by the expression"
+ );
});
test("converts fixed arrays to whole expressions", async function (assert) {
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 cd0cbdc2825..011ecd2567a 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
@@ -1,6 +1,7 @@
import { module, test } from "qunit";
import {
buildScope,
+ caretOffsetFromPoint,
lookupWorkflowMethodDoc,
resolveVariableId,
walkScope,
@@ -398,3 +399,79 @@ module("Unit | lib | discourse-workflows | resolveVariableId", function () {
);
});
});
+
+module(
+ "Unit | lib | discourse-workflows | caretOffsetFromPoint",
+ function (hooks) {
+ let descriptor;
+
+ // Defined rather than stubbed: the API is absent on some engines, which is
+ // itself one of the cases under test.
+ function stubCaretPosition(value) {
+ Object.defineProperty(document, "caretPositionFromPoint", {
+ configurable: true,
+ value,
+ });
+ }
+
+ function textarea(value) {
+ const control = document.createElement("textarea");
+ control.value = value;
+ return control;
+ }
+
+ hooks.beforeEach(function () {
+ descriptor = Object.getOwnPropertyDescriptor(
+ document,
+ "caretPositionFromPoint"
+ );
+ });
+
+ hooks.afterEach(function () {
+ if (descriptor) {
+ Object.defineProperty(document, "caretPositionFromPoint", descriptor);
+ } else {
+ delete document.caretPositionFromPoint;
+ }
+ });
+
+ test("uses a caret position that belongs to the control", function (assert) {
+ const control = textarea("abcdef");
+ stubCaretPosition(() => ({ offsetNode: control, offset: 3 }));
+
+ assert.strictEqual(caretOffsetFromPoint(control, 10, 20), 3);
+ });
+
+ test("keeps a caret position at either edge of the value", function (assert) {
+ const control = textarea("abcdef");
+ stubCaretPosition(() => ({ offsetNode: control, offset: 0 }));
+ assert.strictEqual(caretOffsetFromPoint(control, 10, 20), 0);
+
+ stubCaretPosition(() => ({ offsetNode: control, offset: 6 }));
+ assert.strictEqual(caretOffsetFromPoint(control, 10, 20), 6);
+ });
+
+ test("rejects a caret position outside the control", function (assert) {
+ const control = textarea("abcdef");
+ stubCaretPosition(() => ({ offsetNode: document.body, offset: 0 }));
+
+ assert.strictEqual(caretOffsetFromPoint(control, 10, 20), null);
+ });
+
+ test("rejects an offset past the end of the value", function (assert) {
+ const control = textarea("abcdef");
+ stubCaretPosition(() => ({ offsetNode: control, offset: 9 }));
+
+ assert.strictEqual(caretOffsetFromPoint(control, 10, 20), null);
+ });
+
+ test("returns null without a caret position API", function (assert) {
+ delete document.caretPositionFromPoint;
+
+ assert.strictEqual(
+ caretOffsetFromPoint(textarea("abcdef"), 10, 20),
+ null
+ );
+ });
+ }
+);