{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"stacked-card-slider","type":"registry:component","title":"Stacked card slider","description":"Click to cycle cards with GSAP Flip.","author":"DiMaac (HankTheTank) <https://dimaac.com>","dependencies":["gsap","@gsap/react"],"files":[{"path":"registry/dimaac/stacked-card-slider/stacked-card-slider.tsx","type":"registry:component","target":"components/dimaac/stacked-card-slider.tsx","content":"\"use client\";\n\nimport { useRef, useState } from \"react\";\nimport { gsap } from \"gsap\";\nimport { Flip } from \"gsap/Flip\";\nimport { useGSAP } from \"@gsap/react\";\n\n// A deck of photos stacked on a diagonal. Click it (or press an arrow key, or swipe) and the front\n// card slides away while the rest step forward and a fresh card settles in at the back.\n// GSAP Flip does the stepping: React moves the cards to their new spots, Flip then plays the\n// move backwards-to-forwards, so the animation always starts exactly where the cards were.\n\nif (typeof window !== \"undefined\") gsap.registerPlugin(Flip);\n\nexport type StackedCard = {\n  /** Image address. */\n  image: string;\n  /** What the photo shows, for screen readers. */\n  alt?: string;\n};\n\nexport type StackedCardSliderProps = {\n  /** The cards, front card first. Each click brings the next one to the front. */\n  cards: StackedCard[];\n  /** Width of a card, in pixels. It shrinks on its own if the box is narrower. */\n  cardWidth?: number;\n  /** How far each card behind sticks out up and to the right, in pixels. */\n  offsetStep?: number;\n  /** Card width divided by card height. 0.67 is a 2:3 portrait. */\n  aspectRatio?: number;\n  /** How many cards show in the stack at once (the rest wait invisibly behind the last one). */\n  visibleCards?: number;\n  /** How long one step takes, in seconds. */\n  duration?: number;\n  /** The GSAP ease of the step, e.g. \"sine.inOut\" or \"expo.inOut\". */\n  ease?: string;\n  /** Corner radius of the cards, in pixels. */\n  radius?: number;\n  /** Called with the index (in `cards`) of the new front card as every step starts. */\n  onChange?: (index: number) => void;\n  /** Extra classes for the outer box. Give it a size (it fills its parent); the stack sits in the middle of it. */\n  className?: string;\n  /** Extra classes for each card image, e.g. a different shadow. */\n  cardClassName?: string;\n};\n\ntype View = {\n  /** Which card is at the front */\n  front: number;\n  /** The card that is flying away right now, drawn as a copy on top of everything */\n  leaving: number | null;\n};\n\ntype Pending = {\n  /** Where the cards were before the step */\n  state: Flip.FlipState;\n  /** +1 = forward, -1 = back */\n  step: 1 | -1;\n};\n\nexport function StackedCardSlider({\n  cards,\n  cardWidth = 300,\n  offsetStep = 20,\n  aspectRatio = 0.67,\n  visibleCards = 5,\n  duration = 0.5,\n  ease = \"sine.inOut\",\n  radius = 6,\n  onChange,\n  className = \"\",\n  cardClassName = \"\",\n}: StackedCardSliderProps) {\n  const boxRef = useRef<HTMLDivElement>(null);\n  const cardRefs = useRef<(HTMLImageElement | null)[]>([]);\n  const leavingRef = useRef<HTMLImageElement>(null);\n  const [view, setView] = useState<View>({ front: 0, leaving: null });\n  // The step that was asked for and is waiting for React to move the cards\n  const pending = useRef<Pending | null>(null);\n  const busy = useRef(false);\n  // Read when a step starts, so a new duration or ease needs no rebuild\n  const settings = useRef({ duration, ease, onChange });\n  settings.current = { duration, ease, onChange };\n  const touchStart = useRef<{ x: number; y: number } | null>(null);\n  const swiped = useRef(false);\n\n  const count = cards.length;\n  // If the list changes length, start again from the first card\n  const front = count === 0 ? 0 : view.front % count;\n  const shown = Math.max(1, Math.min(count, Math.round(visibleCards)));\n  const total = offsetStep * (shown - 1);\n  const cardHeight = `calc(var(--stack-card-width) / ${aspectRatio})`;\n\n  const { contextSafe } = useGSAP(\n    () => {\n      busy.current = false;\n      return () => {\n        busy.current = false;\n        pending.current = null;\n      };\n    },\n    { scope: boxRef },\n  );\n\n  // Runs right after React has moved the cards to their new spots\n  useGSAP(\n    () => {\n      const job = pending.current;\n      if (!job) return;\n      pending.current = null;\n\n      const els = cardRefs.current.slice(0, count).filter((el): el is HTMLImageElement => el !== null);\n      const { duration: time, ease: curve } = settings.current;\n      const finish = () => {\n        busy.current = false;\n      };\n\n      // The card flying away leaves toward the bottom left and fades out\n      if (leavingRef.current) {\n        gsap.to(leavingRef.current, {\n          xPercent: -20,\n          yPercent: 20,\n          opacity: 0,\n          transformOrigin: \"bottom left\",\n          duration: time,\n          ease: \"expo.out\",\n          onComplete: () => setView((current) => ({ ...current, leaving: null })),\n        });\n      }\n\n      Flip.from(job.state, {\n        targets: els,\n        // The cards never change size, so move them with transforms only\n        scale: true,\n        duration: time,\n        ease: curve,\n        // The one card that was not measured before the step is the one that arrives\n        onEnter: (entering) =>\n          gsap.from(entering, job.step === 1 ? { yPercent: 20, opacity: 0, duration: time, ease: \"expo.out\" } : { xPercent: -20, yPercent: 20, opacity: 0, transformOrigin: \"bottom left\", duration: time, ease: \"expo.out\" }),\n        onComplete: finish,\n        onInterrupt: finish,\n      });\n    },\n    { scope: boxRef, dependencies: [view.front] },\n  );\n\n  const go = contextSafe((step: 1 | -1) => {\n    if (busy.current || count < 2) return;\n    const next = (front + step + count) % count;\n    const reduced = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    settings.current.onChange?.(next);\n    if (reduced) {\n      setView({ front: next, leaving: null });\n      return;\n    }\n    busy.current = true;\n    const els = cardRefs.current.slice(0, count);\n    // The card that arrives has no \"before\", so it is left out of the measurement\n    const arriving = step === 1 ? front : next;\n    const measured = els.filter((el, index): el is HTMLImageElement => el !== null && index !== arriving);\n    pending.current = { state: Flip.getState(measured, { props: \"opacity,filter\" }), step };\n    setView({ front: next, leaving: step === 1 ? front : null });\n  });\n\n  const onKeyDown = (event: React.KeyboardEvent) => {\n    if (event.key === \"ArrowRight\" || event.key === \"ArrowDown\") {\n      event.preventDefault();\n      go(1);\n    } else if (event.key === \"ArrowLeft\" || event.key === \"ArrowUp\") {\n      event.preventDefault();\n      go(-1);\n    }\n  };\n\n  // A swipe goes forward (to the left) or back (to the right); a plain tap is a click\n  const onPointerDown = (event: React.PointerEvent) => {\n    touchStart.current = { x: event.clientX, y: event.clientY };\n    swiped.current = false;\n  };\n  const onPointerUp = (event: React.PointerEvent) => {\n    const start = touchStart.current;\n    touchStart.current = null;\n    if (!start) return;\n    const dx = event.clientX - start.x;\n    const dy = event.clientY - start.y;\n    if (Math.abs(dx) > 40 && Math.abs(dx) > Math.abs(dy)) {\n      swiped.current = true;\n      go(dx < 0 ? 1 : -1);\n    }\n  };\n  const onClick = (event: React.MouseEvent) => {\n    if (swiped.current) {\n      swiped.current = false;\n      return;\n    }\n    go(event.shiftKey ? -1 : 1);\n  };\n\n  const spot = (rank: number) => {\n    const slot = Math.min(rank, shown - 1);\n    return { left: slot * offsetStep, top: total - slot * offsetStep };\n  };\n\n  const imageStyle = {\n    width: \"var(--stack-card-width)\",\n    height: cardHeight,\n    borderRadius: radius,\n  } as const;\n\n  return (\n    <div\n      ref={boxRef}\n      className={`flex h-full w-full items-center justify-center ${className}`}\n      style={{\n        // The card shrinks to fit the box both ways, so the whole stack always stays on screen\n        containerType: \"size\",\n        [\"--stack-card-width\" as string]: `min(${cardWidth}px, calc(100cqw - ${total + 32}px), calc((100cqh - ${total + 32}px) * ${aspectRatio}))`,\n      }}\n    >\n      <button\n        type=\"button\"\n        aria-label=\"Next card\"\n        onClick={onClick}\n        onKeyDown={onKeyDown}\n        onPointerDown={onPointerDown}\n        onPointerUp={onPointerUp}\n        onPointerCancel={() => (touchStart.current = null)}\n        className=\"relative block shrink-0 cursor-pointer select-none rounded-[10px] border-0 bg-transparent p-0 outline-offset-[14px] focus-visible:outline-2 focus-visible:outline-current\"\n        style={{ width: `calc(var(--stack-card-width) + ${total}px)`, height: `calc(${cardHeight} + ${total}px)`, touchAction: \"pan-y\", WebkitTapHighlightColor: \"transparent\" }}\n      >\n        {cards.map((card, index) => {\n          const rank = (index - front + count) % count;\n          const visible = rank < shown;\n          return (\n            <img\n              key={index}\n              ref={(el) => {\n                cardRefs.current[index] = el;\n              }}\n              src={card.image}\n              alt={card.alt ?? `Card ${index + 1}`}\n              aria-hidden={rank === 0 ? undefined : true}\n              draggable={false}\n              decoding=\"async\"\n              className={`pointer-events-none absolute block object-cover object-top shadow-[0_0_0_1px_rgba(0,0,0,0.18),0_22px_44px_-18px_rgba(0,0,0,0.55)] ${cardClassName}`}\n              style={{\n                ...imageStyle,\n                ...spot(rank),\n                zIndex: count - rank,\n                opacity: visible ? 1 : 0,\n                filter: `brightness(${1 - Math.min(rank, shown - 1) * 0.07})`,\n                willChange: \"transform, opacity\",\n              }}\n            />\n          );\n        })}\n        {view.leaving !== null && cards[view.leaving] ? (\n          <img\n            ref={leavingRef}\n            src={cards[view.leaving]!.image}\n            alt=\"\"\n            aria-hidden=\"true\"\n            draggable={false}\n            className={`pointer-events-none absolute block object-cover object-top shadow-[0_0_0_1px_rgba(0,0,0,0.18),0_22px_44px_-18px_rgba(0,0,0,0.55)] ${cardClassName}`}\n            style={{ ...imageStyle, ...spot(0), zIndex: count + 1, willChange: \"transform, opacity\" }}\n          />\n        ) : null}\n      </button>\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {cards[front] ? `${cards[front]!.alt ?? `Card ${front + 1}`}, card ${front + 1} of ${count}` : \"\"}\n      </span>\n    </div>\n  );\n}\n"}],"categories":["cards","gsap","flip","stack","slider","images"],"docs":"import { StackedCardSlider } from \"@/components/dimaac/stacked-card-slider\". Give its parent a size: it fills it. Docs, playground and props: https://ui.dimaac.com/components/stacked-card-slider","meta":{"tier":"free","preview":"https://ui.dimaac.com/components/stacked-card-slider","credits":[{"by":"Amino","url":"https://www.lummi.ai/photo/vivid-portrait-on-pink-oxbow","what":"Portrait (lime blazer)","source":"Lummi","licence":"Lummi License"},{"by":"Shaun Duval","url":"https://www.lummi.ai/photo/portrait-with-neon-sunglasses-gindg","what":"Portrait (neon profile)","source":"Lummi","licence":"Lummi License"},{"by":"studiomiklus","url":"https://www.lummi.ai/photo/striking-portrait-jodiu","what":"Portrait (platinum blonde)","source":"Lummi","licence":"Lummi License"},{"by":"Lloyd Creates","url":"https://www.lummi.ai/photo/poised-portrait-ooi9b","what":"Portrait (red coat)","source":"Lummi","licence":"Lummi License"},{"by":"SHIHO","url":"https://www.lummi.ai/photo/vibrant-woman-portrait-htofy","what":"Portrait (tinted glasses)","source":"Lummi","licence":"Lummi License"},{"by":"West Kast","url":"https://www.lummi.ai/photo/fashion-portrait-with-orange-visor-damql","what":"Fashion portrait (orange visor)","source":"Lummi","licence":"Lummi License"},{"by":"Steph Meade","url":"https://www.lummi.ai/photo/expressive-minimal-portrait-jrfyc","what":"Portrait (face paint)","source":"Lummi","licence":"Lummi License"}]}}