{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "motion-swap-grid",
  "title": "Swap grid",
  "description": "A grid of slots where items are dragged onto each other to swap places, with a full keyboard path.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "components/core/swap-grid.tsx",
      "content": "'use client';\n\nimport {\n  animate,\n  motion,\n  type MotionValue,\n  type Transition,\n  useMotionValue,\n} from 'motion/react';\nimport { useCallback, useId, useLayoutEffect, useRef, useState } from 'react';\n\nimport { cn } from '@/lib/utils';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\n\nexport type SwapGridItem = {\n  id: string;\n  label: string;\n  content: React.ReactNode;\n};\n\nexport type SwapGridSlots = (string | null)[];\n\ntype TileHandle = {\n  element: HTMLElement;\n  x: MotionValue<number>;\n  y: MotionValue<number>;\n};\n\ntype FlipStart = {\n  left: number;\n  top: number;\n  velocityX: number;\n  velocityY: number;\n};\n\ntype DragSession = {\n  id: string;\n  pointerId: number;\n  startX: number;\n  startY: number;\n  originX: number;\n  originY: number;\n  originSlot: number;\n  isActive: boolean;\n};\n\ntype Grab = {\n  id: string;\n  originSlots: SwapGridSlots;\n};\n\ntype Step = { rows: number; columns: number };\n\nconst SETTLE: Transition = { type: 'spring', bounce: 0, duration: 0.4 };\n\nconst DRAG_THRESHOLD = 4;\n\nconst STEPS: Record<string, Step> = {\n  ArrowUp: { rows: -1, columns: 0 },\n  ArrowDown: { rows: 1, columns: 0 },\n  ArrowLeft: { rows: 0, columns: -1 },\n  ArrowRight: { rows: 0, columns: 1 },\n};\n\nconst CONTROLS = 'button, a, input, select, textarea, [contenteditable=\"true\"]';\n\nfunction placementOf(index: number, columns: number): React.CSSProperties {\n  const column = index % columns;\n  const row = Math.floor(index / columns);\n  return { gridColumn: column + 1, gridRow: row + 1 };\n}\n\nfunction positionOf(index: number, columns: number) {\n  const column = index % columns;\n  const row = Math.floor(index / columns);\n  return `row ${row + 1}, column ${column + 1}`;\n}\n\nfunction neighbourOf(\n  index: number,\n  step: Step,\n  columns: number,\n  slotCount: number\n) {\n  const column = index % columns;\n  const row = Math.floor(index / columns);\n  const nextColumn = column + step.columns;\n  const nextRow = row + step.rows;\n  const isInsideRow = nextColumn >= 0 && nextColumn < columns;\n  const rowStart = nextRow * columns;\n  const nextIndex = rowStart + nextColumn;\n  const isInsideGrid = nextRow >= 0 && nextIndex < slotCount;\n  if (!isInsideRow) {\n    return null;\n  }\n  if (!isInsideGrid) {\n    return null;\n  }\n  return nextIndex;\n}\n\nfunction swappedSlots(slots: SwapGridSlots, from: number, to: number) {\n  const next = [...slots];\n  const moving = next[from];\n  next[from] = next[to];\n  next[to] = moving;\n  return next;\n}\n\nfunction presentIds(ids: (string | null)[]) {\n  return ids.filter((id): id is string => id !== null);\n}\n\nfunction changedIds(before: SwapGridSlots, after: SwapGridSlots) {\n  const moved = after.filter((id, index) => id !== before[index]);\n  return presentIds(moved);\n}\n\nfunction startsOnControl(event: React.PointerEvent<HTMLElement>) {\n  const target = event.target as HTMLElement;\n  const control = target.closest(CONTROLS);\n  if (!control) {\n    return false;\n  }\n  return event.currentTarget.contains(control);\n}\n\nfunction isPrimaryPress(event: React.PointerEvent) {\n  return event.button === 0;\n}\n\nfunction isActivationKey(event: React.KeyboardEvent) {\n  return event.key === 'Enter' || event.key === ' ';\n}\n\nfunction initialSlotsOf(\n  items: SwapGridItem[],\n  defaultSlots: SwapGridSlots | undefined\n) {\n  if (defaultSlots) {\n    return defaultSlots;\n  }\n  return items.map((item) => item.id);\n}\n\nexport type SwapGridProps = {\n  items: SwapGridItem[];\n  columns?: number;\n  defaultSlots?: SwapGridSlots;\n  onSlotsChange?: (slots: SwapGridSlots) => void;\n  className?: string;\n  itemClassName?: string;\n  'aria-label'?: string;\n};\n\nexport function SwapGrid({\n  items,\n  columns = 3,\n  defaultSlots,\n  onSlotsChange,\n  className,\n  itemClassName,\n  'aria-label': ariaLabel,\n}: SwapGridProps) {\n  const prefersReducedMotion = usePrefersReducedMotion();\n  const [slots, setSlots] = useState(() => initialSlotsOf(items, defaultSlots));\n  const [draggingId, setDraggingId] = useState<string | null>(null);\n  const [targetSlot, setTargetSlot] = useState<number | null>(null);\n  const [grab, setGrab] = useState<Grab | null>(null);\n  const [announcement, setAnnouncement] = useState('');\n  const tiles = useRef(new Map<string, TileHandle>());\n  const slotElements = useRef(new Map<number, HTMLElement>());\n  const flipStarts = useRef<Map<string, FlipStart> | null>(null);\n  const drag = useRef<DragSession | null>(null);\n  const hintId = useId();\n  const labels = new Map(items.map((item) => [item.id, item.label]));\n  const contents = new Map(items.map((item) => [item.id, item.content]));\n\n  useLayoutEffect(() => {\n    const starts = flipStarts.current;\n    flipStarts.current = null;\n    if (!starts) {\n      return;\n    }\n    starts.forEach((start, id) => {\n      const tile = tiles.current.get(id);\n      if (!tile) {\n        return;\n      }\n      if (prefersReducedMotion) {\n        tile.x.jump(0);\n        tile.y.jump(0);\n        return;\n      }\n      const deltaX = start.left - tile.element.offsetLeft;\n      const deltaY = start.top - tile.element.offsetTop;\n      tile.x.jump(deltaX);\n      tile.y.jump(deltaY);\n      animate(tile.x, 0, { ...SETTLE, velocity: start.velocityX });\n      animate(tile.y, 0, { ...SETTLE, velocity: start.velocityY });\n    });\n  }, [slots, prefersReducedMotion]);\n\n  const registerTile = useCallback((id: string, handle: TileHandle) => {\n    tiles.current.set(id, handle);\n    return () => {\n      tiles.current.delete(id);\n    };\n  }, []);\n\n  function registerSlot(index: number, element: HTMLElement | null) {\n    if (!element) {\n      slotElements.current.delete(index);\n      return;\n    }\n    slotElements.current.set(index, element);\n  }\n\n  function labelOf(id: string | null) {\n    if (id === null) {\n      return '';\n    }\n    return labels.get(id) ?? id;\n  }\n\n  function rememberPositions(ids: string[]) {\n    const starts = new Map<string, FlipStart>();\n    for (const id of ids) {\n      const tile = tiles.current.get(id);\n      if (!tile) {\n        continue;\n      }\n      const left = tile.element.offsetLeft + tile.x.get();\n      const top = tile.element.offsetTop + tile.y.get();\n      const velocityX = tile.x.getVelocity();\n      const velocityY = tile.y.getVelocity();\n      starts.set(id, { left, top, velocityX, velocityY });\n    }\n    return starts;\n  }\n\n  function commitSlots(next: SwapGridSlots) {\n    const moved = changedIds(slots, next);\n    flipStarts.current = rememberPositions(moved);\n    setSlots(next);\n    onSlotsChange?.(next);\n  }\n\n  function swapMessage(id: string, from: number, to: number) {\n    const label = labelOf(id);\n    const position = positionOf(to, columns);\n    const displaced = slots[to];\n    if (displaced === null) {\n      return `${label} moved to ${position}`;\n    }\n    const displacedLabel = labelOf(displaced);\n    const displacedPosition = positionOf(from, columns);\n    return `${label} swapped with ${displacedLabel}. ${label} is in ${position}, ${displacedLabel} in ${displacedPosition}`;\n  }\n\n  function swap(id: string, from: number, to: number) {\n    const message = swapMessage(id, from, to);\n    const next = swappedSlots(slots, from, to);\n    setAnnouncement(message);\n    commitSlots(next);\n  }\n\n  function slotAt(clientX: number, clientY: number) {\n    for (const [index, element] of slotElements.current) {\n      const box = element.getBoundingClientRect();\n      const isInsideX = clientX >= box.left && clientX <= box.right;\n      const isInsideY = clientY >= box.top && clientY <= box.bottom;\n      if (isInsideX && isInsideY) {\n        return index;\n      }\n    }\n    return null;\n  }\n\n  function returnHome(id: string) {\n    const tile = tiles.current.get(id);\n    if (!tile) {\n      return;\n    }\n    if (prefersReducedMotion) {\n      tile.x.jump(0);\n      tile.y.jump(0);\n      return;\n    }\n    animate(tile.x, 0, SETTLE);\n    animate(tile.y, 0, SETTLE);\n  }\n\n  function pressTile(id: string, event: React.PointerEvent<HTMLElement>) {\n    if (drag.current) {\n      return;\n    }\n    if (!isPrimaryPress(event)) {\n      return;\n    }\n    if (startsOnControl(event)) {\n      return;\n    }\n    const tile = tiles.current.get(id);\n    if (!tile) {\n      return;\n    }\n    drag.current = {\n      id,\n      pointerId: event.pointerId,\n      startX: event.clientX,\n      startY: event.clientY,\n      originX: tile.x.get(),\n      originY: tile.y.get(),\n      originSlot: slots.indexOf(id),\n      isActive: false,\n    };\n  }\n\n  function activateDrag(\n    session: DragSession,\n    tile: TileHandle,\n    event: React.PointerEvent<HTMLElement>\n  ) {\n    session.isActive = true;\n    event.currentTarget.setPointerCapture(event.pointerId);\n    tile.x.stop();\n    tile.y.stop();\n    window.getSelection()?.removeAllRanges();\n    setDraggingId(session.id);\n  }\n\n  function moveTile(event: React.PointerEvent<HTMLElement>) {\n    const session = drag.current;\n    if (!session) {\n      return;\n    }\n    if (event.pointerId !== session.pointerId) {\n      return;\n    }\n    const tile = tiles.current.get(session.id);\n    if (!tile) {\n      return;\n    }\n    const deltaX = event.clientX - session.startX;\n    const deltaY = event.clientY - session.startY;\n    const distance = Math.hypot(deltaX, deltaY);\n    const isStillAPress = !session.isActive && distance < DRAG_THRESHOLD;\n    if (isStillAPress) {\n      return;\n    }\n    if (!session.isActive) {\n      activateDrag(session, tile, event);\n    }\n    tile.x.set(session.originX + deltaX);\n    tile.y.set(session.originY + deltaY);\n    const target = slotAt(event.clientX, event.clientY);\n    setTargetSlot(target);\n  }\n\n  function endDrag(event: React.PointerEvent<HTMLElement>, canDrop: boolean) {\n    const session = drag.current;\n    if (!session) {\n      return;\n    }\n    if (event.pointerId !== session.pointerId) {\n      return;\n    }\n    drag.current = null;\n    if (!session.isActive) {\n      return;\n    }\n    setDraggingId(null);\n    setTargetSlot(null);\n    const target = slotAt(event.clientX, event.clientY);\n    const isOtherSlot = target !== session.originSlot;\n    const isDrop = canDrop && isOtherSlot;\n    if (target === null || !isDrop) {\n      returnHome(session.id);\n      return;\n    }\n    swap(session.id, session.originSlot, target);\n  }\n\n  function releaseTile(event: React.PointerEvent<HTMLElement>) {\n    endDrag(event, true);\n  }\n\n  function cancelDrag(event: React.PointerEvent<HTMLElement>) {\n    endDrag(event, false);\n  }\n\n  function pickUp(id: string) {\n    const slot = slots.indexOf(id);\n    const position = positionOf(slot, columns);\n    const label = labelOf(id);\n    setGrab({ id, originSlots: slots });\n    setAnnouncement(\n      `${label} picked up in ${position}. Use the arrow keys to move it, Enter to drop it, Escape to cancel`\n    );\n  }\n\n  function drop(id: string) {\n    const slot = slots.indexOf(id);\n    const position = positionOf(slot, columns);\n    const label = labelOf(id);\n    setGrab(null);\n    setAnnouncement(`${label} dropped in ${position}`);\n  }\n\n  function cancelGrab(current: Grab) {\n    const slot = current.originSlots.indexOf(current.id);\n    const position = positionOf(slot, columns);\n    const label = labelOf(current.id);\n    setGrab(null);\n    setAnnouncement(`Move cancelled. ${label} is back in ${position}`);\n    commitSlots(current.originSlots);\n  }\n\n  function moveGrabbed(id: string, step: Step) {\n    const from = slots.indexOf(id);\n    const to = neighbourOf(from, step, columns, slots.length);\n    if (to === null) {\n      return;\n    }\n    swap(id, from, to);\n  }\n\n  function handleKeyDown(id: string, event: React.KeyboardEvent<HTMLElement>) {\n    if (event.target !== event.currentTarget) {\n      return;\n    }\n    const isGrabbed = grab?.id === id;\n    if (isActivationKey(event)) {\n      event.preventDefault();\n      if (event.repeat) {\n        return;\n      }\n      if (isGrabbed) {\n        drop(id);\n        return;\n      }\n      pickUp(id);\n      return;\n    }\n    if (!grab) {\n      return;\n    }\n    if (!isGrabbed) {\n      return;\n    }\n    if (event.key === 'Escape') {\n      event.preventDefault();\n      cancelGrab(grab);\n      return;\n    }\n    const step = STEPS[event.key];\n    if (!step) {\n      return;\n    }\n    event.preventDefault();\n    moveGrabbed(id, step);\n  }\n\n  function handleBlur(id: string) {\n    if (grab?.id !== id) {\n      return;\n    }\n    drop(id);\n  }\n\n  function isDropTargetOf(id: string, index: number) {\n    if (draggingId === null) {\n      return false;\n    }\n    if (draggingId === id) {\n      return false;\n    }\n    return targetSlot === index;\n  }\n\n  const gridStyle = {\n    gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`,\n  };\n\n  return (\n    <>\n      <div\n        role='group'\n        aria-label={ariaLabel}\n        className={cn('relative grid gap-3', className)}\n        style={gridStyle}\n      >\n        {slots.map((id, index) => (\n          <SwapSlot\n            key={`slot-${index}`}\n            index={index}\n            columns={columns}\n            isEmpty={id === null}\n            isTarget={targetSlot === index}\n            register={registerSlot}\n          />\n        ))}\n        {slots.map((id, index) => {\n          if (id === null) {\n            return null;\n          }\n          return (\n            <SwapTile\n              key={id}\n              id={id}\n              label={labelOf(id)}\n              slotIndex={index}\n              columns={columns}\n              hintId={hintId}\n              isDragging={draggingId === id}\n              isDropTarget={isDropTargetOf(id, index)}\n              isGrabbed={grab?.id === id}\n              className={itemClassName}\n              register={registerTile}\n              onPress={pressTile}\n              onMove={moveTile}\n              onRelease={releaseTile}\n              onCancel={cancelDrag}\n              onKeyDown={handleKeyDown}\n              onBlur={handleBlur}\n            >\n              {contents.get(id)}\n            </SwapTile>\n          );\n        })}\n      </div>\n      <p id={hintId} className='sr-only'>\n        Press Enter or Space to pick up an item, the arrow keys to swap it with\n        its neighbour, Enter to drop it and Escape to cancel.\n      </p>\n      <p aria-live='polite' className='sr-only'>\n        {announcement}\n      </p>\n    </>\n  );\n}\n\nconst SLOT = [\n  'hairline-border rounded-xl border-dashed border-transparent',\n  'transition-colors duration-150 ease-(--ease-out-strong)',\n  'data-[empty=true]:border-foreground/15',\n  'data-[target=true]:border-primary/50 data-[target=true]:bg-primary/[0.06]',\n].join(' ');\n\ntype SwapSlotProps = {\n  index: number;\n  columns: number;\n  isEmpty: boolean;\n  isTarget: boolean;\n  register: (index: number, element: HTMLElement | null) => void;\n};\n\nfunction SwapSlot({\n  index,\n  columns,\n  isEmpty,\n  isTarget,\n  register,\n}: SwapSlotProps) {\n  function attach(element: HTMLDivElement | null) {\n    register(index, element);\n  }\n\n  return (\n    <div\n      ref={attach}\n      aria-hidden='true'\n      data-empty={isEmpty}\n      data-target={isTarget}\n      className={SLOT}\n      style={placementOf(index, columns)}\n    />\n  );\n}\n\nconst TILE = [\n  'group/tile relative z-10 cursor-grab touch-none rounded-xl outline-none select-none',\n  'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',\n  'data-[dragging=true]:z-30 data-[dragging=true]:cursor-grabbing',\n  'data-[grabbed=true]:z-20',\n].join(' ');\n\nconst TILE_SURFACE = [\n  'size-full rounded-xl bg-card text-card-foreground',\n  'hairline-ring ring-border shadow-[0_1px_2px_rgb(0_0_0/0.04)]',\n  'transition-[scale,box-shadow] duration-150 ease-(--ease-out-strong)',\n  'motion-safe:group-data-[dragging=true]/tile:scale-[1.03] motion-safe:group-data-[grabbed=true]/tile:scale-[1.03]',\n  'group-data-[dragging=true]/tile:shadow-[0_12px_32px_-8px_rgb(0_0_0/0.18)]',\n  'group-data-[grabbed=true]/tile:ring-primary/60 group-data-[target=true]/tile:ring-primary/60',\n].join(' ');\n\ntype SwapTileProps = {\n  id: string;\n  label: string;\n  slotIndex: number;\n  columns: number;\n  hintId: string;\n  isDragging: boolean;\n  isDropTarget: boolean;\n  isGrabbed: boolean;\n  className?: string;\n  register: (id: string, handle: TileHandle) => () => void;\n  onPress: (id: string, event: React.PointerEvent<HTMLElement>) => void;\n  onMove: (event: React.PointerEvent<HTMLElement>) => void;\n  onRelease: (event: React.PointerEvent<HTMLElement>) => void;\n  onCancel: (event: React.PointerEvent<HTMLElement>) => void;\n  onKeyDown: (id: string, event: React.KeyboardEvent<HTMLElement>) => void;\n  onBlur: (id: string) => void;\n  children: React.ReactNode;\n};\n\nfunction SwapTile({\n  id,\n  label,\n  slotIndex,\n  columns,\n  hintId,\n  isDragging,\n  isDropTarget,\n  isGrabbed,\n  className,\n  register,\n  onPress,\n  onMove,\n  onRelease,\n  onCancel,\n  onKeyDown,\n  onBlur,\n  children,\n}: SwapTileProps) {\n  const x = useMotionValue(0);\n  const y = useMotionValue(0);\n\n  const attach = useCallback(\n    (element: HTMLDivElement | null) => {\n      if (!element) {\n        return;\n      }\n      return register(id, { element, x, y });\n    },\n    [id, register, x, y]\n  );\n\n  function press(event: React.PointerEvent<HTMLDivElement>) {\n    onPress(id, event);\n  }\n\n  function keyDown(event: React.KeyboardEvent<HTMLDivElement>) {\n    onKeyDown(id, event);\n  }\n\n  function blur() {\n    onBlur(id);\n  }\n\n  return (\n    <motion.div\n      ref={attach}\n      role='button'\n      tabIndex={0}\n      aria-roledescription='swappable item'\n      aria-label={`${label}, ${positionOf(slotIndex, columns)}`}\n      aria-describedby={hintId}\n      aria-pressed={isGrabbed}\n      data-dragging={isDragging}\n      data-grabbed={isGrabbed}\n      data-target={isDropTarget}\n      className={TILE}\n      style={{ ...placementOf(slotIndex, columns), x, y }}\n      onPointerDown={press}\n      onPointerMove={onMove}\n      onPointerUp={onRelease}\n      onPointerCancel={onCancel}\n      onKeyDown={keyDown}\n      onBlur={blur}\n    >\n      <div className={cn(TILE_SURFACE, className)}>{children}</div>\n    </motion.div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/core/swap-grid.tsx"
    }
  ],
  "categories": [
    "motion"
  ],
  "type": "registry:component"
}