{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sortable-list",
  "type": "registry:ui",
  "title": "Sortable List",
  "description": "A list whose order the person sets, three ways: dragging a row by its handle (mouse, pen or touch), lifting it with the keyboard and moving it with the arrow keys, or pressing \"Move up\" and \"Move down\" buttons. Every move is read out.",
  "categories": [
    "ui"
  ],
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/announce",
    "@rivier-ui/cn",
    "@rivier-ui/motion",
    "@rivier-ui/use-controllable-state"
  ],
  "files": [
    {
      "path": "registry/ui/sortable-list.tsx",
      "type": "registry:ui",
      "target": "components/ui/sortable-list.tsx",
      "content": "\"use client\";\n/**\n * @name sortable-list\n * @category ui\n * @description A list whose order the person sets, three ways: dragging a row by its handle (mouse, pen or touch), lifting it with the keyboard and moving it with the arrow keys, or pressing \"Move up\" and \"Move down\" buttons. Every move is read out.\n * @when The order itself is the data: the stops of a plan, priorities, pictures in a gallery, columns to show. Always give the rows SortableMoveButtons or a SortableHandle (both is best): dragging alone leaves out people who cannot drag (WCAG 2.5.7). It is one vertical list; it does not move rows between lists or sort a grid. For a list sorted by a rule (newest first) use a select for the rule instead; for choosing rather than ordering use chip or checkboxes.\n * @example\n * const [stops, setStops] = useState([\"market\", \"lunch\", \"museum\"]);\n * <SortableList values={stops} onValuesChange={setStops} aria-label=\"Stops, in order\">\n *   {stops.map((id) => (\n *     <SortableItem key={id} value={id} label={NAMES[id]}>\n *       <SortableHandle />\n *       <span className=\"min-w-0 flex-1 truncate\">{NAMES[id]}</span>\n *       <SortableMoveButtons />\n *     </SortableItem>\n *   ))}\n * </SortableList>\n *\n * // Uncontrolled: the list keeps the order and gives it to its children\n * <SortableList defaultValues={[\"a\", \"b\", \"c\"]} aria-label=\"Priorities\">\n *   {(order) => order.map((id) => <SortableItem key={id} value={id} label={id}>…</SortableItem>)}\n * </SortableList>\n *\n * // Save once, when a row has been let go, not at every step it passes\n * <SortableList values={stops} onValuesChange={setStops} onDropped={({ from, to, values }) => (from === to ? undefined : save(values))} aria-label=\"Stops, in order\">…</SortableList>\n */\nimport { ChevronDown, ChevronUp, GripVertical } from \"lucide-react\";\nimport { MotionConfig, Reorder, useDragControls, type DragControls } from \"motion/react\";\nimport {\n  createContext,\n  use,\n  useEffect,\n  useId,\n  useRef,\n  useState,\n  type ComponentProps,\n  type KeyboardEvent,\n  type PointerEvent as ReactPointerEvent,\n  type ReactNode,\n} from \"react\";\nimport { announce } from \"@/lib/announce\";\nimport { cn } from \"@/lib/cn\";\nimport { DURATION, EASE } from \"@/lib/motion\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\n\n/** What is read out. Each takes the row's label, its position counted from 1, and how many rows there are. Translate them with the interface. */\nexport type SortableMessages = {\n  lifted: (label: string, position: number, total: number) => string;\n  moved: (label: string, position: number, total: number) => string;\n  dropped: (label: string, position: number, total: number) => string;\n  cancelled: (label: string, position: number, total: number) => string;\n  /** How the keyboard works, given as the handle's description. */\n  instructions: string;\n  /** The handle's name. */\n  handle: (label: string) => string;\n  moveUp: (label: string) => string;\n  moveDown: (label: string) => string;\n};\n\nexport const SORTABLE_MESSAGES: SortableMessages = {\n  lifted: (label, position, total) => `${label}, lifted. Position ${position} of ${total}. Use the Up and Down arrow keys to move it, Space to drop it, Escape to put it back.`,\n  moved: (label, position, total) => `${label}, position ${position} of ${total}.`,\n  dropped: (label, position, total) => `${label}, dropped at position ${position} of ${total}.`,\n  cancelled: (label, position, total) => `${label}, put back at position ${position} of ${total}.`,\n  instructions: \"Press Space or Enter to lift, the Up and Down arrow keys to move, Space or Enter to drop, Escape to put it back.\",\n  handle: (label) => `Reorder ${label}`,\n  moveUp: (label) => `Move ${label} up`,\n  moveDown: (label) => `Move ${label} down`,\n};\n\n/** One finished move: what `onDropped` is given. */\nexport type SortableDrop = {\n  /** The id of the row that was moved. */\n  value: string;\n  /** Where it was when it was picked up, counted from 0. */\n  from: number;\n  /** Where it was let go, counted from 0. The same as `from` when it was put down where it started. */\n  to: number;\n  /** The ids in the order the list now has. */\n  values: string[];\n};\n\ntype ListContextValue = {\n  values: string[];\n  setValues: (values: string[]) => void;\n  /** A row was picked up (a drag began, or it was lifted with the keyboard): remembers where from. */\n  begin: (value: string) => void;\n  /** The row was let go: reports the move, once. `values` is the order when it is newer than the one rendered (a press of a move button). */\n  finish: (value: string, values?: string[]) => void;\n  /** The row went back where it was (Escape): nothing is reported. */\n  abandon: () => void;\n  messages: SortableMessages;\n  disabled: boolean;\n  instructionsId: string;\n  /** The row lifted with the keyboard, and the order to go back to on Escape. */\n  lifted: { value: string; from: string[] } | null;\n  setLifted: (lifted: { value: string; from: string[] } | null) => void;\n};\n\nconst ListContext = createContext<ListContextValue | null>(null);\n\ntype ItemContextValue = {\n  value: string;\n  label: string;\n  index: number;\n  total: number;\n  disabled: boolean;\n  lifted: boolean;\n  controls: DragControls;\n  /** Moves the row to an index (clamped) and says where it is now. False when it was already there. */\n  moveTo: (index: number) => boolean;\n  /** The same as one whole move, reported to `onDropped`: what a move button does. */\n  moveOnce: (index: number) => boolean;\n};\n\nconst ItemContext = createContext<ItemContextValue | null>(null);\n\nfunction useList(part: string): ListContextValue {\n  const context = use(ListContext);\n  if (!context) throw new Error(`<${part}> must be used inside <SortableList>.`);\n  return context;\n}\n\nfunction useItem(part: string): ItemContextValue {\n  const context = use(ItemContext);\n  if (!context) throw new Error(`<${part}> must be used inside <SortableItem>.`);\n  return context;\n}\n\nexport type SortableListProps = Omit<ComponentProps<\"ol\">, \"children\" | \"values\" | \"onDrag\" | \"onDragStart\" | \"onDragEnd\" | \"onAnimationStart\" | \"ref\"> & {\n  /** The ids of the rows, in order, controlled. Ids are strings and unique. */\n  values?: string[];\n  /** The starting order when uncontrolled. */\n  defaultValues?: string[];\n  /** Called with the new order at every step: each row a dragged row passes, each arrow key, each press of a move button. */\n  onValuesChange?: (values: string[]) => void;\n  /**\n   * Called once when a move ends: a dragged row is let go, a row lifted with the keyboard is dropped (Space,\n   * Enter, Tab or focus leaving), or a move button is pressed. Not called when a lifted row is put back with\n   * Escape. `from` and `to` are equal when the row was put down where it started. The place to save the order.\n   */\n  onDropped?: (drop: SortableDrop) => void;\n  /** Stops all reordering. */\n  disabled?: boolean;\n  /** The words that are read out and the names of the controls, where the English defaults are not wanted. */\n  messages?: Partial<SortableMessages>;\n  /** The rows (one SortableItem per id, keyed by it), or a function that is given the order and returns them. */\n  children: ReactNode | ((values: string[]) => ReactNode);\n};\n\n/**\n * An ordered list (`ol`), so its rows are read as \"2 of 5\". Name it with `aria-label` or\n * `aria-labelledby`. Rows slide to their new places with a transform; under reduced motion they are simply\n * in their new places.\n */\nexport function SortableList({ className, values, defaultValues, onValuesChange, onDropped, disabled = false, messages, children, ...props }: SortableListProps) {\n  const [order, setOrder] = useControllableState({ value: values, defaultValue: defaultValues ?? [], onChange: onValuesChange });\n  const [lifted, setLifted] = useState<ListContextValue[\"lifted\"]>(null);\n  const instructionsId = useId();\n  const merged = { ...SORTABLE_MESSAGES, ...messages };\n  /** The row in the air and where it was picked up: one move is reported once, however it ends. */\n  const moving = useRef<{ value: string; from: number } | null>(null);\n  /** The newest order and listener, for a drag that ends between renders. */\n  const latest = useRef({ order, onDropped });\n  useEffect(() => {\n    latest.current = { order, onDropped };\n  });\n\n  const begin = (value: string): void => {\n    moving.current = { value, from: latest.current.order.indexOf(value) };\n  };\n  const finish = (value: string, next?: string[]): void => {\n    const move = moving.current;\n    moving.current = null;\n    if (!move || move.value !== value) return;\n    const now = next ?? latest.current.order;\n    const to = now.indexOf(value);\n    if (move.from !== -1 && to !== -1) latest.current.onDropped?.({ value, from: move.from, to, values: [...now] });\n  };\n  const abandon = (): void => {\n    moving.current = null;\n  };\n\n  return (\n    <ListContext value={{ values: order, setValues: setOrder, begin, finish, abandon, messages: merged, disabled, instructionsId, lifted, setLifted }}>\n      <MotionConfig reducedMotion=\"user\" transition={{ duration: DURATION.base, ease: EASE }}>\n        <Reorder.Group as=\"ol\" axis=\"y\" values={order} onReorder={setOrder} data-slot=\"sortable-list\" className={cn(\"flex w-full min-w-0 flex-col gap-2\", className)} {...props}>\n          {typeof children === \"function\" ? children(order) : children}\n        </Reorder.Group>\n      </MotionConfig>\n      <span id={instructionsId} hidden>\n        {merged.instructions}\n      </span>\n    </ListContext>\n  );\n}\n\nexport type SortableItemProps = Omit<ComponentProps<\"li\">, \"value\" | \"onDrag\" | \"onDragStart\" | \"onDragEnd\" | \"onAnimationStart\" | \"ref\"> & {\n  /** The row's id: one of the list's `values`. */\n  value: string;\n  /** The row's name in announcements and in the names of its handle and buttons (\"Lunch\"). */\n  label: string;\n  /** This row cannot be moved by the person (others can still move past it). */\n  disabled?: boolean;\n  /**\n   * What starts a drag. \"handle\" (default): only the SortableHandle. \"row\": the whole row, at once with a\n   * mouse or pen, and after a press of half a second on a touch screen, so that the list can still be scrolled.\n   */\n  dragBy?: \"handle\" | \"row\";\n};\n\n/** How long a finger rests on a row before it is lifted, and how far it may wander meanwhile. */\nconst LONG_PRESS = 450;\nconst LONG_PRESS_SLOP = 8;\n\n/** One row. A flat surface with an edge; while it is lifted or dragged the edge takes the highlight colour and the handle is marked as pressed. */\nexport function SortableItem({ className, value, label, disabled = false, dragBy = \"handle\", children, onPointerDown, ...props }: SortableItemProps) {\n  const list = useList(\"SortableItem\");\n  const controls = useDragControls();\n  const [dragging, setDragging] = useState(false);\n  const row = useRef<HTMLLIElement>(null);\n  /** A touch that may become a long press, or has. */\n  const press = useRef<{ timer: number; x: number; y: number; held: boolean } | null>(null);\n\n  const index = list.values.indexOf(value);\n  const total = list.values.length;\n  const blocked = disabled || list.disabled;\n  const lifted = list.lifted?.value === value;\n\n  const moveTo = (to: number): boolean => {\n    const target = Math.min(total - 1, Math.max(0, to));\n    if (index === -1 || target === index) return false;\n    const next = list.values.filter((item) => item !== value);\n    next.splice(target, 0, value);\n    list.setValues(next);\n    announce(list.messages.moved(label, target + 1, total));\n    return true;\n  };\n  /** A press of a move button: picked up, moved and let go in one. */\n  const moveOnce = (to: number): boolean => {\n    const target = Math.min(total - 1, Math.max(0, to));\n    list.begin(value);\n    if (!moveTo(target)) {\n      list.abandon();\n      return false;\n    }\n    const next = list.values.filter((item) => item !== value);\n    next.splice(target, 0, value);\n    list.finish(value, next);\n    return true;\n  };\n\n  const endPress = (): void => {\n    if (press.current) window.clearTimeout(press.current.timer);\n    press.current = null;\n  };\n  useEffect(() => endPress, []);\n\n  // Once a long press has lifted the row, the finger moves the row, not the page. Only a listener that is\n  // not passive may stop the page from scrolling, and React's are passive.\n  useEffect(() => {\n    const element = row.current;\n    if (!element || dragBy !== \"row\") return;\n    const hold = (event: TouchEvent): void => {\n      if (press.current?.held) event.preventDefault();\n    };\n    const menu = (event: Event): void => {\n      if (press.current) event.preventDefault();\n    };\n    element.addEventListener(\"touchmove\", hold, { passive: false });\n    element.addEventListener(\"contextmenu\", menu);\n    return () => {\n      element.removeEventListener(\"touchmove\", hold);\n      element.removeEventListener(\"contextmenu\", menu);\n    };\n  }, [dragBy]);\n\n  const handlePointerDown = (event: ReactPointerEvent<HTMLLIElement>): void => {\n    onPointerDown?.(event);\n    if (event.defaultPrevented || blocked || dragBy !== \"row\" || event.button !== 0) return;\n    if ((event.target as Element).closest(\"button, a, input, select, textarea, [role=button], [data-slot=sortable-handle]\")) return;\n    if (event.pointerType !== \"touch\") {\n      controls.start(event);\n      return;\n    }\n    endPress();\n    const native = event.nativeEvent;\n    press.current = {\n      x: event.clientX,\n      y: event.clientY,\n      held: false,\n      timer: window.setTimeout(() => {\n        if (!press.current) return;\n        press.current.held = true;\n        controls.start(native);\n      }, LONG_PRESS),\n    };\n  };\n\n  return (\n    <ItemContext value={{ value, label, index, total, disabled: blocked, lifted, controls, moveTo, moveOnce }}>\n      <Reorder.Item\n        as=\"li\"\n        ref={row}\n        value={value}\n        // The handle is the row's keyboard stop, not the row itself.\n        tabIndex={undefined}\n        drag={blocked ? false : \"y\"}\n        dragListener={false}\n        dragControls={controls}\n        onDragStart={() => {\n          setDragging(true);\n          list.begin(value);\n        }}\n        onDragEnd={() => {\n          setDragging(false);\n          endPress();\n          announce(list.messages.dropped(label, list.values.indexOf(value) + 1, list.values.length));\n          list.finish(value);\n        }}\n        onPointerDown={handlePointerDown}\n        onPointerMove={(event: ReactPointerEvent<HTMLLIElement>) => {\n          const current = press.current;\n          if (current && !current.held && Math.hypot(event.clientX - current.x, event.clientY - current.y) > LONG_PRESS_SLOP) endPress();\n        }}\n        onPointerUp={endPress}\n        onPointerCancel={endPress}\n        data-slot=\"sortable-item\"\n        data-dragging={dragging ? \"\" : undefined}\n        data-lifted={lifted ? \"\" : undefined}\n        data-disabled={blocked ? \"\" : undefined}\n        className={cn(\n          \"relative flex min-h-(--control-h-lg) w-full min-w-0 items-center gap-2 rounded-control border bg-card px-2 py-1.5 text-sm text-card-foreground data-[disabled]:opacity-60 data-[dragging]:border-primary data-[dragging]:bg-accent data-[lifted]:border-primary data-[lifted]:bg-accent\",\n          dragBy === \"row\" && !blocked && \"cursor-grab select-none [-webkit-touch-callout:none] data-[dragging]:cursor-grabbing\",\n          className,\n        )}\n        {...props}\n      >\n        {children}\n      </Reorder.Item>\n    </ItemContext>\n  );\n}\n\nexport type SortableHandleProps = Omit<ComponentProps<\"button\">, \"type\">;\n\n/**\n * The grip. With a pointer or a finger it drags the row (it does not scroll the page, so a finger can use\n * it at once). With the keyboard: Space or Enter lifts the row, Up and Down move it, Home and End send it to\n * either end, Space or Enter drops it, Escape puts it back where it was lifted. Tab, or focus leaving any\n * other way, drops it where it is. While lifted the button is `aria-pressed`.\n */\nexport function SortableHandle({ className, children, onKeyDown, onPointerDown, onBlur, \"aria-label\": ariaLabel, ...props }: SortableHandleProps) {\n  const list = useList(\"SortableHandle\");\n  const item = useItem(\"SortableHandle\");\n  const { label, index, total, lifted } = item;\n  const { messages } = list;\n\n  const drop = (): void => {\n    list.setLifted(null);\n    announce(messages.dropped(label, index + 1, total));\n    list.finish(item.value);\n  };\n\n  const handleKeyDown = (event: KeyboardEvent<HTMLButtonElement>): void => {\n    onKeyDown?.(event);\n    if (event.defaultPrevented || item.disabled || event.altKey || event.ctrlKey || event.metaKey) return;\n    const { key } = event;\n    if (key === \" \" || key === \"Enter\") {\n      event.preventDefault();\n      if (event.repeat) return;\n      if (lifted) drop();\n      else {\n        list.setLifted({ value: item.value, from: list.values });\n        list.begin(item.value);\n        announce(messages.lifted(label, index + 1, total));\n      }\n      return;\n    }\n    if (!lifted) return;\n    if (key === \"ArrowUp\" || key === \"ArrowDown\" || key === \"Home\" || key === \"End\") {\n      event.preventDefault();\n      item.moveTo(key === \"ArrowUp\" ? index - 1 : key === \"ArrowDown\" ? index + 1 : key === \"Home\" ? 0 : total - 1);\n    } else if (key === \"Escape\") {\n      // The Escape belongs to the lifted row, not to a dialog or sheet the list may be in.\n      event.preventDefault();\n      event.stopPropagation();\n      const from = list.lifted?.from ?? list.values;\n      // Rows added or removed since the lift keep their places; the rest go back.\n      const known = from.filter((value) => list.values.includes(value));\n      const restored = list.values.map((value) => (from.includes(value) ? (known.shift() ?? value) : value));\n      list.setValues(restored);\n      list.setLifted(null);\n      list.abandon();\n      announce(messages.cancelled(label, restored.indexOf(item.value) + 1, total));\n    } else if (key === \"Tab\") {\n      drop();\n    }\n  };\n\n  return (\n    <button\n      type=\"button\"\n      data-slot=\"sortable-handle\"\n      aria-label={ariaLabel ?? messages.handle(label)}\n      aria-describedby={list.instructionsId}\n      aria-pressed={lifted}\n      disabled={item.disabled}\n      onKeyDown={handleKeyDown}\n      onPointerDown={(event) => {\n        onPointerDown?.(event);\n        if (!event.defaultPrevented && !item.disabled && event.button === 0) item.controls.start(event);\n      }}\n      onBlur={(event) => {\n        onBlur?.(event);\n        if (!lifted) return;\n        // Focus left while the row was lifted (a press elsewhere): it stays where it is, and that is a drop.\n        list.setLifted(null);\n        list.finish(item.value);\n      }}\n      className={cn(\n        \"inline-flex size-8 shrink-0 cursor-grab touch-none items-center justify-center rounded-control text-muted-foreground transition-[background-color,color] duration-instant ease-out select-none hover:bg-accent hover:text-foreground active:cursor-grabbing disabled:pointer-events-none disabled:opacity-40 aria-pressed:bg-primary aria-pressed:text-primary-foreground motion-reduce:transition-none pointer-coarse:size-10 [&_svg]:size-4\",\n        className,\n      )}\n      {...props}\n    >\n      {children ?? <GripVertical aria-hidden=\"true\" strokeWidth={1.5} />}\n    </button>\n  );\n}\n\nexport type SortableMoveButtonsProps = ComponentProps<\"div\">;\n\n/**\n * \"Move up\" and \"Move down\": reordering with single presses, for anyone who does not drag. At either end\n * the button that has nowhere to go says it is unavailable but keeps focus, so that pressing \"up\" until the\n * row reaches the top does not drop the keyboard's place.\n */\nexport function SortableMoveButtons({ className, ...props }: SortableMoveButtonsProps) {\n  const { messages } = useList(\"SortableMoveButtons\");\n  const item = useItem(\"SortableMoveButtons\");\n  const button =\n    \"inline-flex size-8 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-[background-color,color,opacity] duration-instant ease-out hover:bg-accent hover:text-foreground aria-disabled:pointer-events-none aria-disabled:opacity-40 motion-reduce:transition-none pointer-coarse:size-10 [&_svg]:size-4\";\n  const atTop = item.disabled || item.index <= 0;\n  const atBottom = item.disabled || item.index >= item.total - 1;\n  return (\n    <div data-slot=\"sortable-move-buttons\" className={cn(\"ms-auto flex shrink-0 items-center\", className)} {...props}>\n      <button type=\"button\" data-slot=\"sortable-move-up\" aria-label={messages.moveUp(item.label)} aria-disabled={atTop || undefined} onClick={() => (atTop ? undefined : item.moveOnce(item.index - 1))} className={button}>\n        <ChevronUp aria-hidden=\"true\" strokeWidth={1.5} />\n      </button>\n      <button type=\"button\" data-slot=\"sortable-move-down\" aria-label={messages.moveDown(item.label)} aria-disabled={atBottom || undefined} onClick={() => (atBottom ? undefined : item.moveOnce(item.index + 1))} className={button}>\n        <ChevronDown aria-hidden=\"true\" strokeWidth={1.5} />\n      </button>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "The order itself is the data: the stops of a plan, priorities, pictures in a gallery, columns to show. Always give the rows SortableMoveButtons or a SortableHandle (both is best): dragging alone leaves out people who cannot drag (WCAG 2.5.7). It is one vertical list; it does not move rows between lists or sort a grid. For a list sorted by a rule (newest first) use a select for the rule instead; for choosing rather than ordering use chip or checkboxes.",
    "example": "const [stops, setStops] = useState([\"market\", \"lunch\", \"museum\"]);\n<SortableList values={stops} onValuesChange={setStops} aria-label=\"Stops, in order\">\n  {stops.map((id) => (\n    <SortableItem key={id} value={id} label={NAMES[id]}>\n      <SortableHandle />\n      <span className=\"min-w-0 flex-1 truncate\">{NAMES[id]}</span>\n      <SortableMoveButtons />\n    </SortableItem>\n  ))}\n</SortableList>\n\n// Uncontrolled: the list keeps the order and gives it to its children\n<SortableList defaultValues={[\"a\", \"b\", \"c\"]} aria-label=\"Priorities\">\n  {(order) => order.map((id) => <SortableItem key={id} value={id} label={id}>…</SortableItem>)}\n</SortableList>\n\n// Save once, when a row has been let go, not at every step it passes\n<SortableList values={stops} onValuesChange={setStops} onDropped={({ from, to, values }) => (from === to ? undefined : save(values))} aria-label=\"Stops, in order\">…</SortableList>",
    "client": true
  }
}
