# Sortable list

> Reorder a short list by dragging or activating move buttons, with numeric position fields as a fallback.

- Kind: ui · Category: Forms · Interactivity: script
- Install: `npx shadcn@latest add @haze/sortable-list`
- File: `src/components/haze/ui/sortable-list.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/button, @haze/input, @haze/utils
- Docs page: https://hazeui.com/ui/sortable-list

## Use when
- People set an order for report sections, shortcuts, or other small lists
- Each item needs a stable ID and a submitted position

## Avoid when
- A long list needs filtering or sorting by multiple columns. Use table.
- Items only need a fixed reading order. Use item.

## Alternatives
- [item](https://hazeui.com/ui/item.md)
- [table](https://hazeui.com/ui/table.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique prefix for the component and its labelled controls. |
| name | `string` | id | no | Prefix for submitted fields in the form name[itemId]. |
| label | `string` | "Display order" | no | Visible name of the ordering task. |
| items | `{ id: string; label: string; description?: string }[]` |  | no | Items in initial order. IDs must be distinct within the list. |
| headingLevel | `2 \| 3 \| 4 \| 5 \| 6` | 2 | no | Heading level for the title. |
| class | `string` |  | no | Additional classes on the section. |

## Accessibility
- Move buttons announce item position after each move and keep keyboard focus on the moved item.
- Validate positions on submission. Without JavaScript, people edit the position fields directly.
- The drag handle is optional for interaction. Touch users can use the move buttons.
- Key Tab then Enter or Space: Activate a move button.

## Agent prompts

### Install and use

Install the Haze UI component "Sortable list" with `npx shadcn@latest add @haze/sortable-list`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import SortableList from "@/components/haze/ui/sortable-list.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/sortable-list.md

### Customize with real content

Adapt the Haze sortable-list ui for our product. Replace the demo values of these props with our real content: id, name, label, items, headingLevel, class. Keep the layout, the heading level rules and these accessibility details: Move buttons announce item position after each move and keep keyboard focus on the moved item. Validate positions on submission. Without JavaScript, people edit the position fields directly. The drag handle is optional for interaction. Touch users can use the move buttons. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using sortable-list, check it fits: use it when people set an order for report sections, shortcuts, or other small lists; each item needs a stable id and a submitted position. Avoid it when a long list needs filtering or sorting by multiple columns. use table.; items only need a fixed reading order. use item.. Alternatives: @haze/item, @haze/table.

## Example requests that should lead here
- Let people reorder three report sections and submit the new positions with the report settings.

## Source

```astro
---
import { ChevronDown, ChevronUp, GripVertical } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";
import Input from "./input.astro";

interface Props {
  id: string;
  name?: string;
  label?: string;
  items?: { id: string; label: string; description?: string }[];
  headingLevel?: 2 | 3 | 4 | 5 | 6;
  class?: string;
}

const {
  id, name = id, label = "Display order", headingLevel = 2, class: className,
  items = [
    { id: "overview", label: "Overview" },
    { id: "activity", label: "Activity" },
    { id: "settings", label: "Settings" },
  ],
} = Astro.props;
const Heading = `h${headingLevel}` as const;
const moveButton = "size-8 rounded-md focus-visible:z-10 active:scale-90 [&_svg]:size-4";
---

<section data-haze-sortable-list aria-labelledby={`${id}-label`} class={cn("grid min-w-0 gap-3", className)}>
  <Heading id={`${id}-label`} class="text-[0.8125rem]/5 font-medium text-foreground">{label}</Heading>
  <ol data-sort-list class="grid min-w-0 gap-1.5">
    {items.map((item, index) => (
      <li data-sort-item data-sort-label={item.label} class="flex min-w-0 items-center gap-2 rounded-xl border border-border bg-card px-3 py-2.5 text-card-foreground motion-safe:transition-[border-color,box-shadow] motion-safe:duration-150 motion-safe:ease-snappy hover:border-border-strong data-[drop-target]:border-foreground">
        <span data-sort-handle aria-hidden="true" class="hidden shrink-0 cursor-grab text-muted-foreground hover:text-foreground active:cursor-grabbing [[data-haze-sortable-list][data-enhanced]_&]:block">
          <GripVertical class="pointer-events-none size-4" />
        </span>
        <div class="grid min-w-0 flex-1 gap-0.5">
          <span class="wrap-anywhere text-[0.8125rem]/5 font-medium">{item.label}</span>
          {item.description && <span class="wrap-anywhere text-[0.8125rem]/5 text-muted-foreground">{item.description}</span>}
        </div>
        <div class="w-14 shrink-0 [[data-haze-sortable-list][data-enhanced]_&]:hidden">
          <Input id={`${id}-position-${index}`} name={`${name}[${item.id}]`} type="number" value={index + 1} min={1} max={items.length} required
            aria-label={`Position for ${item.label}`} data-sort-position class="px-1.5 text-center tabular-nums" />
        </div>
        <div class="hidden shrink-0 gap-0.5 [[data-haze-sortable-list][data-enhanced]_&]:flex">
          <Button data-sort-step="-1" variant="ghost" size="icon" class={moveButton} aria-label={`Move ${item.label} up`}><ChevronUp aria-hidden="true" /></Button>
          <Button data-sort-step="1" variant="ghost" size="icon" class={moveButton} aria-label={`Move ${item.label} down`}><ChevronDown aria-hidden="true" /></Button>
        </div>
      </li>
    ))}
  </ol>
  <p data-sort-status aria-live="polite" class="sr-only"></p>
