Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(desktop): overlays treat a context menu opened inside them as their own (MUL-9083) (#10398)

Jiayuan Zhang508ae8a67afb
diff --git a/apps/desktop/src/renderer/src/components/native-context-menu-overlays.test.tsx b/apps/desktop/src/renderer/src/components/native-context-menu-overlays.test.tsx
new file mode 100644
index 0000000000..1eca3f86f8
--- /dev/null
+++ b/apps/desktop/src/renderer/src/components/native-context-menu-overlays.test.tsx
@@ -0,0 +1,217 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useState } from "react";
+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { I18nProvider } from "@multica/core/i18n/react";
+import { useCommentDraftStore } from "@multica/core/issues/stores";
+import { RESOURCES } from "@multica/views/locales";
+import type { ContextMenuRequest } from "../../../shared/context-menu";
+import { SessionRenameInput } from "../../../../../../packages/views/chat/components/session-rename-input";
+import { useCommentAnnotations } from "../../../../../../packages/views/issues/components/use-comment-annotations";
+import { NativeContextMenu } from "./native-context-menu";
+
+const api = vi.hoisted(() => ({
+ listener: null as ((request: ContextMenuRequest) => void) | null,
+ runContextMenuCommand: vi.fn(),
+}));
+
+vi.mock("@multica/core/api", async (original) => {
+ const actual = await original<typeof import("@multica/core/api")>();
+ return {
+ ...actual,
+ api: { ...actual.api, previewCommentTriggers: vi.fn(async () => ({ agents: [], blocked: [] })), listTasksByIssue: vi.fn(async () => []) },
+ };
+});
+vi.mock("../../../../../../packages/views/editor/content-editor", async () => {
+ const { forwardRef, useImperativeHandle, useRef } = await import("react");
+ return {
+ ContentEditor: forwardRef(function Editor({ ariaLabel }: { ariaLabel?: string }, ref) {
+ const input = useRef<HTMLTextAreaElement>(null);
+ useImperativeHandle(ref, () => ({
+ getMarkdown: () => input.current?.value ?? "",
+ focus: () => input.current?.focus(),
+ hasActiveUploads: () => false,
+ }));
+ return <textarea ref={input} aria-label={ariaLabel} />;
+ }),
+ };
+});
+
+beforeEach(() => {
+ api.listener = null;
+ api.runContextMenuCommand.mockClear();
+ useCommentDraftStore.setState({ drafts: {} });
+ Object.assign(window, {
+ desktopAPI: {
+ onContextMenu: (callback: (request: ContextMenuRequest) => void) => {
+ api.listener = callback;
+ return () => {
+ api.listener = null;
+ };
+ },
+ runContextMenuCommand: api.runContextMenuCommand,
+ },
+ });
+ // jsdom has no layout; give Floating UI a viewport so the bubble is visible.
+ Object.defineProperty(document.documentElement, "clientWidth", { configurable: true, value: 1024 });
+ Object.defineProperty(document.documentElement, "clientHeight", { configurable: true, value: 768 });
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue(new DOMRect(10, 10, 600, 400));
+ Range.prototype.getBoundingClientRect = vi.fn(() => new DOMRect(10, 10, 120, 20));
+ Range.prototype.getClientRects = vi.fn(() => [] as unknown as DOMRectList);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ delete (window as { desktopAPI?: unknown }).desktopAPI;
+});
+
+function renderHost(page: React.ReactNode) {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return render(
+ <QueryClientProvider client={client}>
+ <I18nProvider locale="en" resources={RESOURCES}>
+ {page}
+ <NativeContextMenu />
+ </I18nProvider>
+ </QueryClientProvider>,
+ );
+}
+
+function request(over: Partial<ContextMenuRequest>): ContextMenuRequest {
+ return {
+ id: 1,
+ x: 10,
+ y: 20,
+ isEditable: false,
+ canCut: false,
+ canCopy: false,
+ canPaste: false,
+ canSelectAll: false,
+ suggestions: [],
+ canAddToDictionary: false,
+ hasLink: false,
+ hasImage: false,
+ ...over,
+ };
+}
+
+/**
+ * A real right-click on a field: the press lands on it, the DOM event fires,
+ * main asks for the menu, the menu takes focus, and the item is pressed and
+ * clicked.
+ */
+async function pickFromFieldMenu(field: HTMLElement, item: RegExp) {
+ fireEvent.pointerDown(field, { button: 2 });
+ fireEvent.contextMenu(field, { clientX: 5, clientY: 5 });
+ act(() => api.listener?.(request({ isEditable: true, canCut: true, canCopy: true, canPaste: true })));
+ const menu = await screen.findByRole("menu");
+ await waitFor(() => expect(menu.contains(document.activeElement)).toBe(true));
+ const entry = screen.getByRole("menuitem", { name: item });
+ fireEvent.pointerDown(entry, { button: 0 });
+ fireEvent.click(entry);
+ await waitFor(() => expect(api.runContextMenuCommand).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(screen.queryByRole("menu")).toBeNull());
+}
+
+const draftKey = "reply:issue:root" as const;
+
+function AnnotationHost() {
+ const annotation = useCommentAnnotations({
+ issueId: "issue",
+ draftKey,
+ sources: [{ id: "root", name: "Agent" }],
+ enabled: true,
+ });
+ return (
+ <div ref={annotation.cardRef} {...annotation.captureProps}>
+ {annotation.popup}
+ {annotation.composer?.render()}
+ <div data-comment-content="root" tabIndex={0}>Selected text</div>
+ <button type="button">Elsewhere</button>
+ </div>
+ );
+}
+
+async function openAnnotationNote() {
+ const source = document.querySelector<HTMLElement>("[data-comment-content]")!;
+ const range = document.createRange();
+ range.selectNodeContents(source);
+ act(() => {
+ window.getSelection()!.removeAllRanges();
+ window.getSelection()!.addRange(range);
+ });
+ fireEvent.pointerUp(source);
+ fireEvent.click(await screen.findByRole("button", { name: "Add to reply" }));
+ const note = await screen.findByRole("textbox", { name: "Comment" });
+ note.focus();
+ return note;
+}
+
+describe("NativeContextMenu inside an overlay", () => {
+ it("keeps a comment annotation's note open while its own menu pastes", async () => {
+ renderHost(<AnnotationHost />);
+ const note = await openAnnotationNote();
+
+ await pickFromFieldMenu(note, /^Paste/);
+
+ expect(api.runContextMenuCommand).toHaveBeenCalledWith({ id: 1, type: "paste" });
+ expect(note.isConnected).toBe(true);
+ await waitFor(() => expect(note).toHaveFocus());
+ });
+
+ it("lets Escape close only the menu over an annotation note", async () => {
+ renderHost(<AnnotationHost />);
+ const note = await openAnnotationNote();
+ fireEvent.pointerDown(note, { button: 2 });
+ fireEvent.contextMenu(note, { clientX: 5, clientY: 5 });
+ act(() => api.listener?.(request({ isEditable: true, canPaste: true })));
+ const menu = await screen.findByRole("menu");
+ await waitFor(() => expect(menu.contains(document.activeElement)).toBe(true));
+
+ fireEvent.keyDown(document.activeElement!, { key: "Escape" });
+
+ await waitFor(() => expect(screen.queryByRole("menu")).toBeNull());
+ expect(note.isConnected).toBe(true);
+ expect(api.runContextMenuCommand).not.toHaveBeenCalled();
+ });
+
+ it("still closes the annotation note on a press outside", async () => {
+ renderHost(<AnnotationHost />);
+ const note = await openAnnotationNote();
+
+ fireEvent.pointerDown(screen.getByRole("button", { name: "Elsewhere" }));
+
+ await waitFor(() => expect(note.isConnected).toBe(false));
+ });
+
+ it("does not commit an inline title when choosing Cut from its context menu", async () => {
+ const submit = vi.fn();
+ function RenameHost() {
+ const [editing, setEditing] = useState(true);
+ return editing ? (
+ <SessionRenameInput
+ initialValue="alpha beta"
+ onSubmit={(value) => {
+ submit(value);
+ setEditing(false);
+ }}
+ onCancel={() => setEditing(false)}
+ />
+ ) : (
+ <span>Committed title</span>
+ );
+ }
+ renderHost(<RenameHost />);
+ const input = screen.getByRole("textbox") as HTMLInputElement;
+ input.setSelectionRange(0, 5);
+
+ await pickFromFieldMenu(input, /^Cut/);
+
+ expect({ submitted: submit.mock.calls.length, inputConnected: input.isConnected }).toEqual({
+ submitted: 0,
+ inputConnected: true,
+ });
+ fireEvent.pointerDown(document.body);
+ expect(submit).toHaveBeenCalledWith("alpha beta");
+ });
+});
diff --git a/apps/desktop/src/renderer/src/components/native-context-menu.test.tsx b/apps/desktop/src/renderer/src/components/native-context-menu.test.tsx
index e01fb61990..3e8055bbe5 100644
--- a/apps/desktop/src/renderer/src/components/native-context-menu.test.tsx
+++ b/apps/desktop/src/renderer/src/components/native-context-menu.test.tsx
@@ -1,12 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { useState } from "react";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { I18nProvider } from "@multica/core/i18n/react";
import type { SupportedLocale } from "@multica/core/i18n";
import { RESOURCES } from "@multica/views/locales";
import { useContextMenuScope, type ContextMenuScope } from "@multica/views/common/context-menu-scope";
import type { ContextMenuRequest } from "../../../shared/context-menu";
-import { SessionRenameInput } from "../../../../../../packages/views/chat/components/session-rename-input";
import { NativeContextMenu, tableToMarkdown } from "./native-context-menu";
const api = vi.hoisted(() => ({
@@ -267,22 +265,4 @@ describe("NativeContextMenu", () => {
const handled = fireEvent.keyDown(link, { key: "F10", shiftKey: true });
expect({ nativeAllowed: handled, customMenu: !!screen.queryByRole("menu") }).toEqual({ nativeAllowed: true, customMenu: false });
});
-
- it("does not commit an inline title when choosing Cut from its context menu", async () => {
- const submit = vi.fn();
- function RenameHost() {
- const [editing, setEditing] = useState(true);
- return editing ? <SessionRenameInput initialValue="alpha beta" onSubmit={(value) => { submit(value); setEditing(false); }} onCancel={() => setEditing(false)} /> : <span>Committed title</span>;
- }
- renderHost("en", <RenameHost />);
- const input = screen.getByRole("textbox") as HTMLInputElement;
- input.focus();
- input.setSelectionRange(0, 5);
- rightClick(input, request({ isEditable: true, canCut: true, canCopy: true }));
- const cut = await screen.findByRole("menuitem", { name: /^Cut/ });
- fireEvent.pointerDown(cut, { button: 0 });
- fireEvent.click(cut);
- await waitFor(() => expect(api.runContextMenuCommand).toHaveBeenCalled());
- expect({ submitted: submit.mock.calls.length, inputConnected: input.isConnected }).toEqual({ submitted: 0, inputConnected: true });
- });
});
diff --git a/apps/desktop/src/renderer/src/components/native-context-menu.tsx b/apps/desktop/src/renderer/src/components/native-context-menu.tsx
index 420e267d41..80132242f4 100644
--- a/apps/desktop/src/renderer/src/components/native-context-menu.tsx
+++ b/apps/desktop/src/renderer/src/components/native-context-menu.tsx
@@ -17,6 +17,7 @@ import {
type ResolvedContextMenuScope,
type RowActionItem,
} from "@multica/views/common/context-menu-scope";
+import { contextMenuOriginRef } from "@multica/views/common/context-menu-origin";
import { contextPrimitives } from "@multica/views/common/menu-primitives";
import {
contextMenuActions,
@@ -45,6 +46,8 @@ interface OpenMenu {
/** Focus and selection when the menu opened; an edit command needs both back. */
focus: HTMLElement | null;
ranges: Range[];
+ /** The element the menu is for; overlays around it treat the menu as their own. */
+ origin: Element | null;
page: PageItems | null;
}
@@ -164,11 +167,13 @@ export function NativeContextMenu() {
);
if (!hasContextMenuItems(request) && !hasPageItems(page)) return;
pending.current = null;
+ const focus = active instanceof HTMLElement && active !== document.body ? active : null;
setMenu({
request,
point,
- focus: active instanceof HTMLElement && active !== document.body ? active : null,
+ focus,
ranges,
+ origin: (fresh ? last.target : null) ?? focus,
page,
});
setOpen(true);
@@ -190,6 +195,8 @@ export function NativeContextMenu() {
: undefined,
[point],
);
+ const origin = menu?.origin ?? null;
+ const originRef = useMemo(() => contextMenuOriginRef(origin), [origin]);
if (!menu) return null;
@@ -318,6 +325,7 @@ export function NativeContextMenu() {
}}
>
<ContextMenuContent
+ ref={originRef}
anchor={anchor}
side="bottom"
align="start"
diff --git a/packages/views/chat/components/session-rename-input.test.tsx b/packages/views/chat/components/session-rename-input.test.tsx
index 494546b128..568fde948f 100644
--- a/packages/views/chat/components/session-rename-input.test.tsx
+++ b/packages/views/chat/components/session-rename-input.test.tsx
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import { I18nProvider } from "@multica/core/i18n/react";
import enChat from "../../locales/en/chat.json";
+import { contextMenuOriginRef } from "../../common/context-menu-origin";
import { SessionRenameInput } from "./session-rename-input";
const TEST_RESOURCES = { en: { chat: enChat } };
@@ -57,8 +58,8 @@ describe("SessionRenameInput", () => {
const cut = menu.appendChild(document.createElement("div"));
cut.setAttribute("role", "menuitem");
document.body.appendChild(menu);
+ const release = contextMenuOriginRef(input)(menu);
- fireEvent.contextMenu(input);
fireEvent.pointerDown(cut);
fireEvent.click(cut);
expect(onSubmit).not.toHaveBeenCalled();
@@ -66,6 +67,7 @@ describe("SessionRenameInput", () => {
fireEvent.pointerDown(document.body);
expect(onSubmit).toHaveBeenCalledTimes(1);
+ release?.();
menu.remove();
});
diff --git a/packages/views/chat/components/session-rename-input.tsx b/packages/views/chat/components/session-rename-input.tsx
index 4cad3ff8de..ce71e2a75f 100644
--- a/packages/views/chat/components/session-rename-input.tsx
+++ b/packages/views/chat/components/session-rename-input.tsx
@@ -2,6 +2,7 @@
import { useEffect, useRef, useState } from "react";
import { isImeComposing } from "@multica/core/utils";
+import { contextMenuOrigin } from "../../common/context-menu-origin";
import { useT } from "../../i18n";
/**
@@ -14,7 +15,7 @@ import { useT } from "../../i18n";
* move focus to sibling rows and nested actions while the user is still
* interacting with the panel. Instead a document-level `pointerdown`
* listener commits only when the user actually clicks outside the input
- * (the input's own context menu is not outside).
+ * (a context menu opened on the input is not outside).
*/
export function SessionRenameInput({
initialValue,
@@ -36,9 +37,6 @@ export function SessionRenameInput({
valueRef.current = value;
const onSubmitRef = useRef(onSubmit);
onSubmitRef.current = onSubmit;
- // A right-click on the input opens its edit menu; picking Cut or Paste
- // there is still editing, not a click outside.
- const ownMenuOpenRef = useRef(false);
useEffect(() => {
inputRef.current?.focus();
@@ -47,9 +45,7 @@ export function SessionRenameInput({
const handlePointerDown = (e: PointerEvent) => {
const input = inputRef.current;
if (!input) return;
- if (input.contains(e.target as Node)) return;
- if (ownMenuOpenRef.current && e.target instanceof Element && e.target.closest('[role="menu"]')) return;
- ownMenuOpenRef.current = false;
+ if (input.contains(contextMenuOrigin(e.target) as Node)) return;
onSubmitRef.current(valueRef.current);
};
// Capture phase — commit before outside-click handling can close the
@@ -70,9 +66,6 @@ export function SessionRenameInput({
onChange={(e) => setValue(e.target.value)}
onClick={(e) => e.stopPropagation()}
onPointerDown={(e) => e.stopPropagation()}
- onContextMenu={() => {
- ownMenuOpenRef.current = true;
- }}
onKeyDown={(e) => {
// Keep editing keys inside the input instead of letting the row
// selection keyboard handler consume them.
diff --git a/packages/views/common/context-menu-origin.ts b/packages/views/common/context-menu-origin.ts
new file mode 100644
index 0000000000..8677095fd7
--- /dev/null
+++ b/packages/views/common/context-menu-origin.ts
@@ -0,0 +1,35 @@
+const OVERLAY_OWNER = "data-editor-overlay-owner";
+const origins = new WeakMap<Element, Element>();
+
+/**
+ * A ref for a context menu's popup that records the element the menu was
+ * opened on. The popup is portaled to the body, so a press or focus in it
+ * reads as outside every overlay around that element. Overlays that check
+ * containment resolve the event through `contextMenuOrigin`; overlays that
+ * check `data-editor-overlay-owner` find the origin's owner on the popup.
+ * Either way, picking Cut or Paste from a field's own menu stays inside it.
+ */
+export function contextMenuOriginRef(origin: Element | null) {
+ return (popup: Element | null) => {
+ if (!popup || !origin) return;
+ origins.set(popup, origin);
+ const owner = origin.closest(`[${OVERLAY_OWNER}]`)?.getAttribute(OVERLAY_OWNER);
+ if (owner) popup.setAttribute(OVERLAY_OWNER, owner);
+ return () => {
+ origins.delete(popup);
+ if (owner) popup.removeAttribute(OVERLAY_OWNER);
+ };
+ };
+}
+
+/**
+ * Where an event target belongs: the element its context menu was opened on
+ * when the target is inside one, otherwise the target itself.
+ */
+export function contextMenuOrigin<T extends EventTarget | null>(target: T): T | Element {
+ for (let node: Node | null = target instanceof Node ? target : null; node; node = node.parentNode) {
+ const origin = node instanceof Element ? origins.get(node) : undefined;
+ if (origin) return origin;
+ }
+ return target;
+}
diff --git a/packages/views/editor/bubble-menu.test.tsx b/packages/views/editor/bubble-menu.test.tsx
index 248f5a2a40..7a051347b2 100644
--- a/packages/views/editor/bubble-menu.test.tsx
+++ b/packages/views/editor/bubble-menu.test.tsx
@@ -1,6 +1,9 @@
-import { act, fireEvent, render, screen } from "@testing-library/react";
+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { Editor } from "@tiptap/core";
+import { useState } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { ContextMenu, ContextMenuContent, ContextMenuItem } from "@multica/ui/components/ui/context-menu";
+import { contextMenuOriginRef } from "../common/context-menu-origin";
const formatState = vi.hoisted(() => ({ codeBlock: false }));
@@ -164,6 +167,61 @@ describe("EditorBubbleMenu accessibility", () => {
}
});
+ function showOver(editor: Editor) {
+ Object.defineProperty(editor, "isInitialized", { value: true });
+ document.body.appendChild(editor.view.dom).textContent = "selected text";
+ render(<EditorBubbleMenu editor={editor} />);
+ const handler = (event: string) =>
+ vi.mocked(editor.on).mock.calls.find(([name]) => name === event)?.[1] as () => void;
+ act(() => handler("transaction")());
+ return { blur: handler("blur") };
+ }
+
+ it("stays up while a context menu opened in the editor takes focus and runs an item", async () => {
+ const editor = createEditor();
+ const { blur } = showOver(editor);
+ const copy = vi.fn();
+ function EditMenu() {
+ const [open, setOpen] = useState(true);
+ return (
+ <ContextMenu open={open} onOpenChange={setOpen}>
+ <ContextMenuContent ref={contextMenuOriginRef(editor.view.dom)}>
+ <ContextMenuItem onClick={copy}>Copy</ContextMenuItem>
+ </ContextMenuContent>
+ </ContextMenu>
+ );
+ }
+ render(<EditMenu />);
+
+ const menu = await screen.findByRole("menu");
+ await waitFor(() => expect(menu.contains(document.activeElement)).toBe(true));
+ await act(async () => {
+ blur();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+ const item = screen.getByRole("menuitem", { name: "Copy" });
+ fireEvent.pointerDown(item, { button: 0 });
+ fireEvent.mouseDown(item, { button: 0 });
+ fireEvent.click(item);
+
+ await waitFor(() => expect(screen.queryByRole("menu")).toBeNull());
+ expect(copy).toHaveBeenCalledTimes(1);
+ expect(screen.getByLabelText("Bold", { selector: "button" })).toBeVisible();
+ editor.view.dom.remove();
+ });
+
+ it("hides on a press outside the editor", () => {
+ const editor = createEditor();
+ showOver(editor);
+ const outside = document.body.appendChild(document.createElement("button"));
+
+ fireEvent.mouseDown(outside);
+
+ expect(screen.getByLabelText("Bold", { selector: "button" })).not.toBeVisible();
+ outside.remove();
+ editor.view.dom.remove();
+ });
+
it("gives every icon-only link editing control an accessible name", () => {
render(<EditorBubbleMenu editor={createEditor()} />);
diff --git a/packages/views/editor/bubble-menu.tsx b/packages/views/editor/bubble-menu.tsx
index fc61d8909a..27a84d1b18 100644
--- a/packages/views/editor/bubble-menu.tsx
+++ b/packages/views/editor/bubble-menu.tsx
@@ -37,6 +37,7 @@ import { useCreateIssue } from "@multica/core/issues/mutations";
import { useT } from "../i18n";
import { createShortcutChord, type ShortcutChord } from "@multica/core/shortcuts";
import { ShortcutKeycaps } from "../common/shortcut-keycaps";
+import { contextMenuOrigin } from "../common/context-menu-origin";
import { Toggle, toggleVariants } from "@multica/ui/components/ui/toggle";
import { Separator } from "@multica/ui/components/ui/separator";
import {
@@ -547,8 +548,9 @@ function EditorBubbleMenu({
setTimeout(() => {
if (editor.isDestroyed) return;
const el = floatingRef.current;
- if (el && el.contains(document.activeElement)) return;
- if (editor.view.hasFocus()) return;
+ const active = contextMenuOrigin(document.activeElement);
+ if (el && el.contains(active)) return;
+ if (editor.view.hasFocus() || editor.view.dom.contains(active)) return;
setVisible(false);
}, 0);
};
@@ -585,7 +587,7 @@ function EditorBubbleMenu({
useEffect(() => {
if (!visible) return;
const handle = (e: MouseEvent) => {
- const target = e.target as HTMLElement;
+ const target = contextMenuOrigin(e.target) as HTMLElement;
if (editor.view.dom.contains(target)) return;
if (floatingRef.current?.contains(target)) return;
setVisible(false);
diff --git a/packages/views/editor/extensions/suggestion-popup.test.tsx b/packages/views/editor/extensions/suggestion-popup.test.tsx
index eb97e79262..0672999297 100644
--- a/packages/views/editor/extensions/suggestion-popup.test.tsx
+++ b/packages/views/editor/extensions/suggestion-popup.test.tsx
@@ -3,9 +3,11 @@ import { EditorContent } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import { Suggestion, type SuggestionProps } from "@tiptap/suggestion";
import { PluginKey } from "@tiptap/pm/state";
-import { forwardRef, useImperativeHandle } from "react";
+import { forwardRef, useImperativeHandle, useState } from "react";
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { ContextMenu, ContextMenuContent, ContextMenuItem } from "@multica/ui/components/ui/context-menu";
+import { contextMenuOriginRef } from "../../common/context-menu-origin";
import { createSuggestionPopupRender } from "./suggestion-popup";
import { isPickerAcceptKey } from "../../common/picker-keys";
import { PatchedListItem } from "./list-item";
@@ -205,6 +207,33 @@ describe("createSuggestionPopupRender", () => {
},
);
+ it("stays open while a context menu opened in the editor takes focus and runs an item", async () => {
+ const ed = makeEditor("@");
+ await triggerSuggestion(ed, "@a");
+ const paste = vi.fn();
+ function EditMenu() {
+ const [open, setOpen] = useState(true);
+ return (
+ <ContextMenu open={open} onOpenChange={setOpen}>
+ <ContextMenuContent ref={contextMenuOriginRef(ed.view.dom)}>
+ <ContextMenuItem onClick={paste}>Paste</ContextMenuItem>
+ </ContextMenuContent>
+ </ContextMenu>
+ );
+ }
+ render(<EditMenu />);
+
+ const menu = await screen.findByRole("menu");
+ await waitFor(() => expect(menu.contains(document.activeElement)).toBe(true));
+ const item = screen.getByRole("menuitem", { name: "Paste" });
+ fireEvent.pointerDown(item, { button: 0 });
+ fireEvent.click(item);
+
+ await waitFor(() => expect(screen.queryByRole("menu")).toBeNull());
+ expect(paste).toHaveBeenCalledTimes(1);
+ expect(screen.getByTestId("suggestion-popup")).toBeInTheDocument();
+ });
+
it.each(["@", "/"] as const)(
"keeps the %s popup open long enough for candidate row clicks to insert",
async (char) => {
diff --git a/packages/views/editor/extensions/suggestion-popup.tsx b/packages/views/editor/extensions/suggestion-popup.tsx
index 6a8592bdab..6186f6f823 100644
--- a/packages/views/editor/extensions/suggestion-popup.tsx
+++ b/packages/views/editor/extensions/suggestion-popup.tsx
@@ -5,6 +5,7 @@ import { autoUpdate, computePosition, flip, offset, shift, size } from "@floatin
import { ReactRenderer } from "@tiptap/react";
import { exitSuggestion, type SuggestionKeyDownProps, type SuggestionProps } from "@tiptap/suggestion";
import type { PluginKey } from "@tiptap/pm/state";
+import { contextMenuOrigin } from "../../common/context-menu-origin";
interface SuggestionPopupRenderOptions<
TItem,
@@ -62,9 +63,10 @@ export function createSuggestionPopupRender<
};
const isInsideSuggestionSurface = (
- target: EventTarget | null,
+ eventTarget: EventTarget | null,
props: SuggestionProps<TItem, TSelected>,
) => {
+ const target = contextMenuOrigin(eventTarget);
if (!(target instanceof Node)) return false;
return props.editor.view.dom.contains(target) || !!popup?.contains(target);
};
diff --git a/packages/views/package.json b/packages/views/package.json
index ddf247f33b..2d4ba1c38b 100644
--- a/packages/views/package.json
+++ b/packages/views/package.json
@@ -13,6 +13,7 @@
"./common/actor-avatar": "./common/actor-avatar.tsx",
"./common/appearance-sync": "./common/appearance-sync.tsx",
"./common/cli-install-command": "./common/cli-install-command.tsx",
+ "./common/context-menu-origin": "./common/context-menu-origin.ts",
"./common/context-menu-scope": "./common/context-menu-scope.tsx",
"./common/menu-primitives": "./common/menu-primitives.ts",
"./common/shortcut-keycaps": "./common/shortcut-keycaps.tsx",