From bc06bd6fffd65739c1db02ff23ba38210c893460 Mon Sep 17 00:00:00 2001 From: Akash Vekariya <59219441+akashvekariya@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:40:20 +0530 Subject: [PATCH 1/3] feat: add useSortable hook Adds a headless hook for reordering items by drag or keyboard, within a list and between lists, such as the columns of a board. - Mouse, pen and touch (press and hold) drags with a drag overlay and edge auto-scroll - Full keyboard moves with screen reader announcements - canMove to refuse moves, with a data-drop-refused signal - Optional drag handles, controlled or uncontrolled value - Docs page with list and board demos, and unit tests for the move and keyboard helpers Co-Authored-By: Claude Opus 5.5 --- apps/ui/components/sortable-demo.tsx | 139 +++ apps/ui/content/docs/hooks/meta.json | 2 +- apps/ui/content/docs/hooks/use-sortable.mdx | 233 +++++ apps/ui/mdx-components.tsx | 6 + apps/ui/public/llms.txt | 1 + apps/ui/public/r/registry.json | 10 + apps/ui/public/r/use-sortable.json | 12 + apps/ui/registry.json | 10 + apps/ui/registry/__index__.tsx | 18 + .../ui/registry/default/hooks/use-sortable.ts | 883 ++++++++++++++++++ apps/ui/registry/registry-hooks.ts | 10 + apps/ui/tests/hooks/use-sortable.test.ts | 214 +++++ packages/ui/src/hooks/use-sortable.ts | 883 ++++++++++++++++++ 13 files changed, 2420 insertions(+), 1 deletion(-) create mode 100644 apps/ui/components/sortable-demo.tsx create mode 100644 apps/ui/content/docs/hooks/use-sortable.mdx create mode 100644 apps/ui/public/r/use-sortable.json create mode 100644 apps/ui/registry/default/hooks/use-sortable.ts create mode 100644 apps/ui/tests/hooks/use-sortable.test.ts create mode 100644 packages/ui/src/hooks/use-sortable.ts diff --git a/apps/ui/components/sortable-demo.tsx b/apps/ui/components/sortable-demo.tsx new file mode 100644 index 0000000000..862053c5d3 --- /dev/null +++ b/apps/ui/components/sortable-demo.tsx @@ -0,0 +1,139 @@ +"use client"; + +import { GripVerticalIcon } from "lucide-react"; +import { useState } from "react"; +import { + type SortableValue, + useSortable, +} from "@/registry/default/hooks/use-sortable"; +import { Badge } from "@/registry/default/ui/badge"; + +type Task = { id: string; title: string }; + +const itemClassName = + "flex cursor-grab items-center gap-2 rounded-lg border bg-card px-3 py-2 text-card-foreground text-sm shadow-xs/5 outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-dragging:opacity-50 aria-pressed:data-drop-refused:border-destructive/64"; + +const overlayClassName = + "z-50 flex cursor-grabbing items-center gap-2 rounded-lg border bg-card px-3 py-2 text-card-foreground text-sm shadow-lg data-drop-refused:border-destructive/64"; + +const steps = [ + "Draft the brief", + "Review the designs", + "Build the page", + "Ship it", +]; + +const columns = [ + { id: "todo", label: "To do", limit: undefined }, + { id: "doing", label: "In progress", limit: 2 }, + { id: "done", label: "Done", limit: undefined }, +]; + +const initialBoard: SortableValue = { + doing: [{ id: "t4", title: "Write release notes" }], + done: [{ id: "t5", title: "Set up analytics" }], + todo: [ + { id: "t1", title: "Update pricing page" }, + { id: "t2", title: "Fix signup email" }, + { id: "t3", title: "Plan onboarding call" }, + ], +}; + +export function SortableListDemo() { + const sortable = useSortable({ + defaultValue: { steps }, + getContainerLabel: () => "the list", + }); + + return ( +
+
+ {sortable.value.steps?.map((step) => ( +
+
+ ))} +
+ {sortable.active?.reason === "pointer" && ( +
+
+ )} +
+
+ ); +} + +export function SortableBoardDemo() { + const [board, setBoard] = useState(initialBoard); + const sortable = useSortable({ + canMove: ({ from, to }) => { + const limit = columns.find((column) => column.id === to.container)?.limit; + if (!limit || from.container === to.container) return true; + return (board[to.container]?.length ?? 0) < limit; + }, + getContainerLabel: (id) => + columns.find((column) => column.id === id)?.label ?? id, + getItemLabel: (task) => task.title, + onValueChange: setBoard, + value: board, + }); + + return ( +
+
+ {columns.map((column) => { + const tasks = sortable.value[column.id] ?? []; + return ( +
+
+ {column.label} + + {column.limit + ? `${tasks.length}/${column.limit}` + : tasks.length} + +
+
+ {tasks.map((task) => ( +
+ {task.title} +
+ ))} +
+
+ ); + })} +
+ {sortable.active?.reason === "pointer" && ( +
+ {sortable.active.item.title} +
+ )} +
+
+ ); +} diff --git a/apps/ui/content/docs/hooks/meta.json b/apps/ui/content/docs/hooks/meta.json index e2b2f230b7..d99d5bcddb 100644 --- a/apps/ui/content/docs/hooks/meta.json +++ b/apps/ui/content/docs/hooks/meta.json @@ -1,4 +1,4 @@ { - "pages": ["use-media-query", "use-copy-to-clipboard"], + "pages": ["use-media-query", "use-copy-to-clipboard", "use-sortable"], "title": "Hooks" } diff --git a/apps/ui/content/docs/hooks/use-sortable.mdx b/apps/ui/content/docs/hooks/use-sortable.mdx new file mode 100644 index 0000000000..a3e39fc4ce --- /dev/null +++ b/apps/ui/content/docs/hooks/use-sortable.mdx @@ -0,0 +1,233 @@ +--- +title: useSortable +description: Reorder items by drag or keyboard, within a list and between lists. +--- + +A React hook that adds drag and drop reordering to any list, or to several lists at once, such as the columns of a board. It works with mouse, touch and keyboard, announces every move to screen readers, and renders nothing itself: you spread its props on your own elements. + +## Installation + + + + + CLI + Manual + + + +```bash +npx shadcn@latest add @coss/use-sortable +``` + + + + + + + +Copy and paste the following code into your project. + + + +Update the import paths to match your project setup. + + + + + + + +## Usage + +### Sortable list + +The value is an object of containers, each an ordered array of items. A single list is one container. + +```tsx +import { useSortable } from "@/hooks/use-sortable"; + +function Steps() { + const sortable = useSortable({ + defaultValue: { steps: ["Draft", "Review", "Ship"] }, + }); + + return ( + <> +
+ {sortable.value.steps?.map((step) => ( +
+ {step} +
+ ))} +
+
+ + ); +} +``` + +Strings and numbers are their own ids. For objects, the hook reads `item.id`, or pass `getItemId`. + +### Board with columns + +Give each column its own container key. Items move within a column and between columns. Use `value` and `onValueChange` to control the state, and `canMove` to refuse a move, for example into a full column. + +```tsx +const [board, setBoard] = useState({ + todo: [{ id: "1", title: "Update pricing page" }], + doing: [], + done: [], +}); + +const sortable = useSortable({ + value: board, + onValueChange: setBoard, + canMove: ({ from, to }) => + from.container === to.container || board[to.container].length < 3, + getItemLabel: (task) => task.title, +}); + +return columns.map((column) => ( +
+ {sortable.value[column.id]?.map((task) => ( + + {task.title} + + ))} +
+)); +``` + +`onValueChange` runs once per move, on drop. While dragging, `sortable.value` already shows the item at its new place, so render from it rather than from your own state. + +### Drag overlay + +Render a copy of the dragged item with `getOverlayProps`. It follows the pointer above everything, so columns with their own scroll area do not clip it, and it is inert, so screen readers and the keyboard skip it. The item in the list stays as a placeholder and gets a `data-dragging` attribute. + +```tsx +{sortable.active?.reason === "pointer" && ( + + {sortable.active.item.title} + +)} +``` + +Without an overlay, the item still moves through the list as you drag. + +### Drag handle + +Set `handle` to start drags and keyboard moves only from a handle. Use it when items hold their own buttons or links. + +```tsx +const sortable = useSortable({ handle: true, value, onValueChange }); + + + + {task.title} +; +``` + +Add `dragFromItem` to also drag from anywhere on the item with a mouse or finger, like Trello or Jira, while the keyboard keeps using the handle. A quick click still reaches the item's own buttons and links, so a card can open a dialog on click. + +```tsx +const sortable = useSortable({ handle: true, dragFromItem: true, value, onValueChange }); +``` + +Without a handle, presses on links, buttons and form fields inside an item do not start a drag. Add `data-sortable-ignore` to any other element that should not. With `dragFromItem`, only form fields and elements with `data-sortable-ignore` never start a drag. + +## Interaction + +| Input | Behavior | +|-------|----------| +| Mouse or pen | Drag starts after the pointer moves 5px, so clicks still work | +| Touch | Press and hold for 250ms, then drag. A quick swipe scrolls as usual | +| `Space` or `Enter` | Pick up the focused item, or drop it | +| Arrow keys | Move the picked-up item within its container, or to the previous or next container on the page, skipping any that refuse it | +| `Home` / `End` | Move to the start or end of the container | +| `Escape` | Cancel and put the item back | + +When `canMove` refuses a move, the item stays where it was, the refusing container gets `data-drop-refused`, and screen readers hear why. The signal is yours to show or hide: nothing changes on screen unless you style `data-drop-refused`, and returning `undefined` from `getAnnouncement` for `refuse` events silences the message. Dragging near the edge of a scrollable container or of the page scrolls it. Set `autoScroll` to `false` to turn this off. Left and right arrows are mirrored in right-to-left layouts. + +## Accessibility + +Each item is focusable and described by the keyboard instructions. Every pick-up, move, drop, cancel and refused move is announced, for example "Moved Update pricing page to position 2 of 3 in In progress." Render `getAnnouncerProps` once, anywhere in the tree, so screen readers hear these messages. + +Name items and containers with `getItemLabel` and `getContainerLabel`, translate the instructions with `instructions`, and replace the messages with `getAnnouncement`. + +## API + +```tsx +function useSortable(options: UseSortableOptions): UseSortableReturn; +``` + +### Options + +| Option | Type | Default | Description | +|--------|------|---------|-------------| +| `value` | `Record` | | Items per container, in order. Controlled | +| `defaultValue` | `Record` | `{}` | Initial items when uncontrolled | +| `onValueChange` | `(value, details) => void` | | Called on drop when an item moved. `details` has `item`, `from`, `to` and `reason` | +| `getItemId` | `(item) => string` | the item, or `item.id` | Unique id for an item | +| `getItemLabel` | `(item) => string` | the id | Name of an item in announcements | +| `getContainerLabel` | `(container) => string` | the key | Name of a container in announcements | +| `canMove` | `({ item, from, to }) => boolean` | | Return `false` to refuse a move | +| `orientation` | `"vertical" \| "horizontal"` | `"vertical"` | Direction items flow inside a container | +| `handle` | `boolean` | `false` | Start moves only from `getHandleProps` | +| `dragFromItem` | `boolean` | `false` | With `handle`, also drag from anywhere on the item with mouse or touch | +| `disabled` | `boolean` | `false` | Turn off all moves | +| `autoScroll` | `boolean` | `true` | Scroll near the edges while dragging | +| `instructions` | `string` | English text | Keyboard instructions for screen readers | +| `getAnnouncement` | `(event) => string \| undefined` | English messages | Custom announcements | + +### Return value + +| Property | Type | Description | +|----------|------|-------------| +| `value` | `Record` | The value to render, with the dragged item at its current place | +| `active` | `{ id, item, from, to, reason, refused } \| null` | The item being moved, if any | +| `getContainerProps` | `(container) => props` | Spread on each container element | +| `getItemProps` | `(item) => props` | Spread on each item element | +| `getHandleProps` | `(item) => props` | Spread on the handle when `handle` is set | +| `getOverlayProps` | `() => props` | Spread on the drag overlay | +| `getAnnouncerProps` | `() => props` | Spread on one empty element for screen reader messages | + +A position is `{ container, index }`, where `index` is the item's place after the move. + +### Data attributes + +| Attribute | On | When | +|-----------|----|------| +| `data-dragging` | item | The item is being moved | +| `data-drop-target` | container | The moving item is over this container | +| `data-drop-refused` | container, item, overlay | The container under the item refused it through `canMove` | + +Style them with Tailwind, for example `data-dragging:opacity-50` or `data-drop-refused:bg-destructive/8`. + +### Helpers + +```tsx +import { + getSortableKeyboardTarget, + moveSortableItem, +} from "@/hooks/use-sortable"; + +// Move an item in a value, for example to apply a change from the server +const next = moveSortableItem(value, from, to); + +// Where a key press would move an item, or null +const target = getSortableKeyboardTarget(value, position, "ArrowDown"); +``` + +## Examples + +### List + + + +### Board with a limit + +The In progress column accepts at most two tasks. Drag a third card over it to see it refuse. + + diff --git a/apps/ui/mdx-components.tsx b/apps/ui/mdx-components.tsx index efb7b78f91..1328bcac16 100644 --- a/apps/ui/mdx-components.tsx +++ b/apps/ui/mdx-components.tsx @@ -25,6 +25,10 @@ import { CodeTabs } from "@/components/code-tabs"; import { ComponentPreview } from "@/components/component-preview"; import { ComponentSource } from "@/components/component-source"; import { MediaQueryDemo } from "@/components/media-query-demo"; +import { + SortableBoardDemo, + SortableListDemo, +} from "@/components/sortable-demo"; import { cn } from "@/lib/utils"; export const mdxComponents = { @@ -288,6 +292,8 @@ export const mdxComponents = { ); }, + SortableBoardDemo, + SortableListDemo, Step: ({ className, ...props }: React.ComponentProps<"h3">) => (

