# Sortable List

A list that users reorder by dragging or with the keyboard.

Source: [sortable-list.tsx](https://github.com/jakejarvis/jarvis-ui/blob/main/src/components/ui/sortable-list.tsx)

```tsx
"use client";

import * as React from "react";

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Item, ItemActions, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item";
import { SortableList, SortableListHandle, SortableListItem } from "@/components/ui/sortable-list";
import { people } from "@/examples/data";

const initialTasks = [
  {
    id: "freeze",
    title: "Freeze the release branch",
    detail: "Cut v2.4 from main",
    owner: people[0],
  },
  { id: "notes", title: "Write the release notes", detail: "Changes since v2.3", owner: people[1] },
  { id: "staging", title: "Deploy to staging", detail: "Run the smoke tests", owner: people[2] },
  {
    id: "announce",
    title: "Announce the release",
    detail: "Blog post and changelog",
    owner: people[3],
  },
];

export default function SortableListDemo() {
  const [tasks, setTasks] = React.useState(initialTasks);

  return (
    <SortableList value={tasks} onValueChange={setTasks} className="w-full max-w-sm">
      {tasks.map((task) => (
        <SortableListItem
          key={task.id}
          value={task.id}
          label={task.title}
          render={<Item variant="outline" size="sm" className="gap-2 pl-1.5" />}
        >
          <SortableListHandle />
          <ItemContent>
            <ItemTitle>{task.title}</ItemTitle>
            <ItemDescription>{task.detail}</ItemDescription>
          </ItemContent>
          <ItemActions>
            <Avatar>
              <AvatarImage src={task.owner.image} alt={task.owner.name} />
              <AvatarFallback>{task.owner.initials}</AvatarFallback>
            </Avatar>
          </ItemActions>
        </SortableListItem>
      ))}
    </SortableList>
  );
}
```

## Installation

Add the registry, once per project:

```bash
npx shadcn@latest registry add @jarvis=https://ui.jarv.is/r/{name}.json
```

Then add the component:

```bash
npx shadcn@latest add @jarvis/sortable-list
```

## Usage

```tsx
"use client";

import * as React from "react";

import { Item } from "@/components/ui/item";
import { SortableList, SortableListHandle, SortableListItem } from "@/components/ui/sortable-list";

export function Tasks() {
  const [tasks, setTasks] = React.useState([
    { id: "notes", title: "Write the release notes" },
    { id: "deploy", title: "Deploy to staging" },
  ]);

  return (
    <SortableList value={tasks} onValueChange={setTasks}>
      {tasks.map((task) => (
        <SortableListItem
          key={task.id}
          value={task.id}
          render={<Item variant="outline" size="sm" />}
        >
          <SortableListHandle />
          {task.title}
        </SortableListItem>
      ))}
    </SortableList>
  );
}
```

Pass your items to `SortableList` as `value`, and render a `SortableListItem` for each one, in the same
order, with the item's unique value. For strings and numbers, that's the item itself; otherwise
it's the item's `id`. Pass `getItemValue` to use a different value. When an item is dropped in a
new place, `onValueChange` receives the items in their new order. To let the list keep track of its
own order instead, pass the items as `defaultValue`, and pass `children` a function that renders a
`SortableListItem` for an item. `SortableList` calls it for each item in the current order.

Users drag an item by its `SortableListHandle`, or by the whole item when it has no handle. As an item
moves, the others slide aside to make room, and the item settles into place when it's dropped.
Dragging an item near the edge of a scrolling area scrolls it, whether that's the page, a container
around the list, or the list itself.

Each handle, or each item without one, is a stop in the tab order. Space or Enter picks an item
up, the arrow keys along the list move it, and Home and End move it to the start or end. Space or
Enter drops it, and Escape or moving focus away returns it to where it was. Screen readers that
activate controls with a click, as VoiceOver and TalkBack do, pick up and drop an item the same
way. Screen readers announce the item's position as it moves. `label` on a `SortableListItem` sets the
name they announce for it, in place of its text.

`SortableList` lays the items out in a column, or in a row with `orientation="horizontal"`, and doesn't
style them. Render each one as an [Item](https://ui.jarv.is/components/item.md), or anything else with a background,
since a lifted item passes over the others. `SortableList` has the `list` role and its items the
`listitem` role, except when it's rendered as part of a table or its items have no handles, since
an item without a handle is a button.

## Composition

- `SortableList`
  - `SortableListItem`
    - `SortableListHandle`

## Examples

### Without a handle

Leave out `SortableListHandle` to drag the whole item. On a touch screen, users press and hold the
item for a moment before dragging, so swiping across the list still scrolls the page. Without a
handle, the item is a button, which screen readers read as a single element, so keep other controls
out of it.

```tsx
"use client";

import * as React from "react";

import { Item, ItemContent, ItemTitle } from "@/components/ui/item";
import { SortableList, SortableListItem } from "@/components/ui/sortable-list";

export default function SortableListWithoutHandle() {
  const [priorities, setPriorities] = React.useState([
    "Faster page loads",
    "Offline support",
    "Dark mode",
    "Keyboard shortcuts",
    "Two-factor sign-in",
  ]);

  return (
    <SortableList
      value={priorities}
      onValueChange={setPriorities}
      className="w-full max-w-xs gap-1.5"
    >
      {priorities.map((priority, index) => (
        <SortableListItem
          key={priority}
          value={priority}
          label={priority}
          render={<Item variant="outline" size="xs" className="gap-2.5 px-2.5" />}
        >
          <span className="w-4 text-right text-xs text-faint tabular-nums">{index + 1}</span>
          <ItemContent>
            <ItemTitle>{priority}</ItemTitle>
          </ItemContent>
        </SortableListItem>
      ))}
    </SortableList>
  );
}
```

### Horizontal

`orientation="horizontal"` lays the items out in a row, and the left and right arrow keys move an
item along it.

```tsx
"use client";

import * as React from "react";

import { Item } from "@/components/ui/item";
import { SortableList, SortableListHandle, SortableListItem } from "@/components/ui/sortable-list";

export default function SortableListHorizontal() {
  const [columns, setColumns] = React.useState(["Name", "Status", "Owner", "Due"]);

  return (
    <div className="flex w-full max-w-md flex-col gap-2">
      <SortableList
        value={columns}
        onValueChange={setColumns}
        orientation="horizontal"
        aria-label="Columns"
        className="gap-1.5"
      >
        {columns.map((column) => (
          <SortableListItem
            key={column}
            value={column}
            render={
              <Item
                variant="outline"
                size="xs"
                className="w-auto shrink-0 gap-1 py-0.5 pr-2.5 pl-0.5"
              />
            }
          >
            <SortableListHandle />
            <span className="font-medium">{column}</span>
          </SortableListItem>
        ))}
      </SortableList>
      <p className="text-sm text-muted-foreground">
        Columns show in the order <span className="text-foreground">{columns.join(", ")}</span>.
      </p>
    </div>
  );
}
```

### Interactive content

Give an item a `SortableListHandle` when it holds buttons, switches, links or fields. The controls then
work as usual, and the handle moves the item.

```tsx
"use client";

import { BellIcon, MailIcon, MessageSquareIcon, SmartphoneIcon } from "lucide-react";
import * as React from "react";

import {
  Item,
  ItemActions,
  ItemContent,
  ItemDescription,
  ItemMedia,
  ItemTitle,
} from "@/components/ui/item";
import { SortableList, SortableListHandle, SortableListItem } from "@/components/ui/sortable-list";
import { Switch } from "@/components/ui/switch";

const initialChannels = [
  { id: "push", name: "Push", detail: "On this device", icon: BellIcon, enabled: true },
  { id: "email", name: "Email", detail: "tony@example.com", icon: MailIcon, enabled: true },
  {
    id: "sms",
    name: "Text message",
    detail: "Ending in 4242",
    icon: SmartphoneIcon,
    enabled: false,
  },
  { id: "slack", name: "Slack", detail: "#alerts", icon: MessageSquareIcon, enabled: false },
];

export default function SortableListInteractiveContent() {
  const [channels, setChannels] = React.useState(initialChannels);

  const toggle = (id: string, enabled: boolean) =>
    setChannels((current) =>
      current.map((channel) => (channel.id === id ? { ...channel, enabled } : channel)),
    );

  return (
    <SortableList value={channels} onValueChange={setChannels} className="w-full max-w-sm gap-1.5">
      {channels.map((channel) => (
        <SortableListItem
          key={channel.id}
          value={channel.id}
          label={channel.name}
          render={<Item variant="outline" size="sm" className="gap-2 pl-1.5" />}
        >
          <SortableListHandle />
          <ItemMedia variant="icon">
            <channel.icon />
          </ItemMedia>
          <ItemContent>
            <ItemTitle>{channel.name}</ItemTitle>
            <ItemDescription>{channel.detail}</ItemDescription>
          </ItemContent>
          <ItemActions>
            <Switch
              checked={channel.enabled}
              onCheckedChange={(enabled) => toggle(channel.id, enabled)}
              aria-label={`Notify by ${channel.name.toLowerCase()}`}
            />
          </ItemActions>
        </SortableListItem>
      ))}
    </SortableList>
  );
}
```

### Disabled

`disabled` on a `SortableListItem` keeps that item where it is while the others move around it.
`disabled` on `SortableList` keeps every item in place.

```tsx
"use client";

import { InboxIcon, LockIcon } from "lucide-react";
import * as React from "react";

import { FieldLabel } from "@/components/ui/field";
import { Item, ItemActions, ItemContent, ItemMedia, ItemTitle } from "@/components/ui/item";
import { SortableList, SortableListHandle, SortableListItem } from "@/components/ui/sortable-list";
import { Switch } from "@/components/ui/switch";

export default function SortableListDisabled() {
  const [views, setViews] = React.useState(["Inbox", "Today", "Upcoming", "Projects", "Archive"]);
  const [locked, setLocked] = React.useState(false);

  return (
    <div className="flex w-full max-w-xs flex-col gap-4">
      <FieldLabel className="gap-2 font-normal">
        <Switch checked={locked} onCheckedChange={setLocked} />
        Lock the order
      </FieldLabel>
      <SortableList value={views} onValueChange={setViews} disabled={locked} className="gap-1.5">
        {views.map((view) => (
          <SortableListItem
            key={view}
            value={view}
            disabled={view === "Inbox"}
            render={<Item variant="outline" size="xs" className="gap-2 pl-1" />}
          >
            <SortableListHandle />
            {view === "Inbox" && (
              <ItemMedia>
                <InboxIcon className="text-icon" />
              </ItemMedia>
            )}
            <ItemContent>
              <ItemTitle>{view}</ItemTitle>
            </ItemContent>
            {view === "Inbox" && (
              <ItemActions>
                <LockIcon
                  role="img"
                  aria-label="Always first"
                  className="size-3.5 text-icon-muted"
                />
              </ItemActions>
            )}
          </SortableListItem>
        ))}
      </SortableList>
    </div>
  );
}
```

### Table rows

Render `SortableList` as a [Table](https://ui.jarv.is/components/table.md)'s `TableBody`, and each item as a `TableRow`.
`SortableList` then leaves the layout and the roles to the table, with or without handles. A row's
border depends on its position in the table, which only changes on drop, so this example gives
every row a border while one is lifted.

```tsx
"use client";

import * as React from "react";

import { SortableList, SortableListHandle, SortableListItem } from "@/components/ui/sortable-list";
import { Status } from "@/components/ui/status";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

const initialStages = [
  { id: "lint", name: "Lint", duration: "18s", status: "success" },
  { id: "test", name: "Unit tests", duration: "2m 41s", status: "success" },
  { id: "build", name: "Build", duration: "1m 06s", status: "warning" },
  { id: "e2e", name: "End-to-end tests", duration: "6m 12s", status: "default" },
  { id: "deploy", name: "Deploy", duration: "—", status: "default" },
] as const;

const labels = { success: "Passed", warning: "Slow", default: "Queued" };

export default function SortableListTable() {
  const [stages, setStages] = React.useState([...initialStages]);

  return (
    <div className="w-full max-w-lg">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead className="w-8">
              <span className="sr-only">Reorder</span>
            </TableHead>
            <TableHead>Stage</TableHead>
            <TableHead>Status</TableHead>
            <TableHead className="text-right">Duration</TableHead>
          </TableRow>
        </TableHeader>
        <SortableList
          value={stages}
          onValueChange={setStages}
          render={<TableBody />}
          className="data-dragging:[&>tr>td]:border-b-[0.5px] data-dragging:[&>tr>td]:border-border-muted"
        >
          {stages.map((stage) => (
            <SortableListItem
              key={stage.id}
              value={stage.id}
              label={stage.name}
              render={<TableRow className="data-dragging:bg-layer-0" />}
            >
              <TableCell className="py-1 pr-0">
                <SortableListHandle />
              </TableCell>
              <TableCell className="font-medium">{stage.name}</TableCell>
              <TableCell>
                <Status variant={stage.status}>{labels[stage.status]}</Status>
              </TableCell>
              <TableCell className="text-right text-muted-foreground tabular-nums">
                {stage.duration}
              </TableCell>
            </SortableListItem>
          ))}
        </SortableList>
      </Table>
    </div>
  );
}
```

### In a form

Give a [`Field`](https://ui.jarv.is/components/field.md) or `SortableList` a `name`, and each item's value submits under it
in order, so `formData.getAll(name)` returns the ranking. Pass `form` with a form's `id` when the
list sits outside the form. With a [Form](https://ui.jarv.is/components/form.md), `onFormSubmit` receives the values as
an array. A `FieldLabel` labels the list, and screen readers read the field's description and
errors with it. An item that's mid-drag submits in its original position until it's dropped.

A form reset restores the items' original order. When that changes the order, the reset calls
`onValueChange` with the reason `none`, so the parent of a controlled list decides whether to apply
it. A disabled `SortableList` still submits its order. This example manages its own order with
`defaultValue`.

```tsx
"use client";

import { Button } from "@/components/ui/button";
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
import { Form } from "@/components/ui/form";
import { Item, ItemContent, ItemTitle } from "@/components/ui/item";
import { SortableList, SortableListHandle, SortableListItem } from "@/components/ui/sortable-list";
import { toast } from "@/components/ui/toast";

const initialFeatures = ["Dark mode", "Offline sync", "Shared folders", "Keyboard shortcuts"];

export default function SortableListForm() {
  return (
    <Form
      className="w-full max-w-xs"
      onFormSubmit={(values) =>
        toast.add({
          title: "Thanks for ranking",
          description: (values.features as string[]).join(", "),
        })
      }
    >
      <Field name="features">
        <FieldLabel>Rank these features</FieldLabel>
        <SortableList defaultValue={initialFeatures} className="w-full gap-1.5">
          {(feature) => (
            <SortableListItem
              value={feature}
              render={<Item variant="outline" size="xs" className="gap-2 pl-1" />}
            >
              <SortableListHandle />
              <ItemContent>
                <ItemTitle>{feature}</ItemTitle>
              </ItemContent>
            </SortableListItem>
          )}
        </SortableList>
        <FieldDescription>Put the one you want most first.</FieldDescription>
      </Field>
      <div className="flex gap-2">
        <Button type="submit" variant="primary">
          Send ranking
        </Button>
        <Button type="reset">Reset</Button>
      </div>
    </Form>
  );
}
```

### Scrolling

A list in a [Scroll Area](https://ui.jarv.is/components/scroll-area.md) scrolls while an item is dragged near its top
or bottom, and moving an item with the keyboard keeps it in view.

```tsx
"use client";

import * as React from "react";

import { Item, ItemContent, ItemTitle } from "@/components/ui/item";
import { ScrollArea } from "@/components/ui/scroll-area";
import { SortableList, SortableListHandle, SortableListItem } from "@/components/ui/sortable-list";

export default function SortableListScrolling() {
  const [tracks, setTracks] = React.useState([
    "Morning Light",
    "Paper Boats",
    "Slow Tide",
    "Northern Lines",
    "Glasshouse",
    "Afterglow",
    "Low Orbit",
    "Field Notes",
    "Static Bloom",
    "Long Way Home",
    "Satellites",
    "Last Call",
  ]);

  return (
    <ScrollArea className="h-64 w-full max-w-xs rounded-md border-[0.5px] border-border-muted">
      <SortableList
        value={tracks}
        onValueChange={setTracks}
        aria-label="Queue"
        className="gap-0.5 p-1"
      >
        {tracks.map((track, index) => (
          <SortableListItem
            key={track}
            value={track}
            label={track}
            render={<Item size="xs" className="gap-2 pl-1 data-dragging:bg-surface" />}
          >
            <SortableListHandle />
            <span className="w-4 text-right text-xs text-faint tabular-nums">{index + 1}</span>
            <ItemContent>
              <ItemTitle>{track}</ItemTitle>
            </ItemContent>
          </SortableListItem>
        ))}
      </SortableList>
    </ScrollArea>
  );
}
```

### Saving the order

`onValueChange` runs once per drop, and only when the order changed. `eventDetails.reason` is
`drag` or `keyboard`, depending on how the item moved. `eventDetails.item`, `from` and `to` give the
item that moved and its index before and after, so you can save the move. Calling
`eventDetails.cancel()` slides the item back. Otherwise, the items hold their new places while they
wait for the new order, so it can arrive a moment later, such as from a transition. If it hasn't
arrived after a second, the items slide back.

```tsx
"use client";

import * as React from "react";

import { Item, ItemContent, ItemTitle } from "@/components/ui/item";
import { SortableList, SortableListHandle, SortableListItem } from "@/components/ui/sortable-list";

const initialMetrics = ["Revenue", "Active users", "Conversion", "Churn"];

export default function SortableListSaveOrder() {
  const [metrics, setMetrics] = React.useState(initialMetrics);
  const [lastMove, setLastMove] = React.useState<string | null>(null);

  return (
    <div className="flex w-full max-w-xs flex-col gap-3">
      <SortableList
        value={metrics}
        onValueChange={(next, eventDetails) => {
          setMetrics(next);
          if (eventDetails.reason !== "none") {
            const { item, from, to } = eventDetails;
            setLastMove(`Saved: ${item} moved from ${from + 1} to ${to + 1}.`);
          }
        }}
        className="gap-1.5"
      >
        {metrics.map((metric) => (
          <SortableListItem
            key={metric}
            value={metric}
            render={<Item variant="outline" size="xs" className="gap-2 pl-1" />}
          >
            <SortableListHandle />
            <ItemContent>
              <ItemTitle>{metric}</ItemTitle>
            </ItemContent>
          </SortableListItem>
        ))}
      </SortableList>
      <p className="text-sm text-muted-foreground">
        {lastMove ?? "Move a metric to save the order."}
      </p>
    </div>
  );
}
```

## Props

`SortableListHandle` shows a grip icon, rotated to match the list's `orientation`, unless you pass it
your own children. An item has a `data-dragging` attribute while it's lifted, and `data-dropping`
while it settles. `SortableList` also has `data-dragging` while an item is lifted, set to `pointer` or
`keyboard` depending on how the item was picked up.

| Part | Extends |
| --- | --- |
| `SortableList` | `<div>` |
| `SortableListItem` | `<div>` |
| `SortableListHandle` | `<button>` |

Base UI's [styling](https://base-ui.com/react/handbook/styling) and [composition](https://base-ui.com/react/handbook/composition) guides say more about `className`, `style` and `render`.

### SortableList

| Prop             | Type                                                                                  | Default            | Description                                                                                                                                                                                                                                                  |
| ---------------- | ------------------------------------------------------------------------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `value?`         | `unknown[]`                                                                           | —                  | The items, in order. Render a `SortableListItem` for each, in the same order.                                                                                                                                                                                |
| `defaultValue?`  | `unknown[]`                                                                           | —                  | The items in their initial order, when `value` isn't controlled. Render them with a function as `children`.                                                                                                                                                  |
| `children?`      | `((item: unknown, index: number) => React.ReactNode) \| React.ReactNode`              | —                  | The `SortableListItem`s in the items' order, or a function that renders the `SortableListItem` for an item. The function is called for each item in its current order.                                                                                       |
| `onValueChange?` | `((value: unknown[], eventDetails: SortableListChangeEventDetails<unknown>) => void)` | —                  | Called with the items in their new order when one is dropped in a new place, and when a form reset restores their initial order. After a drop, `eventDetails` says which item moved and where. Calling `eventDetails.cancel()` keeps the items as they were. |
| `getItemValue?`  | `((item: unknown) => string \| number)`                                               | `defaultItemValue` | Returns an item's unique value, which its `SortableListItem` takes as `value`. Defaults to the item itself for strings and numbers, and to its `id` otherwise.                                                                                               |
| `orientation?`   | `"horizontal" \| "vertical"`                                                          | `"vertical"`       | The direction the items are laid out in, which determines the arrow keys that move them.                                                                                                                                                                     |
| `disabled?`      | `boolean`                                                                             | `false`            | Keeps every item in place. The order is still submitted with a form.                                                                                                                                                                                         |
| `name?`          | `string`                                                                              | —                  | The name the items' values are submitted under in a form, in order.                                                                                                                                                                                          |
| `form?`          | `string`                                                                              | —                  | The `id` of the form to submit the order with, when the list isn't inside it.                                                                                                                                                                                |
| `className?`     | `string`                                                                              | —                  | CSS class applied to the element.                                                                                                                                                                                                                            |
| `style?`         | `React.CSSProperties`                                                                 | —                  | Style applied to the element.                                                                                                                                                                                                                                |
| `render?`        | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement`                              | —                  | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render.                                                                    |

### SortableListItem

| Prop         | Type                                                     | Default | Description                                                                                                                                                                               |
| ------------ | -------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `value`      | `string \| number`                                       | —       | The item's unique value, which `getItemValue` returns for it.                                                                                                                             |
| `label?`     | `string`                                                 | —       | The name screen readers announce for the item as it moves. Defaults to its text.                                                                                                          |
| `disabled?`  | `boolean`                                                | `false` | Keeps the item in place. The others move around it.                                                                                                                                       |
| `className?` | `string`                                                 | —       | CSS class applied to the element.                                                                                                                                                         |
| `style?`     | `React.CSSProperties`                                    | —       | Style applied to the element.                                                                                                                                                             |
| `render?`    | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### SortableListHandle

| Prop         | Type                                                     | Default | Description                                                                                                                                                                               |
| ------------ | -------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `className?` | `string`                                                 | —       | CSS class applied to the element.                                                                                                                                                         |
| `style?`     | `React.CSSProperties`                                    | —       | Style applied to the element.                                                                                                                                                             |
| `render?`    | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |
