{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "reorderable-collection",
  "title": "Reorderable Collection",
  "type": "registry:ui",
  "files": [
    {
      "path": "packages/registry-native/components/reorderable-collection/ReorderableCollection.tsx",
      "content": "import * as React from 'react'\nimport { AppState, Pressable, View, type ViewProps } from 'react-native'\nimport type { FlatList } from 'react-native-gesture-handler'\nimport DraggableFlatList, {\n  type DragEndParams,\n  type DraggableFlatListProps,\n  type RenderItemParams,\n} from 'react-native-draggable-flatlist'\nimport { Button, type ButtonProps } from '@/components/ui/button'\nimport { renderTextChildren } from '@/lib/label-children'\nimport { cn } from '@/lib/utils'\nimport { moveOrder, normalizeOrder, sameOrder } from './reorderable-collection.utils'\n\ninterface Row {\n  id: string\n  element: React.ReactElement<ReorderableItemProps>\n  disabled: boolean\n}\nexport interface ReorderableChange {\n  id: string\n  from: number\n  to: number\n  source: 'drag' | 'control'\n}\nexport interface ReorderableCollectionHandle {\n  cancel: () => void\n  scrollToOffset: (options: { offset: number; animated?: boolean }) => void\n  scrollToIndex: (options: { index: number; animated?: boolean; viewPosition?: number; viewOffset?: number }) => void\n}\nexport interface ReorderableCollectionProps extends Omit<\n  DraggableFlatListProps<Row>,\n  | 'data'\n  | 'renderItem'\n  | 'keyExtractor'\n  | 'children'\n  | 'onDragBegin'\n  | 'onDragEnd'\n  | 'onRelease'\n  | 'numColumns'\n  | 'extraData'\n  | 'renderPlaceholder'\n  | 'enableLayoutAnimationExperimental'\n  | 'itemLayoutAnimation'\n  | 'itemEnteringAnimation'\n  | 'itemExitingAnimation'\n  | 'style'\n> {\n  children?: React.ReactNode\n  order?: readonly string[]\n  defaultOrder?: readonly string[]\n  onOrderChange?: (order: string[], change: ReorderableChange) => void\n  disabled?: boolean\n  className?: string\n  style?: ViewProps['style']\n  /** Initial position; use the collection ref to scroll after mount. */\n  contentOffset?: DraggableFlatListProps<Row>['contentOffset']\n}\ninterface ItemState {\n  disabled: boolean\n  busy: boolean\n  canDrag: boolean\n  canMove: (direction: 'previous' | 'next') => boolean\n  drag: () => void\n  move: (direction: 'previous' | 'next') => void\n}\nconst ItemContext = React.createContext<ItemState | null>(null)\nfunction useItem() {\n  const value = React.useContext(ItemContext)\n  if (!value) throw new Error('Reorderable parts must be inside a ReorderableItem in ReorderableCollection')\n  return value\n}\n\nfunction collectItems(children: React.ReactNode, result: Row[] = []): Row[] {\n  React.Children.forEach(children, (child) => {\n    if (child == null || typeof child === 'boolean') return\n    if (React.isValidElement<{ children?: React.ReactNode }>(child) && child.type === React.Fragment) {\n      collectItems(child.props.children, result)\n      return\n    }\n    if (!React.isValidElement<ReorderableItemProps>(child) || child.type !== ReorderableItem) {\n      throw new Error('ReorderableCollection children must be ReorderableItem elements or fragments')\n    }\n    const { id, disabled = false } = child.props\n    if (typeof id !== 'string' || !id.trim() || result.some((item) => item.id === id)) {\n      throw new Error('Every ReorderableItem requires a unique, nonempty string id')\n    }\n    result.push({ id, element: child, disabled })\n  })\n  return result\n}\n\n/**\n * Caller-composed one-dimensional list with native drag/autoscroll and explicit move controls.\n * Mount inside the app's shared GestureHandlerRootView. Give the viewport a bounded height/flex parent.\n * Vertical and horizontal lists are supported; multi-column grid dragging is intentionally not exposed.\n * Backend contract: https://github.com/computerjazz/react-native-draggable-flatlist/tree/v4.0.3#api\n */\nexport const ReorderableCollection = React.forwardRef<ReorderableCollectionHandle, ReorderableCollectionProps>(\n  (\n    {\n      children,\n      order,\n      defaultOrder,\n      onOrderChange,\n      disabled = false,\n      className,\n      style,\n      horizontal = false,\n      containerStyle,\n      contentOffset,\n      onScrollOffsetChange,\n      ...props\n    },\n    ref,\n  ) => {\n    const items = collectItems(children)\n    const ids = items.map((item) => item.id)\n    const idsKey = JSON.stringify(ids)\n    const [internalOrder, setInternalOrder] = React.useState<string[]>(() => normalizeOrder(defaultOrder, ids))\n    const controlled = order !== undefined\n    const currentOrder = normalizeOrder(order ?? internalOrder, ids)\n    const itemMap = new Map(items.map((item) => [item.id, item]))\n    const rows = currentOrder.map((id) => itemMap.get(id)!)\n    const [reset, setReset] = React.useState(0)\n    const signature = JSON.stringify([\n      currentOrder,\n      items.map((item) => [item.id, item.disabled]),\n      disabled,\n      horizontal,\n      controlled,\n    ])\n    const nativeKey = `${signature}:${reset}`\n    const native = React.useRef<FlatList<Row>>(null)\n    const offset = React.useRef(horizontal ? (contentOffset?.x ?? 0) : (contentOffset?.y ?? 0))\n    const mounted = React.useRef(true)\n    const session = React.useRef<{ key: string; id: string } | null>(null)\n    const [activeKey, setActiveKey] = React.useState<string | null>(null)\n    const latest = React.useRef({ nativeKey, currentOrder, itemMap, disabled, controlled, onOrderChange })\n    latest.current = { nativeKey, currentOrder, itemMap, disabled, controlled, onOrderChange }\n    const busy = activeKey === nativeKey\n\n    React.useEffect(() => {\n      mounted.current = true\n      return () => {\n        mounted.current = false\n        session.current = null\n      }\n    }, [])\n    React.useEffect(() => {\n      if (controlled) return\n      setInternalOrder((previous) => {\n        const next = normalizeOrder(previous, ids)\n        return sameOrder(previous, next) ? previous : next\n      })\n      // Child identity, rather than row element identity, owns reconciliation.\n      // eslint-disable-next-line react-hooks/exhaustive-deps\n    }, [idsKey, controlled])\n\n    const cancel = React.useCallback(() => {\n      if (!mounted.current || !session.current) return\n      session.current = null\n      setActiveKey(null)\n      setReset((value) => value + 1)\n    }, [])\n    React.useEffect(() => {\n      const subscription = AppState.addEventListener('change', (state) => {\n        if (state !== 'active') cancel()\n      })\n      return () => subscription.remove()\n    }, [cancel])\n\n    React.useImperativeHandle(\n      ref,\n      () => ({\n        cancel,\n        scrollToOffset: (options) => native.current?.scrollToOffset(options),\n        scrollToIndex: (options) => native.current?.scrollToIndex(options),\n      }),\n      [cancel],\n    )\n\n    const commit = (id: string, to: number, source: ReorderableChange['source']) => {\n      const current = latest.current\n      if (!mounted.current || current.disabled || current.itemMap.get(id)?.disabled) return\n      const next = moveOrder(current.currentOrder, id, to)\n      if (!next) return\n      const from = current.currentOrder.indexOf(id)\n      if (!current.controlled) setInternalOrder(next)\n      current.onOrderChange?.([...next], { id, from, to, source })\n    }\n    const finish = ({ from, to }: DragEndParams<Row>) => {\n      const active = session.current\n      const current = latest.current\n      if (!mounted.current || !active || active.key !== nativeKey || current.nativeKey !== nativeKey) return\n      session.current = null\n      setActiveKey(null)\n      // v4.0.3 retains a cell's last translation until its next onLayout. A refused controlled\n      // update leaves that layout unchanged, so reinitialize the backend after each settlement.\n      setReset((value) => value + 1)\n      if (current.currentOrder[from] !== active.id) return\n      commit(active.id, to, 'drag')\n    }\n    const renderItem = ({ item, drag }: RenderItemParams<Row>) => {\n      const itemDisabled = disabled || item.disabled\n      const index = currentOrder.indexOf(item.id)\n      const canMove = (direction: 'previous' | 'next') =>\n        !itemDisabled && !busy && (direction === 'previous' ? index > 0 : index < currentOrder.length - 1)\n      return (\n        <ItemContext.Provider\n          value={{\n            disabled: itemDisabled,\n            busy,\n            canDrag: !itemDisabled && !busy && currentOrder.length > 1,\n            canMove,\n            drag: () => {\n              const current = latest.current\n              if (\n                !mounted.current ||\n                current.nativeKey !== nativeKey ||\n                current.disabled ||\n                current.itemMap.get(item.id)?.disabled ||\n                session.current?.key === nativeKey ||\n                current.currentOrder.length < 2\n              )\n                return\n              drag()\n            },\n            move: (direction) => {\n              const current = latest.current\n              if (current.nativeKey !== nativeKey || session.current?.key === nativeKey) return\n              const currentIndex = current.currentOrder.indexOf(item.id)\n              commit(item.id, currentIndex + (direction === 'previous' ? -1 : 1), 'control')\n            },\n          }}\n        >\n          {item.element}\n        </ItemContext.Provider>\n      )\n    }\n    return (\n      <View className={cn('w-full', className)} style={[{ height: 320 }, style]}>\n        <DraggableFlatList\n          {...props}\n          key={nativeKey}\n          ref={native}\n          style={{ flex: 1 }}\n          containerStyle={[{ flex: 1 }, containerStyle]}\n          horizontal={horizontal}\n          contentOffset={horizontal ? { x: offset.current, y: 0 } : { x: 0, y: offset.current }}\n          data={rows}\n          extraData={busy}\n          numColumns={1}\n          enableLayoutAnimationExperimental={false}\n          keyExtractor={(item) => item.id}\n          renderItem={renderItem}\n          onScrollOffsetChange={(value) => {\n            if (!mounted.current || latest.current.nativeKey !== nativeKey) return\n            if (Number.isFinite(value)) offset.current = Math.max(0, value)\n            onScrollOffsetChange?.(value)\n          }}\n          onDragBegin={(index) => {\n            const current = latest.current\n            const id = current.currentOrder[index]\n            if (\n              !mounted.current ||\n              current.nativeKey !== nativeKey ||\n              current.disabled ||\n              !id ||\n              current.itemMap.get(id)?.disabled ||\n              current.currentOrder.length < 2\n            )\n              return\n            session.current = { key: nativeKey, id }\n            setActiveKey(nativeKey)\n          }}\n          onDragEnd={finish}\n        />\n      </View>\n    )\n  },\n)\nReorderableCollection.displayName = 'ReorderableCollection'\n\nexport interface ReorderableItemProps extends ViewProps {\n  id: string\n  /** Prevents initiating a move for this item; other items may still pass it. */\n  disabled?: boolean\n  className?: string\n}\nexport const ReorderableItem = React.forwardRef<React.ComponentRef<typeof View>, ReorderableItemProps>(\n  ({ id: _id, disabled: _disabled, className, children, ...props }, ref) => {\n    const item = useItem()\n    return (\n      <View {...props} ref={ref} className={cn(item.disabled && 'opacity-50', className)}>\n        {renderTextChildren(children)}\n      </View>\n    )\n  },\n)\nReorderableItem.displayName = 'ReorderableItem'\n\nexport const ReorderableDragHandle = React.forwardRef<React.ComponentRef<typeof Pressable>, ButtonProps>(\n  ({ disabled, onLongPress, children, ...props }, ref) => {\n    const item = useItem()\n    const blocked = !!disabled || !item.canDrag\n    return (\n      <Button\n        variant=\"outline\"\n        {...props}\n        ref={ref}\n        disabled={blocked}\n        onLongPress={(event) => {\n          if (blocked) return\n          onLongPress?.(event)\n          if (!event.isDefaultPrevented()) item.drag()\n        }}\n      >\n        {children ?? 'Move'}\n      </Button>\n    )\n  },\n)\nReorderableDragHandle.displayName = 'ReorderableDragHandle'\n\nexport interface ReorderableMoveProps extends ButtonProps {\n  direction: 'previous' | 'next'\n}\nexport const ReorderableMove = React.forwardRef<React.ComponentRef<typeof Pressable>, ReorderableMoveProps>(\n  ({ direction, disabled, onPress, children, ...props }, ref) => {\n    const item = useItem()\n    const blocked = !!disabled || !item.canMove(direction)\n    return (\n      <Button\n        variant=\"outline\"\n        {...props}\n        ref={ref}\n        disabled={blocked}\n        onPress={(event) => {\n          if (blocked) return\n          onPress?.(event)\n          if (!event.isDefaultPrevented()) item.move(direction)\n        }}\n      >\n        {children ?? (direction === 'previous' ? 'Move earlier' : 'Move later')}\n      </Button>\n    )\n  },\n)\nReorderableMove.displayName = 'ReorderableMove'\n",
      "type": "registry:ui",
      "target": "~/components/ui/reorderable-collection/ReorderableCollection.tsx"
    },
    {
      "path": "packages/registry-native/components/reorderable-collection/reorderable-collection.utils.ts",
      "content": "/** Reconcile a requested ID order with the currently composed children. */\nexport function normalizeOrder(requested: readonly string[] | undefined, ids: readonly string[]): string[] {\n  const available = new Set(ids)\n  const seen = new Set<string>()\n  const result: string[] = []\n  for (const id of [...(requested ?? []), ...ids]) {\n    if (!available.has(id) || seen.has(id)) continue\n    seen.add(id)\n    result.push(id)\n  }\n  return result\n}\n\nexport function sameOrder(a: readonly string[], b: readonly string[]): boolean {\n  return a.length === b.length && a.every((id, index) => id === b[index])\n}\n\nexport function moveOrder(order: readonly string[], id: string, to: number): string[] | null {\n  const from = order.indexOf(id)\n  if (from < 0 || !Number.isInteger(to) || to < 0 || to >= order.length || from === to) return null\n  const next = [...order]\n  next.splice(from, 1)\n  next.splice(to, 0, id)\n  return next\n}\n",
      "type": "registry:ui",
      "target": "~/components/ui/reorderable-collection/reorderable-collection.utils.ts"
    },
    {
      "path": "packages/registry-native/components/reorderable-collection/index.ts",
      "content": "export * from './ReorderableCollection'\n",
      "type": "registry:ui",
      "target": "~/components/ui/reorderable-collection/index.ts"
    }
  ],
  "dependencies": [
    "react-native-draggable-flatlist@4.0.3",
    "react-native-gesture-handler",
    "react-native-reanimated"
  ],
  "devDependencies": [],
  "registryDependencies": [
    "https://native.uipkge.dev/r/native/button.json",
    "https://native.uipkge.dev/r/native/label-children.json",
    "https://native.uipkge.dev/r/native/utils.json"
  ],
  "description": "Caller-composed one-dimensional drag/autoscroll list with stable IDs, controlled order, and visible move controls.",
  "categories": [
    "interaction"
  ]
}