;\n touch: boolean;\n};\n\ntype Drag = SortableActive & {\n pointer?: { grab: Point; height: number; origin: Point; width: number };\n};\n\ntype Latest = {\n committed: SortableValue;\n getItemId: (item: Item) => string;\n options: UseSortableOptions;\n preview: SortableValue;\n};\n\nfunction defaultGetItemId(item: unknown): string {\n return typeof item === \"object\" && item !== null\n ? `${(item as { id: string | number }).id}`\n : `${item}`;\n}\n\nfunction locate(\n value: SortableValue,\n id: string,\n getItemId: (item: Item) => string,\n): SortablePosition | null {\n for (const [container, items] of Object.entries(value)) {\n const index = items.findIndex((item) => getItemId(item) === id);\n if (index !== -1) return { container, index };\n }\n return null;\n}\n\nfunction moveById(\n value: SortableValue,\n id: string,\n to: SortablePosition,\n getItemId: (item: Item) => string,\n): SortableValue {\n const from = locate(value, id, getItemId);\n return from ? moveSortableItem(value, from, to) : value;\n}\n\nfunction samePosition(a: SortablePosition, b: SortablePosition): boolean {\n return a.container === b.container && a.index === b.index;\n}\n\nfunction isInside(rect: DOMRect, point: Point): boolean {\n return (\n point.x >= rect.left &&\n point.x <= rect.right &&\n point.y >= rect.top &&\n point.y <= rect.bottom\n );\n}\n\nfunction isRtl(element: Element): boolean {\n return getComputedStyle(element).direction === \"rtl\";\n}\n\nfunction getMessage(\n type: SortableEvent[\"type\"],\n item: string,\n where: string,\n container: string,\n): string {\n return {\n cancel: `Move canceled. ${item} returned to ${where}.`,\n drop: `Dropped ${item} at ${where}.`,\n move: `Moved ${item} to ${where}.`,\n refuse: `${item} cannot move to ${container}.`,\n start: `Picked up ${item}, ${where}.`,\n }[type];\n}\n\nfunction getEdgeDelta(start: number, end: number, at: number): number {\n const edge = Math.min(SCROLL_EDGE, (end - start) / 4);\n if (at < start + edge) {\n return -Math.ceil(((start + edge - at) / edge) * SCROLL_SPEED);\n }\n if (at > end - edge) {\n return Math.ceil(((at - end + edge) / edge) * SCROLL_SPEED);\n }\n return 0;\n}\n\nfunction scrollNearEdges(point: Point): boolean {\n let node: Element | null = document.elementFromPoint(point.x, point.y);\n for (; node; node = node.parentElement) {\n const isRoot = node === document.scrollingElement;\n const { overflowX, overflowY } = getComputedStyle(node);\n if (!isRoot && !/auto|scroll|overlay/.test(overflowX + overflowY)) continue;\n const rect = isRoot\n ? new DOMRect(0, 0, window.innerWidth, window.innerHeight)\n : node.getBoundingClientRect();\n if (!isInside(rect, point)) continue;\n const { scrollLeft, scrollTop } = node;\n node.scrollTop += getEdgeDelta(rect.top, rect.bottom, point.y);\n node.scrollLeft += getEdgeDelta(rect.left, rect.right, point.x);\n if (node.scrollTop !== scrollTop || node.scrollLeft !== scrollLeft) {\n return true;\n }\n }\n return false;\n}\n\nexport type SortableValue = Record;\n\nexport type SortableOrientation = \"vertical\" | \"horizontal\";\n\nexport type SortableReason = \"pointer\" | \"keyboard\";\n\nexport type SortablePosition = {\n /** Key of the container in the value. */\n container: string;\n /** Index of the item in that container, after the move. */\n index: number;\n};\n\nexport type SortableMove = {\n item: Item;\n from: SortablePosition;\n to: SortablePosition;\n};\n\nexport type SortableChangeDetails = SortableMove & {\n reason: SortableReason;\n};\n\nexport type SortableActive = SortableChangeDetails & {\n id: string;\n /** The container that refused the item while it is over it, if any. */\n refused: string | null;\n};\n\nexport type SortableEvent = SortableChangeDetails & {\n type: \"start\" | \"move\" | \"drop\" | \"cancel\" | \"refuse\";\n /** The value at the moment of the event, with the item at `to`. */\n value: SortableValue;\n};\n\nexport type SortableRef = (\n element: HTMLElement | null,\n) => undefined | (() => void);\n\nexport type SortableProps = React.HTMLAttributes & {\n \"data-dragging\"?: \"\";\n \"data-drop-refused\"?: \"\";\n \"data-drop-target\"?: \"\";\n ref?: SortableRef;\n};\n\nexport type UseSortableOptions = {\n /** Items per container, in order. Controlled. */\n value?: SortableValue;\n /** Initial items per container when uncontrolled. */\n defaultValue?: SortableValue;\n /** Called once per completed move, on drop. */\n onValueChange?: (\n value: SortableValue,\n details: SortableChangeDetails,\n ) => void;\n /** Defaults to the item for strings and numbers, or its `id`. */\n getItemId?: (item: Item) => string;\n /** Name of an item in announcements. Defaults to its id. */\n getItemLabel?: (item: Item) => string;\n /** Name of a container in announcements. Defaults to its key. */\n getContainerLabel?: (container: string) => string;\n /** Return `false` to refuse a move, for example into a full column. */\n canMove?: (move: SortableMove) => boolean;\n /** Direction items flow inside a container. Defaults to `\"vertical\"`. */\n orientation?: SortableOrientation;\n /** Start moves from elements with `getHandleProps`. The keyboard uses the handle. */\n handle?: boolean;\n /** With `handle`, also start mouse and touch drags from anywhere on the item. */\n dragFromItem?: boolean;\n disabled?: boolean;\n /** Scroll near the edges while dragging. Defaults to `true`. */\n autoScroll?: boolean;\n /** Keyboard instructions for screen readers. */\n instructions?: string;\n /** Custom announcements. Return `undefined` to stay silent. */\n getAnnouncement?: (event: SortableEvent) => string | undefined;\n};\n\nexport type UseSortableReturn = {\n /** The value to render. While dragging, it shows the item at its new place. */\n value: SortableValue;\n active: SortableActive | null;\n getContainerProps: (container: string) => SortableProps;\n getItemProps: (item: Item) => SortableProps;\n getHandleProps: (item: Item) => SortableProps;\n getOverlayProps: () => SortableProps;\n getAnnouncerProps: () => SortableProps;\n};\n\nexport function moveSortableItem(\n value: SortableValue,\n from: SortablePosition,\n to: SortablePosition,\n): SortableValue {\n const source = value[from.container];\n const destination = value[to.container];\n if (!source || !destination || samePosition(from, to)) return value;\n if (from.index < 0 || from.index >= source.length) return value;\n\n const nextSource = source.filter((_, index) => index !== from.index);\n const nextDestination =\n from.container === to.container ? nextSource : [...destination];\n const index = Math.max(0, Math.min(to.index, nextDestination.length));\n nextDestination.splice(index, 0, source[from.index] as Item);\n\n return {\n ...value,\n [from.container]: nextSource,\n [to.container]: nextDestination,\n };\n}\n\nexport function getSortableKeyboardTarget(\n value: SortableValue,\n position: SortablePosition,\n key: string,\n options: {\n canMoveTo?: (position: SortablePosition) => boolean;\n /** Container keys in the order they appear. Defaults to the key order. */\n containers?: readonly string[];\n direction?: \"ltr\" | \"rtl\";\n orientation?: SortableOrientation;\n } = {},\n): SortablePosition | null {\n const {\n canMoveTo = (): boolean => true,\n containers = Object.keys(value),\n direction = \"ltr\",\n orientation = \"vertical\",\n } = options;\n const list = value[position.container];\n if (!list) return null;\n\n const [left, right] =\n direction === \"rtl\"\n ? [\"ArrowRight\", \"ArrowLeft\"]\n : [\"ArrowLeft\", \"ArrowRight\"];\n const vertical = orientation === \"vertical\";\n const [previous, next] = vertical ? [\"ArrowUp\", \"ArrowDown\"] : [left, right];\n const [before, after] = vertical ? [left, right] : [\"ArrowUp\", \"ArrowDown\"];\n\n const within = (index: number): SortablePosition | null => {\n const target = { container: position.container, index };\n const valid = index >= 0 && index < list.length && index !== position.index;\n return valid && canMoveTo(target) ? target : null;\n };\n\n if (key === previous) return within(position.index - 1);\n if (key === next) return within(position.index + 1);\n if (key === \"Home\") return within(0);\n if (key === \"End\") return within(list.length - 1);\n if (key !== before && key !== after) return null;\n\n const step = key === before ? -1 : 1;\n for (\n let index = containers.indexOf(position.container) + step;\n index >= 0 && index < containers.length;\n index += step\n ) {\n const container = containers[index] as string;\n const length = value[container]?.length ?? 0;\n const target = { container, index: Math.min(position.index, length) };\n if (canMoveTo(target)) return target;\n }\n return null;\n}\n\nexport function useSortable(\n options: UseSortableOptions,\n): UseSortableReturn {\n const {\n value: valueProp,\n defaultValue,\n getItemId = defaultGetItemId as (item: Item) => string,\n handle = false,\n dragFromItem = false,\n disabled = false,\n instructions = DEFAULT_INSTRUCTIONS,\n } = options;\n\n const [uncontrolledValue, setUncontrolledValue] = useState<\n SortableValue\n >(() => defaultValue ?? {});\n const committed = valueProp ?? uncontrolledValue;\n const [drag, setDrag] = useState | null>(null);\n const [announcement, setAnnouncement] = useState(\"\");\n const instructionsId = useId();\n\n const preview = useMemo(\n (): SortableValue =>\n drag ? moveById(committed, drag.id, drag.to, getItemId) : committed,\n [committed, drag, getItemId],\n );\n\n const latest = useRef>(null as unknown as Latest);\n latest.current = { committed, getItemId, options, preview };\n const dragRef = useRef | null>(null);\n const focusRef = useRef(null);\n const overlayRef = useRef(null);\n const refs = useRef(new Map()).current;\n const elements = useRef({\n container: new Map(),\n handle: new Map(),\n item: new Map(),\n }).current;\n\n const [controller] = useState(() => {\n let session: Session | null = null;\n let frame = 0;\n let dragStyle: HTMLStyleElement | null = null;\n\n const setDragState = (next: Drag | null): void => {\n dragRef.current = next;\n setDrag(next);\n if (dragStyle && next?.pointer) {\n const cursor = next.refused ? \"not-allowed\" : \"grabbing\";\n dragStyle.textContent = `*, *::before, *::after { cursor: ${cursor} !important; user-select: none !important; -webkit-user-select: none !important; }`;\n }\n };\n\n const isAllowed = (current: Drag, to: SortablePosition): boolean => {\n const { canMove } = latest.current.options;\n return (\n !canMove ||\n samePosition(current.from, to) ||\n canMove({ from: current.from, item: current.item, to })\n );\n };\n\n const announce = (\n type: SortableEvent[\"type\"],\n current: Drag,\n to: SortablePosition,\n value: SortableValue,\n ): void => {\n const { getItemId, options } = latest.current;\n const { from, item, reason } = current;\n const count = value[to.container]?.length ?? 0;\n const container =\n options.getContainerLabel?.(to.container) ?? to.container;\n const message = options.getAnnouncement\n ? options.getAnnouncement({ from, item, reason, to, type, value })\n : getMessage(\n type,\n (options.getItemLabel ?? getItemId)(item),\n `position ${to.index + 1} of ${count} in ${container}`,\n container,\n );\n if (!message) return;\n setAnnouncement((previous) =>\n previous === message ? `${message} ` : message,\n );\n };\n\n const begin = (id: string, reason: SortableReason): Drag | null => {\n const { committed, getItemId } = latest.current;\n const from = locate(committed, id, getItemId);\n if (!from) return null;\n const item = committed[from.container]?.[from.index] as Item;\n return { from, id, item, reason, refused: null, to: from };\n };\n\n const finish = (commit: boolean): void => {\n const current = dragRef.current;\n if (!current) return;\n const { committed, getItemId, options } = latest.current;\n const from = locate(committed, current.id, getItemId);\n setDragState(null);\n if (!from) return;\n const moved = commit && !samePosition(from, current.to);\n const next = moved\n ? moveSortableItem(committed, from, current.to)\n : committed;\n if (moved) {\n if (options.value === undefined) setUncontrolledValue(next);\n const { item, reason, to } = current;\n options.onValueChange?.(next, { from, item, reason, to });\n }\n announce(\n commit ? \"drop\" : \"cancel\",\n current,\n moved ? current.to : from,\n next,\n );\n };\n\n const update = (): void => {\n const current = dragRef.current;\n if (!current?.pointer || !session) return;\n const { grab, height, width } = current.pointer;\n const { x, y } = session.point;\n if (overlayRef.current) {\n overlayRef.current.style.transform = `translate3d(${x - grab.x}px, ${y - grab.y}px, 0)`;\n }\n\n const { getItemId, options, preview } = latest.current;\n let target: [string, HTMLElement] | undefined;\n let smallest = Number.POSITIVE_INFINITY;\n for (const [key, element] of elements.container) {\n const rect = element.getBoundingClientRect();\n const area = rect.width * rect.height;\n if (\n key in preview &&\n isInside(rect, session.point) &&\n area < smallest\n ) {\n target = [key, element];\n smallest = area;\n }\n }\n if (!target) {\n if (current.refused) setDragState({ ...current, refused: null });\n return;\n }\n\n const [container, element] = target;\n const vertical = options.orientation !== \"horizontal\";\n const reversed = !vertical && isRtl(element);\n const center = vertical\n ? y - grab.y + height / 2\n : x - grab.x + width / 2;\n let index = 0;\n for (const item of preview[container] ?? []) {\n const id = getItemId(item);\n const rect =\n id === current.id\n ? undefined\n : elements.item.get(id)?.getBoundingClientRect();\n if (!rect) continue;\n const middle = vertical\n ? rect.top + rect.height / 2\n : rect.left + rect.width / 2;\n if (reversed ? middle > center : middle < center) index++;\n }\n\n const to = { container, index };\n const same = samePosition(to, current.to);\n if (same || isAllowed(current, to)) {\n if (!same || current.refused) {\n setDragState({ ...current, refused: null, to });\n }\n } else if (current.refused !== container) {\n setDragState({ ...current, refused: container });\n announce(\"refuse\", current, to, preview);\n }\n };\n\n const tick = (): void => {\n frame = 0;\n if (!dragRef.current?.pointer || !session) return;\n const scrolled =\n latest.current.options.autoScroll !== false &&\n scrollNearEdges(session.point);\n update();\n if (scrolled) schedule();\n };\n\n const schedule = (): void => {\n if (!frame) frame = requestAnimationFrame(tick);\n };\n\n const preventTouchScroll = (event: TouchEvent): void => {\n if (dragRef.current?.reason === \"pointer\") event.preventDefault();\n };\n\n const endSession = (): void => {\n if (!session) return;\n clearTimeout(session.timer);\n session.element.removeEventListener(\"touchmove\", preventTouchScroll);\n for (const type of WINDOW_EVENTS) {\n window.removeEventListener(type, onWindowEvent, true);\n }\n cancelAnimationFrame(frame);\n frame = 0;\n session = null;\n if (!dragStyle) return;\n dragStyle.remove();\n dragStyle = null;\n const stopClick = (event: Event): void => {\n event.preventDefault();\n event.stopPropagation();\n };\n window.addEventListener(\"click\", stopClick, {\n capture: true,\n once: true,\n });\n setTimeout(() => window.removeEventListener(\"click\", stopClick, true), 0);\n };\n\n const activate = (): void => {\n if (!session) return;\n const current = begin(session.id, \"pointer\");\n if (!current) {\n endSession();\n return;\n }\n const element = elements.item.get(session.id) ?? session.element;\n const rect = element.getBoundingClientRect();\n const grab = {\n x: session.start.x - rect.left,\n y: session.start.y - rect.top,\n };\n dragStyle = document.createElement(\"style\");\n document.head.append(dragStyle);\n window.getSelection()?.removeAllRanges();\n const next: Drag = {\n ...current,\n pointer: {\n grab,\n height: rect.height,\n origin: { x: session.point.x - grab.x, y: session.point.y - grab.y },\n width: rect.width,\n },\n };\n setDragState(next);\n announce(\"start\", next, next.from, latest.current.committed);\n schedule();\n };\n\n function onWindowEvent(event: Event): void {\n if (!session) return;\n const dragging = dragRef.current?.reason === \"pointer\";\n switch (event.type) {\n case \"scroll\":\n if (dragging) schedule();\n return;\n case \"selectstart\":\n case \"contextmenu\":\n if (dragging || session.touch) event.preventDefault();\n return;\n case \"dragstart\":\n event.preventDefault();\n return;\n case \"keydown\":\n if (dragging && (event as KeyboardEvent).key === \"Escape\") {\n event.preventDefault();\n event.stopPropagation();\n finish(false);\n endSession();\n }\n return;\n }\n\n const pointer = event as PointerEvent;\n if (pointer.pointerId !== session.pointerId) return;\n session.point = { x: pointer.clientX, y: pointer.clientY };\n if (event.type === \"pointermove\") {\n const { point, start, touch } = session;\n const distance = Math.hypot(point.x - start.x, point.y - start.y);\n if (dragging) schedule();\n else if (distance > (touch ? TOUCH_TOLERANCE : DRAG_DISTANCE)) {\n if (touch) endSession();\n else activate();\n }\n return;\n }\n if (dragging) {\n if (event.type === \"pointerup\") update();\n finish(event.type === \"pointerup\");\n }\n endSession();\n }\n\n const onPointerDown = (\n event: React.PointerEvent,\n id: string,\n ignore: string,\n ): void => {\n const element = event.currentTarget;\n const ignored = (event.target as Element).closest?.(ignore);\n if (\n latest.current.options.disabled ||\n session ||\n dragRef.current ||\n !event.isPrimary ||\n event.button !== 0 ||\n (ignored && ignored !== element && element.contains(ignored))\n ) {\n return;\n }\n const start = { x: event.clientX, y: event.clientY };\n const touch = event.pointerType === \"touch\";\n session = {\n element,\n id,\n point: start,\n pointerId: event.pointerId,\n start,\n touch,\n };\n for (const type of WINDOW_EVENTS) {\n window.addEventListener(type, onWindowEvent, true);\n }\n if (touch) {\n element.addEventListener(\"touchmove\", preventTouchScroll, {\n passive: false,\n });\n session.timer = setTimeout(activate, TOUCH_DELAY);\n }\n };\n\n const onKeyDown = (\n event: React.KeyboardEvent,\n id: string,\n ): void => {\n const current = dragRef.current;\n const toggle = event.key === \" \" || event.key === \"Enter\";\n if (latest.current.options.disabled) return;\n\n if (!current) {\n if (!toggle || event.repeat || event.target !== event.currentTarget) {\n return;\n }\n event.preventDefault();\n const next = begin(id, \"keyboard\");\n if (!next) return;\n focusRef.current = id;\n setDragState(next);\n announce(\"start\", next, next.from, latest.current.committed);\n return;\n }\n\n if (current.reason !== \"keyboard\" || current.id !== id) return;\n if (toggle || event.key === \"Escape\" || event.key === \"Tab\") {\n event.preventDefault();\n if (event.key === \"Escape\") finish(false);\n else if (toggle && !event.repeat) finish(true);\n return;\n }\n\n const { committed, getItemId, options } = latest.current;\n const value = moveById(committed, id, current.to, getItemId);\n const containers = Object.keys(value).sort((a, b) => {\n const first = elements.container.get(a);\n const second = elements.container.get(b);\n if (!first || !second) return Number(!first) - Number(!second);\n return first.compareDocumentPosition(second) &\n Node.DOCUMENT_POSITION_FOLLOWING\n ? -1\n : 1;\n });\n let rejected = null as SortablePosition | null;\n const to = getSortableKeyboardTarget(value, current.to, event.key, {\n canMoveTo: (target: SortablePosition): boolean => {\n const allowed = isAllowed(current, target);\n if (!allowed && !rejected) rejected = target;\n return allowed;\n },\n containers,\n direction: isRtl(event.currentTarget) ? \"rtl\" : \"ltr\",\n orientation: options.orientation,\n });\n if (\n to ||\n event.key.startsWith(\"Arrow\") ||\n [\"Home\", \"End\"].includes(event.key)\n ) {\n event.preventDefault();\n }\n if (to) {\n setDragState({ ...current, refused: null, to });\n announce(\"move\", current, to, moveById(committed, id, to, getItemId));\n } else if (rejected) {\n setDragState({ ...current, refused: rejected.container });\n announce(\"refuse\", current, rejected, value);\n }\n };\n\n const setOverlay: SortableRef = (element: HTMLElement | null) => {\n overlayRef.current = element;\n return () => {\n if (overlayRef.current === element) overlayRef.current = null;\n };\n };\n\n return {\n dispose: endSession,\n finish,\n onKeyDown,\n onPointerDown,\n setOverlay,\n };\n });\n\n const getRef = (kind: keyof typeof elements, key: string): SortableRef => {\n const cacheKey = `${kind}:${key}`;\n let ref = refs.get(cacheKey);\n if (!ref) {\n const map = elements[kind];\n ref = (element: HTMLElement | null): ReturnType => {\n if (!element) return;\n map.set(key, element);\n return () => {\n if (map.get(key) === element) map.delete(key);\n };\n };\n refs.set(cacheKey, ref);\n }\n return ref;\n };\n\n useEffect(() => controller.dispose, [controller]);\n\n useEffect(() => {\n const current = dragRef.current;\n if (current && (disabled || !locate(committed, current.id, getItemId))) {\n controller.finish(false);\n }\n }, [committed, controller, disabled, getItemId]);\n\n const keyboardDragging = drag?.reason === \"keyboard\";\n useEffect(() => {\n if (!keyboardDragging) return;\n const cancel = (): void => controller.finish(false);\n window.addEventListener(\"pointerdown\", cancel, true);\n return () => window.removeEventListener(\"pointerdown\", cancel, true);\n }, [controller, keyboardDragging]);\n\n useIsoLayoutEffect(() => {\n const id = focusRef.current;\n const element = id && elements[handle ? \"handle\" : \"item\"].get(id);\n if (!element) return;\n if (document.activeElement !== element) {\n element.focus({ preventScroll: true });\n }\n element.scrollIntoView?.({ block: \"nearest\", inline: \"nearest\" });\n if (!dragRef.current) focusRef.current = null;\n }, [drag, elements, handle, preview]);\n\n const getProps = (item: Item, kind: \"item\" | \"handle\"): SortableProps => {\n const id = getItemId(item);\n const dragging = drag?.id === id;\n const props: SortableProps = {\n \"data-dragging\": dragging ? \"\" : undefined,\n \"data-drop-refused\": dragging && drag?.refused ? \"\" : undefined,\n ref: getRef(kind, id),\n };\n if (kind === \"item\" && handle) {\n if (!dragFromItem) return props;\n return {\n ...props,\n onPointerDown: (event: React.PointerEvent): void =>\n controller.onPointerDown(event, id, FIELD_SELECTOR),\n style: { WebkitTouchCallout: \"none\" },\n };\n }\n return {\n ...props,\n \"aria-describedby\": instructionsId,\n \"aria-disabled\": disabled || undefined,\n \"aria-pressed\":\n dragging && drag?.reason === \"keyboard\" ? true : undefined,\n \"aria-roledescription\": \"sortable\",\n onKeyDown: (event: React.KeyboardEvent): void =>\n controller.onKeyDown(event, id),\n onPointerDown: (event: React.PointerEvent): void =>\n controller.onPointerDown(event, id, IGNORE_SELECTOR),\n role: \"button\",\n style: {\n touchAction: handle ? \"none\" : undefined,\n WebkitTouchCallout: \"none\",\n },\n tabIndex: disabled ? -1 : 0,\n };\n };\n\n return {\n active: drag,\n getAnnouncerProps: (): SortableProps => ({\n children: [\n createElement(\n \"span\",\n { id: instructionsId, key: \"instructions\" },\n instructions,\n ),\n createElement(\n \"span\",\n {\n \"aria-atomic\": true,\n \"aria-live\": \"assertive\",\n key: \"announcement\",\n role: \"status\",\n },\n announcement,\n ),\n ],\n style: visuallyHidden,\n }),\n getContainerProps: (container: string): SortableProps => ({\n \"data-drop-refused\": drag?.refused === container ? \"\" : undefined,\n \"data-drop-target\": drag?.to.container === container ? \"\" : undefined,\n ref: getRef(\"container\", container),\n }),\n getHandleProps: (item: Item): SortableProps => getProps(item, \"handle\"),\n getItemProps: (item: Item): SortableProps => getProps(item, \"item\"),\n getOverlayProps: (): SortableProps => {\n const pointer = drag?.pointer;\n return {\n \"aria-hidden\": true,\n \"data-drop-refused\": drag?.refused ? \"\" : undefined,\n ref: controller.setOverlay,\n inert: true,\n style: pointer\n ? {\n boxSizing: \"border-box\",\n height: pointer.height,\n left: 0,\n pointerEvents: \"none\",\n position: \"fixed\",\n top: 0,\n transform: `translate3d(${pointer.origin.x}px, ${pointer.origin.y}px, 0)`,\n width: pointer.width,\n }\n : { display: \"none\" },\n };\n },\n value: preview,\n };\n}\n", + "type": "registry:hook" + } + ], + "type": "registry:hook" +} \ No newline at end of file diff --git a/apps/ui/registry.json b/apps/ui/registry.json index 721a476fb5..32292cc839 100644 --- a/apps/ui/registry.json +++ b/apps/ui/registry.json @@ -12851,6 +12851,16 @@ ], "name": "use-copy-to-clipboard", "type": "registry:hook" + }, + { + "files": [ + { + "path": "registry/default/hooks/use-sortable.ts", + "type": "registry:hook" + } + ], + "name": "use-sortable", + "type": "registry:hook" } ], "name": "coss ui" diff --git a/apps/ui/registry/__index__.tsx b/apps/ui/registry/__index__.tsx index 13046a3c73..c872d08faa 100644 --- a/apps/ui/registry/__index__.tsx +++ b/apps/ui/registry/__index__.tsx @@ -10941,4 +10941,22 @@ export const Index: Record = { categories: undefined, meta: undefined, }, + "use-sortable": { + name: "use-sortable", + description: "", + type: "registry:hook", + registryDependencies: undefined, + files: [{ + path: "registry/default/hooks/use-sortable.ts", + type: "registry:hook", + target: "" + }], + component: React.lazy(async () => { + const mod = await import("@/registry/default/hooks/use-sortable.ts") + const exportName = Object.keys(mod).find(key => typeof mod[key] === 'function' || typeof mod[key] === 'object') || item.name + return { default: mod.default || mod[exportName] } + }), + categories: undefined, + meta: undefined, + }, } \ No newline at end of file diff --git a/apps/ui/registry/default/hooks/use-sortable.ts b/apps/ui/registry/default/hooks/use-sortable.ts new file mode 100644 index 0000000000..026bdc36c5 --- /dev/null +++ b/apps/ui/registry/default/hooks/use-sortable.ts @@ -0,0 +1,883 @@ +"use client"; + +import type * as React from "react"; +import { + createElement, + useEffect, + useId, + useLayoutEffect, + useMemo, + useRef, + useState, +} from "react"; + +const DRAG_DISTANCE = 5; +const TOUCH_DELAY = 250; +const TOUCH_TOLERANCE = 8; +const SCROLL_EDGE = 48; +const SCROLL_SPEED = 20; +const WINDOW_EVENTS: string[] = [ + "pointermove", + "pointerup", + "pointercancel", + "keydown", + "scroll", + "selectstart", + "contextmenu", + "dragstart", +]; +const FIELD_SELECTOR = + "input, select, textarea, [contenteditable]:not([contenteditable='false']), [data-sortable-ignore]"; +const IGNORE_SELECTOR = `a[href], button, ${FIELD_SELECTOR}`; +const DEFAULT_INSTRUCTIONS = + "Press Space or Enter to pick up an item. Use the arrow keys to move it, Space or Enter to drop it, and Escape to cancel."; + +const visuallyHidden: React.CSSProperties = { + border: 0, + clipPath: "inset(50%)", + height: 1, + margin: -1, + overflow: "hidden", + padding: 0, + position: "absolute", + whiteSpace: "nowrap", + width: 1, +}; + +const useIsoLayoutEffect: typeof useLayoutEffect = + typeof window === "undefined" ? useEffect : useLayoutEffect; + +type Point = { x: number; y: number }; + +type Session = { + element: HTMLElement; + id: string; + point: Point; + pointerId: number; + start: Point; + timer?: ReturnType; + touch: boolean; +}; + +type Drag = SortableActive & { + pointer?: { grab: Point; height: number; origin: Point; width: number }; +}; + +type Latest = { + committed: SortableValue; + getItemId: (item: Item) => string; + options: UseSortableOptions; + preview: SortableValue; +}; + +function defaultGetItemId(item: unknown): string { + return typeof item === "object" && item !== null + ? `${(item as { id: string | number }).id}` + : `${item}`; +} + +function locate( + value: SortableValue, + id: string, + getItemId: (item: Item) => string, +): SortablePosition | null { + for (const [container, items] of Object.entries(value)) { + const index = items.findIndex((item) => getItemId(item) === id); + if (index !== -1) return { container, index }; + } + return null; +} + +function moveById( + value: SortableValue, + id: string, + to: SortablePosition, + getItemId: (item: Item) => string, +): SortableValue { + const from = locate(value, id, getItemId); + return from ? moveSortableItem(value, from, to) : value; +} + +function samePosition(a: SortablePosition, b: SortablePosition): boolean { + return a.container === b.container && a.index === b.index; +} + +function isInside(rect: DOMRect, point: Point): boolean { + return ( + point.x >= rect.left && + point.x <= rect.right && + point.y >= rect.top && + point.y <= rect.bottom + ); +} + +function isRtl(element: Element): boolean { + return getComputedStyle(element).direction === "rtl"; +} + +function getMessage( + type: SortableEvent["type"], + item: string, + where: string, + container: string, +): string { + return { + cancel: `Move canceled. ${item} returned to ${where}.`, + drop: `Dropped ${item} at ${where}.`, + move: `Moved ${item} to ${where}.`, + refuse: `${item} cannot move to ${container}.`, + start: `Picked up ${item}, ${where}.`, + }[type]; +} + +function getEdgeDelta(start: number, end: number, at: number): number { + const edge = Math.min(SCROLL_EDGE, (end - start) / 4); + if (at < start + edge) { + return -Math.ceil(((start + edge - at) / edge) * SCROLL_SPEED); + } + if (at > end - edge) { + return Math.ceil(((at - end + edge) / edge) * SCROLL_SPEED); + } + return 0; +} + +function scrollNearEdges(point: Point): boolean { + let node: Element | null = document.elementFromPoint(point.x, point.y); + for (; node; node = node.parentElement) { + const isRoot = node === document.scrollingElement; + const { overflowX, overflowY } = getComputedStyle(node); + if (!isRoot && !/auto|scroll|overlay/.test(overflowX + overflowY)) continue; + const rect = isRoot + ? new DOMRect(0, 0, window.innerWidth, window.innerHeight) + : node.getBoundingClientRect(); + if (!isInside(rect, point)) continue; + const { scrollLeft, scrollTop } = node; + node.scrollTop += getEdgeDelta(rect.top, rect.bottom, point.y); + node.scrollLeft += getEdgeDelta(rect.left, rect.right, point.x); + if (node.scrollTop !== scrollTop || node.scrollLeft !== scrollLeft) { + return true; + } + } + return false; +} + +export type SortableValue = Record; + +export type SortableOrientation = "vertical" | "horizontal"; + +export type SortableReason = "pointer" | "keyboard"; + +export type SortablePosition = { + /** Key of the container in the value. */ + container: string; + /** Index of the item in that container, after the move. */ + index: number; +}; + +export type SortableMove = { + item: Item; + from: SortablePosition; + to: SortablePosition; +}; + +export type SortableChangeDetails = SortableMove & { + reason: SortableReason; +}; + +export type SortableActive = SortableChangeDetails & { + id: string; + /** The container that refused the item while it is over it, if any. */ + refused: string | null; +}; + +export type SortableEvent = SortableChangeDetails & { + type: "start" | "move" | "drop" | "cancel" | "refuse"; + /** The value at the moment of the event, with the item at `to`. */ + value: SortableValue; +}; + +export type SortableRef = ( + element: HTMLElement | null, +) => undefined | (() => void); + +export type SortableProps = React.HTMLAttributes & { + "data-dragging"?: ""; + "data-drop-refused"?: ""; + "data-drop-target"?: ""; + ref?: SortableRef; +}; + +export type UseSortableOptions = { + /** Items per container, in order. Controlled. */ + value?: SortableValue; + /** Initial items per container when uncontrolled. */ + defaultValue?: SortableValue; + /** Called once per completed move, on drop. */ + onValueChange?: ( + value: SortableValue, + details: SortableChangeDetails, + ) => void; + /** Defaults to the item for strings and numbers, or its `id`. */ + getItemId?: (item: Item) => string; + /** Name of an item in announcements. Defaults to its id. */ + getItemLabel?: (item: Item) => string; + /** Name of a container in announcements. Defaults to its key. */ + getContainerLabel?: (container: string) => string; + /** Return `false` to refuse a move, for example into a full column. */ + canMove?: (move: SortableMove) => boolean; + /** Direction items flow inside a container. Defaults to `"vertical"`. */ + orientation?: SortableOrientation; + /** Start moves from elements with `getHandleProps`. The keyboard uses the handle. */ + handle?: boolean; + /** With `handle`, also start mouse and touch drags from anywhere on the item. */ + dragFromItem?: boolean; + disabled?: boolean; + /** Scroll near the edges while dragging. Defaults to `true`. */ + autoScroll?: boolean; + /** Keyboard instructions for screen readers. */ + instructions?: string; + /** Custom announcements. Return `undefined` to stay silent. */ + getAnnouncement?: (event: SortableEvent) => string | undefined; +}; + +export type UseSortableReturn = { + /** The value to render. While dragging, it shows the item at its new place. */ + value: SortableValue; + active: SortableActive | null; + getContainerProps: (container: string) => SortableProps; + getItemProps: (item: Item) => SortableProps; + getHandleProps: (item: Item) => SortableProps; + getOverlayProps: () => SortableProps; + getAnnouncerProps: () => SortableProps; +}; + +export function moveSortableItem( + value: SortableValue, + from: SortablePosition, + to: SortablePosition, +): SortableValue { + const source = value[from.container]; + const destination = value[to.container]; + if (!source || !destination || samePosition(from, to)) return value; + if (from.index < 0 || from.index >= source.length) return value; + + const nextSource = source.filter((_, index) => index !== from.index); + const nextDestination = + from.container === to.container ? nextSource : [...destination]; + const index = Math.max(0, Math.min(to.index, nextDestination.length)); + nextDestination.splice(index, 0, source[from.index] as Item); + + return { + ...value, + [from.container]: nextSource, + [to.container]: nextDestination, + }; +} + +export function getSortableKeyboardTarget( + value: SortableValue, + position: SortablePosition, + key: string, + options: { + canMoveTo?: (position: SortablePosition) => boolean; + /** Container keys in the order they appear. Defaults to the key order. */ + containers?: readonly string[]; + direction?: "ltr" | "rtl"; + orientation?: SortableOrientation; + } = {}, +): SortablePosition | null { + const { + canMoveTo = (): boolean => true, + containers = Object.keys(value), + direction = "ltr", + orientation = "vertical", + } = options; + const list = value[position.container]; + if (!list) return null; + + const [left, right] = + direction === "rtl" + ? ["ArrowRight", "ArrowLeft"] + : ["ArrowLeft", "ArrowRight"]; + const vertical = orientation === "vertical"; + const [previous, next] = vertical ? ["ArrowUp", "ArrowDown"] : [left, right]; + const [before, after] = vertical ? [left, right] : ["ArrowUp", "ArrowDown"]; + + const within = (index: number): SortablePosition | null => { + const target = { container: position.container, index }; + const valid = index >= 0 && index < list.length && index !== position.index; + return valid && canMoveTo(target) ? target : null; + }; + + if (key === previous) return within(position.index - 1); + if (key === next) return within(position.index + 1); + if (key === "Home") return within(0); + if (key === "End") return within(list.length - 1); + if (key !== before && key !== after) return null; + + const step = key === before ? -1 : 1; + for ( + let index = containers.indexOf(position.container) + step; + index >= 0 && index < containers.length; + index += step + ) { + const container = containers[index] as string; + const length = value[container]?.length ?? 0; + const target = { container, index: Math.min(position.index, length) }; + if (canMoveTo(target)) return target; + } + return null; +} + +export function useSortable( + options: UseSortableOptions, +): UseSortableReturn { + const { + value: valueProp, + defaultValue, + getItemId = defaultGetItemId as (item: Item) => string, + handle = false, + dragFromItem = false, + disabled = false, + instructions = DEFAULT_INSTRUCTIONS, + } = options; + + const [uncontrolledValue, setUncontrolledValue] = useState< + SortableValue + >(() => defaultValue ?? {}); + const committed = valueProp ?? uncontrolledValue; + const [drag, setDrag] = useState | null>(null); + const [announcement, setAnnouncement] = useState(""); + const instructionsId = useId(); + + const preview = useMemo( + (): SortableValue => + drag ? moveById(committed, drag.id, drag.to, getItemId) : committed, + [committed, drag, getItemId], + ); + + const latest = useRef>(null as unknown as Latest); + latest.current = { committed, getItemId, options, preview }; + const dragRef = useRef | null>(null); + const focusRef = useRef(null); + const overlayRef = useRef(null); + const refs = useRef(new Map()).current; + const elements = useRef({ + container: new Map(), + handle: new Map(), + item: new Map(), + }).current; + + const [controller] = useState(() => { + let session: Session | null = null; + let frame = 0; + let dragStyle: HTMLStyleElement | null = null; + + const setDragState = (next: Drag | null): void => { + dragRef.current = next; + setDrag(next); + if (dragStyle && next?.pointer) { + const cursor = next.refused ? "not-allowed" : "grabbing"; + dragStyle.textContent = `*, *::before, *::after { cursor: ${cursor} !important; user-select: none !important; -webkit-user-select: none !important; }`; + } + }; + + const isAllowed = (current: Drag, to: SortablePosition): boolean => { + const { canMove } = latest.current.options; + return ( + !canMove || + samePosition(current.from, to) || + canMove({ from: current.from, item: current.item, to }) + ); + }; + + const announce = ( + type: SortableEvent["type"], + current: Drag, + to: SortablePosition, + value: SortableValue, + ): void => { + const { getItemId, options } = latest.current; + const { from, item, reason } = current; + const count = value[to.container]?.length ?? 0; + const container = + options.getContainerLabel?.(to.container) ?? to.container; + const message = options.getAnnouncement + ? options.getAnnouncement({ from, item, reason, to, type, value }) + : getMessage( + type, + (options.getItemLabel ?? getItemId)(item), + `position ${to.index + 1} of ${count} in ${container}`, + container, + ); + if (!message) return; + setAnnouncement((previous) => + previous === message ? `${message} ` : message, + ); + }; + + const begin = (id: string, reason: SortableReason): Drag | null => { + const { committed, getItemId } = latest.current; + const from = locate(committed, id, getItemId); + if (!from) return null; + const item = committed[from.container]?.[from.index] as Item; + return { from, id, item, reason, refused: null, to: from }; + }; + + const finish = (commit: boolean): void => { + const current = dragRef.current; + if (!current) return; + const { committed, getItemId, options } = latest.current; + const from = locate(committed, current.id, getItemId); + setDragState(null); + if (!from) return; + const moved = commit && !samePosition(from, current.to); + const next = moved + ? moveSortableItem(committed, from, current.to) + : committed; + if (moved) { + if (options.value === undefined) setUncontrolledValue(next); + const { item, reason, to } = current; + options.onValueChange?.(next, { from, item, reason, to }); + } + announce( + commit ? "drop" : "cancel", + current, + moved ? current.to : from, + next, + ); + }; + + const update = (): void => { + const current = dragRef.current; + if (!current?.pointer || !session) return; + const { grab, height, width } = current.pointer; + const { x, y } = session.point; + if (overlayRef.current) { + overlayRef.current.style.transform = `translate3d(${x - grab.x}px, ${y - grab.y}px, 0)`; + } + + const { getItemId, options, preview } = latest.current; + let target: [string, HTMLElement] | undefined; + let smallest = Number.POSITIVE_INFINITY; + for (const [key, element] of elements.container) { + const rect = element.getBoundingClientRect(); + const area = rect.width * rect.height; + if ( + key in preview && + isInside(rect, session.point) && + area < smallest + ) { + target = [key, element]; + smallest = area; + } + } + if (!target) { + if (current.refused) setDragState({ ...current, refused: null }); + return; + } + + const [container, element] = target; + const vertical = options.orientation !== "horizontal"; + const reversed = !vertical && isRtl(element); + const center = vertical + ? y - grab.y + height / 2 + : x - grab.x + width / 2; + let index = 0; + for (const item of preview[container] ?? []) { + const id = getItemId(item); + const rect = + id === current.id + ? undefined + : elements.item.get(id)?.getBoundingClientRect(); + if (!rect) continue; + const middle = vertical + ? rect.top + rect.height / 2 + : rect.left + rect.width / 2; + if (reversed ? middle > center : middle < center) index++; + } + + const to = { container, index }; + const same = samePosition(to, current.to); + if (same || isAllowed(current, to)) { + if (!same || current.refused) { + setDragState({ ...current, refused: null, to }); + } + } else if (current.refused !== container) { + setDragState({ ...current, refused: container }); + announce("refuse", current, to, preview); + } + }; + + const tick = (): void => { + frame = 0; + if (!dragRef.current?.pointer || !session) return; + const scrolled = + latest.current.options.autoScroll !== false && + scrollNearEdges(session.point); + update(); + if (scrolled) schedule(); + }; + + const schedule = (): void => { + if (!frame) frame = requestAnimationFrame(tick); + }; + + const preventTouchScroll = (event: TouchEvent): void => { + if (dragRef.current?.reason === "pointer") event.preventDefault(); + }; + + const endSession = (): void => { + if (!session) return; + clearTimeout(session.timer); + session.element.removeEventListener("touchmove", preventTouchScroll); + for (const type of WINDOW_EVENTS) { + window.removeEventListener(type, onWindowEvent, true); + } + cancelAnimationFrame(frame); + frame = 0; + session = null; + if (!dragStyle) return; + dragStyle.remove(); + dragStyle = null; + const stopClick = (event: Event): void => { + event.preventDefault(); + event.stopPropagation(); + }; + window.addEventListener("click", stopClick, { + capture: true, + once: true, + }); + setTimeout(() => window.removeEventListener("click", stopClick, true), 0); + }; + + const activate = (): void => { + if (!session) return; + const current = begin(session.id, "pointer"); + if (!current) { + endSession(); + return; + } + const element = elements.item.get(session.id) ?? session.element; + const rect = element.getBoundingClientRect(); + const grab = { + x: session.start.x - rect.left, + y: session.start.y - rect.top, + }; + dragStyle = document.createElement("style"); + document.head.append(dragStyle); + window.getSelection()?.removeAllRanges(); + const next: Drag = { + ...current, + pointer: { + grab, + height: rect.height, + origin: { x: session.point.x - grab.x, y: session.point.y - grab.y }, + width: rect.width, + }, + }; + setDragState(next); + announce("start", next, next.from, latest.current.committed); + schedule(); + }; + + function onWindowEvent(event: Event): void { + if (!session) return; + const dragging = dragRef.current?.reason === "pointer"; + switch (event.type) { + case "scroll": + if (dragging) schedule(); + return; + case "selectstart": + case "contextmenu": + if (dragging || session.touch) event.preventDefault(); + return; + case "dragstart": + event.preventDefault(); + return; + case "keydown": + if (dragging && (event as KeyboardEvent).key === "Escape") { + event.preventDefault(); + event.stopPropagation(); + finish(false); + endSession(); + } + return; + } + + const pointer = event as PointerEvent; + if (pointer.pointerId !== session.pointerId) return; + session.point = { x: pointer.clientX, y: pointer.clientY }; + if (event.type === "pointermove") { + const { point, start, touch } = session; + const distance = Math.hypot(point.x - start.x, point.y - start.y); + if (dragging) schedule(); + else if (distance > (touch ? TOUCH_TOLERANCE : DRAG_DISTANCE)) { + if (touch) endSession(); + else activate(); + } + return; + } + if (dragging) { + if (event.type === "pointerup") update(); + finish(event.type === "pointerup"); + } + endSession(); + } + + const onPointerDown = ( + event: React.PointerEvent, + id: string, + ignore: string, + ): void => { + const element = event.currentTarget; + const ignored = (event.target as Element).closest?.(ignore); + if ( + latest.current.options.disabled || + session || + dragRef.current || + !event.isPrimary || + event.button !== 0 || + (ignored && ignored !== element && element.contains(ignored)) + ) { + return; + } + const start = { x: event.clientX, y: event.clientY }; + const touch = event.pointerType === "touch"; + session = { + element, + id, + point: start, + pointerId: event.pointerId, + start, + touch, + }; + for (const type of WINDOW_EVENTS) { + window.addEventListener(type, onWindowEvent, true); + } + if (touch) { + element.addEventListener("touchmove", preventTouchScroll, { + passive: false, + }); + session.timer = setTimeout(activate, TOUCH_DELAY); + } + }; + + const onKeyDown = ( + event: React.KeyboardEvent, + id: string, + ): void => { + const current = dragRef.current; + const toggle = event.key === " " || event.key === "Enter"; + if (latest.current.options.disabled) return; + + if (!current) { + if (!toggle || event.repeat || event.target !== event.currentTarget) { + return; + } + event.preventDefault(); + const next = begin(id, "keyboard"); + if (!next) return; + focusRef.current = id; + setDragState(next); + announce("start", next, next.from, latest.current.committed); + return; + } + + if (current.reason !== "keyboard" || current.id !== id) return; + if (toggle || event.key === "Escape" || event.key === "Tab") { + event.preventDefault(); + if (event.key === "Escape") finish(false); + else if (toggle && !event.repeat) finish(true); + return; + } + + const { committed, getItemId, options } = latest.current; + const value = moveById(committed, id, current.to, getItemId); + const containers = Object.keys(value).sort((a, b) => { + const first = elements.container.get(a); + const second = elements.container.get(b); + if (!first || !second) return Number(!first) - Number(!second); + return first.compareDocumentPosition(second) & + Node.DOCUMENT_POSITION_FOLLOWING + ? -1 + : 1; + }); + let rejected = null as SortablePosition | null; + const to = getSortableKeyboardTarget(value, current.to, event.key, { + canMoveTo: (target: SortablePosition): boolean => { + const allowed = isAllowed(current, target); + if (!allowed && !rejected) rejected = target; + return allowed; + }, + containers, + direction: isRtl(event.currentTarget) ? "rtl" : "ltr", + orientation: options.orientation, + }); + if ( + to || + event.key.startsWith("Arrow") || + ["Home", "End"].includes(event.key) + ) { + event.preventDefault(); + } + if (to) { + setDragState({ ...current, refused: null, to }); + announce("move", current, to, moveById(committed, id, to, getItemId)); + } else if (rejected) { + setDragState({ ...current, refused: rejected.container }); + announce("refuse", current, rejected, value); + } + }; + + const setOverlay: SortableRef = (element: HTMLElement | null) => { + overlayRef.current = element; + return () => { + if (overlayRef.current === element) overlayRef.current = null; + }; + }; + + return { + dispose: endSession, + finish, + onKeyDown, + onPointerDown, + setOverlay, + }; + }); + + const getRef = (kind: keyof typeof elements, key: string): SortableRef => { + const cacheKey = `${kind}:${key}`; + let ref = refs.get(cacheKey); + if (!ref) { + const map = elements[kind]; + ref = (element: HTMLElement | null): ReturnType => { + if (!element) return; + map.set(key, element); + return () => { + if (map.get(key) === element) map.delete(key); + }; + }; + refs.set(cacheKey, ref); + } + return ref; + }; + + useEffect(() => controller.dispose, [controller]); + + useEffect(() => { + const current = dragRef.current; + if (current && (disabled || !locate(committed, current.id, getItemId))) { + controller.finish(false); + } + }, [committed, controller, disabled, getItemId]); + + const keyboardDragging = drag?.reason === "keyboard"; + useEffect(() => { + if (!keyboardDragging) return; + const cancel = (): void => controller.finish(false); + window.addEventListener("pointerdown", cancel, true); + return () => window.removeEventListener("pointerdown", cancel, true); + }, [controller, keyboardDragging]); + + useIsoLayoutEffect(() => { + const id = focusRef.current; + const element = id && elements[handle ? "handle" : "item"].get(id); + if (!element) return; + if (document.activeElement !== element) { + element.focus({ preventScroll: true }); + } + element.scrollIntoView?.({ block: "nearest", inline: "nearest" }); + if (!dragRef.current) focusRef.current = null; + }, [drag, elements, handle, preview]); + + const getProps = (item: Item, kind: "item" | "handle"): SortableProps => { + const id = getItemId(item); + const dragging = drag?.id === id; + const props: SortableProps = { + "data-dragging": dragging ? "" : undefined, + "data-drop-refused": dragging && drag?.refused ? "" : undefined, + ref: getRef(kind, id), + }; + if (kind === "item" && handle) { + if (!dragFromItem) return props; + return { + ...props, + onPointerDown: (event: React.PointerEvent): void => + controller.onPointerDown(event, id, FIELD_SELECTOR), + style: { WebkitTouchCallout: "none" }, + }; + } + return { + ...props, + "aria-describedby": instructionsId, + "aria-disabled": disabled || undefined, + "aria-pressed": + dragging && drag?.reason === "keyboard" ? true : undefined, + "aria-roledescription": "sortable", + onKeyDown: (event: React.KeyboardEvent): void => + controller.onKeyDown(event, id), + onPointerDown: (event: React.PointerEvent): void => + controller.onPointerDown(event, id, IGNORE_SELECTOR), + role: "button", + style: { + touchAction: handle ? "none" : undefined, + WebkitTouchCallout: "none", + }, + tabIndex: disabled ? -1 : 0, + }; + }; + + return { + active: drag, + getAnnouncerProps: (): SortableProps => ({ + children: [ + createElement( + "span", + { id: instructionsId, key: "instructions" }, + instructions, + ), + createElement( + "span", + { + "aria-atomic": true, + "aria-live": "assertive", + key: "announcement", + role: "status", + }, + announcement, + ), + ], + style: visuallyHidden, + }), + getContainerProps: (container: string): SortableProps => ({ + "data-drop-refused": drag?.refused === container ? "" : undefined, + "data-drop-target": drag?.to.container === container ? "" : undefined, + ref: getRef("container", container), + }), + getHandleProps: (item: Item): SortableProps => getProps(item, "handle"), + getItemProps: (item: Item): SortableProps => getProps(item, "item"), + getOverlayProps: (): SortableProps => { + const pointer = drag?.pointer; + return { + "aria-hidden": true, + "data-drop-refused": drag?.refused ? "" : undefined, + ref: controller.setOverlay, + inert: true, + style: pointer + ? { + boxSizing: "border-box", + height: pointer.height, + left: 0, + pointerEvents: "none", + position: "fixed", + top: 0, + transform: `translate3d(${pointer.origin.x}px, ${pointer.origin.y}px, 0)`, + width: pointer.width, + } + : { display: "none" }, + }; + }, + value: preview, + }; +} diff --git a/apps/ui/registry/registry-hooks.ts b/apps/ui/registry/registry-hooks.ts index 2768327afa..e1212477fa 100644 --- a/apps/ui/registry/registry-hooks.ts +++ b/apps/ui/registry/registry-hooks.ts @@ -31,4 +31,14 @@ export const hooks: Registry["items"] = [ name: "use-copy-to-clipboard", type: "registry:hook", }, + { + files: [ + { + path: "hooks/use-sortable.ts", + type: "registry:hook", + }, + ], + name: "use-sortable", + type: "registry:hook", + }, ]; diff --git a/apps/ui/tests/hooks/use-sortable.test.ts b/apps/ui/tests/hooks/use-sortable.test.ts new file mode 100644 index 0000000000..9b45ea80a8 --- /dev/null +++ b/apps/ui/tests/hooks/use-sortable.test.ts @@ -0,0 +1,214 @@ +import { describe, expect, it } from "bun:test"; +import { + getSortableKeyboardTarget, + moveSortableItem, +} from "../../registry/default/hooks/use-sortable"; + +const board = { + todo: ["a", "b", "c"], + doing: ["d"], + done: [] as string[], +}; + +describe("moveSortableItem", () => { + it("moves an item forward within a container", () => { + const next = moveSortableItem( + board, + { container: "todo", index: 0 }, + { container: "todo", index: 2 }, + ); + expect(next.todo).toEqual(["b", "c", "a"]); + }); + + it("moves an item backward within a container", () => { + const next = moveSortableItem( + board, + { container: "todo", index: 2 }, + { container: "todo", index: 0 }, + ); + expect(next.todo).toEqual(["c", "a", "b"]); + }); + + it("moves an item to another container", () => { + const next = moveSortableItem( + board, + { container: "todo", index: 1 }, + { container: "doing", index: 0 }, + ); + expect(next.todo).toEqual(["a", "c"]); + expect(next.doing).toEqual(["b", "d"]); + }); + + it("moves an item into an empty container", () => { + const next = moveSortableItem( + board, + { container: "doing", index: 0 }, + { container: "done", index: 0 }, + ); + expect(next.doing).toEqual([]); + expect(next.done).toEqual(["d"]); + }); + + it("clamps the target index to the container size", () => { + const next = moveSortableItem( + board, + { container: "todo", index: 0 }, + { container: "doing", index: 10 }, + ); + expect(next.doing).toEqual(["d", "a"]); + }); + + it("returns the same value when nothing moves", () => { + expect( + moveSortableItem( + board, + { container: "todo", index: 1 }, + { container: "todo", index: 1 }, + ), + ).toBe(board); + expect( + moveSortableItem( + board, + { container: "todo", index: 5 }, + { container: "doing", index: 0 }, + ), + ).toBe(board); + expect( + moveSortableItem( + board, + { container: "todo", index: 0 }, + { container: "missing", index: 0 }, + ), + ).toBe(board); + }); + + it("does not mutate the input", () => { + const value = { list: ["a", "b"] }; + moveSortableItem( + value, + { container: "list", index: 0 }, + { container: "list", index: 1 }, + ); + expect(value.list).toEqual(["a", "b"]); + }); +}); + +describe("getSortableKeyboardTarget", () => { + it("moves up and down within a vertical container", () => { + const position = { container: "todo", index: 1 }; + expect(getSortableKeyboardTarget(board, position, "ArrowDown")).toEqual({ + container: "todo", + index: 2, + }); + expect(getSortableKeyboardTarget(board, position, "ArrowUp")).toEqual({ + container: "todo", + index: 0, + }); + }); + + it("stops at the ends of a container", () => { + expect( + getSortableKeyboardTarget( + board, + { container: "todo", index: 0 }, + "ArrowUp", + ), + ).toBeNull(); + expect( + getSortableKeyboardTarget( + board, + { container: "todo", index: 2 }, + "ArrowDown", + ), + ).toBeNull(); + }); + + it("jumps to the start and end with Home and End", () => { + const position = { container: "todo", index: 1 }; + expect(getSortableKeyboardTarget(board, position, "Home")).toEqual({ + container: "todo", + index: 0, + }); + expect(getSortableKeyboardTarget(board, position, "End")).toEqual({ + container: "todo", + index: 2, + }); + }); + + it("moves to the next and previous container, keeping the index in range", () => { + expect( + getSortableKeyboardTarget( + board, + { container: "todo", index: 2 }, + "ArrowRight", + ), + ).toEqual({ container: "doing", index: 1 }); + expect( + getSortableKeyboardTarget( + board, + { container: "doing", index: 0 }, + "ArrowLeft", + ), + ).toEqual({ container: "todo", index: 0 }); + expect( + getSortableKeyboardTarget( + board, + { container: "done", index: 0 }, + "ArrowRight", + ), + ).toBeNull(); + }); + + it("skips containers that refuse the item", () => { + expect( + getSortableKeyboardTarget( + board, + { container: "todo", index: 0 }, + "ArrowRight", + { canMoveTo: (target) => target.container !== "doing" }, + ), + ).toEqual({ container: "done", index: 0 }); + }); + + it("follows the given container order instead of the key order", () => { + expect( + getSortableKeyboardTarget( + board, + { container: "done", index: 0 }, + "ArrowRight", + { containers: ["done", "todo", "doing"] }, + ), + ).toEqual({ container: "todo", index: 0 }); + }); + + it("mirrors left and right in right-to-left layouts", () => { + expect( + getSortableKeyboardTarget( + board, + { container: "doing", index: 0 }, + "ArrowLeft", + { direction: "rtl" }, + ), + ).toEqual({ container: "done", index: 0 }); + }); + + it("swaps the axes for horizontal containers", () => { + const rows = { first: ["a", "b"], second: ["c"] }; + expect( + getSortableKeyboardTarget( + rows, + { container: "first", index: 0 }, + "ArrowRight", + { orientation: "horizontal" }, + ), + ).toEqual({ container: "first", index: 1 }); + expect( + getSortableKeyboardTarget( + rows, + { container: "first", index: 1 }, + "ArrowDown", + { orientation: "horizontal" }, + ), + ).toEqual({ container: "second", index: 1 }); + }); +}); diff --git a/packages/ui/src/hooks/use-sortable.ts b/packages/ui/src/hooks/use-sortable.ts new file mode 100644 index 0000000000..026bdc36c5 --- /dev/null +++ b/packages/ui/src/hooks/use-sortable.ts @@ -0,0 +1,883 @@ +"use client"; + +import type * as React from "react"; +import { + createElement, + useEffect, + useId, + useLayoutEffect, + useMemo, + useRef, + useState, +} from "react"; + +const DRAG_DISTANCE = 5; +const TOUCH_DELAY = 250; +const TOUCH_TOLERANCE = 8; +const SCROLL_EDGE = 48; +const SCROLL_SPEED = 20; +const WINDOW_EVENTS: string[] = [ + "pointermove", + "pointerup", + "pointercancel", + "keydown", + "scroll", + "selectstart", + "contextmenu", + "dragstart", +]; +const FIELD_SELECTOR = + "input, select, textarea, [contenteditable]:not([contenteditable='false']), [data-sortable-ignore]"; +const IGNORE_SELECTOR = `a[href], button, ${FIELD_SELECTOR}`; +const DEFAULT_INSTRUCTIONS = + "Press Space or Enter to pick up an item. Use the arrow keys to move it, Space or Enter to drop it, and Escape to cancel."; + +const visuallyHidden: React.CSSProperties = { + border: 0, + clipPath: "inset(50%)", + height: 1, + margin: -1, + overflow: "hidden", + padding: 0, + position: "absolute", + whiteSpace: "nowrap", + width: 1, +}; + +const useIsoLayoutEffect: typeof useLayoutEffect = + typeof window === "undefined" ? useEffect : useLayoutEffect; + +type Point = { x: number; y: number }; + +type Session = { + element: HTMLElement; + id: string; + point: Point; + pointerId: number; + start: Point; + timer?: ReturnType; + touch: boolean; +}; + +type Drag = SortableActive & { + pointer?: { grab: Point; height: number; origin: Point; width: number }; +}; + +type Latest = { + committed: SortableValue; + getItemId: (item: Item) => string; + options: UseSortableOptions; + preview: SortableValue; +}; + +function defaultGetItemId(item: unknown): string { + return typeof item === "object" && item !== null + ? `${(item as { id: string | number }).id}` + : `${item}`; +} + +function locate( + value: SortableValue, + id: string, + getItemId: (item: Item) => string, +): SortablePosition | null { + for (const [container, items] of Object.entries(value)) { + const index = items.findIndex((item) => getItemId(item) === id); + if (index !== -1) return { container, index }; + } + return null; +} + +function moveById( + value: SortableValue, + id: string, + to: SortablePosition, + getItemId: (item: Item) => string, +): SortableValue { + const from = locate(value, id, getItemId); + return from ? moveSortableItem(value, from, to) : value; +} + +function samePosition(a: SortablePosition, b: SortablePosition): boolean { + return a.container === b.container && a.index === b.index; +} + +function isInside(rect: DOMRect, point: Point): boolean { + return ( + point.x >= rect.left && + point.x <= rect.right && + point.y >= rect.top && + point.y <= rect.bottom + ); +} + +function isRtl(element: Element): boolean { + return getComputedStyle(element).direction === "rtl"; +} + +function getMessage( + type: SortableEvent["type"], + item: string, + where: string, + container: string, +): string { + return { + cancel: `Move canceled. ${item} returned to ${where}.`, + drop: `Dropped ${item} at ${where}.`, + move: `Moved ${item} to ${where}.`, + refuse: `${item} cannot move to ${container}.`, + start: `Picked up ${item}, ${where}.`, + }[type]; +} + +function getEdgeDelta(start: number, end: number, at: number): number { + const edge = Math.min(SCROLL_EDGE, (end - start) / 4); + if (at < start + edge) { + return -Math.ceil(((start + edge - at) / edge) * SCROLL_SPEED); + } + if (at > end - edge) { + return Math.ceil(((at - end + edge) / edge) * SCROLL_SPEED); + } + return 0; +} + +function scrollNearEdges(point: Point): boolean { + let node: Element | null = document.elementFromPoint(point.x, point.y); + for (; node; node = node.parentElement) { + const isRoot = node === document.scrollingElement; + const { overflowX, overflowY } = getComputedStyle(node); + if (!isRoot && !/auto|scroll|overlay/.test(overflowX + overflowY)) continue; + const rect = isRoot + ? new DOMRect(0, 0, window.innerWidth, window.innerHeight) + : node.getBoundingClientRect(); + if (!isInside(rect, point)) continue; + const { scrollLeft, scrollTop } = node; + node.scrollTop += getEdgeDelta(rect.top, rect.bottom, point.y); + node.scrollLeft += getEdgeDelta(rect.left, rect.right, point.x); + if (node.scrollTop !== scrollTop || node.scrollLeft !== scrollLeft) { + return true; + } + } + return false; +} + +export type SortableValue = Record; + +export type SortableOrientation = "vertical" | "horizontal"; + +export type SortableReason = "pointer" | "keyboard"; + +export type SortablePosition = { + /** Key of the container in the value. */ + container: string; + /** Index of the item in that container, after the move. */ + index: number; +}; + +export type SortableMove = { + item: Item; + from: SortablePosition; + to: SortablePosition; +}; + +export type SortableChangeDetails = SortableMove & { + reason: SortableReason; +}; + +export type SortableActive = SortableChangeDetails & { + id: string; + /** The container that refused the item while it is over it, if any. */ + refused: string | null; +}; + +export type SortableEvent = SortableChangeDetails & { + type: "start" | "move" | "drop" | "cancel" | "refuse"; + /** The value at the moment of the event, with the item at `to`. */ + value: SortableValue; +}; + +export type SortableRef = ( + element: HTMLElement | null, +) => undefined | (() => void); + +export type SortableProps = React.HTMLAttributes & { + "data-dragging"?: ""; + "data-drop-refused"?: ""; + "data-drop-target"?: ""; + ref?: SortableRef; +}; + +export type UseSortableOptions = { + /** Items per container, in order. Controlled. */ + value?: SortableValue; + /** Initial items per container when uncontrolled. */ + defaultValue?: SortableValue; + /** Called once per completed move, on drop. */ + onValueChange?: ( + value: SortableValue, + details: SortableChangeDetails, + ) => void; + /** Defaults to the item for strings and numbers, or its `id`. */ + getItemId?: (item: Item) => string; + /** Name of an item in announcements. Defaults to its id. */ + getItemLabel?: (item: Item) => string; + /** Name of a container in announcements. Defaults to its key. */ + getContainerLabel?: (container: string) => string; + /** Return `false` to refuse a move, for example into a full column. */ + canMove?: (move: SortableMove) => boolean; + /** Direction items flow inside a container. Defaults to `"vertical"`. */ + orientation?: SortableOrientation; + /** Start moves from elements with `getHandleProps`. The keyboard uses the handle. */ + handle?: boolean; + /** With `handle`, also start mouse and touch drags from anywhere on the item. */ + dragFromItem?: boolean; + disabled?: boolean; + /** Scroll near the edges while dragging. Defaults to `true`. */ + autoScroll?: boolean; + /** Keyboard instructions for screen readers. */ + instructions?: string; + /** Custom announcements. Return `undefined` to stay silent. */ + getAnnouncement?: (event: SortableEvent) => string | undefined; +}; + +export type UseSortableReturn = { + /** The value to render. While dragging, it shows the item at its new place. */ + value: SortableValue; + active: SortableActive | null; + getContainerProps: (container: string) => SortableProps; + getItemProps: (item: Item) => SortableProps; + getHandleProps: (item: Item) => SortableProps; + getOverlayProps: () => SortableProps; + getAnnouncerProps: () => SortableProps; +}; + +export function moveSortableItem( + value: SortableValue, + from: SortablePosition, + to: SortablePosition, +): SortableValue { + const source = value[from.container]; + const destination = value[to.container]; + if (!source || !destination || samePosition(from, to)) return value; + if (from.index < 0 || from.index >= source.length) return value; + + const nextSource = source.filter((_, index) => index !== from.index); + const nextDestination = + from.container === to.container ? nextSource : [...destination]; + const index = Math.max(0, Math.min(to.index, nextDestination.length)); + nextDestination.splice(index, 0, source[from.index] as Item); + + return { + ...value, + [from.container]: nextSource, + [to.container]: nextDestination, + }; +} + +export function getSortableKeyboardTarget( + value: SortableValue, + position: SortablePosition, + key: string, + options: { + canMoveTo?: (position: SortablePosition) => boolean; + /** Container keys in the order they appear. Defaults to the key order. */ + containers?: readonly string[]; + direction?: "ltr" | "rtl"; + orientation?: SortableOrientation; + } = {}, +): SortablePosition | null { + const { + canMoveTo = (): boolean => true, + containers = Object.keys(value), + direction = "ltr", + orientation = "vertical", + } = options; + const list = value[position.container]; + if (!list) return null; + + const [left, right] = + direction === "rtl" + ? ["ArrowRight", "ArrowLeft"] + : ["ArrowLeft", "ArrowRight"]; + const vertical = orientation === "vertical"; + const [previous, next] = vertical ? ["ArrowUp", "ArrowDown"] : [left, right]; + const [before, after] = vertical ? [left, right] : ["ArrowUp", "ArrowDown"]; + + const within = (index: number): SortablePosition | null => { + const target = { container: position.container, index }; + const valid = index >= 0 && index < list.length && index !== position.index; + return valid && canMoveTo(target) ? target : null; + }; + + if (key === previous) return within(position.index - 1); + if (key === next) return within(position.index + 1); + if (key === "Home") return within(0); + if (key === "End") return within(list.length - 1); + if (key !== before && key !== after) return null; + + const step = key === before ? -1 : 1; + for ( + let index = containers.indexOf(position.container) + step; + index >= 0 && index < containers.length; + index += step + ) { + const container = containers[index] as string; + const length = value[container]?.length ?? 0; + const target = { container, index: Math.min(position.index, length) }; + if (canMoveTo(target)) return target; + } + return null; +} + +export function useSortable( + options: UseSortableOptions, +): UseSortableReturn { + const { + value: valueProp, + defaultValue, + getItemId = defaultGetItemId as (item: Item) => string, + handle = false, + dragFromItem = false, + disabled = false, + instructions = DEFAULT_INSTRUCTIONS, + } = options; + + const [uncontrolledValue, setUncontrolledValue] = useState< + SortableValue + >(() => defaultValue ?? {}); + const committed = valueProp ?? uncontrolledValue; + const [drag, setDrag] = useState | null>(null); + const [announcement, setAnnouncement] = useState(""); + const instructionsId = useId(); + + const preview = useMemo( + (): SortableValue => + drag ? moveById(committed, drag.id, drag.to, getItemId) : committed, + [committed, drag, getItemId], + ); + + const latest = useRef>(null as unknown as Latest); + latest.current = { committed, getItemId, options, preview }; + const dragRef = useRef | null>(null); + const focusRef = useRef(null); + const overlayRef = useRef(null); + const refs = useRef(new Map()).current; + const elements = useRef({ + container: new Map(), + handle: new Map(), + item: new Map(), + }).current; + + const [controller] = useState(() => { + let session: Session | null = null; + let frame = 0; + let dragStyle: HTMLStyleElement | null = null; + + const setDragState = (next: Drag | null): void => { + dragRef.current = next; + setDrag(next); + if (dragStyle && next?.pointer) { + const cursor = next.refused ? "not-allowed" : "grabbing"; + dragStyle.textContent = `*, *::before, *::after { cursor: ${cursor} !important; user-select: none !important; -webkit-user-select: none !important; }`; + } + }; + + const isAllowed = (current: Drag, to: SortablePosition): boolean => { + const { canMove } = latest.current.options; + return ( + !canMove || + samePosition(current.from, to) || + canMove({ from: current.from, item: current.item, to }) + ); + }; + + const announce = ( + type: SortableEvent["type"], + current: Drag, + to: SortablePosition, + value: SortableValue, + ): void => { + const { getItemId, options } = latest.current; + const { from, item, reason } = current; + const count = value[to.container]?.length ?? 0; + const container = + options.getContainerLabel?.(to.container) ?? to.container; + const message = options.getAnnouncement + ? options.getAnnouncement({ from, item, reason, to, type, value }) + : getMessage( + type, + (options.getItemLabel ?? getItemId)(item), + `position ${to.index + 1} of ${count} in ${container}`, + container, + ); + if (!message) return; + setAnnouncement((previous) => + previous === message ? `${message} ` : message, + ); + }; + + const begin = (id: string, reason: SortableReason): Drag | null => { + const { committed, getItemId } = latest.current; + const from = locate(committed, id, getItemId); + if (!from) return null; + const item = committed[from.container]?.[from.index] as Item; + return { from, id, item, reason, refused: null, to: from }; + }; + + const finish = (commit: boolean): void => { + const current = dragRef.current; + if (!current) return; + const { committed, getItemId, options } = latest.current; + const from = locate(committed, current.id, getItemId); + setDragState(null); + if (!from) return; + const moved = commit && !samePosition(from, current.to); + const next = moved + ? moveSortableItem(committed, from, current.to) + : committed; + if (moved) { + if (options.value === undefined) setUncontrolledValue(next); + const { item, reason, to } = current; + options.onValueChange?.(next, { from, item, reason, to }); + } + announce( + commit ? "drop" : "cancel", + current, + moved ? current.to : from, + next, + ); + }; + + const update = (): void => { + const current = dragRef.current; + if (!current?.pointer || !session) return; + const { grab, height, width } = current.pointer; + const { x, y } = session.point; + if (overlayRef.current) { + overlayRef.current.style.transform = `translate3d(${x - grab.x}px, ${y - grab.y}px, 0)`; + } + + const { getItemId, options, preview } = latest.current; + let target: [string, HTMLElement] | undefined; + let smallest = Number.POSITIVE_INFINITY; + for (const [key, element] of elements.container) { + const rect = element.getBoundingClientRect(); + const area = rect.width * rect.height; + if ( + key in preview && + isInside(rect, session.point) && + area < smallest + ) { + target = [key, element]; + smallest = area; + } + } + if (!target) { + if (current.refused) setDragState({ ...current, refused: null }); + return; + } + + const [container, element] = target; + const vertical = options.orientation !== "horizontal"; + const reversed = !vertical && isRtl(element); + const center = vertical + ? y - grab.y + height / 2 + : x - grab.x + width / 2; + let index = 0; + for (const item of preview[container] ?? []) { + const id = getItemId(item); + const rect = + id === current.id + ? undefined + : elements.item.get(id)?.getBoundingClientRect(); + if (!rect) continue; + const middle = vertical + ? rect.top + rect.height / 2 + : rect.left + rect.width / 2; + if (reversed ? middle > center : middle < center) index++; + } + + const to = { container, index }; + const same = samePosition(to, current.to); + if (same || isAllowed(current, to)) { + if (!same || current.refused) { + setDragState({ ...current, refused: null, to }); + } + } else if (current.refused !== container) { + setDragState({ ...current, refused: container }); + announce("refuse", current, to, preview); + } + }; + + const tick = (): void => { + frame = 0; + if (!dragRef.current?.pointer || !session) return; + const scrolled = + latest.current.options.autoScroll !== false && + scrollNearEdges(session.point); + update(); + if (scrolled) schedule(); + }; + + const schedule = (): void => { + if (!frame) frame = requestAnimationFrame(tick); + }; + + const preventTouchScroll = (event: TouchEvent): void => { + if (dragRef.current?.reason === "pointer") event.preventDefault(); + }; + + const endSession = (): void => { + if (!session) return; + clearTimeout(session.timer); + session.element.removeEventListener("touchmove", preventTouchScroll); + for (const type of WINDOW_EVENTS) { + window.removeEventListener(type, onWindowEvent, true); + } + cancelAnimationFrame(frame); + frame = 0; + session = null; + if (!dragStyle) return; + dragStyle.remove(); + dragStyle = null; + const stopClick = (event: Event): void => { + event.preventDefault(); + event.stopPropagation(); + }; + window.addEventListener("click", stopClick, { + capture: true, + once: true, + }); + setTimeout(() => window.removeEventListener("click", stopClick, true), 0); + }; + + const activate = (): void => { + if (!session) return; + const current = begin(session.id, "pointer"); + if (!current) { + endSession(); + return; + } + const element = elements.item.get(session.id) ?? session.element; + const rect = element.getBoundingClientRect(); + const grab = { + x: session.start.x - rect.left, + y: session.start.y - rect.top, + }; + dragStyle = document.createElement("style"); + document.head.append(dragStyle); + window.getSelection()?.removeAllRanges(); + const next: Drag = { + ...current, + pointer: { + grab, + height: rect.height, + origin: { x: session.point.x - grab.x, y: session.point.y - grab.y }, + width: rect.width, + }, + }; + setDragState(next); + announce("start", next, next.from, latest.current.committed); + schedule(); + }; + + function onWindowEvent(event: Event): void { + if (!session) return; + const dragging = dragRef.current?.reason === "pointer"; + switch (event.type) { + case "scroll": + if (dragging) schedule(); + return; + case "selectstart": + case "contextmenu": + if (dragging || session.touch) event.preventDefault(); + return; + case "dragstart": + event.preventDefault(); + return; + case "keydown": + if (dragging && (event as KeyboardEvent).key === "Escape") { + event.preventDefault(); + event.stopPropagation(); + finish(false); + endSession(); + } + return; + } + + const pointer = event as PointerEvent; + if (pointer.pointerId !== session.pointerId) return; + session.point = { x: pointer.clientX, y: pointer.clientY }; + if (event.type === "pointermove") { + const { point, start, touch } = session; + const distance = Math.hypot(point.x - start.x, point.y - start.y); + if (dragging) schedule(); + else if (distance > (touch ? TOUCH_TOLERANCE : DRAG_DISTANCE)) { + if (touch) endSession(); + else activate(); + } + return; + } + if (dragging) { + if (event.type === "pointerup") update(); + finish(event.type === "pointerup"); + } + endSession(); + } + + const onPointerDown = ( + event: React.PointerEvent, + id: string, + ignore: string, + ): void => { + const element = event.currentTarget; + const ignored = (event.target as Element).closest?.(ignore); + if ( + latest.current.options.disabled || + session || + dragRef.current || + !event.isPrimary || + event.button !== 0 || + (ignored && ignored !== element && element.contains(ignored)) + ) { + return; + } + const start = { x: event.clientX, y: event.clientY }; + const touch = event.pointerType === "touch"; + session = { + element, + id, + point: start, + pointerId: event.pointerId, + start, + touch, + }; + for (const type of WINDOW_EVENTS) { + window.addEventListener(type, onWindowEvent, true); + } + if (touch) { + element.addEventListener("touchmove", preventTouchScroll, { + passive: false, + }); + session.timer = setTimeout(activate, TOUCH_DELAY); + } + }; + + const onKeyDown = ( + event: React.KeyboardEvent, + id: string, + ): void => { + const current = dragRef.current; + const toggle = event.key === " " || event.key === "Enter"; + if (latest.current.options.disabled) return; + + if (!current) { + if (!toggle || event.repeat || event.target !== event.currentTarget) { + return; + } + event.preventDefault(); + const next = begin(id, "keyboard"); + if (!next) return; + focusRef.current = id; + setDragState(next); + announce("start", next, next.from, latest.current.committed); + return; + } + + if (current.reason !== "keyboard" || current.id !== id) return; + if (toggle || event.key === "Escape" || event.key === "Tab") { + event.preventDefault(); + if (event.key === "Escape") finish(false); + else if (toggle && !event.repeat) finish(true); + return; + } + + const { committed, getItemId, options } = latest.current; + const value = moveById(committed, id, current.to, getItemId); + const containers = Object.keys(value).sort((a, b) => { + const first = elements.container.get(a); + const second = elements.container.get(b); + if (!first || !second) return Number(!first) - Number(!second); + return first.compareDocumentPosition(second) & + Node.DOCUMENT_POSITION_FOLLOWING + ? -1 + : 1; + }); + let rejected = null as SortablePosition | null; + const to = getSortableKeyboardTarget(value, current.to, event.key, { + canMoveTo: (target: SortablePosition): boolean => { + const allowed = isAllowed(current, target); + if (!allowed && !rejected) rejected = target; + return allowed; + }, + containers, + direction: isRtl(event.currentTarget) ? "rtl" : "ltr", + orientation: options.orientation, + }); + if ( + to || + event.key.startsWith("Arrow") || + ["Home", "End"].includes(event.key) + ) { + event.preventDefault(); + } + if (to) { + setDragState({ ...current, refused: null, to }); + announce("move", current, to, moveById(committed, id, to, getItemId)); + } else if (rejected) { + setDragState({ ...current, refused: rejected.container }); + announce("refuse", current, rejected, value); + } + }; + + const setOverlay: SortableRef = (element: HTMLElement | null) => { + overlayRef.current = element; + return () => { + if (overlayRef.current === element) overlayRef.current = null; + }; + }; + + return { + dispose: endSession, + finish, + onKeyDown, + onPointerDown, + setOverlay, + }; + }); + + const getRef = (kind: keyof typeof elements, key: string): SortableRef => { + const cacheKey = `${kind}:${key}`; + let ref = refs.get(cacheKey); + if (!ref) { + const map = elements[kind]; + ref = (element: HTMLElement | null): ReturnType => { + if (!element) return; + map.set(key, element); + return () => { + if (map.get(key) === element) map.delete(key); + }; + }; + refs.set(cacheKey, ref); + } + return ref; + }; + + useEffect(() => controller.dispose, [controller]); + + useEffect(() => { + const current = dragRef.current; + if (current && (disabled || !locate(committed, current.id, getItemId))) { + controller.finish(false); + } + }, [committed, controller, disabled, getItemId]); + + const keyboardDragging = drag?.reason === "keyboard"; + useEffect(() => { + if (!keyboardDragging) return; + const cancel = (): void => controller.finish(false); + window.addEventListener("pointerdown", cancel, true); + return () => window.removeEventListener("pointerdown", cancel, true); + }, [controller, keyboardDragging]); + + useIsoLayoutEffect(() => { + const id = focusRef.current; + const element = id && elements[handle ? "handle" : "item"].get(id); + if (!element) return; + if (document.activeElement !== element) { + element.focus({ preventScroll: true }); + } + element.scrollIntoView?.({ block: "nearest", inline: "nearest" }); + if (!dragRef.current) focusRef.current = null; + }, [drag, elements, handle, preview]); + + const getProps = (item: Item, kind: "item" | "handle"): SortableProps => { + const id = getItemId(item); + const dragging = drag?.id === id; + const props: SortableProps = { + "data-dragging": dragging ? "" : undefined, + "data-drop-refused": dragging && drag?.refused ? "" : undefined, + ref: getRef(kind, id), + }; + if (kind === "item" && handle) { + if (!dragFromItem) return props; + return { + ...props, + onPointerDown: (event: React.PointerEvent): void => + controller.onPointerDown(event, id, FIELD_SELECTOR), + style: { WebkitTouchCallout: "none" }, + }; + } + return { + ...props, + "aria-describedby": instructionsId, + "aria-disabled": disabled || undefined, + "aria-pressed": + dragging && drag?.reason === "keyboard" ? true : undefined, + "aria-roledescription": "sortable", + onKeyDown: (event: React.KeyboardEvent): void => + controller.onKeyDown(event, id), + onPointerDown: (event: React.PointerEvent): void => + controller.onPointerDown(event, id, IGNORE_SELECTOR), + role: "button", + style: { + touchAction: handle ? "none" : undefined, + WebkitTouchCallout: "none", + }, + tabIndex: disabled ? -1 : 0, + }; + }; + + return { + active: drag, + getAnnouncerProps: (): SortableProps => ({ + children: [ + createElement( + "span", + { id: instructionsId, key: "instructions" }, + instructions, + ), + createElement( + "span", + { + "aria-atomic": true, + "aria-live": "assertive", + key: "announcement", + role: "status", + }, + announcement, + ), + ], + style: visuallyHidden, + }), + getContainerProps: (container: string): SortableProps => ({ + "data-drop-refused": drag?.refused === container ? "" : undefined, + "data-drop-target": drag?.to.container === container ? "" : undefined, + ref: getRef("container", container), + }), + getHandleProps: (item: Item): SortableProps => getProps(item, "handle"), + getItemProps: (item: Item): SortableProps => getProps(item, "item"), + getOverlayProps: (): SortableProps => { + const pointer = drag?.pointer; + return { + "aria-hidden": true, + "data-drop-refused": drag?.refused ? "" : undefined, + ref: controller.setOverlay, + inert: true, + style: pointer + ? { + boxSizing: "border-box", + height: pointer.height, + left: 0, + pointerEvents: "none", + position: "fixed", + top: 0, + transform: `translate3d(${pointer.origin.x}px, ${pointer.origin.y}px, 0)`, + width: pointer.width, + } + : { display: "none" }, + }; + }, + value: preview, + }; +} From 37dd304930c1a159158df080b630921777adcb42 Mon Sep 17 00:00:00 2001 From: Akash Vekariya <59219441+akashvekariya@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:04:19 +0530 Subject: [PATCH 2/3] fix: keep the refused outline inside board columns Co-Authored-By: Claude Opus 5.5 --- apps/ui/components/sortable-demo.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/ui/components/sortable-demo.tsx b/apps/ui/components/sortable-demo.tsx index 862053c5d3..f3bc014e65 100644 --- a/apps/ui/components/sortable-demo.tsx +++ b/apps/ui/components/sortable-demo.tsx @@ -101,7 +101,7 @@ export function SortableBoardDemo() { const tasks = sortable.value[column.id] ?? []; return (
From 9e6e0a3a65d8bae87370c0220fb194d6227d84eb Mon Sep 17 00:00:00 2001 From: Akash Vekariya <59219441+akashvekariya@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:18:16 +0530 Subject: [PATCH 3/3] feat: support nested lists, grids and long lists in useSortable - dragFrom ("item" | "handle" | "both") replaces handle and dragFromItem - orientation "grid" for wrapping layouts, with row moves by keyboard - A sortable list inside a sortable item no longer starts both drags - Drop index stays right when only visible rows are rendered - Value is typed by your state shape, so useState setters work as onValueChange - Docs for grids, nested lists, containers anywhere and long lists Co-Authored-By: Claude Opus 5.5 --- apps/ui/content/docs/hooks/use-sortable.mdx | 37 ++-- apps/ui/public/r/use-sortable.json | 2 +- .../ui/registry/default/hooks/use-sortable.ts | 164 ++++++++++++------ apps/ui/tests/hooks/use-sortable.test.ts | 21 +++ packages/ui/src/hooks/use-sortable.ts | 164 ++++++++++++------ 5 files changed, 277 insertions(+), 111 deletions(-) diff --git a/apps/ui/content/docs/hooks/use-sortable.mdx b/apps/ui/content/docs/hooks/use-sortable.mdx index a3e39fc4ce..5e07c66682 100644 --- a/apps/ui/content/docs/hooks/use-sortable.mdx +++ b/apps/ui/content/docs/hooks/use-sortable.mdx @@ -116,10 +116,14 @@ Without an overlay, the item still moves through the list as you drag. ### Drag handle -Set `handle` to start drags and keyboard moves only from a handle. Use it when items hold their own buttons or links. +`dragFrom` sets where a drag can start: + +- `"item"` (default): anywhere on the item. +- `"handle"`: only from the element with `getHandleProps`. Use it when items hold their own buttons or links. +- `"both"`: mouse and touch from anywhere on the item, like Trello or Jira, and the keyboard from the handle. A quick click still reaches the item's own buttons and links, so a card can open a dialog on click. ```tsx -const sortable = useSortable({ handle: true, value, onValueChange }); +const sortable = useSortable({ dragFrom: "handle", value, onValueChange });