Skip to content

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

DEV: Add a right-click menu modifier to float-kit (#43356)

Sérgio Saquetim7b13572c76fa
diff --git a/frontend/discourse/app/lib/is-context-menu-exempt-target.ts b/frontend/discourse/app/lib/is-context-menu-exempt-target.ts
new file mode 100644
index 00000000000..cefcaa165c3
--- /dev/null
+++ b/frontend/discourse/app/lib/is-context-menu-exempt-target.ts
@@ -0,0 +1,35 @@
+const NON_CARET_INPUT_TYPES = new Set([
+ "button",
+ "checkbox",
+ "file",
+ "image",
+ "reset",
+ "submit",
+]);
+
+/**
+ * Whether the target owns a text caret and should keep the native context menu.
+ *
+ * Intentionally separate from the predicate that decides which elements own the arrow keys:
+ * that one counts `select` as editable, which is the wrong answer to this question.
+ *
+ * @param target - The contextmenu event's target.
+ */
+export default function isContextMenuExemptTarget(
+ target: EventTarget | null
+): boolean {
+ if (!(target instanceof HTMLElement)) {
+ return false;
+ }
+
+ const tag = target.tagName;
+
+ if (tag === "TEXTAREA" || target.isContentEditable) {
+ return true;
+ }
+
+ return (
+ tag === "INPUT" &&
+ !NON_CARET_INPUT_TYPES.has((target as HTMLInputElement).type)
+ );
+}
diff --git a/frontend/discourse/app/lib/virtual-element-from-point.ts b/frontend/discourse/app/lib/virtual-element-from-point.ts
new file mode 100644
index 00000000000..649f12f094a
--- /dev/null
+++ b/frontend/discourse/app/lib/virtual-element-from-point.ts
@@ -0,0 +1,31 @@
+import type { VirtualElement } from "@floating-ui/dom";
+
+/**
+ * Creates a zero-size reference at a fixed viewport point.
+ *
+ * Deliberately carries no `contextElement`: setting one moves the clipping boundary to that
+ * element's overflow ancestors and reintroduces a scale divisor, neither of which a point
+ * anchored to the viewport wants.
+ *
+ * @param x - The viewport x coordinate.
+ * @param y - The viewport y coordinate.
+ */
+export default function virtualElementFromPoint(
+ x: number,
+ y: number
+): VirtualElement {
+ return {
+ getBoundingClientRect() {
+ return {
+ x,
+ y,
+ left: x,
+ right: x,
+ top: y,
+ bottom: y,
+ width: 0,
+ height: 0,
+ };
+ },
+ };
+}
diff --git a/frontend/discourse/app/static/dev-tools/block-debug/block-info.gts b/frontend/discourse/app/static/dev-tools/block-debug/block-info.gts
index 0c01803e9d6..6ffaab277e9 100644
--- a/frontend/discourse/app/static/dev-tools/block-debug/block-info.gts
+++ b/frontend/discourse/app/static/dev-tools/block-debug/block-info.gts
@@ -115,6 +115,7 @@ export default class BlockInfo extends Component<BlockInfoSignature> {
<template>
<div class="block-debug-info --rendered" data-block-name={{@blockName}}>
<DTooltip
+ @hoverGracePeriod={{150}}
@identifier="block-debug-info"
@interactive={{true}}
@placement="bottom-start"
@@ -123,7 +124,7 @@ export default class BlockInfo extends Component<BlockInfoSignature> {
mobile=(array "click")
desktop=(array "hover" "click")
}}
- @untriggers={{hash mobile=(array "click") desktop=(array "mouseleave")}}
+ @untriggers={{hash mobile=(array "click") desktop=(array "hover")}}
>
<:trigger>
<span class="block-debug-badge">
diff --git a/frontend/discourse/app/static/dev-tools/block-debug/ghost-block.gts b/frontend/discourse/app/static/dev-tools/block-debug/ghost-block.gts
index e08a0f7f42a..87132831e3d 100644
--- a/frontend/discourse/app/static/dev-tools/block-debug/ghost-block.gts
+++ b/frontend/discourse/app/static/dev-tools/block-debug/ghost-block.gts
@@ -143,6 +143,7 @@ export default class GhostBlock extends Component<GhostBlockSignature> {
<template>
<div class="block-debug-ghost" data-block-name={{@blockName}}>
<DTooltip
+ @hoverGracePeriod={{150}}
@identifier="block-debug-ghost"
@interactive={{true}}
@placement="bottom-start"
@@ -151,7 +152,7 @@ export default class GhostBlock extends Component<GhostBlockSignature> {
mobile=(array "click")
desktop=(array "hover" "click")
}}
- @untriggers={{hash mobile=(array "click") desktop=(array "mouseleave")}}
+ @untriggers={{hash mobile=(array "click") desktop=(array "hover")}}
>
<:trigger>
<span class="block-debug-ghost__badge">
diff --git a/frontend/discourse/app/ui-kit/d-modal.gts b/frontend/discourse/app/ui-kit/d-modal.gts
index e30c93aef44..07f31b63710 100644
--- a/frontend/discourse/app/ui-kit/d-modal.gts
+++ b/frontend/discourse/app/ui-kit/d-modal.gts
@@ -557,7 +557,13 @@ export default class DModal extends Component<DModalSignature> {
data-keyboard="false"
aria-modal="true"
role="dialog"
- aria-labelledby={{if @title "discourse-modal-title"}}
+ {{! The title element lives in the header, so hiding the header leaves this pointing at
+ nothing. A dangling reference is dropped when the accessible name is computed, which
+ leaves the dialog unnamed. Such a modal should supply its own label attribute. }}
+ aria-labelledby={{if
+ (and @title (not @hideHeader))
+ "discourse-modal-title"
+ }}
...attributes
{{didInsert this.setupModal}}
{{willDestroy this.cleanupModal}}
diff --git a/frontend/discourse/app/ui-kit/modifiers/d-trap-tab.ts b/frontend/discourse/app/ui-kit/modifiers/d-trap-tab.ts
index 0f71d085ca6..f3f68d94be5 100644
--- a/frontend/discourse/app/ui-kit/modifiers/d-trap-tab.ts
+++ b/frontend/discourse/app/ui-kit/modifiers/d-trap-tab.ts
@@ -9,6 +9,44 @@ import type { CapabilitiesService } from "discourse/services/capabilities";
const FOCUSABLE_ELEMENTS =
"details:not(.is-disabled) summary, [autofocus], a, input, select, textarea, summary";
+/**
+ * Whether an element can actually take focus, and so may serve as a tab stop.
+ *
+ * The selector above matches on tag name alone, so it collects controls the user cannot reach.
+ * Treating one as a stop breaks the wrap outright: `focus()` on an unfocusable element does
+ * nothing, focus stays where it was, and Tab appears dead.
+ *
+ * The eligibility rules match `d-roving-focus`'s, deliberately — both answer "may focus land
+ * here?", and a control that one kit skips while the other stops on is a bug in whichever is
+ * wrong. Only the navigation semantics differ. Ordered cheapest-first, with the computed style
+ * last because resolving it is the expensive predicate.
+ */
+function canHoldFocus(element: HTMLElement): boolean {
+ // Catches controls disabled through an ancestor fieldset too, unlike the IDL property.
+ if (element.matches(":disabled")) {
+ return false;
+ }
+
+ // Inertness applies to descendants, so the candidate's own attribute is insufficient.
+ if (element.closest("[inert]")) {
+ return false;
+ }
+
+ // `offsetParent` is null for a `display: none` subtree; the rect checks keep a
+ // `position: fixed` control, which reports no `offsetParent` while still being visible.
+ const occupiesLayout =
+ element.offsetParent ||
+ element.getClientRects().length ||
+ element.getBoundingClientRect().width;
+
+ if (!occupiesLayout) {
+ return false;
+ }
+
+ // `visibility: hidden` still occupies layout but cannot be focused.
+ return getComputedStyle(element).visibility === "visible";
+}
+
interface DTrapTabSignature {
/** The element the tab trap is attached to. */
Element: HTMLElement;
@@ -60,11 +98,15 @@ export default class DTrapTabModifier extends Modifier<DTrapTabSignature> {
// if there's not autofocus, or the activeElement, is not the autofocusable element
// attempt to focus the first of the focusable elements or just the modal-body
// to make it possible to scroll with arrow down/up
+ // Same eligibility as the Tab wrap: focusing an unfocusable first control silently does
+ // nothing, leaving focus outside the trap with no way in.
const target =
autofocusedElement ||
- this.#element.querySelector<HTMLElement>(
- FOCUSABLE_ELEMENTS + ", button:not(.modal-close)"
- ) ||
+ Array.from(
+ this.#element.querySelectorAll<HTMLElement>(
+ FOCUSABLE_ELEMENTS + ", button:not(.modal-close)"
+ )
+ ).find(canHoldFocus) ||
this.#element.querySelector<HTMLElement>(".d-modal__body");
if (target) {
@@ -91,7 +133,7 @@ export default class DTrapTabModifier extends Modifier<DTrapTabSignature> {
this.#element.querySelectorAll<HTMLElement>(focusableElements)
).filter((element) => {
const tabindex = element.getAttribute("tabindex");
- return tabindex !== "-1";
+ return tabindex !== "-1" && canHoldFocus(element);
});
const firstFocusableElement = filteredFocusableElements[0];
diff --git a/frontend/discourse/float-kit/components/d-float-body.gts b/frontend/discourse/float-kit/components/d-float-body.gts
index f0093beca22..a585b3efabc 100644
--- a/frontend/discourse/float-kit/components/d-float-body.gts
+++ b/frontend/discourse/float-kit/components/d-float-body.gts
@@ -137,12 +137,29 @@ export default class DFloatBody extends Component<DFloatBodySignature> {
return this.args.instance.expanded && this.options.hoverGracePeriod > 0;
}
+ /**
+ * The float borrows its accessible name from its trigger, but only a float whose trigger
+ * markup carries the instance id can do so. A float opened through the service anchors to an
+ * element that was never given that id — and one anchored to a virtual reference has no
+ * element at all — so emitting the id regardless produced a reference to nothing, which is
+ * ignored during name computation and leaves the float silently unnamed. Emit it only when it
+ * actually resolves, and let `ariaLabel` name the float in every other case.
+ */
get contentAriaLabelledby(): string | null | undefined {
+ if (this.#hasPresentationalRole || this.contentAriaLabel) {
+ return;
+ }
+
+ const { id } = this.args.instance;
+ return id && document.getElementById(id) ? id : null;
+ }
+
+ get contentAriaLabel(): string | null | undefined {
if (this.#hasPresentationalRole) {
return;
}
- return this.args.instance.id;
+ return this.options.ariaLabel;
}
/**
@@ -220,6 +237,7 @@ export default class DFloatBody extends Component<DFloatBodySignature> {
data-identifier={{this.options.identifier}}
data-content
aria-labelledby={{this.contentAriaLabelledby}}
+ aria-label={{this.contentAriaLabel}}
role={{@role}}
{{FloatKitApplyFloatingUi this.trigger this.options @instance}}
{{this.trapInteractionPropagation}}
diff --git a/frontend/discourse/float-kit/components/d-inline-float.gts b/frontend/discourse/float-kit/components/d-inline-float.gts
index c722575ab22..6eef67c2bd0 100644
--- a/frontend/discourse/float-kit/components/d-inline-float.gts
+++ b/frontend/discourse/float-kit/components/d-inline-float.gts
@@ -49,6 +49,7 @@ const DInlineFloat: TemplateOnlyComponent<DInlineFloatSignature> = <template>
<DModal
@closeModal={{@instance.close}}
@hideHeader={{true}}
+ aria-label={{@instance.options.ariaLabel}}
data-identifier={{@instance.options.identifier}}
data-content
class={{dConcatClass
diff --git a/frontend/discourse/float-kit/components/d-menu.gts b/frontend/discourse/float-kit/components/d-menu.gts
index c5a87870f8f..4f42e4e3e9b 100644
--- a/frontend/discourse/float-kit/components/d-menu.gts
+++ b/frontend/discourse/float-kit/components/d-menu.gts
@@ -308,6 +308,7 @@ export default class DMenu<Data = unknown> extends Component<
@closeModal={{this.menuInstance.close}}
@hideHeader={{true}}
@autofocus={{this.options.autofocus}}
+ aria-label={{this.options.ariaLabel}}
class={{dConcatClass
"fk-d-menu-modal"
(concat this.options.identifier "-content")
diff --git a/frontend/discourse/float-kit/lib/constants.ts b/frontend/discourse/float-kit/lib/constants.ts
index dee605e7894..38ce761d156 100644
--- a/frontend/discourse/float-kit/lib/constants.ts
+++ b/frontend/discourse/float-kit/lib/constants.ts
@@ -91,6 +91,19 @@ export interface TooltipOptions {
/** Whether to animate the float as it opens and closes. */
animated: boolean;
+ /**
+ * An accessible name for the float's content, already translated. Needed whenever the float
+ * cannot borrow a name from its trigger: a float opened through the service anchors to an
+ * element that carries no `id`, and one anchored to a virtual reference has no trigger element
+ * at all, so in both cases the trigger-derived `aria-labelledby` is dropped and the float would
+ * otherwise be announced unnamed.
+ *
+ * Setting it takes precedence over the trigger-derived name. Like every option it is read once
+ * when the instance is built, so a name that changes while the float is open belongs on the
+ * trigger rather than here.
+ */
+ ariaLabel: string | null;
+
/** Whether to render a directional arrow pointing at the trigger. */
arrow: boolean;
@@ -223,6 +236,15 @@ export interface MenuOptions extends TooltipOptions {
*/
contentRole: FloatContentRole;
+ /**
+ * Where focus returns when the menu closes, resolved **at close time** rather than when the
+ * menu opens. A menu anchored to a virtual reference has no trigger element to fall back on
+ * (`triggerElement` is `null` for one). An element captured at open time is also frequently
+ * stale by the time the menu closes, because an item that mutates the DOM often destroys it.
+ * Returning `null` leaves focus alone. Falls back to the trigger element when unset.
+ */
+ focusTarget: (() => HTMLElement | null) | null;
+
/** Whether to focus the content when the menu opens. */
autofocus: boolean;
@@ -365,6 +387,7 @@ export interface ToastOptions {
export const TOOLTIP: { options: TooltipOptions; portalOutletId: string } = {
options: {
animated: true,
+ ariaLabel: null,
arrow: true,
beforeTrigger: null,
closeOnClickOutside: true,
@@ -400,8 +423,10 @@ export const TOOLTIP: { options: TooltipOptions; portalOutletId: string } = {
export const MENU: { options: MenuOptions; portalOutletId: string } = {
options: {
animated: true,
+ ariaLabel: null,
arrow: false,
autofocus: false,
+ focusTarget: null,
beforeTrigger: null,
closeOnEscape: true,
closeOnClickOutside: true,
diff --git a/frontend/discourse/float-kit/lib/d-menu-instance.ts b/frontend/discourse/float-kit/lib/d-menu-instance.ts
index 53ab6483200..bdb52daff55 100644
--- a/frontend/discourse/float-kit/lib/d-menu-instance.ts
+++ b/frontend/discourse/float-kit/lib/d-menu-instance.ts
@@ -124,12 +124,28 @@ export default class DMenuInstance extends FloatKitInstance {
(options.focusTrigger ?? true) ||
(ownedFocus && this.#focusIsUnowned)
) {
- this.triggerElement?.focus();
+ this.#focusReturnTarget?.focus();
}
await super.close(options);
}
+ /**
+ * Where focus goes once the menu has closed. `focusTarget` is resolved here rather than when
+ * the menu opened, so an action that replaces or removes the element it named still returns
+ * focus to whatever now stands in its place. The trigger element is the fallback, and is
+ * `null` for a menu anchored to a virtual reference — which is exactly the case `focusTarget`
+ * exists to serve.
+ */
+ get #focusReturnTarget(): HTMLElement | null {
+ const { focusTarget } = this.options;
+
+ // An absent thunk means "no opinion", so the trigger is the fallback. A thunk that returns
+ // `null` is an opinion — the caller looked and decided nothing should take focus — so it is
+ // honoured rather than falling through to the trigger.
+ return focusTarget ? focusTarget() : this.triggerElement;
+ }
+
get #focusIsUnowned(): boolean {
const { activeElement } = document;
return !activeElement || activeElement === document.body;
diff --git a/frontend/discourse/float-kit/lib/float-kit-instance.ts b/frontend/discourse/float-kit/lib/float-kit-instance.ts
index a561cab7412..bd827967092 100644
--- a/frontend/discourse/float-kit/lib/float-kit-instance.ts
+++ b/frontend/discourse/float-kit/lib/float-kit-instance.ts
@@ -1,3 +1,4 @@
+import { DEBUG } from "@glimmer/env";
import { tracked } from "@glimmer/tracking";
import { isDestroying } from "@ember/destroyable";
import { action } from "@ember/object";
@@ -295,6 +296,10 @@ export default abstract class FloatKitInstance {
return;
}
+ if (DEBUG) {
+ this.#warnUnknownUntriggers();
+ }
+
makeArray(this.triggers)
.filter(Boolean)
.forEach((trigger) => {
@@ -337,6 +342,11 @@ export default abstract class FloatKitInstance {
case "click":
element.removeEventListener("click", this.onClick);
break;
+ default:
+ if (DEBUG) {
+ // eslint-disable-next-line no-console
+ console.warn(`FloatKit: unknown trigger "${trigger}".`);
+ }
}
});
@@ -353,6 +363,10 @@ export default abstract class FloatKitInstance {
return;
}
+ if (DEBUG) {
+ this.#warnUnknownUntriggers();
+ }
+
makeArray(this.triggers)
.filter(Boolean)
.forEach((trigger) => {
@@ -411,6 +425,11 @@ export default abstract class FloatKitInstance {
passive: true,
});
break;
+ default:
+ if (DEBUG) {
+ // eslint-disable-next-line no-console
+ console.warn(`FloatKit: unknown trigger "${trigger}".`);
+ }
}
});
}
@@ -442,4 +461,22 @@ export default abstract class FloatKitInstance {
get shouldTrapPointerDown() {
return true;
}
+
+ /** Untriggers need validation even though only triggers install listeners. */
+ #warnUnknownUntriggers() {
+ const supported = [
+ "hold",
+ "focus",
+ "focusin",
+ "hover",
+ "delayed-hover",
+ "click",
+ ];
+ for (const untrigger of makeArray(this.untriggers).filter(Boolean)) {
+ if (!supported.includes(untrigger)) {
+ // eslint-disable-next-line no-console
+ console.warn(`FloatKit: unknown untrigger "${untrigger}".`);
+ }
+ }
+ }
}
diff --git a/frontend/discourse/float-kit/modifiers/d-context-menu.ts b/frontend/discourse/float-kit/modifiers/d-context-menu.ts
new file mode 100644
index 00000000000..15c7f9fd09a
--- /dev/null
+++ b/frontend/discourse/float-kit/modifiers/d-context-menu.ts
@@ -0,0 +1,125 @@
+import { registerDestructor } from "@ember/destroyable";
+import { guidFor } from "@ember/object/internals";
+import type Owner from "@ember/owner";
+import { service } from "@ember/service";
+import Modifier, { type ArgsFor } from "ember-modifier";
+import type { MenuOptions } from "discourse/float-kit/lib/constants";
+import type DMenuInstance from "discourse/float-kit/lib/d-menu-instance";
+import type MenuService from "discourse/float-kit/services/menu";
+import isContextMenuExemptTarget from "discourse/lib/is-context-menu-exempt-target";
+import virtualElementFromPoint from "discourse/lib/virtual-element-from-point";
+
+interface FloatKitContextMenuSignature {
+ Element: HTMLElement;
+ Args: {
+ Positional: [];
+ Named: Partial<MenuOptions> & {
+ /** The menu content, receiving `@data` and `@close`. */
+ component: NonNullable<MenuOptions["component"]>;
+
+ /**
+ * Decides synchronously whether to replace the native menu. Return `false` to leave
+ * the event untouched, `true` to accept, or options to accept and override named options.
+ * When omitted, targets that own a text caret keep their native menu.
+ */
+ beforeContextMenu?: (event: MouseEvent) => boolean | Partial<MenuOptions>;
+ };
+ };
+}
+
+/** Opens a menu at the right-click's viewport point and owns its lifetime. */
+export default class FloatKitContextMenu extends Modifier<FloatKitContextMenuSignature> {
+ @service declare menu: MenuService;
+
+ #identifier = `context-menu-${guidFor(this)}`;
+ #disposed = false;
+ #instance: DMenuInstance | undefined;
+ #pendingOpen: Promise<void> = Promise.resolve();
+ #removeListener: (() => void) | undefined;
+
+ constructor(owner: Owner, args: ArgsFor<FloatKitContextMenuSignature>) {
+ super(owner, args);
+ registerDestructor(this, () => {
+ this.#disposed = true;
+ this.#removeListener?.();
+ this.menu.close(this.#instance);
+ });
+ }
+
+ modify(
+ element: HTMLElement,
+ _positional: [],
+ {
+ beforeContextMenu,
+ ...options
+ }: FloatKitContextMenuSignature["Args"]["Named"]
+ ) {
+ this.#removeListener?.();
+
+ const onContextMenu = (event: MouseEvent) => {
+ const decision = beforeContextMenu
+ ? beforeContextMenu(event)
+ : !isContextMenuExemptTarget(event.target);
+
+ if (
+ decision !== true &&
+ (!decision || typeof decision !== "object" || "then" in decision)
+ ) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ // Defaults first: a named argument overrides them, a per-gesture decision overrides both.
+ // A virtual reference has no trigger element, so focus return has nothing to fall back to
+ // unless this modifier names the element the gesture came from.
+ const menuOptions = {
+ autofocus: true,
+ focusTarget: () => element,
+ ...options,
+ ...(typeof decision === "object" ? decision : {}),
+ };
+ menuOptions.identifier ||= this.#identifier;
+ const reference = virtualElementFromPoint(event.clientX, event.clientY);
+
+ // The service can yield while replacing an existing menu. Serialize opens so rapid
+ // gestures cannot register multiple replacements while that close is pending. The chain
+ // must never settle rejected: a rejected promise skips every later `then`, which would
+ // leave the element silently unable to open a menu again.
+ this.#pendingOpen = this.#pendingOpen
+ .then(() => this.#open(reference, menuOptions))
+ .catch(() => {});
+ };
+
+ element.addEventListener("contextmenu", onContextMenu);
+ this.#removeListener = () =>
+ element.removeEventListener("contextmenu", onContextMenu);
+ }
+
+ async #open(
+ reference: ReturnType<typeof virtualElementFromPoint>,
+ options: Partial<MenuOptions>
+ ): Promise<void> {
+ if (this.#disposed) {
+ return;
+ }
+
+ if (
+ this.#instance &&
+ this.#instance.options.identifier !== options.identifier
+ ) {
+ await this.menu.close(this.#instance);
+ if (this.#disposed) {
+ return;
+ }
+ }
+
+ const instance = await this.menu.show(reference, options);
+ if (this.#disposed) {
+ await this.menu.close(instance);
+ } else {
+ this.#instance = instance;
+ }
+ }
+}
diff --git a/frontend/discourse/tests/integration/components/float-kit/d-context-menu-test.gjs b/frontend/discourse/tests/integration/components/float-kit/d-context-menu-test.gjs
new file mode 100644
index 00000000000..222be260ebb
--- /dev/null
+++ b/frontend/discourse/tests/integration/components/float-kit/d-context-menu-test.gjs
@@ -0,0 +1,324 @@
+import { click, find, render, settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import DMenus from "discourse/float-kit/components/d-menus";
+import dContextMenu from "discourse/float-kit/modifiers/d-context-menu";
+import isContextMenuExemptTarget from "discourse/lib/is-context-menu-exempt-target";
+import virtualElementFromPoint from "discourse/lib/virtual-element-from-point";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import DButton from "discourse/ui-kit/d-button";
+
+const Actions = <template>
+ <DButton class="ctx-action" @action={{@close}}>Act</DButton>
+</template>;
+
+/**
+ * Dispatches a real contextmenu event and hands the event back, so a test can see whether
+ * anything called preventDefault on it. `triggerEvent` resolves to nothing, so it cannot
+ * answer that question.
+ */
+async function rightClick(selector, { clientX = 40, clientY = 60 } = {}) {
+ const event = new MouseEvent("contextmenu", {
+ bubbles: true,
+ cancelable: true,
+ clientX,
+ clientY,
+ });
+ find(selector).dispatchEvent(event);
+ await settled();
+ return event;
+}
+
+module("Integration | Component | FloatKit | dContextMenu", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("ctx-oracle: builds a zero-size reference at the given point", function (assert) {
+ const reference = virtualElementFromPoint(120, 250);
+ const rect = reference.getBoundingClientRect();
+
+ assert.strictEqual(rect.width, 0, "the reference has no width");
+ assert.strictEqual(rect.height, 0, "the reference has no height");
+ assert.strictEqual(rect.left, 120, "left is the supplied x");
+ assert.strictEqual(rect.right, 120, "right collapses onto the same x");
+ assert.strictEqual(rect.top, 250, "top is the supplied y");
+ assert.strictEqual(rect.bottom, 250, "bottom collapses onto the same y");
+ assert.strictEqual(
+ reference.contextElement,
+ undefined,
+ "no contextElement, so the reference keeps viewport clipping and no scale divisor"
+ );
+ });
+
+ test("ctx-oracle: exempts targets that own a text caret", async function (assert) {
+ await render(
+ <template>
+ <textarea class="probe-textarea"></textarea>
+ <input class="probe-text" type="text" />
+ <input class="probe-checkbox" type="checkbox" />
+ <div class="probe-editable" contenteditable="true"></div>
+ <select class="probe-select"><option>a</option></select>
+ <button type="button" class="probe-button">b</button>
+ </template>
+ );
+
+ assert.true(
+ isContextMenuExemptTarget(find(".probe-textarea")),
+ "a textarea keeps the native menu"
+ );
+ assert.true(
+ isContextMenuExemptTarget(find(".probe-text")),
+ "a text input keeps the native menu"
+ );
+ assert.true(
+ isContextMenuExemptTarget(find(".probe-editable")),
+ "a contenteditable region keeps the native menu"
+ );
+ assert.false(
+ isContextMenuExemptTarget(find(".probe-checkbox")),
+ "a checkbox owns no caret"
+ );
+ assert.false(
+ isContextMenuExemptTarget(find(".probe-button")),
+ "a button owns no caret"
+ );
+ assert.false(
+ isContextMenuExemptTarget(find(".probe-select")),
+ "a select owns no caret, unlike the arrow-key predicate this is derived from"
+ );
+ assert.false(
+ isContextMenuExemptTarget(null),
+ "a missing target is not exempt"
+ );
+ });
+
+ test("ctx-oracle: an accepted right-click opens a menu and suppresses the native one", async function (assert) {
+ await render(
+ <template>
+ <div class="ctx-host" {{dContextMenu component=Actions}}>host</div>
+ <DMenus />
+ </template>
+ );
+
+ const event = await rightClick(".ctx-host");
+
+ assert.dom(".fk-d-menu .ctx-action").exists("the menu opened");
+ assert.true(
+ event.defaultPrevented,
+ "the native menu is suppressed only because a handler accepted"
+ );
+ });
+
+ test("ctx-oracle: a declining hook leaves the event untouched", async function (assert) {
+ const consulted = [];
+ const decline = (event) => {
+ consulted.push(event.type);
+ return false;
+ };
+
+ await render(
+ <template>
+ <div
+ class="ctx-host"
+ {{dContextMenu component=Actions beforeContextMenu=decline}}
+ >host</div>
+ <DMenus />
+ </template>
+ );
+
+ const event = await rightClick(".ctx-host");
+
+ // Without this the test would pass against a modifier that does nothing at all, since the
+ // remaining assertions only check that nothing happened.
+ assert.deepEqual(
+ consulted,
+ ["contextmenu"],
+ "the hook was consulted, so the decline was a decision rather than an absent listener"
+ );
+ assert.dom(".fk-d-menu").doesNotExist("no menu opened");
+ assert.false(
+ event.defaultPrevented,
+ "the native menu survives a decline, so the browser still gets the gesture"
+ );
+ });
+
+ test("ctx-oracle: an accepted inner handler stops the event reaching an outer one", async function (assert) {
+ const outerSeen = [];
+ const recordOuter = () => {
+ outerSeen.push("outer");
+ return false;
+ };
+
+ await render(
+ <template>
+ <div
+ class="ctx-outer"
+ {{dContextMenu component=Actions beforeContextMenu=recordOuter}}
+ >
+ <div class="ctx-inner" {{dContextMenu component=Actions}}>inner</div>
+ </div>
+ <DMenus />
+ </template>
+ );
+
+ await rightClick(".ctx-inner");
+
+ assert.dom(".fk-d-menu").exists("the innermost handler opened its menu");
+ assert.deepEqual(
+ outerSeen,
+ [],
+ "the outer handler never ran, because accepting stops propagation"
+ );
+ });
+
+ test("ctx-oracle: a declining inner handler lets an outer one accept", async function (assert) {
+ const declineInner = () => false;
+
+ await render(
+ <template>
+ <div class="ctx-outer" {{dContextMenu component=Actions}}>
+ <div
+ class="ctx-inner"
+ {{dContextMenu component=Actions beforeContextMenu=declineInner}}
+ >inner</div>
+ </div>
+ <DMenus />
+ </template>
+ );
+
+ const event = await rightClick(".ctx-inner");
+
+ assert
+ .dom(".fk-d-menu")
+ .exists("the outer handler took the gesture the inner one declined");
+ assert.true(event.defaultPrevented, "the outer handler accepted it");
+ });
+
+ test("ctx-oracle: an editable target declines without a hook", async function (assert) {
+ await render(
+ <template>
+ <div class="ctx-host" {{dContextMenu component=Actions}}>
+ <textarea class="ctx-textarea"></textarea>
+ <span class="ctx-plain">plain</span>
+ </div>
+ <DMenus />
+ </template>
+ );
+
+ const event = await rightClick(".ctx-textarea");
+
+ assert
+ .dom(".fk-d-menu")
+ .doesNotExist("no menu over a caret-owning control");
+ assert.false(
+ event.defaultPrevented,
+ "the browser keeps its spelling and clipboard menu"
+ );
+
+ // Control: the same host must still open elsewhere, or this test would pass against a
+ // modifier that never opens anything.
+ await rightClick(".ctx-plain");
+ assert
+ .dom(".fk-d-menu")
+ .exists("the same host opens for a target that owns no caret");
+ });
+
+ test("ctx-oracle: right-clicking again moves the menu instead of leaving a second one", async function (assert) {
+ await render(
+ <template>
+ <div class="ctx-host" {{dContextMenu component=Actions}}>host</div>
+ <DMenus />
+ </template>
+ );
+
+ await rightClick(".ctx-host", { clientX: 30, clientY: 40 });
+ assert.dom(".fk-d-menu").exists({ count: 1 }, "one menu after the first");
+
+ await rightClick(".ctx-host", { clientX: 300, clientY: 400 });
+ assert
+ .dom(".fk-d-menu")
+ .exists({ count: 1 }, "still exactly one menu after reopening");
+ });
+
+ test("ctx-oracle: a keyboard-invoked right-click takes focus and gives it back, with nothing wired", async function (assert) {
+ await render(
+ <template>
+ <div class="ctx-host" tabindex="0" {{dContextMenu component=Actions}}>
+ host
+ </div>
+ <DMenus />
+ </template>
+ );
+
+ // The platform dispatches this same event for the context-menu key, so a focusable target
+ // is the whole consumer obligation.
+ find(".ctx-host").focus();
+ await rightClick(".ctx-host");
+
+ assert.true(
+ find(".fk-d-menu").contains(document.activeElement),
+ "focus moved into the menu, so the items are reachable without a pointer"
+ );
+
+ await click(".fk-d-menu .ctx-action");
+
+ assert
+ .dom(".ctx-host")
+ .isFocused(
+ "closing returned focus to the element the modifier is installed on"
+ );
+ });
+
+ test("ctx-oracle: the focus defaults are overridable in both directions", async function (assert) {
+ const elsewhere = () => find(".ctx-elsewhere");
+
+ await render(
+ <template>
+ <div
+ class="ctx-host"
+ tabindex="0"
+ {{dContextMenu component=Actions autofocus=false}}
+ >host</div>
+ <div
+ class="ctx-other"
+ tabindex="0"
+ {{dContextMenu component=Actions focusTarget=elsewhere}}
+ >other</div>
+ <button type="button" class="ctx-elsewhere">elsewhere</button>
+ <DMenus />
+ </template>
+ );
+
+ find(".ctx-host").focus();
+ await rightClick(".ctx-host");
+ assert.dom(".ctx-host").isFocused("autofocus=false keeps focus outside");
+ await click(".fk-d-menu .ctx-action");
+
+ find(".ctx-other").focus();
+ await rightClick(".ctx-other");
+ await click(".fk-d-menu .ctx-action");
+ assert
+ .dom(".ctx-elsewhere")
+ .isFocused("an explicit focusTarget still wins over the element default");
+ });
+
+ test("ctx-oracle: removing the element closes the menu it opened", async function (assert) {
+ await render(
+ <template>
+ {{#unless this.hidden}}
+ <div class="ctx-host" {{dContextMenu component=Actions}}>host</div>
+ {{/unless}}
+ <DMenus />
+ </template>
+ );
+
+ await rightClick(".ctx-host");
+ assert.dom(".fk-d-menu").exists("the menu is open");
+
+ this.set("hidden", true);
+ await settled();
+
+ assert.dom(".ctx-host").doesNotExist("the trigger element is gone");
+ assert
+ .dom(".fk-d-menu")
+ .doesNotExist("its menu went with it, rather than floating detached");
+ });
+});
diff --git a/frontend/discourse/tests/integration/components/float-kit/pointer-anchored-menu-test.gjs b/frontend/discourse/tests/integration/components/float-kit/pointer-anchored-menu-test.gjs
new file mode 100644
index 00000000000..c5f90b17eff
--- /dev/null
+++ b/frontend/discourse/tests/integration/components/float-kit/pointer-anchored-menu-test.gjs
@@ -0,0 +1,264 @@
+import { click, find, focus, render, settled, tab } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import ModalContainer from "discourse/components/modal-container";
+import DMenu from "discourse/float-kit/components/d-menu";
+import DMenus from "discourse/float-kit/components/d-menus";
+import { forceMobile } from "discourse/lib/mobile";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import DButton from "discourse/ui-kit/d-button";
+
+const CloseMenu = <template>
+ <DButton class="close-menu" @action={{@close}}>Close menu</DButton>
+</template>;
+
+module(
+ "Integration | Component | FloatKit | PointerAnchoredMenu",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ // Defect 1: frontend/discourse/float-kit/lib/d-menu-instance.ts:127 ignores a virtual trigger's focus target.
+ test("pointer-oracle: closing a virtual-trigger menu resolves focusTarget at close time", async function (assert) {
+ await render(
+ <template>
+ {{#if this.replaceTarget}}
+ <button type="button" class="focus-target">Replacement target</button>
+ {{else}}
+ <button type="button" class="focus-target">Original target</button>
+ {{/if}}
+ <DMenus />
+ </template>
+ );
+
+ const originalTarget = find(".focus-target");
+ const anchorRect = originalTarget.getBoundingClientRect();
+ const virtualTrigger = { getBoundingClientRect: () => anchorRect };
+ await focus(originalTarget);
+
+ await this.owner.lookup("service:menu").show(virtualTrigger, {
+ component: CloseMenu,
+ autofocus: false,
+ focusTarget: () => find(".focus-target"),
+ });
+ await settled();
+ assert
+ .dom(".fk-d-menu .close-menu")
+ .exists(
+ "the virtual trigger and intended option render without throwing"
+ );
+
+ await focus(".close-menu");
+ this.set("replaceTarget", true);
+ await settled();
+
+ const replacementTarget = find(".focus-target");
+ assert.notStrictEqual(
+ replacementTarget,
+ originalTarget,
+ "the focus destination is a new element created after opening"
+ );
+ assert.false(
+ originalTarget.isConnected,
+ "the original target is detached"
+ );
+ assert.dom(".close-menu").isFocused("the menu owns focus before closing");
+
+ await click(".close-menu");
+
+ assert.dom(".fk-d-menu").doesNotExist("the menu has closed");
+ assert.strictEqual(
+ document.activeElement,
+ replacementTarget,
+ "closing the virtual-trigger menu focuses the current focusTarget element"
+ );
+ });
+
+ // Defect 2: frontend/discourse/float-kit/components/d-float-body.gts:145 emits an id with no label element.
+ test("pointer-oracle: an idless service trigger gives the menu a usable label", async function (assert) {
+ await render(
+ <template>
+ <button type="button" class="menu-trigger">Pointer actions</button>
+ <DMenus />
+ </template>
+ );
+
+ const trigger = find(".menu-trigger");
+ const expectedLabel = trigger.textContent.trim();
+ assert
+ .dom(trigger)
+ .doesNotHaveAttribute("id", "the service trigger has no id");
+
+ await this.owner.lookup("service:menu").show(trigger, {
+ component: CloseMenu,
+ ariaLabel: expectedLabel,
+ contentRole: "dialog",
+ });
+ await settled();
+
+ const float = find(".fk-d-menu");
+ assert
+ .dom(float)
+ .exists("the intended ariaLabel option does not prevent rendering");
+ const labelledby = float.getAttribute("aria-labelledby");
+ const labelReferencesResolve =
+ !labelledby ||
+ labelledby
+ .trim()
+ .split(/\s+/)
+ .every((id) => document.getElementById(id));
+ assert.true(
+ labelReferencesResolve,
+ "every aria-labelledby reference resolves to an element in the document"
+ );
+ assert
+ .dom(float)
+ .hasAttribute(
+ "aria-label",
+ expectedLabel,
+ "the menu exposes the supplied label measured from its trigger"
+ );
+ });
+
+ // Defect 3: frontend/discourse/app/ui-kit/modifiers/d-trap-tab.ts:94 retains a hidden first input.
+ test("pointer-oracle: Tab wraps past a hidden input to the first visible control", async function (assert) {
+ await render(
+ <template>
+ <DMenu
+ @autofocus={{false}}
+ @inline={{true}}
+ @label="Actions"
+ @trapTab={{true}}
+ >
+ <:content>
+ <input hidden aria-label="Hidden input" />
+ <input class="visible-input" aria-label="Visible input" />
+ <button type="button" class="first-button">First action</button>
+ <button type="button" class="last-button">Last action</button>
+ </:content>
+ </DMenu>
+ </template>
+ );
+
+ await click(".fk-d-menu__trigger");
+ const visibleInput = find(".fk-d-menu .visible-input");
+ const firstButton = find(".fk-d-menu .first-button");
+ const lastButton = find(".fk-d-menu .last-button");
+ assert
+ .dom(".fk-d-menu input[hidden]")
+ .isNotVisible("the leading input is hidden");
+
+ await focus(visibleInput);
+ await tab();
+ assert.strictEqual(
+ document.activeElement,
+ firstButton,
+ "Tab reaches the first visible button"
+ );
+ await tab();
+ assert.strictEqual(
+ document.activeElement,
+ lastButton,
+ "Tab reaches the last visible button"
+ );
+ await tab();
+ assert.strictEqual(
+ document.activeElement,
+ visibleInput,
+ "Tab wraps to the visible input instead of stalling on the hidden input"
+ );
+ });
+
+ // Defect 3: frontend/discourse/app/ui-kit/modifiers/d-trap-tab.ts:94 retains a CSS-hidden last input.
+ test("pointer-oracle: Shift+Tab wraps past a CSS-hidden input to the last visible control", async function (assert) {
+ await render(
+ <template>
+ <DMenu
+ @autofocus={{false}}
+ @inline={{true}}
+ @label="Actions"
+ @trapTab={{true}}
+ >
+ <:content>
+ <button type="button" class="first-button">First action</button>
+ <button type="button" class="last-button">Last action</button>
+ <input class="visible-input" aria-label="Visible input" />
+ <input
+ class="css-hidden-input"
+ style="display: none"
+ aria-label="CSS-hidden input"
+ />
+ </:content>
+ </DMenu>
+ </template>
+ );
+
+ await click(".fk-d-menu__trigger");
+ const firstButton = find(".fk-d-menu .first-button");
+ const lastButton = find(".fk-d-menu .last-button");
+ const visibleInput = find(".fk-d-menu .visible-input");
+ assert
+ .dom(".css-hidden-input")
+ .isNotVisible("the trailing input is hidden by CSS");
+
+ await focus(visibleInput);
+ await tab({ backwards: true });
+ assert.strictEqual(
+ document.activeElement,
+ lastButton,
+ "Shift+Tab reaches the last visible button"
+ );
+ await tab({ backwards: true });
+ assert.strictEqual(
+ document.activeElement,
+ firstButton,
+ "Shift+Tab reaches the first visible button"
+ );
+ await tab({ backwards: true });
+ assert.strictEqual(
+ document.activeElement,
+ visibleInput,
+ "Shift+Tab wraps to the visible input instead of stalling on the CSS-hidden input"
+ );
+ });
+
+ test("pointer-oracle: a service menu rendered as a mobile modal exposes its supplied label", async function (assert) {
+ forceMobile();
+
+ await render(
+ <template>
+ <button type="button" class="menu-trigger">Open actions</button>
+ <DMenus />
+ <ModalContainer />
+ </template>
+ );
+
+ const expectedLabel = "Pointer actions for the selected item";
+ await this.owner.lookup("service:menu").show(find(".menu-trigger"), {
+ component: CloseMenu,
+ identifier: "pointer-oracle-mobile-menu",
+ modalForMobile: true,
+ ariaLabel: expectedLabel,
+ });
+ await settled();
+
+ const dialog =
+ '.fk-d-menu-modal[data-identifier="pointer-oracle-mobile-menu"]';
+ assert.dom(dialog).exists("the service menu renders in the modal branch");
+ assert
+ .dom(dialog)
+ .hasAttribute("role", "dialog", "the modal is a dialog");
+ assert
+ .dom(dialog)
+ .hasAttribute("aria-modal", "true", "the dialog is modal");
+ assert.dom(".fk-d-menu").doesNotExist("no popover menu is rendered");
+ assert
+ .dom(dialog)
+ .hasAttribute(
+ "aria-label",
+ expectedLabel,
+ "the mobile menu dialog exposes the supplied accessible label"
+ );
+
+ await click(`${dialog} .close-menu`);
+ });
+ }
+);
diff --git a/frontend/discourse/tests/integration/ui-kit/d-modal-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-modal-test.gjs
index 36986247105..abfc537198c 100644
--- a/frontend/discourse/tests/integration/ui-kit/d-modal-test.gjs
+++ b/frontend/discourse/tests/integration/ui-kit/d-modal-test.gjs
@@ -33,6 +33,53 @@ module("Integration | ui-kit | DModal", function (hooks) {
assert.dom(".d-modal .d-modal__subtitle-text").hasText("Modal Subtitle");
});
+ test("modal-name-oracle: title references respect header visibility", async function (assert) {
+ await render(
+ <template>
+ <DModal
+ @hideHeader={{true}}
+ @inline={{true}}
+ @title="admin.search.modal_title"
+ />
+ </template>
+ );
+
+ assert
+ .dom(".d-modal[role='dialog']")
+ .exists("the hidden-header dialog renders");
+ assert.dom(".d-modal__header").doesNotExist("the header is not rendered");
+ assert
+ .dom(".d-modal[role='dialog']")
+ .doesNotHaveAttribute(
+ "aria-labelledby",
+ "a hidden-header dialog does not reference an unrendered title"
+ );
+
+ await render(
+ <template>
+ <DModal @hideHeader={{false}} @inline={{true}} @title="Modal Title" />
+ </template>
+ );
+
+ assert
+ .dom(".d-modal[role='dialog']")
+ .hasAttribute(
+ "aria-labelledby",
+ "discourse-modal-title",
+ "a visible-header dialog retains its title reference"
+ );
+ assert
+ .dom(".d-modal__header .d-modal__title-text")
+ .hasText("Modal Title", "the visible header renders the title");
+ assert.strictEqual(
+ document.getElementById(
+ find(".d-modal[role='dialog']").getAttribute("aria-labelledby")
+ ),
+ find(".d-modal__header .d-modal__title-text"),
+ "the visible-header dialog's label reference resolves to its rendered title"
+ );
+ });
+
test("named blocks", async function (assert) {
await render(
<template>
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 fe32c3cc778..30b27d2f05d 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
@@ -1,191 +1,163 @@
import Component from "@glimmer/component";
-import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";
-import { trustHTML } from "@ember/template";
import DButton from "discourse/ui-kit/d-button";
import { i18n } from "discourse-i18n";
-export default class CanvasContextMenu extends Component {
- @tracked contextMenu = null;
-
- constructor() {
- super(...arguments);
- this.args.onRegister?.(this);
+/**
+ * Shared so the modifier and every programmatic close name the same menu. `menu.close`
+ * returns silently when an identifier matches nothing, so a typo in one of the close paths
+ * would leave the menu open with nothing to catch it.
+ */
+export const CANVAS_CONTEXT_MENU_IDENTIFIER = "workflows-canvas-context-menu";
+
+/** Builds a synchronous menu decision; selection never supplies the payload. */
+export function decideCanvasContextMenu({ event, rete, containerElement }) {
+ if (!rete) {
+ return false;
}
- get style() {
- if (!this.contextMenu || !this.args.canvasElement) {
- return "";
- }
- const rect = this.args.canvasElement.getBoundingClientRect();
- const left = this.contextMenu.screenX - rect.left;
- const top = this.contextMenu.screenY - rect.top;
- return trustHTML(`left: ${left}px; top: ${top}px`);
- }
-
- @action
- async open(event) {
- event.preventDefault();
- this.contextMenu = null;
-
- if (!this.args.rete) {
- return;
+ const rect = containerElement.getBoundingClientRect();
+ const canvasPos = 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;
+ const selectedIds = rete.getSelectedIds();
+ const useCurrentSelection = selectedIds.nodeIds.has(clientId);
+ const selection = useCurrentSelection
+ ? {
+ nodeIds: [...selectedIds.nodeIds],
+ stickyNoteIds: [...selectedIds.stickyNoteIds],
+ }
+ : { nodeIds: [clientId], stickyNoteIds: [] };
+
+ if (clientId && !useCurrentSelection) {
+ void rete.selectableNodes.select(clientId, false);
}
-
- 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;
- 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 = {
+ return {
+ data: {
nodeId: clientId,
selection,
isUnavailable: nodeEl.dataset.unavailable === "true",
canvasPos,
- screenX: event.clientX,
- screenY: event.clientY,
- };
- return;
- }
-
- this.contextMenu = {
- isCanvas: true,
- canvasPos,
- screenX: event.clientX,
- screenY: event.clientY,
+ },
};
}
- @action
- close() {
- this.contextMenu = null;
- }
+ return { data: { isCanvas: true, canvasPos } };
+}
+export default class CanvasContextMenu extends Component {
@action
- editNode() {
- const nodeId = this.contextMenu.nodeId;
- this.contextMenu = null;
- this.args.onEditNode?.(nodeId);
+ addNode() {
+ const canvasPos = this.args.data.canvasPos;
+ this.args.close();
+ if (canvasPos) {
+ this.args.data.onOpenNodePanel?.(canvasPos);
+ }
}
@action
- deleteNode() {
- const selection = this.contextMenu.selection;
- this.contextMenu = null;
- this.args.onDeleteSelected?.(selection);
+ addStickyNote() {
+ const canvasPos = this.args.data.canvasPos;
+ this.args.close();
+ if (canvasPos) {
+ this.args.data.onAddStickyNote?.(canvasPos);
+ }
}
@action
- cutSelection() {
- const selection = this.contextMenu.selection;
- this.contextMenu = null;
- this.args.onCut?.(selection);
+ copySelection() {
+ const selection = this.args.data.selection;
+ this.args.close();
+ this.args.data.onCopy?.(selection);
}
@action
- copySelection() {
- const selection = this.contextMenu.selection;
- this.contextMenu = null;
- this.args.onCopy?.(selection);
+ cutSelection() {
+ const selection = this.args.data.selection;
+ this.args.close();
+ this.args.data.onCut?.(selection);
}
@action
- pasteSelection() {
- const canvasPos = this.contextMenu?.canvasPos;
- this.contextMenu = null;
- this.args.onPaste?.(canvasPos);
+ deleteNode() {
+ const selection = this.args.data.selection;
+ this.args.close();
+ this.args.data.onDeleteSelected?.(selection);
}
@action
- addNode() {
- const canvasPos = this.contextMenu?.canvasPos;
- this.contextMenu = null;
- if (canvasPos) {
- this.args.onOpenNodePanel?.(canvasPos);
- }
+ editNode() {
+ const nodeId = this.args.data.nodeId;
+ this.args.close();
+ this.args.data.onEditNode?.(nodeId);
}
@action
- addStickyNote() {
- const canvasPos = this.contextMenu?.canvasPos;
- this.contextMenu = null;
- if (canvasPos) {
- this.args.onAddStickyNote?.(canvasPos);
- }
+ pasteSelection() {
+ const canvasPos = this.args.data.canvasPos;
+ this.args.close();
+ this.args.data.onPaste?.(canvasPos);
}
<template>
- {{#if this.contextMenu}}
- <div class="workflows-canvas__context-menu" style={{this.style}}>
- {{#if this.contextMenu.isCanvas}}
+ <div class="workflows-canvas__context-menu">
+ {{#if @data.isCanvas}}
+ <DButton
+ class="btn-transparent workflows-canvas__context-menu-item"
+ @action={{this.addNode}}
+ @icon="plus"
+ @translatedLabel={{i18n "discourse_workflows.canvas.add_step"}}
+ />
+ <DButton
+ class="btn-transparent workflows-canvas__context-menu-item"
+ @action={{this.addStickyNote}}
+ @icon="note-sticky"
+ @translatedLabel={{i18n "discourse_workflows.sticky_note.add"}}
+ />
+ <DButton
+ class="btn-transparent workflows-canvas__context-menu-item"
+ @action={{this.pasteSelection}}
+ @icon="paste"
+ @translatedLabel={{i18n "discourse_workflows.canvas.paste"}}
+ />
+ {{else}}
+ {{#unless @data.isUnavailable}}
<DButton
- @action={{this.addNode}}
- @icon="plus"
- @translatedLabel={{i18n "discourse_workflows.canvas.add_step"}}
class="btn-transparent workflows-canvas__context-menu-item"
+ @action={{this.editNode}}
+ @icon="pencil"
+ @translatedLabel={{i18n "discourse_workflows.edit"}}
/>
- <DButton
- @action={{this.addStickyNote}}
- @icon="note-sticky"
- @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
- @action={{this.editNode}}
- @icon="pencil"
- @translatedLabel={{i18n "discourse_workflows.edit"}}
- 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"
- @translatedLabel={{i18n "discourse_workflows.delete"}}
- class="btn-transparent btn-danger workflows-canvas__context-menu-item"
- />
- {{/if}}
- </div>
- {{/if}}
+ {{/unless}}
+ <DButton
+ class="btn-transparent workflows-canvas__context-menu-item"
+ @action={{this.cutSelection}}
+ @icon="scissors"
+ @translatedLabel={{i18n "discourse_workflows.canvas.cut"}}
+ />
+ <DButton
+ class="btn-transparent workflows-canvas__context-menu-item"
+ @action={{this.copySelection}}
+ @icon="copy"
+ @translatedLabel={{i18n "discourse_workflows.canvas.copy"}}
+ />
+ <DButton
+ class="btn-transparent workflows-canvas__context-menu-item"
+ @action={{this.pasteSelection}}
+ @icon="paste"
+ @translatedLabel={{i18n "discourse_workflows.canvas.paste"}}
+ />
+ <DButton
+ class="btn-transparent btn-danger workflows-canvas__context-menu-item"
+ @action={{this.deleteNode}}
+ @icon="trash-can"
+ @translatedLabel={{i18n "discourse_workflows.delete"}}
+ />
+ {{/if}}
+ </div>
</template>
}
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 fcb6bfe562f..848f080ccd7 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
@@ -8,6 +8,7 @@ import didUpdate from "@ember/render-modifiers/modifiers/did-update";
import { service } from "@ember/service";
import { trustHTML } from "@ember/template";
import DMenu from "discourse/float-kit/components/d-menu";
+import dContextMenu from "discourse/float-kit/modifiers/d-context-menu";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { clipboardCopy } from "discourse/lib/utilities";
@@ -24,7 +25,10 @@ import {
positionCanvasClipboardPayload,
serializeCanvasClipboardPayload,
} from "./canvas-clipboard";
-import CanvasContextMenu from "./canvas-context-menu";
+import CanvasContextMenu, {
+ CANVAS_CONTEXT_MENU_IDENTIFIER,
+ decideCanvasContextMenu,
+} from "./canvas-context-menu";
import { runExecuteStep } from "./canvas-execute-step";
import { exportWorkflowToFile, parseWorkflowImport } from "./canvas-file-io";
import { setupCanvasKeyboard } from "./canvas-keyboard";
@@ -252,7 +256,7 @@ export default class WorkflowCanvas extends Component {
onPaste: (event) => this.handlePasteEvent(event),
onDelete: () => this.deleteSelected(),
onEscape: () => {
- this.contextMenuApi?.close();
+ this.menu.close(CANVAS_CONTEXT_MENU_IDENTIFIER);
this.rete.selector.unselectAll();
this.selectionVersion++;
},
@@ -301,7 +305,7 @@ export default class WorkflowCanvas extends Component {
onNodePicked: () => this.selectionVersion++,
onCanvasPointerDown: () => {
this.selectionVersion++;
- this.contextMenuApi?.close();
+ this.menu.close(CANVAS_CONTEXT_MENU_IDENTIFIER);
this.menu.close("workflows-canvas-menu");
this.args.onCloseNodePanel?.();
},
@@ -600,17 +604,33 @@ export default class WorkflowCanvas extends Component {
}
@action
- registerContextMenu(api) {
- this.contextMenuApi = api;
- }
+ beforeContextMenu(event) {
+ const decision = decideCanvasContextMenu({
+ event,
+ rete: this.rete,
+ containerElement: this.containerElement,
+ });
- @action
- handleContextMenu(event) {
- this.contextMenuApi?.open(event);
+ if (!decision) {
+ return false;
+ }
+
+ return {
+ data: {
+ ...decision.data,
+ onEditNode: this.args.onEditNode,
+ onDeleteSelected: this.deleteSelected,
+ onCut: this.cutSelected,
+ onCopy: this.copySelected,
+ onPaste: this.pasteFromClipboard,
+ onOpenNodePanel: this.args.onOpenNodePanel,
+ onAddStickyNote: this.args.onAddStickyNote,
+ },
+ };
}
#invokeAtViewportCenter(callback) {
- this.contextMenuApi?.close();
+ this.menu.close(CANVAS_CONTEXT_MENU_IDENTIFIER);
callback?.(this.rete.viewportCenter());
}
@@ -703,13 +723,13 @@ export default class WorkflowCanvas extends Component {
@action
copySelected(selection = null) {
- this.contextMenuApi?.close();
+ this.menu.close(CANVAS_CONTEXT_MENU_IDENTIFIER);
this.#copySelectedPayload(selection);
}
@action
cutSelected(selection = null) {
- this.contextMenuApi?.close();
+ this.menu.close(CANVAS_CONTEXT_MENU_IDENTIFIER);
const selectedIds = this.#selectedIds(selection);
if (!this.#copySelectedPayload(selectedIds)) {
@@ -791,7 +811,7 @@ export default class WorkflowCanvas extends Component {
@action
async pasteFromClipboard(target = null) {
- this.contextMenuApi?.close();
+ this.menu.close(CANVAS_CONTEXT_MENU_IDENTIFIER);
const result = await this.#readClipboardPayload();
const systemPayload = this.clipboardWritePending ? null : result.payload;
const useLocalPayload = !systemPayload && this.clipboardPayload;
@@ -957,7 +977,11 @@ export default class WorkflowCanvas extends Component {
<div
class="workflows-canvas"
tabindex="0"
- {{on "contextmenu" this.handleContextMenu}}
+ {{dContextMenu
+ identifier=CANVAS_CONTEXT_MENU_IDENTIFIER
+ component=CanvasContextMenu
+ beforeContextMenu=this.beforeContextMenu
+ }}
{{didInsert this.registerCanvas}}
{{didUpdate this.syncToRete @nodes @connections @autoArrangeRequest}}
>
@@ -1246,20 +1270,6 @@ export default class WorkflowCanvas extends Component {
@onClose={{this.closeAiPanel}}
/>
{{/if}}
-
- <CanvasContextMenu
- @canvasElement={{this.canvasElement}}
- @containerElement={{this.containerElement}}
- @rete={{this.rete}}
- @onEditNode={{@onEditNode}}
- @onDeleteSelected={{this.deleteSelected}}
- @onCut={{this.cutSelected}}
- @onCopy={{this.copySelected}}
- @onPaste={{this.pasteFromClipboard}}
- @onOpenNodePanel={{@onOpenNodePanel}}
- @onAddStickyNote={{@onAddStickyNote}}
- @onRegister={{this.registerContextMenu}}
- />
{{/if}}
</div>
</template>
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss b/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss
index 111c3f72772..d9122eb8fa8 100644
--- a/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss
+++ b/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss
@@ -247,12 +247,6 @@
}
&__context-menu {
- position: absolute;
- z-index: var(--z-canvas-chrome);
- background: var(--secondary);
- border: 1px solid var(--primary-low-mid);
- border-radius: var(--d-border-radius);
- box-shadow: var(--shadow-dropdown);
padding: var(--space-1) 0;
min-width: 180px;
max-height: 400px;
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/canvas/canvas-context-menu-supplemental-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/canvas/canvas-context-menu-supplemental-test.gjs
new file mode 100644
index 00000000000..c98673cf0fb
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/canvas/canvas-context-menu-supplemental-test.gjs
@@ -0,0 +1,155 @@
+import { clearRender, click, findAll, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import CanvasContextMenu, {
+ decideCanvasContextMenu,
+} from "discourse/plugins/discourse-workflows/admin/components/workflows/canvas/canvas-context-menu";
+
+const ITEM = ".workflows-canvas__context-menu-item";
+
+module(
+ "Integration | Component | Workflows | Canvas | CanvasContextMenu supplemental",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.containerElement = document.createElement("div");
+ this.containerElement.getBoundingClientRect = () => ({
+ left: 70,
+ top: 90,
+ });
+ this.rete = {
+ containerToCanvas: (x, y) => ({ x: x / 2 - 5, y: y / 2 - 10 }),
+ getSelectedIds: () => ({
+ nodeIds: new Set(["other-node"]),
+ stickyNoteIds: new Set(["sticky-1"]),
+ }),
+ selectableNodes: {
+ select: (...args) => {
+ this.selectCalls.push(args);
+ return new Promise(() => {});
+ },
+ },
+ };
+ this.selectCalls = [];
+ this.event = {
+ clientX: 130,
+ clientY: 170,
+ target: this.containerElement,
+ };
+ });
+
+ test("declines before the editor is ready", function (assert) {
+ assert.false(
+ decideCanvasContextMenu({ event: this.event, rete: null }),
+ "an uninitialized canvas keeps the native menu"
+ );
+ });
+
+ test("converts container offsets and canvas transforms for insertion", function (assert) {
+ const decision = decideCanvasContextMenu(this);
+
+ assert.deepEqual(
+ decision,
+ { data: { isCanvas: true, canvasPos: { x: 25, y: 30 } } },
+ "insertion uses transformed coordinates relative to the container"
+ );
+ assert.deepEqual(
+ this.selectCalls,
+ [],
+ "empty canvas does not select a node"
+ );
+ });
+
+ test("a nested target replaces an unrelated selection without waiting", function (assert) {
+ const node = document.createElement("div");
+ node.className = "workflow-rete-node";
+ node.dataset.clientId = "clicked-node";
+ node.dataset.unavailable = "true";
+ const child = document.createElement("span");
+ node.appendChild(child);
+ this.containerElement.appendChild(node);
+ this.event.target = child;
+
+ const decision = decideCanvasContextMenu(this);
+
+ assert.deepEqual(
+ decision,
+ {
+ data: {
+ nodeId: "clicked-node",
+ selection: { nodeIds: ["clicked-node"], stickyNoteIds: [] },
+ isUnavailable: true,
+ canvasPos: { x: 25, y: 30 },
+ },
+ },
+ "the pending selection cannot delay or contaminate the clicked node payload"
+ );
+ assert.deepEqual(
+ this.selectCalls,
+ [["clicked-node", false]],
+ "selection starts without accumulating the unrelated entities"
+ );
+ });
+
+ test("each item closes before dispatching its data callback", async function (assert) {
+ const selection = {
+ nodeIds: ["node-1", "node-2"],
+ stickyNoteIds: ["sticky-1"],
+ };
+ const canvasPos = { x: 25, y: 30 };
+
+ for (const [isCanvas, label, callback, payload] of [
+ [false, "Edit", "onEditNode", "node-1"],
+ [false, "Cut", "onCut", selection],
+ [false, "Copy", "onCopy", selection],
+ [false, "Paste", "onPaste", canvasPos],
+ [false, "Delete", "onDeleteSelected", selection],
+ [true, "Add step", "onOpenNodePanel", canvasPos],
+ [true, "Add sticky note", "onAddStickyNote", canvasPos],
+ [true, "Paste", "onPaste", canvasPos],
+ ]) {
+ this.data = {
+ isCanvas,
+ nodeId: "node-1",
+ selection,
+ canvasPos,
+ [callback]: (value) => {
+ assert.step(callback);
+ assert.deepEqual(value, payload, `${label} receives its payload`);
+ },
+ };
+ this.close = () => assert.step("close");
+
+ await render(
+ <template>
+ <CanvasContextMenu @close={{this.close}} @data={{this.data}} />
+ </template>
+ );
+ await click(
+ findAll(ITEM).find((item) => item.textContent.trim() === label)
+ );
+
+ assert.verifySteps(
+ ["close", callback],
+ `${label} closes before dispatch`
+ );
+ await clearRender();
+ }
+ });
+
+ test("unavailable nodes omit Edit but retain selection actions", async function (assert) {
+ this.data = { isUnavailable: true };
+
+ await render(
+ <template><CanvasContextMenu @data={{this.data}} /></template>
+ );
+
+ assert.deepEqual(
+ findAll(ITEM).map((item) => item.textContent.trim()),
+ ["Cut", "Copy", "Paste", "Delete"],
+ "only editing is unavailable"
+ );
+ });
+ }
+);
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
index 7bcc1649e99..3960735d3ba 100644
--- 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
@@ -1,7 +1,36 @@
-import { click, render, settled } from "@ember/test-helpers";
+import { click, find, render, settled } from "@ember/test-helpers";
import { module, test } from "qunit";
+import DMenus from "discourse/float-kit/components/d-menus";
+import dContextMenu from "discourse/float-kit/modifiers/d-context-menu";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-import CanvasContextMenu from "discourse/plugins/discourse-workflows/admin/components/workflows/canvas/canvas-context-menu";
+import CanvasContextMenu, {
+ decideCanvasContextMenu,
+} from "discourse/plugins/discourse-workflows/admin/components/workflows/canvas/canvas-context-menu";
+
+const HOST = ".wf-canvas-host";
+const ITEM = ".workflows-canvas__context-menu-item";
+
+/**
+ * Dispatches the event the browser sends for a right-click and for the context-menu key
+ * alike, and hands it back so a test can see whether anything suppressed the native menu.
+ */
+async function contextMenu(selector, { clientX = 100, clientY = 100 } = {}) {
+ const event = new MouseEvent("contextmenu", {
+ bubbles: true,
+ cancelable: true,
+ clientX,
+ clientY,
+ });
+ find(selector).dispatchEvent(event);
+ await settled();
+ return event;
+}
+
+function itemLabelled(text) {
+ return [...document.querySelectorAll(ITEM)].find(
+ (button) => button.textContent.trim() === text
+ );
+}
module(
"Integration | Component | Workflows | Canvas | CanvasContextMenu",
@@ -9,68 +38,229 @@ module(
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.selected = { nodeIds: new Set(), stickyNoteIds: new Set() };
+ this.selectCalls = [];
+
this.rete = {
containerToCanvas: () => ({ x: 10, y: 20 }),
- getSelectedIds: () => ({
- nodeIds: new Set(),
- stickyNoteIds: new Set(),
- }),
+ getSelectedIds: () => this.selected,
selectableNodes: {
- select: async () => {},
+ select: async (...args) => {
+ this.selectCalls.push(args);
+ },
},
};
- });
- 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;
+ this.handlers = {};
+
+ // Mirrors how the canvas wires the modifier, without rendering the whole canvas.
+ // The callbacks ride on the decision rather than on a `data=` argument, because
+ // dContextMenu spreads the decision last and `decision.data` would overwrite it.
+ this.decide = (event) => {
+ const decision = decideCanvasContextMenu({
+ event,
+ rete: this.rete,
+ containerElement: this.containerElement,
+ });
+
+ if (!decision) {
+ return false;
+ }
+
+ return { data: { ...decision.data, ...this.handlers } };
};
+ });
+
+ test("wf-ctx: right-clicking a node opens the menu and suppresses the native one", async function (assert) {
+ await render(
+ <template>
+ <div
+ class="wf-canvas-host"
+ tabindex="0"
+ {{dContextMenu
+ component=CanvasContextMenu
+ beforeContextMenu=this.decide
+ }}
+ >
+ <div class="workflow-rete-node" data-client-id="node-1"></div>
+ </div>
+ <DMenus />
+ </template>
+ );
+
+ const event = await contextMenu(`${HOST} .workflow-rete-node`);
+
+ assert.dom(".fk-d-menu").exists("the canvas menu opened");
+ assert.true(
+ event.defaultPrevented,
+ "the browser's own menu is suppressed"
+ );
+ });
+
+ test("wf-ctx: cut uses the right-clicked node when the rete selection is empty", async function (assert) {
+ let cutWith;
+ this.handlers = { onCut: (selection) => (cutWith = selection) };
await render(
<template>
- <CanvasContextMenu
- @canvasElement={{this.canvasElement}}
- @containerElement={{this.containerElement}}
- @rete={{this.rete}}
- @onRegister={{this.registerContextMenu}}
- @onCut={{this.cutSelection}}
- />
+ <div
+ class="wf-canvas-host"
+ tabindex="0"
+ {{dContextMenu
+ component=CanvasContextMenu
+ beforeContextMenu=this.decide
+ }}
+ >
+ <div class="workflow-rete-node" data-client-id="node-1"></div>
+ </div>
+ <DMenus />
</template>
);
- await this.contextMenu.open({
+ await contextMenu(`${HOST} .workflow-rete-node`);
+ await click(itemLabelled("Cut"));
+
+ assert.deepEqual(
+ cutWith,
+ { nodeIds: ["node-1"], stickyNoteIds: [] },
+ "the node under the pointer is what gets cut"
+ );
+ });
+
+ test("wf-ctx: right-clicking inside an existing selection keeps the whole selection", async function (assert) {
+ this.selected = {
+ nodeIds: new Set(["node-1", "node-2"]),
+ stickyNoteIds: new Set(["sticky-9"]),
+ };
+
+ const decision = this.decide({
preventDefault() {},
- clientX: 100,
- clientY: 100,
+ clientX: 10,
+ clientY: 10,
target: this.nodeElement,
});
- await settled();
- const cutButton = [
- ...document.querySelectorAll(".workflows-canvas__context-menu-item"),
- ].find((button) => button.textContent.trim() === "Cut");
+ assert.deepEqual(
+ decision.data.selection.nodeIds.sort(),
+ ["node-1", "node-2"],
+ "the existing multi-selection survives the right-click"
+ );
+ assert.deepEqual(
+ decision.data.selection.stickyNoteIds,
+ ["sticky-9"],
+ "selected sticky notes survive too"
+ );
+ assert.deepEqual(
+ this.selectCalls,
+ [],
+ "nothing is re-selected, because the click landed inside the selection"
+ );
+ });
- await click(cutButton);
+ test("wf-ctx: the decision is synchronous even though selecting a node is async", async function (assert) {
+ const decision = this.decide({
+ preventDefault() {},
+ clientX: 10,
+ clientY: 10,
+ target: this.nodeElement,
+ });
+ // dContextMenu declines anything thenable, so an async hook opens no menu at all.
+ assert.notStrictEqual(
+ typeof decision?.then,
+ "function",
+ "the hook returns a decision, not a promise"
+ );
assert.deepEqual(
- this.cutSelectionValue,
- { nodeIds: ["node-1"], stickyNoteIds: [] },
- "the context menu passes the node under the pointer to cut"
+ this.selectCalls,
+ [["node-1", false]],
+ "the node is still selected, without the decision waiting on it"
);
});
+
+ test("wf-ctx: right-clicking empty canvas offers canvas actions at that position", async function (assert) {
+ const decision = this.decide({
+ preventDefault() {},
+ clientX: 10,
+ clientY: 10,
+ target: this.containerElement,
+ });
+
+ assert.true(decision.data.isCanvas, "the canvas branch is taken");
+ assert.deepEqual(
+ decision.data.canvasPos,
+ { x: 10, y: 20 },
+ "the canvas position is carried for insert actions"
+ );
+ });
+
+ test("wf-ctx: the context-menu key opens the menu and closing returns focus to the canvas", async function (assert) {
+ await render(
+ <template>
+ <div
+ class="wf-canvas-host"
+ tabindex="0"
+ {{dContextMenu
+ component=CanvasContextMenu
+ beforeContextMenu=this.decide
+ }}
+ >
+ <div class="workflow-rete-node" data-client-id="node-1"></div>
+ </div>
+ <DMenus />
+ </template>
+ );
+
+ find(HOST).focus();
+ await contextMenu(`${HOST} .workflow-rete-node`);
+
+ assert.true(
+ find(".fk-d-menu").contains(document.activeElement),
+ "focus moved into the menu, so the canvas menu is keyboard operable"
+ );
+
+ await click(itemLabelled("Cut"));
+
+ assert
+ .dom(HOST)
+ .isFocused("closing handed focus back to the canvas element");
+ });
+
+ test("wf-ctx: invoking an item closes the menu", async function (assert) {
+ await render(
+ <template>
+ <div
+ class="wf-canvas-host"
+ tabindex="0"
+ {{dContextMenu
+ component=CanvasContextMenu
+ beforeContextMenu=this.decide
+ }}
+ >
+ <div class="workflow-rete-node" data-client-id="node-1"></div>
+ </div>
+ <DMenus />
+ </template>
+ );
+
+ await contextMenu(`${HOST} .workflow-rete-node`);
+ assert.dom(".fk-d-menu").exists("the menu is open");
+
+ await click(itemLabelled("Cut"));
+
+ assert
+ .dom(".fk-d-menu")
+ .doesNotExist("acting on an item closed the menu");
+ });
}
);
diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/context-menu/declining.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/context-menu/declining.gjs
new file mode 100644
index 00000000000..30934477b3e
--- /dev/null
+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/context-menu/declining.gjs
@@ -0,0 +1,69 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import dContextMenu from "discourse/float-kit/modifiers/d-context-menu";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import { i18n } from "discourse-i18n";
+
+const SurfaceActions = <template>
+ <DDropdownMenu as |dropdown|>
+ <dropdown.item>
+ <DButton
+ @label="styleguide.sections.context_menu.actions.duplicate"
+ @action={{@close}}
+ />
+ </dropdown.item>
+ </DDropdownMenu>
+</template>;
+
+/**
+ * A hook that declines over the text field.
+ *
+ * Declining leaves the event untouched, so the browser opens its own menu and its spelling and
+ * clipboard commands still work. The modifier does this for any caret-owning target by default;
+ * the hook here only reports the decision so it is visible.
+ */
+export default class ContextMenuDecliningExample extends Component {
+ @tracked decision;
+
+ get decisionLabel() {
+ if (!this.decision) {
+ return i18n("styleguide.sections.context_menu.declining.untouched");
+ }
+
+ return i18n(`styleguide.sections.context_menu.declining.${this.decision}`);
+ }
+
+ @action
+ acceptOutsideTheField(event) {
+ const accepted = !event.target.closest("input");
+ this.decision = accepted ? "accepted" : "declined";
+ return accepted;
+ }
+
+ <template>
+ <div
+ class="context-menu-demo__surface"
+ tabindex="0"
+ {{dContextMenu
+ component=SurfaceActions
+ beforeContextMenu=this.acceptOutsideTheField
+ }}
+ >
+ <span class="context-menu-demo__label">
+ {{i18n "styleguide.sections.context_menu.declining.surface"}}
+ </span>
+
+ <input
+ class="context-menu-demo__field"
+ type="text"
+ value={{i18n "styleguide.sections.context_menu.declining.field"}}
+ />
+
+ <output
+ class="context-menu-demo__decision"
+ >{{this.decisionLabel}}</output>
+ </div>
+ </template>
+}
diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/context-menu/nesting.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/context-menu/nesting.gjs
new file mode 100644
index 00000000000..063d1833510
--- /dev/null
+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/context-menu/nesting.gjs
@@ -0,0 +1,63 @@
+import dContextMenu from "discourse/float-kit/modifiers/d-context-menu";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import { i18n } from "discourse-i18n";
+
+const BlockActions = <template>
+ <DDropdownMenu as |dropdown|>
+ <dropdown.item>
+ <DButton
+ @label="styleguide.sections.context_menu.actions.duplicate"
+ @action={{@close}}
+ />
+ </dropdown.item>
+ <dropdown.item>
+ <DButton
+ @label="styleguide.sections.context_menu.actions.delete"
+ @action={{@close}}
+ />
+ </dropdown.item>
+ </DDropdownMenu>
+</template>;
+
+const RowActions = <template>
+ <DDropdownMenu as |dropdown|>
+ <dropdown.item>
+ <DButton
+ @label="styleguide.sections.context_menu.actions.rename"
+ @action={{@close}}
+ />
+ </dropdown.item>
+ </DDropdownMenu>
+</template>;
+
+/**
+ * Two surfaces, one inside the other, each with its own menu.
+ *
+ * The event bubbles, so both would run without arbitration. Accepting stops propagation, which
+ * is why the inner surface's menu opens alone rather than alongside its parent's.
+ *
+ * The only thing either surface does for the keyboard is take focus. Opening at the caret,
+ * moving focus into the menu and returning it on close all come from the modifier.
+ */
+export default <template>
+ <div
+ class="context-menu-demo__surface"
+ tabindex="0"
+ {{dContextMenu component=BlockActions}}
+ >
+ <span class="context-menu-demo__label">
+ {{i18n "styleguide.sections.context_menu.nesting.outer"}}
+ </span>
+
+ <div
+ class="context-menu-demo__surface --nested"
+ tabindex="0"
+ {{dContextMenu component=RowActions}}
+ >
+ <span class="context-menu-demo__label">
+ {{i18n "styleguide.sections.context_menu.nesting.inner"}}
+ </span>
+ </div>
+ </div>
+</template>
diff --git a/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/context-menu.gjs b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/context-menu.gjs
new file mode 100644
index 00000000000..3a9c0a173bd
--- /dev/null
+++ b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/context-menu.gjs
@@ -0,0 +1,45 @@
+import { i18n } from "discourse-i18n";
+import ContextMenuDecliningExample from "../../examples/molecules/context-menu/declining";
+import contextMenuDecliningSource from "../../examples/molecules/context-menu/declining?source=file";
+import ContextMenuNestingExample from "../../examples/molecules/context-menu/nesting";
+import contextMenuNestingSource from "../../examples/molecules/context-menu/nesting?source=file";
+import StyleguideExample from "../../styleguide-example";
+
+/**
+ * Demos for the context-menu modifier: what a right-click opens, and what happens when a
+ * handler declines it.
+ *
+ * Both examples use ordinary surfaces rather than a real editor, so anything that misbehaves
+ * here is the modifier rather than a component wrapped around it.
+ */
+export default <template>
+ <p class="section-description">
+ {{i18n "styleguide.sections.context_menu.description"}}
+ </p>
+
+ <StyleguideExample
+ @title={{i18n "styleguide.sections.context_menu.nesting.example"}}
+ @kind="modifier"
+ @description={{i18n
+ "styleguide.sections.context_menu.nesting.example_description"
+ }}
+ @tryThis={{i18n "styleguide.sections.context_menu.nesting.try_this"}}
+ @note={{i18n "styleguide.sections.context_menu.nesting.note"}}
+ @code={{contextMenuNestingSource}}
+ >
+ <ContextMenuNestingExample />
+ </StyleguideExample>
+
+ <StyleguideExample
+ @title={{i18n "styleguide.sections.context_menu.declining.example"}}
+ @kind="modifier"
+ @description={{i18n
+ "styleguide.sections.context_menu.declining.example_description"
+ }}
+ @tryThis={{i18n "styleguide.sections.context_menu.declining.try_this"}}
+ @note={{i18n "styleguide.sections.context_menu.declining.note"}}
+ @code={{contextMenuDecliningSource}}
+ >
+ <ContextMenuDecliningExample />
+ </StyleguideExample>
+</template>
diff --git a/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js b/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js
index 76a8b750feb..e05d0860be6 100644
--- a/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js
+++ b/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js
@@ -14,6 +14,7 @@ import breadCrumbs from "../components/sections/molecules/bread-crumbs";
import categories from "../components/sections/molecules/categories";
import charCounter from "../components/sections/molecules/char-counter";
import comboButton from "../components/sections/molecules/combo-button";
+import contextMenu from "../components/sections/molecules/context-menu";
import dialog from "../components/sections/molecules/dialog";
import dragAndDrop from "../components/sections/molecules/drag-and-drop";
import emptyState from "../components/sections/molecules/empty-state";
@@ -90,6 +91,7 @@ const SECTIONS = [
{ component: rovingFocus, category: "molecules", id: "roving-focus" },
{ component: tooltips, category: "molecules", id: "tooltips" },
{ component: menus, category: "molecules", id: "menus" },
+ { component: contextMenu, category: "molecules", id: "context-menu" },
{ component: multiselect, category: "molecules", id: "multi-select" },
{ component: toasts, category: "molecules", id: "toasts" },
{ component: dialog, category: "molecules", id: "dialog" },
diff --git a/plugins/styleguide/assets/stylesheets/styleguide.scss b/plugins/styleguide/assets/stylesheets/styleguide.scss
index fffd5a2b5eb..80678db823d 100644
--- a/plugins/styleguide/assets/stylesheets/styleguide.scss
+++ b/plugins/styleguide/assets/stylesheets/styleguide.scss
@@ -1013,3 +1013,44 @@
line-height: 1.4;
}
}
+
+.context-menu-demo {
+ &__surface {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 0.75em;
+ padding: 1em;
+ border: 1px dashed var(--primary-low-mid);
+ border-radius: var(--d-border-radius);
+ background: var(--primary-very-low);
+ cursor: context-menu;
+
+ &:focus-visible {
+ outline: 2px solid var(--tertiary);
+ outline-offset: 2px;
+ }
+
+ &.--nested {
+ align-self: stretch;
+ border-style: solid;
+ border-color: var(--tertiary);
+ background: var(--secondary);
+ }
+ }
+
+ &__label {
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ }
+
+ &__field {
+ width: 100%;
+ max-width: 24em;
+ }
+
+ &__decision {
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+ }
+}
diff --git a/plugins/styleguide/config/locales/client.en.yml b/plugins/styleguide/config/locales/client.en.yml
index c9042341946..1b5f2ef3459 100644
--- a/plugins/styleguide/config/locales/client.en.yml
+++ b/plugins/styleguide/config/locales/client.en.yml
@@ -35,6 +35,30 @@ en:
title: "Date/Time inputs"
menus:
title: "Menus"
+ context_menu:
+ title: "Context menu"
+ description: "A right-click opens a menu at the pointer instead of the browser's own. The surfaces below are plain regions rather than real components, so anything that misbehaves here is the modifier."
+ actions:
+ duplicate: "Duplicate"
+ delete: "Delete"
+ rename: "Rename row"
+ nesting:
+ example: "dContextMenu"
+ example_description: "Opens a menu where the pointer is. The reference it anchors to is the menu's own trigger, so nothing else has to know the menu was opened from a right-click."
+ try_this: "Right-click the outer surface, then right-click the inner one. Both are focusable, so Tab to one and press the context-menu key or Shift+F10 to open the same menu without a mouse."
+ note: "Both surfaces carry their own menu and the event bubbles through both. Accepting stops propagation, so the innermost handler opens its menu alone instead of alongside its parent's. The keyboard route is the browser's own: it dispatches the same event to the focused element, which is why the target has to be focusable and why each surface names itself as the focus target so closing gives focus back."
+ outer: "Outer surface"
+ inner: "Inner surface"
+ declining:
+ example: "Declining a right-click"
+ example_description: "A handler decides, synchronously, whether to replace the native menu. Declining leaves the event completely untouched, so an outer handler or the browser still gets it."
+ try_this: "Right-click the surface, then right-click inside the text field."
+ note: "A target that owns a text caret keeps the browser's own menu by default, so spelling and clipboard commands still work without a consumer opting out. The hook here only reports the decision so it is visible."
+ surface: "Outer surface"
+ field: "Right-click me for the browser's own menu"
+ untouched: "No right-click yet"
+ accepted: "Last right-click: accepted"
+ declined: "Last right-click: declined, the browser took it"
multi_select:
title: "Multi select"
toasts:
diff --git a/plugins/styleguide/spec/system/smoke_test_spec.rb b/plugins/styleguide/spec/system/smoke_test_spec.rb
index f7da1683188..af98265a635 100644
--- a/plugins/styleguide/spec/system/smoke_test_spec.rb
+++ b/plugins/styleguide/spec/system/smoke_test_spec.rb
@@ -30,6 +30,7 @@ RSpec.describe "Styleguide Smoke Test" do
{ href: "/molecules/categories", title: "Categories" },
{ href: "/molecules/char-counter", title: "Character Counter" },
{ href: "/molecules/combo-button", title: "Combo Button" },
+ { href: "/molecules/context-menu", title: "Context menu" },
{ href: "/molecules/empty-state", title: "Empty State" },
{ href: "/molecules/menus", title: "Menus" },
{ href: "/molecules/navigation-bar", title: "Navigation Bar" },
diff --git a/plugins/styleguide/test/javascripts/integration/components/context-menu-section-test.gjs b/plugins/styleguide/test/javascripts/integration/components/context-menu-section-test.gjs
new file mode 100644
index 00000000000..0ba4b622d46
--- /dev/null
+++ b/plugins/styleguide/test/javascripts/integration/components/context-menu-section-test.gjs
@@ -0,0 +1,96 @@
+import { click, find, findAll, render, settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import DMenus from "discourse/float-kit/components/d-menus";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import ContextMenuSection from "discourse/plugins/styleguide/discourse/components/sections/molecules/context-menu";
+
+/**
+ * Dispatches the same event the browser sends for both a right-click and the context-menu key,
+ * so one helper covers the pointer and keyboard routes.
+ */
+async function contextMenu(element, { clientX = 20, clientY = 30 } = {}) {
+ element.dispatchEvent(
+ new MouseEvent("contextmenu", {
+ bubbles: true,
+ cancelable: true,
+ clientX,
+ clientY,
+ })
+ );
+ await settled();
+}
+
+module(
+ "Integration | Component | Styleguide | context menu section",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("styleguide-ctx: the section renders and its surface opens a menu", async function (assert) {
+ await render(
+ <template>
+ <ContextMenuSection />
+ <DMenus />
+ </template>
+ );
+
+ const surface = find(".context-menu-demo__surface");
+ assert.dom(surface).exists("the demo surface rendered");
+
+ await contextMenu(surface);
+
+ assert
+ .dom(".fk-d-menu")
+ .exists("right-clicking the documented surface opens its menu");
+ });
+
+ test("styleguide-ctx: the demo surfaces are reachable by keyboard", async function (assert) {
+ await render(
+ <template>
+ <ContextMenuSection />
+ <DMenus />
+ </template>
+ );
+
+ // The context-menu key only reaches an element that can hold focus, so a demo built from
+ // non-focusable divs would document a pattern nobody can operate without a mouse.
+ const surfaces = findAll(".context-menu-demo__surface");
+ assert.true(surfaces.length >= 3, "all three demo surfaces rendered");
+
+ surfaces.forEach((surface) => {
+ assert
+ .dom(surface)
+ .hasAttribute(
+ "tabindex",
+ "0",
+ "every documented surface can take focus"
+ );
+ });
+ });
+
+ test("styleguide-ctx: closing returns focus to the surface the menu came from", async function (assert) {
+ await render(
+ <template>
+ <ContextMenuSection />
+ <DMenus />
+ </template>
+ );
+
+ const surface = find(".context-menu-demo__surface");
+ surface.focus();
+ await contextMenu(surface);
+
+ assert.true(
+ find(".fk-d-menu").contains(document.activeElement),
+ "focus moved into the open menu"
+ );
+
+ await click(".fk-d-menu button");
+
+ assert
+ .dom(surface)
+ .isFocused(
+ "focus came back to the surface rather than being stranded on the document"
+ );
+ });
+ }
+);
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice/video-tile.gjs b/plugins/voice/assets/javascripts/discourse/components/voice/video-tile.gjs
index d07a752eb0e..d98e35acc9a 100644
--- a/plugins/voice/assets/javascripts/discourse/components/voice/video-tile.gjs
+++ b/plugins/voice/assets/javascripts/discourse/components/voice/video-tile.gjs
@@ -9,6 +9,7 @@ import { service } from "@ember/service";
import { trustHTML } from "@ember/template";
import { avatarUrl } from "discourse/lib/avatar-utils";
import { prioritizeNameInUx } from "discourse/lib/settings";
+import virtualElementFromPoint from "discourse/lib/virtual-element-from-point";
import { eq } from "discourse/truth-helpers";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import dIcon from "discourse/ui-kit/helpers/d-icon";
@@ -21,7 +22,6 @@ import {
DEFAULT_TILE_ASPECT,
trackVideoAspect,
} from "../../lib/voice/video-grid-layout";
-import virtualElementFromEvent from "../../lib/voice/virtual-element-from-event";
import VoiceParticipantSidebarContextMenu from "../voice-participant-sidebar-context-menu";
export default class VoiceVideoTile extends Component {
@@ -82,7 +82,10 @@ export default class VoiceVideoTile extends Component {
event.preventDefault();
event.stopPropagation();
- this.#showParticipantMenu(virtualElementFromEvent(event), "bottom-start");
+ this.#showParticipantMenu(
+ virtualElementFromPoint(event.clientX, event.clientY),
+ "bottom-start"
+ );
}
@action
diff --git a/plugins/voice/assets/javascripts/discourse/initializers/voice-sidebar.js b/plugins/voice/assets/javascripts/discourse/initializers/voice-sidebar.js
index a1d2137e6bd..e332d9b52a1 100644
--- a/plugins/voice/assets/javascripts/discourse/initializers/voice-sidebar.js
+++ b/plugins/voice/assets/javascripts/discourse/initializers/voice-sidebar.js
@@ -4,6 +4,7 @@ import { avatarUrl } from "discourse/lib/avatar-utils";
import getURL from "discourse/lib/get-url";
import { withPluginApi } from "discourse/lib/plugin-api";
import { prioritizeNameInUx } from "discourse/lib/settings";
+import virtualElementFromPoint from "discourse/lib/virtual-element-from-point";
import { i18n } from "discourse-i18n";
import VoiceCreateRoomModal from "discourse/plugins/voice/discourse/components/modal/voice-create-room";
import VoiceParticipantSidebarContextMenu from "discourse/plugins/voice/discourse/components/voice-participant-sidebar-context-menu";
@@ -12,7 +13,6 @@ import VoiceRoomSidebarContextMenu from "discourse/plugins/voice/discourse/compo
import buildAnonRoomsSection from "../lib/voice/anon-rooms-section";
import { humanKeyName } from "../lib/voice/ptt-utils";
import roomIcon, { roomBadge } from "../lib/voice/room-icon";
-import virtualElementFromEvent from "../lib/voice/virtual-element-from-event";
const LINK_NAME_PREFIX = "voice-room-";
const CHAT_PANEL = "chat";
@@ -772,17 +772,20 @@ export default {
return;
}
- menuService.show(virtualElementFromEvent(event), {
- identifier: "voice-participant-menu",
- component: VoiceParticipantSidebarContextMenu,
- placement: "bottom-start",
- data: {
- room,
- participant,
- canManageRoom: room.can_manage,
- isCurrentUser: participant.id === currentUser?.id,
- },
- });
+ menuService.show(
+ virtualElementFromPoint(event.clientX, event.clientY),
+ {
+ identifier: "voice-participant-menu",
+ component: VoiceParticipantSidebarContextMenu,
+ placement: "bottom-start",
+ data: {
+ room,
+ participant,
+ canManageRoom: room.can_manage,
+ isCurrentUser: participant.id === currentUser?.id,
+ },
+ }
+ );
return;
}
@@ -814,12 +817,15 @@ export default {
return;
}
- menuService.show(virtualElementFromEvent(event), {
- identifier: "voice-room-menu",
- component: VoiceRoomSidebarContextMenu,
- placement: "bottom-start",
- data: { room },
- });
+ menuService.show(
+ virtualElementFromPoint(event.clientX, event.clientY),
+ {
+ identifier: "voice-room-menu",
+ component: VoiceRoomSidebarContextMenu,
+ placement: "bottom-start",
+ data: { room },
+ }
+ );
};
document.addEventListener("contextmenu", sidebarContextMenuHandler);
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/virtual-element-from-event.js b/plugins/voice/assets/javascripts/discourse/lib/voice/virtual-element-from-event.js
deleted file mode 100644
index e410330387f..00000000000
--- a/plugins/voice/assets/javascripts/discourse/lib/voice/virtual-element-from-event.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * Builds a float-kit trigger anchored at the pointer position of an event,
- * so imperative menus open where the user clicked instead of at the edge of
- * the element that received the event.
- *
- * @param {MouseEvent} event
- * @returns {import("@floating-ui/dom").VirtualElement}
- */
-export default function virtualElementFromEvent(event) {
- const { clientX, clientY, target } = event;
-
- return {
- getBoundingClientRect() {
- return {
- x: clientX,
- y: clientY,
- top: clientY,
- bottom: clientY,
- left: clientX,
- right: clientX,
- width: 0,
- height: 0,
- };
- },
- contextElement: target instanceof HTMLElement ? target : undefined,
- };
-}