Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): make server rail drag-only (#630)

Gener84c82f548927
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index e08b7ce07..db6501cb2 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -48,7 +48,7 @@ export const SPEC_SECONDS = {
"35-channel-ref-directory-states.spec.ts": 60,
"35-bot-token-usage-quota.spec.ts": 45,
"36-server-switch-pending-checkpoint.spec.ts": 60,
- "37-server-rail-pdd.spec.ts": 10,
+ "37-server-rail-pdd.spec.ts": 120,
"38-community-navigation-checkpoint-matrix.spec.ts": 60,
"39-mobile-message-interactions.spec.ts": 20,
"39-mobile-composer-send.spec.ts": 45,
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index f3897db88..28037d731 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -70,7 +70,7 @@ describe("planE2eShards", () => {
expect(first).toHaveLength(E2E_SHARD_COUNT)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
- expect(totals.sort((left, right) => left - right)).toEqual([394, 395, 395, 395, 396])
+ expect(totals.sort((left, right) => left - right)).toEqual([415, 416, 416, 418, 420])
expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)
})
diff --git a/src/web/src/components/community/shell/rail-folder.test.ts b/src/web/src/components/community/shell/rail-folder.test.ts
index b992fd5b0..8a20ec370 100644
--- a/src/web/src/components/community/shell/rail-folder.test.ts
+++ b/src/web/src/components/community/shell/rail-folder.test.ts
@@ -3,6 +3,7 @@ import { railFolderPropsEqual } from "./rail-folder"
const base = {
folderId: "folder",
+ name: "Group",
open: false,
active: false,
unread: false,
@@ -16,6 +17,7 @@ describe("RailFolder memo boundary", () => {
expect(railFolderPropsEqual(base, { ...base, unread: true })).toBe(false)
expect(railFolderPropsEqual(base, { ...base, open: true })).toBe(false)
expect(railFolderPropsEqual(base, { ...base, active: true })).toBe(false)
+ expect(railFolderPropsEqual(base, { ...base, name: "Team" })).toBe(false)
})
it("rerenders only when thumbnail presentation changes", () => {
@@ -28,4 +30,9 @@ describe("RailFolder memo boundary", () => {
folderServers: [{ ...base.folderServers[0]!, icon: "/new.png" }],
})).toBe(false)
})
+
+
+ it("rerenders when the shared drag description changes", () => {
+ expect(railFolderPropsEqual(base, { ...base, dragDescriptionId: "rail-help" })).toBe(false)
+ })
})
diff --git a/src/web/src/components/community/shell/rail-folder.tsx b/src/web/src/components/community/shell/rail-folder.tsx
index 6307c71aa..44de602eb 100644
--- a/src/web/src/components/community/shell/rail-folder.tsx
+++ b/src/web/src/components/community/shell/rail-folder.tsx
@@ -11,6 +11,7 @@ import type { RailEntity, RailOperation } from "@/lib/community/server-rail-mode
type RailFolderProps = {
folderId: string
+ name: string
open: boolean
active: boolean
unread: boolean
@@ -24,12 +25,12 @@ type RailFolderProps = {
element: HTMLElement,
dragHandle: HTMLElement,
) => () => void
- onMove?: (source: RailEntity, focusTarget: HTMLElement) => void
+ dragDescriptionId?: string
}
function RailFolderImpl({
- folderId, open, active, unread, onToggle, folderServers, onUngroup, dragging: isDragActive,
- preview, registerItem, onMove,
+ folderId, name, open, active, unread, onToggle, folderServers, onUngroup, dragging: isDragActive,
+ preview, registerItem, dragDescriptionId,
}: RailFolderProps) {
const rootRef = useRef<HTMLDivElement>(null)
const buttonRef = useRef<HTMLButtonElement>(null)
@@ -63,44 +64,45 @@ function RailFolderImpl({
<button
ref={buttonRef}
data-testid={tid.serverRailFolder(folderId)}
+ data-dragging={isDragActive || undefined}
+ data-rail-preview={preview ?? undefined}
+ aria-label={name}
+ aria-describedby={dragDescriptionId}
+ aria-keyshortcuts="Space ArrowUp ArrowDown Escape"
onClick={onToggle}
- className={[
- "grid size-10 cursor-pointer touch-manipulation grid-cols-2 gap-1 p-2 transition-[border-radius,background-color] duration-150 active:cursor-grabbing",
- open ? "rounded-xl bg-primary/15" : "rounded-[18px] bg-accent hover:rounded-xl hover:bg-primary/20",
+ className="group/folder grid size-11 cursor-pointer place-items-center focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none active:cursor-grabbing"
+ >
+ <span className={[
+ "pointer-events-none grid size-10 grid-cols-2 gap-1 p-2 transition-[border-radius,background-color] duration-150",
+ open ? "rounded-xl bg-primary/15" : "rounded-[18px] bg-accent group-hover/folder:rounded-xl group-hover/folder:bg-primary/20",
preview === "combine" ? "bg-primary/10 outline outline-2! outline-primary" : "",
].join(" ")}
- >
- {Array.from({ length: 4 }).map((_, i) => {
- const s = folderServers[i]
- return s ? (
- <span
- key={s.id}
- className={[
- "relative grid aspect-square place-items-center overflow-hidden rounded-sm text-[7px] font-semibold",
- s.icon ? "bg-card text-muted-foreground" : "text-white [text-shadow:0_1px_1px_rgb(0_0_0/0.35)]",
- ].join(" ")}
- >
- {s.icon ? <img src={s.icon} alt={s.name} className="size-full object-cover" /> : <><SeededBackdrop seed={s.id} /><span className="relative">{s.initial}</span></>}
- </span>
- ) : (
- <span key={i} className="aspect-square rounded-sm bg-card/50" />
- )
- })}
+ >
+ {Array.from({ length: 4 }).map((_, i) => {
+ const s = folderServers[i]
+ return s ? (
+ <span
+ key={s.id}
+ className={[
+ "relative grid aspect-square place-items-center overflow-hidden rounded-sm text-[7px] font-semibold",
+ s.icon ? "bg-card text-muted-foreground" : "text-white [text-shadow:0_1px_1px_rgb(0_0_0/0.35)]",
+ ].join(" ")}
+ >
+ {s.icon ? <img src={s.icon} alt={s.name} className="size-full object-cover" /> : <><SeededBackdrop seed={s.id} /><span className="relative">{s.initial}</span></>}
+ </span>
+ ) : (
+ <span key={i} className="aspect-square rounded-sm bg-card/50" />
+ )
+ })}
+ </span>
</button>
</ContextMenuTrigger>
<ContextMenuContent className="w-52">
- {onMove && (
- <ContextMenuItem onClick={() => {
- if (buttonRef.current) onMove({ kind: "folder", id: folderId }, buttonRef.current)
- }}>
- Move…
- </ContextMenuItem>
- )}
<ContextMenuItem onClick={onUngroup}>Ungroup</ContextMenuItem>
</ContextMenuContent>
</ContextMenu>
</TooltipTrigger>
- <TooltipContent side="right" sideOffset={8}>Group</TooltipContent>
+ <TooltipContent side="right" sideOffset={8}>{name}</TooltipContent>
</Tooltip>
)
}
@@ -108,6 +110,7 @@ function RailFolderImpl({
export function railFolderPropsEqual(prev: RailFolderProps, next: RailFolderProps) {
if (
prev.folderId !== next.folderId ||
+ prev.name !== next.name ||
prev.open !== next.open ||
prev.active !== next.active ||
prev.unread !== next.unread ||
@@ -115,7 +118,7 @@ export function railFolderPropsEqual(prev: RailFolderProps, next: RailFolderProp
prev.preview !== next.preview ||
!!prev.onUngroup !== !!next.onUngroup ||
!!prev.registerItem !== !!next.registerItem ||
- !!prev.onMove !== !!next.onMove ||
+ prev.dragDescriptionId !== next.dragDescriptionId ||
prev.folderServers.length !== next.folderServers.length
) return false
return prev.folderServers.every((server, index) => {
diff --git a/src/web/src/components/community/shell/server-rail-model.test.ts b/src/web/src/components/community/shell/server-rail-model.test.ts
index 559690776..d81045e62 100644
--- a/src/web/src/components/community/shell/server-rail-model.test.ts
+++ b/src/web/src/components/community/shell/server-rail-model.test.ts
@@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest"
import {
commitRailInstruction,
planRailPersistence,
+ railInstructionIsAvailable,
+ railOperationAvailability,
railStateFromData,
railStateErrors,
visibleTopLevelServers,
@@ -125,4 +127,44 @@ describe("server rail normalized reducer", () => {
invalid.folders.two.push("c")
expect(railStateErrors(invalid)).toContain("server c belongs to multiple folders")
})
+
+ it("derives exact state-aware operations for every sensor", () => {
+ expect(railOperationAvailability(
+ fixture(),
+ { kind: "folder", id: "one" },
+ { kind: "folder", id: "two" },
+ )).toEqual({ "reorder-before": false, "reorder-after": true, combine: false })
+ expect(railOperationAvailability(
+ fixture(),
+ { kind: "server", id: "c" },
+ { kind: "folder", id: "one" },
+ )).toEqual({ "reorder-before": false, "reorder-after": false, combine: false })
+ expect(railOperationAvailability(
+ fixture(),
+ { kind: "server", id: "a" },
+ { kind: "folder", id: "one" },
+ )).toEqual({ "reorder-before": false, "reorder-after": false, combine: true })
+ expect(railInstructionIsAvailable(fixture(), {
+ operation: "combine",
+ source: { kind: "server", id: "a" },
+ target: { kind: "server", id: "b" },
+ })).toBe(true)
+ expect(railInstructionIsAvailable(fixture(), {
+ operation: "reorder-before",
+ source: { kind: "server", id: "a" },
+ target: { kind: "server", id: "b" },
+ })).toBe(false)
+ })
+
+ it("allocates a collision-free temporary id for server-combine previews", () => {
+ const state = fixture()
+ state.folderOrder.push("__rail_preview_folder__")
+ state.folders.__rail_preview_folder__ = ["f"]
+
+ expect(railInstructionIsAvailable(state, {
+ operation: "combine",
+ source: { kind: "server", id: "a" },
+ target: { kind: "server", id: "b" },
+ })).toBe(true)
+ })
})
diff --git a/src/web/src/components/community/shell/server-rail-move-menu.tsx b/src/web/src/components/community/shell/server-rail-move-menu.tsx
deleted file mode 100644
index 71717edd2..000000000
--- a/src/web/src/components/community/shell/server-rail-move-menu.tsx
+++ /dev/null
@@ -1,192 +0,0 @@
-"use client"
-
-import { useEffect, useMemo, useState } from "react"
-import { MAX_SERVER_RAIL_FOLDERS } from "@alook/shared"
-import { Button } from "@/components/ui/button"
-import { tid } from "@/lib/community/testids"
-import {
- Sheet,
- SheetBody,
- SheetContent,
- SheetDescription,
- SheetFooter,
- SheetHeader,
- SheetTitle,
-} from "@/components/ui/sheet"
-import {
- folderForServer,
- visibleTopLevelServers,
- type RailEntity,
- type RailInstruction,
- type RailState,
-} from "@/lib/community/server-rail-model"
-
-type Destination = "rail" | "new" | `folder:${string}` | "folders"
-
-export function ServerRailMoveMenu({
- source,
- state,
- serverNames,
- folderNames,
- onClose,
- onMove,
-}: {
- source: RailEntity | null
- state: RailState
- serverNames: ReadonlyMap<string, string>
- folderNames: ReadonlyMap<string, string>
- onClose: () => void
- onMove: (instruction: RailInstruction) => void
-}) {
- const sourceFolder = source?.kind === "server" ? folderForServer(state, source.id) : null
- const [destination, setDestination] = useState<Destination>("rail")
- const [targetId, setTargetId] = useState("")
- const [placement, setPlacement] = useState<"before" | "after" | "inside">("after")
-
- const targets = useMemo(() => {
- if (!source) return []
- if (source.kind === "folder") {
- return state.folderOrder.filter((folderId) => folderId !== source.id)
- }
- if (destination === "rail" || destination === "new") {
- return visibleTopLevelServers(state).filter((serverId) => serverId !== source.id)
- }
- if (destination.startsWith("folder:")) {
- return (state.folders[destination.slice("folder:".length)] ?? [])
- .filter((serverId) => serverId !== source.id)
- }
- return []
- }, [destination, source, state])
-
- useEffect(() => {
- if (!source) return
- const initialDestination: Destination = source.kind === "folder"
- ? "folders"
- : sourceFolder
- ? `folder:${sourceFolder}`
- : "rail"
- setDestination(initialDestination)
- setPlacement("after")
- }, [source, sourceFolder])
-
- useEffect(() => {
- setTargetId(targets[0] ?? "")
- }, [targets])
-
- const submit = () => {
- if (!source || !targetId) return
- const target: RailEntity = source.kind === "folder"
- ? { kind: "folder", id: targetId }
- : destination.startsWith("folder:") && placement === "inside"
- ? { kind: "folder", id: destination.slice("folder:".length) }
- : { kind: "server", id: targetId }
- const operation = destination === "new" || placement === "inside"
- ? "combine"
- : placement === "before"
- ? "reorder-before"
- : "reorder-after"
- onMove({
- operation,
- source,
- target,
- ...(destination === "new" ? { newFolderId: `temp_${crypto.randomUUID()}` } : {}),
- })
- }
-
- return (
- <Sheet open={!!source} onOpenChange={(open) => { if (!open) onClose() }}>
- <SheetContent side="bottom" className="max-h-[min(32rem,80dvh)] rounded-t-2xl" showCloseButton>
- <SheetHeader>
- <SheetTitle>Move {source?.kind === "folder" ? "group" : "server"}</SheetTitle>
- <SheetDescription>Choose a destination, then its exact position.</SheetDescription>
- </SheetHeader>
- <SheetBody className="space-y-4">
- <label className="grid gap-1.5 text-sm font-medium">
- <span>Destination</span>
- <select
- data-testid={tid.serverRailMoveDestination}
- value={destination}
- onChange={(event) => {
- setDestination(event.target.value as Destination)
- setPlacement("after")
- }}
- className="h-10 rounded-lg border border-input bg-card px-3 text-card-foreground outline-none focus:ring-2 focus:ring-ring"
- >
- {source?.kind === "folder" ? (
- <option value="folders">Group order</option>
- ) : (
- <>
- <option value="rail">Server rail</option>
- {state.folderOrder.map((folderId) => (
- <option key={folderId} value={`folder:${folderId}`}>
- {folderNames.get(folderId) ?? "Group"}
- </option>
- ))}
- {!sourceFolder && state.folderOrder.length < MAX_SERVER_RAIL_FOLDERS && (
- <option value="new">New group</option>
- )}
- </>
- )}
- </select>
- </label>
- <label className="grid gap-1.5 text-sm font-medium">
- <span>Position</span>
- <select
- data-testid={tid.serverRailMoveTarget}
- value={targetId}
- onChange={(event) => setTargetId(event.target.value)}
- className="h-10 rounded-lg border border-input bg-card px-3 text-card-foreground outline-none focus:ring-2 focus:ring-ring"
- >
- {targets.map((id) => (
- <option key={id} value={id}>
- {source?.kind === "folder"
- ? folderNames.get(id) ?? "Group"
- : serverNames.get(id) ?? "Server"}
- </option>
- ))}
- </select>
- </label>
- {destination !== "new" && targets.length > 0 && (
- <div className="grid grid-cols-2 gap-2" role="group" aria-label="Placement">
- <Button
- type="button"
- variant={placement === "before" ? "default" : "outline"}
- onClick={() => setPlacement("before")}
- >
- Before
- </Button>
- <Button
- type="button"
- variant={placement === "after" ? "default" : "outline"}
- onClick={() => setPlacement("after")}
- >
- After
- </Button>
- {source?.kind === "server" && destination.startsWith("folder:") && (
- <Button
- type="button"
- variant={placement === "inside" ? "default" : "outline"}
- className="col-span-2"
- onClick={() => setPlacement("inside")}
- >
- Inside group
- </Button>
- )}
- </div>
- )}
- </SheetBody>
- <SheetFooter>
- <Button type="button" variant="outline" onClick={onClose}>Cancel</Button>
- <Button
- type="button"
- data-testid={tid.serverRailMoveConfirm}
- disabled={!targetId}
- onClick={submit}
- >
- Move
- </Button>
- </SheetFooter>
- </SheetContent>
- </Sheet>
- )
-}
diff --git a/src/web/src/components/community/shell/server-rail-pdd-contract.test.ts b/src/web/src/components/community/shell/server-rail-pdd-contract.test.ts
index 40573f6a4..2c540a015 100644
--- a/src/web/src/components/community/shell/server-rail-pdd-contract.test.ts
+++ b/src/web/src/components/community/shell/server-rail-pdd-contract.test.ts
@@ -29,15 +29,47 @@ describe("server rail PDD component contract", () => {
expect(adapter).toContain("}, 500)")
})
- it("keeps Move behind contextual actions and uses a compact two-step sheet", () => {
+ it("uses drag as the only spatial model and retains only Ungroup", () => {
const server = read("./sortable-server.tsx")
const folder = read("./rail-folder.tsx")
- const move = read("./server-rail-move-menu.tsx")
- expect(server).toContain("Move…")
- expect(folder).toContain("Move…")
- expect(move).toContain("Choose a destination, then its exact position.")
- expect(move).toContain('side="bottom"')
- expect(move).toContain("tid.serverRailMoveDestination")
- expect(move).not.toContain("fixed right-")
+ const rail = read("./server-rail.tsx")
+ expect(server).not.toContain("Move…")
+ expect(server).not.toContain("Create group")
+ expect(folder).not.toContain("Move…")
+ expect(folder).toContain("Ungroup")
+ expect(rail).not.toContain("ServerRailMoveMenu")
+ })
+
+ it("separates touch scroll intent and exposes keyboard drag instructions", () => {
+ const adapter = read("./use-server-rail-pdd.ts")
+ const rail = read("./server-rail.tsx")
+ const server = read("./sortable-server.tsx")
+ const folder = read("./rail-folder.tsx")
+ expect(adapter).toContain("SERVER_RAIL_TOUCH_HOLD_MS = 450")
+ expect(adapter).toContain("SERVER_RAIL_TOUCH_DRIFT_PX = 10")
+ const touchStart = adapter.slice(
+ adapter.indexOf("const onTouchStart"),
+ adapter.indexOf("const onTouchMove"),
+ )
+ const preArmScroll = adapter.slice(
+ adapter.indexOf('if (exactIntent === "scroll")'),
+ adapter.indexOf('if (exactIntent === "wait")'),
+ )
+ expect(touchStart).not.toContain("preventDefault")
+ expect(preArmScroll).toContain("clearTouch()")
+ expect(preArmScroll).not.toContain("preventDefault")
+ expect(adapter).toContain('addEventListener("touchstart", onTouchStart, { passive: true })')
+ expect(adapter).toContain("event.preventDefault()")
+ expect(adapter).toContain('addEventListener("touchmove", onTouchMove, { passive: false })')
+ expect(adapter).toContain('addEventListener("touchend", onTouchEnd, { passive: false })')
+ expect(adapter).not.toContain("scroll.scrollTop -=")
+ expect(adapter).not.toContain("pending.scrolling")
+ expect(adapter).toContain('addEventListener("scroll", cancelPendingTouchForNativeScroll')
+ expect(server).not.toContain("touch-none")
+ expect(folder).not.toContain("touch-none")
+ expect(adapter).toContain("requestAnimationFrame(runTouchFrame)")
+ expect(adapter).not.toContain("matchMedia")
+ expect(rail).toContain("Press Space to pick up a server or group")
+ expect(rail).toContain("onAnnounce: announce")
})
})
diff --git a/src/web/src/components/community/shell/server-rail.pending.test.ts b/src/web/src/components/community/shell/server-rail.pending.test.ts
index 58f7a33c1..55e96030f 100644
--- a/src/web/src/components/community/shell/server-rail.pending.test.ts
+++ b/src/web/src/components/community/shell/server-rail.pending.test.ts
@@ -33,7 +33,6 @@ vi.mock("./rail-folder", () => ({
}))
vi.mock("./rail-icon", () => ({ RailIcon: () => null }))
vi.mock("./animated-alook-logo", () => ({ AnimatedAlookLogo: () => null }))
-vi.mock("./server-rail-move-menu", () => ({ ServerRailMoveMenu: () => null }))
vi.mock("../settings/create-server-dialog", () => ({ CreateServerDialog: () => null }))
vi.mock("@/components/ui/skeleton", () => ({
Skeleton: (props: Record<string, unknown>) => createElement("skeleton", props),
@@ -51,6 +50,7 @@ vi.mock("@/lib/community-onboarding", () => ({
const servers = [
{ id: "a", name: "A", initial: "A", active: true, unread: false, mentions: 0 },
{ id: "b", name: "B", initial: "B", active: false, unread: false, mentions: 0 },
+ { id: "c", name: "C", initial: "C", active: false, unread: false, mentions: 0 },
]
const folders = [{
id: "one",
@@ -60,13 +60,17 @@ const folders = [{
}]
const animationFrames: FrameRequestCallback[] = []
-function renderRail() {
- return TestRenderer.create(createElement(ServerRail, {
+function railElement(currentFolders = folders) {
+ return createElement(ServerRail, {
servers,
- folders,
+ folders: currentFolders,
view: "server",
onHome: vi.fn(),
- }))
+ })
+}
+
+function renderRail() {
+ return TestRenderer.create(railElement())
}
type MutationCallbacks = {
@@ -165,21 +169,25 @@ describe("ServerRail one-in-flight structural guard", () => {
expect(child?.props.server.unread).toBe(true)
})
- it.each(["create-first", "ungroup-first"] as const)(
- "allows one PATCH when stale create and ungroup callbacks race: %s",
+ it.each(["drop-first", "ungroup-first"] as const)(
+ "allows one PATCH when drag-drop and ungroup callbacks race: %s",
async (order) => {
let renderer!: TestRenderer.ReactTestRenderer
await act(async () => { renderer = renderRail() })
- const create = renderer.root.findAllByType("sortable-server")[0]!.props.onCreateFolder
const ungroup = renderer.root.findByType("rail-folder").props.onUngroup
+ const instruction = {
+ operation: "reorder-after",
+ source: { kind: "server", id: "a" },
+ target: { kind: "server", id: "c" },
+ } satisfies RailInstruction
await act(async () => {
- if (order === "create-first") {
- create()
+ if (order === "drop-first") {
+ drop(instruction)
ungroup()
} else {
ungroup()
- create()
+ drop(instruction)
}
})
@@ -189,8 +197,8 @@ describe("ServerRail one-in-flight structural guard", () => {
const options = mocks.mutate.mock.calls[0]![1]
await act(async () => { options.onSettled() })
await act(async () => {
- if (order === "create-first") ungroup()
- else create()
+ if (order === "drop-first") ungroup()
+ else drop(instruction)
})
expect(mocks.mutate).toHaveBeenCalledTimes(2)
},
@@ -217,7 +225,7 @@ describe("ServerRail one-in-flight structural guard", () => {
})
it.each(["success", "error"] as const)(
- "returns Move focus only after the mutation settles: %s",
+ "returns drag source focus only after the mutation settles: %s",
async (outcome) => {
const focus = vi.fn()
mocks.querySelector.mockReturnValue({ focus })
@@ -244,20 +252,21 @@ describe("ServerRail one-in-flight structural guard", () => {
)
it.each(["success", "error"] as const)(
- "returns Create group focus to its source server after settle: %s",
+ "returns combine-created-group focus to its source server after settle: %s",
async (outcome) => {
const focus = vi.fn()
mocks.querySelector.mockReturnValue({ focus })
- let renderer!: TestRenderer.ReactTestRenderer
- await act(async () => { renderer = renderRail() })
- const create = renderer.root.findAllByType("sortable-server")
- .find((node) => node.props.server.id === "a")!.props.onCreateFolder
- await act(async () => create())
+ await act(async () => { renderRail() })
+ await act(async () => drop({
+ operation: "combine",
+ source: { kind: "server", id: "a" },
+ target: { kind: "server", id: "c" },
+ }))
const { args, callbacks } = latestMutation()
await act(async () => {
if (outcome === "success") {
- const clientId = args.commands[0]?.clientId
+ const clientId = args.commands.find((command) => command.kind === "create-folder")?.clientId
callbacks.onSuccess({ createdFolderIds: clientId ? { [clientId]: "created" } : {} })
} else {
callbacks.onError()
@@ -273,6 +282,77 @@ describe("ServerRail one-in-flight structural guard", () => {
},
)
+ it("preserves a user collapse while a created group id is reconciling", async () => {
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => { renderer = renderRail() })
+ await act(async () => drop({
+ operation: "combine",
+ source: { kind: "server", id: "a" },
+ target: { kind: "server", id: "c" },
+ }))
+ const { args, callbacks } = latestMutation()
+ const clientId = args.commands.find((command) => command.kind === "create-folder")?.clientId
+ expect(clientId).toBeDefined()
+ const optimisticFolder = renderer.root.findAllByType("rail-folder")
+ .find((folder) => folder.props.folderId === clientId)
+ expect(optimisticFolder?.props.open).toBe(true)
+
+ await act(async () => optimisticFolder?.props.onToggle())
+ expect(optimisticFolder?.props.open).toBe(false)
+ await act(async () => renderer.update(railElement([
+ ...folders,
+ {
+ id: "created",
+ name: "Group",
+ position: 1,
+ servers: [
+ { id: "a", name: "A", initial: "A" },
+ { id: "c", name: "C", initial: "C" },
+ ],
+ },
+ ])))
+ await act(async () => callbacks.onSuccess({
+ createdFolderIds: clientId ? { [clientId]: "created" } : {},
+ }))
+
+ const reconciledFolder = renderer.root.findAllByType("rail-folder")
+ .find((folder) => folder.props.folderId === "created")
+ expect(reconciledFolder?.props.open).toBe(false)
+ })
+
+ it("keeps a created group expanded when cache reconciliation replaces its id", async () => {
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => { renderer = renderRail() })
+ await act(async () => drop({
+ operation: "combine",
+ source: { kind: "server", id: "a" },
+ target: { kind: "server", id: "c" },
+ }))
+ const { args, callbacks } = latestMutation()
+ const clientId = args.commands.find((command) => command.kind === "create-folder")?.clientId
+ expect(clientId).toBeDefined()
+
+ await act(async () => renderer.update(railElement([
+ ...folders,
+ {
+ id: "created",
+ name: "Group",
+ position: 1,
+ servers: [
+ { id: "a", name: "A", initial: "A" },
+ { id: "c", name: "C", initial: "C" },
+ ],
+ },
+ ])))
+ await act(async () => callbacks.onSuccess({
+ createdFolderIds: clientId ? { [clientId]: "created" } : {},
+ }))
+
+ const reconciledFolder = renderer.root.findAllByType("rail-folder")
+ .find((folder) => folder.props.folderId === "created")
+ expect(reconciledFolder?.props.open).toBe(true)
+ })
+
it.each(["success", "error"] as const)(
"returns Ungroup focus after settle to a surviving entity: %s",
async (outcome) => {
diff --git a/src/web/src/components/community/shell/server-rail.tsx b/src/web/src/components/community/shell/server-rail.tsx
index 3b1b52025..bcfd0154c 100644
--- a/src/web/src/components/community/shell/server-rail.tsx
+++ b/src/web/src/components/community/shell/server-rail.tsx
@@ -2,7 +2,6 @@
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"
import { Plus } from "lucide-react"
-import { MAX_SERVER_RAIL_FOLDERS } from "@alook/shared"
import { announce, cleanup as cleanupLiveRegion } from "@atlaskit/pragmatic-drag-and-drop-live-region"
import { RailIcon } from "./rail-icon"
import { AnimatedAlookLogo } from "./animated-alook-logo"
@@ -12,7 +11,6 @@ import { Skeleton } from "@/components/ui/skeleton"
import { SortableServer } from "./sortable-server"
import { RailFolder } from "./rail-folder"
import { CreateServerDialog } from "../settings/create-server-dialog"
-import { ServerRailMoveMenu } from "./server-rail-move-menu"
import {
cloneRailState,
commitRailInstruction,
@@ -33,13 +31,20 @@ import {
isCommunityOnboardingStage,
} from "@/lib/community-onboarding"
-type MoveSheetState = { source: RailEntity; focusTarget: HTMLElement } | null
+const DRAG_INSTRUCTIONS_ID = "server-rail-drag-instructions"
function reconcileCreatedFolders(
state: RailState,
createdFolderIds: Record<string, string>,
+ explicitlyCollapsed: ReadonlySet<string>,
): RailState {
if (Object.keys(createdFolderIds).length === 0) return state
+ const expanded = new Set(state.expanded.map((id) => createdFolderIds[id] ?? id))
+ for (const [clientId, folderId] of Object.entries(createdFolderIds)) {
+ if (!explicitlyCollapsed.has(clientId) && !explicitlyCollapsed.has(folderId)) {
+ expanded.add(folderId)
+ }
+ }
return {
...state,
folderOrder: state.folderOrder.map((id) => createdFolderIds[id] ?? id),
@@ -47,10 +52,7 @@ function reconcileCreatedFolders(
createdFolderIds[id] ?? id,
serverIds,
])),
- expanded: [...new Set([
- ...state.expanded.map((id) => createdFolderIds[id] ?? id),
- ...Object.values(createdFolderIds),
- ])],
+ expanded: [...expanded],
}
}
@@ -92,12 +94,12 @@ export const ServerRail = memo(function ServerRail({
)
const [preview, setPreview] = useState<RailInstruction | null>(null)
const [dragSource, setDragSource] = useState<RailEntity | null>(null)
- const [moveSheet, setMoveSheet] = useState<MoveSheetState>(null)
const [createOpen, setCreateOpen] = useState(false)
const scrollRef = useRef<HTMLDivElement>(null)
const dragSnapshotRef = useRef<RailState | null>(null)
const stateRef = useRef(state)
const mutationPendingRef = useRef(false)
+ const collapsedPendingFolderIdsRef = useRef(new Set<string>())
const railMutation = useServerRailCommit()
const serverIdentityOrder = servers.map((server) => server.id).join("\0")
const serverIds = useMemo(
@@ -115,6 +117,7 @@ export const ServerRail = memo(function ServerRail({
}, [])
const releaseMutation = useCallback(() => {
mutationPendingRef.current = false
+ collapsedPendingFolderIdsRef.current.clear()
}, [])
useEffect(() => {
@@ -214,7 +217,11 @@ export const ServerRail = memo(function ServerRail({
{ before, after: result.state, commands: result.commands },
{
onSuccess: (response) => {
- setState((current) => reconcileCreatedFolders(current, response.createdFolderIds))
+ setState((current) => reconcileCreatedFolders(
+ current,
+ response.createdFolderIds,
+ collapsedPendingFolderIdsRef.current,
+ ))
announce(label)
},
onError: () => {
@@ -258,40 +265,15 @@ export const ServerRail = memo(function ServerRail({
)
}, [claimMutation, focusEntity, railMutation, releaseMutation])
- const createSingleServerFolder = useCallback((serverId: string) => {
- const before = cloneRailState(stateRef.current)
- if (before.folderOrder.length >= MAX_SERVER_RAIL_FOLDERS) return
- const after = cloneRailState(before)
- const clientId = `temp_${crypto.randomUUID()}`
- after.folderOrder.push(clientId)
- after.folders[clientId] = [serverId]
- after.expanded.push(clientId)
- const commands = planRailPersistence(before, after)
- if (!claimMutation()) return
- setState(after)
- railMutation.mutate(
- { before, after, commands },
- {
- onSuccess: (response) => {
- setState((current) => reconcileCreatedFolders(current, response.createdFolderIds))
- announce("Group created")
- },
- onError: () => {
- setState(before)
- announce("Creating group failed and was rolled back")
- },
- onSettled: () => {
- releaseMutation()
- focusEntity({ kind: "server", id: serverId }, { afterReconcile: true })
- },
- },
- )
- }, [claimMutation, focusEntity, railMutation, releaseMutation])
-
const { registerItem } = useServerRailPdd({
scrollRef,
+ getState: () => stateRef.current,
+ canStart: () => !mutationPendingRef.current,
+ getEntityLabel: (entity) => entity.kind === "server"
+ ? serverNames.get(entity.id) ?? "Server"
+ : folderNames.get(entity.id) ?? "Group",
onDragStart: (source) => {
- dragSnapshotRef.current = cloneRailState(state)
+ dragSnapshotRef.current = cloneRailState(stateRef.current)
setDragSource(source)
},
onPreview: setPreview,
@@ -310,6 +292,7 @@ export const ServerRail = memo(function ServerRail({
? current
: { ...current, expanded: [...current.expanded, folderId] })
},
+ onAnnounce: announce,
})
const previewFor = (entity: RailEntity) => preview?.target.kind === entity.kind
@@ -324,6 +307,10 @@ export const ServerRail = memo(function ServerRail({
return (
<nav aria-label="Server navigation" className="flex min-h-0 w-14 shrink-0 flex-col items-center overflow-hidden pt-2">
+ <span id={DRAG_INSTRUCTIONS_ID} className="sr-only">
+ Press Space to pick up a server or group. Use the arrow keys to choose a position,
+ Space or Enter to drop, and Escape to cancel.
+ </span>
<div className="flex w-full shrink-0 flex-col items-center gap-2">
<Tooltip>
<TooltipTrigger render={<div className="group relative flex w-full justify-center" />}>
@@ -369,11 +356,10 @@ export const ServerRail = memo(function ServerRail({
onLeave={() => onLeaveServer?.(serverId)}
onOpenSettings={() => onOpenSettings?.(serverId)}
onOpenInvitePopover={onOpenInvitePopover ? () => onOpenInvitePopover(serverId) : undefined}
- onCreateFolder={state.folderOrder.length < MAX_SERVER_RAIL_FOLDERS ? () => createSingleServerFolder(serverId) : undefined}
dragging={dragging({ kind: "server", id: serverId })}
preview={previewFor({ kind: "server", id: serverId })}
registerItem={registerItem}
- onMove={(source, focusTarget) => setMoveSheet({ source, focusTarget })}
+ dragDescriptionId={DRAG_INSTRUCTIONS_ID}
/>
)
})}
@@ -385,21 +371,29 @@ export const ServerRail = memo(function ServerRail({
<div key={folderId} className="flex w-full flex-col items-center gap-2">
<RailFolder
folderId={folderId}
+ name={folderNames.get(folderId) ?? "Group"}
open={open}
active={!open && serversInFolder.some((server) => server.id === activeId)}
unread={!open && serversInFolder.some((server) => server.unread)}
- onToggle={() => setState((current) => ({
- ...current,
- expanded: current.expanded.includes(folderId)
- ? current.expanded.filter((id) => id !== folderId)
- : [...current.expanded, folderId],
- }))}
+ onToggle={() => setState((current) => {
+ const collapsing = current.expanded.includes(folderId)
+ if (mutationPendingRef.current) {
+ if (collapsing) collapsedPendingFolderIdsRef.current.add(folderId)
+ else collapsedPendingFolderIdsRef.current.delete(folderId)
+ }
+ return {
+ ...current,
+ expanded: collapsing
+ ? current.expanded.filter((id) => id !== folderId)
+ : [...current.expanded, folderId],
+ }
+ })}
folderServers={serversInFolder}
onUngroup={() => ungroupFolder(folderId)}
dragging={dragging({ kind: "folder", id: folderId })}
preview={previewFor({ kind: "folder", id: folderId })}
registerItem={registerItem}
- onMove={(source, focusTarget) => setMoveSheet({ source, focusTarget })}
+ dragDescriptionId={DRAG_INSTRUCTIONS_ID}
/>
{open && serversInFolder.length > 0 && (
<div className="relative flex w-full flex-col items-center gap-2 py-1">
@@ -417,7 +411,7 @@ export const ServerRail = memo(function ServerRail({
dragging={dragging({ kind: "server", id: server.id })}
preview={previewFor({ kind: "server", id: server.id })}
registerItem={registerItem}
- onMove={(source, focusTarget) => setMoveSheet({ source, focusTarget })}
+ dragDescriptionId={DRAG_INSTRUCTIONS_ID}
/>
))}
</div>
@@ -445,19 +439,6 @@ export const ServerRail = memo(function ServerRail({
/>
</div>
- <ServerRailMoveMenu
- source={moveSheet?.source ?? null}
- state={state}
- serverNames={serverNames}
- folderNames={folderNames}
- onClose={() => setMoveSheet(null)}
- onMove={(instruction) => {
- const focusTarget = moveSheet?.focusTarget
- setMoveSheet(null)
- applyInstruction(instruction, cloneRailState(state), focusTarget)
- }}
- />
-
{createOpen && (
<CreateServerDialog
onClose={() => setCreateOpen(false)}
diff --git a/src/web/src/components/community/shell/sortable-server.focus.test.ts b/src/web/src/components/community/shell/sortable-server.focus.test.ts
index 47f01e563..97cdeadfa 100644
--- a/src/web/src/components/community/shell/sortable-server.focus.test.ts
+++ b/src/web/src/components/community/shell/sortable-server.focus.test.ts
@@ -31,12 +31,13 @@ const server = {
mentions: 0,
}
-function renderServer() {
+function renderServer(active = false) {
const buttonNodes: Array<{ focus: ReturnType<typeof vi.fn> }> = []
const renderer = TestRenderer.create(createElement(SortableServer, {
server,
+ active,
onClick: vi.fn(),
- onMove: vi.fn(),
+ dragDescriptionId: "rail-help",
}), {
createNodeMock: (element) => {
if (element.type !== "button") return {}
@@ -73,4 +74,28 @@ describe("SortableServer lazy menu focus", () => {
expect(result.renderer.root.findAllByType("context-menu-trigger")).toHaveLength(1)
expect(result.buttonNodes.every((node) => node.focus.mock.calls.length === 0)).toBe(true)
})
+
+ it("exposes keyboard drag help without positional menu shortcuts", async () => {
+ let result!: ReturnType<typeof renderServer>
+ await act(async () => { result = renderServer() })
+ const button = result.renderer.root.findByType("button")
+ expect(button.props["aria-describedby"]).toBe("rail-help")
+ expect(button.props["aria-keyshortcuts"]).toContain("Space")
+ await act(async () => result.activationRoot().props.onPointerEnter())
+ const menuText = JSON.stringify(result.renderer.toJSON())
+ expect(menuText).not.toContain("Move…")
+ expect(menuText).not.toContain("Create group")
+ })
+
+ it("keeps active and inactive cursor state on the actual button", async () => {
+ let active!: ReturnType<typeof renderServer>
+ let inactive!: ReturnType<typeof renderServer>
+ await act(async () => {
+ active = renderServer(true)
+ inactive = renderServer(false)
+ })
+
+ expect(active.renderer.root.findByType("button").props.className).toContain("cursor-default")
+ expect(inactive.renderer.root.findByType("button").props.className).toContain("cursor-pointer")
+ })
})
diff --git a/src/web/src/components/community/shell/sortable-server.tsx b/src/web/src/components/community/shell/sortable-server.tsx
index 01f70148e..030d82b30 100644
--- a/src/web/src/components/community/shell/sortable-server.tsx
+++ b/src/web/src/components/community/shell/sortable-server.tsx
@@ -1,6 +1,6 @@
"use client";
-import { memo, useEffect, useLayoutEffect, useRef, useState } from "react";
+import { memo, useLayoutEffect, useRef, useState } from "react";
import {
ContextMenu,
ContextMenuTrigger,
@@ -29,7 +29,6 @@ type SortableServerProps = {
onLeave?: () => void;
onOpenSettings?: () => void;
onOpenInvitePopover?: () => void;
- onCreateFolder?: () => void;
inFolder?: boolean;
dragging?: boolean;
preview?: RailOperation | null;
@@ -38,7 +37,7 @@ type SortableServerProps = {
element: HTMLElement,
dragHandle: HTMLElement,
) => () => void;
- onMove?: (source: RailEntity, focusTarget: HTMLElement) => void;
+ dragDescriptionId?: string;
};
function SortableServerImpl({
@@ -49,12 +48,11 @@ function SortableServerImpl({
onLeave,
onOpenSettings,
onOpenInvitePopover,
- onCreateFolder,
inFolder,
dragging: isDragActive,
preview,
registerItem,
- onMove,
+ dragDescriptionId,
}: SortableServerProps) {
const rootRef = useRef<HTMLDivElement>(null)
const buttonRef = useRef<HTMLButtonElement>(null)
@@ -70,7 +68,7 @@ function SortableServerImpl({
// and a right-click is always preceded by a pointerenter so the menu is
// mounted before it's invoked).
const [activated, setActivated] = useState(false);
- useEffect(() => {
+ useLayoutEffect(() => {
if (!registerItem || !rootRef.current || !buttonRef.current) return
return registerItem(
{ kind: "server", id: server.id },
@@ -123,33 +121,44 @@ function SortableServerImpl({
<button
ref={buttonRef}
data-testid={tid.serverIcon(server.id)}
+ data-dragging={isDragActive || undefined}
+ data-rail-preview={preview ?? undefined}
+ aria-label={server.name}
+ aria-describedby={dragDescriptionId}
+ aria-keyshortcuts="Space ArrowUp ArrowDown ArrowLeft ArrowRight Escape"
onClick={active ? undefined : onClick}
className={[
- "relative grid size-10 touch-manipulation place-items-center overflow-hidden font-brand text-xl font-bold transition-all duration-150 active:cursor-grabbing",
+ "group/server absolute left-1/2 top-1/2 z-1 grid size-11 -translate-x-1/2 -translate-y-1/2 place-items-center focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none active:cursor-grabbing",
+ active ? "cursor-default" : "cursor-pointer",
+ ].join(" ")}
+ >
+ <span className={[
+ "pointer-events-none relative grid size-10 place-items-center overflow-hidden font-brand text-xl font-bold transition-all duration-150",
active
? "cursor-default rounded-xl"
- : "cursor-pointer rounded-[18px] hover:rounded-xl",
+ : "cursor-pointer rounded-[18px] group-hover/server:rounded-xl",
server.icon
? active
? "bg-primary text-primary-foreground"
- : "bg-card hover:bg-primary hover:text-primary-foreground"
- : "text-white [text-shadow:0_1px_2px_rgb(0_0_0/0.35)] hover:brightness-110",
+ : "bg-card group-hover/server:bg-primary group-hover/server:text-primary-foreground"
+ : "text-white [text-shadow:0_1px_2px_rgb(0_0_0/0.35)] group-hover/server:brightness-110",
].join(" ")}
- >
- {server.icon ? (
- <img
- src={server.icon}
- alt={server.name}
- className="size-full object-cover"
- />
- ) : (
- <>
- <SeededBackdrop seed={server.id} />
- <span className="relative -translate-x-0.5 [-webkit-text-stroke:0.5px_currentColor]">
- {server.initial}
- </span>
- </>
- )}
+ >
+ {server.icon ? (
+ <img
+ src={server.icon}
+ alt={server.name}
+ className="size-full object-cover"
+ />
+ ) : (
+ <>
+ <SeededBackdrop seed={server.id} />
+ <span className="relative -translate-x-0.5 [-webkit-text-stroke:0.5px_currentColor]">
+ {server.initial}
+ </span>
+ </>
+ )}
+ </span>
</button>
{server.mentions > 0 && (
<span
@@ -178,18 +187,6 @@ function SortableServerImpl({
Invite to Server
</ContextMenuItem>
)}
- {!inFolder && onCreateFolder && (
- <ContextMenuItem onClick={onCreateFolder}>
- Create group
- </ContextMenuItem>
- )}
- {onMove && (
- <ContextMenuItem onClick={() => {
- if (buttonRef.current) onMove({ kind: "server", id: server.id }, buttonRef.current)
- }}>
- Move…
- </ContextMenuItem>
- )}
<ContextMenuItem onClick={onOpenSettings} data-testid={tid.serverSettingsOpen}>
Server settings
</ContextMenuItem>
@@ -271,8 +268,7 @@ export function serverPropsEqual(prev: SortableServerProps, next: SortableServer
!!prev.onLeave === !!next.onLeave &&
!!prev.onOpenSettings === !!next.onOpenSettings &&
!!prev.onOpenInvitePopover === !!next.onOpenInvitePopover &&
- !!prev.onCreateFolder === !!next.onCreateFolder &&
- !!prev.onMove === !!next.onMove &&
+ prev.dragDescriptionId === next.dragDescriptionId &&
!!prev.onPrefetch === !!next.onPrefetch
);
}
diff --git a/src/web/src/components/community/shell/use-server-rail-pdd.behavior.test.ts b/src/web/src/components/community/shell/use-server-rail-pdd.behavior.test.ts
new file mode 100644
index 000000000..1bd5cf6cd
--- /dev/null
+++ b/src/web/src/components/community/shell/use-server-rail-pdd.behavior.test.ts
@@ -0,0 +1,616 @@
+import { createElement, type RefObject } from "react"
+import TestRenderer, { act, type ReactTestRenderer } from "react-test-renderer"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+
+const adapters = vi.hoisted(() => ({
+ draggables: [] as unknown[],
+ targets: [] as unknown[],
+ monitor: null as unknown,
+ autoScroll: null as unknown,
+ cleanupDraggable: vi.fn(),
+ cleanupTarget: vi.fn(),
+ cleanupMonitor: vi.fn(),
+ cleanupAutoScroll: vi.fn(),
+}))
+
+vi.mock("@atlaskit/pragmatic-drag-and-drop/adapter/element-adapter", () => ({
+ draggable: (options: unknown) => {
+ adapters.draggables.push(options)
+ return adapters.cleanupDraggable
+ },
+ dropTargetForElements: (options: unknown) => {
+ adapters.targets.push(options)
+ return adapters.cleanupTarget
+ },
+ monitorForElements: (options: unknown) => {
+ adapters.monitor = options
+ return adapters.cleanupMonitor
+ },
+}))
+
+vi.mock("@atlaskit/pragmatic-drag-and-drop-auto-scroll/element", () => ({
+ autoScrollForElements: (options: unknown) => {
+ adapters.autoScroll = options
+ return adapters.cleanupAutoScroll
+ },
+}))
+
+import type { RailEntity, RailState } from "@/lib/community/server-rail-model"
+import {
+ SERVER_RAIL_TOUCH_HOLD_MS,
+ useServerRailPdd,
+} from "./use-server-rail-pdd"
+
+type TestEvent = {
+ type: string
+ defaultPrevented: boolean
+ propagationStopped: boolean
+ preventDefault: () => void
+ stopPropagation: () => void
+ [key: string]: unknown
+}
+
+function testEvent(type: string, fields: Record<string, unknown> = {}): TestEvent {
+ return {
+ type,
+ defaultPrevented: false,
+ propagationStopped: false,
+ preventDefault() { this.defaultPrevented = true },
+ stopPropagation() { this.propagationStopped = true },
+ ...fields,
+ }
+}
+
+class FakeEventTarget {
+ private readonly listeners = new Map<string, Set<(event: TestEvent) => void>>()
+
+ addEventListener(type: string, listener: (event: TestEvent) => void) {
+ const listeners = this.listeners.get(type) ?? new Set()
+ listeners.add(listener)
+ this.listeners.set(type, listeners)
+ }
+
+ removeEventListener(type: string, listener: (event: TestEvent) => void) {
+ this.listeners.get(type)?.delete(listener)
+ }
+
+ dispatch(type: string, event = testEvent(type)): TestEvent {
+ for (const listener of this.listeners.get(type) ?? []) listener(event)
+ return event
+ }
+
+ dispatchEvent(event: TestEvent): boolean {
+ this.dispatch(event.type, event)
+ return !event.defaultPrevented
+ }
+}
+
+class FakeMouseEvent implements TestEvent {
+ [key: string]: unknown
+ readonly type: string
+ readonly clientX: number
+ readonly clientY: number
+ defaultPrevented = false
+ propagationStopped = false
+
+ constructor(type: string, init: { clientX?: number; clientY?: number } = {}) {
+ this.type = type
+ this.clientX = init.clientX ?? 0
+ this.clientY = init.clientY ?? 0
+ }
+
+ preventDefault() { this.defaultPrevented = true }
+ stopPropagation() { this.propagationStopped = true }
+}
+
+type Rect = { top: number; bottom: number; left: number; right: number; height: number; width: number }
+
+function rect(top: number, bottom: number, left = 0, right = 40): Rect {
+ return { top, bottom, left, right, height: bottom - top, width: right - left }
+}
+
+class FakeElement extends FakeEventTarget {
+ scrollTop = 0
+ isConnected = true
+ clickCount = 0
+ lastClickEvent: FakeMouseEvent | null = null
+ readonly focus = vi.fn()
+
+ constructor(public bounds: Rect) {
+ super()
+ }
+
+ getBoundingClientRect() { return this.bounds }
+
+ click() {
+ this.clickCount += 1
+ this.lastClickEvent = new FakeMouseEvent("click")
+ this.dispatchEvent(this.lastClickEvent)
+ }
+}
+
+class FakeDocument extends FakeEventTarget {
+ visibilityState: "visible" | "hidden" = "visible"
+ points: FakeElement[] = []
+ readonly documentElement = { style: { userSelect: "text" } }
+ readonly removeAllRanges = vi.fn()
+
+ elementsFromPoint() { return this.points }
+ getSelection() { return { removeAllRanges: this.removeAllRanges } }
+}
+
+type HookOptions = Parameters<typeof useServerRailPdd>[0]
+type HookApi = ReturnType<typeof useServerRailPdd>
+
+type DraggableOptions = {
+ canDrag: () => boolean
+ getInitialData: () => Record<string, unknown>
+}
+
+type TargetOptions = {
+ canDrop: (args: { source: { data: Record<string, unknown> } }) => boolean
+ getIsSticky: () => boolean
+ getData: (args: {
+ input: { clientX: number; clientY: number }
+ element: HTMLElement
+ source: { data: Record<string, unknown> }
+ }) => Record<string, unknown>
+}
+
+type MonitorOptions = {
+ canMonitor: (args: { source: { data: Record<string, unknown> } }) => boolean
+ onDragStart: (args: { source: { data: Record<string, unknown> } }) => void
+ onDrag: (args: MonitorLocation) => void
+ onDropTargetChange: (args: MonitorLocation) => void
+ onDrop: (args: MonitorLocation) => void
+}
+
+type MonitorLocation = {
+ source: { data: Record<string, unknown> }
+ location: { current: { dropTargets: Array<{ data: Record<string, unknown> }> } }
+}
+
+type AutoScrollOptions = {
+ getAllowedAxis: () => string
+ getConfiguration: () => { maxScrollSpeed: string }
+}
+
+const renderers: ReactTestRenderer[] = []
+let fakeDocument: FakeDocument
+let fakeWindow: FakeEventTarget
+let animationFrames: Map<number, FrameRequestCallback>
+let nextFrameId: number
+
+function stateFixture(): RailState {
+ return {
+ serverOrder: ["a", "b", "c", "d"],
+ folderOrder: ["f", "g"],
+ folders: { f: ["c"], g: ["d"] },
+ expanded: [],
+ }
+}
+
+function Capture({ options, onResult }: { options: HookOptions; onResult: (api: HookApi) => void }) {
+ onResult(useServerRailPdd(options))
+ return null
+}
+
+async function renderHook(overrides: Partial<HookOptions> = {}) {
+ const scroll = new FakeElement(rect(0, 300, 0, 56))
+ const callbacks = {
+ getState: vi.fn(() => stateFixture()),
+ canStart: vi.fn(() => true),
+ getEntityLabel: vi.fn((entity: RailEntity) => entity.id.toUpperCase()),
+ onDragStart: vi.fn(),
+ onPreview: vi.fn(),
+ onDrop: vi.fn(),
+ onCancel: vi.fn(),
+ onHoverExpand: vi.fn(),
+ onAnnounce: vi.fn(),
+ }
+ let options: HookOptions = {
+ scrollRef: { current: scroll as unknown as HTMLElement },
+ ...callbacks,
+ ...overrides,
+ }
+ let current!: HookApi
+ let renderer!: ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(Capture, {
+ options,
+ onResult: (api) => { current = api },
+ }))
+ })
+ renderers.push(renderer)
+ return {
+ callbacks,
+ scroll,
+ get current() { return current },
+ async rerender(next: Partial<HookOptions>) {
+ options = { ...options, ...next }
+ await act(async () => renderer.update(createElement(Capture, {
+ options,
+ onResult: (api) => { current = api },
+ })))
+ },
+ }
+}
+
+function register(
+ api: HookApi,
+ entity: RailEntity,
+ bounds: Rect,
+) {
+ const element = new FakeElement(bounds)
+ const handle = new FakeElement(bounds)
+ const cleanup = api.registerItem(
+ entity,
+ element as unknown as HTMLElement,
+ handle as unknown as HTMLElement,
+ )
+ return { entity, element, handle, cleanup }
+}
+
+function point(identifier: number, clientX: number, clientY: number) {
+ return { identifier, clientX, clientY }
+}
+
+function touch(
+ handle: FakeElement,
+ type: "touchstart" | "touchmove" | "touchend" | "touchcancel",
+ touches: ReturnType<typeof point>[],
+ changedTouches = touches,
+) {
+ return handle.dispatch(type, testEvent(type, { touches, changedTouches }))
+}
+
+function key(target: FakeEventTarget, value: string) {
+ return target.dispatch("keydown", testEvent("keydown", { key: value }))
+}
+
+function flushAnimationFrame() {
+ const first = animationFrames.entries().next().value as [number, FrameRequestCallback] | undefined
+ if (!first) return
+ animationFrames.delete(first[0])
+ first[1](0)
+}
+
+function monitorLocation(
+ source: RailEntity,
+ records: Array<{ data: Record<string, unknown> }>,
+): MonitorLocation {
+ return {
+ source: { data: { railKind: source.kind, railId: source.id } },
+ location: { current: { dropTargets: records } },
+ }
+}
+
+function targetRecord(
+ index: number,
+ target: FakeElement,
+ source: RailEntity,
+ clientY: number,
+) {
+ const options = adapters.targets[index] as TargetOptions
+ return {
+ data: options.getData({
+ input: { clientX: 20, clientY },
+ element: target as unknown as HTMLElement,
+ source: { data: { railKind: source.kind, railId: source.id } },
+ }),
+ }
+}
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ adapters.draggables.length = 0
+ adapters.targets.length = 0
+ adapters.monitor = null
+ adapters.autoScroll = null
+ adapters.cleanupDraggable.mockReset()
+ adapters.cleanupTarget.mockReset()
+ adapters.cleanupMonitor.mockReset()
+ adapters.cleanupAutoScroll.mockReset()
+ fakeDocument = new FakeDocument()
+ fakeWindow = new FakeEventTarget()
+ animationFrames = new Map()
+ nextFrameId = 1
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true)
+ vi.stubGlobal("document", fakeDocument)
+ vi.stubGlobal("window", fakeWindow)
+ vi.stubGlobal("MouseEvent", FakeMouseEvent)
+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
+ const id = nextFrameId++
+ animationFrames.set(id, callback)
+ return id
+ })
+ vi.stubGlobal("cancelAnimationFrame", (id: number) => animationFrames.delete(id))
+})
+
+afterEach(async () => {
+ await act(async () => {
+ for (const renderer of renderers.splice(0)) renderer.unmount()
+ })
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+})
+
+describe("useServerRailPdd behavior", () => {
+ it("adapts native PDD availability, previews, hover expansion, and drop", async () => {
+ const hook = await renderHook()
+ const a = register(hook.current, { kind: "server", id: "a" }, rect(0, 40))
+ const b = register(hook.current, { kind: "server", id: "b" }, rect(80, 120))
+ const folder = register(hook.current, { kind: "folder", id: "f" }, rect(160, 200))
+ register(hook.current, { kind: "folder", id: "g" }, rect(240, 280))
+
+ const draggable = adapters.draggables[0] as DraggableOptions
+ expect(draggable.canDrag()).toBe(true)
+ expect(draggable.getInitialData()).toEqual({ railKind: "server", railId: "a" })
+ const bTarget = adapters.targets[1] as TargetOptions
+ expect(bTarget.canDrop({ source: { data: draggable.getInitialData() } })).toBe(true)
+ expect(bTarget.canDrop({ source: { data: { railKind: "server", railId: "b" } } })).toBe(false)
+ expect(bTarget.getIsSticky()).toBe(false)
+ bTarget.getData({
+ input: { clientX: 20, clientY: 100 },
+ element: b.element as unknown as HTMLElement,
+ source: { data: { railKind: "invalid", railId: "x" } },
+ })
+
+ const monitor = adapters.monitor as MonitorOptions
+ expect(monitor.canMonitor({ source: { data: draggable.getInitialData() } })).toBe(true)
+ expect(monitor.canMonitor({ source: { data: {} } })).toBe(false)
+ monitor.onDragStart({ source: { data: {} } })
+ monitor.onDragStart({ source: { data: draggable.getInitialData() } })
+ expect(draggable.canDrag()).toBe(false)
+
+ const afterB = targetRecord(1, b.element, a.entity, 115)
+ monitor.onDrag(monitorLocation(a.entity, [afterB]))
+ expect(hook.callbacks.onPreview).toHaveBeenLastCalledWith(expect.objectContaining({
+ operation: "reorder-after",
+ }))
+
+ const intoFolder = targetRecord(2, folder.element, a.entity, 180)
+ monitor.onDropTargetChange(monitorLocation(a.entity, [intoFolder]))
+ const sameFolderNewSource = targetRecord(2, folder.element, b.entity, 180)
+ monitor.onDrag(monitorLocation(b.entity, [sameFolderNewSource]))
+ await act(async () => vi.advanceTimersByTime(500))
+ expect(hook.callbacks.onHoverExpand).toHaveBeenCalledWith("f")
+
+ monitor.onDrop(monitorLocation(a.entity, [afterB]))
+ expect(hook.callbacks.onDrop).toHaveBeenCalledWith(expect.objectContaining({
+ operation: "reorder-after",
+ }))
+ monitor.onDrag(monitorLocation(a.entity, [afterB]))
+ monitor.onDropTargetChange(monitorLocation(a.entity, [afterB]))
+ monitor.onDrop(monitorLocation(a.entity, [afterB]))
+ const autoScroll = adapters.autoScroll as AutoScrollOptions
+ expect(autoScroll.getAllowedAxis()).toBe("vertical")
+ expect(autoScroll.getConfiguration()).toEqual({ maxScrollSpeed: "fast" })
+ })
+
+ it("supports keyboard pickup, spatial changes, drop, cancellation, and pending lock", async () => {
+ const hook = await renderHook()
+ const a = register(hook.current, { kind: "server", id: "a" }, rect(0, 40, 10, 50))
+ const b = register(hook.current, { kind: "server", id: "b" }, rect(80, 120, 0, 40))
+ register(hook.current, { kind: "folder", id: "f" }, rect(160, 200))
+
+ expect(key(a.handle, "x").defaultPrevented).toBe(false)
+ expect(key(a.handle, " ").defaultPrevented).toBe(true)
+ expect(hook.callbacks.onAnnounce).toHaveBeenCalledWith(expect.stringContaining("A picked up"))
+ flushAnimationFrame()
+ expect(a.handle.focus).toHaveBeenCalledWith({ preventScroll: true })
+
+ const replacement = register(hook.current, a.entity, rect(0, 40))
+ expect(replacement.handle.focus).toHaveBeenCalledWith({ preventScroll: true })
+ expect(key(a.handle, "ArrowDown").defaultPrevented).toBe(true)
+ expect(hook.callbacks.onAnnounce).toHaveBeenCalledWith("A will move after B")
+ expect(key(a.handle, "ArrowRight").defaultPrevented).toBe(true)
+ expect(hook.callbacks.onAnnounce).toHaveBeenCalledWith("A will move into B")
+ expect(key(a.handle, "ArrowLeft").defaultPrevented).toBe(true)
+ expect(key(a.handle, "ArrowDown").defaultPrevented).toBe(true)
+ expect(hook.callbacks.onAnnounce).toHaveBeenCalledWith("A will move into F")
+ expect(key(a.handle, "Enter").defaultPrevented).toBe(true)
+ expect(hook.callbacks.onDrop).toHaveBeenCalled()
+
+ key(b.handle, " ")
+ expect(key(b.handle, "ArrowUp").defaultPrevented).toBe(true)
+ key(b.handle, " ")
+ expect(hook.callbacks.onDrop).toHaveBeenCalledWith(expect.objectContaining({
+ operation: "reorder-before",
+ }))
+
+ const folderHandle = (adapters.draggables[2] as DraggableOptions)
+ expect(folderHandle.getInitialData()).toEqual({ railKind: "folder", railId: "f" })
+ const registeredFolder = register(hook.current, { kind: "folder", id: "g" }, rect(240, 280))
+ key(registeredFolder.handle, " ")
+ expect(key(registeredFolder.handle, "ArrowDown").defaultPrevented).toBe(true)
+ key(registeredFolder.handle, "Escape")
+
+ key(a.handle, " ")
+ const escape = key(fakeDocument, "Escape")
+ expect(escape.propagationStopped).toBe(true)
+ expect(hook.callbacks.onAnnounce).toHaveBeenCalledWith("A move cancelled")
+
+ key(a.handle, " ")
+ fakeWindow.dispatch("blur")
+ key(a.handle, " ")
+ fakeDocument.visibilityState = "hidden"
+ fakeDocument.dispatch("visibilitychange")
+ fakeDocument.visibilityState = "visible"
+
+ key(a.handle, " ")
+ await hook.rerender({ canStart: () => false })
+ expect(hook.callbacks.onCancel).toHaveBeenCalled()
+ const locked = key(a.handle, " ")
+ expect(locked.defaultPrevented).toBe(false)
+ expect(hook.callbacks.onAnnounce).toHaveBeenCalledWith(
+ "A server rail move is already being saved",
+ )
+ })
+
+ it("falls back across keyboard combine and relative-order availability", async () => {
+ const hook = await renderHook()
+ const b = register(hook.current, { kind: "server", id: "b" }, rect(0, 40))
+ register(hook.current, { kind: "server", id: "a" }, rect(80, 120))
+
+ expect(key(b.handle, " ").defaultPrevented).toBe(true)
+ expect(key(b.handle, "ArrowDown").defaultPrevented).toBe(true)
+ expect(hook.callbacks.onAnnounce).toHaveBeenLastCalledWith("B will move into A")
+
+ expect(key(b.handle, "ArrowLeft").defaultPrevented).toBe(true)
+ expect(hook.callbacks.onAnnounce).toHaveBeenLastCalledWith("B will move before A")
+
+ hook.callbacks.getState.mockReturnValue({
+ serverOrder: ["c", "d"],
+ folderOrder: [],
+ folders: {},
+ expanded: [],
+ })
+ expect(key(b.handle, "ArrowLeft").defaultPrevented).toBe(false)
+ expect(key(b.handle, "Escape").defaultPrevented).toBe(true)
+
+ hook.callbacks.getState.mockReturnValue({
+ serverOrder: ["a", "b"],
+ folderOrder: ["f"],
+ folders: { f: ["a", "b"] },
+ expanded: ["f"],
+ })
+ expect(key(b.handle, " ").defaultPrevented).toBe(true)
+ const noOpAnnouncementCount = hook.callbacks.onAnnounce.mock.calls.length
+ expect(key(b.handle, "ArrowDown").defaultPrevented).toBe(true)
+ expect(hook.callbacks.onAnnounce).toHaveBeenCalledTimes(noOpAnnouncementCount)
+ expect(key(b.handle, "Escape").defaultPrevented).toBe(true)
+ })
+
+ it("separates taps, scroll, context menu, multi-touch, and cancellation", async () => {
+ const hook = await renderHook()
+ const a = register(hook.current, { kind: "server", id: "a" }, rect(0, 40))
+
+ touch(a.handle, "touchstart", [point(1, 10, 10)])
+ const tapEnd = touch(a.handle, "touchend", [], [point(1, 10, 10)])
+ expect(tapEnd.defaultPrevented).toBe(true)
+ expect(a.handle.clickCount).toBe(1)
+
+ touch(a.handle, "touchstart", [point(2, 10, 10)])
+ const scrollMove = touch(a.handle, "touchmove", [point(2, 10, 30)])
+ expect(scrollMove.defaultPrevented).toBe(false)
+
+ touch(a.handle, "touchstart", [point(3, 10, 10)])
+ hook.scroll.dispatch("scroll")
+ touch(a.handle, "touchmove", [point(3, 10, 30)])
+ expect(hook.callbacks.onDragStart).not.toHaveBeenCalled()
+
+ touch(a.handle, "touchstart", [point(4, 10, 10)])
+ touch(a.handle, "touchstart", [point(4, 10, 10), point(5, 12, 12)])
+ expect(hook.callbacks.onCancel).toHaveBeenCalled()
+
+ touch(a.handle, "touchstart", [point(40, 10, 10)])
+ touch(a.handle, "touchmove", [point(40, 10, 20), point(41, 12, 22)])
+
+ touch(a.handle, "touchstart", [point(6, 10, 10)])
+ touch(a.handle, "touchmove", [point(7, 10, 30)])
+ touch(a.handle, "touchstart", [point(8, 10, 10)])
+ touch(a.handle, "touchcancel", [])
+
+ touch(a.handle, "touchstart", [point(9, 10, 10)])
+ await act(async () => vi.advanceTimersByTime(650))
+ a.handle.click()
+ expect(a.handle.lastClickEvent?.defaultPrevented).toBe(true)
+ expect(a.handle.lastClickEvent?.propagationStopped).toBe(true)
+
+ touch(a.handle, "touchstart", [point(10, 10, 10)])
+ await act(async () => vi.advanceTimersByTime(SERVER_RAIL_TOUCH_HOLD_MS))
+ const clickCount = a.handle.clickCount
+ touch(a.handle, "touchend", [], [point(10, 10, 10)])
+ expect(a.handle.clickCount).toBe(clickCount)
+ a.handle.click()
+ expect(a.handle.lastClickEvent?.defaultPrevented).toBe(true)
+
+ hook.callbacks.canStart.mockReturnValueOnce(true)
+ touch(a.handle, "touchstart", [point(11, 10, 10)])
+ await act(async () => vi.advanceTimersByTime(SERVER_RAIL_TOUCH_HOLD_MS))
+ hook.callbacks.canStart.mockReturnValue(false)
+ touch(a.handle, "touchmove", [point(11, 10, 30)])
+ expect(hook.callbacks.onAnnounce).toHaveBeenCalledWith(
+ "A server rail move is already being saved",
+ )
+ })
+
+ it("drags by touch through every hit region and owns edge scroll only after hold", async () => {
+ const hook = await renderHook()
+ hook.scroll.bounds = rect(0, 100, 0, 56)
+ hook.scroll.scrollTop = 20
+ const a = register(hook.current, { kind: "server", id: "a" }, rect(0, 40))
+ const b = register(hook.current, { kind: "server", id: "b" }, rect(80, 120))
+ const f = register(hook.current, { kind: "folder", id: "f" }, rect(160, 200))
+ const g = register(hook.current, { kind: "folder", id: "g" }, rect(240, 280))
+
+ async function drag(
+ source: typeof a,
+ target: typeof a,
+ identifier: number,
+ startY: number,
+ endY: number,
+ includeChangedTouch = true,
+ ) {
+ touch(source.handle, "touchstart", [point(identifier, 20, startY)])
+ await act(async () => vi.advanceTimersByTime(SERVER_RAIL_TOUCH_HOLD_MS))
+ fakeDocument.points = [target.element]
+ const move = touch(source.handle, "touchmove", [point(identifier, 20, endY)])
+ expect(move.defaultPrevented).toBe(true)
+ touch(source.handle, "touchmove", [point(identifier, 20, endY)])
+ flushAnimationFrame()
+ touch(
+ source.handle,
+ "touchend",
+ [],
+ includeChangedTouch ? [point(identifier, 20, endY)] : [],
+ )
+ }
+
+ await drag(b, a, 1, 100, 5)
+ await drag(a, b, 2, 10, 115, false)
+
+ touch(a.handle, "touchstart", [point(3, 20, 10)])
+ await act(async () => vi.advanceTimersByTime(SERVER_RAIL_TOUCH_HOLD_MS))
+ fakeDocument.points = [f.element]
+ touch(a.handle, "touchmove", [point(3, 20, 180)])
+ const context = a.handle.dispatch("contextmenu", testEvent("contextmenu"))
+ expect(context.defaultPrevented).toBe(true)
+ touch(a.handle, "touchend", [], [point(3, 20, 180)])
+
+ await drag(g, f, 4, 260, 176)
+ await drag(f, g, 5, 180, 264)
+ expect(hook.callbacks.onDrop.mock.calls.map(([instruction]) => instruction.operation))
+ .toEqual(expect.arrayContaining([
+ "reorder-before",
+ "reorder-after",
+ "combine",
+ ]))
+ expect(hook.scroll.scrollTop).not.toBe(20)
+ expect(fakeDocument.removeAllRanges).toHaveBeenCalled()
+ expect(fakeDocument.documentElement.style.userSelect).toBe("text")
+
+ touch(a.handle, "touchstart", [point(6, 20, 10)])
+ await act(async () => vi.advanceTimersByTime(SERVER_RAIL_TOUCH_HOLD_MS))
+ fakeDocument.points = [a.element]
+ touch(a.handle, "touchmove", [point(6, 20, 35)])
+ touch(a.handle, "touchend", [], [])
+ expect(hook.callbacks.onCancel).toHaveBeenCalled()
+ })
+
+ it("cancels when an active source leaves, but survives its lazy replacement", async () => {
+ const hook = await renderHook()
+ const a = register(hook.current, { kind: "server", id: "a" }, rect(0, 40))
+ key(a.handle, " ")
+ a.cleanup()
+ const replacement = register(hook.current, a.entity, rect(0, 40))
+ await act(async () => Promise.resolve())
+ expect(hook.callbacks.onCancel).not.toHaveBeenCalled()
+ replacement.cleanup()
+ await act(async () => Promise.resolve())
+ expect(hook.callbacks.onCancel).toHaveBeenCalledTimes(1)
+ expect(adapters.cleanupTarget).toHaveBeenCalledTimes(2)
+ expect(adapters.cleanupDraggable).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/src/web/src/components/community/shell/use-server-rail-pdd.test.ts b/src/web/src/components/community/shell/use-server-rail-pdd.test.ts
index a3da968c6..0ef21c425 100644
--- a/src/web/src/components/community/shell/use-server-rail-pdd.test.ts
+++ b/src/web/src/components/community/shell/use-server-rail-pdd.test.ts
@@ -1,6 +1,12 @@
import { describe, expect, it } from "vitest"
import { attachInstruction } from "@atlaskit/pragmatic-drag-and-drop-hitbox/list-item"
-import { railEntityFromData, railInstructionFromRecords } from "./use-server-rail-pdd"
+import {
+ railEntityFromData,
+ railInstructionFromRecords,
+ railTouchMoveIntent,
+ SERVER_RAIL_TOUCH_DRIFT_PX,
+ SERVER_RAIL_TOUCH_HOLD_MS,
+} from "./use-server-rail-pdd"
describe("server rail PDD record adapter", () => {
it("reads only typed rail entities", () => {
@@ -40,4 +46,39 @@ describe("server rail PDD record adapter", () => {
it("rejects self and missing targets", () => {
expect(railInstructionFromRecords({ railKind: "server", railId: "one" }, [])).toBeNull()
})
+
+ it("keeps ordinary scroll outside the 450ms/10px drag intent", () => {
+ expect(SERVER_RAIL_TOUCH_HOLD_MS).toBe(450)
+ expect(SERVER_RAIL_TOUCH_DRIFT_PX).toBe(10)
+ expect(railTouchMoveIntent({
+ armed: false,
+ dragging: false,
+ distance: 10,
+ touchCount: 1,
+ })).toBe("wait")
+ expect(railTouchMoveIntent({
+ armed: false,
+ dragging: false,
+ distance: 10.1,
+ touchCount: 1,
+ })).toBe("scroll")
+ expect(railTouchMoveIntent({
+ armed: true,
+ dragging: false,
+ distance: 10.1,
+ touchCount: 1,
+ })).toBe("start-drag")
+ expect(railTouchMoveIntent({
+ armed: true,
+ dragging: true,
+ distance: 30,
+ touchCount: 1,
+ })).toBe("drag")
+ expect(railTouchMoveIntent({
+ armed: true,
+ dragging: true,
+ distance: 30,
+ touchCount: 2,
+ })).toBe("cancel")
+ })
})
diff --git a/src/web/src/components/community/shell/use-server-rail-pdd.ts b/src/web/src/components/community/shell/use-server-rail-pdd.ts
index 36cd78555..1481c6fac 100644
--- a/src/web/src/components/community/shell/use-server-rail-pdd.ts
+++ b/src/web/src/components/community/shell/use-server-rail-pdd.ts
@@ -12,10 +12,37 @@ import {
dropTargetForElements,
monitorForElements,
} from "@atlaskit/pragmatic-drag-and-drop/adapter/element-adapter"
-import type { RailEntity, RailInstruction } from "@/lib/community/server-rail-model"
+import {
+ railInstructionIsAvailable,
+ railOperationAvailability,
+ type RailEntity,
+ type RailInstruction,
+ type RailOperation,
+ type RailState,
+} from "@/lib/community/server-rail-model"
type RailData = Record<string | symbol, unknown>
+export const SERVER_RAIL_TOUCH_HOLD_MS = 450
+export const SERVER_RAIL_TOUCH_DRIFT_PX = 10
+
+export function railTouchMoveIntent({
+ armed,
+ dragging,
+ distance,
+ touchCount,
+}: {
+ armed: boolean
+ dragging: boolean
+ distance: number
+ touchCount: number
+}): "wait" | "scroll" | "start-drag" | "drag" | "cancel" {
+ if (touchCount !== 1) return "cancel"
+ if (dragging) return "drag"
+ if (!armed) return distance > SERVER_RAIL_TOUCH_DRIFT_PX ? "scroll" : "wait"
+ return distance > SERVER_RAIL_TOUCH_DRIFT_PX ? "start-drag" : "wait"
+}
+
function sameEntity(left: RailEntity | null, right: RailEntity | null): boolean {
return left?.kind === right?.kind && left?.id === right?.id
}
@@ -40,18 +67,16 @@ export function railInstructionFromRecords(
return { operation: instruction.operation, source, target }
}
-function operationAvailability(source: RailEntity | null, target: RailEntity): {
+function pddAvailability(state: RailState, source: RailEntity | null, target: RailEntity): {
"reorder-before": Availability
"reorder-after": Availability
combine: Availability
} {
- const canReorder = source?.kind === target.kind
- const canCombine = source?.kind === "server"
- && (target.kind === "server" || target.kind === "folder")
+ const available = railOperationAvailability(state, source, target)
return {
- "reorder-before": canReorder ? "available" : "not-available",
- "reorder-after": canReorder ? "available" : "not-available",
- combine: canCombine ? "available" : "not-available",
+ "reorder-before": available["reorder-before"] ? "available" : "not-available",
+ "reorder-after": available["reorder-after"] ? "available" : "not-available",
+ combine: available.combine ? "available" : "not-available",
}
}
@@ -63,26 +88,71 @@ function sameInstruction(left: RailInstruction | null, right: RailInstruction |
export function useServerRailPdd({
scrollRef,
+ getState,
+ canStart,
+ getEntityLabel,
onDragStart,
onPreview,
onDrop,
onCancel,
onHoverExpand,
+ onAnnounce,
}: {
scrollRef: RefObject<HTMLElement | null>
+ getState: () => RailState
+ canStart: () => boolean
+ getEntityLabel: (entity: RailEntity) => string
onDragStart: (source: RailEntity) => void
onPreview: (instruction: RailInstruction | null) => void
onDrop: (instruction: RailInstruction) => void
onCancel: () => void
onHoverExpand: (folderId: string) => void
+ onAnnounce: (message: string) => void
}) {
- const handlersRef = useRef({ onDragStart, onPreview, onDrop, onCancel, onHoverExpand })
+ const handlersRef = useRef({
+ getState,
+ canStart,
+ getEntityLabel,
+ onDragStart,
+ onPreview,
+ onDrop,
+ onCancel,
+ onHoverExpand,
+ onAnnounce,
+ })
useEffect(() => {
- handlersRef.current = { onDragStart, onPreview, onDrop, onCancel, onHoverExpand }
- }, [onCancel, onDragStart, onDrop, onHoverExpand, onPreview])
+ handlersRef.current = {
+ getState,
+ canStart,
+ getEntityLabel,
+ onDragStart,
+ onPreview,
+ onDrop,
+ onCancel,
+ onHoverExpand,
+ onAnnounce,
+ }
+ }, [canStart, getEntityLabel, getState, onAnnounce, onCancel, onDragStart, onDrop, onHoverExpand, onPreview])
const previewRef = useRef<RailInstruction | null>(null)
const hoverTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const hoverFolderRef = useRef<string | null>(null)
+ const itemsRef = useRef(new Map<HTMLElement, { entity: RailEntity; handle: HTMLElement }>())
+ const activeRef = useRef<{ sensor: "native" | "touch" | "keyboard"; source: RailEntity } | null>(null)
+ const suppressClickUntilRef = useRef(0)
+ const selectionStyleRef = useRef<string | null>(null)
+ const touchRef = useRef<{
+ entity: RailEntity
+ identifier: number
+ startX: number
+ startY: number
+ clientX: number
+ clientY: number
+ armed: boolean
+ dragging: boolean
+ timer: ReturnType<typeof setTimeout> | null
+ contextTimer: ReturnType<typeof setTimeout> | null
+ frame: number | null
+ } | null>(null)
const clearHover = useCallback(() => {
if (hoverTimerRef.current) clearTimeout(hoverTimerRef.current)
@@ -110,14 +180,201 @@ export function useServerRailPdd({
}, 500)
}, [clearHover])
+ const restoreSelection = useCallback(() => {
+ if (selectionStyleRef.current === null) return
+ document.documentElement.style.userSelect = selectionStyleRef.current
+ selectionStyleRef.current = null
+ }, [])
+
+ const clearTouch = useCallback(() => {
+ const touch = touchRef.current
+ if (touch?.timer) clearTimeout(touch.timer)
+ if (touch?.contextTimer) clearTimeout(touch.contextTimer)
+ if (touch?.frame !== null && touch?.frame !== undefined) cancelAnimationFrame(touch.frame)
+ touchRef.current = null
+ restoreSelection()
+ }, [restoreSelection])
+
+ const cancelActive = useCallback((announcement?: string) => {
+ if (!activeRef.current && !touchRef.current) return
+ activeRef.current = null
+ clearTouch()
+ clearHover()
+ updatePreview(null)
+ handlersRef.current.onCancel()
+ if (announcement) handlersRef.current.onAnnounce(announcement)
+ }, [clearHover, clearTouch, updatePreview])
+
+ const begin = useCallback((source: RailEntity, sensor: "native" | "touch" | "keyboard") => {
+ if (activeRef.current || !handlersRef.current.canStart()) {
+ handlersRef.current.onAnnounce("A server rail move is already being saved")
+ return false
+ }
+ activeRef.current = { sensor, source }
+ handlersRef.current.onDragStart(source)
+ if (sensor === "keyboard") {
+ handlersRef.current.onAnnounce(
+ `${handlersRef.current.getEntityLabel(source)} picked up. Use arrow keys to choose a position, Space or Enter to drop, and Escape to cancel.`,
+ )
+ }
+ return true
+ }, [])
+
+ const describePreview = useCallback((instruction: RailInstruction) => {
+ const source = handlersRef.current.getEntityLabel(instruction.source)
+ const target = handlersRef.current.getEntityLabel(instruction.target)
+ if (instruction.operation === "combine") return `${source} will move into ${target}`
+ return `${source} will move ${instruction.operation === "reorder-before" ? "before" : "after"} ${target}`
+ }, [])
+
+ const setPreview = useCallback((instruction: RailInstruction | null, announcePreview = false) => {
+ const valid = instruction && railInstructionIsAvailable(
+ handlersRef.current.getState(),
+ instruction,
+ ) ? instruction : null
+ const changed = !sameInstruction(previewRef.current, valid)
+ updatePreview(valid)
+ if (changed && valid && announcePreview) {
+ handlersRef.current.onAnnounce(describePreview(valid))
+ }
+ }, [describePreview, updatePreview])
+
+ const finishDrop = useCallback((instruction: RailInstruction | null) => {
+ const valid = instruction && railInstructionIsAvailable(
+ handlersRef.current.getState(),
+ instruction,
+ ) ? instruction : null
+ activeRef.current = null
+ clearTouch()
+ clearHover()
+ updatePreview(null)
+ if (valid) handlersRef.current.onDrop(valid)
+ else handlersRef.current.onCancel()
+ }, [clearHover, clearTouch, updatePreview])
+
+ const itemAtPoint = useCallback((source: RailEntity, clientX: number, clientY: number) => {
+ const targetElement = document.elementsFromPoint(clientX, clientY)
+ .find((element) => itemsRef.current.has(element as HTMLElement)) as HTMLElement | undefined
+ if (!targetElement) return null
+ const target = itemsRef.current.get(targetElement)!.entity
+ if (sameEntity(source, target)) return null
+ const availability = railOperationAvailability(handlersRef.current.getState(), source, target)
+ const rect = targetElement.getBoundingClientRect()
+ const ratio = rect.height > 0 ? (clientY - rect.top) / rect.height : 0.5
+ let operation: RailOperation | null = null
+ if (ratio < 0.25 && availability["reorder-before"]) operation = "reorder-before"
+ else if (ratio > 0.75 && availability["reorder-after"]) operation = "reorder-after"
+ else if (availability.combine) operation = "combine"
+ else if (ratio < 0.5 && availability["reorder-before"]) operation = "reorder-before"
+ else if (availability["reorder-after"]) operation = "reorder-after"
+ return operation ? { operation, source, target } satisfies RailInstruction : null
+ }, [])
+
+ const runTouchFrame = useCallback(function frame() {
+ const touch = touchRef.current
+ const scroll = scrollRef.current
+ if (!touch?.dragging || !scroll) return
+ const rect = scroll.getBoundingClientRect()
+ const edge = 32
+ let delta = 0
+ if (touch.clientY < rect.top + edge) {
+ delta = -Math.ceil(12 * (1 - Math.max(0, touch.clientY - rect.top) / edge))
+ } else if (touch.clientY > rect.bottom - edge) {
+ delta = Math.ceil(12 * (1 - Math.max(0, rect.bottom - touch.clientY) / edge))
+ }
+ if (delta !== 0) {
+ scroll.scrollTop += delta
+ setPreview(itemAtPoint(touch.entity, touch.clientX, touch.clientY))
+ }
+ touch.frame = requestAnimationFrame(frame)
+ }, [itemAtPoint, scrollRef, setPreview])
+
+ const orderedItems = useCallback(() => [...itemsRef.current.values()].sort((left, right) => {
+ const leftRect = left.handle.getBoundingClientRect()
+ const rightRect = right.handle.getBoundingClientRect()
+ return leftRect.top - rightRect.top || leftRect.left - rightRect.left
+ }), [])
+
+ const keyboardInstruction = useCallback((source: RailEntity, direction: -1 | 1) => {
+ const items = orderedItems()
+ const currentTarget = previewRef.current?.target ?? source
+ const currentIndex = items.findIndex(({ entity }) => sameEntity(entity, currentTarget))
+ for (
+ let index = currentIndex + direction;
+ index >= 0 && index < items.length;
+ index += direction
+ ) {
+ const target = items[index]!.entity
+ if (sameEntity(source, target)) continue
+ const availability = railOperationAvailability(handlersRef.current.getState(), source, target)
+ const operation = target.kind === "folder" && availability.combine
+ ? "combine"
+ : direction < 0 && availability["reorder-before"]
+ ? "reorder-before"
+ : direction > 0 && availability["reorder-after"]
+ ? "reorder-after"
+ : availability.combine
+ ? "combine"
+ : null
+ if (operation) return { operation, source, target } satisfies RailInstruction
+ }
+ return null
+ }, [orderedItems])
+
+ const handleKeyboardCommand = useCallback((event: KeyboardEvent, source: RailEntity) => {
+ if (event.key === "Escape") {
+ event.preventDefault()
+ cancelActive(`${handlersRef.current.getEntityLabel(source)} move cancelled`)
+ return true
+ }
+ if (event.key === " " || event.key === "Enter") {
+ event.preventDefault()
+ finishDrop(previewRef.current)
+ return true
+ }
+ if (event.key === "ArrowUp" || event.key === "ArrowDown") {
+ event.preventDefault()
+ setPreview(keyboardInstruction(source, event.key === "ArrowUp" ? -1 : 1), true)
+ return true
+ }
+ const current = previewRef.current
+ if (!current || current.target.kind !== "server" || source.kind !== "server") return false
+ const availability = railOperationAvailability(
+ handlersRef.current.getState(),
+ source,
+ current.target,
+ )
+ if (event.key === "ArrowRight" && availability.combine) {
+ event.preventDefault()
+ setPreview({ ...current, operation: "combine" }, true)
+ return true
+ }
+ if (event.key !== "ArrowLeft") return false
+ const operation = availability["reorder-before"]
+ ? "reorder-before"
+ : availability["reorder-after"]
+ ? "reorder-after"
+ : null
+ if (!operation) return false
+ event.preventDefault()
+ setPreview({ ...current, operation }, true)
+ return true
+ }, [cancelActive, finishDrop, keyboardInstruction, setPreview])
+
const registerItem = useCallback((
entity: RailEntity,
element: HTMLElement,
dragHandle: HTMLElement,
) => {
+ itemsRef.current.set(element, { entity, handle: dragHandle })
+ if (
+ activeRef.current?.sensor === "keyboard"
+ && sameEntity(activeRef.current.source, entity)
+ ) dragHandle.focus({ preventScroll: true })
const cleanupDraggable = draggable({
element,
dragHandle,
+ canDrag: () => !touchRef.current && !activeRef.current && handlersRef.current.canStart(),
getInitialData: () => ({ railKind: entity.kind, railId: entity.id }),
})
const cleanupTarget = dropTargetForElements({
@@ -130,49 +387,241 @@ export function useServerRailPdd({
input,
element: targetElement,
axis: "vertical",
- operations: operationAvailability(railEntityFromData(source.data), entity),
+ operations: pddAvailability(
+ handlersRef.current.getState(),
+ railEntityFromData(source.data),
+ entity,
+ ),
},
),
})
+
+ const onTouchStart = (event: TouchEvent) => {
+ if (event.touches.length !== 1) {
+ if (touchRef.current || activeRef.current?.sensor === "touch") cancelActive()
+ return
+ }
+ if (touchRef.current || activeRef.current) return
+ if (!handlersRef.current.canStart()) return
+ suppressClickUntilRef.current = 0
+ const touch = event.touches[0]!
+ const pending = {
+ entity,
+ identifier: touch.identifier,
+ startX: touch.clientX,
+ startY: touch.clientY,
+ clientX: touch.clientX,
+ clientY: touch.clientY,
+ armed: false,
+ dragging: false,
+ timer: null as ReturnType<typeof setTimeout> | null,
+ contextTimer: null as ReturnType<typeof setTimeout> | null,
+ frame: null as number | null,
+ }
+ pending.timer = setTimeout(() => {
+ if (touchRef.current === pending) {
+ pending.armed = true
+ pending.timer = null
+ }
+ }, SERVER_RAIL_TOUCH_HOLD_MS)
+ pending.contextTimer = setTimeout(() => {
+ if (touchRef.current !== pending || pending.dragging) return
+ dragHandle.dispatchEvent(new MouseEvent("contextmenu", {
+ bubbles: true,
+ cancelable: true,
+ button: 2,
+ clientX: pending.clientX,
+ clientY: pending.clientY,
+ }))
+ }, 650)
+ touchRef.current = pending
+ }
+ const onTouchMove = (event: TouchEvent) => {
+ const pending = touchRef.current
+ if (!pending || !sameEntity(pending.entity, entity)) return
+ if (event.touches.length !== 1) {
+ cancelActive()
+ return
+ }
+ const touch = [...event.touches].find((candidate) => candidate.identifier === pending.identifier)
+ if (!touch) {
+ cancelActive()
+ return
+ }
+ pending.clientX = touch.clientX
+ pending.clientY = touch.clientY
+ const exactDistance = Math.hypot(touch.clientX - pending.startX, touch.clientY - pending.startY)
+ const exactIntent = railTouchMoveIntent({
+ armed: pending.armed,
+ dragging: pending.dragging,
+ distance: exactDistance,
+ touchCount: event.touches.length,
+ })
+ if (exactIntent === "scroll") {
+ clearTouch()
+ return
+ }
+ if (exactIntent === "wait") return
+ if (exactIntent === "start-drag") {
+ if (!begin(entity, "touch")) {
+ clearTouch()
+ return
+ }
+ if (pending.contextTimer) clearTimeout(pending.contextTimer)
+ pending.contextTimer = null
+ pending.dragging = true
+ selectionStyleRef.current = document.documentElement.style.userSelect
+ document.documentElement.style.userSelect = "none"
+ document.getSelection()?.removeAllRanges()
+ pending.frame = requestAnimationFrame(runTouchFrame)
+ }
+ event.preventDefault()
+ setPreview(itemAtPoint(entity, touch.clientX, touch.clientY))
+ }
+ const onTouchEnd = (event: TouchEvent) => {
+ const pending = touchRef.current
+ if (!pending || !sameEntity(pending.entity, entity)) return
+ const touch = [...event.changedTouches].find((candidate) => candidate.identifier === pending.identifier)
+ if (pending.dragging) {
+ const clientX = touch?.clientX ?? pending.clientX
+ const clientY = touch?.clientY ?? pending.clientY
+ setPreview(itemAtPoint(entity, clientX, clientY))
+ suppressClickUntilRef.current = Date.now() + 800
+ finishDrop(itemAtPoint(entity, clientX, clientY))
+ } else {
+ const shouldClick = !pending.armed
+ if (shouldClick) event.preventDefault()
+ else suppressClickUntilRef.current = Date.now() + 800
+ clearTouch()
+ if (shouldClick) dragHandle.click()
+ }
+ }
+ const onTouchCancel = () => cancelActive()
+ const onContextMenu = (event: MouseEvent) => {
+ const pending = touchRef.current
+ if (pending && sameEntity(pending.entity, entity) && !pending.dragging) {
+ suppressClickUntilRef.current = Date.now() + 800
+ clearTouch()
+ return
+ }
+ if (activeRef.current?.sensor === "touch") event.preventDefault()
+ }
+ const onClickCapture = (event: MouseEvent) => {
+ if (Date.now() >= suppressClickUntilRef.current) return
+ event.preventDefault()
+ event.stopPropagation()
+ }
+ const onKeyDown = (event: KeyboardEvent) => {
+ const active = activeRef.current
+ if (!active) {
+ if (event.key !== " " || !begin(entity, "keyboard")) return
+ event.preventDefault()
+ requestAnimationFrame(() => {
+ const registered = [...itemsRef.current.values()]
+ .find((item) => item.handle.isConnected && sameEntity(item.entity, entity))
+ registered?.handle.focus({ preventScroll: true })
+ })
+ return
+ }
+ if (active.sensor !== "keyboard" || !sameEntity(active.source, entity)) return
+ handleKeyboardCommand(event, entity)
+ }
+ dragHandle.addEventListener("touchstart", onTouchStart, { passive: true })
+ dragHandle.addEventListener("touchmove", onTouchMove, { passive: false })
+ dragHandle.addEventListener("touchend", onTouchEnd, { passive: false })
+ dragHandle.addEventListener("touchcancel", onTouchCancel, { passive: true })
+ dragHandle.addEventListener("contextmenu", onContextMenu)
+ dragHandle.addEventListener("click", onClickCapture, true)
+ dragHandle.addEventListener("keydown", onKeyDown)
return () => {
+ dragHandle.removeEventListener("touchstart", onTouchStart)
+ dragHandle.removeEventListener("touchmove", onTouchMove)
+ dragHandle.removeEventListener("touchend", onTouchEnd)
+ dragHandle.removeEventListener("touchcancel", onTouchCancel)
+ dragHandle.removeEventListener("contextmenu", onContextMenu)
+ dragHandle.removeEventListener("click", onClickCapture, true)
+ dragHandle.removeEventListener("keydown", onKeyDown)
+ itemsRef.current.delete(element)
+ // Lazy context-menu activation briefly remounts the same rail entity.
+ // Defer cancellation until the replacement registration has had a chance
+ // to land, while still cancelling when an entity truly leaves the rail.
+ queueMicrotask(() => {
+ const stillRegistered = [...itemsRef.current.values()]
+ .some((item) => sameEntity(item.entity, entity))
+ if (!stillRegistered && (
+ sameEntity(touchRef.current?.entity ?? null, entity)
+ || sameEntity(activeRef.current?.source ?? null, entity)
+ )) cancelActive()
+ })
cleanupTarget()
cleanupDraggable()
}
- }, [])
+ }, [begin, cancelActive, clearTouch, finishDrop, handleKeyboardCommand, itemAtPoint, runTouchFrame, setPreview])
useEffect(() => monitorForElements({
canMonitor: ({ source }) => railEntityFromData(source.data) !== null,
onDragStart: ({ source }) => {
const entity = railEntityFromData(source.data)
- if (entity) handlersRef.current.onDragStart(entity)
+ if (entity) begin(entity, "native")
},
onDrag: ({ source, location }) => {
- updatePreview(railInstructionFromRecords(source.data, location.current.dropTargets))
+ if (activeRef.current?.sensor !== "native") return
+ setPreview(railInstructionFromRecords(source.data, location.current.dropTargets))
},
onDropTargetChange: ({ source, location }) => {
- updatePreview(railInstructionFromRecords(source.data, location.current.dropTargets))
+ if (activeRef.current?.sensor !== "native") return
+ setPreview(railInstructionFromRecords(source.data, location.current.dropTargets))
},
onDrop: ({ source, location }) => {
+ if (activeRef.current?.sensor !== "native") return
const instruction = railInstructionFromRecords(source.data, location.current.dropTargets)
- clearHover()
- previewRef.current = null
- handlersRef.current.onPreview(null)
- if (instruction) handlersRef.current.onDrop(instruction)
- else handlersRef.current.onCancel()
+ finishDrop(instruction)
},
- }), [clearHover, updatePreview])
+ }), [begin, finishDrop, setPreview])
useEffect(() => {
const element = scrollRef.current
if (!element) return
- return autoScrollForElements({
+ const cancelPendingTouchForNativeScroll = () => {
+ const pending = touchRef.current
+ if (pending && !pending.dragging) clearTouch()
+ }
+ element.addEventListener("scroll", cancelPendingTouchForNativeScroll, { passive: true })
+ const cleanupAutoScroll = autoScrollForElements({
element,
getAllowedAxis: () => "vertical",
getConfiguration: () => ({ maxScrollSpeed: "fast" }),
})
- }, [scrollRef])
+ return () => {
+ element.removeEventListener("scroll", cancelPendingTouchForNativeScroll)
+ cleanupAutoScroll()
+ }
+ }, [clearTouch, scrollRef])
- useEffect(() => () => clearHover(), [clearHover])
+ useEffect(() => {
+ const cancel = () => cancelActive()
+ const cancelWhenHidden = () => {
+ if (document.visibilityState === "hidden") cancelActive()
+ }
+ const handleActiveKeyboardDrag = (event: KeyboardEvent) => {
+ const active = activeRef.current
+ if (active?.sensor !== "keyboard") return
+ if (handleKeyboardCommand(event, active.source)) event.stopPropagation()
+ }
+ window.addEventListener("blur", cancel)
+ document.addEventListener("visibilitychange", cancelWhenHidden)
+ document.addEventListener("keydown", handleActiveKeyboardDrag, true)
+ return () => {
+ window.removeEventListener("blur", cancel)
+ document.removeEventListener("visibilitychange", cancelWhenHidden)
+ document.removeEventListener("keydown", handleActiveKeyboardDrag, true)
+ cancelActive()
+ }
+ }, [cancelActive, handleKeyboardCommand])
+
+ useEffect(() => {
+ if (!canStart()) cancelActive()
+ }, [canStart, cancelActive])
return { registerItem }
}
diff --git a/src/web/src/lib/community/server-rail-model.ts b/src/web/src/lib/community/server-rail-model.ts
index 375a3d78d..9d96e8fd5 100644
--- a/src/web/src/lib/community/server-rail-model.ts
+++ b/src/web/src/lib/community/server-rail-model.ts
@@ -8,6 +8,8 @@ export type RailEntity =
export type RailOperation = "reorder-before" | "reorder-after" | "combine"
+export type RailOperationAvailability = Record<RailOperation, boolean>
+
export type RailInstruction = {
operation: RailOperation
source: RailEntity
@@ -76,7 +78,7 @@ export function cloneRailState(state: RailState): RailState {
}
}
-export function folderForServer(state: RailState, serverId: string): string | null {
+function folderForServer(state: RailState, serverId: string): string | null {
for (const folderId of state.folderOrder) {
if (state.folders[folderId]?.includes(serverId)) return folderId
}
@@ -301,6 +303,52 @@ export function commitRailInstruction(
return { applied: true, state: next, commands }
}
+function previewInstruction(instruction: RailInstruction, state: RailState): RailInstruction {
+ if (
+ instruction.operation !== "combine"
+ || instruction.source.kind !== "server"
+ || instruction.target.kind !== "server"
+ || instruction.newFolderId
+ ) return instruction
+ let suffix = 0
+ let newFolderId = "__rail_preview_folder__"
+ while (state.folders[newFolderId]) {
+ suffix += 1
+ newFolderId = `__rail_preview_folder_${suffix}__`
+ }
+ return { ...instruction, newFolderId }
+}
+
+export function railInstructionIsAvailable(
+ state: RailState,
+ instruction: RailInstruction,
+): boolean {
+ return commitRailInstruction(state, previewInstruction(instruction, state)).applied
+}
+
+export function railOperationAvailability(
+ state: RailState,
+ source: RailEntity | null,
+ target: RailEntity,
+): RailOperationAvailability {
+ if (!source) {
+ return { "reorder-before": false, "reorder-after": false, combine: false }
+ }
+ return {
+ "reorder-before": railInstructionIsAvailable(state, {
+ operation: "reorder-before",
+ source,
+ target,
+ }),
+ "reorder-after": railInstructionIsAvailable(state, {
+ operation: "reorder-after",
+ source,
+ target,
+ }),
+ combine: railInstructionIsAvailable(state, { operation: "combine", source, target }),
+ }
+}
+
export function railMoveAnnouncement(
instruction: RailInstruction,
names: { servers: ReadonlyMap<string, string>; folders: ReadonlyMap<string, string> },
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 9c4c46def..860bd99d6 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -24,9 +24,6 @@ export const tid = {
serverRailFolderIndicator: (id: string) => `community-server-rail-folder-indicator-${id}`,
serverRailInsert: (id: string) => `community-server-rail-insert-${id}`,
serverRailInsertFolder: (id: string) => `community-server-rail-insert-folder-${id}`,
- serverRailMoveDestination: "community-server-rail-move-destination",
- serverRailMoveTarget: "community-server-rail-move-target",
- serverRailMoveConfirm: "community-server-rail-move-confirm",
channelSidebarScroll: "community-channel-sidebar-scroll",
channelSidebarPending: (serverId: string) => `community-channel-sidebar-pending-${serverId}`,
channelHeaderServer: (serverId: string) => `community-channel-header-server-${serverId}`,
diff --git a/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts
index 2efd1f671..a0aea76e5 100644
--- a/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts
+++ b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts
@@ -126,7 +126,7 @@ test.describe.serial("Inbox/read refresh ownership", () => {
const { page } = await asUser("bob")
await gotoAfterUserWsAuth(page, "/c/me")
- await page.getByRole("button", { name: "Inbox" }).click()
+ await page.getByRole("button", { name: "Inbox", exact: true }).click()
await expect(page.getByTestId(tid.inboxUnreadChannel(channelA))).toBeVisible()
await expect(page.getByTestId(tid.inboxUnreadChannel(channelB))).toBeVisible()
@@ -143,12 +143,12 @@ test.describe.serial("Inbox/read refresh ownership", () => {
await page.getByTestId(tid.inboxUnreadChannel(channelA)).click()
await expect(page).toHaveURL(`/c/channels/${serverId}/${channelA}`)
- await expect(page.getByRole("heading", { name: "Inbox" })).toHaveCount(0)
+ await expect(page.getByRole("heading", { name: "Inbox", exact: true })).toHaveCount(0)
await expect(page.getByRole("heading", { name: channelAName, exact: true })).toBeVisible({
timeout: 20_000,
})
- await page.getByRole("button", { name: "Inbox" }).click()
+ await page.getByRole("button", { name: "Inbox", exact: true }).click()
await expect(page.getByTestId(tid.inboxUnreadChannel(channelA))).toHaveCount(0)
await expect(page.getByTestId(tid.inboxUnreadChannel(channelB))).toBeVisible()
await readStarted.promise
@@ -185,7 +185,7 @@ test.describe.serial("Inbox/read refresh ownership", () => {
await expect(page.getByRole("heading", { name: channelAName, exact: true })).toBeVisible({
timeout: 20_000,
})
- await page.getByRole("button", { name: "Inbox" }).click()
+ await page.getByRole("button", { name: "Inbox", exact: true }).click()
expect((await initialInbox).status()).toBe(200)
await expect(page.getByTestId(tid.inboxUnreadChannel(channelA))).toHaveCount(0)
@@ -295,7 +295,7 @@ test.describe.serial("Inbox/read refresh ownership", () => {
await expect(page.getByRole("heading", { name: channelName, exact: true })).toBeVisible({
timeout: 20_000,
})
- await page.getByRole("button", { name: "Inbox" }).click()
+ await page.getByRole("button", { name: "Inbox", exact: true }).click()
expect((await initialInbox).status()).toBe(200)
await expect(page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)
@@ -376,7 +376,7 @@ test.describe.serial("Inbox/read refresh ownership", () => {
if (path === `/api/community/channels/${firstChildId}/read`) childTargets.push(target)
})
- await page.getByRole("button", { name: "Inbox" }).click()
+ await page.getByRole("button", { name: "Inbox", exact: true }).click()
await expect(page.getByTestId(tid.inboxUnreadChild(firstChildId))).toBeVisible()
const parentRead = page.waitForResponse((response) => (
response.request().method() === "PUT"
@@ -388,7 +388,7 @@ test.describe.serial("Inbox/read refresh ownership", () => {
expect(parentTargets).toEqual([first!.openerMessageId])
expect(childTargets).toEqual([])
- await page.getByRole("button", { name: "Inbox" }).click()
+ await page.getByRole("button", { name: "Inbox", exact: true }).click()
await expect(page.getByTestId(tid.inboxUnreadChild(firstChildId))).toHaveCount(0)
await expect(page.getByTestId(tid.inboxUnreadChild(laterChildId))).toBeVisible()
const snapshot = await (await page.request.get(
@@ -465,7 +465,7 @@ test.describe.serial("Inbox/read refresh ownership", () => {
if (match?.[1] && target) puts.push({ channelId: match[1], target })
})
- await page.getByRole("button", { name: "Inbox" }).click()
+ await page.getByRole("button", { name: "Inbox", exact: true }).click()
await expect(page.getByTestId(tid.inboxUnreadChild(readChildId))).toBeVisible()
const readChildPut = page.waitForResponse((response) => (
response.request().method() === "PUT"
@@ -476,7 +476,7 @@ test.describe.serial("Inbox/read refresh ownership", () => {
await page.waitForTimeout(700)
expect(puts.filter((put) => put.channelId === parentId)).toEqual([])
- await page.getByRole("button", { name: "Inbox" }).click()
+ await page.getByRole("button", { name: "Inbox", exact: true }).click()
await expect(page.getByTestId(tid.inboxUnreadChild(unreadChildId))).toBeVisible()
const parentPut = page.waitForResponse((response) => (
response.request().method() === "PUT"
@@ -501,7 +501,7 @@ test.describe.serial("Inbox/read refresh ownership", () => {
expect(cursor(parentId)).toBe(unreadChild!.openerSeq)
expect(cursor(readChildId)).toBeGreaterThan(0)
expect(cursor(unreadChildId)).toBeGreaterThan(0)
- await page.getByRole("button", { name: "Inbox" }).click()
+ await page.getByRole("button", { name: "Inbox", exact: true }).click()
await expect(page.getByTestId(tid.inboxUnreadChannel(parentId))).toBeVisible()
await expect(page.getByTestId(tid.inboxUnreadChild(nonParticipantChildId))).toHaveCount(0)
})
@@ -521,7 +521,7 @@ test.describe.serial("Inbox/read refresh ownership", () => {
await expect(page.getByRole("heading", { name: channelName, exact: true })).toBeVisible({
timeout: 20_000,
})
- await page.getByRole("button", { name: "Inbox" }).click()
+ await page.getByRole("button", { name: "Inbox", exact: true }).click()
expect((await initialInbox).status()).toBe(200)
await expect(page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)
const stopWatching = await watchInboxRow(page, tid.inboxUnreadChannel(channelId))
diff --git a/src/web/src/test/e2e-ui/36-server-switch-pending-checkpoint.spec.ts b/src/web/src/test/e2e-ui/36-server-switch-pending-checkpoint.spec.ts
index 76fa3859b..4e3574d40 100644
--- a/src/web/src/test/e2e-ui/36-server-switch-pending-checkpoint.spec.ts
+++ b/src/web/src/test/e2e-ui/36-server-switch-pending-checkpoint.spec.ts
@@ -143,14 +143,14 @@ test("server switching exposes one target-scoped cold checkpoint and skips it wh
await warmB.release()
await expect.poll(() => new URL(page.url()).pathname.startsWith(`/c/channels/${serverB}`))
.toBe(true)
- await expect(page.getByRole("button", { name: serverBName, exact: true }))
+ await expect(page.locator("#sidebar").getByRole("button", { name: serverBName, exact: true }))
.toBeVisible({ timeout: 30_000 })
await expect(page.getByTestId(tid.channelRow(channelB))).toBeVisible({ timeout: 30_000 })
await clickServer(page, serverA)
await expect.poll(() => new URL(page.url()).pathname.startsWith(`/c/channels/${serverA}`))
.toBe(true)
- await expect(page.getByRole("button", { name: serverAName, exact: true }))
+ await expect(page.locator("#sidebar").getByRole("button", { name: serverAName, exact: true }))
.toBeVisible({ timeout: 30_000 })
await expect(page.getByRole("heading", { name: channelAName })).toBeVisible({ timeout: 30_000 })
await expectActiveServer(page, serverA, serverB)
@@ -159,7 +159,7 @@ test("server switching exposes one target-scoped cold checkpoint and skips it wh
await expect.poll(coldC.heldNavigation).toBeGreaterThan(0)
await expect(page.getByTestId(tid.channelSidebarPending(serverC))).toBeVisible()
await expect(page.getByTestId(tid.pendingMain("server-landing"))).toBeVisible()
- await expect(page.getByRole("button", { name: channelAName })).toHaveCount(0)
+ await expect(page.getByRole("button", { name: channelAName, exact: true })).toHaveCount(0)
await expectActiveServer(page, serverC, serverA)
expect(mutations).toEqual([])
await coldC.release()
@@ -171,7 +171,7 @@ test("server switching exposes one target-scoped cold checkpoint and skips it wh
await clickServer(page, serverA)
await expect.poll(() => new URL(page.url()).pathname.startsWith(`/c/channels/${serverA}`))
.toBe(true)
- await expect(page.getByRole("button", { name: serverAName, exact: true }))
+ await expect(page.locator("#sidebar").getByRole("button", { name: serverAName, exact: true }))
.toBeVisible({ timeout: 30_000 })
await expect(page.getByRole("heading", { name: channelAName })).toBeVisible({ timeout: 30_000 })
await expectActiveServer(page, serverA, serverC)
@@ -186,7 +186,7 @@ test("server switching exposes one target-scoped cold checkpoint and skips it wh
await expect.poll(coldD.heldNavigation).toBeGreaterThan(0)
const mobileCheckpoint = page.getByTestId(tid.channelSidebarPending(serverD))
await expect(mobileCheckpoint).toBeVisible()
- await expect(page.getByRole("button", { name: channelAName })).toHaveCount(0)
+ await expect(page.getByRole("button", { name: channelAName, exact: true })).toHaveCount(0)
const mobileBox = await mobileCheckpoint.boundingBox()
expect(mobileBox).not.toBeNull()
expect(mobileBox!.width).toBeGreaterThan(300)
diff --git a/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts b/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts
index 73cc2502a..f3e37e7e2 100644
--- a/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts
+++ b/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts
@@ -1,4 +1,4 @@
-import type { Locator, Page } from "@playwright/test"
+import { devices, type Locator, type Page } from "@playwright/test"
import { expect, test } from "./_fixtures/community-fixture"
import { seedChannel, seedServer } from "./_fixtures/seed"
import { tid } from "./_fixtures/testids"
@@ -48,13 +48,210 @@ async function railGeometry(page: Page, serverId: string): Promise<RailGeometry>
}, { rail: tid.serverRailScroll, add: tid.serverAdd })
}
-async function openMove(page: Page, serverId: string) {
- const icon = page.getByTestId(tid.serverIcon(serverId))
- await icon.focus()
- await expect(icon.locator("xpath=ancestor::*[@data-slot='context-menu-trigger'][1]")).toBeVisible()
- await icon.click({ button: "right" })
- await page.getByRole("menuitem", { name: "Move…" }).click()
- await expect(page.getByRole("heading", { name: "Move server" })).toBeVisible()
+async function dispatchTouchGesture(
+ page: Page,
+ origin: Locator,
+ start: { x: number; y: number },
+ end: { x: number; y: number },
+ holdMs: number,
+ probe?: { source: Locator; target: Locator },
+ liveTargetRatio = 0.5,
+ previewScreenshotPath?: string,
+) {
+ await page.evaluate(() => {
+ Reflect.set(window, "__railTouchEvents", [])
+ if (Reflect.get(window, "__railTouchProbeInstalled")) return
+ Reflect.set(window, "__railTouchProbeInstalled", true)
+ for (const type of ["touchstart", "touchmove", "touchend", "touchcancel", "contextmenu"]) {
+ document.addEventListener(type, () => {
+ const events = Reflect.get(window, "__railTouchEvents") as string[] | undefined
+ events?.push(type)
+ }, { capture: true })
+ }
+ })
+ const dispatch = (type: "touchstart" | "touchmove" | "touchend", point: { x: number; y: number }) =>
+ origin.evaluate((element, args) => {
+ const touch = new Touch({
+ identifier: 1,
+ target: element,
+ clientX: args.point.x,
+ clientY: args.point.y,
+ screenX: args.point.x,
+ screenY: args.point.y,
+ })
+ element.dispatchEvent(new TouchEvent(args.type, {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ touches: args.type === "touchend" ? [] : [touch],
+ targetTouches: args.type === "touchend" ? [] : [touch],
+ changedTouches: [touch],
+ }))
+ }, { type, point })
+ await dispatch("touchstart", start)
+ await page.waitForTimeout(20)
+ if (holdMs > 0) await page.waitForTimeout(holdMs)
+ let sawDragging = false
+ let sawPreview = false
+ let capturedPreview = false
+ let currentEnd = end
+ for (let step = 1; step <= 8; step += 1) {
+ const ratio = step / 8
+ if (probe) {
+ const liveTarget = await probe.target.boundingBox()
+ if (liveTarget) {
+ currentEnd = {
+ x: liveTarget.x + liveTarget.width / 2,
+ y: liveTarget.y + liveTarget.height * liveTargetRatio,
+ }
+ }
+ }
+ await dispatch("touchmove", {
+ x: start.x + (currentEnd.x - start.x) * ratio,
+ y: start.y + (currentEnd.y - start.y) * ratio,
+ })
+ await page.waitForTimeout(20)
+ if (probe) {
+ sawDragging ||= await probe.source.getAttribute("data-dragging") === "true"
+ sawPreview ||= await probe.target.getAttribute("data-rail-preview") !== null
+ if (sawPreview && previewScreenshotPath && !capturedPreview) {
+ capturedPreview = true
+ await page.screenshot({ path: previewScreenshotPath })
+ }
+ }
+ }
+ await dispatch("touchend", currentEnd)
+ await page.waitForTimeout(20)
+ return {
+ events: await page.evaluate(() => Reflect.get(window, "__railTouchEvents") as string[]),
+ sawDragging,
+ sawPreview,
+ }
+}
+
+async function dispatchNativeTouchSwipe(
+ page: Page,
+ start: { x: number; y: number },
+ end: { x: number; y: number },
+) {
+ const session = await page.context().newCDPSession(page)
+ try {
+ const point = (x: number, y: number) => [{
+ x,
+ y,
+ radiusX: 1,
+ radiusY: 1,
+ force: 1,
+ id: 1,
+ }]
+ await session.send("Input.dispatchTouchEvent", {
+ type: "touchStart",
+ touchPoints: point(start.x, start.y),
+ })
+ for (let step = 1; step <= 8; step += 1) {
+ const ratio = step / 8
+ await session.send("Input.dispatchTouchEvent", {
+ type: "touchMove",
+ touchPoints: point(
+ start.x + (end.x - start.x) * ratio,
+ start.y + (end.y - start.y) * ratio,
+ ),
+ })
+ await page.waitForTimeout(20)
+ }
+ await session.send("Input.dispatchTouchEvent", {
+ type: "touchEnd",
+ touchPoints: [],
+ })
+ } finally {
+ await session.detach()
+ }
+}
+
+async function touchDrag(
+ page: Page,
+ source: Locator,
+ target: Locator,
+ targetRatio = 0.5,
+ previewScreenshotPath?: string,
+) {
+ const scrollIntoView = async (locator: Locator) => {
+ let lastError: unknown
+ for (let attempt = 0; attempt < 5; attempt += 1) {
+ try {
+ await locator.scrollIntoViewIfNeeded()
+ await expect(locator).toBeVisible()
+ return
+ } catch (error) {
+ lastError = error
+ await page.waitForTimeout(50)
+ }
+ }
+ throw lastError
+ }
+ await scrollIntoView(source)
+ await scrollIntoView(target)
+ const sourceTestId = await source.getAttribute("data-testid")
+ const sourceBox = await source.boundingBox()
+ const targetBox = await target.boundingBox()
+ if (!sourceBox || !targetBox) throw new Error("touch drag target is outside the viewport")
+ const result = await dispatchTouchGesture(
+ page,
+ source,
+ { x: sourceBox.x + sourceBox.width / 2, y: sourceBox.y + sourceBox.height / 2 },
+ { x: targetBox.x + targetBox.width / 2, y: targetBox.y + targetBox.height * targetRatio },
+ 460,
+ { source, target },
+ targetRatio,
+ previewScreenshotPath,
+ )
+ return { ...result, sourceTestId }
+}
+
+async function startStationaryTouch(page: Page, origin: Locator) {
+ const box = await origin.boundingBox()
+ if (!box) throw new Error("touch target is outside the viewport")
+ const point = { x: box.x + box.width / 2, y: box.y + box.height / 2 }
+ const dispatch = (type: "touchstart" | "touchend") => origin.evaluate((element, args) => {
+ const touch = new Touch({
+ identifier: 2,
+ target: element,
+ clientX: args.point.x,
+ clientY: args.point.y,
+ screenX: args.point.x,
+ screenY: args.point.y,
+ })
+ element.dispatchEvent(new TouchEvent(args.type, {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ touches: args.type === "touchend" ? [] : [touch],
+ targetTouches: args.type === "touchend" ? [] : [touch],
+ changedTouches: [touch],
+ }))
+ }, { type, point })
+ await dispatch("touchstart")
+ return () => dispatch("touchend")
+}
+
+async function expectTouchPatch(
+ page: Page,
+ action: () => Promise<{ sourceTestId: string | null }>,
+) {
+ const response = page.waitForResponse((candidate) => (
+ candidate.request().method() === "PATCH"
+ && new URL(candidate.url()).pathname === RAIL_ENDPOINT
+ ), { timeout: 15_000 })
+ const reconcile = Promise.all([
+ page.waitForResponse((candidate) => candidate.request().method() === "GET"
+ && new URL(candidate.url()).pathname === "/api/community/servers"),
+ page.waitForResponse((candidate) => candidate.request().method() === "GET"
+ && new URL(candidate.url()).pathname === "/api/community/users/me/server-folders"),
+ ])
+ const { sourceTestId } = await action()
+ expect((await response).status()).toBe(200)
+ expect((await reconcile).every((candidate) => candidate.status() === 200)).toBe(true)
+ if (sourceTestId) await expect(page.getByTestId(sourceTestId)).toBeFocused()
}
async function dragUntilNativeDrop(
@@ -78,19 +275,23 @@ async function dragUntilNativeDrop(
}
}
-test("server rail commits one PDD drop and exposes mobile Move parity", async ({ asUser }) => {
+test("server rail keeps scroll separate from native, touch, and keyboard drag", async ({ asUser }, testInfo) => {
test.setTimeout(150_000)
const stamp = Date.now()
const first = await seedServer("alice", `Rail first ${stamp}`)
const second = await seedServer("alice", `Rail second ${stamp}`)
const overflowServers: string[] = []
- for (let index = 0; index < 12; index++) {
+ for (let index = 0; index < 18; index++) {
overflowServers.push(await seedServer("alice", `Rail overflow ${index} ${stamp}`))
}
const tail = overflowServers.at(-1)!
const swipeServer = overflowServers.at(-2)!
+ const scrollSwipeServer = overflowServers.at(-5)!
const channel = await seedChannel("alice", first, `rail-${stamp}`)
- const { page } = await asUser("alice")
+ const { page } = await asUser("alice", {
+ ...devices["Pixel 7"],
+ viewport: { width: 1280, height: 900 },
+ })
await page.setViewportSize({ width: 1280, height: 900 })
await page.goto(`/c/channels/${first}/${channel}`)
await expect(page.getByTestId(tid.serverIcon(first))).toBeVisible({ timeout: 30_000 })
@@ -148,43 +349,182 @@ test("server rail commits one PDD drop and exposes mobile Move parity", async ({
expect(mobileTail.railScrollTop).toBe(mobileTail.railMaxScrollTop)
expect(mobileTail.target.bottom).toBeLessThanOrEqual(mobileTail.userBar.top + 0.5)
expect(mobileTail.targetOwnsCenter).toBe(true)
- await openMove(page, tail)
- await page.getByTestId(tid.serverRailMoveDestination).selectOption("new")
- await page.getByTestId(tid.serverRailMoveTarget).selectOption(first)
- const createResponsePromise = page.waitForResponse((response) =>
- response.request().method() === "PATCH" && new URL(response.url()).pathname === RAIL_ENDPOINT,
+ await rail.evaluate((element) => { element.scrollTop = Math.max(0, element.scrollHeight - element.clientHeight - 120) })
+ const beforeSwipe = await rail.evaluate((element) => element.scrollTop)
+ const swipeTarget = page.getByTestId(tid.serverIcon(scrollSwipeServer))
+ await expect(swipeTarget).toBeInViewport()
+ const swipeBox = await swipeTarget.boundingBox()
+ expect(swipeBox).not.toBeNull()
+ await expect(swipeTarget).toHaveCSS("touch-action", "auto")
+ await dispatchNativeTouchSwipe(
+ page,
+ { x: swipeBox!.x + 22, y: swipeBox!.y + 22 },
+ { x: swipeBox!.x + 22, y: Math.max(20, swipeBox!.y - 120) },
+ )
+ expect(railRequests).toHaveLength(1)
+ await expect.poll(() => rail.evaluate((element) => element.scrollTop))
+ .toBeGreaterThan(beforeSwipe)
+ expect(new URL(page.url()).pathname).toBe(`/c/channels/${first}`)
+ await page.waitForTimeout(300)
+
+ await rail.evaluate((element) => { element.scrollTop = element.scrollHeight })
+ await expect(page.getByTestId(tid.serverIcon(tail))).toBeInViewport()
+ await expect(page.getByTestId(tid.serverIcon(swipeServer))).toBeInViewport()
+ const tapTarget = page.getByTestId(tid.serverIcon(tail))
+ await tapTarget.evaluate((element) => {
+ Reflect.set(window, "__railTapClicks", 0)
+ element.addEventListener("click", () => {
+ Reflect.set(window, "__railTapClicks", Number(Reflect.get(window, "__railTapClicks")) + 1)
+ })
+ })
+ await tapTarget.tap()
+ await expect.poll(() => page.evaluate(() => Reflect.get(window, "__railTapClicks"))).toBe(1)
+ await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${tail}`)
+ expect(railRequests).toHaveLength(1)
+ await page.goto(`/c/channels/${first}/${channel}`)
+ await page.getByTestId(tid.channelHeaderServer(first)).click()
+ await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${first}`)
+ await expect(page.getByTestId(tid.serverIcon(first))).toBeVisible({ timeout: 30_000 })
+ await rail.evaluate((element) => { element.scrollTop = element.scrollHeight })
+ await expect(page.getByTestId(tid.serverIcon(tail))).toBeInViewport()
+ await expect(page.getByTestId(tid.serverIcon(swipeServer))).toBeInViewport()
+ const createResponsePromise = page.waitForResponse((response) => (
+ response.request().method() === "PATCH"
+ && new URL(response.url()).pathname === RAIL_ENDPOINT
+ ), { timeout: 15_000 })
+ const createReconcilePromise = Promise.all([
+ page.waitForResponse((response) => response.request().method() === "GET"
+ && new URL(response.url()).pathname === "/api/community/servers"),
+ page.waitForResponse((response) => response.request().method() === "GET"
+ && new URL(response.url()).pathname === "/api/community/users/me/server-folders"),
+ ])
+ const firstTouch = await touchDrag(
+ page,
+ page.getByTestId(tid.serverIcon(tail)),
+ page.getByTestId(tid.serverIcon(swipeServer)),
+ 0.5,
+ testInfo.outputPath("server-rail-touch-preview-390-light.png"),
)
- await page.getByTestId(tid.serverRailMoveConfirm).click()
+ expect(firstTouch.events).toContain("touchstart")
+ expect(firstTouch.events).toContain("touchmove")
+ expect(firstTouch.events).toContain("touchend")
+ expect(firstTouch.events).not.toContain("contextmenu")
+ expect(firstTouch.sawDragging).toBe(true)
+ expect(firstTouch.sawPreview).toBe(true)
const createResponse = await createResponsePromise
expect(createResponse.status()).toBe(200)
- await expect(page.getByRole("heading", { name: "Move server" })).toBeHidden()
+ expect((await createReconcilePromise).every((response) => response.status() === 200)).toBe(true)
+ if (firstTouch.sourceTestId) {
+ await expect(page.getByTestId(firstTouch.sourceTestId)).toBeFocused()
+ }
expect(railRequests).toHaveLength(2)
expect(railRequests[1]?.body).toMatchObject({
- commands: [{ kind: "create-folder", name: "Group", serverIds: [tail, first] }],
+ commands: [{ kind: "create-folder", name: "Group", serverIds: [tail, swipeServer] }],
+ })
+ const folderSelector = `[data-testid^="${tid.serverRailFolder("")}"]`
+ const firstFolder = page.locator(folderSelector).first()
+ await expect(firstFolder).toBeVisible()
+
+ await expectTouchPatch(page, () => touchDrag(
+ page,
+ page.getByTestId(tid.serverIcon(tail)),
+ page.getByTestId(tid.serverIcon(swipeServer)),
+ 0.85,
+ ))
+ expect(railRequests[2]?.body).toMatchObject({
+ commands: [{ kind: "replace-folder-items" }],
+ })
+
+ const nearbyTopLevel = overflowServers.at(-3)!
+ await expectTouchPatch(page, () => touchDrag(
+ page,
+ page.getByTestId(tid.serverIcon(tail)),
+ page.getByTestId(tid.serverIcon(nearbyTopLevel)),
+ 0.15,
+ ))
+ expect(railRequests[3]?.body).toMatchObject({
+ commands: [
+ { kind: "reorder-servers" },
+ { kind: "replace-folder-items" },
+ ],
+ })
+
+ await expectTouchPatch(page, () => touchDrag(
+ page,
+ page.getByTestId(tid.serverIcon(tail)),
+ firstFolder,
+ ))
+ expect(railRequests[4]?.body).toMatchObject({
+ commands: [{ kind: "replace-folder-items" }],
+ })
+
+ const secondGroupSource = overflowServers.at(-4)!
+ await expectTouchPatch(page, () => touchDrag(
+ page,
+ page.getByTestId(tid.serverIcon(secondGroupSource)),
+ page.getByTestId(tid.serverIcon(nearbyTopLevel)),
+ ))
+ expect(railRequests[5]?.body).toMatchObject({
+ commands: [{ kind: "create-folder" }],
+ })
+ const secondFolder = page.locator(folderSelector).nth(1)
+ await expect(secondFolder).toBeVisible()
+
+ await expectTouchPatch(page, () => touchDrag(
+ page,
+ page.getByTestId(tid.serverIcon(tail)),
+ secondFolder,
+ ))
+ expect(railRequests[6]?.body).toMatchObject({
+ commands: [
+ { kind: "replace-folder-items" },
+ { kind: "replace-folder-items" },
+ ],
+ })
+
+ await expectTouchPatch(page, () => touchDrag(page, secondFolder, firstFolder, 0.15))
+ expect(railRequests[7]?.body).toMatchObject({
+ commands: [{ kind: "reorder-folders" }],
})
await expect(page.getByTestId(tid.serverIcon(tail))).toBeVisible()
await expect(page.getByTestId(tid.serverIcon(first))).toBeVisible()
await expect(page.getByTestId(tid.serverIcon(second))).toBeVisible()
- await rail.evaluate((element) => { element.scrollTop = element.scrollHeight })
+ const beforeLongPress = railRequests.length
+ await firstFolder.scrollIntoViewIfNeeded()
+ const endLongPress = await startStationaryTouch(page, firstFolder)
+ await page.waitForTimeout(700)
+ await expect(page.getByRole("menuitem", { name: "Ungroup" })).toBeVisible()
+ await expect(page.getByRole("menuitem", { name: "Move…" })).toHaveCount(0)
+ await expect(page.getByRole("menuitem", { name: "Create group" })).toHaveCount(0)
+ await endLongPress()
+ expect(railRequests).toHaveLength(beforeLongPress)
+ await page.keyboard.press("Escape")
+ await expect(page.getByRole("menuitem", { name: "Ungroup" })).toHaveCount(0)
+ await page.getByTestId(tid.serverIcon(tail)).scrollIntoViewIfNeeded()
await expect.poll(async () => (await railGeometry(page, tail)).targetOwnsCenter)
.toBe(true)
const expandedTail = await railGeometry(page, tail)
expect(expandedTail.rootScrollTop).toBe(0)
expect(expandedTail.target.bottom).toBeLessThanOrEqual(expandedTail.userBar.top + 0.5)
expect(expandedTail.targetOwnsCenter).toBe(true)
- const beforeSwipe = await rail.evaluate((element) => element.scrollTop)
- const swipeTarget = page.getByTestId(tid.serverIcon(swipeServer))
- await expect(swipeTarget).toBeInViewport()
- const box = await swipeTarget.boundingBox()
- expect(box).not.toBeNull()
- await page.mouse.move(box!.x + 20, box!.y + 20)
- await page.mouse.down()
- await page.mouse.move(box!.x + 20, Math.max(10, box!.y - 100), { steps: 8 })
- await page.mouse.up()
- expect(railRequests).toHaveLength(2)
- expect(await rail.evaluate((element) => element.scrollTop)).toBeGreaterThanOrEqual(beforeSwipe)
+ await page.screenshot({ path: testInfo.outputPath("server-rail-touch-combine-390.png") })
await page.setViewportSize({ width: 1280, height: 900 })
+ await page.emulateMedia({ colorScheme: "dark" })
+ await expect(page.locator("html")).toHaveClass(/dark/)
+ const darkKeyboardSource = page.getByTestId(tid.serverIcon(first))
+ await darkKeyboardSource.focus()
+ await page.keyboard.press("Space")
+ await expect(darkKeyboardSource).toBeFocused()
+ await expect(darkKeyboardSource).toHaveAttribute("data-dragging", "true")
+ await page.keyboard.press("ArrowDown")
+ const keyboardInsert = page.locator(`[data-testid^="${tid.serverRailInsert("")}"]`).first()
+ await expect(keyboardInsert).toBeVisible()
+ await page.screenshot({ path: testInfo.outputPath("server-rail-keyboard-preview-1280-dark.png") })
+ await page.keyboard.press("Escape")
+ await expect(keyboardInsert).toHaveCount(0)
+ await page.emulateMedia({ colorScheme: "light" })
+ await expect(page.locator("html")).not.toHaveClass(/dark/)
let releaseCommit!: () => void
const commitGate = new Promise<void>((resolve) => { releaseCommit = resolve })
let delayed = false
@@ -199,23 +539,27 @@ test("server rail commits one PDD drop and exposes mobile Move parity", async ({
response.request().method() === "PATCH" && new URL(response.url()).pathname === RAIL_ENDPOINT,
)
try {
- const topLevel = page.getByTestId(tid.serverIcon(second))
- await topLevel.focus()
- await expect(topLevel.locator("xpath=ancestor::*[@data-slot='context-menu-trigger'][1]")).toBeVisible()
- await topLevel.click({ button: "right" })
- await page.getByRole("menuitem", { name: "Create group" }).click()
- await expect.poll(() => railRequests.length).toBe(3)
+ const keyboardSource = page.getByTestId(tid.serverIcon(first))
+ await keyboardSource.focus()
+ await page.keyboard.press("Space")
+ await page.keyboard.press("ArrowDown")
+ await expect(page.locator(`[data-testid^="${tid.serverRailInsert("")}"]`).first()).toBeVisible()
+ await page.keyboard.press("Enter")
+ await expect.poll(() => railRequests.length).toBe(9)
const existingFolder = page.locator(`[data-testid^="${tid.serverRailFolder("")}"]`).first()
await existingFolder.click({ button: "right" })
+ await expect(page.getByRole("menuitem", { name: "Move…" })).toHaveCount(0)
+ await expect(page.getByRole("menuitem", { name: "Create group" })).toHaveCount(0)
await page.getByRole("menuitem", { name: "Ungroup" }).click()
await page.waitForTimeout(250)
- expect(railRequests).toHaveLength(3)
+ expect(railRequests).toHaveLength(9)
} finally {
releaseCommit()
}
expect((await pendingResponse).status()).toBe(200)
await page.unroute(`**${RAIL_ENDPOINT}`)
+ await page.screenshot({ path: testInfo.outputPath("server-rail-keyboard-1280.png") })
})
test("short server rail keeps Add adjacent and desktop geometry stable", async ({ asUser }) => {
diff --git a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
index 8c2034621..86edff51b 100644
--- a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
+++ b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
@@ -645,7 +645,11 @@ test("mobile reply, avatar mention, and typing space keep exact backend and WS i
await expect.poll(() => aliceProxy.frames.some((frame) => (
frameHasMessage(frame, dmId, dmWsReadyId)
)), { timeout: 20_000 }).toBe(true)
- await expect(alice.page.getByTestId(tid.message(dmWsReadyId))).toBeVisible()
+ const dmReplyTarget = alice.page.getByTestId(tid.message(dmWsReadyId))
+ const dmScrollToPresent = alice.page.getByTestId(tid.scrollToPresent)
+ await expect(dmReplyTarget.or(dmScrollToPresent).first()).toBeVisible()
+ if (await dmScrollToPresent.isVisible()) await dmScrollToPresent.click()
+ await expect(dmReplyTarget).toBeVisible()
await dispatchSwipe(alice.page, dmWsReadyId, { x: 72, y: 1 })
await expect(replyPreview).toHaveText(`Replying to ${bobInfo.name} · dm reply target ${stamp}`)
await expect(composerEditable(alice.page)).toBeFocused()
diff --git a/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts b/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
index 73cedaacb..16665e7f3 100644
--- a/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
+++ b/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
@@ -1,4 +1,4 @@
-import type { Locator, Page } from "@playwright/test"
+import type { Locator, Page, Response } from "@playwright/test"
import { expect, test, userId } from "./_fixtures/community-fixture"
import { composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"
import { memberInfo, seedChannel, seedJoinServer, seedMessage, seedServer } from "./_fixtures/seed"
@@ -12,17 +12,39 @@ async function expectIndicatorHeight(indicator: Locator, height: number) {
await expect.poll(() => indicatorHeight(indicator), { timeout: 20_000 }).toBe(height)
}
-async function createSingleServerFolder(page: Page, serverId: string) {
- const icon = page.getByTestId(tid.serverIcon(serverId))
- await icon.focus()
- await expect(icon.locator("xpath=ancestor::*[@data-slot='context-menu-trigger'][1]")).toBeVisible()
- await icon.click({ button: "right" })
- const response = page.waitForResponse((candidate) => (
- candidate.request().method() === "PATCH"
- && new URL(candidate.url()).pathname === "/api/community/users/me/server-rail"
- ))
- await page.getByRole("menuitem", { name: "Create group" }).click()
- expect((await response).status()).toBe(200)
+async function combineServers(page: Page, sourceId: string, targetId: string) {
+ const sourceButton = page.getByTestId(tid.serverIcon(sourceId))
+ const targetButton = page.getByTestId(tid.serverIcon(targetId))
+ await sourceButton.focus()
+ await targetButton.focus()
+ const source = sourceButton
+ .locator("xpath=ancestor::*[@draggable='true'][1]")
+ const target = targetButton
+ .locator("xpath=ancestor::*[@draggable='true'][1]")
+ await expect(source).toHaveCount(1)
+ await expect(target).toHaveCount(1)
+ const targetBox = await target.boundingBox()
+ if (!targetBox) throw new Error("server rail drag target is outside the viewport")
+ let responseStatus: number | null = null
+ const captureResponse = (candidate: Response) => {
+ if (
+ candidate.request().method() === "PATCH"
+ && new URL(candidate.url()).pathname === "/api/community/users/me/server-rail"
+ ) responseStatus = candidate.status()
+ }
+ page.on("response", captureResponse)
+ try {
+ for (let attempt = 0; attempt < 3 && responseStatus === null; attempt += 1) {
+ await source.dragTo(target, {
+ targetPosition: { x: targetBox.width / 2, y: targetBox.height / 2 },
+ force: true,
+ })
+ await page.waitForTimeout(250)
+ }
+ expect(responseStatus).toBe(200)
+ } finally {
+ page.off("response", captureResponse)
+ }
}
test("server unread owns exact rail geometry, folder aggregation, read clear, and mobile parity", async ({ asUser }, testInfo) => {
@@ -30,10 +52,12 @@ test("server unread owns exact rail geometry, folder aggregation, read clear, an
const stamp = Date.now()
const foregroundServer = await seedServer("alice", `Unread foreground ${stamp}`)
const backgroundServer = await seedServer("alice", `Unread background ${stamp}`)
+ const neutralServer = await seedServer("alice", `Unread neutral ${stamp}`)
const foregroundChannel = await seedChannel("alice", foregroundServer, `foreground-${stamp}`)
const backgroundChannel = await seedChannel("alice", backgroundServer, `background-${stamp}`)
await seedJoinServer("alice", "bob", foregroundServer)
await seedJoinServer("alice", "bob", backgroundServer)
+ await seedJoinServer("alice", "bob", neutralServer)
const bobInfo = await memberInfo("alice", backgroundServer, userId("bob"))
const { page } = await asUser("bob")
await page.setViewportSize({ width: 1280, height: 900 })
@@ -56,13 +80,15 @@ test("server unread owns exact rail geometry, folder aggregation, read clear, an
await page.getByTestId(tid.serverIcon(foregroundServer)).focus()
await expectIndicatorHeight(backgroundIndicator, 10)
- await createSingleServerFolder(page, backgroundServer)
+ await combineServers(page, backgroundServer, neutralServer)
const folder = page.locator(`[data-testid^="${tid.serverRailFolder("")}"]`).first()
await expect(folder).toBeVisible()
const folderTestId = await folder.getAttribute("data-testid")
if (!folderTestId) throw new Error("missing folder testid")
const folderId = folderTestId.slice(tid.serverRailFolder("").length)
const folderIndicator = page.getByTestId(tid.serverRailFolderIndicator(folderId))
+ await page.mouse.move(300, 300)
+ await page.getByRole("button", { name: "Home" }).focus()
await expectIndicatorHeight(folderIndicator, 0)
await page.getByTestId(tid.serverIcon(foregroundServer)).focus()
await expectIndicatorHeight(backgroundIndicator, 10)
diff --git a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
index 1808f906d..7c4a5d53c 100644
--- a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
+++ b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
@@ -127,10 +127,17 @@ async function expectRailReplacementDoesNotBlockMessages({
triggerUnread: () => Promise<string>
}) {
const beforeReadSeq = await readSeq(page, channelId)
- let releaseRail!: () => void
- const railRelease = new Promise<void>((resolve) => { releaseRail = resolve })
+ let releaseRailGate!: () => void
+ const railRelease = new Promise<void>((resolve) => { releaseRailGate = resolve })
let markRailHeld!: () => void
const railHeld = new Promise<void>((resolve) => { markRailHeld = resolve })
+ let markRailSettled!: () => void
+ const railSettled = new Promise<void>((resolve) => { markRailSettled = resolve })
+ let railRequestHeld = false
+ const releaseRail = async () => {
+ releaseRailGate()
+ if (railRequestHeld) await railSettled
+ }
let serverListRequests = 0
let messagesRequests = 0
@@ -141,8 +148,15 @@ async function expectRailReplacementDoesNotBlockMessages({
}
serverListRequests += 1
if (serverListRequests === 1) {
+ railRequestHeld = true
markRailHeld()
await railRelease
+ try {
+ await route.continue()
+ } finally {
+ markRailSettled()
+ }
+ return
}
await route.continue()
})
@@ -157,7 +171,7 @@ async function expectRailReplacementDoesNotBlockMessages({
try {
const latestId = await triggerUnread()
await railHeld
- await page.getByRole("button", { name: "Inbox" }).click()
+ await page.getByRole("button", { name: "Inbox", exact: true }).click()
const inboxRow = page.getByTestId(inboxRowTestId)
await expect(inboxRow).toBeVisible({ timeout: 30_000 })
const messagesResponse = page.waitForResponse((response) => (
@@ -171,7 +185,7 @@ async function expectRailReplacementDoesNotBlockMessages({
expect(serverListRequests).toBeGreaterThanOrEqual(1)
expect(messagesRequests).toBeGreaterThanOrEqual(1)
expect(await readSeq(page, channelId)).toBe(beforeReadSeq)
- releaseRail()
+ await releaseRail()
const body = await response.json() as { messages: Array<{ id: string; seq: number }> }
expect(body.messages.at(-1)?.id).toBe(latestId)
@@ -190,7 +204,7 @@ async function expectRailReplacementDoesNotBlockMessages({
await expect.poll(() => readSeq(page, channelId), { timeout: 20_000 })
.toBeGreaterThan(beforeReadSeq)
} finally {
- releaseRail()
+ await releaseRail()
page.off("request", countMessagesRequest)
await page.unroute("**/api/community/servers")
}
@@ -260,7 +274,7 @@ test.describe.serial("account unread projection", () => {
await gotoAfterUserWsAuth(page, `/c/channels/${backgroundServer}/${forumId}`)
await expect(page).toHaveURL(`/c/channels/${backgroundServer}/${forumId}`)
await expectUnreadDot(page.getByTestId(tid.forumSidebarThread(forumChild)))
- await page.getByRole("button", { name: "Inbox" }).click()
+ await page.getByRole("button", { name: "Inbox", exact: true }).click()
await expect(page.getByTestId(tid.inboxUnreadChannel(unreadChannel))).toBeVisible()
await expect(page.getByTestId(tid.inboxUnreadChild(forumChild))).toBeVisible()
await expect(page.getByTestId(tid.inboxUnreadDm(dmId))).toBeVisible()
@@ -296,7 +310,7 @@ test.describe.serial("account unread projection", () => {
await page.setViewportSize({ width: 390, height: 844 })
await gotoAfterUserWsAuth(page, "/c/me")
- await page.getByRole("button", { name: "Inbox" }).click()
+ await page.getByRole("button", { name: "Inbox", exact: true }).click()
await expect(page.getByTestId(tid.inboxUnreadChannel(unreadChannel))).toHaveCount(0)
await expect(page.getByTestId(tid.inboxUnreadChild(forumChild))).toBeVisible()
await expect(page.getByTestId(tid.inboxUnreadDm(dmId))).toBeVisible()
@@ -423,7 +437,7 @@ test.describe.serial("account unread projection", () => {
const { page } = await asUser("bob")
await gotoAfterUserWsAuth(page, "/c/me")
- await page.getByRole("button", { name: "Inbox" }).click()
+ await page.getByRole("button", { name: "Inbox", exact: true }).click()
await expect(page.getByTestId(tid.inboxUnreadChannel(channelId))).toBeVisible()
await expect(page.getByTestId(tid.inboxUnreadDm(dmId))).toBeVisible()
diff --git a/src/web/src/test/e2e-ui/_fixtures/actions.ts b/src/web/src/test/e2e-ui/_fixtures/actions.ts
index 29dcb8845..fea0e0b94 100644
--- a/src/web/src/test/e2e-ui/_fixtures/actions.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/actions.ts
@@ -36,6 +36,7 @@ export async function gotoAfterUserWsAuth(page: Page, url: string): Promise<void
// Keep Next's development-only portals from capturing pointer input intended
// for the product UI. Production builds do not mount either overlay.
export async function ignoreNextDevToolsPointerCapture(page: Page): Promise<void> {
+ await page.locator("head").waitFor({ state: "attached" })
await page.addStyleTag({
content: [
"nextjs-portal { pointer-events: none !important; }",