{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"reorder-list","type":"registry:component","title":"Reorder list","description":"Picks rows up by the handle and slides the rest out of the way.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/reorder-list.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useLayoutEffect, useRef, useState } from \"react\";\nimport { Reorder, motion, useDragControls, type Variants } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nexport type ReorderListItem = { id: string; label: string; meta?: string };\n\n// No bounce: rows that overshoot their slot would read as the wrong order.\nconst SLIDE = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\n// Lifting is a touch slower than setting down, so the drop feels decisive.\nconst LIFT = { type: \"spring\", duration: 0.25, bounce: 0 } as const;\nconst SETTLE = { type: \"spring\", duration: 0.2, bounce: 0 } as const;\n// Enough to read as picked up without the row outgrowing the column.\nconst LIFT_SCALE = 1.02;\n// Critically damped (damping = 2 * sqrt(stiffness)): the released row glides\n// home carrying its release velocity and stops dead in its slot.\nconst HOME = { bounceStiffness: 500, bounceDamping: 45 };\n// Effectively instant, for reduced motion.\nconst SNAP = { bounceStiffness: 1e6, bounceDamping: 1e7 };\n// A little give past the ends of the list, never enough to grow the page.\nconst EDGE_GIVE = 0.08;\n// Layered and transparent so it darkens whatever is underneath. The 1px ring\n// keeps the lifted edge visible in dark mode, where shadows barely show.\nconst LIFTED_SHADOW = [\n  \"0 0 0 1px light-dark(oklch(0 0 0 / 0.06), oklch(1 0 0 / 0.08))\",\n  \"0 2px 4px light-dark(oklch(0 0 0 / 0.06), oklch(0 0 0 / 0.4))\",\n  \"0 16px 32px -8px light-dark(oklch(0 0 0 / 0.18), oklch(0 0 0 / 0.7))\",\n].join(\", \");\n\ntype Grab = { id: string; before: ReorderListItem[] };\n\n/**\n * Drag a row by its handle, or from the keyboard: focus a handle, Space (or\n * Enter) picks the row up, arrows / Home / End move it, Space drops it and\n * Escape puts it back. Without a row held, the arrows move between handles.\n */\nexport function ReorderList({\n  items,\n  onReorder,\n  label,\n  className,\n}: {\n  items: ReorderListItem[];\n  onReorder: (items: ReorderListItem[]) => void;\n  label: string;\n  className?: string;\n}) {\n  const reduceMotion = !!useReducedMotion();\n  const listRef = useRef<HTMLUListElement>(null);\n  const handles = useRef(new Map<string, HTMLButtonElement>());\n  const [grab, setGrab] = useState<Grab | null>(null);\n  const [dragging, setDragging] = useState(false);\n  const [announcement, setAnnouncement] = useState(\"\");\n  const instructions = useId();\n\n  // For callbacks that fire after later renders than the one that made them.\n  const latest = useRef({ items, grab });\n  useEffect(() => {\n    latest.current = { items, grab };\n  });\n\n  // React moves the held row's DOM node when the order changes, which can\n  // drop focus. Put it back before paint so the next arrow press still lands.\n  useLayoutEffect(() => {\n    if (!grab) return;\n    const handle = handles.current.get(grab.id);\n    if (handle && document.activeElement !== handle) {\n      handle.focus({ preventScroll: true });\n    }\n  }, [grab, items]);\n\n  const name = (id: string, list = items) =>\n    list.find((i) => i.id === id)?.label ?? \"\";\n  const position = (id: string, list = items) =>\n    `position ${list.findIndex((i) => i.id === id) + 1} of ${list.length}`;\n\n  const pickUp = (id: string) => {\n    setGrab({ id, before: items });\n    setAnnouncement(`Picked up ${name(id)}, ${position(id)}.`);\n  };\n\n  const drop = () => {\n    if (!grab) return;\n    setGrab(null);\n    setAnnouncement(`Dropped ${name(grab.id)} at ${position(grab.id)}.`);\n  };\n\n  const cancel = () => {\n    if (!grab) return;\n    onReorder(grab.before);\n    setGrab(null);\n    setAnnouncement(\n      `Cancelled. ${name(grab.id)} returned to ${position(grab.id, grab.before)}.`,\n    );\n  };\n\n  const moveTo = (id: string, to: number) => {\n    const from = items.findIndex((i) => i.id === id);\n    const target = Math.max(0, Math.min(to, items.length - 1));\n    if (target === from) return;\n    const next = [...items];\n    next.splice(target, 0, ...next.splice(from, 1));\n    onReorder(next);\n    setAnnouncement(`Moved ${name(id)} to ${position(id, next)}.`);\n  };\n\n  const onKeyDown = (id: string, event: React.KeyboardEvent) => {\n    const index = items.findIndex((i) => i.id === id);\n    const held = grab?.id === id;\n    const focus = (offset: number) =>\n      handles.current.get(items[index + offset]?.id)?.focus();\n    const keys: Record<string, (() => void) | undefined> = {\n      \" \": () => (held ? drop() : pickUp(id)),\n      Enter: () => (held ? drop() : pickUp(id)),\n      Escape: held ? cancel : undefined,\n      ArrowUp: () => (held ? moveTo(id, index - 1) : focus(-1)),\n      ArrowDown: () => (held ? moveTo(id, index + 1) : focus(1)),\n      Home: held ? () => moveTo(id, 0) : undefined,\n      End: held ? () => moveTo(id, items.length - 1) : undefined,\n    };\n    const run = keys[event.key];\n    if (!run) return;\n    event.preventDefault();\n    run();\n  };\n\n  // Tabbing or clicking away sets the row down where it is. Checked a frame\n  // later, because a reorder can blur the handle for a moment before the\n  // layout effect above refocuses it.\n  const onBlur = (id: string) => {\n    requestAnimationFrame(() => {\n      const { grab: current, items: list } = latest.current;\n      if (current?.id !== id) return;\n      if (document.activeElement === handles.current.get(id)) return;\n      setGrab(null);\n      setAnnouncement(`Dropped ${name(id, list)} at ${position(id, list)}.`);\n    });\n  };\n\n  return (\n    <div className={cn(\"w-[400px] max-w-full\", className)}>\n      <Reorder.Group\n        ref={listRef}\n        axis=\"y\"\n        values={items}\n        onReorder={onReorder}\n        aria-label={label}\n        className={cn(\n          \"flex flex-col gap-3\",\n          // Keeps a fast drag from painting a selection across the list.\n          dragging && \"cursor-grabbing select-none\",\n        )}\n      >\n        {items.map((item) => (\n          <Row\n            key={item.id}\n            item={item}\n            lifted={grab?.id === item.id}\n            reduceMotion={reduceMotion}\n            constraints={listRef}\n            describedBy={instructions}\n            handleRef={(node) => {\n              if (node) handles.current.set(item.id, node);\n              else handles.current.delete(item.id);\n            }}\n            onKeyDown={(e) => onKeyDown(item.id, e)}\n            onBlur={() => onBlur(item.id)}\n            onDragStart={() => {\n              drop();\n              setDragging(true);\n            }}\n            onDragEnd={() => {\n              setDragging(false);\n              const { items: list } = latest.current;\n              setAnnouncement(\n                `Dropped ${name(item.id, list)} at ${position(item.id, list)}.`,\n              );\n            }}\n          />\n        ))}\n      </Reorder.Group>\n\n      <p id={instructions} className=\"sr-only\">\n        Press Space to pick up. While holding, use the arrow keys to move,\n        Space to drop, or Escape to cancel.\n      </p>\n      <p className=\"sr-only\" aria-live=\"assertive\" aria-atomic>\n        {announcement}\n      </p>\n    </div>\n  );\n}\n\nfunction Row({\n  item,\n  lifted,\n  reduceMotion,\n  constraints,\n  describedBy,\n  handleRef,\n  onKeyDown,\n  onBlur,\n  onDragStart,\n  onDragEnd,\n}: {\n  item: ReorderListItem;\n  lifted: boolean;\n  reduceMotion: boolean;\n  constraints: React.RefObject<HTMLUListElement | null>;\n  describedBy: string;\n  handleRef: (node: HTMLButtonElement | null) => void;\n  onKeyDown: (event: React.KeyboardEvent) => void;\n  onBlur: () => void;\n  onDragStart: () => void;\n  onDragEnd: () => void;\n}) {\n  const controls = useDragControls();\n\n  // Scale goes through Motion alongside the x/y that Reorder drives, so they\n  // compose into one transform. A CSS scale class here would fight them.\n  const row: Variants = {\n    rest: { scale: 1, transition: SETTLE },\n    lifted: { scale: reduceMotion ? 1 : LIFT_SCALE, transition: LIFT },\n  };\n  // The shadow fades on its own layer: opacity is cheap to animate, and the\n  // shadow can use light-dark(), which Motion can't interpolate.\n  const shadow: Variants = {\n    rest: { opacity: 0, transition: SETTLE },\n    lifted: { opacity: 1, transition: LIFT },\n  };\n\n  return (\n    <Reorder.Item\n      value={item}\n      // Rows never change size, so only position is projected and the text\n      // inside can't stretch mid-slide.\n      layout=\"position\"\n      dragListener={false}\n      dragControls={controls}\n      dragConstraints={constraints}\n      dragElastic={EDGE_GIVE}\n      dragTransition={reduceMotion ? SNAP : HOME}\n      transition={{ layout: reduceMotion ? { duration: 0 } : SLIDE }}\n      initial={false}\n      animate={lifted ? \"lifted\" : \"rest\"}\n      whileDrag=\"lifted\"\n      variants={row}\n      onDragStart={onDragStart}\n      onDragEnd={onDragEnd}\n      className={cn(\n        \"relative flex items-center gap-3 rounded-[16px] bg-muted p-1.5 pr-4\",\n        // Reorder only raises a row while it's pointer-dragged, so a row\n        // moved from the keyboard needs this to slide over its neighbours.\n        lifted && \"z-10!\",\n      )}\n    >\n      <motion.span\n        aria-hidden\n        variants={shadow}\n        style={{ boxShadow: LIFTED_SHADOW }}\n        className=\"pointer-events-none absolute inset-0 rounded-[inherit]\"\n      />\n      {/* 6px row padding around 10px corners keeps the radii concentric: 16 = 10 + 6,\n          and the 40px handle plus that padding makes a 52px row.\n          No press scale: pressing lifts the whole row, which is the feedback. */}\n      <button\n        ref={handleRef}\n        type=\"button\"\n        aria-label={`Reorder ${item.label}`}\n        aria-describedby={describedBy}\n        onPointerDown={(e) => {\n          // Stops the press from starting a text selection or moving focus.\n          e.preventDefault();\n          controls.start(e);\n        }}\n        onKeyDown={onKeyDown}\n        onBlur={onBlur}\n        className={cn(\n          \"relative flex size-10 shrink-0 cursor-grab touch-none items-center justify-center rounded-[10px] text-muted-foreground outline-hidden transition-[color,background-color] duration-150 ease-out select-none hover:bg-foreground/5 hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground active:cursor-grabbing\",\n          lifted && \"bg-foreground/5 text-foreground\",\n        )}\n      >\n        <svg\n          viewBox=\"0 0 16 16\"\n          className=\"size-5\"\n          fill=\"currentColor\"\n          aria-hidden\n        >\n          <circle cx=\"6\" cy=\"4\" r=\"1.25\" />\n          <circle cx=\"10\" cy=\"4\" r=\"1.25\" />\n          <circle cx=\"6\" cy=\"8\" r=\"1.25\" />\n          <circle cx=\"10\" cy=\"8\" r=\"1.25\" />\n          <circle cx=\"6\" cy=\"12\" r=\"1.25\" />\n          <circle cx=\"10\" cy=\"12\" r=\"1.25\" />\n        </svg>\n      </button>\n      <span className=\"relative min-w-0 flex-1 truncate text-[15px] font-medium text-foreground\">\n        {item.label}\n      </span>\n      {item.meta && (\n        <span className=\"relative shrink-0 text-[13px] text-muted-foreground tabular-nums\">\n          {item.meta}\n        </span>\n      )}\n    </Reorder.Item>\n  );\n}\n\nconst TRACKS: ReorderListItem[] = [\n  { id: \"a\", label: \"Nuvole bianche\", meta: \"5:57\" },\n  { id: \"b\", label: \"Holocene\", meta: \"5:37\" },\n  { id: \"c\", label: \"Retrograde\", meta: \"3:43\" },\n  { id: \"d\", label: \"Weightless\", meta: \"8:09\" },\n  { id: \"e\", label: \"Svefn-g-englar\", meta: \"10:04\" },\n];\n\nexport default function ReorderListDemo() {\n  const [tracks, setTracks] = useState(TRACKS);\n  return <ReorderList items={tracks} onReorder={setTracks} label=\"Playlist\" />;\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"categories":["cards"],"docs":"From ui lab: https://lab.xevrion.dev/lab/reorder-list"}