Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): make channel sidebar touch drag safe (#590)

Gener1767c67b4425
diff --git a/src/web/src/components/community/channels/channel-sidebar.touch-dnd.contract.test.ts b/src/web/src/components/community/channels/channel-sidebar.touch-dnd.contract.test.ts
new file mode 100644
index 000000000..083db3424
--- /dev/null
+++ b/src/web/src/components/community/channels/channel-sidebar.touch-dnd.contract.test.ts
@@ -0,0 +1,45 @@
+import { readFileSync } from "node:fs"
+import { describe, expect, it } from "vitest"
+
+const readSource = (relativePath: string) =>
+ readFileSync(new URL(relativePath, import.meta.url), "utf8")
+
+describe("channel sidebar touch drag contracts", () => {
+ it("uses input-specific sensors with the agreed activation constraints", () => {
+ const sidebar = readSource("./channel-sidebar.tsx")
+
+ expect(sidebar).toContain(
+ "useSensor(MouseSensor, { activationConstraint: { distance: 5 } })",
+ )
+ expect(sidebar).toContain(
+ "useSensor(TouchSensor, { activationConstraint: { delay: 250, tolerance: 5 } })",
+ )
+ expect(sidebar).toContain(
+ "useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })",
+ )
+ expect(sidebar).toContain("collisionDetection={channelSidebarCollisionDetection}")
+ expect(sidebar).toContain('activeData?.kind !== "category"')
+ expect(sidebar).toContain("containerId === containerId")
+ expect(sidebar).toContain("catOrder.includes(activeStr)")
+ expect(sidebar).not.toContain("PointerSensor")
+ })
+
+ it("keeps the whole channel row and category header draggable without blocking touch scroll", () => {
+ const channel = readSource("./sortable-channel.tsx")
+ const category = readSource("./sortable-category.tsx")
+
+ expect(channel).toContain("onClick={onClick}")
+ expect(category).toContain("onClick: onToggle")
+ expect(category).toContain('data: { kind: "category" }')
+ expect(category).toContain("ref: setActivatorNodeRef")
+ expect(category).toContain("onTouchStartCapture: listeners?.onTouchStart")
+ expect(category).not.toContain("useDroppable")
+
+ for (const source of [channel, category]) {
+ expect(source).toContain("...attributes")
+ expect(source).toContain("...listeners")
+ expect(source).toContain("touch-manipulation")
+ expect(source).not.toContain("touch-none")
+ }
+ })
+})
diff --git a/src/web/src/components/community/channels/channel-sidebar.tsx b/src/web/src/components/community/channels/channel-sidebar.tsx
index 797b82967..c038a2610 100644
--- a/src/web/src/components/community/channels/channel-sidebar.tsx
+++ b/src/web/src/components/community/channels/channel-sidebar.tsx
@@ -3,9 +3,10 @@
import { Fragment, memo, useRef, useState } from "react"
import { Settings, Users, Link2, Bell, ChevronDown, UserPlus } from "lucide-react"
import {
- DndContext, closestCenter, PointerSensor, useSensor, useSensors,
+ DndContext, KeyboardSensor, MouseSensor, TouchSensor, closestCenter, useSensor, useSensors,
+ type CollisionDetection,
} from "@dnd-kit/core"
-import { SortableContext, verticalListSortingStrategy } from "@dnd-kit/sortable"
+import { SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy } from "@dnd-kit/sortable"
import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem } from "@/components/ui/context-menu"
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"
import { Skeleton } from "@/components/ui/skeleton"
@@ -14,7 +15,7 @@ import { SortableChannel, PendingChannelRow } from "./sortable-channel"
import { CreateChannelDialog } from "../settings/create-channel-dialog"
import { CreateCategoryDialog } from "../settings/create-category-dialog"
import { CategorySettingsDialog } from "../settings/category-settings-dialog"
-import { catId, catOf, isCat, reorderChannelsWithin, type ChannelTree } from "./use-channel-tree"
+import { catId, catOf, reorderChannelsWithin, type ChannelTree } from "./use-channel-tree"
import { InviteDialog } from "../social/invite-dialog"
import { ChannelAddMembersDialog } from "../members/channel-add-members-dialog"
import type { Channel } from "@/lib/community/models/navigation"
@@ -32,6 +33,20 @@ type Dialog =
| { kind: "manage-members"; channelId: string; channelName: string }
| null
+type SortableData = { kind?: "category" | "channel"; sortable?: { containerId?: string } }
+
+const channelSidebarCollisionDetection: CollisionDetection = (args) => {
+ const activeData = args.active.data.current as SortableData | undefined
+ if (args.pointerCoordinates && activeData?.kind !== "category") return closestCenter(args)
+
+ const containerId = activeData?.sortable?.containerId
+ if (!containerId) return closestCenter(args)
+
+ const sameContainer = args.droppableContainers.filter((container) =>
+ (container.data.current as SortableData | undefined)?.sortable?.containerId === containerId)
+ return closestCenter({ ...args, droppableContainers: sameContainer })
+}
+
// The channel sidebar (server view). Category/channel reorder + add/remove/rename live in
// useChannelTree. The category gear/right-click opens settings; "+" (or empty-space
// right-click) creates; channels right-click to edit/delete. A private category only
@@ -82,7 +97,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({
const dragOriginCat = useRef<string | undefined>(undefined)
const onDragStart = (e: { active: { id: string | number } }) => {
const activeStr = String(e.active.id)
- dragOriginCat.current = isCat(activeStr) ? undefined : catOf(activeStr, order)
+ dragOriginCat.current = catOrder.includes(activeStr) ? undefined : catOf(activeStr, order)
}
const onDragEnd = (e: Parameters<typeof treeDragEnd>[0]) => {
const originCat = dragOriginCat.current
@@ -92,7 +107,9 @@ export const ChannelSidebar = memo(function ChannelSidebar({
if (!over || active.id === over.id) return
const activeStr = String(active.id)
const overStr = String(over.id)
- if (activeStr.startsWith("cat_") && overStr.startsWith("cat_")) {
+ const activeIsCategory = catOrder.includes(activeStr)
+ const overIsCategory = catOrder.includes(overStr)
+ if (activeIsCategory && overIsCategory) {
const reordered = catOrder.indexOf(activeStr) !== -1 ? (() => {
const from = catOrder.indexOf(activeStr)
const to = catOrder.indexOf(overStr)
@@ -104,13 +121,13 @@ export const ChannelSidebar = memo(function ChannelSidebar({
})() : null
// Never send an optimistic (pending) category id to the reorder endpoint.
if (reordered) onReorderCategories?.(reordered.filter((cid) => !catPending[cid]))
- } else if (!activeStr.startsWith("cat_")) {
+ } else if (!activeIsCategory) {
// The channel's category AFTER onDragOver settled the optimistic move.
const destCat = catOf(activeStr, order)
// A blocked public↔private move: the cursor landed in a different-privacy
// category, so onDragOver refused to move it and destCat === originCat.
// Detect the attempt from the drop target and warn.
- const dropTargetCat = isCat(overStr) ? overStr : catOf(overStr, order)
+ const dropTargetCat = overIsCategory ? overStr : catOf(overStr, order)
if (
originCat && dropTargetCat && dropTargetCat !== originCat &&
destCat === originCat &&
@@ -141,7 +158,11 @@ export const ChannelSidebar = memo(function ChannelSidebar({
onReorderChannels?.(allChannelIds)
}
}
- const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }))
+ const sensors = useSensors(
+ useSensor(MouseSensor, { activationConstraint: { distance: 5 } }),
+ useSensor(TouchSensor, { activationConstraint: { delay: 250, tolerance: 5 } }),
+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
+ )
const [dialog, setDialog] = useState<Dialog>(null)
const withMute = (ch: Channel): Channel => mutedChannels && ch.id in mutedChannels ? { ...ch, muted: mutedChannels[ch.id] } : ch
const hasActiveSidebarThread = !!activeThreadId && Object.values(forumThreadsByParent)
@@ -226,7 +247,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({
// one DndContext spans everything: categories sort among themselves, channels across categories
const channelTree = (
- <DndContext id="d-channels" sensors={sensors} collisionDetection={closestCenter} onDragStart={onDragStart} onDragOver={onDragOver} onDragEnd={onDragEnd}>
+ <DndContext id="d-channels" sensors={sensors} collisionDetection={channelSidebarCollisionDetection} onDragStart={onDragStart} onDragOver={onDragOver} onDragEnd={onDragEnd}>
{/* uncategorized channels (empty-name category) render bare at the top — no header */}
{noneCatId && order[noneCatId]?.length > 0 && (
<SortableContext items={order[noneCatId].filter((c) => !c.pending).map((c) => c.id)} strategy={verticalListSortingStrategy}>
diff --git a/src/web/src/components/community/channels/sortable-category.tsx b/src/web/src/components/community/channels/sortable-category.tsx
index cd7697fe5..5b10d9a68 100644
--- a/src/web/src/components/community/channels/sortable-category.tsx
+++ b/src/web/src/components/community/channels/sortable-category.tsx
@@ -4,7 +4,6 @@ import { useState } from "react"
import type React from "react"
import { ChevronDown, Plus, Settings, Lock, Trash2 } from "lucide-react"
import { useSortable } from "@dnd-kit/sortable"
-import { useDroppable } from "@dnd-kit/core"
import { CSS } from "@dnd-kit/utilities"
import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuSeparator } from "@/components/ui/context-menu"
import { ConfirmDialog } from "@/components/ui/confirm-dialog"
@@ -16,8 +15,8 @@ export function hasCategoryMenu(h: { onAddChannel?: () => void; onSettings?: ()
return !!(h.onAddChannel || h.onSettings || h.onDelete)
}
-// A drag-sortable category. The whole header is the drag surface (no handle) — a 5px
-// activation distance distinguishes a click (collapse) from a drag. It is also a drop
+// A drag-sortable category. The whole header is the drag surface (no handle) — mouse
+// movement or a touch long-press distinguishes collapse from reorder. It is also a drop
// target so channels can be dropped onto it (including its empty space). Right-click
// (or the gear) opens Settings; the "+" creates a channel; a lock shows when private.
export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChannel, onSettings, onDelete, isPrivate, canReorder = true, pending = false, children }: {
@@ -34,18 +33,22 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChan
children: React.ReactNode
}) {
const [confirmingDelete, setConfirmingDelete] = useState(false)
- const { attributes, listeners, setNodeRef, transform, transition, isDragging, isOver, activeIndex, index } = useSortable({ id: catDndId, disabled: !canReorder })
- const { setNodeRef: setDropRef, isOver: isChannelOver } = useDroppable({ id: catDndId })
+ const { attributes, listeners, setActivatorNodeRef, setNodeRef, transform, transition, isDragging, isOver, activeIndex, index } = useSortable({ id: catDndId, data: { kind: "category" }, disabled: !canReorder })
const style = { transform: CSS.Transform.toString(transform), transition, opacity: isDragging ? 0.4 : 1, zIndex: isDragging ? 10 : undefined }
const showLine = isOver && !isDragging
const lineSide: "top" | "bottom" = activeIndex !== -1 && activeIndex < index ? "bottom" : "top"
// The header div is the drag surface; it renders bare (no ContextMenu) when there are no
// actions, so share its props/children across both branches to avoid drift.
const headerProps = {
+ ref: setActivatorNodeRef,
...attributes,
...listeners,
+ onTouchStart: undefined,
+ onTouchStartCapture: listeners?.onTouchStart
+ ? (event: React.TouchEvent<HTMLDivElement>) => listeners.onTouchStart?.(event)
+ : undefined,
onClick: onToggle,
- className: `group flex w-full touch-none items-center gap-1 rounded px-1 py-1 text-xs font-semibold text-muted-foreground/80 select-none hover:text-foreground ${canReorder ? "cursor-grab active:cursor-grabbing" : "cursor-pointer"}`,
+ 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 ${canReorder ? "cursor-grab active:cursor-grabbing" : "cursor-pointer"}`,
}
const headerInner = (
<>
@@ -103,7 +106,7 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChan
<div {...headerProps}>{headerInner}</div>
)}
{open && (
- <div ref={setDropRef} className={`rounded-md transition-colors ${isChannelOver ? "bg-accent/40" : ""}`}>
+ <div className={`rounded-md transition-colors ${isOver ? "bg-accent/40" : ""}`}>
{children}
</div>
)}
diff --git a/src/web/src/components/community/channels/sortable-channel.tsx b/src/web/src/components/community/channels/sortable-channel.tsx
index 4dfcc070a..136edaab9 100644
--- a/src/web/src/components/community/channels/sortable-channel.tsx
+++ b/src/web/src/components/community/channels/sortable-channel.tsx
@@ -35,7 +35,7 @@ export function PendingChannelRow({ ch }: { ch: Channel }) {
}
// A single drag-sortable channel row. The whole row is the drag surface (no handle);
-// a 5px activation distance keeps a tap = "switch channel" and a drag = reorder.
+// mouse movement or a touch long-press distinguishes navigation from reorder.
// Right-click opens an edit/mute/delete menu.
export function SortableChannel({ ch, active, onClick, onPrefetch, onEdit, onDelete, onManageMembers, canReorder = true }: {
ch: Channel
@@ -63,7 +63,7 @@ export function SortableChannel({ ch, active, onClick, onPrefetch, onEdit, onDel
{...attributes}
{...listeners}
className={[
- "group relative flex h-8 w-full cursor-pointer touch-none items-center gap-2 rounded-md px-2 text-sm select-none",
+ "group relative flex h-8 w-full cursor-pointer touch-manipulation items-center gap-2 rounded-md px-2 text-sm select-none",
canReorder ? "active:cursor-grabbing" : "",
active
? "bg-sidebar-accent text-foreground"
diff --git a/src/web/src/components/community/channels/use-channel-tree.test.ts b/src/web/src/components/community/channels/use-channel-tree.test.ts
index ebee10855..0b8ee7a4d 100644
--- a/src/web/src/components/community/channels/use-channel-tree.test.ts
+++ b/src/web/src/components/community/channels/use-channel-tree.test.ts
@@ -1,17 +1,50 @@
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
import { describe, it, expect } from "vitest"
import {
- isCat,
catId,
catOf,
moveChannelAcrossCategories,
reorderChannelsWithin,
reorderCategories,
mergeChannelMetadata,
+ useChannelTree,
type ChannelOrder,
} from "./use-channel-tree"
import type { Channel, Category } from "@/lib/community/models/navigation"
+import type { DragEndEvent } from "@dnd-kit/core"
const ch = (id: string): Channel => ({ id, name: id, active: false, unread: false })
+const category = (id: string, channels: Channel[]): Category => ({ id, name: id, channels })
+
+type Tree = ReturnType<typeof useChannelTree>
+
+function CaptureTree({ categories, onResult }: { categories: Category[]; onResult: (tree: Tree) => void }) {
+ onResult(useChannelTree(categories))
+ return null
+}
+
+async function renderTreeHook(categories: Category[]) {
+ let current!: Tree
+ await act(async () => {
+ TestRenderer.create(
+ React.createElement(CaptureTree, { categories, onResult: (tree) => { current = tree } }),
+ )
+ })
+ return {
+ get current() {
+ return current
+ },
+ async drag(callback: (tree: Tree) => void) {
+ await act(async () => callback(current))
+ },
+ }
+}
+
+const dragEvent = (activeId: string, overId: string): DragEndEvent => ({
+ active: { id: activeId },
+ over: { id: overId },
+}) as DragEndEvent
const order: ChannelOrder = {
cat_A: [ch("a1"), ch("a2")],
@@ -19,10 +52,9 @@ const order: ChannelOrder = {
}
describe("id helpers", () => {
- it("isCat / catId", () => {
+ it("keeps persisted category ids unchanged for dnd", () => {
expect(catId("cat_A")).toBe("cat_A")
- expect(isCat("cat_A")).toBe(true)
- expect(isCat("a1")).toBe(false)
+ expect(catId("5vg7bs")).toBe("5vg7bs")
})
})
@@ -34,6 +66,10 @@ describe("catOf", () => {
it("resolves a category id to itself", () => {
expect(catOf("cat_B", order)).toBe("cat_B")
})
+ it("resolves an opaque category id from the actual tree keys", () => {
+ const opaqueOrder = { "5vg7bs": [ch("a1")] }
+ expect(catOf("5vg7bs", opaqueOrder)).toBe("5vg7bs")
+ })
it("returns undefined for an unknown channel", () => {
expect(catOf("zzz", order)).toBeUndefined()
})
@@ -101,6 +137,43 @@ describe("reorderCategories", () => {
})
})
+describe("useChannelTree opaque category drag callbacks", () => {
+ const categories = [
+ category("5vg7bs", [ch("a1"), ch("a2")]),
+ category("9qsh2k", [ch("b1"), ch("b2")]),
+ ]
+
+ it("ignores category drag-over instead of moving a channel", async () => {
+ const hook = await renderTreeHook(categories)
+ const before = hook.current.order
+
+ await hook.drag((tree) => tree.onDragOver(dragEvent("5vg7bs", "b1")))
+
+ expect(hook.current.order).toBe(before)
+ expect(hook.current.order["5vg7bs"].map((channel) => channel.id)).toEqual(["a1", "a2"])
+ expect(hook.current.order["9qsh2k"].map((channel) => channel.id)).toEqual(["b1", "b2"])
+ })
+
+ it("reorders opaque categories through the hook drop callback", async () => {
+ const hook = await renderTreeHook(categories)
+
+ await hook.drag((tree) => tree.onDragEnd(dragEvent("5vg7bs", "9qsh2k")))
+
+ expect(hook.current.catOrder).toEqual(["9qsh2k", "5vg7bs"])
+ })
+
+ it("treats an opaque category dropped over a channel as a no-op", async () => {
+ const hook = await renderTreeHook(categories)
+ const beforeOrder = hook.current.order
+ const beforeCatOrder = hook.current.catOrder
+
+ await hook.drag((tree) => tree.onDragEnd(dragEvent("5vg7bs", "b1")))
+
+ expect(hook.current.order).toBe(beforeOrder)
+ expect(hook.current.catOrder).toBe(beforeCatOrder)
+ })
+})
+
// Regression: the sync effect's id-set early-return silently swallowed
// metadata-only updates (unread/name) — see "The useChannelTree gap" in
// plans/community-unread-indicators.md.
diff --git a/src/web/src/components/community/channels/use-channel-tree.ts b/src/web/src/components/community/channels/use-channel-tree.ts
index 458920326..fbd3b7db2 100644
--- a/src/web/src/components/community/channels/use-channel-tree.ts
+++ b/src/web/src/components/community/channels/use-channel-tree.ts
@@ -5,16 +5,15 @@ import { arrayMove } from "@dnd-kit/sortable"
import type { DragEndEvent } from "@dnd-kit/core"
import type { Category, Channel } from "@/lib/community/models/navigation"
-// dnd ids: category ids are used directly (they already have a "cat_" prefix);
-// channel ids are bare. We distinguish by checking the "cat_" prefix.
-export const isCat = (id: string) => id.startsWith("cat_")
+// DnD keeps the persisted opaque IDs unchanged. Category identity comes from
+// membership in `catOrder` / `order`, never from an ID prefix.
export const catId = (id: string) => id
export type ChannelOrder = Record<string, Channel[]>
-/** Which category currently holds a channel id (or the category itself if `id` is a cat id). */
+/** Which category currently holds a channel id (or the category itself if `id` is an order key). */
export function catOf(id: string, order: ChannelOrder): string | undefined {
- if (isCat(id)) return id
+ if (Object.hasOwn(order, id)) return id
return Object.keys(order).find((cat) => order[cat].some((c) => c.id === id))
}
@@ -195,7 +194,7 @@ export function useChannelTree(categories: Category[]) {
const onDragOver = useCallback((e: DragEndEvent) => {
const { active, over } = e
- if (!over || isCat(String(active.id))) return // category drags handled on drop
+ if (!over || catOrder.includes(String(active.id))) return // category drags handled on drop
setOrder((prev) => {
const fromCat = catOf(String(active.id), prev)
const toCat = catOf(String(over.id), prev)
@@ -208,18 +207,20 @@ export function useChannelTree(categories: Category[]) {
}
return moveChannelAcrossCategories(prev, String(active.id), String(over.id))
})
- }, [catPrivate])
+ }, [catOrder, catPrivate])
const onDragEnd = useCallback((e: DragEndEvent) => {
const { active, over } = e
if (!over || active.id === over.id) return
- if (isCat(String(active.id)) && isCat(String(over.id))) {
+ const activeIsCategory = catOrder.includes(String(active.id))
+ const overIsCategory = catOrder.includes(String(over.id))
+ if (activeIsCategory && overIsCategory) {
setCatOrder((prev) => reorderCategories(prev, String(active.id), String(over.id)))
return
}
- if (isCat(String(active.id))) return
+ if (activeIsCategory) return
setOrder((prev) => reorderChannelsWithin(prev, String(active.id), String(over.id)))
- }, [])
+ }, [catOrder])
return useMemo(() => ({
collapsed, catOrder, order, catNames, catPrivate, catPending, catCreators,