Sortable list
Drag or use keys to reorder rows.
Installation
Run the CLI
Run
pnpm dlx asta-ui@latest initonce, then this. The file lands incomponents/astabyte/and the colour tokens go into your CSS.$ pnpm dlx asta-ui@latest add sortable-listOr install the package
Don’t want the file? Import from
asta-ui/sortable-listand update withpnpm update asta-ui. Add the stylesheet once. More.$ pnpm add asta-uiimport { SortableList } from "asta-ui/sortable-list";Or copy it by hand
Copy this file. Keep the paths, or fix the
@/imports. Then add the tokens fromglobals.css."use client"; import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type PointerEvent, type ReactNode } from "react"; const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" "); const EASE = "cubic-bezier(.16,1,.3,1)"; export interface SortableListProps<T extends { id: string }> { items: T[]; onReorder: (items: T[]) => void; renderItem: (item: T, state: { index: number; dragging: boolean }) => ReactNode; /** Accessible name of the list. */ label: string; /** Text used in announcements. Defaults to the id. */ getLabel?: (item: T) => string; className?: string; } interface Drag { id: string; from: number; to: number; startY: number; tops: number[]; heights: number[]; gap: number; } const move = <T,>(list: T[], from: number, to: number) => { const next = list.slice(); const [it] = next.splice(from, 1); next.splice(to, 0, it); return next; }; const Grip = () => ( <svg viewBox="0 0 16 16" className="h-4 w-4" fill="currentColor" aria-hidden> {[4, 8, 12].flatMap((y) => [6, 10].map((x) => <circle key={`${x}${y}`} cx={x} cy={y} r="1.15" />))} </svg> ); /** * A list you put in order. Drag a row by its handle and the others slide aside to open a gap where it will * land. With the keyboard, Space picks a row up, the arrows move it and Space drops it (Escape puts it back). * Every move is announced, and rows glide to their new places instead of jumping. */ export function SortableList<T extends { id: string }>({ items, onReorder, renderItem, label, getLabel = (it) => it.id, className }: SortableListProps<T>) { const [drag, setDrag] = useState<Drag | null>(null); const [grabbed, setGrabbed] = useState<string | null>(null); const [say, setSay] = useState(""); const rows = useRef(new Map<string, HTMLLIElement>()); const handles = useRef(new Map<string, HTMLButtonElement>()); const flip = useRef<Map<string, number> | null>(null); const before = useRef<T[] | null>(null); const reduce = useRef(false); useEffect(() => { reduce.current = window.matchMedia("(prefers-reduced-motion: reduce)").matches; }, []); /** Remember where every row is drawn now, so the next layout can glide from there. */ const snapshot = () => { const m = new Map<string, number>(); rows.current.forEach((el, id) => m.set(id, el.getBoundingClientRect().top)); flip.current = m; }; useLayoutEffect(() => { const m = flip.current; if (!m) return; flip.current = null; if (reduce.current) return; rows.current.forEach((el, id) => { const old = m.get(id); if (old === undefined) return; const d = old - el.getBoundingClientRect().top; if (Math.abs(d) > 0.5) el.animate([{ transform: `translateY(${d}px)` }, { transform: "none" }], { duration: 320, easing: EASE }); }); if (grabbed) handles.current.get(grabbed)?.focus(); }, [items, grabbed]); const name = (id: string) => { const it = items.find((x) => x.id === id); return it ? getLabel(it) : id; }; // ---- Pointer ---- const onDown = (e: PointerEvent<HTMLButtonElement>, id: string, index: number) => { if (e.button !== 0 || grabbed) return; e.currentTarget.setPointerCapture(e.pointerId); const els = items.map((it) => rows.current.get(it.id)!); const tops = els.map((el) => el.offsetTop); const heights = els.map((el) => el.offsetHeight); const gap = els.length > 1 ? tops[1] - tops[0] - heights[0] : 0; setDrag({ id, from: index, to: index, startY: e.clientY, tops, heights, gap }); setSay(`Picked up ${name(id)}.`); }; const onMove = (e: PointerEvent<HTMLButtonElement>) => { if (!drag) return; const dy = e.clientY - drag.startY; const el = rows.current.get(drag.id); if (el) el.style.transform = `translateY(${dy}px) scale(1.015)`; const center = drag.tops[drag.from] + drag.heights[drag.from] / 2 + dy; let to = drag.from; drag.tops.forEach((t, i) => { const mid = t + drag.heights[i] / 2; if (i > drag.from && center > mid) to = i; if (i < drag.from && center < mid && i < to) to = i; }); if (to !== drag.to) setDrag({ ...drag, to }); }; const onUp = (e: PointerEvent<HTMLButtonElement>) => { if (!drag) return; const el = rows.current.get(drag.id); setDrag(null); if (drag.to !== drag.from) { snapshot(); if (el) el.style.transform = ""; onReorder(move(items, drag.from, drag.to)); setSay(`${name(drag.id)} dropped at position ${drag.to + 1} of ${items.length}.`); return; } // Same place: glide back from wherever it was let go. if (el) { el.style.transform = ""; const dy = e.clientY - drag.startY; if (!reduce.current && Math.abs(dy) > 0.5) el.animate([{ transform: `translateY(${dy}px)` }, { transform: "none" }], { duration: 320, easing: EASE }); } setSay(`${name(drag.id)} dropped. Position unchanged.`); }; // ---- Keyboard ---- const onKey = (e: KeyboardEvent<HTMLButtonElement>, id: string, index: number) => { const n = items.length; if (e.key === " " || e.key === "Enter") { e.preventDefault(); if (grabbed) { setGrabbed(null); before.current = null; setSay(`${name(id)} dropped at position ${index + 1} of ${n}.`); } else { setGrabbed(id); before.current = items; setSay(`Picked up ${name(id)}, position ${index + 1} of ${n}. Use the up and down arrows to move it, Space to drop, Escape to cancel.`); } } else if (grabbed === id && (e.key === "ArrowUp" || e.key === "ArrowDown")) { e.preventDefault(); const to = Math.max(0, Math.min(n - 1, index + (e.key === "ArrowUp" ? -1 : 1))); if (to === index) return; snapshot(); onReorder(move(items, index, to)); setSay(`${name(id)} moved to position ${to + 1} of ${n}.`); } else if (grabbed === id && e.key === "Escape") { e.preventDefault(); if (before.current) { snapshot(); onReorder(before.current); } before.current = null; setGrabbed(null); setSay(`Cancelled. ${name(id)} is back where it was.`); } }; const shiftFor = (i: number) => { if (!drag || i === drag.from) return 0; const h = drag.heights[drag.from] + drag.gap; if (drag.from < drag.to && i > drag.from && i <= drag.to) return -h; if (drag.to < drag.from && i >= drag.to && i < drag.from) return h; return 0; }; return ( <div className={className}> <ul aria-label={label} className="flex flex-col gap-1.5"> {items.map((it, i) => { const dragging = drag?.id === it.id; const lifted = dragging || grabbed === it.id; const shift = shiftFor(i); return ( <li key={it.id} ref={(el) => { if (el) rows.current.set(it.id, el); else rows.current.delete(it.id); }} style={dragging ? undefined : { transform: shift ? `translateY(${shift}px)` : undefined, transition: drag ? `transform .28s ${EASE}` : undefined }} className={cx( "relative flex items-center gap-2 rounded-[11px] bg-paper py-2 pl-1.5 pr-3", "shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_10%,transparent)] transition-shadow duration-200", lifted && "z-10 shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-brand)_55%,transparent),0_14px_30px_-14px_rgb(0_0_0/0.35)]", )} > <button ref={(el) => { if (el) handles.current.set(it.id, el); else handles.current.delete(it.id); }} type="button" aria-label={`Reorder ${getLabel(it)}`} aria-pressed={grabbed === it.id} onPointerDown={(e) => onDown(e, it.id, i)} onPointerMove={onMove} onPointerUp={onUp} onPointerCancel={onUp} onKeyDown={(e) => onKey(e, it.id, i)} onBlur={() => { if (grabbed === it.id && !flip.current) { setGrabbed(null); before.current = null; } }} className={cx( "flex h-8 w-7 shrink-0 touch-none items-center justify-center rounded-md outline-none transition-colors", "focus-visible:ring-2 focus-visible:ring-brand/50", dragging ? "cursor-grabbing text-ink" : "cursor-grab text-mute hover:bg-paper-2 hover:text-ink", grabbed === it.id && "bg-brand text-on-brand hover:bg-brand hover:text-on-brand", )} > <Grip /> </button> <div className="min-w-0 flex-1">{renderItem(it, { index: i, dragging: lifted })}</div> </li> ); })} </ul> <p aria-live="assertive" className="sr-only"> {say} </p> </div> ); } export default SortableList;Or ask your AI agent
Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.
Add the Astabyte UI Sortable list component to my project. Drag or use keys to reorder rows. It includes: drag handle, gap preview, keyboard, Escape to cancel, announcements, glide. Install it: ```sh pnpm dlx asta-ui@latest add sortable-list --radix ``` Or with the shadcn CLI: ```sh pnpm dlx shadcn@latest add https://ui.astabyte.com/r/sortable-list.json ``` If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4). Import it like this: ```tsx import { SortableList } from "@/components/astabyte/sortable-list"; ``` Usage example and props: https://ui.astabyte.com/sortable-list Full catalogue for context: https://ui.astabyte.com/llms.txt Rules: - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS. - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback. - Keep keyboard, focus and ARIA behaviour. - Use fake data and fake brand names in examples. Use it to: [describe where it goes and what it should do]Or use plain HTML + CSS
Not on React? Use it from Django, Rails, Laravel, Go
html/template, htmx or a static page. Loadasta.cssandasta.jsonce (thehead.htmltab), then paste the markup. Theui.astabyte.com/cdnlink is temporary: pin a version from jsDelivr for production. More in HTML + CSS.<!-- asta.js: drag a handle, or focus it and press Space, the arrows, then Space (Esc cancels). Listen for "asta:reorder". --> <ol class="asta-sortable" data-asta-sortable aria-label="Q1 priorities" style="max-width:440px"> <li class="asta-sortable-item" data-id="checkout"><button type="button" class="asta-sortable-handle" aria-label="Reorder Checkout redesign. Space to grab, arrows to move"><svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor" aria-hidden="true"><circle cx="6" cy="4" r="1.2"/><circle cx="10" cy="4" r="1.2"/><circle cx="6" cy="8" r="1.2"/><circle cx="10" cy="8" r="1.2"/><circle cx="6" cy="12" r="1.2"/><circle cx="10" cy="12" r="1.2"/></svg></button><span class="asta-sortable-text">Checkout redesign</span><span class="asta-sortable-meta">Growth · 24 votes</span><input type="hidden" name="order[]" value="checkout"></li> <li class="asta-sortable-item" data-id="search"><button type="button" class="asta-sortable-handle" aria-label="Reorder Faster search. Space to grab, arrows to move"><svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor" aria-hidden="true"><circle cx="6" cy="4" r="1.2"/><circle cx="10" cy="4" r="1.2"/><circle cx="6" cy="8" r="1.2"/><circle cx="10" cy="8" r="1.2"/><circle cx="6" cy="12" r="1.2"/><circle cx="10" cy="12" r="1.2"/></svg></button><span class="asta-sortable-text">Faster search</span><span class="asta-sortable-meta">Platform · 18 votes</span><input type="hidden" name="order[]" value="search"></li> <li class="asta-sortable-item" data-id="ds"><button type="button" class="asta-sortable-handle" aria-label="Reorder Design system docs. Space to grab, arrows to move"><svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor" aria-hidden="true"><circle cx="6" cy="4" r="1.2"/><circle cx="10" cy="4" r="1.2"/><circle cx="6" cy="8" r="1.2"/><circle cx="10" cy="8" r="1.2"/><circle cx="6" cy="12" r="1.2"/><circle cx="10" cy="12" r="1.2"/></svg></button><span class="asta-sortable-text">Design system docs</span><span class="asta-sortable-meta">Design · 15 votes</span><input type="hidden" name="order[]" value="ds"></li> <li class="asta-sortable-item" data-id="mobile"><button type="button" class="asta-sortable-handle" aria-label="Reorder Offline mode. Space to grab, arrows to move"><svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor" aria-hidden="true"><circle cx="6" cy="4" r="1.2"/><circle cx="10" cy="4" r="1.2"/><circle cx="6" cy="8" r="1.2"/><circle cx="10" cy="8" r="1.2"/><circle cx="6" cy="12" r="1.2"/><circle cx="10" cy="12" r="1.2"/></svg></button><span class="asta-sortable-text">Offline mode</span><span class="asta-sortable-meta">Mobile · 11 votes</span><input type="hidden" name="order[]" value="mobile"></li> <li class="asta-sortable-item" data-id="billing"><button type="button" class="asta-sortable-handle" aria-label="Reorder Usage-based billing. Space to grab, arrows to move"><svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor" aria-hidden="true"><circle cx="6" cy="4" r="1.2"/><circle cx="10" cy="4" r="1.2"/><circle cx="6" cy="8" r="1.2"/><circle cx="10" cy="8" r="1.2"/><circle cx="6" cy="12" r="1.2"/><circle cx="10" cy="12" r="1.2"/></svg></button><span class="asta-sortable-text">Usage-based billing</span><span class="asta-sortable-meta">Billing · 9 votes</span><input type="hidden" name="order[]" value="billing"></li> </ol>
Usage
The demo above, as code.
"use client";
import { useState } from "react";
import { SortableList } from "@/components/astabyte/sortable-list";
interface Item {
id: string;
title: string;
team: string;
votes: number;
}
const START: Item[] = [
{ id: "sso", title: "Single sign-on for teams", team: "Platform", votes: 214 },
{ id: "export", title: "Export reports as CSV", team: "Insights", votes: 168 },
{ id: "dark", title: "Dark mode for the editor", team: "Design", votes: 152 },
{ id: "mobile", title: "Offline mode on mobile", team: "Apps", votes: 97 },
{ id: "api", title: "Webhooks for new orders", team: "Platform", votes: 83 },
];
export default function SortableListDemo() {
const [items, setItems] = useState(START);
const changed = items.some((it, i) => it.id !== START[i].id);
return (
<div className="flex min-h-[480px] w-full items-center justify-center p-5 sm:p-10">
<div className="w-full max-w-[460px]">
<div className="mb-4 flex items-end justify-between gap-3">
<div>
<p className="text-[15px] font-medium tracking-[-0.01em] text-ink">Q1 priorities</p>
<p className="mt-0.5 text-[12.5px] text-mute">Drag by the handle, or focus it and press Space.</p>
</div>
<button
type="button"
onClick={() => setItems(START)}
disabled={!changed}
className="shrink-0 rounded-md px-2 py-1 text-[12.5px] text-mute outline-none transition-opacity hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50 disabled:opacity-0"
>
Reset
</button>
</div>
<SortableList
label="Q1 priorities"
items={items}
onReorder={setItems}
getLabel={(it) => it.title}
renderItem={(it, { index }) => (
<div className="flex items-center gap-3">
<span className="w-5 shrink-0 text-center font-mono text-[12px] tabular-nums text-mute">{index + 1}</span>
<div className="min-w-0 flex-1">
<p className="truncate text-[13.5px] font-medium text-ink">{it.title}</p>
<p className="text-[12px] text-mute">{it.team}</p>
</div>
<span className="shrink-0 rounded-md bg-paper-2 px-2 py-0.5 text-[11.5px] tabular-nums text-ink-2">▲ {it.votes}</span>
</div>
)}
/>
</div>
</div>
);
}