{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "skewed-carousel",
  "title": "Skewed Carousel",
  "description": "A carousel of cards that turn away in 3D as they slide, with spring motion, swipe, dots and arrow keys. No dependencies.",
  "files": [
    {
      "path": "registry/mewo/ui/skewed-carousel.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { cn } from \"@/lib/utils\"\n\nexport interface SkewedCarouselItem {\n  /** Image URL. */\n  image: string\n  /** Caption under the active slide, and the slide's accessible name. */\n  title: string\n  /** Image description for screen readers. Defaults to the title. */\n  alt?: string\n}\n\nexport interface SkewedCarouselProps extends Omit<React.ComponentProps<\"div\">, \"children\"> {\n  /** Slides, in order. */\n  items?: SkewedCarouselItem[]\n  /** Slide focused on mount. */\n  initialIndex?: number\n  /** Slide width in pixels. */\n  cardWidth?: number\n  /** Aspect ratio of each slide, as CSS `aspect-ratio`. */\n  aspectRatio?: string\n  /** Degrees each slide turns per step away from the active one. */\n  rotation?: number\n  /** Scale of every inactive slide. */\n  inactiveScale?: number\n  /** Perspective of each slide, in pixels. */\n  perspective?: number\n  /** Corner radius of the slides, in pixels. */\n  borderRadius?: number\n  /** Blur on inactive captions, in pixels. */\n  titleBlur?: number\n  /** Multiplier on the transition duration. 2 is twice as slow. */\n  speed?: number\n  /** Show the caption on the active slide. */\n  showTitles?: boolean\n  /** Show the previous and next buttons. */\n  showControls?: boolean\n  /** Show the progress dots. */\n  showDots?: boolean\n  /** Wrap around at either end. */\n  loop?: boolean\n  /** Advance on a timer. It holds while the pointer or keyboard focus is on the carousel, and off screen. */\n  autoplay?: boolean\n  /** Delay between automatic advances, in milliseconds. */\n  autoplayDelay?: number\n  /** A sideways drag of 45px or more moves one slide. */\n  enableDrag?: boolean\n  /** Left and right arrow keys move one slide while the carousel has focus. */\n  enableKeyboard?: boolean\n  /** Called with the active slide's index whenever it changes. */\n  onIndexChange?: (index: number) => void\n}\n\nexport const DEFAULT_ITEMS: SkewedCarouselItem[] = [\n  \"Northern Light\",\n  \"Paper Cranes\",\n  \"Quiet Harbour\",\n  \"Glass Garden\",\n  \"Late Train\",\n  \"Salt Flats\",\n  \"Copper Hills\",\n  \"Night Market\",\n  \"Still Water\",\n  \"Long Shadow\",\n].map((title, index) => ({ title, image: `https://cataas.com/cat/${[\"dBaJIho0PvGiwVsm\", \"BswnFbCjndW2X9oO\", \"EMgyHa7PjTe3j9SE\", \"IN8bFy4SO9xHp4ib\", \"YHCa57fmqzJfBODT\", \"1si02A2ZNdeNH3yo\", \"37guCJ2aCCt3m360\", \"C5Ddbc1ilh45jiAk\", \"HTjBKfHqCZn9lkRt\", \"FAkFJCfYbZOF8aDI\"][index]}` }))\n\n// Springs, in rad/s at speed 1 and as a damping ratio. The strip overshoots a little, the slides barely.\nconst STRIP_SPRING = { omega: 11.25, zeta: 0.8 }\nconst SLIDE_SPRING = { omega: 8.5, zeta: 0.9 }\nconst DOT_SPRING = { omega: 20, zeta: 0.75 }\n// A drag this long in pixels moves one slide, whatever the card width. The strip does not follow the pointer.\nconst SWIPE_DISTANCE = 45\n// Inactive captions wait this many pixels below their place and rise as their slide arrives.\nconst CAPTION_DROP = 10\nconst DOT_GAP = 6\n// Springs are integrated in fixed substeps so a slow frame does not change their shape.\nconst SUBSTEP = 1 / 240\n\ntype Spring = { x: number; v: number; target: number }\nconst spring = (x: number): Spring => ({ x, v: 0, target: x })\n\nconst clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value))\n\n/** Advances a damped spring by `dt` seconds. */\nexport function stepSpring(s: Spring, omega: number, zeta: number, dt: number) {\n  for (let t = 0; t < dt - 1e-9; t += SUBSTEP) {\n    const h = Math.min(SUBSTEP, dt - t)\n    s.v += (omega * omega * (s.target - s.x) - 2 * zeta * omega * s.v) * h\n    s.x += s.v * h\n  }\n}\n\n/** Where a slide rests `offset` slides away from the active one: its turn, scale and caption drop. */\nexport function slidePose(offset: number, rotation: number, inactiveScale: number) {\n  return {\n    rotate: -offset * rotation,\n    scale: offset === 0 ? 1 : inactiveScale,\n    captionY: offset === 0 ? 0 : CAPTION_DROP,\n  }\n}\n\n/** The slide a move to `index` lands on: wrapped when looping, held at the ends otherwise. */\nexport function landingIndex(index: number, count: number, loop: boolean) {\n  if (count <= 0) return 0\n  return loop ? ((index % count) + count) % count : clamp(index, 0, count - 1)\n}\n\nconst settled = (s: Spring, eps: number) => Math.abs(s.target - s.x) < eps && Math.abs(s.v) < eps * 10\n\nfunction Chevron({ direction }: { direction: \"left\" | \"right\" }) {\n  return (\n    <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.25\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n      <polyline points={direction === \"left\" ? \"15 18 9 12 15 6\" : \"9 18 15 12 9 6\"} />\n    </svg>\n  )\n}\n\nexport function SkewedCarousel({\n  items = DEFAULT_ITEMS,\n  initialIndex = 3,\n  cardWidth = 200,\n  aspectRatio = \"3 / 4\",\n  rotation = 60,\n  inactiveScale = 0.85,\n  perspective = 800,\n  borderRadius = 8,\n  titleBlur = 2,\n  speed = 1,\n  showTitles = true,\n  showControls = true,\n  showDots = true,\n  loop = false,\n  autoplay = false,\n  autoplayDelay = 3000,\n  enableDrag = true,\n  enableKeyboard = true,\n  onIndexChange,\n  className,\n  onKeyDown,\n  onPointerEnter,\n  onPointerLeave,\n  onFocus,\n  onBlur,\n  ...props\n}: SkewedCarouselProps) {\n  const count = items.length\n  const [index, setIndex] = React.useState(() => landingIndex(initialIndex, count, false))\n  const active = landingIndex(index, count, false)\n\n  const stripRef = React.useRef<HTMLDivElement>(null)\n  const cardRefs = React.useRef<(HTMLDivElement | null)[]>([])\n  const captionRefs = React.useRef<(HTMLSpanElement | null)[]>([])\n  const indicatorRef = React.useRef<HTMLSpanElement>(null)\n  const onIndexChangeRef = React.useRef(onIndexChange)\n  // On mount the strip starts at the first slide with every card flat, then springs to the initial slide.\n  const motionRef = React.useRef({\n    raf: 0,\n    last: 0,\n    wake: () => {},\n    speed,\n    strip: spring(0),\n    dot: spring(active),\n    slides: [] as { rotate: Spring; scale: Spring; captionY: Spring }[],\n  })\n\n  React.useEffect(() => {\n    onIndexChangeRef.current = onIndexChange\n    motionRef.current.speed = speed\n  })\n\n  const draw = React.useCallback(() => {\n    const m = motionRef.current\n    if (stripRef.current) stripRef.current.style.transform = Math.abs(m.strip.x) < 1e-3 ? \"\" : `translateX(${m.strip.x.toFixed(3)}px)`\n    m.slides.forEach((s, i) => {\n      const card = cardRefs.current[i]\n      if (card) {\n        const flat = Math.abs(s.rotate.x) < 1e-3 && Math.abs(s.scale.x - 1) < 1e-4\n        card.style.transform = flat ? \"\" : `scale(${s.scale.x.toFixed(5)}) rotateY(${s.rotate.x.toFixed(4)}deg)`\n      }\n      const caption = captionRefs.current[i]\n      if (caption) caption.style.transform = Math.abs(s.captionY.x) < 1e-3 ? \"\" : `translateY(${s.captionY.x.toFixed(4)}px)`\n    })\n    if (indicatorRef.current) indicatorRef.current.style.transform = `translateX(calc(${m.dot.x.toFixed(5)} * (100% + ${DOT_GAP}px)))`\n  }, [])\n\n  // The frame loop lives in one effect; prop changes only move the springs' targets and call wake().\n  React.useLayoutEffect(() => {\n    const m = motionRef.current\n    const tick = (now: number) => {\n      // dt is clamped so a hitch or a tab switch does not jump the springs.\n      const dt = clamp((now - m.last) / 1000, 1 / 240, 0.05)\n      m.last = now\n      const k = 1 / Math.max(0.05, m.speed)\n      const springs = [m.strip, m.dot, ...m.slides.flatMap((s) => [s.rotate, s.scale, s.captionY])]\n      stepSpring(m.strip, STRIP_SPRING.omega * k, STRIP_SPRING.zeta, dt)\n      stepSpring(m.dot, DOT_SPRING.omega * k, DOT_SPRING.zeta, dt)\n      for (const s of m.slides) for (const sp of [s.rotate, s.scale, s.captionY]) stepSpring(sp, SLIDE_SPRING.omega * k, SLIDE_SPRING.zeta, dt)\n      let moving = !settled(m.strip, 0.01) || !settled(m.dot, 1e-4)\n      for (const s of m.slides) if (!settled(s.rotate, 0.005) || !settled(s.scale, 1e-5) || !settled(s.captionY, 0.005)) moving = true\n      if (!moving) for (const sp of springs) Object.assign(sp, { x: sp.target, v: 0 })\n      draw()\n      // The loop ends as soon as everything has settled; a carousel at rest costs nothing.\n      m.raf = moving ? requestAnimationFrame(tick) : 0\n    }\n    m.wake = () => {\n      if (m.raf) return\n      // The first step covers a full frame, so the move starts the moment the slide changes.\n      m.last = performance.now() - 1000 / 60\n      m.raf = requestAnimationFrame(tick)\n    }\n    return () => {\n      cancelAnimationFrame(m.raf)\n      m.raf = 0\n      m.wake = () => {}\n    }\n  }, [draw])\n\n  // A new slide or setting only moves the springs' targets and wakes the loop.\n  React.useLayoutEffect(() => {\n    const m = motionRef.current\n    while (m.slides.length < count) m.slides.push({ rotate: spring(0), scale: spring(1), captionY: spring(0) })\n    m.slides.length = count\n    m.strip.target = -active * cardWidth\n    m.dot.target = active\n    m.slides.forEach((s, i) => {\n      const pose = slidePose(i - active, rotation, inactiveScale)\n      s.rotate.target = pose.rotate\n      s.scale.target = pose.scale\n      s.captionY.target = pose.captionY\n    })\n    const reduced = window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches ?? false\n    if (reduced) {\n      for (const sp of [m.strip, m.dot, ...m.slides.flatMap((s) => [s.rotate, s.scale, s.captionY])]) Object.assign(sp, { x: sp.target, v: 0 })\n      draw()\n      return\n    }\n    draw()\n    m.wake()\n  }, [active, count, cardWidth, rotation, inactiveScale, showTitles, showDots, draw])\n\n  const reported = React.useRef(active)\n  React.useEffect(() => {\n    if (reported.current === active) return\n    reported.current = active\n    onIndexChangeRef.current?.(active)\n  }, [active])\n\n  const goTo = React.useCallback((target: number) => setIndex(landingIndex(target, count, loop)), [count, loop])\n  const canPrevious = loop || active > 0\n  const canNext = loop || active < count - 1\n\n  // Autoplay holds while the pointer or keyboard focus is on the carousel, off screen, and in a hidden tab.\n  const [hold, setHold] = React.useState({ hover: false, focus: false, away: false })\n  React.useEffect(() => {\n    const root = stripRef.current?.closest<HTMLElement>('[data-slot=\"skewed-carousel\"]')\n    if (!root || !autoplay) return\n    const onVisibility = () => setHold((h) => ({ ...h, away: document.hidden }))\n    const observer = new IntersectionObserver(([entry]) => setHold((h) => ({ ...h, away: !entry.isIntersecting || document.hidden })))\n    observer.observe(root)\n    document.addEventListener(\"visibilitychange\", onVisibility)\n    return () => {\n      observer.disconnect()\n      document.removeEventListener(\"visibilitychange\", onVisibility)\n    }\n  }, [autoplay])\n  const held = hold.hover || hold.focus || hold.away\n  React.useEffect(() => {\n    if (!autoplay || held || !canNext || count < 2) return\n    // The timer restarts after every change, so a manual move never jumps straight on.\n    const id = window.setTimeout(() => goTo(active + 1), Math.max(200, autoplayDelay))\n    return () => window.clearTimeout(id)\n  }, [autoplay, held, canNext, count, autoplayDelay, active, goTo])\n\n  // Drag: nothing follows the pointer; on release a long enough swipe moves one slide.\n  const dragRef = React.useRef<{ id: number; x: number; captured: boolean } | null>(null)\n  const swallowClick = React.useRef(false)\n\n  const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {\n    if (!enableDrag || (event.pointerType === \"mouse\" && event.button !== 0)) return\n    dragRef.current = { id: event.pointerId, x: event.clientX, captured: false }\n    swallowClick.current = false\n  }\n  const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {\n    const drag = dragRef.current\n    if (!drag || drag.id !== event.pointerId || drag.captured) return\n    // Capture only once it is clearly a drag, so a plain click still reaches the card under it.\n    if (Math.abs(event.clientX - drag.x) > 5) {\n      drag.captured = true\n      event.currentTarget.setPointerCapture?.(event.pointerId)\n    }\n  }\n  const onPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {\n    const drag = dragRef.current\n    if (!drag || drag.id !== event.pointerId) return\n    dragRef.current = null\n    const dx = event.clientX - drag.x\n    if (Math.abs(dx) > 5) swallowClick.current = true\n    if (Math.abs(dx) >= SWIPE_DISTANCE) goTo(active + (dx < 0 ? 1 : -1))\n  }\n\n  const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    onKeyDown?.(event)\n    if (!enableKeyboard || event.defaultPrevented || event.target !== event.currentTarget) return\n    const direction = event.key === \"ArrowRight\" ? 1 : event.key === \"ArrowLeft\" ? -1 : 0\n    if (direction === 0) return\n    event.preventDefault()\n    goTo(active + direction)\n  }\n\n  return (\n    <div\n      data-slot=\"skewed-carousel\"\n      role=\"group\"\n      aria-roledescription=\"carousel\"\n      aria-label=\"Image carousel\"\n      tabIndex={0}\n      className={cn(\n        \"relative flex w-full flex-col items-center overflow-hidden text-foreground outline-none select-none focus-visible:outline-2 focus-visible:outline-ring\",\n        className\n      )}\n      onKeyDown={handleKeyDown}\n      onPointerEnter={(event) => {\n        onPointerEnter?.(event)\n        if (event.pointerType === \"mouse\") setHold((h) => ({ ...h, hover: true }))\n      }}\n      onPointerLeave={(event) => {\n        onPointerLeave?.(event)\n        if (event.pointerType === \"mouse\") setHold((h) => ({ ...h, hover: false }))\n      }}\n      onFocus={(event) => {\n        onFocus?.(event)\n        setHold((h) => ({ ...h, focus: event.target.matches(\":focus-visible\") }))\n      }}\n      onBlur={(event) => {\n        onBlur?.(event)\n        if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setHold((h) => ({ ...h, focus: false }))\n      }}\n      {...props}\n    >\n      <div style={{ width: cardWidth }}>\n        <div\n          ref={stripRef}\n          className=\"flex w-fit touch-pan-y\"\n          onPointerDown={onPointerDown}\n          onPointerMove={onPointerMove}\n          onPointerUp={onPointerUp}\n          onPointerCancel={() => {\n            dragRef.current = null\n          }}\n          onClickCapture={(event) => {\n            if (!swallowClick.current) return\n            swallowClick.current = false\n            event.stopPropagation()\n            event.preventDefault()\n          }}\n        >\n          {items.map((item, i) => {\n            const isActive = i === active\n            return (\n              <div key={i} style={{ perspective }} aria-hidden={isActive ? undefined : true}>\n                <div\n                  ref={(el) => {\n                    cardRefs.current[i] = el\n                  }}\n                  data-slot=\"skewed-carousel-card\"\n                  className=\"will-change-transform\"\n                  style={{ width: cardWidth, aspectRatio }}\n                >\n                  <button\n                    type=\"button\"\n                    className=\"relative block size-full cursor-pointer overflow-hidden border-0 bg-transparent p-0 outline-none focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-current\"\n                    style={{ borderRadius }}\n                    tabIndex={isActive ? 0 : -1}\n                    aria-label={item.title}\n                    aria-current={isActive}\n                    onClick={() => goTo(i)}\n                  >\n                    <img className=\"block size-full object-cover [-webkit-user-drag:none]\" src={item.image} alt={item.alt ?? item.title} draggable={false} />\n                    {showTitles && (\n                      <>\n                        <span\n                          className=\"pointer-events-none absolute inset-x-0 bottom-0 h-2/5 bg-linear-to-t from-black/80 via-black/30 to-transparent\"\n                          style={{ opacity: isActive ? 1 : 0 }}\n                        />\n                        <span\n                          ref={(el) => {\n                            captionRefs.current[i] = el\n                          }}\n                          className=\"pointer-events-none absolute inset-x-0 bottom-0 block px-3.5 pb-3 text-left text-sm leading-snug font-medium tracking-[-0.01em] text-white [text-shadow:0_1px_2px_rgb(0_0_0/0.35)]\"\n                          style={{ opacity: isActive ? 1 : 0, filter: isActive ? undefined : `blur(${titleBlur}px)` }}\n                        >\n                          {item.title}\n                        </span>\n                      </>\n                    )}\n                  </button>\n                </div>\n              </div>\n            )\n          })}\n        </div>\n      </div>\n\n      {(showControls || showDots) && (\n        <div className=\"mt-9 flex items-center gap-4\">\n          {showControls && (\n            <button\n              type=\"button\"\n              aria-label=\"Previous slide\"\n              disabled={!canPrevious}\n              onClick={() => goTo(active - 1)}\n              className=\"grid cursor-pointer place-items-center rounded p-1 opacity-40 transition-opacity duration-200 hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-current disabled:pointer-events-none disabled:opacity-15\"\n            >\n              <Chevron direction=\"left\" />\n            </button>\n          )}\n          {showDots && (\n            <div className=\"relative flex w-44 items-center gap-1.5 sm:w-56\">\n              {items.map((item, i) => (\n                <button\n                  key={i}\n                  type=\"button\"\n                  aria-label={`Show ${item.title}`}\n                  aria-current={i === active}\n                  onClick={() => goTo(i)}\n                  className=\"relative h-0.5 flex-1 cursor-pointer rounded-full bg-current/20 transition-colors duration-200 before:absolute before:inset-x-0 before:-inset-y-2.5 before:content-[''] hover:bg-current/45 focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-current\"\n                />\n              ))}\n              <span\n                ref={indicatorRef}\n                aria-hidden\n                className=\"pointer-events-none absolute top-1/2 left-0 -mt-px h-0.5 rounded-full bg-current\"\n                style={{ width: `calc((100% - ${Math.max(0, count - 1)} * ${DOT_GAP}px) / ${Math.max(1, count)})` }}\n              />\n            </div>\n          )}\n          {showControls && (\n            <button\n              type=\"button\"\n              aria-label=\"Next slide\"\n              disabled={!canNext}\n              onClick={() => goTo(active + 1)}\n              className=\"grid cursor-pointer place-items-center rounded p-1 opacity-40 transition-opacity duration-200 hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-current disabled:pointer-events-none disabled:opacity-15\"\n            >\n              <Chevron direction=\"right\" />\n            </button>\n          )}\n        </div>\n      )}\n\n      <span className=\"sr-only\" aria-live={autoplay && !held ? \"off\" : \"polite\"}>\n        {count ? `Slide ${active + 1} of ${count}: ${items[active].title}` : \"\"}\n      </span>\n    </div>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "meta": {
    "added": "2026-10-28"
  },
  "categories": [
    "card"
  ],
  "type": "registry:ui"
}