{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "swipe-cards",
  "title": "Swipe cards",
  "description": "A stack of photo cards to swipe right to like or left to skip: the card tilts as it travels, a stamp and the matching button fill in near the commit point, and the cards behind rise to take its place.",
  "dependencies": [
    "motion",
    "lucide-react"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "registry/items/swipe-cards/swipe-cards.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { flushSync } from \"react-dom\";\nimport {\n  animate,\n  motion,\n  useDragControls,\n  useMotionValue,\n  useReducedMotionConfig,\n  useTransform,\n  type MotionValue,\n  type PanInfo,\n} from \"motion/react\";\nimport { Check, Heart, X } from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport type SwipeCardsItem = {\n  id: string;\n  title: string;\n  /** Cover image URL. */\n  image: string;\n  /** Shown under the title in the `choice` variant. */\n  description?: string;\n  /** Preformatted, e.g. \"₦85,000\". */\n  price?: string;\n  brand?: string;\n  condition?: string;\n  size?: string;\n};\n\nexport type SwipeDirection = \"left\" | \"right\";\n\nexport interface SwipeCardsProps {\n  items: SwipeCardsItem[];\n  /**\n   * `feed`: round skip and heart buttons, a price chip and condition, as on the\n   * Steeze tab. `choice`: two labelled pills (No / Yes, Less / More) that fill\n   * as the card leans, for quick surveys and tuning.\n   */\n  variant?: \"feed\" | \"choice\";\n  /** Left action and the stamp shown when dragging left. Defaults to \"Skip\" (feed) or \"No\" (choice). */\n  leftLabel?: string;\n  /** Right action. Defaults to \"Like\" (feed, stamped as ♥) or \"Yes\" (choice). */\n  rightLabel?: string;\n  /** Start again from the first card after the last. Defaults to true. */\n  loop?: boolean;\n  /** A card left the deck. `index` is its position in `items`. */\n  onSwipe?: (item: SwipeCardsItem, direction: SwipeDirection, index: number) => void;\n  /** The top card changed; `index` is its position in `items`. */\n  onIndexChange?: (index: number) => void;\n  /** Every card is gone (only when `loop` is false). */\n  onEmpty?: () => void;\n  /** The top card was tapped or Enter was pressed on the deck. */\n  onCardPress?: (item: SwipeCardsItem) => void;\n  /** Shows an \"Add to Bag\" chip on each card. */\n  onAddToBag?: (item: SwipeCardsItem) => void;\n  addToBagLabel?: string;\n  /** The drag crossed the commit point; the app plays a light haptic here. */\n  onThresholdCross?: (direction: SwipeDirection) => void;\n  /** Rendered in place of the deck once it is empty. */\n  empty?: React.ReactNode;\n  /** Accessible name for the deck. */\n  label?: string;\n  className?: string;\n}\n\n/** Commit when the drag passes a quarter of the deck's width… */\nconst THRESHOLD = 0.25;\n/** …or is released faster than this, in px/s. */\nconst FLING = 800;\n/** Each card behind sits 12px lower and 3% smaller. */\nconst STACK_SEP = 12;\nconst STACK_SCALE = 0.03;\n/** Degrees of tilt per deck-width of drag. */\nconst TILT = 15;\n/** Reanimated's withTiming default (ease in-out quad), 280ms, to 1.5 widths away. */\nconst FLY = { duration: 0.28, ease: [0.455, 0.03, 0.515, 0.955] } as const;\nconst SNAP = { type: \"spring\", stiffness: 300, damping: 20 } as const;\n\nconst clamp01 = (value: number) => Math.min(1, Math.max(0, value));\n\ntype CardMotion = {\n  x: MotionValue<number>;\n  y: MotionValue<number>;\n  rotate: MotionValue<number>;\n  scale: MotionValue<number>;\n  opacity: MotionValue<number>;\n};\n\ntype TopEffects = {\n  leftStamp: MotionValue<number>;\n  rightStamp: MotionValue<number>;\n  leftFill: MotionValue<number>;\n  rightFill: MotionValue<number>;\n  leftPill: MotionValue<number>;\n  rightPill: MotionValue<number>;\n};\n\n/**\n * Steeze's swipe deck: drag the top card right to like it or left to skip it,\n * or use the buttons or the arrow keys. The card tilts as it travels, a stamp\n * and the matching button fill in as it nears the commit point, and the cards\n * behind rise to take its place. Data in, a callback per swipe out.\n */\nexport function SwipeCards({\n  items,\n  variant = \"feed\",\n  leftLabel,\n  rightLabel,\n  loop = true,\n  onSwipe,\n  onIndexChange,\n  onEmpty,\n  onCardPress,\n  onAddToBag,\n  addToBagLabel = \"Add to Bag\",\n  onThresholdCross,\n  empty = null,\n  label = \"Swipe deck\",\n  className,\n}: SwipeCardsProps) {\n  const reduceMotion = useReducedMotionConfig();\n  const left = leftLabel ?? (variant === \"choice\" ? \"No\" : \"Skip\");\n  const right = rightLabel ?? (variant === \"choice\" ? \"Yes\" : \"Like\");\n\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const controls = useDragControls();\n  const [swiped, setSwiped] = React.useState(0);\n  const busy = React.useRef(false);\n  const crossed = React.useRef<{ left: boolean; right: boolean }>({ left: false, right: false });\n  const dragged = React.useRef(false);\n\n  // Pan of the top card, and the deck's width (the source measures the screen).\n  const x = useMotionValue(0);\n  const y = useMotionValue(0);\n  const width = useMotionValue(360);\n  const topOpacity = useMotionValue(1);\n  const zero = useMotionValue(0);\n  const one = useMotionValue(1);\n\n  React.useEffect(() => {\n    const element = rootRef.current;\n    if (!element) return;\n    const observer = new ResizeObserver(([entry]) => width.set(entry.contentRect.width || 360));\n    observer.observe(element);\n    return () => observer.disconnect();\n  }, [width]);\n\n  const threshold = () => width.get() * THRESHOLD;\n  const progress = useTransform(() => clamp01(Math.abs(x.get()) / threshold()));\n  const tilt = useTransform(() => (x.get() / width.get()) * TILT);\n\n  // The cards behind close the gap as the top card leaves.\n  const secondScale = useTransform(progress, [0, 1], [1 - STACK_SCALE, 1]);\n  const secondY = useTransform(progress, [0, 1], [STACK_SEP, 0]);\n  const thirdScale = useTransform(progress, [0, 1], [1 - STACK_SCALE * 2, 1 - STACK_SCALE]);\n  const thirdY = useTransform(progress, [0, 1], [STACK_SEP * 2, STACK_SEP]);\n\n  const effects: TopEffects = {\n    leftStamp: useTransform(() => clamp01((-x.get() - threshold() * 0.4) / (threshold() * 0.6))),\n    rightStamp: useTransform(() => clamp01((x.get() - threshold() * 0.4) / (threshold() * 0.6))),\n    leftFill: useTransform(() => clamp01(-x.get() / threshold())),\n    rightFill: useTransform(() => clamp01(x.get() / threshold())),\n    // The pills read full at half the threshold, before the card commits.\n    leftPill: useTransform(() => clamp01(-x.get() / (threshold() * 0.5))),\n    rightPill: useTransform(() => clamp01(x.get() / (threshold() * 0.5))),\n  };\n\n  const motionFor: CardMotion[] = [\n    { x, y, rotate: reduceMotion ? zero : tilt, scale: one, opacity: topOpacity },\n    { x: zero, y: secondY, rotate: zero, scale: secondScale, opacity: one },\n    { x: zero, y: thirdY, rotate: zero, scale: thirdScale, opacity: one },\n  ];\n\n  const length = items.length;\n  const finished = !loop && swiped >= length;\n  const positionOf = (absolute: number) => (loop ? absolute % length : absolute);\n  const cardAt = (absolute: number) =>\n    length === 0 || (!loop && absolute >= length) ? null : items[positionOf(absolute)];\n  const current = cardAt(swiped);\n\n  const emptyRef = React.useRef(onEmpty);\n  React.useEffect(() => {\n    emptyRef.current = onEmpty;\n  });\n  React.useEffect(() => {\n    if (finished && length > 0) emptyRef.current?.();\n  }, [finished, length]);\n\n  function commit(direction: SwipeDirection) {\n    if (busy.current || !current) return;\n    busy.current = true;\n    const item = current;\n    const index = positionOf(swiped);\n    const land = () => {\n      // Recentre the pan first, then swap the cards in the same task, so the\n      // next card is never painted off-screen and the old one never recentred.\n      x.jump(0);\n      y.jump(0);\n      topOpacity.jump(1);\n      flushSync(() => setSwiped((count) => count + 1));\n      busy.current = false;\n      crossed.current = { left: false, right: false };\n      onSwipe?.(item, direction, index);\n      if (loop || swiped + 1 < length) onIndexChange?.(positionOf(swiped + 1));\n    };\n    if (reduceMotion) {\n      void animate(topOpacity, 0, { duration: 0.18, ease: \"easeOut\" }).then(land);\n    } else {\n      const distance = width.get() * 1.5;\n      void animate(x, direction === \"right\" ? distance : -distance, FLY).then(land);\n    }\n  }\n\n  function onDrag() {\n    const dx = x.get();\n    const limit = threshold();\n    if (Math.abs(dx) < limit / 2) {\n      crossed.current = { left: false, right: false };\n    } else if (dx > limit && !crossed.current.right) {\n      crossed.current.right = true;\n      onThresholdCross?.(\"right\");\n    } else if (dx < -limit && !crossed.current.left) {\n      crossed.current.left = true;\n      onThresholdCross?.(\"left\");\n    }\n  }\n\n  function onDragEnd(_: unknown, info: PanInfo) {\n    const dx = x.get();\n    if (Math.abs(dx) > threshold() || Math.abs(info.velocity.x) > FLING) {\n      commit(dx > 0 || (dx === 0 && info.velocity.x > 0) ? \"right\" : \"left\");\n      return;\n    }\n    crossed.current = { left: false, right: false };\n    const back = reduceMotion ? { duration: 0.15 } : SNAP;\n    void animate(x, 0, back);\n    void animate(y, 0, back);\n  }\n\n  function onKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {\n    if (event.target !== event.currentTarget) return;\n    if (event.key === \"ArrowLeft\") {\n      event.preventDefault();\n      commit(\"left\");\n    } else if (event.key === \"ArrowRight\") {\n      event.preventDefault();\n      commit(\"right\");\n    } else if (event.key === \"Enter\" && current) {\n      onCardPress?.(current);\n    }\n  }\n\n  if (length === 0 || finished) return <>{empty}</>;\n\n  const stack = [0, 1, 2]\n    .map((depth) => ({ depth, absolute: swiped + depth, item: cardAt(swiped + depth) }))\n    .filter((card): card is { depth: number; absolute: number; item: SwipeCardsItem } => card.item !== null);\n\n  return (\n    <div\n      ref={rootRef}\n      role=\"group\"\n      aria-roledescription=\"swipe deck\"\n      aria-label={label}\n      aria-keyshortcuts=\"ArrowLeft ArrowRight\"\n      tabIndex={0}\n      onKeyDown={onKeyDown}\n      className={cn(\n        \"relative aspect-[37/65] w-full max-w-[370px] select-none rounded-[20px] outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-4 focus-visible:ring-offset-background\",\n        className,\n      )}\n    >\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {current ? `${current.title}${current.price ? `, ${current.price}` : \"\"}. Left arrow: ${left}. Right arrow: ${right}.` : \"\"}\n      </span>\n      {stack\n        .slice()\n        .reverse()\n        .map(({ depth, absolute, item }) => {\n          const top = depth === 0;\n          const style = motionFor[depth];\n          return (\n            <motion.div\n              key={absolute}\n              aria-hidden={top ? undefined : true}\n              inert={!top}\n              className={cn(\"absolute inset-x-0 top-[5%] h-[90%] rounded-[20px]\", top && \"cursor-grab active:cursor-grabbing\")}\n              style={{ ...style, zIndex: 10 - depth, touchAction: top ? \"none\" : undefined }}\n              drag={top}\n              dragControls={controls}\n              dragListener={false}\n              dragMomentum={false}\n              onDrag={top ? onDrag : undefined}\n              onDragStart={() => {\n                dragged.current = true;\n              }}\n              onDragEnd={top ? onDragEnd : undefined}\n              onPointerDown={(event) => {\n                if (!top || busy.current) return;\n                dragged.current = false;\n                controls.start(event);\n              }}\n              onClick={() => {\n                if (top && !dragged.current) onCardPress?.(item);\n              }}\n            >\n              <Card\n                item={item}\n                variant={variant}\n                left={left}\n                right={right}\n                effects={top ? effects : null}\n                onLeft={() => commit(\"left\")}\n                onRight={() => commit(\"right\")}\n                onAddToBag={onAddToBag}\n                addToBagLabel={addToBagLabel}\n              />\n            </motion.div>\n          );\n        })}\n    </div>\n  );\n}\n\n/** Keeps a press on a control from starting a drag or counting as a card tap. */\nfunction guard(action: () => void) {\n  return {\n    onPointerDown: (event: React.PointerEvent) => event.stopPropagation(),\n    onClick: (event: React.MouseEvent) => {\n      event.stopPropagation();\n      action();\n    },\n  };\n}\n\nfunction Card({\n  item,\n  variant,\n  left,\n  right,\n  effects,\n  onLeft,\n  onRight,\n  onAddToBag,\n  addToBagLabel,\n}: {\n  item: SwipeCardsItem;\n  variant: \"feed\" | \"choice\";\n  left: string;\n  right: string;\n  effects: TopEffects | null;\n  onLeft: () => void;\n  onRight: () => void;\n  onAddToBag?: (item: SwipeCardsItem) => void;\n  addToBagLabel: string;\n}) {\n  const choice = variant === \"choice\";\n  const details = item.condition ? `${item.condition}${item.size ? ` • ${item.size}` : \"\"}` : item.size;\n\n  return (\n    <div className=\"relative size-full overflow-hidden rounded-[20px] bg-tonal\">\n      {/* eslint-disable-next-line @next/next/no-img-element -- registry items are framework-agnostic */}\n      <img src={item.image} alt=\"\" draggable={false} className=\"pointer-events-none absolute inset-0 size-full object-cover\" />\n\n      {/* Stamps: the left action shows top right while leaning left, and vice versa. */}\n      <motion.span\n        aria-hidden=\"true\"\n        style={{ opacity: effects?.leftStamp ?? 0 }}\n        className=\"pointer-events-none absolute top-4 right-4 z-20 rotate-[15deg] font-heading text-[44px] leading-none font-semibold text-destructive\"\n      >\n        {left}\n      </motion.span>\n      <motion.span\n        aria-hidden=\"true\"\n        style={{ opacity: effects?.rightStamp ?? 0 }}\n        className={cn(\n          \"pointer-events-none absolute top-4 left-4 z-20 -rotate-[15deg] leading-none text-lead\",\n          choice ? \"font-heading text-[44px] font-semibold\" : \"text-[64px]\",\n        )}\n      >\n        {choice ? right : \"♥\"}\n      </motion.span>\n\n      {onAddToBag ? (\n        <button\n          type=\"button\"\n          {...guard(() => onAddToBag(item))}\n          className=\"absolute top-4 right-4 z-10 rounded-inset bg-secondary/80 px-3 py-2 font-body text-sm font-semibold text-secondary-foreground shadow-[0_2px_4px_var(--menu-shadow)] transition-opacity hover:opacity-90 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-menu-ink\"\n        >\n          {addToBagLabel}\n        </button>\n      ) : null}\n\n      {/* A blurred, darkened band rising from the bottom, under the details. */}\n      <div className=\"absolute inset-x-0 bottom-0 flex flex-col justify-end\">\n        <div\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute inset-x-0 bottom-0 h-[220px] backdrop-blur-[6px]\"\n          style={{\n            maskImage: \"linear-gradient(to bottom, transparent, black 30%)\",\n            WebkitMaskImage: \"linear-gradient(to bottom, transparent, black 30%)\",\n            backgroundImage:\n              \"linear-gradient(to bottom, transparent, color-mix(in srgb, var(--menu-shadow) 50%, transparent) 50%, var(--menu-shadow))\",\n          }}\n        />\n        <div className=\"relative p-5 pt-8\">\n          <div className=\"flex w-full items-start justify-between\">\n            <h3 className=\"mr-4 line-clamp-2 flex-1 font-heading text-[26px] leading-8 font-medium tracking-[-0.5px] text-menu-ink\">\n              {item.title}\n            </h3>\n            {item.price ? (\n              <span className=\"shrink-0 self-start rounded-full bg-secondary px-3 py-1 font-body text-base font-bold whitespace-nowrap text-secondary-foreground\">\n                {item.price}\n              </span>\n            ) : null}\n          </div>\n\n          {choice && item.description ? (\n            <p className=\"mt-1 mb-4 line-clamp-2 font-body text-base text-menu-dim\">{item.description}</p>\n          ) : item.brand || (!choice && details) ? (\n            <div className=\"mt-2 mb-4 flex items-center justify-between gap-3\">\n              {item.brand ? (\n                <span className=\"font-body text-sm font-semibold tracking-tighter text-menu-dim uppercase\">{item.brand}</span>\n              ) : (\n                <span />\n              )}\n              {!choice && details ? (\n                <span className=\"max-w-[180px] truncate rounded-full bg-tonal px-3 py-1.5 font-body text-sm font-medium text-on-tonal\">\n                  {details}\n                </span>\n              ) : null}\n            </div>\n          ) : (\n            <div className=\"mb-4\" />\n          )}\n\n          {choice ? (\n            <div className=\"mt-2 flex items-center justify-center gap-4\">\n              <button\n                type=\"button\"\n                aria-label={left}\n                {...guard(onLeft)}\n                className=\"relative flex items-center justify-center overflow-hidden rounded-full bg-tonal px-7 py-2 font-body text-lg font-semibold text-on-tonal focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-menu-ink\"\n              >\n                <motion.span\n                  aria-hidden=\"true\"\n                  style={{ scaleX: effects?.leftPill ?? 0 }}\n                  className=\"absolute inset-0 origin-right bg-stop/40\"\n                />\n                <span className=\"relative flex items-center gap-2\">\n                  <X aria-hidden=\"true\" className=\"size-[18px]\" />\n                  {left}\n                </span>\n              </button>\n              <button\n                type=\"button\"\n                aria-label={right}\n                {...guard(onRight)}\n                className=\"relative flex items-center justify-center overflow-hidden rounded-full bg-tonal px-7 py-2 font-body text-lg font-semibold text-on-tonal focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-menu-ink\"\n              >\n                <motion.span\n                  aria-hidden=\"true\"\n                  style={{ scaleX: effects?.rightPill ?? 0 }}\n                  className=\"absolute inset-0 origin-left bg-lead/45\"\n                />\n                <span className=\"relative flex items-center gap-2\">\n                  <Check aria-hidden=\"true\" className=\"size-[18px]\" />\n                  {right}\n                </span>\n              </button>\n            </div>\n          ) : (\n            <div className=\"mt-2 flex items-center justify-center gap-4\">\n              <button\n                type=\"button\"\n                aria-label={left}\n                {...guard(onLeft)}\n                className=\"relative flex size-[52px] items-center justify-center overflow-hidden rounded-full text-menu-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-menu-ink\"\n              >\n                <motion.span\n                  aria-hidden=\"true\"\n                  style={{ scaleY: effects?.leftFill ?? 0 }}\n                  className=\"absolute inset-0 origin-bottom bg-destructive\"\n                />\n                <X aria-hidden=\"true\" className=\"relative size-[26px]\" />\n              </button>\n              <button\n                type=\"button\"\n                aria-label={right}\n                {...guard(onRight)}\n                className=\"relative flex size-[52px] items-center justify-center overflow-hidden rounded-full text-lead focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-menu-ink\"\n              >\n                <motion.span\n                  aria-hidden=\"true\"\n                  style={{ scaleY: effects?.rightFill ?? 0 }}\n                  className=\"absolute inset-0 origin-bottom bg-menu-ink\"\n                />\n                <Heart aria-hidden=\"true\" className=\"relative size-[30px] fill-current\" />\n              </button>\n            </div>\n          )}\n        </div>\n      </div>\n    </div>\n  );\n}\n\nexport default SwipeCards;\n",
      "type": "registry:block"
    }
  ],
  "meta": {
    "kind": "pattern",
    "whenToUse": "Use for fast, one-at-a-time judgements over visual items: a discovery feed, a taste survey, tuning recommendations. Not for anything people need to compare side by side or come back to; a swipe is gone. Buttons and the arrow keys do the same as a drag.",
    "origin": {
      "project": "Steeze",
      "path": "components/swipe/SwipeDeck.tsx + SwipeCard.tsx (app/(root)/(tabs)/steeze.tsx)"
    },
    "credits": [
      {
        "name": "Steeze category photos, found on Pinterest (original photographers unknown); gallery preview only, not shipped",
        "license": "unknown"
      }
    ]
  },
  "type": "registry:block"
}
