UIPackage React Native
Search
Menu

Reorderable Collection

Caller-composed one-dimensional drag/autoscroll list with stable IDs, controlled order, and visible move controls.

Install

First install? Set up the registry in your app.

npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add reorderable-collection

Source files

Expand a file to read the source the installer copies into your app.

components/ui/reorderable-collection/ReorderableCollection.tsx
import * as React from 'react'
import { AppState, Pressable, View, type ViewProps } from 'react-native'
import type { FlatList } from 'react-native-gesture-handler'
import DraggableFlatList, {
  type DragEndParams,
  type DraggableFlatListProps,
  type RenderItemParams,
} from 'react-native-draggable-flatlist'
import { Button, type ButtonProps } from '@/components/ui/button'
import { renderTextChildren } from '@/lib/label-children'
import { cn } from '@/lib/utils'
import { moveOrder, normalizeOrder, sameOrder } from './reorderable-collection.utils'

interface Row {
  id: string
  element: React.ReactElement<ReorderableItemProps>
  disabled: boolean
}
export interface ReorderableChange {
  id: string
  from: number
  to: number
  source: 'drag' | 'control'
}
export interface ReorderableCollectionHandle {
  cancel: () => void
  scrollToOffset: (options: { offset: number; animated?: boolean }) => void
  scrollToIndex: (options: { index: number; animated?: boolean; viewPosition?: number; viewOffset?: number }) => void
}
export interface ReorderableCollectionProps extends Omit<
  DraggableFlatListProps<Row>,
  | 'data'
  | 'renderItem'
  | 'keyExtractor'
  | 'children'
  | 'onDragBegin'
  | 'onDragEnd'
  | 'onRelease'
  | 'numColumns'
  | 'extraData'
  | 'renderPlaceholder'
  | 'enableLayoutAnimationExperimental'
  | 'itemLayoutAnimation'
  | 'itemEnteringAnimation'
  | 'itemExitingAnimation'
  | 'style'
> {
  children?: React.ReactNode
  order?: readonly string[]
  defaultOrder?: readonly string[]
  onOrderChange?: (order: string[], change: ReorderableChange) => void
  disabled?: boolean
  className?: string
  style?: ViewProps['style']
  /** Initial position; use the collection ref to scroll after mount. */
  contentOffset?: DraggableFlatListProps<Row>['contentOffset']
}
interface ItemState {
  disabled: boolean
  busy: boolean
  canDrag: boolean
  canMove: (direction: 'previous' | 'next') => boolean
  drag: () => void
  move: (direction: 'previous' | 'next') => void
}
const ItemContext = React.createContext<ItemState | null>(null)
function useItem() {
  const value = React.useContext(ItemContext)
  if (!value) throw new Error('Reorderable parts must be inside a ReorderableItem in ReorderableCollection')
  return value
}

function collectItems(children: React.ReactNode, result: Row[] = []): Row[] {
  React.Children.forEach(children, (child) => {
    if (child == null || typeof child === 'boolean') return
    if (React.isValidElement<{ children?: React.ReactNode }>(child) && child.type === React.Fragment) {
      collectItems(child.props.children, result)
      return
    }
    if (!React.isValidElement<ReorderableItemProps>(child) || child.type !== ReorderableItem) {
      throw new Error('ReorderableCollection children must be ReorderableItem elements or fragments')
    }
    const { id, disabled = false } = child.props
    if (typeof id !== 'string' || !id.trim() || result.some((item) => item.id === id)) {
      throw new Error('Every ReorderableItem requires a unique, nonempty string id')
    }
    result.push({ id, element: child, disabled })
  })
  return result
}

/**
 * Caller-composed one-dimensional list with native drag/autoscroll and explicit move controls.
 * Mount inside the app's shared GestureHandlerRootView. Give the viewport a bounded height/flex parent.
 * Vertical and horizontal lists are supported; multi-column grid dragging is intentionally not exposed.
 * Backend contract: https://github.com/computerjazz/react-native-draggable-flatlist/tree/v4.0.3#api
 */