</section>

<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const list = root.querySelector<HTMLOListElement>("[data-sort-list]");
    const status = root.querySelector<HTMLElement>("[data-sort-status]");
    if (!list || !status) return;
    const rows = Array.from(list.querySelectorAll<HTMLLIElement>(":scope > [data-sort-item]"));
    if (rows.length < 2) return;

    const order = () => Array.from(list.children) as HTMLLIElement[];
    const motions = new WeakMap<HTMLLIElement, Animation>();
    const reduced = matchMedia("(prefers-reduced-motion: reduce)");
    let dragged: HTMLLIElement | null = null;
    let dropTarget: HTMLLIElement | null = null;

    const sync = () => {
      for (const [index, row] of order().entries()) {
        row.querySelector<HTMLInputElement>("[data-sort-position]")!.value = String(index + 1);
        row.querySelector('[data-sort-step="-1"]')!.setAttribute("aria-disabled", String(index === 0));
        row.querySelector('[data-sort-step="1"]')!.setAttribute("aria-disabled", String(index === rows.length - 1));
      }
    };

    const move = (row: HTMLLIElement, to: number) => {
      const current = order();
      const from = current.indexOf(row);
      const destination = current[to];
      if (!destination || row === destination) return;

      const positions = reduced.matches ? null : current.map((item) => item.getBoundingClientRect().top);
      current.forEach((item) => motions.get(item)?.cancel());
      const focus = document.activeElement;
      if (from < to) destination.after(row);
      else destination.before(row);
      sync();
      if (focus instanceof HTMLElement && row.contains(focus)) focus.focus({ preventScroll: true });
      status.textContent = `${row.dataset.sortLabel} moved to position ${to + 1} of ${rows.length}.`;

      if (positions) {
        const easing = getComputedStyle(root).getPropertyValue("--ease-snappy").trim() || "ease";
        const offsets = current.map((item, index) => positions[index] - item.getBoundingClientRect().top);
        current.forEach((item, index) => {
          if (!offsets[index]) return;
          motions.set(item, item.animate([{ translate: `0 ${offsets[index]}px` }, { translate: "0 0" }], { duration: 200, easing }));
        });
      }
    };

    const clearDrag = () => {
      dropTarget?.removeAttribute("data-drop-target");
      dropTarget = null;
      dragged = null;
    };

    for (const row of rows) {
      const handle = row.querySelector<HTMLElement>("[data-sort-handle]")!;
      handle.draggable = true;
      handle.addEventListener("dragstart", (event) => {
        if (!event.dataTransfer) return;
        dragged = row;
        event.dataTransfer.effectAllowed = "move";
        event.dataTransfer.setData("text/plain", row.dataset.sortLabel || "");
        event.dataTransfer.setDragImage(row, 16, 16);
      });
      handle.addEventListener("dragend", clearDrag);
    }
    list.addEventListener("click", (event) => {
      const button = (event.target as Element).closest<HTMLButtonElement>("button[data-sort-step]");
      const row = button?.closest<HTMLLIElement>("[data-sort-item]");
      if (!button || !row || row.parentElement !== list) return;
      move(row, order().indexOf(row) + Number(button.dataset.sortStep));
    });
    list.addEventListener("dragover", (event) => {
      if (!dragged) return;
      event.preventDefault();
      if (event.dataTransfer) event.dataTransfer.dropEffect = "move";
      const target = (event.target as Element).closest<HTMLLIElement>("[data-sort-item]");
      if (target === dropTarget) return;
      dropTarget?.removeAttribute("data-drop-target");
      dropTarget = target?.parentElement === list ? target : null;
      if (dropTarget !== dragged) dropTarget?.setAttribute("data-drop-target", "");
    });
    list.addEventListener("drop", (event) => {
      if (!dragged) return;
      event.preventDefault();
      if (dropTarget) move(dragged, order().indexOf(dropTarget));
      clearDrag();
    });
    list.querySelector<HTMLInputElement>("[data-sort-position]")?.form?.addEventListener("reset", (event) => {
      queueMicrotask(() => {
        if (event.defaultPrevented) return;
        rows.forEach((row) => motions.get(row)?.cancel());
        list.append(...rows);
        sync();
        status.textContent = "Original order restored.";
      });
    });
    sync();
    root.setAttribute("data-enhanced", "");
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-sortable-list]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-sortable-list-listener")) {
    document.documentElement.setAttribute("data-haze-sortable-list-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
