diff --git a/apps/ui/components/sortable-demo.tsx b/apps/ui/components/sortable-demo.tsx new file mode 100644 index 000000000..f3bc014e6 --- /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 e2b2f230b..d99d5bcdd 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 000000000..5e07c6668 --- /dev/null +++ b/apps/ui/content/docs/hooks/use-sortable.mdx @@ -0,0 +1,250 @@ +--- +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 + +`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({ dragFrom: "handle", value, onValueChange }); + + + + {task.title} +; +``` + +With `"item"` or `"handle"`, presses on links, buttons and form fields inside an item do not start a drag. With `"both"`, only form fields do. Add `data-sortable-ignore` to any other element that should never start a drag. + +### Grids + +Set `orientation` to `"grid"` for items that wrap onto several rows, such as a gallery. Left and right arrows move one place, up and down move one row. + +```tsx +const sortable = useSortable({ orientation: "grid", value, onValueChange }); +``` + +### Nested lists + +A sortable list can live inside a sortable item, such as a checklist inside a card. Use one hook for the cards and another for the checklists. A press on a checklist row moves the row, a press elsewhere on the card moves the card. The same works for reordering the columns of a board: one hook for the columns, with `dragFrom: "handle"` on each column header, and one for the cards. + +### Containers anywhere + +Containers do not have to sit next to each other. Use one hook for everything that should exchange items, for example a backlog list in a sidebar and the columns of a board. + +### Long lists + +Only rendered items are measured, so lists that render just the visible rows (virtualized lists) still drop items at the right index. + +## 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. In a grid, up and down move one row | +| `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" \| "grid"` | `"vertical"` | How items flow inside a container | +| `dragFrom` | `"item" \| "handle" \| "both"` | `"item"` | Where a drag can start | +| `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 `dragFrom` is `"handle"` or `"both"` | +| `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 efb7b78f9..1328bcac1 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">) => (

