Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): hand off long-press menus to dragging (#1053)

Gener61fb4f4b16f1
diff --git a/src/web/src/components/community/channels/channel-dnd.tsx b/src/web/src/components/community/channels/channel-dnd.tsx
index 38bb7485b..8dfeb9db3 100644
--- a/src/web/src/components/community/channels/channel-dnd.tsx
+++ b/src/web/src/components/community/channels/channel-dnd.tsx
@@ -37,6 +37,12 @@ export function ChannelDndScope({ tree, onDrop, enabled = true, children }: {
if (item?.owner === owner && result && latest.current.enabled && projectChannelTreeDrop(latest.current.tree, result)) latest.current.onDrop(result)
}, [owner])
useDndCancellation(useCallback(() => finish(), [finish]))
+ useLayoutEffect(() => {
+ const monitor = manager.getMonitor()
+ if (enabled || !monitor.isDragging() || (monitor.getItem() as Item | null)?.owner !== owner) return
+ finish()
+ manager.getActions().endDrag()
+ }, [enabled, finish, manager, owner])
useLayoutEffect(() => () => {
current.current = null
if ((manager.getMonitor().getItem() as Item | null)?.owner === owner && manager.getMonitor().isDragging()) manager.getActions().endDrag()
diff --git a/src/web/src/components/community/channels/sortable-category.tsx b/src/web/src/components/community/channels/sortable-category.tsx
index 33f380bde..a79e0f981 100644
--- a/src/web/src/components/community/channels/sortable-category.tsx
+++ b/src/web/src/components/community/channels/sortable-category.tsx
@@ -1,16 +1,15 @@
"use client"
-import type { ContextMenu as ContextMenuPrimitive } from "@base-ui/react/context-menu"
-import { useEffect, useRef } from "react"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
import type React from "react"
import { ChevronDown, Plus, Settings, Folder, Lock, Trash2 } from "lucide-react"
import { useChannelDndItem } from "./channel-dnd"
-import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuSeparator } from "@/components/ui/context-menu"
+import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, isKeyboardContextMenu } from "@/components/ui/context-menu"
import { ConfirmDialog } from "@/components/ui/confirm-dialog"
import { tid } from "@/lib/community/testids"
import { DropLine } from "../drop-line"
+import { useDndContextMenu } from "../use-dnd-context-menu"
export function hasCategoryMenu(h: { onAddChannel?: () => void; onSettings?: () => void; onDelete?: () => void }) {
return !!(h.onAddChannel || h.onSettings || h.onDelete)
@@ -47,7 +46,7 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChan
"aria-description": isPrivate ? "Private category" : "Public category",
"aria-expanded": hasChannels ? open : undefined,
onPointerDownCapture: resumeClick,
- onKeyDownCapture: (event: React.KeyboardEvent) => { if (event.key === "Enter" || event.key === " ") resumeClick() },
+ onKeyDownCapture: (event: React.KeyboardEvent) => { if (event.key === "Enter" || event.key === " " || isKeyboardContextMenu(event.nativeEvent)) resumeClick() },
onClick: () => { if (hasChannels && !suppressClick()) onToggle() },
onKeyDown: (event: React.KeyboardEvent) => { if (event.target === event.currentTarget && hasChannels && (event.key === "Enter" || event.key === " ")) { event.preventDefault(); if (!suppressClick()) onToggle() } },
className: `group flex w-full touch-manipulation items-center gap-1 rounded px-1 py-1 text-xs font-semibold text-muted-foreground/80 select-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none ${placement === "append" ? "bg-primary/5 ring-1 ring-primary" : ""} ${canReorder ? "cursor-grab active:cursor-grabbing" : "cursor-pointer"}`,
@@ -80,18 +79,12 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChan
</>
)
const hasMenu = hasCategoryMenu({ onAddChannel, onSettings, onDelete })
- const menuActionsRef = useRef<ContextMenuPrimitive.Root.Actions | null>(null)
- useEffect(() => {
- if (!hasMenu) {
- menuActionsRef.current?.close()
- menuActionsRef.current?.unmount()
- }
- }, [hasMenu])
+ const menu = useDndContextMenu({ canOpen: hasMenu, canDrag: () => canReorder, suppressOpen: suppressClick })
return (
<div ref={setNodeRef} data-channel-category={catDndId} style={style} className={`relative mb-4 ${pending ? "opacity-60" : ""}`}>
{showLine && <DropLine side={lineSide} />}
- <ContextMenu disabled={!hasMenu} actionsRef={menuActionsRef}>
- <ContextMenuTrigger render={<div {...headerProps} />} onTouchStart={(event) => { if (canReorder) event.preventBaseUIHandler() }}>
+ <ContextMenu disabled={!hasMenu} actionsRef={menu.actionsRef} onOpenChange={menu.onOpenChange}>
+ <ContextMenuTrigger render={<div {...headerProps} />} {...menu.triggerProps}>
{headerInner}
</ContextMenuTrigger>
{hasMenu && <ContextMenuContent className="w-48">
diff --git a/src/web/src/components/community/channels/sortable-channel.tsx b/src/web/src/components/community/channels/sortable-channel.tsx
index 83f2c5d67..aa3ad9750 100644
--- a/src/web/src/components/community/channels/sortable-channel.tsx
+++ b/src/web/src/components/community/channels/sortable-channel.tsx
@@ -1,20 +1,19 @@
"use client"
-import type { ContextMenu as ContextMenuPrimitive } from "@base-ui/react/context-menu"
import { CommunityNavigationLink } from "../shell/community-navigation-link"
-import { useEffect, useRef } from "react"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
import { BellOff, Loader2, Pencil, Trash2, Users } from "lucide-react"
import { EntityIcon } from "../entity-icon"
import { useChannelDndItem } from "./channel-dnd"
-import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuSeparator } from "@/components/ui/context-menu"
+import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, isKeyboardContextMenu } from "@/components/ui/context-menu"
import { ConfirmDialog } from "@/components/ui/confirm-dialog"
import { DropLine } from "../drop-line"
import { tid } from "@/lib/community/testids"
import type { Channel } from "@/lib/community/models/navigation"
import { selectUnreadPresentation } from "@/hooks/community/unread-presentation"
import { ChannelUnreadIndicator } from "./channel-unread-indicator"
+import { useDndContextMenu } from "../use-dnd-context-menu"
export function hasChannelMenu(h: { onEdit?: () => void; onManageMembers?: () => void; onDelete?: () => void }) {
return !!(h.onEdit || h.onManageMembers || h.onDelete)
@@ -69,7 +68,7 @@ export function SortableChannel({ ch, href, active, onClick, onEdit, onDelete, o
"aria-roledescription": canReorder ? "draggable" : undefined,
role: "button", tabIndex: 0,
onPointerDownCapture: resumeClick,
- onKeyDownCapture: (event: React.KeyboardEvent) => { if (event.key === "Enter" || event.key === " ") resumeClick() },
+ onKeyDownCapture: (event: React.KeyboardEvent) => { if (event.key === "Enter" || event.key === " " || isKeyboardContextMenu(event.nativeEvent)) resumeClick() },
onClickCapture: (event: React.MouseEvent) => { if (suppressClick()) { event.preventDefault(); event.stopPropagation() } },
className: [
"group relative flex h-8 w-full cursor-pointer touch-manipulation items-center gap-2 rounded-md px-2 text-sm select-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
@@ -105,17 +104,11 @@ export function SortableChannel({ ch, href, active, onClick, onEdit, onDelete, o
<div {...rowProps} onClick={activate}>{content}</div>
)
const hasMenu = hasChannelMenu({ onEdit, onManageMembers, onDelete })
- const menuActionsRef = useRef<ContextMenuPrimitive.Root.Actions | null>(null)
- useEffect(() => {
- if (!hasMenu) {
- menuActionsRef.current?.close()
- menuActionsRef.current?.unmount()
- }
- }, [hasMenu])
+ const menu = useDndContextMenu({ canOpen: hasMenu, canDrag: () => canReorder, suppressOpen: suppressClick })
return (
<>
- <ContextMenu disabled={!hasMenu} actionsRef={menuActionsRef}>
- <ContextMenuTrigger render={row} onTouchStart={(event) => { if (canReorder) event.preventBaseUIHandler() }} />
+ <ContextMenu disabled={!hasMenu} actionsRef={menu.actionsRef} onOpenChange={menu.onOpenChange}>
+ <ContextMenuTrigger render={row} {...menu.triggerProps} />
{hasMenu && <ContextMenuContent className="w-48">
<div className="truncate px-2 py-2 text-xs font-semibold text-muted-foreground">/{ch.name}</div>
{onEdit && <ContextMenuItem onClick={onEdit}><Pencil className="size-4" /> Edit channel</ContextMenuItem>}
diff --git a/src/web/src/components/community/community-dnd.dom.test.tsx b/src/web/src/components/community/community-dnd.dom.test.tsx
index 9a83ba2af..1c74bdc74 100644
--- a/src/web/src/components/community/community-dnd.dom.test.tsx
+++ b/src/web/src/components/community/community-dnd.dom.test.tsx
@@ -336,7 +336,7 @@ describe("React DnD community scopes", () => {
ui.drop()
expect(onReorder).toHaveBeenCalledExactlyOnceWith(["empty", "public", "private", "private2"])
})
- it("reserves touch hold for dragging without stopping native input or opening a menu", async () => {
+ it("opens the held item menu without stopping native touch input needed by dragging", async () => {
vi.useFakeTimers()
const touchStarted = vi.fn()
document.addEventListener("touchstart", touchStarted)
@@ -346,7 +346,7 @@ describe("React DnD community scopes", () => {
fireEvent.touchStart(node, { touches: [{ identifier: 1, clientX: 20, clientY: 20, target: node }] })
await act(async () => { vi.advanceTimersByTime(700) })
expect(touchStarted).toHaveBeenCalledTimes(1)
- expect(ui.queryByRole("menu")).not.toBeInTheDocument()
+ expect(ui.queryByRole("menu")).toBeInTheDocument()
fireEvent.touchEnd(node, { touches: [] })
} finally {
document.removeEventListener("touchstart", touchStarted)
diff --git a/src/web/src/components/community/community-dnd.tsx b/src/web/src/components/community/community-dnd.tsx
index fe94c5485..ad62600b6 100644
--- a/src/web/src/components/community/community-dnd.tsx
+++ b/src/web/src/components/community/community-dnd.tsx
@@ -7,12 +7,14 @@ import { HTML5Backend } from "react-dnd-html5-backend"
import { TouchBackend } from "react-dnd-touch-backend"
import { MouseTransition, MultiBackend, TouchTransition } from "dnd-multi-backend"
+export const communityTouchHoldDelay = 650
+
export const communityDndOptions = {
backends: [
{ id: "html5", backend: HTML5Backend, transition: MouseTransition },
{
id: "touch", backend: TouchBackend, transition: TouchTransition,
- options: { delayTouchStart: 650, touchSlop: 8, enableMouseEvents: false, enableKeyboardEvents: true, ignoreContextMenu: true },
+ options: { delayTouchStart: communityTouchHoldDelay, touchSlop: 8, enableMouseEvents: false, enableKeyboardEvents: true, ignoreContextMenu: true },
},
],
}
diff --git a/src/web/src/components/community/community-touch-menu.dom.test.tsx b/src/web/src/components/community/community-touch-menu.dom.test.tsx
new file mode 100644
index 000000000..50eb29ef4
--- /dev/null
+++ b/src/web/src/components/community/community-touch-menu.dom.test.tsx
@@ -0,0 +1,261 @@
+import { useLayoutEffect } from "react"
+import { useDragDropManager } from "react-dnd"
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { act, fireEvent, mockElementGeometry, render } from "@/test/react-dom-harness"
+import { CommunityDndProvider, communityTouchHoldDelay } from "./community-dnd"
+import { SortableServer } from "./shell/sortable-server"
+import { useServerRailDnd } from "./shell/use-server-rail-dnd"
+import { ChannelDndScope } from "./channels/channel-dnd"
+import { SortableChannel } from "./channels/sortable-channel"
+import { SortableCategory } from "./channels/sortable-category"
+import { useChannelTree, type ChannelTreeDrop } from "./channels/use-channel-tree"
+import type { RailInstruction } from "@/lib/community/server-rail-model"
+import { tid } from "@/lib/community/testids"
+
+type Kind = "server" | "channel" | "category"
+type DragDropManager = ReturnType<typeof useDragDropManager>
+const views: Array<{ unmount: () => void }> = []
+const pointMethods = ["elementFromPoint", "elementsFromPoint"] as const
+const originals = pointMethods.map(key => Object.getOwnPropertyDescriptor(document, key))
+
+afterEach(() => {
+ for (const view of views.splice(0)) view.unmount()
+ vi.runOnlyPendingTimers()
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ pointMethods.forEach((key, index) => {
+ const original = originals[index]
+ if (original) Object.defineProperty(document, key, original)
+ else Reflect.deleteProperty(document, key)
+ })
+})
+
+function Probe({ ready }: { ready: (manager: DragDropManager) => void }) {
+ const manager = useDragDropManager()
+ useLayoutEffect(() => { ready(manager) }, [manager, ready])
+ return null
+}
+
+function Rail({ drop, activate, menuAction, enabled }: { drop: (instruction: RailInstruction) => void; activate: () => void; menuAction: () => void; enabled: boolean }) {
+ const dnd = useServerRailDnd({ getState: () => ({ serverIds: ["a", "b"], folderIds: [], folders: {}, expanded: [] }), canStart: () => enabled, onDragStart: () => {}, onPreview: () => {}, onDrop: drop, onCancel: () => {} })
+ return <>{["a", "b"].map(id => <SortableServer key={id} server={{ id, name: id, initial: id, active: false, unread: false, mentions: 0 }} onClick={activate} onOpenSettings={menuAction} dnd={dnd} />)}</>
+}
+
+function Tree({ kind, drop, activate, menuAction, enabled }: { kind: Exclude<Kind, "server">; drop: (event: ChannelTreeDrop) => void; activate: () => void; menuAction: () => void; enabled: boolean }) {
+ const tree = useChannelTree([{ id: "category-a", name: "a", channels: [{ id: "channel-a", name: "a", unread: false, active: false }, { id: "channel-b", name: "b", unread: false, active: false }] }, { id: "category-b", name: "b", channels: [] }])
+ return <ChannelDndScope tree={tree} onDrop={drop} enabled={enabled}>{[`${kind}-a`, `${kind}-b`].map(id => kind === "channel"
+ ? <SortableChannel key={id} ch={{ id, name: id, unread: false, active: false }} active={false} onClick={activate} onEdit={menuAction} canReorder={enabled} />
+ : <SortableCategory key={id} id={id} name={id} open onToggle={activate} onSettings={menuAction} canReorder={enabled} hasChannels>{null}</SortableCategory>)}</ChannelDndScope>
+}
+
+function EmptyChannelScope({ enabled }: { enabled: boolean }) {
+ const tree = useChannelTree([])
+ return <ChannelDndScope tree={tree} onDrop={() => {}} enabled={enabled}>{null}</ChannelDndScope>
+}
+
+function setup(kind: Kind, enabled = true, includeOtherScope = false) {
+ vi.useFakeTimers()
+ const drop = vi.fn(), activate = vi.fn(), menuAction = vi.fn()
+ let manager!: DragDropManager
+ const content = (enabled: boolean, otherEnabled = true) => <CommunityDndProvider><Probe ready={value => { manager = value }} />{kind === "server" ? <Rail drop={drop} activate={activate} menuAction={menuAction} enabled={enabled} /> : <Tree kind={kind} drop={drop} activate={activate} menuAction={menuAction} enabled={enabled} />}{includeOtherScope && <EmptyChannelScope enabled={otherEnabled} />}</CommunityDndProvider>
+ const view = render(content(enabled))
+ views.push(view)
+ const testid = kind === "server" ? tid.serverIcon : kind === "channel" ? tid.channelRow : tid.categoryHeader
+ const source = view.getByTestId(testid(kind === "server" ? "a" : `${kind}-a`)), target = view.getByTestId(testid(kind === "server" ? "b" : `${kind}-b`))
+ mockElementGeometry(source, { top: 0, left: 0, width: 100, height: 40 })
+ mockElementGeometry(target, { top: 100, left: 0, width: 100, height: 40 })
+ if (kind === "category") {
+ mockElementGeometry(source.parentElement!, { top: 0, left: 0, width: 100, height: 40 })
+ mockElementGeometry(target.parentElement!, { top: 100, left: 0, width: 100, height: 40 })
+ }
+ Object.defineProperty(document, "elementFromPoint", { configurable: true, value: (_x: number, y: number) => y >= 90 ? target : source })
+ Object.defineProperty(document, "elementsFromPoint", { configurable: true, value: (_x: number, y: number) => [y >= 90 ? target : source] })
+ const touch = (y: number) => ({ identifier: 1, clientX: 20, clientY: y, target: source })
+ const start = () => {
+ fireEvent.pointerDown(source, { pointerType: "touch", button: 0 })
+ fireEvent.touchStart(source, { touches: [touch(20)], targetTouches: [touch(20)], changedTouches: [touch(20)] })
+ }
+ const move = (y: number) => fireEvent.touchMove(source, { touches: [touch(y)], targetTouches: [touch(y)], changedTouches: [touch(y)] })
+ const end = () => fireEvent.touchEnd(source, { touches: [], targetTouches: [], changedTouches: [touch(120)] })
+ const hold = async () => { await act(async () => { vi.advanceTimersByTime(communityTouchHoldDelay + 20) }) }
+ return { ...view, manager, drop, activate, menuAction, source, start, move, end, hold, setEnabled: (next: boolean) => view.rerender(content(next)), setOtherEnabled: (next: boolean) => view.rerender(content(enabled, next)) }
+}
+
+describe("native community touch menu and drag handoff", () => {
+ it.each<Exclude<Kind, "server">>(["channel", "category"])("finishes a %s drop once when saving disables reordering", async kind => {
+ const ui = setup(kind)
+ ui.drop.mockImplementationOnce(() => { ui.setEnabled(false) })
+ ui.start()
+ await ui.hold()
+ ui.move(55)
+ ui.move(130)
+ ui.end()
+ expect(ui.manager.getMonitor().isDragging()).toBe(false)
+ expect(ui.drop).toHaveBeenCalledTimes(1)
+ expect(ui.activate).not.toHaveBeenCalled()
+ expect(ui.menuAction).not.toHaveBeenCalled()
+ })
+
+ it.each<Exclude<Kind, "server">>(["channel", "category"])("releases an active %s drag when permission changes and permits a new authorized gesture", async kind => {
+ const ui = setup(kind)
+ ui.start()
+ await ui.hold()
+ ui.move(55)
+ expect(ui.manager.getMonitor().isDragging()).toBe(true)
+ ui.setEnabled(false)
+ expect(ui.manager.getMonitor().isDragging()).toBe(false)
+ expect(ui.source).not.toHaveAttribute("data-dragging")
+ expect(kind === "category" ? ui.source.parentElement : ui.source).toHaveStyle({ opacity: "1" })
+ expect(ui.queryByRole("menu")).not.toBeInTheDocument()
+ ui.move(130)
+ ui.end()
+ expect(ui.drop).not.toHaveBeenCalled()
+ expect(ui.activate).not.toHaveBeenCalled()
+ expect(ui.menuAction).not.toHaveBeenCalled()
+ ui.setEnabled(true)
+ ui.start()
+ await ui.hold()
+ expect(ui.getByRole("menu")).toBeInTheDocument()
+ ui.move(55)
+ expect(ui.manager.getMonitor().isDragging()).toBe(true)
+ ui.move(130)
+ ui.end()
+ expect(ui.drop).toHaveBeenCalledTimes(1)
+ })
+
+ it("preserves another scope's native drag when a channel scope becomes disabled", async () => {
+ const ui = setup("server", true, true)
+ ui.start()
+ await ui.hold()
+ ui.move(55)
+ expect(ui.manager.getMonitor().isDragging()).toBe(true)
+ ui.setOtherEnabled(false)
+ expect(ui.manager.getMonitor().isDragging()).toBe(true)
+ ui.move(130)
+ ui.end()
+ expect(ui.drop).toHaveBeenCalledTimes(1)
+ })
+
+ it.each((["server", "channel", "category"] as Kind[]).flatMap(kind =>
+ (["drop", "cancel"] as const).flatMap(finish =>
+ [{ key: "ContextMenu", shiftKey: false }, { key: "F10", shiftKey: true }].map(shortcut => ({ kind, finish, ...shortcut })))),
+ )("opens the $kind menu with $key after native drag $finish without another pointer", async ({ kind, finish, key, shiftKey }) => {
+ const ui = setup(kind)
+ ui.start()
+ await ui.hold()
+ ui.move(55)
+ expect(ui.manager.getMonitor().isDragging()).toBe(true)
+ fireEvent.keyDown(ui.source, { key, shiftKey })
+ expect(ui.queryByRole("menu")).not.toBeInTheDocument()
+ if (finish === "drop") {
+ ui.move(130)
+ ui.end()
+ } else fireEvent.touchCancel(ui.source, { touches: [], targetTouches: [], changedTouches: [] })
+ expect(ui.manager.getMonitor().isDragging()).toBe(false)
+ expect(ui.drop).toHaveBeenCalledTimes(finish === "drop" ? 1 : 0)
+ fireEvent.contextMenu(ui.source, { button: 2 })
+ fireEvent.click(ui.source)
+ expect(ui.queryByRole("menu")).not.toBeInTheDocument()
+ expect(ui.activate).not.toHaveBeenCalled()
+ fireEvent.keyDown(ui.source, { key, shiftKey })
+ expect(ui.getByRole("menu")).toBeInTheDocument()
+ expect(ui.menuAction).not.toHaveBeenCalled()
+ expect(ui.activate).not.toHaveBeenCalled()
+ })
+
+ it.each<Kind>(["server", "channel", "category"])("closes a held %s menu when the same touch starts dragging", async kind => {
+ const ui = setup(kind)
+ ui.start()
+ await ui.hold()
+ expect(ui.getByRole("menu")).toBeInTheDocument()
+ expect(ui.manager.getMonitor().isDragging()).toBe(false)
+ ui.move(55)
+ expect(ui.manager.getMonitor().isDragging()).toBe(true)
+ expect(ui.queryByRole("menu")).not.toBeInTheDocument()
+ expect(document.querySelector('[data-slot="context-menu-content"]')).toBeNull()
+ fireEvent.contextMenu(ui.source, { button: 2 })
+ expect(ui.queryByRole("menu")).not.toBeInTheDocument()
+ ui.move(130)
+ ui.end()
+ expect(ui.manager.getMonitor().isDragging()).toBe(false)
+ expect(ui.drop).toHaveBeenCalledTimes(1)
+ fireEvent.contextMenu(ui.source, { button: 2 })
+ fireEvent.click(ui.source)
+ expect(ui.queryByRole("menu")).not.toBeInTheDocument()
+ expect(ui.activate).not.toHaveBeenCalled()
+ expect(ui.menuAction).not.toHaveBeenCalled()
+ ui.start()
+ await ui.hold()
+ expect(ui.getByRole("menu")).toBeInTheDocument()
+ ui.end()
+ })
+
+ it("leaves movement before the hold available for scrolling", async () => {
+ const ui = setup("channel")
+ ui.start()
+ const moved = ui.move(26)
+ await ui.hold()
+ fireEvent.contextMenu(ui.source, { button: 2 })
+ expect(moved).toBe(true)
+ expect(ui.queryByRole("menu")).not.toBeInTheDocument()
+ expect(ui.manager.getMonitor().isDragging()).toBe(false)
+ ui.end()
+ expect(ui.drop).not.toHaveBeenCalled()
+ expect(ui.activate).not.toHaveBeenCalled()
+ })
+
+ it("cancels an unfinished hold and permits the next touch", async () => {
+ const ui = setup("category")
+ ui.start()
+ fireEvent.touchCancel(ui.source, { touches: [], targetTouches: [], changedTouches: [] })
+ await ui.hold()
+ expect(ui.queryByRole("menu")).not.toBeInTheDocument()
+ ui.start()
+ await ui.hold()
+ expect(ui.getByRole("menu")).toBeInTheDocument()
+ ui.end()
+ expect(ui.drop).not.toHaveBeenCalled()
+ })
+
+ it("keeps a menu-only hold open on release and prevents the synthesized navigation click", async () => {
+ const ui = setup("channel")
+ ui.start()
+ await ui.hold()
+ expect(ui.end()).toBe(false)
+ expect(ui.getByRole("menu")).toBeInTheDocument()
+ expect(ui.activate).not.toHaveBeenCalled()
+ fireEvent.click(ui.getAllByRole("menuitem")[0])
+ expect(ui.menuAction).toHaveBeenCalledTimes(1)
+ expect(ui.drop).not.toHaveBeenCalled()
+ })
+
+ it("keeps Base UI long press and keyboard menus for a non-draggable item", async () => {
+ const ui = setup("channel", false)
+ ui.start()
+ await ui.hold()
+ expect(ui.getByRole("menu")).toBeInTheDocument()
+ ui.end()
+ expect(ui.manager.getMonitor().isDragging()).toBe(false)
+ fireEvent.keyDown(ui.source, { key: "Escape" })
+ await act(async () => { vi.runOnlyPendingTimers() })
+ fireEvent.keyDown(ui.source, { key: "ContextMenu" })
+ expect(ui.getByRole("menu")).toBeInTheDocument()
+ expect(ui.drop).not.toHaveBeenCalled()
+ })
+
+ it("cancels an active native drag without a drop and releases the next hold", async () => {
+ const ui = setup("server")
+ ui.start()
+ await ui.hold()
+ ui.move(55)
+ expect(ui.manager.getMonitor().isDragging()).toBe(true)
+ fireEvent.touchCancel(ui.source, { touches: [], targetTouches: [], changedTouches: [] })
+ expect(ui.manager.getMonitor().isDragging()).toBe(false)
+ expect(ui.drop).not.toHaveBeenCalled()
+ expect(ui.activate).not.toHaveBeenCalled()
+ ui.start()
+ await ui.hold()
+ expect(ui.getByRole("menu")).toBeInTheDocument()
+ ui.end()
+ })
+})
diff --git a/src/web/src/components/community/shell/sortable-server.focus.dom.test.ts b/src/web/src/components/community/shell/sortable-server.focus.dom.test.ts
index d2f3d3c86..67773db88 100644
--- a/src/web/src/components/community/shell/sortable-server.focus.dom.test.ts
+++ b/src/web/src/components/community/shell/sortable-server.focus.dom.test.ts
@@ -6,7 +6,8 @@ import { act, fireEvent, render, setupUser } from "@/test/react-dom-harness"
const feedback = vi.hoisted(() => ({ tooltip: vi.fn() }))
-vi.mock("@/components/ui/context-menu", () => ({
+vi.mock(import("@/components/ui/context-menu"), async importOriginal => ({
+ ...await importOriginal(),
ContextMenu: ({ children }: { children: ReactNode }) => createElement(Fragment, null, children),
ContextMenuTrigger: ({ render }: { render: ReactNode }) =>
createElement("context-menu-trigger", null, render),
diff --git a/src/web/src/components/community/shell/sortable-server.tsx b/src/web/src/components/community/shell/sortable-server.tsx
index 8ff56b391..643894022 100644
--- a/src/web/src/components/community/shell/sortable-server.tsx
+++ b/src/web/src/components/community/shell/sortable-server.tsx
@@ -9,6 +9,7 @@ import {
ContextMenuContent,
ContextMenuItem,
ContextMenuSeparator,
+ isKeyboardContextMenu,
} from "@/components/ui/context-menu";
import { RailIndicator } from "./rail-indicator";
import {
@@ -27,6 +28,7 @@ import { RailDndBinding, type RailDndController } from "./use-server-rail-dnd"
import { CommunityNavigationLink } from "./community-navigation-link"
import { serverRootHref } from "@/lib/community/community-route"
+import { useDndContextMenu } from "../use-dnd-context-menu"
type SortableServerProps = {
href?: string;
@@ -66,6 +68,7 @@ function SortableServerImpl({
const [confirmLeave, setConfirmLeave] = useAtom(useCreateAtom(false));
const [activated, setActivated] = useAtom(useCreateAtom(false));
const [tooltipOpen, setTooltipOpen] = useAtom(useCreateAtom(false));
+ const menu = useDndContextMenu({ canOpen: true, canDrag: () => dnd?.latest.current.canStart() ?? false, suppressOpen: () => dnd?.suppressClick() ?? false })
useEffect(() => { if (isDragActive) setTooltipOpen(false) }, [isDragActive, setTooltipOpen])
const activate = activated ? undefined : () => setActivated(true);
@@ -79,7 +82,7 @@ function SortableServerImpl({
onPointerEnter={activate}
onPointerDownCapture={activate}
onFocusCapture={activate}
- onKeyDownCapture={activate}
+ onKeyDownCapture={(event) => { activate?.(); if (isKeyboardContextMenu(event.nativeEvent)) dnd?.resumeClick() }}
onContextMenuCapture={activate}
>
{dnd && <RailDndBinding dnd={dnd} entity={{ kind: "server", id: server.id }} element={rootRef} handle={linkRef} />}
@@ -131,8 +134,8 @@ function SortableServerImpl({
);
const withMenu = (
- <ContextMenu>
- <ContextMenuTrigger render={icon} onTouchStart={(event) => { if (dnd?.latest.current.canStart()) event.preventBaseUIHandler() }} />
+ <ContextMenu actionsRef={menu.actionsRef} onOpenChange={menu.onOpenChange}>
+ <ContextMenuTrigger render={icon} {...menu.triggerProps} />
{activated && (
<ContextMenuContent className="w-52">
<div className="truncate px-2 py-1 text-xs font-semibold text-muted-foreground">
diff --git a/src/web/src/components/community/use-dnd-context-menu.ts b/src/web/src/components/community/use-dnd-context-menu.ts
new file mode 100644
index 000000000..e20924604
--- /dev/null
+++ b/src/web/src/components/community/use-dnd-context-menu.ts
@@ -0,0 +1,94 @@
+"use client"
+
+import { useCallback, useContext, useEffect, useLayoutEffect, useRef } from "react"
+import type { ContextMenu } from "@base-ui/react/context-menu"
+import { DndContext } from "react-dnd"
+import { communityTouchHoldDelay } from "./community-dnd"
+
+type Options = {
+ canOpen: boolean
+ canDrag: () => boolean
+ suppressOpen: () => boolean
+}
+
+export function useDndContextMenu(options: Options) {
+ const { dragDropManager: manager } = useContext(DndContext)
+ const latest = useRef(options)
+ const actionsRef = useRef<ContextMenu.Root.Actions | null>(null)
+ const hold = useRef<{ node: HTMLElement; x: number; y: number; ready: boolean } | null>(null)
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null)
+ const clearTimer = useCallback(() => {
+ if (timer.current !== null) clearTimeout(timer.current)
+ timer.current = null
+ }, [])
+ const clearHold = useCallback(() => {
+ clearTimer()
+ hold.current = null
+ }, [clearTimer])
+ useLayoutEffect(() => {
+ latest.current = options
+ if (!options.canOpen || !options.canDrag()) clearHold()
+ })
+ useEffect(() => {
+ if (options.canOpen) return
+ actionsRef.current?.close()
+ actionsRef.current?.unmount()
+ }, [options.canOpen])
+ useEffect(() => {
+ let dragging = false
+ const closeForDrag = () => {
+ const active = manager?.getMonitor().isDragging() ?? false
+ const started = active && !dragging
+ dragging = active
+ if (!started) return
+ clearHold()
+ actionsRef.current?.close()
+ actionsRef.current?.unmount()
+ }
+ const unsubscribe = manager?.getMonitor().subscribeToStateChange(closeForDrag)
+ const visibility = () => { if (document.hidden) clearHold() }
+ window.addEventListener("blur", clearHold)
+ document.addEventListener("visibilitychange", visibility)
+ return () => {
+ unsubscribe?.()
+ window.removeEventListener("blur", clearHold)
+ document.removeEventListener("visibilitychange", visibility)
+ clearHold()
+ }
+ }, [manager, clearHold])
+ const suppressed = () => manager?.getMonitor().isDragging() || latest.current.suppressOpen()
+ const onOpenChange: NonNullable<ContextMenu.Root.Props["onOpenChange"]> = (open, details) => {
+ if (open && (!latest.current.canOpen || suppressed())) details.cancel()
+ if (!open) clearHold()
+ }
+ const triggerProps: Pick<ContextMenu.Trigger.Props, "onTouchStart" | "onTouchMove" | "onTouchEnd" | "onTouchCancel" | "onContextMenu"> = {
+ onTouchStart: (event) => {
+ clearHold()
+ if (!latest.current.canDrag()) return
+ event.preventBaseUIHandler()
+ if (!latest.current.canOpen || event.touches.length !== 1 || suppressed()) return
+ const touch = event.touches[0]
+ const current = { node: event.currentTarget, x: touch.clientX, y: touch.clientY, ready: false }
+ hold.current = current
+ timer.current = setTimeout(() => {
+ timer.current = null
+ if (hold.current !== current || !current.node.isConnected || !latest.current.canOpen || !latest.current.canDrag() || suppressed()) return
+ current.ready = true
+ current.node.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, button: 2, clientX: current.x, clientY: current.y }))
+ }, communityTouchHoldDelay)
+ },
+ onTouchMove: () => { if (!hold.current?.ready) clearTimer() },
+ onTouchEnd: (event) => {
+ if (hold.current?.ready) event.preventDefault()
+ clearHold()
+ },
+ onTouchCancel: clearHold,
+ onContextMenu: (event) => {
+ if (suppressed() || (hold.current && !hold.current.ready)) {
+ event.preventDefault()
+ event.preventBaseUIHandler()
+ }
+ },
+ }
+ return { actionsRef, onOpenChange, triggerProps }
+}
diff --git a/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts b/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts
index ac20a31bd..e480e4ecd 100644
--- a/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts
+++ b/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts
@@ -317,6 +317,9 @@ async function expectFilterRail(
await expect(page.locator("html")).not.toHaveClass(/dark/)
await expect(bar).toBeVisible()
await expect(rail).toBeVisible()
+ await expect(all).toBeVisible({ timeout: 20_000 })
+ await expect(last).toBeVisible({ timeout: 20_000 })
+ await expect(rail.getByRole("status", { name: "Loading tag filters" })).toHaveCount(0)
const initial = await rail.evaluate((element) => {
const style = getComputedStyle(element)
element.scrollLeft = 0
diff --git a/src/web/src/test/e2e-ui/37-server-rail-dnd.spec.ts b/src/web/src/test/e2e-ui/37-server-rail-dnd.spec.ts
index ad88d2bcf..32a7a4d7a 100644
--- a/src/web/src/test/e2e-ui/37-server-rail-dnd.spec.ts
+++ b/src/web/src/test/e2e-ui/37-server-rail-dnd.spec.ts
@@ -55,7 +55,7 @@ async function dispatchTouchGesture(
start: { x: number; y: number },
end: { x: number; y: number },
holdMs: number,
- probe?: { source: Locator; target: Locator },
+ probe?: { source: Locator; target: Locator; expectsMenu: boolean },
liveTargetRatio = 0.5,
previewScreenshotPath?: string,
) {
@@ -72,6 +72,19 @@ async function dispatchTouchGesture(
})
const dispatch = (type: "touchstart" | "touchmove" | "touchend", point: { x: number; y: number }) =>
origin.evaluate((element, args) => {
+ const pointer = (type: "pointerdown" | "pointerup") => new PointerEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ pointerId: 1,
+ pointerType: "touch",
+ isPrimary: true,
+ button: 0,
+ buttons: type === "pointerdown" ? 1 : 0,
+ clientX: args.point.x,
+ clientY: args.point.y,
+ })
+ if (args.type === "touchstart") element.dispatchEvent(pointer("pointerdown"))
const touch = new Touch({
identifier: 1,
target: element,
@@ -88,10 +101,17 @@ async function dispatchTouchGesture(
targetTouches: args.type === "touchend" ? [] : [touch],
changedTouches: [touch],
}))
+ if (args.type === "touchend") element.dispatchEvent(pointer("pointerup"))
}, { type, point })
await dispatch("touchstart", start)
await page.waitForTimeout(20)
if (holdMs > 0) await page.waitForTimeout(holdMs)
+ let sawHeldMenu = false
+ let sawMenuUnmounted = false
+ if (probe?.expectsMenu) {
+ await expect(page.getByRole("menu")).toBeVisible()
+ sawHeldMenu = true
+ }
let sawDragging = false
let sawFeedback = false
let capturedPreview = false
@@ -114,7 +134,17 @@ async function dispatchTouchGesture(
await dispatch("touchmove", currentPoint)
await page.waitForTimeout(20)
if (probe) {
- sawDragging ||= await probe.source.getAttribute("data-dragging") === "true"
+ const dragging = await probe.source.getAttribute("data-dragging") === "true"
+ sawDragging ||= dragging
+ if (dragging && probe.expectsMenu && !sawMenuUnmounted) {
+ await expect(page.getByRole("menu")).toHaveCount(0)
+ await expect(page.locator('[data-slot="context-menu-content"]')).toHaveCount(0)
+ await expect.poll(() => probe.target.evaluate((element) => {
+ const rect = element.getBoundingClientRect()
+ return element.contains(document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2))
+ })).toBe(true)
+ sawMenuUnmounted = true
+ }
sawFeedback ||= await probe.target.evaluate((element) => !!element.closest("[data-rail-preview]"))
if (sawFeedback && previewScreenshotPath && !capturedPreview) {
capturedPreview = true
@@ -125,10 +155,18 @@ async function dispatchTouchGesture(
await dispatch("touchend", currentEnd)
await page.waitForTimeout(20)
await expect(page.locator("[data-rail-floating-preview]")).toHaveCount(0)
+ if (probe?.expectsMenu) {
+ expect(sawHeldMenu).toBe(true)
+ expect(sawMenuUnmounted).toBe(true)
+ await expect(page.getByRole("menu")).toHaveCount(0)
+ await expect(page.locator('[data-slot="context-menu-content"]')).toHaveCount(0)
+ }
return {
events: await page.evaluate(() => Reflect.get(window, "__railTouchEvents") as string[]),
sawDragging,
sawFeedback,
+ sawHeldMenu,
+ sawMenuUnmounted,
}
}
@@ -196,6 +234,7 @@ async function touchDrag(
await scrollIntoView(target)
await waitForElementMotion(source)
const sourceTestId = await source.getAttribute("data-testid")
+ expect(sourceTestId).not.toBeNull()
const sourceBox = await source.boundingBox()
const targetBox = await target.boundingBox()
if (!sourceBox || !targetBox) throw new Error("touch drag target is outside the viewport")
@@ -205,7 +244,7 @@ async function touchDrag(
{ x: sourceBox.x + sourceBox.width / 2, y: sourceBox.y + sourceBox.height / 2 },
{ x: targetBox.x + targetBox.width / 2, y: targetBox.y + targetBox.height * targetRatio },
660,
- { source, target },
+ { source, target, expectsMenu: sourceTestId!.startsWith(tid.serverIcon("")) },
targetRatio,
previewScreenshotPath,
)
@@ -530,7 +569,9 @@ test("server rail keeps scroll separate from React DnD native and touch drag", a
expect(firstTouch.events).toContain("touchstart")
expect(firstTouch.events).toContain("touchmove")
expect(firstTouch.events).toContain("touchend")
- expect(firstTouch.events).not.toContain("contextmenu")
+ expect(firstTouch.events).toContain("contextmenu")
+ expect(firstTouch.sawHeldMenu).toBe(true)
+ expect(firstTouch.sawMenuUnmounted).toBe(true)
expect(firstTouch.sawDragging).toBe(true)
expect(firstTouch.sawFeedback).toBe(true)
await expect(page.locator("[data-rail-preview]")).toHaveCount(0)
@@ -774,11 +815,13 @@ test("short server rail keeps Add adjacent and desktop geometry stable", async (
const endLongPress = await startStationaryTouch(page, onlyServer)
try {
await page.waitForTimeout(700)
+ await expect(page.getByRole("menu")).toBeVisible()
await expect(onlyServer).not.toHaveAttribute("data-dragging", "true")
await expect(page.locator("[data-rail-floating-preview]")).toHaveCount(0)
} finally { await endLongPress() }
await expect.poll(() => page.evaluate(() => Reflect.get(window, "__railOnlyServerClicks")))
- .toBe(1)
+ .toBe(0)
+ await expect(page.getByRole("menu")).toBeVisible()
expect(new URL(page.url()).pathname).toBe(`/c/channels/${serverId}`)
expect(railPatchCount).toBe(0)
})