Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(desktop): popovers and dropdown menus stay open while a field inside them uses its context menu (MUL-9089) (#10405)
Jiayuan Zhang220f325bea6e
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.tsxindex 1eca3f86f8..64b0fe6f30 100644--- 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@@ -5,6 +5,13 @@ 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 { Popover, PopoverContent, PopoverTrigger } from "@multica/ui/components/ui/popover";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";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";@@ -104,13 +111,13 @@ 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");+ const entry = await screen.findByRole("menuitem", { name: item });+ const menu = entry.closest("[role=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());+ await waitFor(() => expect(menu.isConnected).toBe(false));}const draftKey = "reply:issue:root" as const;@@ -214,4 +221,79 @@ describe("NativeContextMenu inside an overlay", () => {fireEvent.pointerDown(document.body);expect(submit).toHaveBeenCalledWith("alpha beta");});++ function PopoverHost({ nested = false }: { nested?: boolean }) {+ const field = <input aria-label="Search" defaultValue="alpha" />;+ return (+ <>+ <Popover defaultOpen>+ <PopoverTrigger>Open</PopoverTrigger>+ <PopoverContent aria-label="Outer">+ {nested ? (+ <Popover defaultOpen>+ <PopoverTrigger>Inner</PopoverTrigger>+ <PopoverContent aria-label="Inner">{field}</PopoverContent>+ </Popover>+ ) : (+ field+ )}+ </PopoverContent>+ </Popover>+ <button type="button">Elsewhere</button>+ </>+ );+ }++ it("keeps a popover open while the menu of a field inside it pastes", async () => {+ renderHost(<PopoverHost />);+ const field = await screen.findByRole("textbox", { name: "Search" });+ field.focus();++ await pickFromFieldMenu(field, /^Paste/);++ expect(api.runContextMenuCommand).toHaveBeenCalledWith({ id: 1, type: "paste" });+ expect(field.isConnected).toBe(true);+ expect(field).toHaveValue("alpha");+ await waitFor(() => expect(field).toHaveFocus());+ });++ it("keeps an outer popover open while a nested popover's field uses its menu", async () => {+ renderHost(<PopoverHost nested />);+ const field = await screen.findByRole("textbox", { name: "Search" });+ field.focus();++ await pickFromFieldMenu(field, /^Copy/);++ expect(field.isConnected).toBe(true);+ expect(screen.getByLabelText("Outer")).toBeInTheDocument();+ });++ it("still closes the popover on a press outside", async () => {+ renderHost(<PopoverHost />);+ const field = await screen.findByRole("textbox", { name: "Search" });++ fireEvent.pointerDown(screen.getByRole("button", { name: "Elsewhere" }));+ fireEvent.click(screen.getByRole("button", { name: "Elsewhere" }));++ await waitFor(() => expect(field.isConnected).toBe(false));+ });++ it("keeps a dropdown menu with a search field open while the field's menu cuts", async () => {+ renderHost(+ <DropdownMenu defaultOpen>+ <DropdownMenuTrigger>Filter</DropdownMenuTrigger>+ <DropdownMenuContent>+ <input aria-label="Filter options" defaultValue="alpha" />+ <DropdownMenuItem>Option</DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>,+ );+ const field = await screen.findByRole("textbox", { name: "Filter options" });+ field.focus();++ await pickFromFieldMenu(field, /^Cut/);++ expect(field.isConnected).toBe(true);+ await waitFor(() => expect(field).toHaveFocus());+ });});diff --git a/apps/desktop/src/renderer/src/components/native-context-menu.tsx b/apps/desktop/src/renderer/src/components/native-context-menu.tsxindex 80132242f4..d89fb3e234 100644--- a/apps/desktop/src/renderer/src/components/native-context-menu.tsx+++ b/apps/desktop/src/renderer/src/components/native-context-menu.tsx@@ -17,7 +17,7 @@ import {type ResolvedContextMenuScope,type RowActionItem,} from "@multica/views/common/context-menu-scope";-import { contextMenuOriginRef } from "@multica/views/common/context-menu-origin";+import { contextMenuOriginRef } from "@multica/ui/lib/context-menu-origin";import { contextPrimitives } from "@multica/views/common/menu-primitives";import {contextMenuActions,diff --git a/packages/ui/components/ui/dropdown-menu.tsx b/packages/ui/components/ui/dropdown-menu.tsxindex 27121028aa..cf9b114c5a 100644--- a/packages/ui/components/ui/dropdown-menu.tsx+++ b/packages/ui/components/ui/dropdown-menu.tsx@@ -5,9 +5,23 @@ import { Menu as MenuPrimitive } from "@base-ui/react/menu"import { cn } from "@multica/ui/lib/utils"import { ChevronRightIcon, CheckIcon } from "@multica/ui/icons"+import {+ ContextMenuOwnerProvider,+ useContextMenuOwner,+ useContextMenuOwnerRef,+} from "@multica/ui/hooks/use-context-menu-owner"-function DropdownMenu({ ...props }: MenuPrimitive.Root.Props) {- return <MenuPrimitive.Root data-slot="dropdown-menu" {...props} />+function DropdownMenu({ onOpenChange, ...props }: MenuPrimitive.Root.Props) {+ const owner = useContextMenuOwner(onOpenChange)+ return (+ <ContextMenuOwnerProvider value={owner.register}>+ <MenuPrimitive.Root+ data-slot="dropdown-menu"+ onOpenChange={owner.onOpenChange}+ {...props}+ />+ </ContextMenuOwnerProvider>+ )}function DropdownMenuPortal({ ...props }: MenuPrimitive.Portal.Props) {@@ -37,9 +51,11 @@ function DropdownMenuContent({// bubbles through the React component tree — without this, clicking a// menu item inside a row that's wrapped in <a> (agent / runtime list// rows) would ALSO fire the row's onClick → unintended navigation.+ const ownerRef = useContextMenuOwnerRef()return (<MenuPrimitive.Portal><MenuPrimitive.Positioner+ ref={ownerRef}className="isolate z-50 outline-none"align={align}alignOffset={alignOffset}@@ -108,8 +124,20 @@ function DropdownMenuItem({)}-function DropdownMenuSub({ ...props }: MenuPrimitive.SubmenuRoot.Props) {- return <MenuPrimitive.SubmenuRoot data-slot="dropdown-menu-sub" {...props} />+function DropdownMenuSub({+ onOpenChange,+ ...props+}: MenuPrimitive.SubmenuRoot.Props) {+ const owner = useContextMenuOwner(onOpenChange)+ return (+ <ContextMenuOwnerProvider value={owner.register}>+ <MenuPrimitive.SubmenuRoot+ data-slot="dropdown-menu-sub"+ onOpenChange={owner.onOpenChange}+ {...props}+ />+ </ContextMenuOwnerProvider>+ )}function DropdownMenuSubTrigger({diff --git a/packages/ui/components/ui/popover.tsx b/packages/ui/components/ui/popover.tsxindex 5ee403574e..5625622dae 100644--- a/packages/ui/components/ui/popover.tsx+++ b/packages/ui/components/ui/popover.tsx@@ -4,9 +4,23 @@ import * as React from "react"import { Popover as PopoverPrimitive } from "@base-ui/react/popover"import { cn } from "@multica/ui/lib/utils"+import {+ ContextMenuOwnerProvider,+ useContextMenuOwner,+ useContextMenuOwnerRef,+} from "@multica/ui/hooks/use-context-menu-owner"-function Popover({ ...props }: PopoverPrimitive.Root.Props) {- return <PopoverPrimitive.Root data-slot="popover" {...props} />+function Popover({ onOpenChange, ...props }: PopoverPrimitive.Root.Props) {+ const owner = useContextMenuOwner(onOpenChange)+ return (+ <ContextMenuOwnerProvider value={owner.register}>+ <PopoverPrimitive.Root+ data-slot="popover"+ onOpenChange={owner.onOpenChange}+ {...props}+ />+ </ContextMenuOwnerProvider>+ )}function PopoverTrigger({ ...props }: PopoverPrimitive.Trigger.Props) {@@ -32,9 +46,11 @@ function PopoverContent({// popup unmounts the moment focus leaves for the dialog, tearing the dialog// down with it.Pick<PopoverPrimitive.Portal.Props, "keepMounted">) {+ const ownerRef = useContextMenuOwnerRef()return (<PopoverPrimitive.Portal keepMounted={keepMounted}><PopoverPrimitive.Positioner+ ref={ownerRef}align={align}alignOffset={alignOffset}side={side}diff --git a/packages/ui/hooks/use-context-menu-owner.test.tsx b/packages/ui/hooks/use-context-menu-owner.test.tsxnew file mode 100644index 0000000000..44a61d53ed--- /dev/null+++ b/packages/ui/hooks/use-context-menu-owner.test.tsx@@ -0,0 +1,66 @@+import { afterEach, describe, expect, it } from "vitest";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { contextMenuOriginRef } from "@multica/ui/lib/context-menu-origin";+import { Popover, PopoverContent, PopoverTrigger } from "@multica/ui/components/ui/popover";++let menu: HTMLElement;++/**+ * A context menu portaled to the body. It exists before the popover opens:+ * Base UI ignores presses on elements injected after it.+ */+function openContextMenu(origin: Element) {+ contextMenuOriginRef(origin)(menu);+ return menu.firstElementChild as HTMLElement;+}++function renderPopover() {+ menu = document.body.appendChild(document.createElement("div"));+ menu.setAttribute("role", "menu");+ const item = menu.appendChild(document.createElement("div"));+ item.setAttribute("role", "menuitem");+ item.tabIndex = -1;+ render(+ <>+ <Popover defaultOpen>+ <PopoverTrigger>Open</PopoverTrigger>+ <PopoverContent>+ <input aria-label="Search" />+ </PopoverContent>+ </Popover>+ <input aria-label="Elsewhere" />+ </>,+ );+ return screen.getByRole("textbox", { name: "Search" });+}++afterEach(() => {+ menu.remove();+});++describe("Popover with a context menu", () => {+ it("stays open when focus and a press move into the menu of a field inside it", async () => {+ const field = renderPopover();+ field.focus();+ const item = openContextMenu(field);++ item.focus();+ fireEvent.pointerDown(item);+ fireEvent.mouseDown(item);+ fireEvent.click(item);++ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(field.isConnected).toBe(true);+ });++ it("closes for a context menu opened outside it", async () => {+ const field = renderPopover();+ const item = openContextMenu(screen.getByRole("textbox", { name: "Elsewhere" }));++ fireEvent.pointerDown(item);+ fireEvent.mouseDown(item);+ fireEvent.click(item);++ await waitFor(() => expect(field.isConnected).toBe(false));+ });+});diff --git a/packages/ui/hooks/use-context-menu-owner.ts b/packages/ui/hooks/use-context-menu-owner.tsnew file mode 100644index 0000000000..d21c201b0e--- /dev/null+++ b/packages/ui/hooks/use-context-menu-owner.ts@@ -0,0 +1,74 @@+"use client"++import * as React from "react"++import { contextMenuOrigin } from "@multica/ui/lib/context-menu-origin"++type Register = (element: Element) => () => void++interface OpenChangeDetails {+ reason: string+ event: Event+ cancel: () => void+}++const OwnerContext = React.createContext<Register | null>(null)++export const ContextMenuOwnerProvider = OwnerContext.Provider++/** Whether a dismissal came from a context menu opened on one of `owned`. */+function fromOwnContextMenu(owned: Set<Element>, details: OpenChangeDetails) {+ const { reason, event } = details+ if (reason !== "outside-press" && reason !== "focus-out") return false+ const target = event instanceof FocusEvent ? event.relatedTarget : event?.target+ const origin = contextMenuOrigin(target ?? null)+ if (origin === target || !(origin instanceof Element)) return false+ for (const element of owned) {+ if (element.contains(origin)) return true+ }+ return false+}++/**+ * For a Base UI popup root (Popover, Menu). The app's context menu is+ * portaled to the body and takes focus, so Base UI reads a press or focus in+ * it as outside the popup and closes it, unmounting the field the menu was+ * about to cut from or paste into. This keeps the popup open when the menu+ * was opened inside it, or inside a popup nested in it: provide `register`+ * through `ContextMenuOwnerProvider` and attach `useContextMenuOwnerRef` to+ * the element around the popup.+ */+export function useContextMenuOwner<D extends OpenChangeDetails>(+ onOpenChange: ((open: boolean, details: D) => void) | undefined+) {+ const parent = React.useContext(OwnerContext)+ const owned = React.useRef(new Set<Element>()).current+ const register = React.useCallback<Register>(+ (element) => {+ owned.add(element)+ const releaseParent = parent?.(element)+ return () => {+ owned.delete(element)+ releaseParent?.()+ }+ },+ [owned, parent]+ )+ const handleOpenChange = (open: boolean, details: D) => {+ if (!open && fromOwnContextMenu(owned, details)) {+ details.cancel()+ return+ }+ onOpenChange?.(open, details)+ }+ return { register, onOpenChange: handleOpenChange }+}++/** A ref that claims an element for the popup roots around it. */+export function useContextMenuOwnerRef() {+ const register = React.useContext(OwnerContext)+ return React.useCallback(+ (element: Element | null) => (element && register ? register(element) : undefined),+ [register]+ )+}diff --git a/packages/views/common/context-menu-origin.ts b/packages/ui/lib/context-menu-origin.tssimilarity index 100%rename from packages/views/common/context-menu-origin.tsrename to packages/ui/lib/context-menu-origin.tsdiff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 71ea09f88d..10c30fcbe3 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -23,6 +23,7 @@"./lib/data-table": "./lib/data-table.ts","./lib/code-style": "./lib/code-style.ts","./lib/clipboard": "./lib/clipboard.ts",+ "./lib/context-menu-origin": "./lib/context-menu-origin.ts","./lib/motion": "./lib/motion.ts","./lib/multica-brand": "./lib/multica-brand.ts","./icons": "./icons/index.ts",diff --git a/packages/views/chat/components/session-rename-input.test.tsx b/packages/views/chat/components/session-rename-input.test.tsxindex 568fde948f..a561da3fc1 100644--- a/packages/views/chat/components/session-rename-input.test.tsx+++ b/packages/views/chat/components/session-rename-input.test.tsx@@ -2,7 +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 { contextMenuOriginRef } from "@multica/ui/lib/context-menu-origin";import { SessionRenameInput } from "./session-rename-input";const TEST_RESOURCES = { en: { chat: enChat } };diff --git a/packages/views/chat/components/session-rename-input.tsx b/packages/views/chat/components/session-rename-input.tsxindex ce71e2a75f..10007cadff 100644--- a/packages/views/chat/components/session-rename-input.tsx+++ b/packages/views/chat/components/session-rename-input.tsx@@ -2,7 +2,7 @@import { useEffect, useRef, useState } from "react";import { isImeComposing } from "@multica/core/utils";-import { contextMenuOrigin } from "../../common/context-menu-origin";+import { contextMenuOrigin } from "@multica/ui/lib/context-menu-origin";import { useT } from "../../i18n";/**diff --git a/packages/views/editor/bubble-menu.test.tsx b/packages/views/editor/bubble-menu.test.tsxindex 7a051347b2..748b621c57 100644--- a/packages/views/editor/bubble-menu.test.tsx+++ b/packages/views/editor/bubble-menu.test.tsx@@ -3,7 +3,7 @@ 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";+import { contextMenuOriginRef } from "@multica/ui/lib/context-menu-origin";const formatState = vi.hoisted(() => ({ codeBlock: false }));diff --git a/packages/views/editor/bubble-menu.tsx b/packages/views/editor/bubble-menu.tsxindex 27a84d1b18..8083ec5001 100644--- a/packages/views/editor/bubble-menu.tsx+++ b/packages/views/editor/bubble-menu.tsx@@ -37,7 +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 { contextMenuOrigin } from "@multica/ui/lib/context-menu-origin";import { Toggle, toggleVariants } from "@multica/ui/components/ui/toggle";import { Separator } from "@multica/ui/components/ui/separator";import {diff --git a/packages/views/editor/extensions/suggestion-popup.test.tsx b/packages/views/editor/extensions/suggestion-popup.test.tsxindex 0672999297..17215ea578 100644--- a/packages/views/editor/extensions/suggestion-popup.test.tsx+++ b/packages/views/editor/extensions/suggestion-popup.test.tsx@@ -7,7 +7,7 @@ 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 { contextMenuOriginRef } from "@multica/ui/lib/context-menu-origin";import { createSuggestionPopupRender } from "./suggestion-popup";import { isPickerAcceptKey } from "../../common/picker-keys";import { PatchedListItem } from "./list-item";diff --git a/packages/views/editor/extensions/suggestion-popup.tsx b/packages/views/editor/extensions/suggestion-popup.tsxindex 6186f6f823..9e82b0449d 100644--- a/packages/views/editor/extensions/suggestion-popup.tsx+++ b/packages/views/editor/extensions/suggestion-popup.tsx@@ -5,7 +5,7 @@ import { autoUpdate, computePosition, flip, offset, shift, size } from "@floatinimport { 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";+import { contextMenuOrigin } from "@multica/ui/lib/context-menu-origin";interface SuggestionPopupRenderOptions<TItem,diff --git a/packages/views/package.json b/packages/views/package.jsonindex 8ab82da886..534148cb9a 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -13,7 +13,6 @@"./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",