= new WeakSet();\n\ntype Point = { x: number; y: number };\n\ntype Session = {\n element: HTMLElement;\n id: string;\n point: Point;\n pointerId: number;\n start: Point;\n timer?: ReturnType;\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: SortableItem) => 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\" | \"grid\";\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\n/** The item type of a value, for example `Task` for `{ todo: Task[] }`. */\nexport type SortableItem> =\n Value[keyof Value][number];\n\nexport type UseSortableOptions> = {\n /** Items per container, in order. Controlled. */\n value?: Value;\n /** Initial items per container when uncontrolled. */\n defaultValue?: Value;\n /** Called once per completed move, on drop. */\n onValueChange?: (\n value: Value,\n details: SortableChangeDetails>,\n ) => void;\n /** Defaults to the item for strings and numbers, or its `id`. */\n getItemId?: (item: SortableItem) => string;\n /** Name of an item in announcements. Defaults to its id. */\n getItemLabel?: (item: SortableItem) => 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 /**\n * Where a drag can start. `\"item\"`: anywhere on the item. `\"handle\"`: only\n * from `getHandleProps`. `\"both\"`: mouse and touch from anywhere, keyboard\n * from the handle. Defaults to `\"item\"`.\n */\n dragFrom?: \"item\" | \"handle\" | \"both\";\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?: (\n event: SortableEvent>,\n ) => string | undefined;\n};\n\nexport type UseSortableReturn> = {\n /** The value to render. While dragging, it shows the item at its new place. */\n value: Value & SortableValue>;\n active: SortableActive> | null;\n getContainerProps: (container: string) => SortableProps;\n getItemProps: (item: SortableItem) => SortableProps;\n getHandleProps: (item: SortableItem) => 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 /** Items per row when `orientation` is `\"grid\"`. */\n gridColumns?: number;\n orientation?: SortableOrientation;\n } = {},\n): SortablePosition | null {\n const {\n canMoveTo = (): boolean => true,\n containers = Object.keys(value),\n direction = \"ltr\",\n gridColumns = 1,\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 (orientation === \"grid\") {\n const columns = Math.max(1, gridColumns);\n const row = Math.floor(position.index / columns);\n const lastRow = Math.floor((list.length - 1) / columns);\n if (key === \"ArrowUp\") return within(position.index - columns);\n if (key === \"ArrowDown\") {\n if (row >= lastRow) return null;\n return within(Math.min(position.index + columns, list.length - 1));\n }\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 (orientation === \"grid\" || (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 type Item = SortableItem;\n const {\n value: valueProp,\n defaultValue,\n getItemId = defaultGetItemId as (item: Item) => string,\n dragFrom = \"item\",\n disabled = false,\n instructions = DEFAULT_INSTRUCTIONS,\n } = options;\n const handle = dragFrom !== \"item\";\n const dragFromItem = dragFrom === \"both\";\n\n const [uncontrolledValue, setUncontrolledValue] = useState<\n SortableValue\n >(() => (defaultValue ?? {}) as SortableValue);\n const committed =\n (valueProp as SortableValue | undefined) ?? 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 as unknown as Value, {\n from,\n item,\n reason,\n to,\n });\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 orientation = options.orientation ?? \"vertical\";\n const reversed = orientation !== \"vertical\" && isRtl(element);\n const centerX = x - grab.x + width / 2;\n const centerY = y - grab.y + height / 2;\n const isBefore = (rect: DOMRect): boolean => {\n const middleX = rect.left + rect.width / 2;\n const leading = reversed ? middleX > centerX : middleX < centerX;\n if (orientation === \"vertical\") {\n return rect.top + rect.height / 2 < centerY;\n }\n if (orientation === \"horizontal\") return leading;\n return (\n rect.bottom < centerY ||\n (rect.top <= centerY && centerY <= rect.bottom && leading)\n );\n };\n // Count positions among all items, so lists that only render the\n // visible part (virtualized) still get the right index.\n let lastBefore = -1;\n let firstAfter = -1;\n let position = 0;\n for (const item of preview[container] ?? []) {\n const id = getItemId(item);\n if (id === current.id) continue;\n const rect = elements.item.get(id)?.getBoundingClientRect();\n if (rect && isBefore(rect)) lastBefore = position;\n else if (rect && firstAfter === -1) firstAfter = position;\n position++;\n }\n const index =\n lastBefore !== -1 ? lastBefore + 1 : Math.max(firstAfter, 0);\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 claimedEvents.has(event.nativeEvent) ||\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 claimedEvents.add(event.nativeEvent);\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 countGridColumns = (list: readonly Item[]): number => {\n const { getItemId } = latest.current;\n let top: number | undefined;\n let count = 0;\n for (const item of list) {\n const rect = elements.item\n .get(getItemId(item))\n ?.getBoundingClientRect();\n if (!rect) continue;\n top ??= rect.top;\n if (Math.abs(rect.top - top) > 1) break;\n count++;\n }\n return Math.max(count, 1);\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 gridColumns: countGridColumns(value[current.to.container] ?? []),\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 as unknown as Value & SortableValue,\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 721a476fb..32292cc83 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 13046a3c7..c872d08fa 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 000000000..86db3f7f5 --- /dev/null +++ b/apps/ui/registry/default/hooks/use-sortable.ts @@ -0,0 +1,947 @@ +"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; + +const claimedEvents: WeakSet = new WeakSet(); + +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: SortableItem) => 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" | "grid"; + +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; +}; + +/** The item type of a value, for example `Task` for `{ todo: Task[] }`. */ +export type SortableItem> = + Value[keyof Value][number]; + +export type UseSortableOptions> = { + /** Items per container, in order. Controlled. */ + value?: Value; + /** Initial items per container when uncontrolled. */ + defaultValue?: Value; + /** Called once per completed move, on drop. */ + onValueChange?: ( + value: Value, + details: SortableChangeDetails>, + ) => void; + /** Defaults to the item for strings and numbers, or its `id`. */ + getItemId?: (item: SortableItem) => string; + /** Name of an item in announcements. Defaults to its id. */ + getItemLabel?: (item: SortableItem) => 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; + /** + * Where a drag can start. `"item"`: anywhere on the item. `"handle"`: only + * from `getHandleProps`. `"both"`: mouse and touch from anywhere, keyboard + * from the handle. Defaults to `"item"`. + */ + dragFrom?: "item" | "handle" | "both"; + 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: Value & SortableValue>; + active: SortableActive> | null; + getContainerProps: (container: string) => SortableProps; + getItemProps: (item: SortableItem) => SortableProps; + getHandleProps: (item: SortableItem) => 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"; + /** Items per row when `orientation` is `"grid"`. */ + gridColumns?: number; + orientation?: SortableOrientation; + } = {}, +): SortablePosition | null { + const { + canMoveTo = (): boolean => true, + containers = Object.keys(value), + direction = "ltr", + gridColumns = 1, + 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 (orientation === "grid") { + const columns = Math.max(1, gridColumns); + const row = Math.floor(position.index / columns); + const lastRow = Math.floor((list.length - 1) / columns); + if (key === "ArrowUp") return within(position.index - columns); + if (key === "ArrowDown") { + if (row >= lastRow) return null; + return within(Math.min(position.index + columns, list.length - 1)); + } + } + + 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 (orientation === "grid" || (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 { + type Item = SortableItem; + const { + value: valueProp, + defaultValue, + getItemId = defaultGetItemId as (item: Item) => string, + dragFrom = "item", + disabled = false, + instructions = DEFAULT_INSTRUCTIONS, + } = options; + const handle = dragFrom !== "item"; + const dragFromItem = dragFrom === "both"; + + const [uncontrolledValue, setUncontrolledValue] = useState< + SortableValue + >(() => (defaultValue ?? {}) as SortableValue); + const committed = + (valueProp as SortableValue | undefined) ?? 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 as unknown as Value, { + 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 orientation = options.orientation ?? "vertical"; + const reversed = orientation !== "vertical" && isRtl(element); + const centerX = x - grab.x + width / 2; + const centerY = y - grab.y + height / 2; + const isBefore = (rect: DOMRect): boolean => { + const middleX = rect.left + rect.width / 2; + const leading = reversed ? middleX > centerX : middleX < centerX; + if (orientation === "vertical") { + return rect.top + rect.height / 2 < centerY; + } + if (orientation === "horizontal") return leading; + return ( + rect.bottom < centerY || + (rect.top <= centerY && centerY <= rect.bottom && leading) + ); + }; + // Count positions among all items, so lists that only render the + // visible part (virtualized) still get the right index. + let lastBefore = -1; + let firstAfter = -1; + let position = 0; + for (const item of preview[container] ?? []) { + const id = getItemId(item); + if (id === current.id) continue; + const rect = elements.item.get(id)?.getBoundingClientRect(); + if (rect && isBefore(rect)) lastBefore = position; + else if (rect && firstAfter === -1) firstAfter = position; + position++; + } + const index = + lastBefore !== -1 ? lastBefore + 1 : Math.max(firstAfter, 0); + + 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 ( + claimedEvents.has(event.nativeEvent) || + latest.current.options.disabled || + session || + dragRef.current || + !event.isPrimary || + event.button !== 0 || + (ignored && ignored !== element && element.contains(ignored)) + ) { + return; + } + claimedEvents.add(event.nativeEvent); + 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 countGridColumns = (list: readonly Item[]): number => { + const { getItemId } = latest.current; + let top: number | undefined; + let count = 0; + for (const item of list) { + const rect = elements.item + .get(getItemId(item)) + ?.getBoundingClientRect(); + if (!rect) continue; + top ??= rect.top; + if (Math.abs(rect.top - top) > 1) break; + count++; + } + return Math.max(count, 1); + }; + + 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", + gridColumns: countGridColumns(value[current.to.container] ?? []), + 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 as unknown as Value & SortableValue, + }; +} diff --git a/apps/ui/registry/registry-hooks.ts b/apps/ui/registry/registry-hooks.ts index 2768327af..e1212477f 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 000000000..78e78c5bd --- /dev/null +++ b/apps/ui/tests/hooks/use-sortable.test.ts @@ -0,0 +1,235 @@ +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("moves by rows in a grid", () => { + const tiles = { grid: ["a", "b", "c", "d", "e", "f", "g"] }; + const grid = { gridColumns: 3, orientation: "grid" as const }; + const at = (index: number) => ({ container: "grid", index }); + expect(getSortableKeyboardTarget(tiles, at(1), "ArrowDown", grid)).toEqual( + at(4), + ); + expect(getSortableKeyboardTarget(tiles, at(4), "ArrowUp", grid)).toEqual( + at(1), + ); + expect(getSortableKeyboardTarget(tiles, at(5), "ArrowDown", grid)).toEqual( + at(6), + ); + expect( + getSortableKeyboardTarget(tiles, at(6), "ArrowDown", grid), + ).toBeNull(); + expect(getSortableKeyboardTarget(tiles, at(2), "ArrowRight", grid)).toEqual( + at(3), + ); + }); + + 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 000000000..86db3f7f5 --- /dev/null +++ b/packages/ui/src/hooks/use-sortable.ts @@ -0,0 +1,947 @@ +"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; + +const claimedEvents: WeakSet = new WeakSet(); + +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: SortableItem) => 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" | "grid"; + +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; +}; + +/** The item type of a value, for example `Task` for `{ todo: Task[] }`. */ +export type SortableItem> = + Value[keyof Value][number]; + +export type UseSortableOptions> = { + /** Items per container, in order. Controlled. */ + value?: Value; + /** Initial items per container when uncontrolled. */ + defaultValue?: Value; + /** Called once per completed move, on drop. */ + onValueChange?: ( + value: Value, + details: SortableChangeDetails>, + ) => void; + /** Defaults to the item for strings and numbers, or its `id`. */ + getItemId?: (item: SortableItem) => string; + /** Name of an item in announcements. Defaults to its id. */ + getItemLabel?: (item: SortableItem) => 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; + /** + * Where a drag can start. `"item"`: anywhere on the item. `"handle"`: only + * from `getHandleProps`. `"both"`: mouse and touch from anywhere, keyboard + * from the handle. Defaults to `"item"`. + */ + dragFrom?: "item" | "handle" | "both"; + 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: Value & SortableValue>; + active: SortableActive> | null; + getContainerProps: (container: string) => SortableProps; + getItemProps: (item: SortableItem) => SortableProps; + getHandleProps: (item: SortableItem) => 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"; + /** Items per row when `orientation` is `"grid"`. */ + gridColumns?: number; + orientation?: SortableOrientation; + } = {}, +): SortablePosition | null { + const { + canMoveTo = (): boolean => true, + containers = Object.keys(value), + direction = "ltr", + gridColumns = 1, + 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 (orientation === "grid") { + const columns = Math.max(1, gridColumns); + const row = Math.floor(position.index / columns); + const lastRow = Math.floor((list.length - 1) / columns); + if (key === "ArrowUp") return within(position.index - columns); + if (key === "ArrowDown") { + if (row >= lastRow) return null; + return within(Math.min(position.index + columns, list.length - 1)); + } + } + + 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 (orientation === "grid" || (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 { + type Item = SortableItem; + const { + value: valueProp, + defaultValue, + getItemId = defaultGetItemId as (item: Item) => string, + dragFrom = "item", + disabled = false, + instructions = DEFAULT_INSTRUCTIONS, + } = options; + const handle = dragFrom !== "item"; + const dragFromItem = dragFrom === "both"; + + const [uncontrolledValue, setUncontrolledValue] = useState< + SortableValue + >(() => (defaultValue ?? {}) as SortableValue); + const committed = + (valueProp as SortableValue | undefined) ?? 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 as unknown as Value, { + 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 orientation = options.orientation ?? "vertical"; + const reversed = orientation !== "vertical" && isRtl(element); + const centerX = x - grab.x + width / 2; + const centerY = y - grab.y + height / 2; + const isBefore = (rect: DOMRect): boolean => { + const middleX = rect.left + rect.width / 2; + const leading = reversed ? middleX > centerX : middleX < centerX; + if (orientation === "vertical") { + return rect.top + rect.height / 2 < centerY; + } + if (orientation === "horizontal") return leading; + return ( + rect.bottom < centerY || + (rect.top <= centerY && centerY <= rect.bottom && leading) + ); + }; + // Count positions among all items, so lists that only render the + // visible part (virtualized) still get the right index. + let lastBefore = -1; + let firstAfter = -1; + let position = 0; + for (const item of preview[container] ?? []) { + const id = getItemId(item); + if (id === current.id) continue; + const rect = elements.item.get(id)?.getBoundingClientRect(); + if (rect && isBefore(rect)) lastBefore = position; + else if (rect && firstAfter === -1) firstAfter = position; + position++; + } + const index = + lastBefore !== -1 ? lastBefore + 1 : Math.max(firstAfter, 0); + + 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 ( + claimedEvents.has(event.nativeEvent) || + latest.current.options.disabled || + session || + dragRef.current || + !event.isPrimary || + event.button !== 0 || + (ignored && ignored !== element && element.contains(ignored)) + ) { + return; + } + claimedEvents.add(event.nativeEvent); + 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 countGridColumns = (list: readonly Item[]): number => { + const { getItemId } = latest.current; + let top: number | undefined; + let count = 0; + for (const item of list) { + const rect = elements.item + .get(getItemId(item)) + ?.getBoundingClientRect(); + if (!rect) continue; + top ??= rect.top; + if (Math.abs(rect.top - top) > 1) break; + count++; + } + return Math.max(count, 1); + }; + + 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", + gridColumns: countGridColumns(value[current.to.container] ?? []), + 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 as unknown as Value & SortableValue, + }; +}