{
  "name": "sortable",
  "type": "registry:ui",
  "dependencies": [
    "cn",
    "@dnd-kit/core",
    "@dnd-kit/modifiers",
    "@dnd-kit/sortable",
    "@dnd-kit/utilities",
    "radix-ui",
    "@base-ui/utils@0.5.0"
  ],
  "files": [
    {
      "path": "ui/sortable.tsx",
      "type": "registry:ui",
      "content": "\"use client\";\n\nimport { useIsHydrated } from \"@base-ui/utils/hydration\";\nimport { useMergedRefs } from \"@base-ui/utils/useMergedRefs\";\nimport {\n  type Active,\n  type Announcements,\n  closestCenter,\n  closestCorners,\n  defaultDropAnimationSideEffects,\n  DndContext,\n  type DndContextProps,\n  type DragEndEvent,\n  type DraggableAttributes,\n  type DraggableSyntheticListeners,\n  DragOverlay,\n  type DragStartEvent,\n  type DropAnimation,\n  KeyboardSensor,\n  MouseSensor,\n  type Over,\n  type ScreenReaderInstructions,\n  TouchSensor,\n  type UniqueIdentifier,\n  useSensor,\n  useSensors,\n} from \"@dnd-kit/core\";\nimport {\n  restrictToHorizontalAxis,\n  restrictToParentElement,\n  restrictToVerticalAxis,\n} from \"@dnd-kit/modifiers\";\nimport {\n  arrayMove,\n  horizontalListSortingStrategy,\n  SortableContext,\n  type SortableContextProps,\n  sortableKeyboardCoordinates,\n  useSortable,\n  verticalListSortingStrategy,\n} from \"@dnd-kit/sortable\";\nimport { CSS, isKeyboardEvent } from \"@dnd-kit/utilities\";\nimport { cn } from \"cn\";\nimport { Slot as SlotPrimitive } from \"radix-ui\";\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\n\nconst orientationConfig = {\n  vertical: {\n    modifiers: [restrictToVerticalAxis, restrictToParentElement],\n    strategy: verticalListSortingStrategy,\n    collisionDetection: closestCenter,\n  },\n  horizontal: {\n    modifiers: [restrictToHorizontalAxis, restrictToParentElement],\n    strategy: horizontalListSortingStrategy,\n    collisionDetection: closestCenter,\n  },\n  mixed: {\n    modifiers: [restrictToParentElement],\n    strategy: undefined,\n    collisionDetection: closestCorners,\n  },\n};\n\nconst orientationKeys = {\n  vertical: \"up and down arrow keys\",\n  horizontal: \"left and right arrow keys\",\n  mixed: \"arrow keys\",\n};\n\nconst ROOT_NAME = \"Sortable\";\nconst CONTENT_NAME = \"SortableContent\";\nconst ITEM_NAME = \"SortableItem\";\nconst ITEM_HANDLE_NAME = \"SortableItemHandle\";\nconst OVERLAY_NAME = \"SortableOverlay\";\n\ninterface SortableRootContextValue<T> {\n  id: string;\n  items: UniqueIdentifier[];\n  modifiers: DndContextProps[\"modifiers\"];\n  strategy: SortableContextProps[\"strategy\"];\n  activeId: UniqueIdentifier | null;\n  setActiveId: (id: UniqueIdentifier | null) => void;\n  getItemValue: (item: T) => UniqueIdentifier;\n  flatCursor: boolean;\n}\n\nconst SortableRootContext =\n  React.createContext<SortableRootContextValue<unknown> | null>(null);\n\nfunction useSortableContext(consumerName: string) {\n  const context = React.useContext(SortableRootContext);\n  if (!context) {\n    throw new Error(`\\`${consumerName}\\` must be used within \\`${ROOT_NAME}\\``);\n  }\n  return context;\n}\n\ninterface GetItemValue<T> {\n  /**\n   * Callback that returns a unique identifier for each sortable item. Required for array of objects.\n   * @example getItemValue={(item) => item.id}\n   */\n  getItemValue: (item: T) => UniqueIdentifier;\n}\n\ntype SortableProps<T> = DndContextProps &\n  (T extends object ? GetItemValue<T> : Partial<GetItemValue<T>>) & {\n    value: T[];\n    onValueChange?: (items: T[]) => void;\n    onMove?: (\n      event: DragEndEvent & { activeIndex: number; overIndex: number },\n    ) => void;\n    strategy?: SortableContextProps[\"strategy\"];\n    orientation?: \"horizontal\" | \"vertical\" | \"mixed\";\n    flatCursor?: boolean;\n    getItemLabel?: (item: T) => string;\n  };\n\nfunction Sortable<T>(props: SortableProps<T>) {\n  const {\n    value,\n    onValueChange,\n    collisionDetection,\n    modifiers,\n    strategy,\n    onMove,\n    orientation = \"vertical\",\n    flatCursor = false,\n    getItemValue: getItemValueProp,\n    getItemLabel: getItemLabelProp,\n    accessibility,\n    onDragStart: onDragStartProp,\n    onDragEnd: onDragEndProp,\n    onDragCancel: onDragCancelProp,\n    ...sortableProps\n  } = props;\n\n  const id = React.useId();\n  const [activeId, setActiveId] = React.useState<UniqueIdentifier | null>(null);\n  const isKeyboardDragRef = React.useRef(false);\n  const overIndexRef = React.useRef<number | undefined>(undefined);\n\n  const sensors = useSensors(\n    useSensor(MouseSensor, {\n      activationConstraint: { distance: 4 },\n    }),\n    useSensor(TouchSensor, {\n      activationConstraint: { delay: 250, tolerance: 5 },\n    }),\n    useSensor(KeyboardSensor, {\n      coordinateGetter: sortableKeyboardCoordinates,\n    }),\n  );\n  const config = React.useMemo(\n    () => orientationConfig[orientation],\n    [orientation],\n  );\n\n  const getItemValue = React.useCallback(\n    (item: T): UniqueIdentifier => {\n      if (typeof item === \"object\" && !getItemValueProp) {\n        throw new Error(\n          \"`getItemValue` is required when using array of objects\",\n        );\n      }\n      return getItemValueProp\n        ? getItemValueProp(item)\n        : (item as UniqueIdentifier);\n    },\n    [getItemValueProp],\n  );\n\n  const items = React.useMemo(() => {\n    return value.map((item) => getItemValue(item));\n  }, [value, getItemValue]);\n\n  const onDragStart = React.useCallback(\n    (event: DragStartEvent) => {\n      onDragStartProp?.(event);\n\n      isKeyboardDragRef.current = isKeyboardEvent(event.activatorEvent);\n      setActiveId(event.active.id);\n    },\n    [onDragStartProp],\n  );\n\n  const onDragEnd = React.useCallback(\n    (event: DragEndEvent) => {\n      onDragEndProp?.(event);\n      setActiveId(null);\n\n      const { active, over } = event;\n      if (!over || active.id === over.id) return;\n\n      const activeIndex = value.findIndex(\n        (item) => getItemValue(item) === active.id,\n      );\n      const overIndex = value.findIndex(\n        (item) => getItemValue(item) === over.id,\n      );\n      if (activeIndex === -1 || overIndex === -1) return;\n\n      if (onMove) {\n        onMove({ ...event, activeIndex, overIndex });\n      } else {\n        onValueChange?.(arrayMove(value, activeIndex, overIndex));\n      }\n    },\n    [value, onValueChange, onMove, getItemValue, onDragEndProp],\n  );\n\n  const onDragCancel = React.useCallback(\n    (event: DragEndEvent) => {\n      onDragCancelProp?.(event);\n      setActiveId(null);\n    },\n    [onDragCancelProp],\n  );\n\n  const announcements: Announcements = React.useMemo(() => {\n    const total = value.length;\n\n    function getLabel(id: UniqueIdentifier) {\n      const item = value.find((item) => getItemValue(item) === id);\n      if (item === undefined || !getItemLabelProp) return String(id);\n      return getItemLabelProp(item);\n    }\n\n    function getIndex(entry: Active | Over | null): number | undefined {\n      return entry?.data.current?.sortable?.index;\n    }\n\n    return {\n      onDragStart({ active }) {\n        const index = getIndex(active) ?? 0;\n        overIndexRef.current = index;\n        const message = `Grabbed ${getLabel(active.id)}, position ${index + 1} of ${total}.`;\n        if (!isKeyboardDragRef.current) return message;\n        return `${message} Use the ${orientationKeys[orientation]} to move it, Space or Enter to drop it, or Escape to cancel.`;\n      },\n      onDragOver({ active, over }) {\n        const overIndex = getIndex(over);\n        if (overIndex === overIndexRef.current) return undefined;\n        overIndexRef.current = overIndex;\n        if (overIndex === undefined) {\n          return `${getLabel(active.id)} is outside the list.`;\n        }\n        return `${getLabel(active.id)}, position ${overIndex + 1} of ${total}.`;\n      },\n      onDragEnd({ active, over }) {\n        const overIndex = getIndex(over);\n        if (overIndex === undefined) {\n          return `Dropped ${getLabel(active.id)}. It stays at position ${(getIndex(active) ?? 0) + 1} of ${total}.`;\n        }\n        return `Dropped ${getLabel(active.id)} at position ${overIndex + 1} of ${total}.`;\n      },\n      onDragCancel({ active }) {\n        return `Cancelled. ${getLabel(active.id)} is back at position ${(getIndex(active) ?? 0) + 1} of ${total}.`;\n      },\n    };\n  }, [value, getItemValue, getItemLabelProp, orientation]);\n\n  const screenReaderInstructions: ScreenReaderInstructions = React.useMemo(\n    () => ({\n      draggable: `To pick up an item, press Space or Enter. Use the ${orientationKeys[orientation]} to move it, Space or Enter to drop it, or Escape to cancel.`,\n    }),\n    [orientation],\n  );\n\n  const contextValue = React.useMemo(\n    () => ({\n      id,\n      items,\n      modifiers: modifiers ?? config.modifiers,\n      strategy: strategy ?? config.strategy,\n      activeId,\n      setActiveId,\n      getItemValue,\n      flatCursor,\n    }),\n    [\n      id,\n      items,\n      modifiers,\n      strategy,\n      config.modifiers,\n      config.strategy,\n      activeId,\n      getItemValue,\n      flatCursor,\n    ],\n  );\n\n  return (\n    <SortableRootContext.Provider\n      value={contextValue as SortableRootContextValue<unknown>}\n    >\n      <DndContext\n        collisionDetection={collisionDetection ?? config.collisionDetection}\n        modifiers={modifiers ?? config.modifiers}\n        sensors={sensors}\n        {...sortableProps}\n        id={id}\n        onDragStart={onDragStart}\n        onDragEnd={onDragEnd}\n        onDragCancel={onDragCancel}\n        accessibility={{\n          announcements,\n          screenReaderInstructions,\n          ...accessibility,\n        }}\n      />\n    </SortableRootContext.Provider>\n  );\n}\n\nconst SortableContentContext = React.createContext<boolean>(false);\n\ninterface SortableContentProps extends React.ComponentProps<\"div\"> {\n  strategy?: SortableContextProps[\"strategy\"];\n  children: React.ReactNode;\n  asChild?: boolean;\n  withoutSlot?: boolean;\n}\n\nfunction SortableContent(props: SortableContentProps) {\n  const {\n    strategy: strategyProp,\n    asChild,\n    withoutSlot,\n    children,\n    ref,\n    ...contentProps\n  } = props;\n\n  const context = useSortableContext(CONTENT_NAME);\n\n  const ContentPrimitive = asChild ? SlotPrimitive.Slot : \"div\";\n\n  return (\n    <SortableContentContext.Provider value={true}>\n      <SortableContext\n        items={context.items}\n        strategy={strategyProp ?? context.strategy}\n      >\n        {withoutSlot ? (\n          children\n        ) : (\n          <ContentPrimitive\n            data-slot=\"sortable-content\"\n            {...contentProps}\n            ref={ref}\n          >\n            {children}\n          </ContentPrimitive>\n        )}\n      </SortableContext>\n    </SortableContentContext.Provider>\n  );\n}\n\ninterface SortableItemContextValue {\n  id: string;\n  attributes: DraggableAttributes;\n  listeners: DraggableSyntheticListeners | undefined;\n  setActivatorNodeRef: (node: HTMLElement | null) => void;\n  isDragging?: boolean;\n  disabled?: boolean;\n}\n\nconst SortableItemContext =\n  React.createContext<SortableItemContextValue | null>(null);\n\nfunction useSortableItemContext(consumerName: string) {\n  const context = React.useContext(SortableItemContext);\n  if (!context) {\n    throw new Error(`\\`${consumerName}\\` must be used within \\`${ITEM_NAME}\\``);\n  }\n  return context;\n}\n\ninterface SortableItemProps extends React.ComponentProps<\"div\"> {\n  value: UniqueIdentifier;\n  asHandle?: boolean;\n  asChild?: boolean;\n  disabled?: boolean;\n}\n\nfunction SortableItem(props: SortableItemProps) {\n  const {\n    value,\n    style,\n    asHandle,\n    asChild,\n    disabled,\n    className,\n    ref,\n    id: idProp,\n    ...itemProps\n  } = props;\n\n  const inSortableContent = React.useContext(SortableContentContext);\n  const inSortableOverlay = React.useContext(SortableOverlayContext);\n\n  if (!inSortableContent && !inSortableOverlay) {\n    throw new Error(\n      `\\`${ITEM_NAME}\\` must be used within \\`${CONTENT_NAME}\\` or \\`${OVERLAY_NAME}\\``,\n    );\n  }\n\n  if (value === \"\") {\n    throw new Error(`\\`${ITEM_NAME}\\` value cannot be an empty string`);\n  }\n\n  const context = useSortableContext(ITEM_NAME);\n  const instanceId = React.useId();\n  const id = idProp ?? instanceId;\n  const {\n    attributes,\n    listeners,\n    setNodeRef,\n    setActivatorNodeRef,\n    transform,\n    transition,\n    isDragging,\n  } = useSortable({ id: value, disabled });\n\n  const onNodeRefChange = React.useCallback(\n    (node: HTMLElement | null) => {\n      setNodeRef(node);\n      if (asHandle && !disabled) setActivatorNodeRef(node);\n    },\n    [disabled, asHandle, setNodeRef, setActivatorNodeRef],\n  );\n\n  const composedRef = useMergedRefs(ref, onNodeRefChange);\n\n  const composedStyle = React.useMemo<React.CSSProperties>(() => {\n    return {\n      transform: CSS.Translate.toString(transform),\n      transition,\n      ...style,\n    };\n  }, [transform, transition, style]);\n\n  const itemContext = React.useMemo<SortableItemContextValue>(\n    () => ({\n      id,\n      attributes,\n      listeners,\n      setActivatorNodeRef,\n      isDragging,\n      disabled,\n    }),\n    [id, attributes, listeners, setActivatorNodeRef, isDragging, disabled],\n  );\n\n  const handleProps =\n    asHandle && !disabled ? { ...attributes, ...listeners } : undefined;\n\n  const ItemPrimitive = asChild ? SlotPrimitive.Slot : \"div\";\n\n  return (\n    <SortableItemContext.Provider value={itemContext}>\n      <ItemPrimitive\n        id={id}\n        data-disabled={disabled ? \"\" : undefined}\n        data-dragging={isDragging ? \"\" : undefined}\n        data-slot=\"sortable-item\"\n        {...itemProps}\n        {...handleProps}\n        ref={composedRef}\n        style={composedStyle}\n        className={cn(\n          \"focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:outline-hidden\",\n          {\n            \"touch-none select-none\": asHandle,\n            \"cursor-default\": context.flatCursor,\n            \"data-dragging:cursor-grabbing\": !context.flatCursor,\n            \"cursor-grab\": !isDragging && asHandle && !context.flatCursor,\n            \"opacity-50\": isDragging,\n            \"pointer-events-none opacity-50\": disabled,\n          },\n          className,\n        )}\n      />\n    </SortableItemContext.Provider>\n  );\n}\n\ninterface SortableItemHandleProps extends React.ComponentProps<\"button\"> {\n  asChild?: boolean;\n}\n\nfunction SortableItemHandle(props: SortableItemHandleProps) {\n  const { asChild, disabled, className, ref, ...itemHandleProps } = props;\n\n  const context = useSortableContext(ITEM_HANDLE_NAME);\n  const itemContext = useSortableItemContext(ITEM_HANDLE_NAME);\n\n  const isDisabled = disabled ?? itemContext.disabled;\n\n  const { setActivatorNodeRef } = itemContext;\n\n  const onActivatorNodeRef = React.useCallback(\n    (node: HTMLElement | null) => {\n      if (isDisabled) return;\n      setActivatorNodeRef(node);\n    },\n    [isDisabled, setActivatorNodeRef],\n  );\n\n  const composedRef = useMergedRefs(ref, onActivatorNodeRef);\n\n  const handleProps = isDisabled\n    ? undefined\n    : { ...itemContext.attributes, ...itemContext.listeners };\n\n  const HandlePrimitive = asChild ? SlotPrimitive.Slot : \"button\";\n\n  return (\n    <HandlePrimitive\n      type=\"button\"\n      aria-controls={itemContext.id}\n      data-disabled={isDisabled ? \"\" : undefined}\n      data-dragging={itemContext.isDragging ? \"\" : undefined}\n      data-slot=\"sortable-item-handle\"\n      {...itemHandleProps}\n      {...handleProps}\n      ref={composedRef}\n      className={cn(\n        \"select-none disabled:pointer-events-none disabled:opacity-50\",\n        context.flatCursor\n          ? \"cursor-default\"\n          : \"cursor-grab data-dragging:cursor-grabbing\",\n        className,\n      )}\n      disabled={isDisabled}\n    />\n  );\n}\n\nconst SortableOverlayContext = React.createContext(false);\n\nconst dropAnimation: DropAnimation = {\n  sideEffects: defaultDropAnimationSideEffects({\n    styles: {\n      active: {\n        opacity: \"0.4\",\n      },\n    },\n  }),\n};\n\ninterface SortableOverlayProps extends Omit<\n  React.ComponentProps<typeof DragOverlay>,\n  \"children\"\n> {\n  container?: Element | DocumentFragment | null;\n  children?:\n    | ((params: { value: UniqueIdentifier }) => React.ReactNode)\n    | React.ReactNode;\n}\n\nfunction SortableOverlay(props: SortableOverlayProps) {\n  const { container: containerProp, children, ...overlayProps } = props;\n\n  const context = useSortableContext(OVERLAY_NAME);\n\n  const mounted = useIsHydrated();\n\n  const container =\n    containerProp ?? (mounted ? globalThis.document?.body : null);\n\n  if (!container) return null;\n\n  return ReactDOM.createPortal(\n    <DragOverlay\n      dropAnimation={dropAnimation}\n      modifiers={context.modifiers}\n      className={cn(!context.flatCursor && \"cursor-grabbing\")}\n      {...overlayProps}\n    >\n      <SortableOverlayContext.Provider value={true}>\n        {context.activeId\n          ? typeof children === \"function\"\n            ? children({ value: context.activeId })\n            : children\n          : null}\n      </SortableOverlayContext.Provider>\n    </DragOverlay>,\n    container,\n  );\n}\n\nexport {\n  Sortable,\n  SortableContent,\n  SortableItem,\n  SortableItemHandle,\n  SortableOverlay,\n  type SortableProps,\n};\n",
      "target": ""
    }
  ]
}