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