Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): align channel drag previews and drop feedback (#1054)

Gener65e68a3246f7
diff --git a/src/web/src/components/community/channels/channel-dnd.tsx b/src/web/src/components/community/channels/channel-dnd.tsx
index 8dfeb9db3..923bd29af 100644
--- a/src/web/src/components/community/channels/channel-dnd.tsx
+++ b/src/web/src/components/community/channels/channel-dnd.tsx
@@ -1,22 +1,33 @@
"use client"
-import { createContext, useCallback, useContext, useLayoutEffect, useMemo, useRef, type ReactNode } from "react"
+import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, type ReactNode, type SyntheticEvent } from "react"
import { useDrag, useDragDropManager, useDragLayer, useDrop, type DropTargetMonitor } from "react-dnd"
+import { getEmptyImage } from "react-dnd-html5-backend"
+import { useAtom, useCreateAtom } from "@tanstack/react-store"
import { useDndCancellation } from "../community-dnd"
+import { ChannelDragPreview, type ChannelPreviewItem } from "./channel-drag-preview"
import { projectChannelTreeDrop, resolveChannelTreeDrop, type ChannelTree, type ChannelTreeDrop, type ChannelTreeEntity } from "./use-channel-tree"
const CHANNEL_ITEM = "community/channel-tree"
-type Item = ChannelTreeEntity & { owner: object }
+type Item = ChannelPreviewItem & { owner: object; element: HTMLElement | null }
+type ReturnPreview = { item: Item; element: HTMLElement; offset: { x: number; y: number } }
type TargetId = ReturnType<DropTargetMonitor["getHandlerId"]>
+type Target = {
+ kind: "row" | "header" | "end"
+ instruction: (item: Item, point: { x: number; y: number } | null) => ChannelTreeDrop | null
+}
+type Feedback = { targetId: NonNullable<TargetId>; kind: Target["kind"]; drop: ChannelTreeDrop; hovered: boolean }
type Controller = {
owner: object
- begin: (entity: ChannelTreeEntity) => Item
- finish: (item?: Item, result?: ChannelTreeDrop | null) => void
+ targets: Map<NonNullable<TargetId>, Target>
+ begin: (entity: ChannelTreeEntity, element: HTMLElement | null) => Item
+ finish: (item?: Item, result?: ChannelTreeDrop | null, animate?: boolean) => void
resolve: (item: Item, result: ChannelTreeDrop) => ChannelTreeDrop | null
suppressClick: () => boolean
resumeClick: () => void
}
const ChannelDndContext = createContext<Controller | null>(null)
+const ChannelFeedbackContext = createContext<Feedback | null>(null)
export function ChannelDndScope({ tree, onDrop, enabled = true, children }: {
tree: ChannelTree
@@ -28,33 +39,91 @@ export function ChannelDndScope({ tree, onDrop, enabled = true, children }: {
useLayoutEffect(() => { latest.current = { tree, onDrop, enabled } })
const manager = useDragDropManager()
const owner = useMemo(() => ({}), [])
+ const targets = useMemo(() => new Map<NonNullable<TargetId>, Target>(), [])
const current = useRef<Item | null>(null)
+ const lastOffset = useRef<{ x: number; y: number } | null>(null)
+ const returning = useCreateAtom<ReturnPreview | null>(null)
+ const [returnPreview] = useAtom(returning)
const suppressed = useRef(false)
- const finish = useCallback((item?: Item, result?: ChannelTreeDrop | null) => {
- if (!current.current) return
+ const finish = useCallback((item?: Item, result?: ChannelTreeDrop | null, animate = true) => {
+ const origin = current.current
+ if (!origin) return
current.current = null
suppressed.current = true
- if (item?.owner === owner && result && latest.current.enabled && projectChannelTreeDrop(latest.current.tree, result)) latest.current.onDrop(result)
- }, [owner])
+ if (item?.owner === owner && result && latest.current.enabled && projectChannelTreeDrop(latest.current.tree, result)) {
+ latest.current.onDrop(result)
+ } else {
+ const offset = manager.getMonitor().getSourceClientOffset() ?? lastOffset.current
+ const element = origin.element
+ if (animate && element?.isConnected && origin.width > 0 && origin.height > 0 && offset
+ && !window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
+ returning.set(() => ({ item: origin, element, offset }))
+ }
+ }
+ }, [manager, owner, returning])
useDndCancellation(useCallback(() => finish(), [finish]))
useLayoutEffect(() => {
const monitor = manager.getMonitor()
+ if (!enabled) returning.set(() => null)
if (enabled || !monitor.isDragging() || (monitor.getItem() as Item | null)?.owner !== owner) return
- finish()
+ finish(undefined, undefined, false)
manager.getActions().endDrag()
- }, [enabled, finish, manager, owner])
+ }, [enabled, finish, manager, owner, returning])
+ useLayoutEffect(() => manager.getMonitor().subscribeToOffsetChange(() => {
+ const monitor = manager.getMonitor()
+ if ((monitor.getItem() as Item | null)?.owner !== owner) return
+ const offset = monitor.getSourceClientOffset()
+ if (offset) lastOffset.current = offset
+ }), [manager, owner])
useLayoutEffect(() => () => {
current.current = null
+ returning.set(() => null)
if ((manager.getMonitor().getItem() as Item | null)?.owner === owner && manager.getMonitor().isDragging()) manager.getActions().endDrag()
- }, [manager, owner])
+ }, [manager, owner, returning])
const controller = useMemo<Controller>(() => ({
- owner, finish,
- begin: (entity) => { const item = { ...entity, owner }; current.current = item; suppressed.current = false; return item },
+ owner, targets, finish,
+ begin: (entity, element) => {
+ const rect = element?.getBoundingClientRect()
+ const item = { ...entity, owner, element, width: rect?.width ?? 0, height: rect?.height ?? 0 }
+ returning.set(() => null)
+ lastOffset.current = null
+ current.current = item
+ suppressed.current = false
+ return item
+ },
resolve: (item, result) => item.owner === owner && latest.current.enabled ? resolveChannelTreeDrop(latest.current.tree, result) : null,
suppressClick: () => !!current.current || suppressed.current,
resumeClick: () => { if (!current.current) suppressed.current = false },
- }), [owner, finish])
- return <ChannelDndContext.Provider value={controller}>{children}</ChannelDndContext.Provider>
+ }), [owner, targets, finish, returning])
+ const feedback = useDragLayer(monitor => {
+ const item = monitor.getItem<Item>()
+ if (!latest.current.enabled || !monitor.isDragging() || monitor.getItemType() !== CHANNEL_ITEM || item?.owner !== owner) {
+ return null
+ }
+ const point = monitor.getClientOffset()
+ let feedback: Feedback | null = null
+ for (const targetId of manager.getMonitor().getTargetIds().toReversed()) {
+ const target = targets.get(targetId)
+ if (!target || !manager.getMonitor().canDropOnTarget(targetId)) continue
+ const drop = target.instruction(item, point)
+ if (drop) { feedback = { targetId, kind: target.kind, drop, hovered: true }; break }
+ }
+ if (!feedback) for (const [targetId, target] of targets) {
+ if (target.kind !== "end") continue
+ const drop = target.instruction(item, point)
+ if (drop) { feedback = { targetId, kind: target.kind, drop, hovered: false }; break }
+ }
+ return feedback
+ })
+ const drag = useDragLayer(monitor => {
+ const item = monitor.getItem<Item>()
+ return monitor.isDragging() && monitor.getItemType() === CHANNEL_ITEM && item?.owner === owner
+ ? { item, offset: monitor.getSourceClientOffset() } : { item: null, offset: null }
+ })
+ return <ChannelDndContext.Provider value={controller}><ChannelFeedbackContext.Provider value={feedback}>{children}
+ <ChannelDragPreview item={returnPreview?.item ?? drag.item} offset={returnPreview?.offset ?? drag.offset} tree={tree}
+ returning={returnPreview} onReturnComplete={() => { if (returning.get() === returnPreview) returning.set(() => null) }} />
+ </ChannelFeedbackContext.Provider></ChannelDndContext.Provider>
}
export function useChannelDragActive() {
@@ -67,9 +136,10 @@ export function useChannelDragActive() {
export function useChannelDndItem(id: string, kind: ChannelTreeEntity["kind"], canReorder: boolean) {
const controller = useContext(ChannelDndContext)
- const nativeMonitor = useDragDropManager().getMonitor()
+ const feedback = useContext(ChannelFeedbackContext)
const element = useRef<HTMLElement | null>(null)
const header = useRef<HTMLElement | null>(null)
+ const pressAllowsDrag = useRef(true)
const instruction = useCallback((item: Item, point: { x: number; y: number } | null, append = false): ChannelTreeDrop | null => {
if (!controller || !canReorder || !point) return null
const rect = (append ? header.current : element.current)?.getBoundingClientRect()
@@ -80,11 +150,15 @@ export function useChannelDndItem(id: string, kind: ChannelTreeEntity["kind"], c
}, [controller, canReorder, id, kind])
const [{ isDragging }, drag, preview] = useDrag<Item, ChannelTreeDrop, { isDragging: boolean }>(() => ({
type: CHANNEL_ITEM,
- canDrag: () => canReorder && !!controller,
- item: () => controller?.begin({ id, kind }) ?? null,
+ canDrag: () => canReorder && !!controller && pressAllowsDrag.current,
+ item: () => controller?.begin({ id, kind }, kind === "category" ? header.current : element.current) ?? null,
end: (item, monitor) => controller?.finish(item, monitor.didDrop() ? monitor.getDropResult() : null),
collect: (monitor) => ({ isDragging: monitor.isDragging() }),
}), [controller, id, kind, canReorder])
+ useEffect(() => {
+ preview(getEmptyImage(), { captureDraggingState: true })
+ return () => { preview(null) }
+ }, [preview])
const [{ rowTargetId }, drop] = useDrop<Item, ChannelTreeDrop, { rowTargetId: TargetId }>(() => ({
accept: CHANNEL_ITEM,
canDrop: (item, monitor) => (kind === "channel" || item.kind === "category") && !!instruction(item, monitor.getClientOffset()),
@@ -97,33 +171,40 @@ export function useChannelDndItem(id: string, kind: ChannelTreeEntity["kind"], c
drop: (item, monitor) => monitor.didDrop() ? undefined : instruction(item, monitor.getClientOffset(), true) ?? undefined,
collect: (monitor) => ({ headerTargetId: monitor.getHandlerId() }),
}), [instruction, kind])
- const latestTargets = useRef({ rowTargetId, headerTargetId, instruction, kind })
- useLayoutEffect(() => { latestTargets.current = { rowTargetId, headerTargetId, instruction, kind } })
- const feedback = useDragLayer((monitor) => {
- const item = monitor.getItem<Item>()
- const current = latestTargets.current
- const headerOver = current.headerTargetId !== null && nativeMonitor.isOverTarget(current.headerTargetId, { shallow: true }) && nativeMonitor.canDropOnTarget(current.headerTargetId)
- const rowOver = current.rowTargetId !== null && nativeMonitor.isOverTarget(current.rowTargetId, { shallow: current.kind !== "category" }) && nativeMonitor.canDropOnTarget(current.rowTargetId)
- return item && (rowOver || headerOver) ? current.instruction(item, monitor.getClientOffset(), headerOver)?.placement ?? null : null
- })
+ useLayoutEffect(() => {
+ if (!controller) return
+ if (rowTargetId !== null) controller.targets.set(rowTargetId, { kind: "row", instruction })
+ if (headerTargetId !== null) controller.targets.set(headerTargetId, { kind: "header", instruction: (item, point) => instruction(item, point, true) })
+ return () => {
+ if (rowTargetId !== null) controller.targets.delete(rowTargetId)
+ if (headerTargetId !== null) controller.targets.delete(headerTargetId)
+ }
+ }, [controller, rowTargetId, headerTargetId, instruction])
+ const placement = feedback?.hovered && (feedback.targetId === rowTargetId || feedback.targetId === headerTargetId) ? feedback.drop.placement : null
const setNodeRef = useCallback((node: HTMLElement | null) => {
- element.current = node; drop(node); preview(node)
+ element.current = node; drop(node)
if (kind === "channel") drag(canReorder ? node : null)
- }, [drop, preview, drag, kind, canReorder])
+ }, [drop, drag, kind, canReorder])
const setActivatorNodeRef = useCallback((node: HTMLElement | null) => {
header.current = node; headerDrop(node); drag(canReorder ? node : null)
}, [drag, headerDrop, canReorder])
return {
- setNodeRef, setActivatorNodeRef, isDragging, isOver: feedback !== null,
- placement: feedback, lineSide: feedback === "after" ? "bottom" as const : "top" as const,
+ setNodeRef, setActivatorNodeRef, isDragging, isOver: placement !== null,
+ placement, lineSide: placement === "after" ? "bottom" as const : "top" as const,
dragActive: useChannelDragActive(),
suppressClick: () => controller?.suppressClick() ?? false,
- resumeClick: () => controller?.resumeClick(),
+ resumeClick: (event?: SyntheticEvent<HTMLElement>) => {
+ const target = event?.target
+ const action = target instanceof Element ? target.closest("button") : null
+ pressAllowsDrag.current = !action || action === event?.currentTarget || !event?.currentTarget.contains(action)
+ controller?.resumeClick()
+ },
}
}
export function ChannelDropContainer({ id, before = false, lastRowId }: { id: string; before?: boolean; lastRowId?: string }) {
const controller = useContext(ChannelDndContext)
+ const feedback = useContext(ChannelFeedbackContext)
const anchor = useRef<HTMLDivElement | null>(null)
const lastRow = useRef<HTMLElement | null>(null)
useLayoutEffect(() => {
@@ -140,17 +221,22 @@ export function ChannelDropContainer({ id, before = false, lastRowId }: { id: st
const result: ChannelTreeDrop = { active: { id: item.id, kind: item.kind }, over: { id, kind: "category" }, placement: "append" }
return controller?.resolve(item, result) ?? null
}, [controller, id, before])
- const [, drop] = useDrop<Item, ChannelTreeDrop>(() => ({
+ const [{ targetId }, drop] = useDrop<Item, ChannelTreeDrop, { targetId: TargetId }>(() => ({
accept: CHANNEL_ITEM,
canDrop: (item, monitor) => !!instruction(item, monitor.getClientOffset()),
drop: (item, monitor) => monitor.didDrop() ? undefined : instruction(item, monitor.getClientOffset()) ?? undefined,
+ collect: monitor => ({ targetId: monitor.getHandlerId() }),
}), [instruction])
const setDropRef = useCallback((node: HTMLDivElement | null) => { drop(node) }, [drop])
- const latestInstruction = useRef(instruction)
- useLayoutEffect(() => { latestInstruction.current = instruction })
- const visible = useDragLayer((monitor) => !!latestInstruction.current(monitor.getItem<Item>(), monitor.getClientOffset()))
+ useLayoutEffect(() => {
+ if (!controller || targetId === null) return
+ controller.targets.set(targetId, { kind: "end", instruction })
+ return () => { controller.targets.delete(targetId) }
+ }, [controller, targetId, instruction])
+ const visible = feedback?.hovered && feedback.kind !== "header" && feedback.drop.placement === "append" && feedback.drop.over.id === id
+ const open = visible || feedback?.kind === "end" && feedback.targetId === targetId
return <div ref={anchor} data-channel-drop-anchor={id} aria-hidden="true" className="relative h-0">
<div ref={setDropRef} data-channel-drop-end={id} data-drop-visible={visible || undefined}
- className={`absolute inset-x-0 ${before ? "bottom-0" : "top-0"} ${visible ? "h-4 rounded-md border border-dashed border-primary bg-primary/5" : "pointer-events-none h-0"}`} />
+ className={`absolute inset-x-0 ${before ? "bottom-0" : "top-0"} ${open ? "h-4" : "pointer-events-none h-0"} ${visible ? "rounded-md border border-dashed border-primary bg-primary/5" : ""}`} />
</div>
}
diff --git a/src/web/src/components/community/channels/channel-drag-preview.tsx b/src/web/src/components/community/channels/channel-drag-preview.tsx
new file mode 100644
index 000000000..58d8eb830
--- /dev/null
+++ b/src/web/src/components/community/channels/channel-drag-preview.tsx
@@ -0,0 +1,37 @@
+"use client"
+
+import { Folder, Lock } from "lucide-react"
+import { useMemo } from "react"
+import { DndDragPreview } from "../dnd-drag-preview"
+import { EntityIcon } from "../entity-icon"
+import { tid } from "@/lib/community/testids"
+import type { ChannelTree, ChannelTreeEntity } from "./use-channel-tree"
+
+export type ChannelPreviewItem = ChannelTreeEntity & { width: number; height: number }
+
+export function ChannelDragPreview({ item, offset, tree, returning, onReturnComplete }: {
+ item: ChannelPreviewItem | null
+ offset: { x: number; y: number } | null
+ tree: ChannelTree
+ returning: { element: HTMLElement } | null
+ onReturnComplete: () => void
+}) {
+ const channel = useMemo(() => item?.kind === "channel" ? Object.values(tree.order).flat().find(row => row.id === item.id) : undefined, [item?.kind, item?.id, tree.order])
+ if (!item || !offset || item.width <= 0 || item.height <= 0) return null
+ const name = channel?.name ?? tree.catNames[item.id]
+ if (name === undefined) return null
+ return <DndDragPreview offset={offset} width={item.width} height={item.height} returning={returning} onReturnComplete={onReturnComplete}
+ data-testid={tid.channelDragPreview} data-channel-floating-preview={item.kind} data-channel-preview-phase={returning ? "returning" : "dragging"}>
+ {item.kind === "channel" ? (
+ <div className="flex size-full items-center gap-2 rounded-md bg-sidebar px-2 text-sm text-foreground opacity-50 select-none">
+ <span className="grid size-5 shrink-0 place-items-center opacity-70"><EntityIcon kind={channel?.type} className="size-4" /></span>
+ <span className="truncate font-semibold">{name}</span>
+ </div>
+ ) : (
+ <div className="flex size-full items-center gap-1 rounded bg-sidebar px-1 py-1 text-xs font-semibold text-muted-foreground/80 opacity-50 select-none">
+ {tree.catPrivate[item.id] ? <Lock className="size-3 shrink-0" /> : <Folder className="size-3 shrink-0" />}
+ <span className="truncate">{name}</span>
+ </div>
+ )}
+ </DndDragPreview>
+}
diff --git a/src/web/src/components/community/channels/sortable-category.tsx b/src/web/src/components/community/channels/sortable-category.tsx
index a79e0f981..b6cc1e597 100644
--- a/src/web/src/components/community/channels/sortable-category.tsx
+++ b/src/web/src/components/community/channels/sortable-category.tsx
@@ -35,7 +35,7 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChan
}) {
const [confirmingDelete, setConfirmingDelete] = useAtom(useCreateAtom(false))
const { setActivatorNodeRef, setNodeRef, isDragging, isOver, placement, lineSide, suppressClick, resumeClick } = useChannelDndItem(catDndId, "category", canReorder)
- const style = { opacity: isDragging ? 0.4 : 1, zIndex: isDragging ? 10 : undefined }
+ const style = { opacity: isDragging ? 0.3 : 1, zIndex: isDragging ? 10 : undefined }
const showLine = isOver && !isDragging && placement !== "append"
const headerProps = {
ref: setActivatorNodeRef,
@@ -46,6 +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,
+ onTouchStartCapture: 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() } },
@@ -53,11 +54,13 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChan
}
const headerInner = (
<>
- {isPrivate ? <Lock className="size-3 shrink-0" aria-hidden="true" /> : <Folder className="size-3 shrink-0" aria-hidden="true" />}
- <span className="flex-1 truncate text-left">{name}</span>
+ {isPrivate ? <Lock className="pointer-events-none size-3 shrink-0" aria-hidden="true" /> : <Folder className="pointer-events-none size-3 shrink-0" aria-hidden="true" />}
+ <span className="pointer-events-none flex-1 truncate text-left">{name}</span>
{onSettings && (
<button
onPointerDown={(e) => e.stopPropagation()}
+ onTouchStart={(e) => e.stopPropagation()}
+ onDragStart={(e) => { e.preventDefault(); e.stopPropagation() }}
onClick={(e) => { e.stopPropagation(); onSettings() }}
className="grid size-4 place-items-center rounded opacity-0 hover:bg-accent group-hover:opacity-100"
aria-label={`Category settings for ${name}`}
@@ -68,6 +71,8 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChan
{onAddChannel && (
<button
onPointerDown={(e) => e.stopPropagation()}
+ onTouchStart={(e) => e.stopPropagation()}
+ onDragStart={(e) => { e.preventDefault(); e.stopPropagation() }}
onClick={(e) => { e.stopPropagation(); onAddChannel() }}
className="grid size-4 place-items-center rounded opacity-0 hover:bg-accent group-hover:opacity-100"
aria-label={`Create channel in ${name}`}
@@ -75,7 +80,7 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChan
<Plus className="size-3.5" />
</button>
)}
- {hasChannels && <ChevronDown className={`size-3 shrink-0 transition-transform ${open ? "" : "-rotate-90"}`} />}
+ {hasChannels && <ChevronDown className={`pointer-events-none size-3 shrink-0 transition-transform ${open ? "" : "-rotate-90"}`} />}
</>
)
const hasMenu = hasCategoryMenu({ onAddChannel, onSettings, onDelete })
diff --git a/src/web/src/components/community/channels/sortable-channel.tsx b/src/web/src/components/community/channels/sortable-channel.tsx
index aa3ad9750..e5eac3676 100644
--- a/src/web/src/components/community/channels/sortable-channel.tsx
+++ b/src/web/src/components/community/channels/sortable-channel.tsx
@@ -51,7 +51,7 @@ export function SortableChannel({ ch, href, active, onClick, onEdit, onDelete, o
}) {
const [confirmingDelete, setConfirmingDelete] = useAtom(useCreateAtom(false))
const { setNodeRef, isDragging, isOver, placement, lineSide, dragActive, suppressClick, resumeClick } = useChannelDndItem(ch.id, "channel", canReorder)
- const style = { opacity: isDragging ? 0.4 : 1, zIndex: isDragging ? 10 : undefined }
+ const style = { opacity: isDragging ? 0.3 : 1, zIndex: isDragging ? 10 : undefined }
const showLine = isOver && !isDragging && placement !== "append"
const activate = () => { if (!suppressClick()) onClick() }
const unread = selectUnreadPresentation({
@@ -68,6 +68,7 @@ export function SortableChannel({ ch, href, active, onClick, onEdit, onDelete, o
"aria-roledescription": canReorder ? "draggable" : undefined,
role: "button", tabIndex: 0,
onPointerDownCapture: resumeClick,
+ onTouchStartCapture: 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: [
@@ -86,12 +87,12 @@ export function SortableChannel({ ch, href, active, onClick, onEdit, onDelete, o
<>
{showLine && <DropLine side={lineSide} />}
<ChannelUnreadIndicator visible={unread.showDot} hidden={isDragging} />
- <span className="grid size-5 shrink-0 place-items-center opacity-70">
+ <span className="pointer-events-none grid size-5 shrink-0 place-items-center opacity-70">
<EntityIcon kind={ch.type} className="size-4" />
</span>
- <span className="truncate font-semibold">{ch.name}</span>
+ <span className="pointer-events-none truncate font-semibold">{ch.name}</span>
{ch.muted ? (
- <BellOff className="ml-auto size-4 shrink-0 opacity-70" />
+ <BellOff className="pointer-events-none ml-auto size-4 shrink-0 opacity-70" />
) : null}
</>
)
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 1c74bdc74..4712001f4 100644
--- a/src/web/src/components/community/community-dnd.dom.test.tsx
+++ b/src/web/src/components/community/community-dnd.dom.test.tsx
@@ -17,11 +17,13 @@ function setup(children: ReactNode) {
let backend!: TestBackendImpl
const sources = new Map<HTMLElement, string>()
const targets = new Map<HTMLElement, string>()
+ const previews = new Map<string, { node: HTMLElement; options?: { captureDraggingState?: boolean } }>()
const view = render(<DndProvider context={{}} backend={(manager, context) => {
backend = TestBackend(manager, context) as TestBackendImpl
Object.assign(backend, {
connectDragSource: (id: string, node: HTMLElement) => { sources.set(node, id); return () => { sources.delete(node) } },
connectDropTarget: (id: string, node: HTMLElement) => { targets.set(node, id); return () => { targets.delete(node) } },
+ connectDragPreview: (id: string, node: HTMLElement, options?: { captureDraggingState?: boolean }) => { previews.set(id, { node, options }); return () => { previews.delete(id) } },
})
return backend
}}><CommunityDndProvider>{children}</CommunityDndProvider></DndProvider>)
@@ -32,7 +34,7 @@ function setup(children: ReactNode) {
const hover = (id: string, y = 20) => act(() => backend.simulateHover([targets.get(node(id))!], { clientOffset: { x: 20, y } }))
const drop = () => act(() => { backend.simulateDrop(); backend.simulateEndDrag() })
const cancel = () => fireEvent.keyDown(window, { key: "Escape" })
- return { ...view, node, start, hover, drop, cancel, backend, targets }
+ return { ...view, node, start, hover, drop, cancel, backend, targets, sources, previews }
}
const state: RailState = { serverIds: ["a", "b", "c"], folderIds: ["f"], folders: { f: ["c"] }, expanded: [] }
@@ -56,7 +58,7 @@ const categories: Category[] = [
function TreeFixture({ onDrop, canReorder = true, rootBefore = true }: { onDrop: (event: ChannelTreeDrop) => void; canReorder?: boolean; rootBefore?: boolean }) {
const tree = useChannelTree(categories)
const settle = (event: ChannelTreeDrop) => { onDrop(event) }
- return <ChannelDndScope tree={tree} onDrop={settle}>
+ return <ChannelDndScope tree={tree} onDrop={settle} enabled={canReorder}>
<output data-testid="tree-order">{JSON.stringify({ cats: tree.catOrder, channels: Object.fromEntries(Object.entries(tree.order).map(([id, rows]) => [id, rows.map((row) => row.id)])) })}</output>
{tree.catOrder.map((id) => <TreeItem key={id} id={id} kind="category" canReorder={canReorder} />)}
{Object.values(tree.order).flat().map((row) => <TreeItem key={row.id} id={row.id} kind="channel" canReorder={canReorder} />)}
@@ -80,6 +82,195 @@ function ActualSidebarFixture({ onReorder }: { onReorder: (ids: string[]) => voi
}
describe("React DnD community scopes", () => {
+ it("renders a same-kind drag preview only in its owning scope", () => {
+ const ui = setup(<><div data-scope="first"><TreeFixture onDrop={vi.fn()} /></div><div data-scope="second"><TreeFixture onDrop={vi.fn()} /></div></>)
+ const source = ui.container.querySelector<HTMLElement>('[data-scope="second"] [data-testid="text"]')!
+ source.getBoundingClientRect = () => ({ top: 0, bottom: 32, left: 0, right: 220, width: 220, height: 32 }) as DOMRect
+ act(() => ui.backend.simulateBeginDrag([ui.sources.get(source)!], { clientOffset: { x: 20, y: 20 }, getSourceClientOffset: () => ({ x: 0, y: 0 }) }))
+ expect(document.querySelectorAll("[data-channel-floating-preview]")).toHaveLength(1)
+ ui.cancel()
+ expect(document.querySelector("[data-channel-floating-preview]")).toBeNull()
+ })
+
+ it("returns a canceled channel preview to the current source geometry and clears it after native animation", () => {
+ const nativeAnimate = Object.getOwnPropertyDescriptor(Element.prototype, "animate")
+ const media = vi.spyOn(window, "matchMedia").mockReturnValue({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() } as unknown as MediaQueryList)
+ const animation = { onfinish: null as (() => void) | null, cancel: vi.fn() }
+ const animate = vi.fn(() => animation)
+ Object.defineProperty(Element.prototype, "animate", { configurable: true, value: animate })
+ try {
+ const onDrop = vi.fn(), ui = setup(<TreeFixture onDrop={onDrop} />)
+ ui.node("text").getBoundingClientRect = () => ({ top: 0, bottom: 32, left: 0, right: 220, width: 220, height: 32 }) as DOMRect
+ ui.start("text"); ui.hover("empty", 130)
+ ui.node("text").getBoundingClientRect = () => ({ top: 20, bottom: 52, left: 10, right: 230, width: 220, height: 32 }) as DOMRect
+ ui.cancel()
+ expect(document.querySelector("[data-channel-preview-phase='returning']")).not.toBeNull()
+ expect(animate).toHaveBeenCalledExactlyOnceWith([
+ { transform: "translate(0px, 110px)" }, { transform: "translate(10px, 20px)" },
+ ], { duration: 150, easing: "cubic-bezier(0.2, 0.8, 0.2, 1)", fill: "forwards" })
+ act(() => { animation.onfinish?.() })
+ expect(document.querySelector("[data-channel-floating-preview]")).toBeNull()
+ expect(animation.cancel).toHaveBeenCalledTimes(1)
+ expect(onDrop).not.toHaveBeenCalled()
+ } finally {
+ media.mockRestore()
+ if (nativeAnimate) Object.defineProperty(Element.prototype, "animate", nativeAnimate)
+ else Reflect.deleteProperty(Element.prototype, "animate")
+ }
+ })
+
+ it("removes the channel preview immediately on permission loss and route exit, then permits a fresh authorized drag", () => {
+ const onDrop = vi.fn()
+ function PermissionFixture() {
+ const [enabled, setEnabled] = useState(true)
+ return <><button data-testid="permission" onClick={() => setEnabled(value => !value)}>Toggle permission</button><TreeFixture onDrop={onDrop} canReorder={enabled} /></>
+ }
+ const ui = setup(<PermissionFixture />)
+ ui.node("text").getBoundingClientRect = () => ({ top: 0, bottom: 32, left: 0, right: 220, width: 220, height: 32 }) as DOMRect
+ ui.start("text"); ui.hover("empty", 130)
+ expect(document.querySelectorAll("[data-channel-floating-preview]")).toHaveLength(1)
+ fireEvent.click(ui.node("permission"))
+ expect(document.querySelector("[data-channel-floating-preview]")).toBeNull()
+ expect(ui.backend.manager.getMonitor().isDragging()).toBe(false)
+ fireEvent.click(ui.node("permission"))
+ ui.start("text")
+ expect(document.querySelectorAll("[data-channel-floating-preview]")).toHaveLength(1)
+ ui.unmount()
+ expect(document.querySelector("[data-channel-floating-preview]")).toBeNull()
+ expect(onDrop).not.toHaveBeenCalled()
+ })
+
+ it("keeps one insertion indication across adjacent channel halves, gaps and the container end", () => {
+ function FeedbackFixture() {
+ const tree = useChannelTree([{ id: "main", name: "Main", channels: [channel("a"), channel("b"), channel("c")] }, { id: "spare", name: "Spare", channels: [channel("moving")] }])
+ return <ChannelSidebar tree={tree} serverId="server" serverName="Fixture" activeChannel="" setActiveChannel={() => {}} />
+ }
+ const ui = setup(<FeedbackFixture />)
+ for (const [id, top] of [["a", 40], ["b", 76], ["c", 112], ["moving", 190]] as const) {
+ ui.node(tid.channelRow(id)).getBoundingClientRect = () => ({ top, bottom: top + 32, left: 0, right: 220, width: 220, height: 32 }) as DOMRect
+ }
+ const end = ui.container.querySelector<HTMLElement>('[data-channel-drop-end="main"]')!
+ end.parentElement!.getBoundingClientRect = () => ({ top: 144, bottom: 144, left: 0, right: 220, width: 220, height: 0 }) as DOMRect
+ const count = () => ui.container.querySelectorAll('[data-slot="community-drop-line"]').length
+ + ui.container.querySelectorAll('[data-channel-drop-end][data-drop-visible="true"]').length
+ ui.start(tid.channelRow("moving"))
+ for (const [id, y] of [["a", 48], ["a", 68], ["b", 80], ["b", 100], ["c", 116], ["c", 140]] as const) {
+ ui.hover(tid.channelRow(id), y)
+ expect(count()).toBe(1)
+ }
+ expect(ui.container.querySelectorAll('[data-slot="community-drop-line"]')).toHaveLength(0)
+ expect(end).toHaveAttribute("data-drop-visible", "true")
+ act(() => ui.backend.simulateHover([ui.targets.get(end)!], { clientOffset: { x: 20, y: 151 } }))
+ expect(count()).toBe(1)
+ act(() => ui.backend.simulateHover([], { clientOffset: { x: 20, y: 74 } }))
+ expect(count()).toBe(0)
+ ui.cancel()
+ expect(count()).toBe(0)
+ })
+
+ it("keeps only the latest adjacent insertion when native hover changes before React commits", () => {
+ const onReorder = vi.fn()
+ function FeedbackFixture() {
+ const tree = useChannelTree([{ id: "main", name: "Main", channels: [channel("a"), channel("b"), channel("c")] }, { id: "spare", name: "Spare", channels: [channel("moving")] }])
+ return <ChannelSidebar tree={tree} serverId="server" serverName="Fixture" activeChannel="" setActiveChannel={() => {}} onReorderChannels={onReorder} />
+ }
+ const ui = setup(<FeedbackFixture />)
+ for (const [id, top] of [["a", 40], ["b", 76], ["c", 112], ["moving", 190]] as const) {
+ ui.node(tid.channelRow(id)).getBoundingClientRect = () => ({ top, bottom: top + 32, left: 0, right: 220, width: 220, height: 32 }) as DOMRect
+ }
+ const end = ui.container.querySelector<HTMLElement>('[data-channel-drop-end="main"]')!
+ end.parentElement!.getBoundingClientRect = () => ({ top: 144, bottom: 144, left: 0, right: 220, width: 220, height: 0 }) as DOMRect
+ const move = (id: string, y: number) => ui.backend.simulateHover([ui.targets.get(ui.node(tid.channelRow(id)))!], { clientOffset: { x: 20, y } })
+ const lines = () => ui.container.querySelectorAll('[data-slot="community-drop-line"]')
+ ui.start(tid.channelRow("moving"))
+ act(() => { move("a", 68); move("b", 80) })
+ expect(lines()).toHaveLength(1)
+ expect(ui.node(tid.channelRow("a")).querySelector('[data-slot="community-drop-line"]')).toBeNull()
+ expect(ui.node(tid.channelRow("b")).querySelector('[data-slot="community-drop-line"]')).not.toBeNull()
+ act(() => { move("c", 140); move("a", 68) })
+ expect(lines()).toHaveLength(1)
+ expect(end).not.toHaveAttribute("data-drop-visible")
+ ui.drop()
+ expect(lines()).toHaveLength(0)
+ expect(onReorder).toHaveBeenCalledExactlyOnceWith(["a", "moving", "b", "c"], { channelId: "moving", categoryId: "main" })
+ })
+
+ it("gives only the native hovered end ownership when end landing geometries overlap", () => {
+ const onDrop = vi.fn(), ui = setup(<TreeFixture onDrop={onDrop} rootBefore={false} />)
+ const end = ui.container.querySelector<HTMLElement>('[data-channel-drop-end="empty"]')!
+ const other = ui.container.querySelector<HTMLElement>(`[data-channel-drop-end="${UNCATEGORIZED_CATEGORY_ID}"]`)!
+ for (const node of [end, other]) node.parentElement!.getBoundingClientRect = () => ({ top: 100, bottom: 100, left: 0, right: 100, height: 0, width: 100 }) as DOMRect
+ ui.start("text")
+ act(() => ui.backend.simulateHover([ui.targets.get(end)!], { clientOffset: { x: 20, y: 108 } }))
+ expect(end).toHaveAttribute("data-drop-visible", "true")
+ expect(other).not.toHaveAttribute("data-drop-visible")
+ ui.drop()
+ expect(onDrop).toHaveBeenCalledExactlyOnceWith({ active: { id: "text", kind: "channel" }, over: { id: "empty", kind: "category" }, placement: "append" })
+ })
+
+ it("keeps a hovered category header as the sole append feedback over an overlapping end", () => {
+ const ui = setup(<TreeFixture onDrop={vi.fn()} />)
+ const end = ui.container.querySelector<HTMLElement>('[data-channel-drop-end="empty"]')!
+ end.parentElement!.getBoundingClientRect = () => ({ top: 100, bottom: 100, left: 0, right: 100, height: 0, width: 100 }) as DOMRect
+ ui.start("text"); ui.hover("empty-handle", 108)
+ expect(ui.node("empty")).toHaveAttribute("data-placement", "append")
+ expect(end).not.toHaveAttribute("data-drop-visible")
+ ui.cancel()
+ })
+
+ it("opens transparent landing geometry without showing an accepted end until native hover", () => {
+ const onDrop = vi.fn(), ui = setup(<TreeFixture onDrop={onDrop} />)
+ const end = ui.container.querySelector<HTMLElement>('[data-channel-drop-end="empty"]')!
+ end.parentElement!.getBoundingClientRect = () => ({ top: 100, bottom: 100, left: 0, right: 100, height: 0, width: 100 }) as DOMRect
+ ui.start("text")
+ act(() => ui.backend.simulateHover([], { clientOffset: { x: 20, y: 108 } }))
+ expect(end).toHaveClass("h-4")
+ expect(end).not.toHaveClass("pointer-events-none")
+ expect(end).not.toHaveClass("border-dashed")
+ expect(end).not.toHaveAttribute("data-drop-visible")
+ ui.drop()
+ expect(onDrop).not.toHaveBeenCalled()
+ ui.start("text")
+ act(() => ui.backend.simulateHover([ui.targets.get(end)!], { clientOffset: { x: 20, y: 108 } }))
+ expect(end).toHaveAttribute("data-drop-visible", "true")
+ ui.drop()
+ expect(onDrop).toHaveBeenCalledExactlyOnceWith({ active: { id: "text", kind: "channel" }, over: { id: "empty", kind: "category" }, placement: "append" })
+ })
+
+ it("uses the valid parent category when its native header target cannot accept a category", () => {
+ const onDrop = vi.fn(), ui = setup(<TreeFixture onDrop={onDrop} />)
+ ui.node("private").getBoundingClientRect = () => ({ top: 100, bottom: 200, left: 0, right: 220, width: 220, height: 100 }) as DOMRect
+ ui.start("public-handle")
+ act(() => ui.backend.simulateHover([ui.targets.get(ui.node("private"))!, ui.targets.get(ui.node("private-handle"))!], { clientOffset: { x: 20, y: 190 } }))
+ expect(ui.node("private")).toHaveAttribute("data-placement", "after")
+ ui.drop()
+ expect(onDrop).toHaveBeenCalledExactlyOnceWith({ active: { id: "public", kind: "category" }, over: { id: "private", kind: "category" }, placement: "after" })
+ })
+
+ it.each(["text", "private-handle"])("moves one pointer-transparent preview with %s and removes it on cancellation", id => {
+ const onDrop = vi.fn()
+ const ui = setup(<TreeFixture onDrop={onDrop} />)
+ const height = id === "text" ? 32 : 24
+ ui.node(id).getBoundingClientRect = () => ({ top: 0, bottom: height, left: 0, right: 220, width: 220, height }) as DOMRect
+ ui.start(id)
+ const preview = document.querySelector<HTMLElement>("[data-channel-floating-preview]")!
+ expect(preview).not.toBeNull()
+ expect(preview).toHaveAttribute("aria-hidden", "true")
+ expect(preview).toHaveClass("pointer-events-none")
+ expect(preview).toHaveTextContent(id === "text" ? "text" : "Private")
+ expect(preview.querySelector("button,a,[role='button']")).toBeNull()
+ expect(preview.firstElementChild).toHaveStyle({ width: "220px", height: `${height}px`, transform: "translate(0px, 0px)" })
+ const nativeImage = ui.previews.get(ui.sources.get(ui.node(id))!)!
+ expect(nativeImage.node).toBeInstanceOf(HTMLImageElement)
+ expect(nativeImage.options).toMatchObject({ captureDraggingState: true })
+ ui.hover("empty", 130)
+ expect(document.querySelectorAll("[data-channel-floating-preview]")).toHaveLength(1)
+ expect(preview.firstElementChild).toHaveStyle({ transform: "translate(0px, 110px)" })
+ ui.cancel()
+ expect(document.querySelector("[data-channel-floating-preview]")).toBeNull()
+ expect(onDrop).not.toHaveBeenCalled()
+ })
+
it("settles page-background release as cancellation, retaining only a visual return", () => {
vi.spyOn(window, "matchMedia").mockReturnValue({ matches: false } as MediaQueryList)
let dnd!: RailDndController
@@ -206,9 +397,9 @@ describe("React DnD community scopes", () => {
expect(railInstructionAt(capped, source, target, 0.5)).toBeNull()
expect(railInstructionAt(capped, source, target, 0.9)).toMatchObject({ operation: "reorder-after" })
})
- it("uses official touch activation settings and keeps a native HTML5 preview", () => {
+ it("uses the shared half-second touch activation and native HTML5 backend", () => {
expect(communityDndOptions.backends.map((entry) => entry.id)).toEqual(["html5", "touch"])
- expect(communityDndOptions.backends[1].options).toMatchObject({ delayTouchStart: 650, touchSlop: 8 })
+ expect(communityDndOptions.backends[1].options).toMatchObject({ delayTouchStart: 500, touchSlop: 8 })
})
it("commits one rail instruction on drop; Escape commits nothing", () => {
const onDrop = vi.fn(), onCancel = vi.fn()
diff --git a/src/web/src/components/community/community-dnd.tsx b/src/web/src/components/community/community-dnd.tsx
index ad62600b6..a6436cd53 100644
--- a/src/web/src/components/community/community-dnd.tsx
+++ b/src/web/src/components/community/community-dnd.tsx
@@ -7,7 +7,7 @@ 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 communityTouchHoldDelay = 500
export const communityDndOptions = {
backends: [
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
index 50eb29ef4..77d6b23b5 100644
--- a/src/web/src/components/community/community-touch-menu.dom.test.tsx
+++ b/src/web/src/components/community/community-touch-menu.dom.test.tsx
@@ -5,7 +5,7 @@ import { act, fireEvent, mockElementGeometry, render } from "@/test/react-dom-ha
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 { ChannelDndScope, ChannelDropContainer } 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"
@@ -41,11 +41,11 @@ function Rail({ drop, activate, menuAction, enabled }: { drop: (instruction: Rai
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 }) {
+function Tree({ kind, drop, activate, menuAction, enabled, withHref }: { kind: Exclude<Kind, "server">; drop: (event: ChannelTreeDrop) => void; activate: () => void; menuAction: () => void; enabled: boolean; withHref: 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>
+ ? <SortableChannel key={id} ch={{ id, name: id, unread: false, active: false }} href={withHref ? `/c/channels/server/${id}` : undefined} active={false} onClick={activate} onEdit={menuAction} canReorder={enabled} />
+ : <SortableCategory key={id} id={id} name={id} open onToggle={activate} onAddChannel={menuAction} onSettings={menuAction} canReorder={enabled} hasChannels>{null}</SortableCategory>)}<ChannelDropContainer id="category-b" /></ChannelDndScope>
}
function EmptyChannelScope({ enabled }: { enabled: boolean }) {
@@ -53,35 +53,183 @@ function EmptyChannelScope({ enabled }: { enabled: boolean }) {
return <ChannelDndScope tree={tree} onDrop={() => {}} enabled={enabled}>{null}</ChannelDndScope>
}
-function setup(kind: Kind, enabled = true, includeOtherScope = false) {
+function setup(kind: Kind, enabled = true, includeOtherScope = false, options: { target?: "row" | "text" | "settings" | "create"; channelHref?: boolean } = {}) {
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 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} withHref={options.channelHref ?? false} />}{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`))
+ const startNode = options.target === "text"
+ ? Array.from(source.querySelectorAll("span")).find(node => node.textContent === (kind === "server" ? "a" : `${kind}-a`))
+ : options.target === "settings" || options.target === "create"
+ ? source.querySelector(`button[aria-label="${options.target === "settings" ? "Category settings for" : "Create channel in"} ${kind}-a"] svg`)
+ : source
+ if (!startNode) throw new Error("Missing touch start target")
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 = () => {
+ Object.defineProperty(document, "elementFromPoint", { configurable: true, value: (_x: number, y: number) => y >= 90 ? target : startNode })
+ Object.defineProperty(document, "elementsFromPoint", { configurable: true, value: (_x: number, y: number) => [y >= 90 ? target : startNode] })
+ const touch = (y: number) => ({ identifier: 1, clientX: 20, clientY: y, target: startNode })
+ const start = (pointer = true) => {
+ if (pointer) fireEvent.pointerDown(startNode, { pointerType: "touch", button: 0 })
+ fireEvent.touchStart(startNode, { touches: [touch(20)], targetTouches: [touch(20)], changedTouches: [touch(20)] })
+ }
+ const warm = () => {
+ const warmTouch = { identifier: 2, clientX: 20, clientY: 20, target: source }
fireEvent.pointerDown(source, { pointerType: "touch", button: 0 })
- fireEvent.touchStart(source, { touches: [touch(20)], targetTouches: [touch(20)], changedTouches: [touch(20)] })
+ fireEvent.touchStart(source, { touches: [warmTouch], targetTouches: [warmTouch], changedTouches: [warmTouch] })
+ fireEvent.touchCancel(source, { touches: [], targetTouches: [], changedTouches: [warmTouch] })
}
- 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 move = (y: number) => fireEvent.touchMove(startNode, { touches: [touch(y)], targetTouches: [touch(y)], changedTouches: [touch(y)] })
+ const end = (y = 120) => fireEvent.touchEnd(startNode, { touches: [], targetTouches: [], changedTouches: [touch(y)] })
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)) }
+ return { ...view, manager, drop, activate, menuAction, source, startNode, start, warm, 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<Kind>(["server", "channel", "category"])("opens the %s menu at 500ms and starts same-touch dragging without another hold", async kind => {
+ const ui = setup(kind, true, false, { target: "text", channelHref: true })
+ ui.start()
+ await act(async () => { vi.advanceTimersByTime(499) })
+ expect(ui.queryByRole("menu")).not.toBeInTheDocument()
+ expect(ui.manager.getMonitor().isDragging()).toBe(false)
+ await act(async () => { vi.advanceTimersByTime(1) })
+ expect(ui.getByRole("menu")).toBeInTheDocument()
+ ui.move(55)
+ expect(ui.manager.getMonitor().isDragging()).toBe(true)
+ expect(ui.queryByRole("menu")).not.toBeInTheDocument()
+ ui.move(130)
+ ui.end()
+ expect(ui.drop).toHaveBeenCalledTimes(1)
+ expect(ui.activate).not.toHaveBeenCalled()
+ expect(ui.menuAction).not.toHaveBeenCalled()
+ })
+
+ it.each(["settings", "create"] as const)("keeps a category %s button hold out of the parent menu and drag", async target => {
+ const ui = setup("category", true, false, { target })
+ expect(ui.startNode.closest("button")).not.toBeNull()
+ ui.start()
+ await ui.hold()
+ expect(ui.queryByRole("menu")).not.toBeInTheDocument()
+ ui.move(55)
+ expect(ui.manager.getMonitor().isDragging()).toBe(false)
+ ui.move(130)
+ ui.end()
+ expect(ui.drop).not.toHaveBeenCalled()
+ expect(ui.activate).not.toHaveBeenCalled()
+ expect(ui.menuAction).not.toHaveBeenCalled()
+ })
+
+ it.each(["settings", "create"] as const)("activates only the category %s button on a short touch", async target => {
+ const ui = setup("category", true, false, { target })
+ ui.start()
+ ui.end()
+ fireEvent.click(ui.startNode)
+ await ui.hold()
+ expect(ui.menuAction).toHaveBeenCalledTimes(1)
+ expect(ui.activate).not.toHaveBeenCalled()
+ expect(ui.drop).not.toHaveBeenCalled()
+ expect(ui.queryByRole("menu")).not.toBeInTheDocument()
+ expect(ui.manager.getMonitor().isDragging()).toBe(false)
+ })
+
+ it.each(["settings", "create"] as const)("cancels a native mouse drag from the category %s button", target => {
+ const ui = setup("category", true, false, { target })
+ expect(fireEvent.dragStart(ui.startNode, { dataTransfer: {} })).toBe(false)
+ expect(ui.manager.getMonitor().isDragging()).toBe(false)
+ expect(ui.drop).not.toHaveBeenCalled()
+ expect(ui.activate).not.toHaveBeenCalled()
+ expect(ui.menuAction).not.toHaveBeenCalled()
+ })
+
+ it.each((["settings", "create"] as const).flatMap(target => [true, false].map(pointer => ({ target, pointer }))))("rejects the category $target press in active TouchBackend with pointer events=$pointer", async ({ target, pointer }) => {
+ const ui = setup("category", true, false, { target })
+ ui.warm()
+ ui.start(pointer)
+ await ui.hold()
+ ui.move(55)
+ expect(ui.manager.getMonitor().isDragging()).toBe(false)
+ expect(document.querySelector("[data-channel-floating-preview]")).toBeNull()
+ ui.move(130); ui.end()
+ expect(ui.drop).not.toHaveBeenCalled()
+ expect(ui.queryByRole("menu")).not.toBeInTheDocument()
+ expect(ui.menuAction).not.toHaveBeenCalled()
+ ui.warm()
+ const touch = (y: number) => ({ identifier: 3, clientX: 20, clientY: y, target: ui.source })
+ fireEvent.pointerDown(ui.source, { pointerType: "touch", button: 0 })
+ fireEvent.touchStart(ui.source, { touches: [touch(20)], targetTouches: [touch(20)], changedTouches: [touch(20)] })
+ await ui.hold()
+ fireEvent.touchMove(ui.source, { touches: [touch(55)], targetTouches: [touch(55)], changedTouches: [touch(55)] })
+ expect(ui.manager.getMonitor().isDragging()).toBe(true)
+ fireEvent.touchMove(ui.source, { touches: [touch(130)], targetTouches: [touch(130)], changedTouches: [touch(130)] })
+ fireEvent.touchEnd(ui.source, { touches: [], targetTouches: [], changedTouches: [touch(130)] })
+ expect(ui.drop).toHaveBeenCalledTimes(1)
+ })
+
+ it.each(["settings", "create"] as const)("rejects a parent-target HTML5 dragstart initiated on the category %s button", target => {
+ const ui = setup("category", true, false, { target })
+ fireEvent.pointerDown(ui.startNode, { pointerType: "mouse", button: 0 })
+ fireEvent.mouseDown(ui.startNode, { button: 0 })
+ expect(fireEvent.dragStart(ui.source, { clientX: 20, clientY: 20, dataTransfer: { setData: vi.fn(), setDragImage: vi.fn(), types: [], files: [] } })).toBe(false)
+ expect(ui.manager.getMonitor().isDragging()).toBe(false)
+ expect(ui.drop).not.toHaveBeenCalled()
+ fireEvent.pointerDown(ui.source, { pointerType: "mouse", button: 0 })
+ fireEvent.mouseDown(ui.source, { button: 0 })
+ fireEvent.dragStart(ui.source, { clientX: 20, clientY: 20, dataTransfer: { setData: vi.fn(), setDragImage: vi.fn(), types: [], files: [] } })
+ expect(ui.manager.getMonitor().isDragging()).toBe(true)
+ fireEvent.keyDown(window, { key: "Escape" })
+ expect(ui.manager.getMonitor().isDragging()).toBe(false)
+ expect(ui.drop).not.toHaveBeenCalled()
+ })
+
+ it("opens an unselected end hit area on the first native move and saves only after an accepted hover", async () => {
+ const ui = setup("channel", true, false, { target: "text", channelHref: true })
+ const end = ui.container.querySelector<HTMLElement>('[data-channel-drop-end="category-b"]')!
+ mockElementGeometry(end.parentElement!, { top: 100, left: 0, width: 100, height: 0 })
+ const hit = (y: number) => y < 90 ? ui.startNode : end.classList.contains("h-4") ? end : document.body
+ Object.defineProperty(document, "elementFromPoint", { configurable: true, value: (_x: number, y: number) => hit(y) })
+ Object.defineProperty(document, "elementsFromPoint", { configurable: true, value: (_x: number, y: number) => [hit(y)] })
+ ui.start(); await ui.hold(); ui.move(108)
+ expect(ui.manager.getMonitor().isDragging()).toBe(true)
+ expect(ui.manager.getMonitor().getTargetIds()).toEqual([])
+ expect(end).toHaveClass("h-4")
+ expect(end).not.toHaveAttribute("data-drop-visible")
+ expect(end).not.toHaveClass("border-dashed")
+ ui.end(108)
+ expect(ui.drop).not.toHaveBeenCalled()
+ ui.start(); await ui.hold(); ui.move(108); ui.move(109)
+ expect(end).toHaveAttribute("data-drop-visible", "true")
+ ui.end(109)
+ expect(ui.drop).toHaveBeenCalledExactlyOnceWith({ active: { id: "channel-a", kind: "channel" }, over: { id: "category-b", kind: "category" }, placement: "append" })
+ })
+
+ it.each((["channel", "category"] as const).flatMap(kind => (["row", "text"] as const).map(target => ({ kind, target }))))("starts a $kind drag at its $target with production link rendering", async ({ kind, target }) => {
+ const ui = setup(kind, true, false, { target, channelHref: true })
+ expect(ui.source.tagName).toBe(kind === "channel" ? "A" : "DIV")
+ expect(ui.source.contains(ui.startNode)).toBe(true)
+ if (target === "text") expect(ui.startNode).not.toBe(ui.source)
+ ui.start()
+ await ui.hold()
+ expect(ui.startNode.isConnected).toBe(true)
+ expect(ui.getByRole("menu")).toBeInTheDocument()
+ ui.move(55)
+ expect(ui.manager.getMonitor().isDragging()).toBe(true)
+ expect(ui.queryByRole("menu")).not.toBeInTheDocument()
+ 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"])("finishes a %s drop once when saving disables reordering", async kind => {
const ui = setup(kind)
ui.drop.mockImplementationOnce(() => { ui.setEnabled(false) })
diff --git a/src/web/src/components/community/dnd-drag-preview.tsx b/src/web/src/components/community/dnd-drag-preview.tsx
new file mode 100644
index 000000000..b5e774b5d
--- /dev/null
+++ b/src/web/src/components/community/dnd-drag-preview.tsx
@@ -0,0 +1,48 @@
+"use client"
+
+import { useLayoutEffect, useRef, type ComponentProps, type ReactNode } from "react"
+import { createPortal } from "react-dom"
+
+export function DndDragPreview({ offset, width, height, returning, onReturnComplete, anchorClassName = "", children, ...props }: {
+ offset: { x: number; y: number }
+ width: number
+ height: number
+ returning: { element: HTMLElement } | null
+ onReturnComplete: () => void
+ anchorClassName?: string
+ children: ReactNode
+} & Omit<ComponentProps<"div">, "children" | "className" | "style">) {
+ const anchor = useRef<HTMLDivElement>(null)
+ const complete = useRef(onReturnComplete)
+ useLayoutEffect(() => { complete.current = onReturnComplete }, [onReturnComplete])
+ useLayoutEffect(() => {
+ if (!returning || !anchor.current) return
+ const media = window.matchMedia("(prefers-reduced-motion: reduce)")
+ const element = returning.element
+ const rect = element.getBoundingClientRect()
+ if (!element.isConnected || rect.width === 0 || rect.height === 0 || media.matches) {
+ complete.current()
+ return
+ }
+ const animation = anchor.current.animate([
+ { transform: `translate(${offset.x}px, ${offset.y}px)` },
+ { transform: `translate(${rect.left + (rect.width - width) / 2}px, ${rect.top + (rect.height - height) / 2}px)` },
+ ], { duration: 150, easing: "cubic-bezier(0.2, 0.8, 0.2, 1)", fill: "forwards" })
+ animation.onfinish = () => complete.current()
+ const reduce = () => { if (media.matches) complete.current() }
+ media.addEventListener("change", reduce)
+ return () => {
+ animation.onfinish = null
+ animation.cancel()
+ media.removeEventListener("change", reduce)
+ }
+ }, [returning, width, height, offset.x, offset.y])
+ return createPortal(
+ <div {...props} aria-hidden="true" className="pointer-events-none fixed inset-0 z-50">
+ <div ref={anchor} className={`absolute left-0 top-0 grid place-items-center ${anchorClassName}`}
+ style={{ width, height, transform: `translate(${offset.x}px, ${offset.y}px)` }}>
+ {children}
+ </div>
+ </div>, document.body,
+ )
+}
diff --git a/src/web/src/components/community/drop-line.tsx b/src/web/src/components/community/drop-line.tsx
index fa2b07e10..c35628f9f 100644
--- a/src/web/src/components/community/drop-line.tsx
+++ b/src/web/src/components/community/drop-line.tsx
@@ -2,6 +2,7 @@
export function DropLine({ side }: { side: "top" | "bottom" }) {
return (
<div
+ data-slot="community-drop-line"
className={`pointer-events-none absolute inset-x-1 z-10 h-0.5 rounded-full bg-primary ${side === "top" ? "-top-px" : "-bottom-px"}`}
/>
)
diff --git a/src/web/src/components/community/shell/server-rail-drag-preview.tsx b/src/web/src/components/community/shell/server-rail-drag-preview.tsx
index fcccbf656..8af30a52a 100644
--- a/src/web/src/components/community/shell/server-rail-drag-preview.tsx
+++ b/src/web/src/components/community/shell/server-rail-drag-preview.tsx
@@ -1,7 +1,6 @@
"use client"
-import { createPortal } from "react-dom"
-import { useLayoutEffect, useRef } from "react"
+import { DndDragPreview } from "../dnd-drag-preview"
import type { Server } from "@/lib/community/models/navigation"
import { RailServerIcon } from "./rail-server-icon"
import { RailFolderIcon } from "./rail-folder"
@@ -17,30 +16,6 @@ export function ServerRailDragPreview({ dnd, servers, folderNames, state, active
activeServerId: string
}) {
const { entity, offset, returning } = useServerRailDrag(dnd)
- const anchor = useRef<HTMLDivElement>(null)
- useLayoutEffect(() => {
- if (!returning || !anchor.current) return
- const media = window.matchMedia("(prefers-reduced-motion: reduce)")
- const element = returning.element
- const rect = element.getBoundingClientRect()
- if (!element.isConnected || rect.width === 0 || rect.height === 0 || media.matches) {
- dnd.completeReturn(returning)
- return
- }
- const animation = anchor.current.animate([
- { transform: `translate(${returning.offset.x}px, ${returning.offset.y}px)` },
- { transform: `translate(${rect.left + (rect.width - 44) / 2}px, ${rect.top + (rect.height - 44) / 2}px)` },
- ], { duration: 150, easing: "cubic-bezier(0.2, 0.8, 0.2, 1)", fill: "forwards" })
- const complete = () => dnd.completeReturn(returning)
- animation.onfinish = complete
- const reduce = () => { if (media.matches) complete() }
- media.addEventListener("change", reduce)
- return () => {
- animation.onfinish = null
- animation.cancel()
- media.removeEventListener("change", reduce)
- }
- }, [dnd, returning])
if (!entity || !offset) return null
const server = entity.kind === "server" ? servers.get(entity.id) : undefined
const name = server?.name ?? folderNames.get(entity.id) ?? "Group"
@@ -48,9 +23,10 @@ export function ServerRailDragPreview({ dnd, servers, folderNames, state, active
const child = servers.get(id)
return child ? [child] : []
})
- return createPortal(
- <div aria-hidden="true" data-testid={tid.serverRailDragPreview} data-rail-floating-preview={entity.kind} data-rail-preview-phase={returning ? "returning" : "dragging"} className="pointer-events-none fixed inset-0 z-50">
- <div ref={anchor} className="absolute left-0 top-0 grid size-11 place-items-center" style={{ transform: `translate(${offset.x}px, ${offset.y}px)` }}>
+ return (
+ <DndDragPreview offset={offset} width={44} height={44} returning={returning}
+ onReturnComplete={() => { if (returning) dnd.completeReturn(returning) }} anchorClassName="size-11"
+ data-testid={tid.serverRailDragPreview} data-rail-floating-preview={entity.kind} data-rail-preview-phase={returning ? "returning" : "dragging"}>
<span data-slot="community-server-rail-drag-glyph" className="relative grid size-11 place-items-center opacity-50">
{server ? <RailServerIcon server={server} active={activeServerId === server.id} /> : (
<span data-slot="community-server-rail-drag-folder" className={`grid size-10 shrink-0 place-items-center bg-accent/50 text-muted-foreground dark:bg-accent ${children.some((child) => child.id === activeServerId) ? "rounded-xl" : "rounded-[18px]"}`}>
@@ -63,7 +39,6 @@ export function ServerRailDragPreview({ dnd, servers, folderNames, state, active
<span className="absolute -left-1 top-1/2 size-2 -translate-y-1/2 rotate-45 rounded-xs bg-foreground" />
<span className="truncate">{name}</span>
</span>
- </div>
- </div>, document.body,
+ </DndDragPreview>
)
}
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 045207a5f..8edbf8e48 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -36,6 +36,7 @@ export const tid = {
serverRailInsert: (id: string) => `community-server-rail-insert-${id}`,
serverRailInsertFolder: (id: string) => `community-server-rail-insert-folder-${id}`,
categoryHeader: (id: string) => `community-category-header-${id}`,
+ channelDragPreview: "community-channel-drag-preview",
channelSidebarScroll: "community-channel-sidebar-scroll",
channelSidebarPending: (serverId: string) => `community-channel-sidebar-pending-${serverId}`,
messageHeaderLeadingLoading: "community-message-header-leading-loading",