export const ReorderableCollection = React.forwardRef<ReorderableCollectionHandle, ReorderableCollectionProps>(
  (
    {
      children,
      order,
      defaultOrder,
      onOrderChange,
      disabled = false,
      className,
      style,
      horizontal = false,
      containerStyle,
      contentOffset,
      onScrollOffsetChange,
      ...props
    },
    ref,
  ) => {
    const items = collectItems(children)
    const ids = items.map((item) => item.id)
    const idsKey = JSON.stringify(ids)
    const [internalOrder, setInternalOrder] = React.useState<string[]>(() => normalizeOrder(defaultOrder, ids))
    const controlled = order !== undefined
    const currentOrder = normalizeOrder(order ?? internalOrder, ids)
    const itemMap = new Map(items.map((item) => [item.id, item]))
    const rows = currentOrder.map((id) => itemMap.get(id)!)
    const [reset, setReset] = React.useState(0)
    const signature = JSON.stringify([
      currentOrder,
      items.map((item) => [item.id, item.disabled]),
      disabled,
      horizontal,
      controlled,
    ])
    const nativeKey = `${signature}:${reset}`
    const native = React.useRef<FlatList<Row>>(null)
    const offset = React.useRef(horizontal ? (contentOffset?.x ?? 0) : (contentOffset?.y ?? 0))
    const mounted = React.useRef(true)
    const session = React.useRef<{ key: string; id: string } | null>(null)
    const [activeKey, setActiveKey] = React.useState<string | null>(null)
    const latest = React.useRef({ nativeKey, currentOrder, itemMap, disabled, controlled, onOrderChange })
    latest.current = { nativeKey, currentOrder, itemMap, disabled, controlled, onOrderChange }
    const busy = activeKey === nativeKey

    React.useEffect(() => {
      mounted.current = true
      return () => {
        mounted.current = false
        session.current = null
      }
    }, [])
    React.useEffect(() => {
      if (controlled) return
      setInternalOrder((previous) => {
        const next = normalizeOrder(previous, ids)
        return sameOrder(previous, next) ? previous : next
      })
      // Child identity, rather than row element identity, owns reconciliation.
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [idsKey, controlled])

    const cancel = React.useCallback(() => {
      if (!mounted.current || !session.current) return
      session.current = null
      setActiveKey(null)
      setReset((value) => value + 1)
    }, [])
    React.useEffect(() => {
      const subscription = AppState.addEventListener('change', (state) => {
        if (state !== 'active') cancel()
      })
      return () => subscription.remove()
    }, [cancel])

    React.useImperativeHandle(
      ref,
      () => ({
        cancel,
        scrollToOffset: (options) => native.current?.scrollToOffset(options),
        scrollToIndex: (options) => native.current?.scrollToIndex(options),
      }),
      [cancel],
    )

    const commit = (id: string, to: number, source: ReorderableChange['source']) => {
      const current = latest.current
      if (!mounted.current || current.disabled || current.itemMap.get(id)?.disabled) return
      const next = moveOrder(current.currentOrder, id, to)
      if (!next) return
      const from = current.currentOrder.indexOf(id)
      if (!current.controlled) setInternalOrder(next)
      current.onOrderChange?.([...next], { id, from, to, source })
    }
    const finish = ({ from, to }: DragEndParams<Row>) => {
      const active = session.current
      const current = latest.current
      if (!mounted.current || !active || active.key !== nativeKey || current.nativeKey !== nativeKey) return
      session.current = null
      setActiveKey(null)
      // v4.0.3 retains a cell's last translation until its next onLayout. A refused controlled
      // update leaves that layout unchanged, so reinitialize the backend after each settlement.
      setReset((value) => value + 1)
      if (current.currentOrder[from] !== active.id) return
      commit(active.id, to, 'drag')
    }
    const renderItem = ({ item, drag }: RenderItemParams<Row>) => {
      const itemDisabled = disabled || item.disabled
      const index = currentOrder.indexOf(item.id)
      const canMove = (direction: 'previous' | 'next') =>
        !itemDisabled && !busy && (direction === 'previous' ? index > 0 : index < currentOrder.length - 1)
      return (
        <ItemContext.Provider
          value={{
            disabled: itemDisabled,
            busy,
            canDrag: !itemDisabled && !busy && currentOrder.length > 1,
            canMove,
            drag: () => {
              const current = latest.current
              if (
                !mounted.current ||
                current.nativeKey !== nativeKey ||
                current.disabled ||
                current.itemMap.get(item.id)?.disabled ||
                session.current?.key === nativeKey ||
                current.currentOrder.length < 2
              )
                return
              drag()
            },
            move: (direction) => {
              const current = latest.current
              if (current.nativeKey !== nativeKey || session.current?.key === nativeKey) return
              const currentIndex = current.currentOrder.indexOf(item.id)
              commit(item.id, currentIndex + (direction === 'previous' ? -1 : 1), 'control')
            },
          }}
        >
          {item.element}
        </ItemContext.Provider>
      )
    }
    return (
      <View className={cn('w-full', className)} style={[{ height: 320 }, style]}>
        <DraggableFlatList
          {...props}
          key={nativeKey}
          ref={native}
          style={{ flex: 1 }}
          containerStyle={[{ flex: 1 }, containerStyle]}
          horizontal={horizontal}
          contentOffset={horizontal ? { x: offset.current, y: 0 } : { x: 0, y: offset.current }}
          data={rows}
          extraData={busy}
          numColumns={1}
          enableLayoutAnimationExperimental={false}
          keyExtractor={(item) => item.id}
          renderItem={renderItem}
          onScrollOffsetChange={(value) => {
            if (!mounted.current || latest.current.nativeKey !== nativeKey) return
            if (Number.isFinite(value)) offset.current = Math.max(0, value)
            onScrollOffsetChange?.(value)
          }}
          onDragBegin={(index) => {
            const current = latest.current
            const id = current.currentOrder[index]
            if (
              !mounted.current ||
              current.nativeKey !== nativeKey ||
              current.disabled ||
              !id ||
              current.itemMap.get(id)?.disabled ||
              current.currentOrder.length < 2
            )
              return
            session.current = { key: nativeKey, id }
            setActiveKey(nativeKey)
          }}
          onDragEnd={finish}
        />
      </View>
    )
  },
)
ReorderableCollection.displayName = 'ReorderableCollection'

export interface ReorderableItemProps extends ViewProps {
  id: string
  /** Prevents initiating a move for this item; other items may still pass it. */
  disabled?: boolean
  className?: string
}
export const ReorderableItem = React.forwardRef<React.ComponentRef<typeof View>, ReorderableItemProps>(
  ({ id: _id, disabled: _disabled, className, children, ...props }, ref) => {
    const item = useItem()
    return (
      <View {...props} ref={ref} className={cn(item.disabled && 'opacity-50', className)}>
        {renderTextChildren(children)}
      </View>
    )
  },
)
ReorderableItem.displayName = 'ReorderableItem'

export const ReorderableDragHandle = React.forwardRef<React.ComponentRef<typeof Pressable>, ButtonProps>(
  ({ disabled, onLongPress, children, ...props }, ref) => {
    const item = useItem()
    const blocked = !!disabled || !item.canDrag
    return (
      <Button
        variant="outline"
        {...props}
        ref={ref}
        disabled={blocked}
        onLongPress={(event) => {
          if (blocked) return
          onLongPress?.(event)
          if (!event.isDefaultPrevented()) item.drag()
        }}
      >
        {children ?? 'Move'}
      </Button>
    )
  },
)
ReorderableDragHandle.displayName = 'ReorderableDragHandle'

export interface ReorderableMoveProps extends ButtonProps {
  direction: 'previous' | 'next'
}
export const ReorderableMove = React.forwardRef<React.ComponentRef<typeof Pressable>, ReorderableMoveProps>(
  ({ direction, disabled, onPress, children, ...props }, ref) => {
    const item = useItem()
    const blocked = !!disabled || !item.canMove(direction)
    return (
      <Button
        variant="outline"
        {...props}
        ref={ref}
        disabled={blocked}
        onPress={(event) => {
          if (blocked) return
          onPress?.(event)
          if (!event.isDefaultPrevented()) item.move(direction)
        }}
      >
        {children ?? (direction === 'previous' ? 'Move earlier' : 'Move later')}
      </Button>
    )
  },
)
ReorderableMove.displayName = 'ReorderableMove'
components/ui/reorderable-collection/reorderable-collection.utils.ts
/** Reconcile a requested ID order with the currently composed children. */
export function normalizeOrder(requested: readonly string[] | undefined, ids: readonly string[]): string[] {
  const available = new Set(ids)
  const seen = new Set<string>()
  const result: string[] = []
  for (const id of [...(requested ?? []), ...ids]) {
    if (!available.has(id) || seen.has(id)) continue
    seen.add(id)
    result.push(id)
  }
  return result
}

export function sameOrder(a: readonly string[], b: readonly string[]): boolean {
  return a.length === b.length && a.every((id, index) => id === b[index])
}

export function moveOrder(order: readonly string[], id: string, to: number): string[] | null {
  const from = order.indexOf(id)
  if (from < 0 || !Number.isInteger(to) || to < 0 || to >= order.length || from === to) return null
  const next = [...order]
  next.splice(from, 1)
  next.splice(to, 0, id)
  return next
}
components/ui/reorderable-collection/index.ts
export * from './ReorderableCollection'

Dependencies

Registry items

npm packages

  • react-native-draggable-flatlist@4.0.3
  • react-native-gesture-handler
  • react-native-reanimated
Browse controls and interactions