Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 139 additions & 0 deletions apps/ui/components/sortable-demo.tsx
Original file line number Diff line number Diff line change
@@ -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<Task> = {
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 (
<div className="my-8">
<div
className="flex max-w-sm flex-col gap-2"
{...sortable.getContainerProps("steps")}
>
{sortable.value.steps?.map((step) => (
<div
className={itemClassName}
key={step}
{...sortable.getItemProps(step)}
>
<GripVerticalIcon
aria-hidden="true"
className="size-4 shrink-0 text-muted-foreground"
/>
{step}
</div>
))}
</div>
{sortable.active?.reason === "pointer" && (
<div className={overlayClassName} {...sortable.getOverlayProps()}>
<GripVerticalIcon
aria-hidden="true"
className="size-4 shrink-0 text-muted-foreground"
/>
{sortable.active.item}
</div>
)}
<div {...sortable.getAnnouncerProps()} />
</div>
);
}

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 (
<div className="my-8 overflow-x-auto">
<div className="grid min-w-[36rem] grid-cols-3 gap-3">
{columns.map((column) => {
const tasks = sortable.value[column.id] ?? [];
return (
<div
className="flex flex-col gap-2 rounded-xl bg-muted/72 p-2 transition-colors data-drop-refused:bg-destructive/8 data-drop-refused:ring-1 data-drop-refused:ring-destructive/48 data-drop-refused:ring-inset"
key={column.id}
{...sortable.getContainerProps(column.id)}
>
<div className="flex items-center justify-between px-1 font-medium text-sm">
{column.label}
<Badge variant="outline">
{column.limit
? `${tasks.length}/${column.limit}`
: tasks.length}
</Badge>
</div>
<div className="flex min-h-24 flex-col gap-2">
{tasks.map((task) => (
<div
className={itemClassName}
key={task.id}
{...sortable.getItemProps(task)}
>
{task.title}
</div>
))}
</div>
</div>
);
})}
</div>
{sortable.active?.reason === "pointer" && (
<div className={overlayClassName} {...sortable.getOverlayProps()}>
{sortable.active.item.title}
</div>
)}
<div {...sortable.getAnnouncerProps()} />
</div>
);
}
2 changes: 1 addition & 1 deletion apps/ui/content/docs/hooks/meta.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"pages": ["use-media-query", "use-copy-to-clipboard"],
"pages": ["use-media-query", "use-copy-to-clipboard", "use-sortable"],
"title": "Hooks"
}
250 changes: 250 additions & 0 deletions apps/ui/content/docs/hooks/use-sortable.mdx
Original file line number Diff line number Diff line change
@@ -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

<CodeTabs>

<TabsList>
<TabsTab value="cli">CLI</TabsTab>
<TabsTab value="manual">Manual</TabsTab>
</TabsList>
<TabsPanel value="cli">

```bash
npx shadcn@latest add @coss/use-sortable
```

</TabsPanel>

<TabsPanel value="manual">

<Steps>

<Step>Copy and paste the following code into your project.</Step>

<ComponentSource name="use-sortable" title="hooks/use-sortable.ts" />

<Step>Update the import paths to match your project setup.</Step>

</Steps>

</TabsPanel>

</CodeTabs>

## 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 (
<>
<div {...sortable.getContainerProps("steps")}>
{sortable.value.steps?.map((step) => (
<div key={step} {...sortable.getItemProps(step)}>
{step}
</div>
))}
</div>
<div {...sortable.getAnnouncerProps()} />
</>
);
}
```

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) => (
<div key={column.id} {...sortable.getContainerProps(column.id)}>
{sortable.value[column.id]?.map((task) => (
<Card key={task.id} {...sortable.getItemProps(task)}>
{task.title}
</Card>
))}
</div>
));
```

`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" && (
<Card className="z-50 shadow-lg" {...sortable.getOverlayProps()}>
{sortable.active.item.title}
</Card>
)}
```

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 });

<Card {...sortable.getItemProps(task)}>
<button aria-label={`Move ${task.title}`} {...sortable.getHandleProps(task)}>
<GripVerticalIcon aria-hidden="true" />
</button>
{task.title}
</Card>;
```

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<Item>(options: UseSortableOptions<Item>): UseSortableReturn<Item>;
```

### Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `value` | `Record<string, Item[]>` | | Items per container, in order. Controlled |
| `defaultValue` | `Record<string, Item[]>` | `{}` | 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<string, Item[]>` | 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

<SortableListDemo />

### Board with a limit

The In progress column accepts at most two tasks. Drag a third card over it to see it refuse.

<SortableBoardDemo />
Loading
Loading