Sortable List
SaveA vertical list you reorder by dragging a handle or from the keyboard, where the lifted row floats over a dashed slot while its neighbors glide aside.
- Category
- Layout
- Version
- 0.1.0
- Frameworks
- Next.js, Vite + React
- Styling
- Tailwind CSS v4
Preview
Sortable List preview
Release checklist
Drag a handle or press Space on it
- 1Freeze the main branchInes, Mon
- 2Write the 2.4 release notesTomás, Mon
- 3Run the billing migration on stagingPriya, Tue
- 4Smoke test the agent runnerKenji, Tue
- 5Post the changelog and email customersInes, Wed
Press Space or Enter to lift. Use the arrow keys to move, Space or Enter to drop, Escape to cancel.
Installation
npx @shakenui/cli add sortable-listReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add sortable-list --dry-runUsage
sortable-list-example.tsx
"use client";
import { useState } from "react";
import { SortableList } from "@/components/shaken/ui/sortable-list";
type Step = { id: string; title: string; owner: string; due: string };
const initial: Step[] = [
{ id: "freeze", title: "Freeze the main branch", owner: "Ines", due: "Mon" },
{ id: "notes", title: "Write the 2.4 release notes", owner: "Tomás", due: "Mon" },
{ id: "migrate", title: "Run the billing migration on staging", owner: "Priya", due: "Tue" },
{ id: "smoke", title: "Smoke test the agent runner", owner: "Kenji", due: "Tue" },
{ id: "announce", title: "Post the changelog and email customers", owner: "Ines", due: "Wed" },
];
export default function SortableListExample() {
const [steps, setSteps] = useState(initial);
return (
<div className="grid w-full max-w-md grid-cols-[minmax(0,1fr)] gap-3">
<div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">
<h3 id="release-steps" className="text-sm font-semibold text-zinc-950 dark:text-white">
Release checklist
</h3>
<p className="text-xs text-zinc-500">Drag a handle or press Space on it</p>
</div>
<SortableList
aria-labelledby="release-steps"
items={steps}
onReorder={setSteps}
getKey={(step) => step.id}
getLabel={(step) => step.title}
>
{(step, { index }) => (
<div className="flex min-w-0 items-center gap-3">
<span className="w-4 shrink-0 text-right font-mono text-xs text-zinc-500 tabular-nums">{index + 1}</span>
<span className="min-w-0 flex-1 truncate">{step.title}</span>
<span className="hidden shrink-0 text-xs text-zinc-500 sm:inline">
{step.owner}, {step.due}
</span>
</div>
)}
</SortableList>
</div>
);
}API
| Prop | Type | Default | Description |
|---|---|---|---|
| items | T[] | — | The items in order. The list is controlled. |
| onReorder | (items: T[], move: { item, from, to }) => void | — | Called once per completed move with the new order. |
| getKey | (item: T) => string | — | A stable, unique key for each item. |
| getLabel | (item: T) => string | — | Plain text naming an item, used in the handle label and announcements. |
| children | (item: T, state: { index, lifted }) => ReactNode | — | Renders an item's content next to its handle. |
| itemClassName | string | — | Classes for each row's surface. |
| disabled | boolean | false | Turns off dragging and keyboard moves. |
Accessibility
- Each row has a handle button labeled "Reorder <item>" and described by the keyboard instructions.
- Space or Enter on a handle lifts the row (aria-pressed="true"); Arrow Up and Down move it, Home and End jump to the ends, Space or Enter drops it, and Escape puts it back. Tabbing away drops it where it is.
- Focus stays on the moved row's handle through every move.
- Pick up, every position change, drop and cancel are announced in an assertive live region with the position, such as "position 3 of 5".
- Escape also cancels a pointer drag.
- Keyboard moves change position without gliding. With reduced motion, rows never glide or scale; the lift shows through the border and shadow only.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/ui/sortable-list.tsxsortable-list- npm packages: motion@^14.14.0React and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/sortable-list/0.1.0.json.
ui/sortable-list.tsxShowHide
ui/sortable-list.tsx
"use client";
import { animate, motion, useMotionValue, useReducedMotion, type Transition } from "motion/react";
import {
useCallback,
useEffect,
useId,
useLayoutEffect,
useRef,
useState,
type ComponentProps,
type KeyboardEvent,
type PointerEvent,
type ReactNode,
} from "react";
function cx(...classes: (string | false | null | undefined)[]) {
return classes.filter(Boolean).join(" ");
}
/** Neighbors glide with the shared indicator spring: no bounce, about a third of a second. */
const glide: Transition = { type: "spring", duration: 0.35, bounce: 0 };
const lift: Transition = { type: "spring", duration: 0.25, bounce: 0 };
function moveKey(keys: string[], from: number, to: number) {
const next = keys.slice();
const [key] = next.splice(from, 1);
next.splice(to, 0, key!);
return next;
}
function rowGap(list: HTMLElement) {
const gap = parseFloat(getComputedStyle(list).rowGap);
return Number.isFinite(gap) ? gap : 0;
}
export interface SortableItemState {
/** Position in the list as shown right now, starting at 0. */
index: number;
/** The item is picked up, by pointer or keyboard. */
lifted: boolean;
}
export interface SortableListProps<T> extends Omit<ComponentProps<"ul">, "children" | "onChange"> {
/** The items, in order. The list is controlled: update them in `onReorder`. */
items: T[];
/** Called once per completed move with the items in their new order. */
onReorder: (items: T[], move: { item: T; from: number; to: number }) => void;
/** A stable, unique key for each item. */
getKey: (item: T) => string;
/** Plain text that names an item in the handle label and in announcements. */
getLabel: (item: T) => string;
/** Renders an item's content, to the right of its handle. */
children: (item: T, state: SortableItemState) => ReactNode;
/** Classes for each row's surface, merged after the defaults. */
itemClassName?: string;
/** Turns off dragging and keyboard moves. */
disabled?: boolean;
}
type Active = { key: string; mode: "pointer" | "keyboard"; from: number };
/**
* A vertical list you reorder by dragging a row's handle or from the keyboard. With a pointer the
* row lifts, follows the pointer and leaves a dashed slot where it will land while the other rows
* glide aside. From the keyboard, Space or Enter on a handle lifts the row, the arrow keys move it
* (Home and End jump to the ends), Space or Enter drops it and Escape puts it back. Every step is
* announced to screen readers. Keyboard moves and reduced motion change position without gliding.
*/
export function SortableList<T>({
items,
onReorder,
getKey,
getLabel,
children,
itemClassName,
disabled = false,
className,
...props
}: SortableListProps<T>) {
const instructionsId = useId();
const reduce = useReducedMotion() ?? false;
const listRef = useRef<HTMLUListElement>(null);
const rows = useRef(new Map<string, HTMLLIElement>());
const handles = useRef(new Map<string, HTMLButtonElement>());
// While an item is lifted the list renders a draft order; it is committed once, on drop.
const [draft, setDraftState] = useState<string[] | null>(null);
const draftRef = useRef<string[] | null>(null);
const setDraft = (next: string[] | null) => {
draftRef.current = next;
setDraftState(next);
};
const [active, setActiveState] = useState<Active | null>(null);
const activeRef = useRef<Active | null>(null);
const setActive = (next: Active | null) => {
activeRef.current = next;
setActiveState(next);
};
const [settling, setSettling] = useState<string | null>(null);
// Keyboard moves must not animate position; pointer drags glide. Stays off until the next drag.
const [glideOn, setGlideOn] = useState(true);
const [message, setMessage] = useState("");
const y = useMotionValue(0);
const drag = useRef<{ pointerId: number; grab: number; desired: number } | null>(null);
const settleFrom = useRef<number | null>(null);
const refocus = useRef<string | null>(null);
const moving = useRef(false);
const byKey = new Map(items.map((item) => [getKey(item), item] as const));
const keys = items.map(getKey);
const order = (draft ?? keys).filter((key) => byKey.has(key));
const total = order.length;
const labelOf = (key: string) => getLabel(byKey.get(key)!);
const announce = useCallback((text: string) => setMessage(text), []);
const commit = (key: string, final: string[], from: number) => {
const to = final.indexOf(key);
if (to !== from) onReorder(final.map((k) => byKey.get(k)!), { item: byKey.get(key)!, from, to });
return to;
};
// Keep the dragged row under the pointer after the list reorders around it, restore focus to
// the handle that keyboard moves carried through the DOM, and settle a dropped row into its slot.
useLayoutEffect(() => {
const current = activeRef.current;
if (current?.mode === "pointer" && drag.current) {
const row = rows.current.get(current.key);
if (row) y.set(drag.current.desired - row.offsetTop);
}
if (refocus.current) {
const handle = handles.current.get(refocus.current);
if (handle && document.activeElement !== handle) handle.focus({ preventScroll: true });
refocus.current = null;
}
moving.current = false;
});
useLayoutEffect(() => {
if (!settling || settleFrom.current == null) return;
const row = rows.current.get(settling);
const from = settleFrom.current;
settleFrom.current = null;
if (!row || reduce) {
y.set(0);
setSettling(null);
return;
}
y.set(from - row.offsetTop);
const controls = animate(y, 0, glide);
controls.then(() => setSettling((key) => (key === settling ? null : key)));
return () => controls.stop();
}, [settling, reduce, y]);
// Escape cancels a pointer drag too; the dragging cursor stays on while the pointer is down.
useEffect(() => {
if (active?.mode !== "pointer") return;
const onKey = (event: globalThis.KeyboardEvent) => {
if (event.key === "Escape") {
event.preventDefault();
endPointer(true);
}
};
const body = document.body.style;
const previous = { cursor: body.cursor, userSelect: body.userSelect };
body.cursor = "grabbing";
body.userSelect = "none";
window.addEventListener("keydown", onKey);
return () => {
window.removeEventListener("keydown", onKey);
body.cursor = previous.cursor;
body.userSelect = previous.userSelect;
};
// endPointer reads refs only.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [active?.mode]);
function onPointerDown(key: string, event: PointerEvent<HTMLButtonElement>) {
if (disabled || event.button !== 0 || activeRef.current) return;
const row = rows.current.get(key);
if (!row) return;
event.preventDefault();
event.currentTarget.setPointerCapture(event.pointerId);
y.stop();
y.set(0);
drag.current = { pointerId: event.pointerId, grab: event.clientY - row.getBoundingClientRect().top, desired: row.offsetTop };
const from = keys.indexOf(key);
setGlideOn(true);
setSettling(null);
setDraft(keys);
setActive({ key, mode: "pointer", from });
announce(`Picked up ${labelOf(key)}. Position ${from + 1} of ${total}.`);
}
function onPointerMove(key: string, event: PointerEvent<HTMLButtonElement>) {
const d = drag.current;
const list = listRef.current;
const row = rows.current.get(key);
const current = draftRef.current;
if (!d || event.pointerId !== d.pointerId || !list || !row || !current) return;
const height = row.offsetHeight;
const first = rows.current.get(current[0]!)?.offsetTop ?? 0;
const bottom = list.clientHeight - height;
// Where the row's top wants to be, in list coordinates, held loosely inside the list.
const desired = Math.min(Math.max(event.clientY - list.getBoundingClientRect().top - d.grab, first - 12), bottom + 12);
d.desired = desired;
// The target slot counts the other rows whose middle sits above the dragged row's middle,
// laid out as if the dragged row were gone, so the answer never flips back and forth.
const gap = rowGap(list);
let top = first;
let to = 0;
for (const k of current) {
if (k === key) continue;
const el = rows.current.get(k);
if (!el) continue;
if (top + el.offsetHeight / 2 < desired + height / 2) to++;
top += el.offsetHeight + gap;
}
const from = current.indexOf(key);
if (to !== from) {
setDraft(moveKey(current, from, to));
announce(`${labelOf(key)}, position ${to + 1} of ${current.length}.`);
}
y.set(desired - row.offsetTop);
}
function endPointer(cancel: boolean) {
const d = drag.current;
const current = activeRef.current;
if (!d || !current) return;
drag.current = null;
const final = cancel ? keys : (draftRef.current ?? keys);
settleFrom.current = d.desired;
setSettling(current.key);
setDraft(null);
setActive(null);
const label = labelOf(current.key);
if (cancel) {
announce(`Move cancelled. ${label} returned to position ${current.from + 1} of ${total}.`);
} else {
const to = commit(current.key, final, current.from);
announce(`Dropped ${label} at position ${to + 1} of ${total}.`);
}
}
function onKeyDown(key: string, event: KeyboardEvent<HTMLButtonElement>) {
if (disabled) return;
const current = activeRef.current;
const lifted = current?.key === key && current.mode === "keyboard";
const label = labelOf(key);
if (!lifted) {
if ((event.key === " " || event.key === "Enter") && !current) {
event.preventDefault();
const from = keys.indexOf(key);
setGlideOn(false);
setDraft(keys);
setActive({ key, mode: "keyboard", from });
announce(`Lifted ${label}, position ${from + 1} of ${total}. Use the arrow keys to move it, Space to drop, Escape to cancel.`);
}
return;
}
const draftKeys = draftRef.current ?? keys;
const from = draftKeys.indexOf(key);
let to = from;
switch (event.key) {
case "ArrowUp":
case "ArrowLeft":
to = Math.max(0, from - 1);
break;
case "ArrowDown":
case "ArrowRight":
to = Math.min(draftKeys.length - 1, from + 1);
break;
case "Home":
to = 0;
break;
case "End":
to = draftKeys.length - 1;
break;
case " ":
case "Enter": {
event.preventDefault();
const final = commit(key, draftKeys, current.from);
moving.current = true;
refocus.current = key;
setDraft(null);
setActive(null);
announce(`Dropped ${label} at position ${final + 1} of ${total}.`);
return;
}
case "Escape":
event.preventDefault();
cancelKeyboard(key);
return;
default:
return;
}
event.preventDefault();
if (to === from) return;
// React moves the focused row's node, which blurs it; the layout effect focuses it again.
moving.current = true;
refocus.current = key;
setDraft(moveKey(draftKeys, from, to));
announce(`${label}, position ${to + 1} of ${draftKeys.length}.`);
}
function cancelKeyboard(key: string) {
const current = activeRef.current;
if (!current) return;
moving.current = true;
refocus.current = key;
setDraft(null);
setActive(null);
announce(`Move cancelled. ${labelOf(key)} returned to position ${current.from + 1} of ${total}.`);
}
function onBlur(key: string) {
const current = activeRef.current;
if (moving.current || current?.mode !== "keyboard" || current.key !== key) return;
// Tabbing or clicking away drops the item where it is.
const final = commit(key, draftRef.current ?? keys, current.from);
setDraft(null);
setActive(null);
announce(`Dropped ${labelOf(key)} at position ${final + 1} of ${total}.`);
}
return (
<>
<ul ref={listRef} className={cx("relative grid grid-cols-[minmax(0,1fr)] gap-1.5", className)} {...props}>
{order.map((key, index) => {
const item = byKey.get(key)!;
const isActive = active?.key === key;
const lifted = isActive;
const floating = isActive && active.mode === "pointer";
const tracked = floating || settling === key;
const label = getLabel(item);
return (
<motion.li
key={key}
ref={(el: HTMLLIElement | null) => {
if (el) rows.current.set(key, el);
else rows.current.delete(key);
}}
layout={glideOn && !reduce && !tracked ? "position" : false}
transition={glide}
className={cx("relative", tracked && "z-10")}
>
{/* The slot the floating row will drop into. */}
<span
aria-hidden="true"
className={cx(
"pointer-events-none absolute inset-0 rounded-lg border border-dashed border-zinc-950/20 bg-zinc-950/[0.02] dark:border-white/20 dark:bg-white/[0.02]",
"transition-opacity duration-150 ease-out motion-reduce:transition-none",
floating ? "opacity-100" : "opacity-0",
)}
/>
<motion.div
style={tracked ? { y } : undefined}
animate={{ scale: lifted && !reduce ? 1.02 : 1 }}
transition={lift}
className={cx(
"relative flex min-h-11 items-center gap-1.5 rounded-lg border bg-white py-1.5 pr-3 pl-1.5 text-sm text-zinc-950 dark:bg-black dark:text-white",
"transition-[border-color] duration-150 ease-out motion-reduce:transition-none",
// The lift shadow lives on a pseudo-element so only its opacity animates.
"after:pointer-events-none after:absolute after:-inset-px after:rounded-[inherit] after:opacity-0 after:content-['']",
"after:shadow-[0_14px_32px_-12px_rgb(0_0_0/0.28),0_3px_8px_-3px_rgb(0_0_0/0.1)]",
"dark:after:shadow-[0_18px_40px_-12px_rgb(0_0_0/1),inset_0_1px_0_rgb(255_255_255/0.1)]",
"after:transition-opacity after:duration-200 after:ease-out motion-reduce:after:transition-none",
lifted
? "border-zinc-950/15 after:opacity-100 dark:border-white/25"
: "border-zinc-950/10 dark:border-white/10",
itemClassName,
)}
>
<button
type="button"
ref={(el) => {
if (el) handles.current.set(key, el);
else handles.current.delete(key);
}}
disabled={disabled}
aria-label={`Reorder ${label}`}
aria-describedby={instructionsId}
aria-pressed={lifted && active.mode === "keyboard"}
onPointerDown={(event) => onPointerDown(key, event)}
onPointerMove={(event) => onPointerMove(key, event)}
onPointerUp={() => endPointer(false)}
onPointerCancel={() => endPointer(true)}
onKeyDown={(event) => onKeyDown(key, event)}
onBlur={() => onBlur(key)}
className={cx(
"inline-flex size-7 shrink-0 touch-none items-center justify-center rounded-md select-none",
"text-zinc-400 transition-colors duration-150 ease-out motion-reduce:transition-none dark:text-zinc-500",
"hover:bg-zinc-950/[0.04] hover:text-zinc-700 dark:hover:bg-white/[0.06] dark:hover:text-zinc-300",
"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-0 focus-visible:outline-sky-500",
"disabled:pointer-events-none disabled:opacity-40",
lifted ? "cursor-grabbing text-zinc-700 dark:text-zinc-200" : "cursor-grab",
)}
>
<GripGlyph />
</button>
<div className="min-w-0 flex-1">{children(item, { index, lifted })}</div>
</motion.div>
</motion.li>
);
})}
</ul>
<p id={instructionsId} hidden>
Press Space or Enter to lift. Use the arrow keys to move, Space or Enter to drop, Escape to cancel.
</p>
<span aria-live="assertive" aria-atomic="true" className="sr-only">
{message}
</span>
</>
);
}
function GripGlyph() {
return (
<svg aria-hidden="true" viewBox="0 0 16 16" className="size-4" fill="currentColor">
<circle cx="6" cy="4" r="1.15" />
<circle cx="10" cy="4" r="1.15" />
<circle cx="6" cy="8" r="1.15" />
<circle cx="10" cy="8" r="1.15" />
<circle cx="6" cy="12" r="1.15" />
<circle cx="10" cy="12" r="1.15" />
</svg>
);
}