Skip to content

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

FEAT: Add workflow canvas clipboard (#41217)

Sam4feb44b1213c
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-clipboard.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-clipboard.js
new file mode 100644
index 00000000000..f7c5d1d789c
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-clipboard.js
@@ -0,0 +1,337 @@
+import { i18n } from "discourse-i18n";
+
+const PAYLOAD_TYPE = "discourse-workflows/canvas-selection";
+const PAYLOAD_VERSION = 1;
+const MARKER_NAME = "discourse-workflows-canvas-selection";
+const MARKER_PREFIX = `<!-- ${MARKER_NAME}:v${PAYLOAD_VERSION}:`;
+const MARKER_PATTERN = new RegExp(
+ `<!--\\s*${MARKER_NAME}:v${PAYLOAD_VERSION}:([A-Za-z0-9+/=]+)\\s*-->`
+);
+const STICKY_NOTE_COLORS = new Set([
+ "yellow",
+ "blue",
+ "green",
+ "pink",
+ "purple",
+ "orange",
+]);
+
+function normalizeLineEndings(text) {
+ return typeof text === "string" ? text.replace(/\r\n/g, "\n") : text;
+}
+
+export function isSerializedCanvasClipboardPayload(text, serializedPayload) {
+ return Boolean(
+ text &&
+ serializedPayload &&
+ normalizeLineEndings(text) === normalizeLineEndings(serializedPayload)
+ );
+}
+
+function clonePosition(position) {
+ if (!position || typeof position !== "object") {
+ return null;
+ }
+
+ const x = Number(position.x);
+ const y = Number(position.y);
+
+ if (!Number.isFinite(x) || !Number.isFinite(y)) {
+ return null;
+ }
+
+ return { x, y };
+}
+
+function cloneSize(size) {
+ if (!size || typeof size !== "object") {
+ return null;
+ }
+
+ const width = Number(size.width);
+ const height = Number(size.height);
+
+ if (!Number.isFinite(width) || !Number.isFinite(height)) {
+ return null;
+ }
+
+ return { width, height };
+}
+
+function cloneColor(color) {
+ return STICKY_NOTE_COLORS.has(color) ? color : undefined;
+}
+
+function cloneNodeForClipboard(node) {
+ return {
+ clientId: node.clientId,
+ type: node.type,
+ typeVersion: node.typeVersion,
+ name: node.name,
+ configuration: structuredClone(node.configuration || {}),
+ position: clonePosition(node.position),
+ };
+}
+
+function cloneStickyNoteForClipboard(note) {
+ return {
+ clientId: note.clientId,
+ position: clonePosition(note.position),
+ size: cloneSize(note.size),
+ color: cloneColor(note.color),
+ text: note.text,
+ };
+}
+
+function cloneConnectionForClipboard(connection) {
+ return structuredClone(connection);
+}
+
+function encodeBase64(text) {
+ const bytes = new TextEncoder().encode(text);
+ let binary = "";
+
+ for (const byte of bytes) {
+ binary += String.fromCharCode(byte);
+ }
+
+ return btoa(binary);
+}
+
+function decodeBase64(text) {
+ const binary = atob(text);
+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
+
+ return new TextDecoder().decode(bytes);
+}
+
+function normalizeArray(value) {
+ return Array.isArray(value) ? value : [];
+}
+
+function validNode(node) {
+ return (
+ node &&
+ typeof node === "object" &&
+ !Array.isArray(node) &&
+ typeof node.clientId === "string" &&
+ typeof node.type === "string"
+ );
+}
+
+function validStickyNote(note) {
+ return (
+ note &&
+ typeof note === "object" &&
+ !Array.isArray(note) &&
+ typeof note.clientId === "string"
+ );
+}
+
+function validConnection(connection) {
+ return (
+ connection &&
+ typeof connection === "object" &&
+ !Array.isArray(connection) &&
+ typeof connection.sourceClientId === "string" &&
+ typeof connection.targetClientId === "string"
+ );
+}
+
+function uniqueByClientId(items) {
+ const seen = new Set();
+
+ return items.filter((item) => {
+ if (seen.has(item.clientId)) {
+ return false;
+ }
+
+ seen.add(item.clientId);
+ return true;
+ });
+}
+
+function normalizeClipboardTarget(target) {
+ if (!target) {
+ return null;
+ }
+
+ const x = target.canvasX ?? target.x;
+ const y = target.canvasY ?? target.y;
+
+ if (!Number.isFinite(x) || !Number.isFinite(y)) {
+ return null;
+ }
+
+ return { x, y };
+}
+
+export function buildCanvasClipboardPayload(
+ { nodes = [], connections = [], stickyNotes = [] },
+ { nodeIds = new Set(), stickyNoteIds = new Set() }
+) {
+ const selectedNodeIds = new Set(nodeIds);
+ const selectedStickyNoteIds = new Set(stickyNoteIds);
+ const copiedNodes = nodes
+ .filter((node) => selectedNodeIds.has(node.clientId))
+ .map(cloneNodeForClipboard);
+ const copiedStickyNotes = stickyNotes
+ .filter((note) => selectedStickyNoteIds.has(note.clientId))
+ .map(cloneStickyNoteForClipboard);
+
+ if (copiedNodes.length === 0 && copiedStickyNotes.length === 0) {
+ return null;
+ }
+
+ return {
+ type: PAYLOAD_TYPE,
+ version: PAYLOAD_VERSION,
+ nodes: copiedNodes,
+ connections: connections
+ .filter(
+ (connection) =>
+ selectedNodeIds.has(connection.sourceClientId) &&
+ selectedNodeIds.has(connection.targetClientId)
+ )
+ .map(cloneConnectionForClipboard),
+ stickyNotes: copiedStickyNotes,
+ };
+}
+
+export function serializeCanvasClipboardPayload(payload) {
+ const encodedPayload = encodeBase64(JSON.stringify(payload));
+
+ return `${i18n("discourse_workflows.canvas.clipboard_text")}\n${MARKER_PREFIX}${encodedPayload} -->`;
+}
+
+export function parseCanvasClipboardText(text) {
+ if (!text || typeof text !== "string") {
+ return null;
+ }
+
+ const encodedPayload = text.match(MARKER_PATTERN)?.[1];
+ let payloadText;
+ let payload;
+
+ try {
+ payloadText = encodedPayload ? decodeBase64(encodedPayload) : text.trim();
+ payload = JSON.parse(payloadText);
+ } catch {
+ return null;
+ }
+
+ return normalizeCanvasClipboardPayload(payload);
+}
+
+export function payloadForCanvasClipboardPaste(parsedPayload, localPayload) {
+ return parsedPayload || localPayload || null;
+}
+
+export function normalizeCanvasClipboardPayload(payload) {
+ if (
+ !payload ||
+ typeof payload !== "object" ||
+ Array.isArray(payload) ||
+ payload.type !== PAYLOAD_TYPE ||
+ payload.version !== PAYLOAD_VERSION
+ ) {
+ return null;
+ }
+
+ const nodes = uniqueByClientId(
+ normalizeArray(payload.nodes).filter(validNode)
+ );
+ const stickyNotes = uniqueByClientId(
+ normalizeArray(payload.stickyNotes).filter(validStickyNote)
+ );
+ const nodeIds = new Set(nodes.map((node) => node.clientId));
+ const connections = normalizeArray(payload.connections).filter(
+ (connection) =>
+ validConnection(connection) &&
+ nodeIds.has(connection.sourceClientId) &&
+ nodeIds.has(connection.targetClientId)
+ );
+
+ if (nodes.length === 0 && stickyNotes.length === 0) {
+ return null;
+ }
+
+ return {
+ type: PAYLOAD_TYPE,
+ version: PAYLOAD_VERSION,
+ nodes: nodes.map((node) => ({
+ clientId: node.clientId,
+ type: node.type,
+ typeVersion: node.typeVersion,
+ name: node.name,
+ configuration:
+ node.configuration &&
+ typeof node.configuration === "object" &&
+ !Array.isArray(node.configuration)
+ ? structuredClone(node.configuration)
+ : {},
+ position: clonePosition(node.position),
+ })),
+ connections: structuredClone(connections),
+ stickyNotes: stickyNotes.map((note) => ({
+ clientId: note.clientId,
+ position: clonePosition(note.position),
+ size: cloneSize(note.size),
+ color: cloneColor(note.color),
+ text: note.text,
+ })),
+ };
+}
+
+export function positionCanvasClipboardPayload(
+ payload,
+ { target = null, sourceOffset = 0 } = {}
+) {
+ const nodes = structuredClone(payload.nodes || []);
+ const stickyNotes = structuredClone(payload.stickyNotes || []);
+ const items = [...nodes, ...stickyNotes];
+ const targetPosition = normalizeClipboardTarget(target);
+ const positionedItems = items.filter((item) => item.position);
+
+ if (targetPosition) {
+ if (positionedItems.length > 0) {
+ const xs = positionedItems.map((item) => item.position.x);
+ const ys = positionedItems.map((item) => item.position.y);
+ const centerX = (Math.min(...xs) + Math.max(...xs)) / 2;
+ const centerY = (Math.min(...ys) + Math.max(...ys)) / 2;
+ const dx = targetPosition.x - centerX;
+ const dy = targetPosition.y - centerY;
+
+ items.forEach((item, index) => {
+ item.position = item.position
+ ? { x: item.position.x + dx, y: item.position.y + dy }
+ : {
+ x: targetPosition.x + index * 20,
+ y: targetPosition.y + index * 20,
+ };
+ });
+ } else {
+ items.forEach((item, index) => {
+ item.position = {
+ x: targetPosition.x + index * 20,
+ y: targetPosition.y + index * 20,
+ };
+ });
+ }
+ } else if (sourceOffset) {
+ for (const item of items) {
+ if (item.position) {
+ item.position = {
+ x: item.position.x + sourceOffset,
+ y: item.position.y + sourceOffset,
+ };
+ }
+ }
+ }
+
+ return {
+ nodes,
+ connections: structuredClone(payload.connections || []),
+ stickyNotes,
+ };
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-context-menu.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-context-menu.gjs
index 2944d6e3b70..fe32c3cc778 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-context-menu.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-context-menu.gjs
@@ -24,7 +24,7 @@ export default class CanvasContextMenu extends Component {
}
@action
- open(event) {
+ async open(event) {
event.preventDefault();
this.contextMenu = null;
@@ -32,26 +32,37 @@ export default class CanvasContextMenu extends Component {
return;
}
+ const rect = this.args.containerElement.getBoundingClientRect();
+ const canvasPos = this.args.rete.containerToCanvas(
+ event.clientX - rect.left,
+ event.clientY - rect.top
+ );
const nodeEl = event.target.closest(".workflow-rete-node");
if (nodeEl) {
const clientId = nodeEl.dataset.clientId;
- if (clientId && !this.args.rete.getSelectedIds().nodeIds.has(clientId)) {
- this.args.rete.selectableNodes.select(clientId, false);
+ const selectedIds = this.args.rete.getSelectedIds();
+ const useCurrentSelection = selectedIds.nodeIds.has(clientId);
+ const selection = useCurrentSelection
+ ? {
+ nodeIds: [...selectedIds.nodeIds],
+ stickyNoteIds: [...selectedIds.stickyNoteIds],
+ }
+ : { nodeIds: [clientId], stickyNoteIds: [] };
+
+ if (clientId && !useCurrentSelection) {
+ await this.args.rete.selectableNodes.select(clientId, false);
}
this.contextMenu = {
nodeId: clientId,
+ selection,
isUnavailable: nodeEl.dataset.unavailable === "true",
+ canvasPos,
screenX: event.clientX,
screenY: event.clientY,
};
return;
}
- const rect = this.args.containerElement.getBoundingClientRect();
- const canvasPos = this.args.rete.containerToCanvas(
- event.clientX - rect.left,
- event.clientY - rect.top
- );
this.contextMenu = {
isCanvas: true,
canvasPos,
@@ -74,8 +85,30 @@ export default class CanvasContextMenu extends Component {
@action
deleteNode() {
+ const selection = this.contextMenu.selection;
+ this.contextMenu = null;
+ this.args.onDeleteSelected?.(selection);
+ }
+
+ @action
+ cutSelection() {
+ const selection = this.contextMenu.selection;
+ this.contextMenu = null;
+ this.args.onCut?.(selection);
+ }
+
+ @action
+ copySelection() {
+ const selection = this.contextMenu.selection;
this.contextMenu = null;
- this.args.onDeleteSelected?.();
+ this.args.onCopy?.(selection);
+ }
+
+ @action
+ pasteSelection() {
+ const canvasPos = this.contextMenu?.canvasPos;
+ this.contextMenu = null;
+ this.args.onPaste?.(canvasPos);
}
@action
@@ -112,6 +145,12 @@ export default class CanvasContextMenu extends Component {
@translatedLabel={{i18n "discourse_workflows.sticky_note.add"}}
class="btn-transparent workflows-canvas__context-menu-item"
/>
+ <DButton
+ @action={{this.pasteSelection}}
+ @icon="paste"
+ @translatedLabel={{i18n "discourse_workflows.canvas.paste"}}
+ class="btn-transparent workflows-canvas__context-menu-item"
+ />
{{else}}
{{#unless this.contextMenu.isUnavailable}}
<DButton
@@ -121,6 +160,24 @@ export default class CanvasContextMenu extends Component {
class="btn-transparent workflows-canvas__context-menu-item"
/>
{{/unless}}
+ <DButton
+ @action={{this.cutSelection}}
+ @icon="scissors"
+ @translatedLabel={{i18n "discourse_workflows.canvas.cut"}}
+ class="btn-transparent workflows-canvas__context-menu-item"
+ />
+ <DButton
+ @action={{this.copySelection}}
+ @icon="copy"
+ @translatedLabel={{i18n "discourse_workflows.canvas.copy"}}
+ class="btn-transparent workflows-canvas__context-menu-item"
+ />
+ <DButton
+ @action={{this.pasteSelection}}
+ @icon="paste"
+ @translatedLabel={{i18n "discourse_workflows.canvas.paste"}}
+ class="btn-transparent workflows-canvas__context-menu-item"
+ />
<DButton
@action={{this.deleteNode}}
@icon="trash-can"
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-keyboard.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-keyboard.js
index e6180966c81..4afd98afef5 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-keyboard.js
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-keyboard.js
@@ -1,7 +1,13 @@
const PAUSED_SHORTCUTS = ["-", "="];
function isInputElement(target) {
- return target.tagName === "INPUT" || target.tagName === "TEXTAREA";
+ return (
+ target.tagName === "INPUT" ||
+ target.tagName === "TEXTAREA" ||
+ target.tagName === "SELECT" ||
+ target.isContentEditable ||
+ target.closest?.("[contenteditable='true']")
+ );
}
export function setupCanvasKeyboard(
@@ -24,8 +30,14 @@ export function setupCanvasKeyboard(
e.preventDefault();
actions.onRedo?.();
},
- "meta::c": () => actions.onCopy?.(),
- "meta::v": () => actions.onPaste?.(),
+ "meta::c": (e) => {
+ e.preventDefault();
+ actions.onCopy?.();
+ },
+ "meta::x": (e) => {
+ e.preventDefault();
+ actions.onCut?.();
+ },
"::delete": () => actions.onDelete?.(),
"::backspace": () => actions.onDelete?.(),
"::escape": () => actions.onEscape?.(),
@@ -52,11 +64,43 @@ export function setupCanvasKeyboard(
binding?.(event);
};
+ const pasteHandler = (event) => {
+ if (isInputElement(event.target)) {
+ return;
+ }
+
+ actions.onPaste?.(event);
+ };
+
+ const copyHandler = (event) => {
+ if (isInputElement(event.target)) {
+ return;
+ }
+
+ event.preventDefault();
+ actions.onCopy?.();
+ };
+
+ const cutHandler = (event) => {
+ if (isInputElement(event.target)) {
+ return;
+ }
+
+ event.preventDefault();
+ actions.onCut?.();
+ };
+
canvasElement.addEventListener("keydown", handler);
+ canvasElement.addEventListener("paste", pasteHandler);
+ canvasElement.addEventListener("copy", copyHandler);
+ canvasElement.addEventListener("cut", cutHandler);
return {
teardown() {
canvasElement.removeEventListener("keydown", handler);
+ canvasElement.removeEventListener("paste", pasteHandler);
+ canvasElement.removeEventListener("copy", copyHandler);
+ canvasElement.removeEventListener("cut", cutHandler);
try {
keyboardShortcutsService.unpause(PAUSED_SHORTCUTS);
} catch {
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-sticky-notes.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-sticky-notes.js
index 27963a1dbaf..836970aaea9 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-sticky-notes.js
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-sticky-notes.js
@@ -1,5 +1,6 @@
export function computeStickyNoteRects(stickyNotes) {
return (stickyNotes || []).map((n) => ({
+ clientId: n.clientId,
x: n.position.x,
y: n.position.y,
width: n.size.width,
@@ -7,9 +8,17 @@ export function computeStickyNoteRects(stickyNotes) {
}));
}
-export function buildStickyNoteTranslateHandler(stickyNotes, onMove) {
+function resolveStickyNotes(stickyNotesOrGetter) {
+ return typeof stickyNotesOrGetter === "function"
+ ? stickyNotesOrGetter()
+ : stickyNotesOrGetter;
+}
+
+export function buildStickyNoteTranslateHandler(stickyNotesOrGetter, onMove) {
return (id, dx, dy) => {
- const note = (stickyNotes || []).find((n) => n.clientId === id);
+ const note = (resolveStickyNotes(stickyNotesOrGetter) || []).find(
+ (n) => n.clientId === id
+ );
if (note) {
onMove?.(id, {
x: note.position.x + dx,
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/index.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/index.gjs
index 8a0ddb07b3e..7a49c0d6378 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/index.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/index.gjs
@@ -10,11 +10,20 @@ import { trustHTML } from "@ember/template";
import DMenu from "discourse/float-kit/components/d-menu";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
+import { clipboardCopy } from "discourse/lib/utilities";
import DButton from "discourse/ui-kit/d-button";
import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
import BuildWithAiModal from "../build-with-ai-modal";
+import {
+ buildCanvasClipboardPayload,
+ isSerializedCanvasClipboardPayload,
+ parseCanvasClipboardText,
+ payloadForCanvasClipboardPaste,
+ positionCanvasClipboardPayload,
+ serializeCanvasClipboardPayload,
+} from "./canvas-clipboard";
import CanvasContextMenu from "./canvas-context-menu";
import { exportWorkflowToFile, parseWorkflowImport } from "./canvas-file-io";
import { setupCanvasKeyboard } from "./canvas-keyboard";
@@ -46,7 +55,9 @@ export default class WorkflowCanvas extends Component {
@tracked hasUnpublishedChangesOverride = null;
@tracked selectionVersion = 0;
@tracked aiPanelOpen = false;
- copiedEntities = { nodes: [], stickyNotes: [] };
+ clipboardPayload = null;
+ serializedClipboardPayload = null;
+ clipboardWritePending = false;
pasteOffset = 0;
isFirstSync = true;
lastAutoArrangeRequest = 0;
@@ -232,8 +243,9 @@ export default class WorkflowCanvas extends Component {
return {
onUndo: () => this.args.onUndo?.(),
onRedo: () => this.args.onRedo?.(),
- onCopy: () => this.#copy(),
- onPaste: () => this.#paste(),
+ onCut: () => this.cutSelected(),
+ onCopy: () => this.copySelected(),
+ onPaste: (event) => this.handlePasteEvent(event),
onDelete: () => this.deleteSelected(),
onEscape: () => {
this.contextMenuApi?.close();
@@ -272,6 +284,8 @@ export default class WorkflowCanvas extends Component {
this.menu.close("workflows-canvas-menu");
this.args.onCloseNodePanel?.();
},
+ onSelectionDragFinished: (selectionRect) =>
+ this.#selectStickyNotesInRect(selectionRect),
onNodeDragEnd: () => this.args.onNodeDragEnd?.(),
onConnectionCreated: (...a) => this.args.onCreateConnection?.(...a),
onNodeDelete: (clientId) => this.args.onRemoveNodes?.([clientId]),
@@ -293,6 +307,37 @@ export default class WorkflowCanvas extends Component {
return computeStickyNoteRects(this.args.stickyNotes);
}
+ async #selectStickyNotesInRect(selectionRect) {
+ for (const noteRect of this.#stickyNoteRects()) {
+ if (this.#rectsIntersect(noteRect, selectionRect)) {
+ await this.rete.selectStickyNote(
+ noteRect.clientId,
+ {
+ onStickyNoteTranslate: buildStickyNoteTranslateHandler(
+ () => this.args.stickyNotes,
+ this.args.onStickyNoteMove
+ ),
+ onStickyNoteUnselect: () => {
+ this.selectionVersion++;
+ },
+ },
+ { accumulate: true }
+ );
+ }
+ }
+
+ this.selectionVersion++;
+ }
+
+ #rectsIntersect(rect, selectionRect) {
+ return !(
+ rect.x + rect.width < selectionRect.left ||
+ rect.x > selectionRect.right ||
+ rect.y + rect.height < selectionRect.top ||
+ rect.y > selectionRect.bottom
+ );
+ }
+
#shouldHydrateInitialAutoLayout(nodes) {
return (
!this.didHydrateInitialAutoLayout && nodes.some((node) => !node.position)
@@ -524,7 +569,7 @@ export default class WorkflowCanvas extends Component {
async selectStickyNote(clientId) {
await this.rete.selectStickyNote(clientId, {
onStickyNoteTranslate: buildStickyNoteTranslateHandler(
- this.args.stickyNotes,
+ () => this.args.stickyNotes,
this.args.onStickyNoteMove
),
onStickyNoteUnselect: () => {
@@ -534,35 +579,176 @@ export default class WorkflowCanvas extends Component {
this.selectionVersion++;
}
- #copy() {
- const { nodeIds, stickyNoteIds } = this.rete.getSelectedIds();
- const cloneMatching = (items, ids) =>
- (items || []).filter((n) => ids.has(n.clientId)).map(structuredClone);
- const nodes = cloneMatching(this.args.nodes, nodeIds);
- const stickyNotes = cloneMatching(this.args.stickyNotes, stickyNoteIds);
- if (nodes.length > 0 || stickyNotes.length > 0) {
- this.copiedEntities = { nodes, stickyNotes };
- this.pasteOffset = 0;
+ #selectedIds(selection = null) {
+ if (!selection) {
+ return this.rete.getSelectedIds();
+ }
+
+ return {
+ nodeIds: new Set(selection.nodeIds || []),
+ stickyNoteIds: new Set(selection.stickyNoteIds || []),
+ };
+ }
+
+ #selectedClipboardPayload(selection = null) {
+ return buildCanvasClipboardPayload(
+ {
+ nodes: this.args.nodes || [],
+ connections: this.args.connections || [],
+ stickyNotes: this.args.stickyNotes || [],
+ },
+ this.#selectedIds(selection)
+ );
+ }
+
+ #storeClipboardPayload(payload) {
+ this.clipboardPayload = payload;
+ this.serializedClipboardPayload = serializeCanvasClipboardPayload(payload);
+ this.pasteOffset = 0;
+ }
+
+ async #writeClipboardPayload() {
+ this.clipboardWritePending = true;
+
+ try {
+ await clipboardCopy(this.serializedClipboardPayload);
+ } catch {
+ this.toasts.warning({
+ data: {
+ message: i18n("discourse_workflows.canvas.clipboard_unavailable"),
+ },
+ });
+ } finally {
+ this.clipboardWritePending = false;
+ }
+ }
+
+ #showNothingToPaste() {
+ this.toasts.info({
+ data: { message: i18n("discourse_workflows.canvas.nothing_to_paste") },
+ });
+ }
+
+ #copySelectedPayload(selection = null) {
+ const payload = this.#selectedClipboardPayload(selection);
+
+ if (!payload) {
+ return null;
}
+
+ this.#storeClipboardPayload(payload);
+ void this.#writeClipboardPayload();
+
+ return payload;
+ }
+
+ @action
+ copySelected(selection = null) {
+ this.contextMenuApi?.close();
+ this.#copySelectedPayload(selection);
}
- #paste() {
- const { nodes, stickyNotes } = this.copiedEntities;
- if (nodes.length === 0 && stickyNotes.length === 0) {
+ @action
+ cutSelected(selection = null) {
+ this.contextMenuApi?.close();
+ const selectedIds = this.#selectedIds(selection);
+
+ if (!this.#copySelectedPayload(selectedIds)) {
return;
}
- this.pasteOffset += 20;
- const offset = this.pasteOffset;
- const shift = (items) =>
- items.map((item) => ({
- ...item,
- position: item.position
- ? { x: item.position.x + offset, y: item.position.y + offset }
- : null,
- }));
- this.args.onPasteEntities?.({
- nodes: shift(nodes),
- stickyNotes: shift(stickyNotes),
+
+ this.args.onCutSelected?.({
+ nodeIds: [...selectedIds.nodeIds],
+ stickyNoteIds: [...selectedIds.stickyNoteIds],
+ });
+ this.rete.selector.unselectAll();
+ this.selectionVersion++;
+ }
+
+ #positionedPayload(payload, { target = null, useSourceOffset = false } = {}) {
+ const sourceOffset = useSourceOffset ? (this.pasteOffset += 20) : 0;
+
+ return positionCanvasClipboardPayload(payload, { target, sourceOffset });
+ }
+
+ #pastePayload(payload, options = {}) {
+ if (!this.rete) {
+ return;
+ }
+
+ this.args.onPasteEntities?.(this.#positionedPayload(payload, options));
+ }
+
+ async #readClipboardPayload() {
+ if (!navigator.clipboard?.readText) {
+ return { payload: null, didRead: false };
+ }
+
+ try {
+ const text = await navigator.clipboard.readText();
+ return {
+ payload: parseCanvasClipboardText(text),
+ didRead: true,
+ isLocal: isSerializedCanvasClipboardPayload(
+ text,
+ this.serializedClipboardPayload
+ ),
+ };
+ } catch {
+ return { payload: null, didRead: false };
+ }
+ }
+
+ @action
+ handlePasteEvent(event) {
+ if (!this.rete) {
+ return;
+ }
+
+ const text = event.clipboardData?.getData("text/plain");
+ const payload = this.clipboardWritePending
+ ? null
+ : parseCanvasClipboardText(text);
+ const useLocalPayload = !payload && this.clipboardPayload;
+ const pastePayload = payloadForCanvasClipboardPaste(
+ payload,
+ useLocalPayload ? this.clipboardPayload : null
+ );
+
+ if (!pastePayload) {
+ return;
+ }
+
+ event.preventDefault();
+ const isLocal =
+ useLocalPayload ||
+ isSerializedCanvasClipboardPayload(text, this.serializedClipboardPayload);
+
+ this.#pastePayload(pastePayload, {
+ target: isLocal ? null : this.rete.viewportCenter(),
+ useSourceOffset: isLocal,
+ });
+ }
+
+ @action
+ async pasteFromClipboard(target = null) {
+ this.contextMenuApi?.close();
+ const result = await this.#readClipboardPayload();
+ const systemPayload = this.clipboardWritePending ? null : result.payload;
+ const useLocalPayload = !systemPayload && this.clipboardPayload;
+ const payload = payloadForCanvasClipboardPaste(
+ systemPayload,
+ useLocalPayload ? this.clipboardPayload : null
+ );
+
+ if (!payload) {
+ this.#showNothingToPaste();
+ return;
+ }
+
+ this.#pastePayload(payload, {
+ target,
+ useSourceOffset: !target && (result.isLocal || useLocalPayload),
});
}
@@ -583,17 +769,36 @@ export default class WorkflowCanvas extends Component {
@action
async translateSelected(draggedClientId, dx, dy) {
+ const { stickyNoteIds } = this.rete.getSelectedIds();
+
+ for (const stickyNoteId of stickyNoteIds) {
+ if (stickyNoteId === draggedClientId) {
+ continue;
+ }
+
+ const note = (this.args.stickyNotes || []).find(
+ (stickyNote) => stickyNote.clientId === stickyNoteId
+ );
+ if (note) {
+ this.args.onStickyNoteMove?.(stickyNoteId, {
+ x: note.position.x + dx,
+ y: note.position.y + dy,
+ });
+ }
+ }
+
await this.rete.translateSelectedEntities(
draggedClientId,
"sticky-note",
dx,
- dy
+ dy,
+ { labels: ["node"] }
);
}
@action
- deleteSelected() {
- const { nodeIds, stickyNoteIds } = this.rete.getSelectedIds();
+ deleteSelected(selection = null) {
+ const { nodeIds, stickyNoteIds } = this.#selectedIds(selection);
if (nodeIds.size > 0 || stickyNoteIds.size > 0) {
this.args.onRemoveSelected?.({
nodeIds: [...nodeIds],
@@ -987,6 +1192,9 @@ export default class WorkflowCanvas extends Component {
@rete={{this.rete}}
@onEditNode={{@onEditNode}}
@onDeleteSelected={{this.deleteSelected}}
+ @onCut={{this.cutSelected}}
+ @onCopy={{this.copySelected}}
+ @onPaste={{this.pasteFromClipboard}}
@onOpenNodePanel={{@onOpenNodePanel}}
@onAddStickyNote={{@onAddStickyNote}}
@onRegister={{this.registerContextMenu}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/rete-editor.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/rete-editor.js
index ed8df040091..62640ef30f1 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/rete-editor.js
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/rete-editor.js
@@ -126,10 +126,15 @@ export class ReteEditorBridge {
class ToggleSelector extends AreaExtensions.Selector {
async add(entity, accumulate) {
- if (accumulate && this.entities.has(`${entity.label}_${entity.id}`)) {
- await this.remove(entity);
+ const entityKey = `${entity.label}_${entity.id}`;
+
+ if (this.entities.has(entityKey)) {
+ if (accumulate) {
+ await this.remove(entity);
+ }
return;
}
+
await super.add(entity, accumulate);
}
}
@@ -167,7 +172,12 @@ export class ReteEditorBridge {
area.addPipe((context) => {
if (context.type === "pointerdown") {
- const target = context.data.event.target;
+ const event = context.data.event;
+ if (event.button !== 0) {
+ return;
+ }
+
+ const target = event.target;
if (target?.closest?.(".workflow-sticky-note")) {
return;
}
@@ -254,17 +264,25 @@ export class ReteEditorBridge {
this.isSyncing = false;
this.isAutoArranging = false;
this.wasDragging = false;
+ this.selectionDrag = null;
+ this.selectionBoxElement = null;
this.lastPickedId = null;
this.lastPickedTime = 0;
}
setupPipes() {
- this.area.addPipe((context) => {
+ this.area.addPipe(async (context) => {
if (this.isSyncing || this.isAutoArranging) {
return context;
}
switch (context.type) {
+ case "translate":
+ if (this.selectionDrag) {
+ return;
+ }
+ break;
+
case "nodetranslated":
this.callbacks.onNodeDragged?.(
context.data.id,
@@ -299,7 +317,19 @@ export class ReteEditorBridge {
break;
}
+ case "pointermove":
+ if (this.selectionDrag) {
+ this.updateSelectionDrag(context.data);
+ return;
+ }
+ break;
+
case "pointerup":
+ if (this.selectionDrag) {
+ await this.finishSelectionDrag(context.data);
+ return;
+ }
+
if (this.wasDragging) {
this.wasDragging = false;
this.container.classList.remove("is-dragging");
@@ -311,6 +341,10 @@ export class ReteEditorBridge {
const target = context.data.event.target;
if (!target?.closest?.(".workflow-rete-node")) {
this.callbacks.onCanvasPointerDown?.(context.data.event);
+ if (this.canStartSelectionDrag(context.data.event)) {
+ this.startSelectionDrag(context.data);
+ return;
+ }
}
break;
}
@@ -394,6 +428,123 @@ export class ReteEditorBridge {
}
}
+ pointerPosition(data) {
+ const event = data.event;
+
+ if (Number.isFinite(event?.clientX) && Number.isFinite(event?.clientY)) {
+ const rect = this.container.getBoundingClientRect();
+ return {
+ x: event.clientX - rect.left,
+ y: event.clientY - rect.top,
+ };
+ }
+
+ return {
+ x: data.position.x * this.transform.k + this.transform.x,
+ y: data.position.y * this.transform.k + this.transform.y,
+ };
+ }
+
+ canStartSelectionDrag(event) {
+ return (
+ event?.button === 0 &&
+ !event.ctrlKey &&
+ !event.metaKey &&
+ !event.shiftKey &&
+ !event.target?.closest?.(
+ "button,a,input,textarea,select,.workflow-sticky-note,.workflows-canvas__controls,.workflows-canvas__top-bar"
+ )
+ );
+ }
+
+ startSelectionDrag(data) {
+ const start = this.pointerPosition(data);
+ this.selectionBoxElement?.remove();
+ this.selectionDrag = { start, current: start };
+ this.container.classList.add("is-selecting");
+ this.selectionBoxElement = document.createElement("div");
+ this.selectionBoxElement.className = "workflows-canvas__selection-box";
+ this.container.appendChild(this.selectionBoxElement);
+ this.updateSelectionBox();
+ }
+
+ updateSelectionDrag(data) {
+ this.selectionDrag.current = this.pointerPosition(data);
+ this.updateSelectionBox();
+ }
+
+ updateSelectionBox() {
+ const { start, current } = this.selectionDrag;
+ const left = Math.min(start.x, current.x);
+ const top = Math.min(start.y, current.y);
+ const width = Math.abs(current.x - start.x);
+ const height = Math.abs(current.y - start.y);
+
+ Object.assign(this.selectionBoxElement.style, {
+ left: `${left}px`,
+ top: `${top}px`,
+ width: `${width}px`,
+ height: `${height}px`,
+ });
+ }
+
+ async finishSelectionDrag(data) {
+ this.updateSelectionDrag(data);
+ const { start, current } = this.selectionDrag;
+ const distance = Math.hypot(current.x - start.x, current.y - start.y);
+
+ this.selectionBoxElement?.remove();
+ this.selectionBoxElement = null;
+ this.selectionDrag = null;
+ this.container.classList.remove("is-selecting");
+
+ await this.selector.unselectAll();
+
+ if (distance < 4) {
+ return;
+ }
+
+ const startCanvas = this.containerToCanvas(start.x, start.y);
+ const currentCanvas = this.containerToCanvas(current.x, current.y);
+ const selectionRect = {
+ left: Math.min(startCanvas.canvasX, currentCanvas.canvasX),
+ right: Math.max(startCanvas.canvasX, currentCanvas.canvasX),
+ top: Math.min(startCanvas.canvasY, currentCanvas.canvasY),
+ bottom: Math.max(startCanvas.canvasY, currentCanvas.canvasY),
+ };
+
+ for (const node of this.editor.getNodes()) {
+ if (this.nodeIntersectsSelection(node, selectionRect)) {
+ await this.selectableNodes.select(node.id, true);
+ }
+ }
+
+ await this.callbacks.onSelectionDragFinished?.(selectionRect);
+ }
+
+ nodeIntersectsSelection(node, selectionRect) {
+ const view = this.area.nodeViews.get(node.id);
+ if (!view) {
+ return false;
+ }
+
+ const width = node.width || this.getNodeWidth(node.workflowData || node);
+ const height = node.height || this.getNodeHeight(node.workflowData || node);
+ const nodeRect = {
+ left: view.position.x,
+ right: view.position.x + width,
+ top: view.position.y,
+ bottom: view.position.y + height,
+ };
+
+ return !(
+ nodeRect.right < selectionRect.left ||
+ nodeRect.left > selectionRect.right ||
+ nodeRect.bottom < selectionRect.top ||
+ nodeRect.top > selectionRect.bottom
+ );
+ }
+
getSelectedIds() {
const nodeIds = new Set();
const stickyNoteIds = new Set();
@@ -407,8 +558,11 @@ export class ReteEditorBridge {
return { nodeIds, stickyNoteIds };
}
- async selectStickyNote(clientId, stickyCallbacks) {
- const accumulate = this.accumulating.active();
+ async selectStickyNote(
+ clientId,
+ stickyCallbacks,
+ { accumulate = this.accumulating.active() } = {}
+ ) {
const entityKey = `sticky-note_${clientId}`;
if (this.selector.entities.has(entityKey)) {
@@ -436,8 +590,17 @@ export class ReteEditorBridge {
return this.selector.entities.has(`sticky-note_${clientId}`);
}
- async translateSelectedEntities(draggedId, draggedLabel, dx, dy) {
+ async translateSelectedEntities(
+ draggedId,
+ draggedLabel,
+ dx,
+ dy,
+ { labels = null } = {}
+ ) {
for (const entity of this.selector.entities.values()) {
+ if (labels && !labels.includes(entity.label)) {
+ continue;
+ }
if (entity.id === draggedId && entity.label === draggedLabel) {
continue;
}
@@ -952,6 +1115,10 @@ export class ReteEditorBridge {
}
destroy() {
+ this.container.classList.remove("is-selecting");
+ this.selectionBoxElement?.remove();
+ this.selectionBoxElement = null;
+ this.selectionDrag = null;
this.shiftAbort?.abort();
this.renderer.cancelScheduledConnectionUpdate();
this.renderer.destroyMeasureSvg();
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/sticky-note.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/sticky-note.gjs
index f74c0430d5d..1d7b133e3f0 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/sticky-note.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/sticky-note.gjs
@@ -4,7 +4,7 @@ import { fn } from "@ember/helper";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
import { trustHTML } from "@ember/template";
-import DMenu from "discourse/float-kit/components/d-menu";
+import { modifier } from "ember-modifier";
import DTooltip from "discourse/float-kit/components/d-tooltip";
import { eq } from "discourse/truth-helpers";
import DCookText from "discourse/ui-kit/d-cook-text";
@@ -34,11 +34,34 @@ function stopPropagation(event) {
event.stopPropagation();
}
+const registerStickyNoteElement = modifier((element, [component]) => {
+ component.stickyNoteElement = element;
+
+ return () => {
+ if (component.stickyNoteElement === element) {
+ component.stickyNoteElement = null;
+ }
+ };
+});
+
export default class StickyNote extends Component {
@tracked isEditing = false;
+ @tracked colorPickerOpen = false;
+ stickyNoteElement = null;
colorOptions = COLORS;
resizeEdges = RESIZE_EDGES;
+ handleDocumentClick = (event) => {
+ if (!this.stickyNoteElement?.contains(event.target)) {
+ this.closeColorPicker();
+ }
+ };
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.closeColorPicker();
+ }
+
get style() {
const { position, size, color } = this.args.note;
const match = COLORS.find((c) => c.name === color) || COLORS[0];
@@ -51,6 +74,29 @@ export default class StickyNote extends Component {
);
}
+ openColorPicker() {
+ if (this.colorPickerOpen) {
+ return;
+ }
+
+ this.colorPickerOpen = true;
+
+ requestAnimationFrame(() => {
+ if (this.colorPickerOpen) {
+ document.addEventListener("click", this.handleDocumentClick);
+ }
+ });
+ }
+
+ closeColorPicker() {
+ if (!this.colorPickerOpen) {
+ return;
+ }
+
+ this.colorPickerOpen = false;
+ document.removeEventListener("click", this.handleDocumentClick);
+ }
+
#startDrag(event, { onMove, onEnd }) {
event.stopPropagation();
event.preventDefault();
@@ -169,9 +215,22 @@ export default class StickyNote extends Component {
}
@action
- selectColor(colorName, close) {
+ toggleColorPicker(event) {
+ event.preventDefault();
+
+ if (this.colorPickerOpen) {
+ this.closeColorPicker();
+ } else {
+ this.openColorPicker();
+ }
+ }
+
+ @action
+ selectColor(colorName, event) {
+ event?.preventDefault();
+ event?.stopPropagation();
this.args.onChangeColor?.(colorName);
- close();
+ this.closeColorPicker();
this.args.onAfterMutation?.();
}
@@ -189,6 +248,7 @@ export default class StickyNote extends Component {
(if @isSelected "is-selected")
}}
style={{this.style}}
+ {{registerStickyNoteElement this}}
{{on "pointerdown" this.handlePointerDown}}
{{on "dblclick" this.startEditing}}
>
@@ -198,34 +258,15 @@ export default class StickyNote extends Component {
@content={{i18n "discourse_workflows.sticky_note.change_color"}}
>
<:trigger>
- <DMenu
- @identifier="sticky-note-color-picker"
- @inline={{true}}
+ <button
+ type="button"
class="workflow-canvas-toolbar__btn"
+ aria-expanded={{if this.colorPickerOpen "true" "false"}}
+ {{on "pointerdown" stopPropagation}}
+ {{on "click" this.toggleColorPicker}}
>
- <:trigger>
- {{dIcon "palette"}}
- </:trigger>
- <:content as |args|>
- <div class="workflow-sticky-note__color-picker">
- {{#each this.colorOptions as |colorOpt|}}
- <button
- type="button"
- class={{dConcatClass
- "workflow-sticky-note__color-swatch"
- (if (eq @note.color colorOpt.name) "is-active")
- }}
- style={{swatchStyle colorOpt.bg}}
- title={{colorOpt.name}}
- {{on
- "click"
- (fn this.selectColor colorOpt.name args.close)
- }}
- />
- {{/each}}
- </div>
- </:content>
- </DMenu>
+ {{dIcon "palette"}}
+ </button>
</:trigger>
</DTooltip>
<DTooltip
@@ -245,6 +286,26 @@ export default class StickyNote extends Component {
</DTooltip>
</CanvasHoverToolbar>
+ {{#if this.colorPickerOpen}}
+ <div
+ class="workflow-sticky-note__color-picker"
+ {{on "pointerdown" stopPropagation}}
+ >
+ {{#each this.colorOptions as |colorOpt|}}
+ <button
+ type="button"
+ class={{dConcatClass
+ "workflow-sticky-note__color-swatch"
+ (if (eq @note.color colorOpt.name) "is-active")
+ }}
+ style={{swatchStyle colorOpt.bg}}
+ title={{colorOpt.name}}
+ {{on "click" (fn this.selectColor colorOpt.name)}}
+ />
+ {{/each}}
+ </div>
+ {{/if}}
+
<div class="workflow-sticky-note__content">
{{#if this.isEditing}}
<textarea
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/graph-utils.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/graph-utils.js
index c90cf2973f6..c8a7b3d22b7 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/graph-utils.js
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/graph-utils.js
@@ -228,13 +228,34 @@ function reconnectLoopNode(connections, loopNodeClientId, idsToRemove) {
);
}
-export function removeNodesFromGraph(nodes, connections, clientIds) {
+export function removeNodesFromGraph(
+ nodes,
+ connections,
+ clientIds,
+ { reconnect = true } = {}
+) {
const idsToRemove = new Set(clientIds);
if (idsToRemove.size === 0) {
return { nodes, connections };
}
+ const remainingNodes = nodes.filter(
+ (node) => !idsToRemove.has(node.clientId)
+ );
+ const remainingConnections = connections.filter(
+ (connection) =>
+ !idsToRemove.has(connection.sourceClientId) &&
+ !idsToRemove.has(connection.targetClientId)
+ );
+
+ if (!reconnect) {
+ return {
+ nodes: remainingNodes,
+ connections: remainingConnections,
+ };
+ }
+
const reconnects = [];
for (const node of nodes) {
@@ -253,15 +274,6 @@ export function removeNodesFromGraph(nodes, connections, clientIds) {
}
}
- const remainingNodes = nodes.filter(
- (node) => !idsToRemove.has(node.clientId)
- );
- const remainingConnections = connections.filter(
- (connection) =>
- !idsToRemove.has(connection.sourceClientId) &&
- !idsToRemove.has(connection.targetClientId)
- );
-
return {
nodes: remainingNodes,
connections: dedupeConnections([...remainingConnections, ...reconnects]),
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/index.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/index.gjs
index f770da8f87f..8628632d14d 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/index.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/index.gjs
@@ -71,6 +71,58 @@ function shouldHideTriggerNodeTypes(context, nodes) {
return isTriggerType(sourceNode?.type);
}
+export function buildPastedGraph({
+ existingNodes,
+ existingConnections,
+ copiedNodes = [],
+ copiedConnections = [],
+ nodeTypeFor = (node) => node?.type,
+}) {
+ const newNodes = [];
+ const remappedClientIds = new Map();
+
+ for (const copiedNode of copiedNodes) {
+ const newNode = WorkflowNode.create({
+ type: copiedNode.type,
+ typeVersion: copiedNode.typeVersion,
+ name: generateNodeName(copiedNode.type, [...existingNodes, ...newNodes]),
+ configuration: structuredClone(copiedNode.configuration || {}),
+ position: copiedNode.position
+ ? { x: copiedNode.position.x, y: copiedNode.position.y }
+ : null,
+ });
+ remappedClientIds.set(copiedNode.clientId, newNode.clientId);
+ newNodes.push(newNode);
+ }
+
+ const updatedNodes = [...existingNodes, ...newNodes];
+ const remappedConnections = copiedConnections.flatMap((connection) => {
+ const sourceClientId = remappedClientIds.get(connection.sourceClientId);
+ const targetClientId = remappedClientIds.get(connection.targetClientId);
+
+ if (!sourceClientId || !targetClientId) {
+ return [];
+ }
+
+ return [
+ {
+ ...structuredClone(connection),
+ sourceClientId,
+ targetClientId,
+ },
+ ];
+ });
+
+ return {
+ updatedNodes,
+ updatedConnections: normalizeConnectionsForNodes(
+ [...existingConnections, ...remappedConnections],
+ updatedNodes,
+ nodeTypeFor
+ ),
+ };
+}
+
export default class WorkflowsEditor extends Component {
@service router;
@service dialog;
@@ -495,16 +547,28 @@ export default class WorkflowsEditor extends Component {
return nextAvailableTargetInputIndex(connections, targetClientId);
}
+ #showMaxNodesReached() {
+ this.toasts.error({
+ data: {
+ message: i18n("discourse_workflows.canvas.max_nodes_reached", {
+ max: MAX_NODES,
+ }),
+ },
+ });
+ }
+
+ #canAddNodes(count, existingNodes = this.formApi.get("nodes")) {
+ if (existingNodes.length + count <= MAX_NODES) {
+ return true;
+ }
+
+ this.#showMaxNodesReached();
+ return false;
+ }
+
#addNewNode(nodeType, position, configOverrides, wireConnections) {
const existingNodes = this.formApi.get("nodes");
- if (existingNodes.length >= MAX_NODES) {
- this.toasts.error({
- data: {
- message: i18n("discourse_workflows.canvas.max_nodes_reached", {
- max: MAX_NODES,
- }),
- },
- });
+ if (!this.#canAddNodes(1, existingNodes)) {
return;
}
this.#captureUndo();
@@ -880,13 +944,23 @@ export default class WorkflowsEditor extends Component {
@action
removeSelected({ nodeIds, stickyNoteIds }) {
+ this.#removeSelected({ nodeIds, stickyNoteIds });
+ }
+
+ @action
+ cutSelected({ nodeIds, stickyNoteIds }) {
+ this.#removeSelected({ nodeIds, stickyNoteIds }, { reconnect: false });
+ }
+
+ #removeSelected({ nodeIds, stickyNoteIds }, { reconnect = true } = {}) {
this.#captureUndo();
if (nodeIds.length > 0) {
const updatedGraph = removeNodesFromGraph(
this.formApi.get("nodes"),
this.formApi.get("connections"),
- nodeIds
+ nodeIds,
+ { reconnect }
);
this.formApi.set("nodes", updatedGraph.nodes);
this.formApi.set("connections", updatedGraph.connections);
@@ -907,14 +981,7 @@ export default class WorkflowsEditor extends Component {
@action
addNodeToLoop(loopNodeClientId, nodeType, configOverrides = null) {
const existingNodes = this.formApi.get("nodes");
- if (existingNodes.length >= MAX_NODES) {
- this.toasts.error({
- data: {
- message: i18n("discourse_workflows.canvas.max_nodes_reached", {
- max: MAX_NODES,
- }),
- },
- });
+ if (!this.#canAddNodes(1, existingNodes)) {
return;
}
this.#captureUndo();
@@ -1061,14 +1128,7 @@ export default class WorkflowsEditor extends Component {
@action
importNodes(newNodes, newConnections, newStickyNotes, staticData) {
const existingNodes = this.formApi.get("nodes");
- if (existingNodes.length + newNodes.length > MAX_NODES) {
- this.toasts.error({
- data: {
- message: i18n("discourse_workflows.canvas.max_nodes_reached", {
- max: MAX_NODES,
- }),
- },
- });
+ if (!this.#canAddNodes(newNodes.length, existingNodes)) {
return;
}
this.#captureUndo();
@@ -1176,23 +1236,29 @@ export default class WorkflowsEditor extends Component {
}
@action
- pasteEntities({ nodes, stickyNotes }) {
+ pasteEntities({ nodes = [], connections = [], stickyNotes = [] }) {
+ if (nodes.length === 0 && stickyNotes.length === 0) {
+ return;
+ }
+
+ const existingNodes = this.formApi.get("nodes");
+ if (!this.#canAddNodes(nodes.length, existingNodes)) {
+ return;
+ }
+
this.#captureUndo();
if (nodes.length > 0) {
- const existingNodes = this.formApi.get("nodes");
- const newNodes = nodes.map((copiedNode) =>
- WorkflowNode.create({
- type: copiedNode.type,
- typeVersion: copiedNode.typeVersion,
- name: generateNodeName(copiedNode.type, existingNodes),
- configuration: structuredClone(copiedNode.configuration || {}),
- position: copiedNode.position
- ? { x: copiedNode.position.x, y: copiedNode.position.y }
- : null,
- })
- );
- this.formApi.set("nodes", [...existingNodes, ...newNodes]);
+ const { updatedNodes, updatedConnections } = buildPastedGraph({
+ existingNodes,
+ existingConnections: this.formApi.get("connections"),
+ copiedNodes: nodes,
+ copiedConnections: connections,
+ nodeTypeFor: (node) => this.#nodeTypeFor(node),
+ });
+
+ this.formApi.set("nodes", updatedNodes);
+ this.formApi.set("connections", updatedConnections);
}
if (stickyNotes.length > 0) {
@@ -1540,6 +1606,7 @@ export default class WorkflowsEditor extends Component {
@onStickyNoteUpdateText={{this.stickyNoteUpdateText}}
@onStickyNoteChangeColor={{this.stickyNoteChangeColor}}
@onRemoveSelected={{this.removeSelected}}
+ @onCutSelected={{this.cutSelected}}
@onPasteEntities={{this.pasteEntities}}
@workflow={{@workflow}}
@session={{this.workflowSession}}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss b/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss
index 5e413c0867e..d024d724b5e 100644
--- a/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss
+++ b/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss
@@ -97,9 +97,13 @@
&__rete-container {
width: 100%;
height: 100%;
- cursor: grab;
+ cursor: default;
- &:active {
+ &.is-selecting {
+ cursor: crosshair;
+ }
+
+ &.is-dragging {
cursor: grabbing;
}
@@ -108,6 +112,15 @@
}
}
+ &__selection-box {
+ position: absolute;
+ z-index: calc(var(--z-canvas-elements) + 3);
+ pointer-events: none;
+ border: 1px solid var(--tertiary);
+ background: rgb(var(--tertiary-rgb), 0.14);
+ border-radius: 2px;
+ }
+
&__controls {
position: absolute;
bottom: var(--space-2);
@@ -333,7 +346,10 @@
&.is-selected &__icon-block {
border-color: var(--tertiary);
- box-shadow: 0 0 0 1px var(--tertiary);
+ background: color-mix(in srgb, var(--tertiary) 12%, var(--secondary));
+ box-shadow:
+ 0 0 0 2px var(--secondary),
+ 0 0 0 5px var(--tertiary);
}
@media (prefers-reduced-motion: no-preference) {
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/canvas/hover-toolbar.scss b/plugins/discourse-workflows/assets/stylesheets/common/canvas/hover-toolbar.scss
index 1bfd8c32894..90d2c5ac2cd 100644
--- a/plugins/discourse-workflows/assets/stylesheets/common/canvas/hover-toolbar.scss
+++ b/plugins/discourse-workflows/assets/stylesheets/common/canvas/hover-toolbar.scss
@@ -9,6 +9,7 @@
opacity: 0;
pointer-events: none;
transition: opacity 0.15s;
+ z-index: calc(var(--z-canvas-elements) + 2);
&.is-visible {
opacity: 1;
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/canvas/sticky-note.scss b/plugins/discourse-workflows/assets/stylesheets/common/canvas/sticky-note.scss
index 99ffe1ed30a..62f7bdd872b 100644
--- a/plugins/discourse-workflows/assets/stylesheets/common/canvas/sticky-note.scss
+++ b/plugins/discourse-workflows/assets/stylesheets/common/canvas/sticky-note.scss
@@ -1,6 +1,6 @@
.workflow-sticky-note {
position: absolute;
- z-index: -1;
+ z-index: 0;
border-radius: 4px;
box-shadow: 0 2px 8px rgb(0 0 0 / 0.12);
pointer-events: auto;
@@ -15,6 +15,15 @@
cursor: grabbing;
}
+ &:has(.workflow-sticky-note__color-picker) {
+ z-index: calc(var(--z-canvas-chrome) + 1);
+
+ .workflow-canvas-toolbar {
+ opacity: 1;
+ pointer-events: auto;
+ }
+ }
+
&.is-selected {
outline: 2px solid var(--tertiary);
outline-offset: -1px;
@@ -22,7 +31,7 @@
&__color-picker {
position: absolute;
- top: -58px;
+ top: -32px;
left: 50%;
transform: translateX(-50%);
display: flex;
@@ -33,7 +42,7 @@
border: 1px solid var(--primary-low-mid);
border-radius: var(--d-border-radius);
box-shadow: var(--shadow-dropdown);
- z-index: 10;
+ z-index: calc(var(--z-canvas-chrome) + 1);
}
&__color-swatch {
diff --git a/plugins/discourse-workflows/config/locales/client.en.yml b/plugins/discourse-workflows/config/locales/client.en.yml
index f8387215875..c0527158ed0 100644
--- a/plugins/discourse-workflows/config/locales/client.en.yml
+++ b/plugins/discourse-workflows/config/locales/client.en.yml
@@ -1115,6 +1115,12 @@ en:
redo: "Redo"
auto_layout: "Auto layout [2]"
add_step: "Add step"
+ cut: "Cut"
+ copy: "Copy"
+ paste: "Paste"
+ clipboard_text: "Discourse workflow selection. Paste this into a Discourse workflow editor to duplicate it."
+ clipboard_unavailable: "Copied for this window, but the system clipboard is unavailable."
+ nothing_to_paste: "Nothing to paste"
remove_connection: "Remove connection"
export_nodes: "Export"
import_nodes: "Import"
diff --git a/plugins/discourse-workflows/plugin.rb b/plugins/discourse-workflows/plugin.rb
index d9cbc58a0d7..d050d461630 100644
--- a/plugins/discourse-workflows/plugin.rb
+++ b/plugins/discourse-workflows/plugin.rb
@@ -47,6 +47,9 @@ register_svg_icon "user-plus"
register_svg_icon "grip-vertical"
register_svg_icon "paragraph"
register_svg_icon "arrow-down-a-z"
+register_svg_icon "copy"
+register_svg_icon "paste"
+register_svg_icon "scissors"
add_admin_route "discourse_workflows.admin.title", "discourse-workflows", use_new_show_route: true
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/canvas/canvas-context-menu-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/canvas/canvas-context-menu-test.gjs
new file mode 100644
index 00000000000..7bcc1649e99
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/canvas/canvas-context-menu-test.gjs
@@ -0,0 +1,76 @@
+import { click, render, settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import CanvasContextMenu from "discourse/plugins/discourse-workflows/admin/components/workflows/canvas/canvas-context-menu";
+
+module(
+ "Integration | Component | Workflows | Canvas | CanvasContextMenu",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.canvasElement = document.createElement("div");
+ this.containerElement = document.createElement("div");
+ this.nodeElement = document.createElement("div");
+ this.nodeElement.className = "workflow-rete-node";
+ this.nodeElement.dataset.clientId = "node-1";
+ this.nodeElement.dataset.unavailable = "false";
+
+ this.containerElement.appendChild(this.nodeElement);
+ document.getElementById("qunit-fixture").appendChild(this.canvasElement);
+ document
+ .getElementById("qunit-fixture")
+ .appendChild(this.containerElement);
+
+ this.rete = {
+ containerToCanvas: () => ({ x: 10, y: 20 }),
+ getSelectedIds: () => ({
+ nodeIds: new Set(),
+ stickyNoteIds: new Set(),
+ }),
+ selectableNodes: {
+ select: async () => {},
+ },
+ };
+ });
+
+ test("cut uses the right-clicked node when Rete selection is empty", async function (assert) {
+ this.registerContextMenu = (api) => (this.contextMenu = api);
+ this.cutSelection = (selection) => {
+ this.cutSelectionValue = selection;
+ };
+
+ await render(
+ <template>
+ <CanvasContextMenu
+ @canvasElement={{this.canvasElement}}
+ @containerElement={{this.containerElement}}
+ @rete={{this.rete}}
+ @onRegister={{this.registerContextMenu}}
+ @onCut={{this.cutSelection}}
+ />
+ </template>
+ );
+
+ await this.contextMenu.open({
+ preventDefault() {},
+ clientX: 100,
+ clientY: 100,
+ target: this.nodeElement,
+ });
+ await settled();
+
+ const cutButton = [
+ ...document.querySelectorAll(".workflows-canvas__context-menu-item"),
+ ].find((button) => button.textContent.trim() === "Cut");
+
+ await click(cutButton);
+
+ assert.deepEqual(
+ this.cutSelectionValue,
+ { nodeIds: ["node-1"], stickyNoteIds: [] },
+ "the context menu passes the node under the pointer to cut"
+ );
+ });
+ }
+);
diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas-test.js b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas-test.js
index c739e58602a..44966f4bc29 100644
--- a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas-test.js
+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas-test.js
@@ -287,4 +287,50 @@ module("Unit | Component | workflows canvas", function (hooks) {
"discard changes is hidden for an unpublished workflow"
);
});
+
+ test("translateSelected moves selected sticky notes and selected nodes", async function (assert) {
+ const movedStickyNotes = [];
+ let translatedEntities;
+ const canvas = Object.create(WorkflowCanvas.prototype);
+
+ Object.defineProperty(canvas, "args", {
+ value: {
+ stickyNotes: [
+ { clientId: "note-1", position: { x: 10, y: 20 } },
+ { clientId: "note-2", position: { x: 30, y: 40 } },
+ { clientId: "note-3", position: { x: 50, y: 60 } },
+ ],
+ onStickyNoteMove(clientId, position) {
+ movedStickyNotes.push({ clientId, position });
+ },
+ },
+ });
+ canvas.rete = {
+ getSelectedIds() {
+ return {
+ nodeIds: new Set(["node-1"]),
+ stickyNoteIds: new Set(["note-1", "note-2", "note-3"]),
+ };
+ },
+ async translateSelectedEntities(...args) {
+ translatedEntities = args;
+ },
+ };
+
+ await canvas.translateSelected("note-1", 5, 10);
+
+ assert.deepEqual(
+ movedStickyNotes,
+ [
+ { clientId: "note-2", position: { x: 35, y: 50 } },
+ { clientId: "note-3", position: { x: 55, y: 70 } },
+ ],
+ "non-dragged selected sticky notes move by the drag delta"
+ );
+ assert.deepEqual(
+ translatedEntities,
+ ["note-1", "sticky-note", 5, 10, { labels: ["node"] }],
+ "Rete translates only selected nodes for sticky-note drags"
+ );
+ });
});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-bridge-test.js b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-bridge-test.js
index d36c5b670b3..291cb04c2a7 100644
--- a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-bridge-test.js
+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-bridge-test.js
@@ -123,6 +123,200 @@ module("Unit | Canvas Bridge", function (hooks) {
bridge.destroy();
});
+ test("canvas drag selects nodes inside the selection rectangle", async function (assert) {
+ let selectionRect;
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks({
+ onSelectionDragFinished: (rect) => {
+ selectionRect = rect;
+ },
+ }),
+ nodeTypes: NODE_TYPES,
+ });
+
+ await bridge.syncState(
+ [
+ { clientId: "n1", type: "trigger:manual", position: { x: 0, y: 0 } },
+ {
+ clientId: "n2",
+ type: "action:http_request",
+ position: { x: 200, y: 0 },
+ },
+ {
+ clientId: "n3",
+ type: "action:http_request",
+ position: { x: 500, y: 0 },
+ },
+ ],
+ []
+ );
+
+ const canvasTarget = { closest: () => null };
+ const rect = container.getBoundingClientRect();
+ await bridge.area.emit({
+ type: "pointerdown",
+ data: {
+ position: { x: -10, y: -10 },
+ event: {
+ button: 0,
+ target: canvasTarget,
+ clientX: rect.left - 10,
+ clientY: rect.top - 10,
+ },
+ },
+ });
+ await bridge.area.emit({
+ type: "pointermove",
+ data: {
+ position: { x: 360, y: 120 },
+ event: {
+ button: 0,
+ target: canvasTarget,
+ clientX: rect.left + 360,
+ clientY: rect.top + 120,
+ },
+ },
+ });
+ await bridge.area.emit({
+ type: "pointerup",
+ data: {
+ position: { x: 360, y: 120 },
+ event: {
+ button: 0,
+ target: canvasTarget,
+ clientX: rect.left + 360,
+ clientY: rect.top + 120,
+ },
+ },
+ });
+
+ assert.deepEqual(
+ [...bridge.getSelectedIds().nodeIds].sort(),
+ ["n1", "n2"],
+ "only nodes intersecting the canvas selection rectangle are selected"
+ );
+ assert.deepEqual(
+ selectionRect,
+ { left: -10, right: 360, top: -10, bottom: 120 },
+ "selection rectangle is available for sticky note selection"
+ );
+
+ bridge.destroy();
+ });
+
+ test("secondary pointerdown is ignored by canvas selection", async function (assert) {
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks(),
+ nodeTypes: NODE_TYPES,
+ });
+
+ await bridge.syncState(
+ [{ clientId: "n1", type: "trigger:manual", position: { x: 0, y: 0 } }],
+ []
+ );
+ await bridge.selectableNodes.select("n1", false);
+
+ const result = await bridge.area.emit({
+ type: "pointerdown",
+ data: {
+ position: { x: 10, y: 10 },
+ event: {
+ button: 2,
+ target: { closest: () => null },
+ clientX: 10,
+ clientY: 10,
+ },
+ },
+ });
+
+ assert.strictEqual(
+ result,
+ undefined,
+ "right-click pointerdown is consumed"
+ );
+ assert.deepEqual(
+ [...bridge.getSelectedIds().nodeIds],
+ ["n1"],
+ "right-click pointerdown does not clear the current selection"
+ );
+
+ bridge.destroy();
+ });
+
+ test("dragging a selected node moves the rest of the selection", async function (assert) {
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks(),
+ nodeTypes: NODE_TYPES,
+ });
+
+ await bridge.syncState(
+ [
+ { clientId: "n1", type: "trigger:manual", position: { x: 0, y: 0 } },
+ {
+ clientId: "n2",
+ type: "action:http_request",
+ position: { x: 200, y: 0 },
+ },
+ ],
+ []
+ );
+
+ await bridge.selectableNodes.select("n1", true);
+ await bridge.selectableNodes.select("n2", true);
+ await bridge.area.emit({ type: "nodepicked", data: { id: "n1" } });
+
+ assert.deepEqual(
+ [...bridge.getSelectedIds().nodeIds].sort(),
+ ["n1", "n2"],
+ "picking a selected node preserves the multi-selection"
+ );
+
+ await bridge.area.emit({
+ type: "nodetranslated",
+ data: {
+ id: "n1",
+ previous: { x: 0, y: 0 },
+ position: { x: 50, y: 20 },
+ },
+ });
+
+ assert.deepEqual(
+ bridge.area.nodeViews.get("n2").position,
+ { x: 250, y: 20 },
+ "the non-picked selected node follows the dragged node delta"
+ );
+
+ bridge.destroy();
+ });
+
+ test("node translation remains available without a modifier key", async function (assert) {
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks(),
+ nodeTypes: NODE_TYPES,
+ });
+
+ await bridge.syncState(
+ [{ clientId: "n1", type: "trigger:manual", position: { x: 0, y: 0 } }],
+ []
+ );
+
+ const translation = {
+ type: "nodetranslate",
+ data: {
+ id: "n1",
+ previous: { x: 0, y: 0 },
+ position: { x: 100, y: 100 },
+ },
+ };
+
+ assert.true(
+ Boolean(await bridge.area.emit(translation)),
+ "node dragging is still handled by Rete normally"
+ );
+
+ bridge.destroy();
+ });
+
test("syncState manages connections and creates connection entries", async function (assert) {
const bridge = await createReteEditor(container, {
callbacks: noopCallbacks(),
diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-clipboard-test.js b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-clipboard-test.js
new file mode 100644
index 00000000000..c705a659c6a
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-clipboard-test.js
@@ -0,0 +1,333 @@
+import { module, test } from "qunit";
+import {
+ buildCanvasClipboardPayload,
+ isSerializedCanvasClipboardPayload,
+ normalizeCanvasClipboardPayload,
+ parseCanvasClipboardText,
+ payloadForCanvasClipboardPaste,
+ positionCanvasClipboardPayload,
+ serializeCanvasClipboardPayload,
+} from "discourse/plugins/discourse-workflows/admin/components/workflows/canvas/canvas-clipboard";
+
+module("Unit | Lib | workflows canvas clipboard", function () {
+ test("buildCanvasClipboardPayload copies selected entities and internal connections", function (assert) {
+ const payload = buildCanvasClipboardPayload(
+ {
+ nodes: [
+ {
+ clientId: "node-1",
+ type: "trigger:manual",
+ typeVersion: "1.0",
+ name: "Manual",
+ configuration: { foo: "bar" },
+ position: { x: 10, y: 20 },
+ },
+ {
+ clientId: "node-2",
+ type: "action:topic",
+ typeVersion: "1.0",
+ name: "Topic",
+ configuration: { value: 1 },
+ position: { x: 100, y: 120 },
+ },
+ {
+ clientId: "node-3",
+ type: "action:post",
+ typeVersion: "1.0",
+ name: "Post",
+ configuration: {},
+ },
+ ],
+ connections: [
+ {
+ sourceClientId: "node-1",
+ targetClientId: "node-2",
+ sourceOutput: "main",
+ targetInput: "main",
+ sourceOutputIndex: 0,
+ targetInputIndex: 0,
+ },
+ {
+ sourceClientId: "node-2",
+ targetClientId: "node-3",
+ },
+ ],
+ stickyNotes: [
+ {
+ clientId: "note-1",
+ position: { x: 1, y: 2 },
+ size: { width: 100, height: 100 },
+ color: "yellow",
+ text: "Remember this",
+ },
+ ],
+ },
+ {
+ nodeIds: new Set(["node-1", "node-2"]),
+ stickyNoteIds: new Set(["note-1"]),
+ }
+ );
+
+ assert.deepEqual(
+ payload.nodes.map((node) => node.clientId),
+ ["node-1", "node-2"],
+ "selected nodes are copied"
+ );
+ assert.deepEqual(
+ payload.connections.map((connection) => [
+ connection.sourceClientId,
+ connection.targetClientId,
+ ]),
+ [["node-1", "node-2"]],
+ "only internal selected-node connections are copied"
+ );
+ assert.deepEqual(
+ payload.stickyNotes.map((note) => note.clientId),
+ ["note-1"],
+ "selected sticky notes are copied"
+ );
+ });
+
+ test("buildCanvasClipboardPayload returns null for an empty selection", function (assert) {
+ assert.strictEqual(
+ buildCanvasClipboardPayload(
+ { nodes: [], connections: [], stickyNotes: [] },
+ { nodeIds: new Set(), stickyNoteIds: new Set() }
+ ),
+ null
+ );
+ });
+
+ test("serializeCanvasClipboardPayload produces readable text with an embedded payload", function (assert) {
+ const payload = buildCanvasClipboardPayload(
+ {
+ nodes: [
+ {
+ clientId: "node-1",
+ type: "trigger:manual",
+ configuration: { label: "héllo" },
+ position: { x: 10, y: 20 },
+ },
+ ],
+ },
+ { nodeIds: new Set(["node-1"]) }
+ );
+
+ const text = serializeCanvasClipboardPayload(payload);
+ const parsedPayload = parseCanvasClipboardText(text);
+
+ assert.true(
+ text.startsWith("Discourse workflow selection."),
+ "non-workflow paste targets receive readable text first"
+ );
+ assert.deepEqual(
+ parsedPayload.nodes.map((node) => ({
+ clientId: node.clientId,
+ type: node.type,
+ configuration: node.configuration,
+ position: node.position,
+ })),
+ payload.nodes.map((node) => ({
+ clientId: node.clientId,
+ type: node.type,
+ configuration: node.configuration,
+ position: node.position,
+ })),
+ "embedded payload nodes can be parsed"
+ );
+ });
+
+ test("parseCanvasClipboardText accepts raw payload JSON", function (assert) {
+ const payload = normalizeCanvasClipboardPayload({
+ type: "discourse-workflows/canvas-selection",
+ version: 1,
+ nodes: [{ clientId: "node-1", type: "trigger:manual" }],
+ connections: [],
+ stickyNotes: [],
+ });
+
+ assert.deepEqual(
+ parseCanvasClipboardText(JSON.stringify(payload)),
+ payload,
+ "raw payloads parse for backwards-compatible debugging"
+ );
+ });
+
+ test("parseCanvasClipboardText rejects invalid or unrelated text", function (assert) {
+ assert.strictEqual(parseCanvasClipboardText("hello"), null);
+ assert.strictEqual(parseCanvasClipboardText("{}"), null);
+ assert.strictEqual(
+ parseCanvasClipboardText(
+ "<!-- discourse-workflows-canvas-selection:v1:not-base64 -->"
+ ),
+ null
+ );
+ });
+
+ test("normalizeCanvasClipboardPayload deduplicates client ids and validates sticky note fields", function (assert) {
+ const payload = normalizeCanvasClipboardPayload({
+ type: "discourse-workflows/canvas-selection",
+ version: 1,
+ nodes: [
+ { clientId: "node-1", type: "trigger:manual" },
+ { clientId: "node-1", type: "action:topic" },
+ ],
+ connections: [
+ { sourceClientId: "node-1", targetClientId: "node-1" },
+ { sourceClientId: "node-1", targetClientId: "missing-node" },
+ ],
+ stickyNotes: [
+ {
+ clientId: "note-1",
+ size: { width: "300", height: 150 },
+ color: "blue",
+ },
+ {
+ clientId: "note-2",
+ size: { width: "large", height: 150 },
+ color: "evil",
+ },
+ {
+ clientId: "note-2",
+ size: { width: 10, height: 10 },
+ color: "yellow",
+ },
+ ],
+ });
+
+ assert.deepEqual(
+ payload.nodes.map((node) => [node.clientId, node.type]),
+ [["node-1", "trigger:manual"]],
+ "duplicate node ids are dropped"
+ );
+ assert.deepEqual(
+ payload.connections,
+ [{ sourceClientId: "node-1", targetClientId: "node-1" }],
+ "connections are limited to normalized nodes"
+ );
+ assert.deepEqual(
+ payload.stickyNotes.map((note) => ({
+ clientId: note.clientId,
+ size: note.size,
+ color: note.color,
+ })),
+ [
+ {
+ clientId: "note-1",
+ size: { width: 300, height: 150 },
+ color: "blue",
+ },
+ { clientId: "note-2", size: null, color: undefined },
+ ],
+ "sticky note size and color are normalized"
+ );
+ });
+
+ test("isSerializedCanvasClipboardPayload tolerates clipboard line ending normalization", function (assert) {
+ const payload = normalizeCanvasClipboardPayload({
+ type: "discourse-workflows/canvas-selection",
+ version: 1,
+ nodes: [{ clientId: "node-1", type: "trigger:manual" }],
+ connections: [],
+ stickyNotes: [],
+ });
+ const serialized = serializeCanvasClipboardPayload(payload);
+
+ assert.true(
+ isSerializedCanvasClipboardPayload(
+ serialized.replace(/\n/g, "\r\n"),
+ serialized
+ ),
+ "local copies are detected after clipboard line ending conversion"
+ );
+ });
+
+ test("payloadForCanvasClipboardPaste falls back to the local canvas payload", function (assert) {
+ const localPayload = { nodes: [{ clientId: "local" }] };
+ const systemPayload = { nodes: [{ clientId: "system" }] };
+
+ assert.strictEqual(
+ payloadForCanvasClipboardPaste(systemPayload, localPayload),
+ systemPayload,
+ "system clipboard workflow payloads win"
+ );
+ assert.strictEqual(
+ payloadForCanvasClipboardPaste(null, localPayload),
+ localPayload,
+ "local payload is used when the system clipboard has no workflow payload"
+ );
+ assert.strictEqual(
+ payloadForCanvasClipboardPaste(null, null),
+ null,
+ "empty paste sources stay empty"
+ );
+ });
+
+ test("positionCanvasClipboardPayload centers pasted entities on a target", function (assert) {
+ const positioned = positionCanvasClipboardPayload(
+ {
+ nodes: [
+ { clientId: "node-1", position: { x: 10, y: 20 } },
+ { clientId: "node-2", position: { x: 110, y: 120 } },
+ ],
+ connections: [{ sourceClientId: "node-1", targetClientId: "node-2" }],
+ stickyNotes: [{ clientId: "note-1", position: { x: 60, y: 70 } }],
+ },
+ { target: { canvasX: 200, canvasY: 300 } }
+ );
+
+ assert.deepEqual(
+ positioned.nodes.map((node) => node.position),
+ [
+ { x: 150, y: 250 },
+ { x: 250, y: 350 },
+ ],
+ "nodes are moved around the target center"
+ );
+ assert.deepEqual(
+ positioned.stickyNotes.map((note) => note.position),
+ [{ x: 200, y: 300 }],
+ "sticky notes are moved with the pasted selection"
+ );
+ assert.deepEqual(
+ positioned.connections,
+ [{ sourceClientId: "node-1", targetClientId: "node-2" }],
+ "connections are preserved"
+ );
+ });
+
+ test("positionCanvasClipboardPayload staggers positionless entities on a target", function (assert) {
+ const positioned = positionCanvasClipboardPayload(
+ {
+ nodes: [
+ { clientId: "node-1", position: { x: 10, y: 20 } },
+ { clientId: "node-2" },
+ ],
+ stickyNotes: [{ clientId: "note-1" }],
+ },
+ { target: { canvasX: 100, canvasY: 100 } }
+ );
+
+ assert.deepEqual(
+ positioned.nodes.map((node) => node.position),
+ [
+ { x: 100, y: 100 },
+ { x: 120, y: 120 },
+ ]
+ );
+ assert.deepEqual(positioned.stickyNotes[0].position, { x: 140, y: 140 });
+ });
+
+ test("positionCanvasClipboardPayload offsets local pastes without a target", function (assert) {
+ const positioned = positionCanvasClipboardPayload(
+ {
+ nodes: [{ clientId: "node-1", position: { x: 10, y: 20 } }],
+ stickyNotes: [{ clientId: "note-1", position: { x: 30, y: 40 } }],
+ },
+ { sourceOffset: 20 }
+ );
+
+ assert.deepEqual(positioned.nodes[0].position, { x: 30, y: 40 });
+ assert.deepEqual(positioned.stickyNotes[0].position, { x: 50, y: 60 });
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-keyboard-test.js b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-keyboard-test.js
index afaadfff8ec..cc4da998d00 100644
--- a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-keyboard-test.js
+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-keyboard-test.js
@@ -50,6 +50,12 @@ module("Unit | Canvas Keyboard", function (hooks) {
return event;
}
+ function dispatchEvent(type, opts = {}) {
+ const event = new Event(type, { bubbles: true, cancelable: true });
+ (opts.target ?? canvasElement).dispatchEvent(event);
+ return event;
+ }
+
test("pauses Discourse shortcuts on setup", function (assert) {
keyboard = setup({});
assert.deepEqual(service.paused, ["-", "="]);
@@ -91,19 +97,50 @@ module("Unit | Canvas Keyboard", function (hooks) {
assert.true(redone);
});
- test("Ctrl+C triggers onCopy", function (assert) {
+ test("Ctrl+C triggers onCopy and prevents native copy", function (assert) {
+ let copied = false;
+ keyboard = setup({ onCopy: () => (copied = true) });
+
+ const event = press("c", { meta: true });
+ assert.true(copied);
+ assert.true(event.defaultPrevented, "native copy is prevented");
+ });
+
+ test("Ctrl+X triggers onCut and prevents native cut", function (assert) {
+ let cut = false;
+ keyboard = setup({ onCut: () => (cut = true) });
+
+ const event = press("x", { meta: true });
+ assert.true(cut);
+ assert.true(event.defaultPrevented, "native cut is prevented");
+ });
+
+ test("native copy event triggers onCopy and prevents browser copy", function (assert) {
let copied = false;
keyboard = setup({ onCopy: () => (copied = true) });
- press("c", { meta: true });
+ const event = dispatchEvent("copy");
+
assert.true(copied);
+ assert.true(event.defaultPrevented, "native copy is prevented");
});
- test("Ctrl+V triggers onPaste", function (assert) {
+ test("native cut event triggers onCut and prevents browser cut", function (assert) {
+ let cut = false;
+ keyboard = setup({ onCut: () => (cut = true) });
+
+ const event = dispatchEvent("cut");
+
+ assert.true(cut);
+ assert.true(event.defaultPrevented, "native cut is prevented");
+ });
+
+ test("paste event triggers onPaste", function (assert) {
let pasted = false;
keyboard = setup({ onPaste: () => (pasted = true) });
- press("v", { meta: true });
+ dispatchEvent("paste");
+
assert.true(pasted);
});
@@ -175,6 +212,47 @@ module("Unit | Canvas Keyboard", function (hooks) {
assert.false(called);
});
+ test("ignores keystrokes on select elements", function (assert) {
+ let called = false;
+ keyboard = setup({ onDelete: () => (called = true) });
+
+ const select = document.createElement("select");
+ canvasElement.appendChild(select);
+ press("Delete", { target: select });
+
+ assert.false(called);
+ });
+
+ test("ignores paste events on textarea elements", function (assert) {
+ let called = false;
+ keyboard = setup({ onPaste: () => (called = true) });
+
+ const textarea = document.createElement("textarea");
+ canvasElement.appendChild(textarea);
+ dispatchEvent("paste", { target: textarea });
+
+ assert.false(called);
+ });
+
+ test("ignores copy and cut events on editable elements", function (assert) {
+ let called = false;
+ keyboard = setup({
+ onCopy: () => (called = true),
+ onCut: () => (called = true),
+ });
+
+ const editable = document.createElement("div");
+ editable.contentEditable = "true";
+ canvasElement.appendChild(editable);
+
+ const copyEvent = dispatchEvent("copy", { target: editable });
+ const cutEvent = dispatchEvent("cut", { target: editable });
+
+ assert.false(called);
+ assert.false(copyEvent.defaultPrevented, "native copy is allowed");
+ assert.false(cutEvent.defaultPrevented, "native cut is allowed");
+ });
+
test("missing action callbacks do not throw", function (assert) {
keyboard = setup({});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-sticky-notes-test.js b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-sticky-notes-test.js
index b815df8298e..863a62ab7ce 100644
--- a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-sticky-notes-test.js
+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-sticky-notes-test.js
@@ -11,15 +11,23 @@ module("Unit | Canvas Sticky Notes", function (hooks) {
module("computeStickyNoteRects", function () {
test("maps sticky notes to position/size rects", function (assert) {
const notes = [
- { position: { x: 10, y: 20 }, size: { width: 100, height: 50 } },
- { position: { x: 30, y: 40 }, size: { width: 200, height: 150 } },
+ {
+ clientId: "sn1",
+ position: { x: 10, y: 20 },
+ size: { width: 100, height: 50 },
+ },
+ {
+ clientId: "sn2",
+ position: { x: 30, y: 40 },
+ size: { width: 200, height: 150 },
+ },
];
const rects = computeStickyNoteRects(notes);
assert.deepEqual(rects, [
- { x: 10, y: 20, width: 100, height: 50 },
- { x: 30, y: 40, width: 200, height: 150 },
+ { clientId: "sn1", x: 10, y: 20, width: 100, height: 50 },
+ { clientId: "sn2", x: 30, y: 40, width: 200, height: 150 },
]);
});
@@ -58,6 +66,22 @@ module("Unit | Canvas Sticky Notes", function (hooks) {
assert.deepEqual(movedPosition, { x: 110, y: 195 });
});
+ test("uses latest sticky notes from a getter", function (assert) {
+ let notes = [{ clientId: "sn1", position: { x: 0, y: 0 } }];
+ let movedPosition;
+ const handler = buildStickyNoteTranslateHandler(
+ () => notes,
+ (id, pos) => {
+ movedPosition = pos;
+ }
+ );
+
+ notes = [{ clientId: "sn1", position: { x: 20, y: 30 } }];
+ handler("sn1", 5, 10);
+
+ assert.deepEqual(movedPosition, { x: 25, y: 40 });
+ });
+
test("does nothing when note is not found", function (assert) {
const notes = [{ clientId: "sn1", position: { x: 0, y: 0 } }];
let called = false;
diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/editor-test.js b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/editor-test.js
index a847d516bef..43e625236af 100644
--- a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/editor-test.js
+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/editor-test.js
@@ -1,6 +1,7 @@
import { module, test } from "qunit";
import { i18n } from "discourse-i18n";
import WorkflowsEditor, {
+ buildPastedGraph,
isNodeUnavailable,
} from "discourse/plugins/discourse-workflows/admin/components/workflows/editor";
@@ -24,8 +25,12 @@ function setFormApi(editor, data) {
get(key) {
return data[key];
},
+ set(key, value) {
+ data[key] = value;
+ },
},
});
+ return data;
}
function setRouter(editor, assert) {
@@ -312,4 +317,127 @@ module("Unit | Component | workflows editor", function () {
["trigger:manual", "action:topic"]
);
});
+
+ test("buildPastedGraph duplicates nodes with unique names and remaps internal connections", function (assert) {
+ const existingNodes = [
+ {
+ clientId: "existing-trigger",
+ type: "trigger:manual",
+ name: i18n("discourse_workflows.nodes.trigger:manual"),
+ },
+ ];
+
+ const { updatedNodes, updatedConnections } = buildPastedGraph({
+ existingNodes,
+ existingConnections: [],
+ copiedNodes: [
+ {
+ clientId: "copied-trigger",
+ type: "trigger:manual",
+ typeVersion: "1.0",
+ configuration: { foo: "bar" },
+ position: { x: 10, y: 20 },
+ },
+ {
+ clientId: "copied-action",
+ type: "trigger:manual",
+ typeVersion: "1.0",
+ configuration: { baz: "qux" },
+ position: { x: 100, y: 20 },
+ },
+ ],
+ copiedConnections: [
+ {
+ sourceClientId: "copied-trigger",
+ targetClientId: "copied-action",
+ sourceOutput: "main",
+ targetInput: "main",
+ sourceOutputIndex: 0,
+ targetInputIndex: 0,
+ },
+ ],
+ });
+
+ assert.deepEqual(
+ updatedNodes.map((node) => node.name),
+ [
+ i18n("discourse_workflows.nodes.trigger:manual"),
+ `${i18n("discourse_workflows.nodes.trigger:manual")} 1`,
+ `${i18n("discourse_workflows.nodes.trigger:manual")} 2`,
+ ],
+ "names are generated against already-pasted nodes"
+ );
+ assert.strictEqual(
+ updatedConnections.length,
+ 1,
+ "internal connection pasted"
+ );
+ assert.strictEqual(
+ updatedConnections[0].sourceClientId,
+ updatedNodes[1].clientId,
+ "connection source is remapped"
+ );
+ assert.strictEqual(
+ updatedConnections[0].targetClientId,
+ updatedNodes[2].clientId,
+ "connection target is remapped"
+ );
+ });
+
+ test("buildPastedGraph normalizes pasted indexed input connections", function (assert) {
+ const { updatedNodes, updatedConnections } = buildPastedGraph({
+ existingNodes: [],
+ existingConnections: [],
+ copiedNodes: [
+ {
+ clientId: "source-1",
+ type: "trigger:manual",
+ position: { x: 10, y: 20 },
+ },
+ {
+ clientId: "source-2",
+ type: "trigger:manual",
+ position: { x: 10, y: 120 },
+ },
+ {
+ clientId: "target",
+ type: "action:multi_input",
+ position: { x: 200, y: 20 },
+ },
+ ],
+ copiedConnections: [
+ { sourceClientId: "source-1", targetClientId: "target" },
+ { sourceClientId: "source-2", targetClientId: "target" },
+ ],
+ nodeTypeFor(node) {
+ if (node.type === "action:multi_input") {
+ return {
+ identifier: "action:multi_input",
+ inputs: [{ key: "items", multiple: true }],
+ };
+ }
+
+ return node.type;
+ },
+ });
+
+ const targetNode = updatedNodes.find(
+ (node) => node.type === "action:multi_input"
+ );
+ const targetConnections = updatedConnections.filter(
+ (connection) => connection.targetClientId === targetNode.clientId
+ );
+
+ assert.deepEqual(
+ targetConnections.map((connection) => ({
+ targetInput: connection.targetInput,
+ targetInputIndex: connection.targetInputIndex,
+ })),
+ [
+ { targetInput: "items", targetInputIndex: 0 },
+ { targetInput: "items", targetInputIndex: 1 },
+ ],
+ "pasted connections into indexed inputs are assigned stable indexes"
+ );
+ });
});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-graph-utils-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-graph-utils-test.js
index 4950f7c0e21..1068ca0f18c 100644
--- a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-graph-utils-test.js
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-graph-utils-test.js
@@ -65,6 +65,38 @@ module("Unit | Utility | workflows graph utils", function () {
});
});
+ test("can remove nodes without reconnecting neighbours", function (assert) {
+ const graph = removeNodesFromGraph(
+ [
+ { clientId: "trigger", type: "trigger:manual" },
+ { clientId: "action", type: "action:set_fields" },
+ { clientId: "done", type: "action:topic_tags" },
+ ],
+ [
+ {
+ sourceClientId: "trigger",
+ sourceOutput: "main",
+ targetClientId: "action",
+ },
+ {
+ sourceClientId: "action",
+ sourceOutput: "main",
+ targetClientId: "done",
+ },
+ ],
+ ["action"],
+ { reconnect: false }
+ );
+
+ assert.deepEqual(normalizeGraph(graph), {
+ nodes: [
+ { clientId: "done", type: "action:topic_tags" },
+ { clientId: "trigger", type: "trigger:manual" },
+ ],
+ connections: [],
+ });
+ });
+
test("removing a loop node keeps the former body node standalone and reconnects the done path", function (assert) {
const graph = removeNodesFromGraph(
[