{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "concave-carousel",
  "title": "Concave Carousel",
  "description": "A gallery wall that curves around the viewer in CSS 3D, with a slow drift, spring snapping, drag and flick, the wheel, captions and a floor reflection. No dependencies.",
  "files": [
    {
      "path": "registry/mewo/ui/concave-carousel.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { cn } from \"@/lib/utils\"\n\nexport interface ConcaveCarouselItem {\n  /** Image URL. It is cropped to fill its panel, like `object-fit: cover`. */\n  src: string\n  /** Image description for screen readers. */\n  alt: string\n  /** First caption line, under the panel. Also names the panel for screen readers. */\n  title?: string\n  /** Second caption line. */\n  subtitle?: string\n  /** Clicking the centred image, or pressing Enter, navigates here. */\n  href?: string\n}\n\n/** What `controlsRef` receives. */\nexport interface ConcaveCarouselControls {\n  /** Turn the wall one panel forward. */\n  next: () => void\n  /** Turn the wall one panel back. */\n  previous: () => void\n  /** Turn the wall the short way round to the panel at `index`. */\n  goTo: (index: number) => void\n}\n\nexport interface ConcaveCarouselProps extends Omit<React.ComponentProps<\"div\">, \"children\" | \"onSelect\" | \"draggable\"> {\n  /** Images hung around the wall, in order. */\n  items?: ConcaveCarouselItem[]\n  /** Index of the image that starts in the centre. */\n  startIndex?: number\n  /** Width / height of every panel. Images are cropped to fill it. */\n  aspect?: number\n  /** Height of the centred panel as a fraction of the space above the caption. */\n  size?: number\n  /** How strongly the wall bends around the viewer: 0 is a flat strip, 1 a tight drum. */\n  curvature?: number\n  /** Viewer distance from the wall, in panel heights. */\n  distance?: number\n  /** Viewing angle in degrees. Negative looks up at the wall, positive looks down at the floor. */\n  tilt?: number\n  /** Space between panels in pixels, at the centred panel. */\n  gap?: number\n  /** Corner radius in pixels, at the centred panel. */\n  radius?: number\n  /** Opacity of the floor reflection. 0 removes it. */\n  reflection?: number\n  /** How much the wall fades toward the left and right edges, 0 to 1. */\n  dim?: number\n  /** drift: turn slowly and continuously. step: one panel every `interval`. off: stay still. */\n  autoplay?: \"drift\" | \"step\" | \"off\"\n  /** Drift speed in panels per second. Negative turns the other way (also for step). */\n  speed?: number\n  /** Seconds between steps when autoplay is \"step\". */\n  interval?: number\n  /** Settle with a panel centred after a drag, flick or scroll. */\n  snap?: boolean\n  /** How far a flick carries the wall, 0 to 1. */\n  inertia?: number\n  /** Brake the motion while the pointer rests on the wall. */\n  pauseOnHover?: boolean\n  /** Drag or flick the wall to turn it. */\n  draggable?: boolean\n  /** Scroll to turn the wall, one panel per notch. */\n  wheel?: boolean\n  /** Show each panel's title and subtitle under it. */\n  captions?: boolean\n  /** Previous and next buttons with a counter. */\n  controls?: boolean\n  /** Any CSS background for the root. Leave it unset for a transparent root. */\n  backgroundColor?: string\n  /** Stops autoplay. Space toggles it too. */\n  paused?: boolean\n  /** Called with the centred image's index whenever it changes. */\n  onIndexChange?: (index: number) => void\n  /** The centred image was clicked, or Enter was pressed. */\n  onSelect?: (item: ConcaveCarouselItem, index: number) => void\n  /** Receives `next`, `previous` and `goTo`. The root's own `ref` stays the consumer's. */\n  controlsRef?: React.Ref<ConcaveCarouselControls>\n}\n\nexport const DEFAULT_ITEMS: ConcaveCarouselItem[] = [\n  [\"Harbour Light\", \"Morning on the water\"],\n  [\"Paper Lanterns\", \"A street after rain\"],\n  [\"Quiet Ridge\", \"Above the tree line\"],\n  [\"Salt Road\", \"Flat white for miles\"],\n  [\"Glass House\", \"Green behind every pane\"],\n  [\"Night Ferry\", \"The last crossing\"],\n  [\"Copper Field\", \"Late summer, low sun\"],\n  [\"Still Water\", \"A lake with no wind\"],\n].map(([title, subtitle], index) => ({\n  src: `https://cataas.com/cat/${[\"afcjk0kZwJsapLu4\", \"4zJgFagrJcsYIDks\", \"VYLBb86IBQNRMCa9\", \"OK7AhogAWT9naJqJ\", \"1LlIgMhb3DfoW4qw\", \"nBsZd23B3uqH6AGy\", \"kPvP0fDe61Q2ujXV\", \"nu2fL4UsGVlbTn8U\"][index]}`,\n  alt: \"Placeholder photograph\",\n  title,\n  subtitle,\n}))\n\nconst DEFAULT_LABEL = \"Curved gallery. Drag, scroll or use the arrow keys to turn it. Space pauses the motion.\"\nconst REDUCED_MOTION = \"(prefers-reduced-motion: reduce)\"\n\n// Each panel is drawn as vertical strips so it bends along the wall.\nconst STRIPS = 8\n// Neighbouring strips overlap by this many pixels, which hides the seams between them.\nconst STRIP_OVERLAP = 0.8\n// Snap spring: about 610ms to settle, about 1% overshoot.\nconst SPRING_K = 53.3\nconst SPRING_C = 12.4\n// The spring is integrated in fixed substeps so a slow frame does not change its shape.\nconst SUBSTEP = 1 / 240\n// Drift brakes and picks up again with these time constants, in seconds.\nconst BRAKE_TAU = 0.35\nconst ACCEL_TAU = 0.8\n// Input holds the drift (and the next step) this long, in milliseconds; leaving the wall after a hover holds it this long.\nconst RESUME_AFTER_INPUT = 2400\nconst RESUME_AFTER_HOVER = 600\n// Seconds of coasting per unit of inertia.\nconst COAST_TIME = 0.9\n// Pixels of wheel delta per panel.\nconst WHEEL_STEP = 50\n// Pixels a press travels before it becomes a drag.\nconst DRAG_THRESHOLD = 4\n// Wall radius at curvature 1, in panel widths: radius = 1.16 × width ÷ curvature.\nconst CURVE_RADIUS = 1.16\n// Viewer distance in centred-panel heights is VIEW_SLOPE × distance + VIEW_OFFSET.\n// Distance 4 puts the viewer 4.17 heights away, distance 6 puts it 5.92 away.\nconst VIEW_SLOPE = 0.875\nconst VIEW_OFFSET = 0.67\n// Pixels kept free under the wall for the captions and for the controls.\nconst CAPTION_RESERVE = 64\nconst CONTROLS_RESERVE = 59\n// A caption sits this far under its panel's bottom edge, in centred-panel heights.\nconst CAPTION_OFFSET = 0.145\n// The reflection starts this far under the panel, in panel heights, and this fraction of it fades in.\nconst REFLECT_GAP = 0.07\nconst REFLECT_LENGTH = 0.45\n// Each frame's step is clamped to this range in seconds, so a hitch or a tab switch cannot fling the wall.\nconst MIN_DT = 1 / 240\nconst MAX_DT = 0.05\n\ntype Mode = \"drift\" | \"spring\" | \"drag\" | \"coast\"\n\ntype Live = {\n  autoplay: \"drift\" | \"step\" | \"off\"\n  speed: number\n  interval: number\n  paused: boolean\n  reduced: boolean\n  pauseOnHover: boolean\n  snap: boolean\n  inertia: number\n  tilt: number\n  gap: number\n  captions: boolean\n  items: ConcaveCarouselItem[]\n  onIndexChange?: (index: number) => void\n  onSelect?: (item: ConcaveCarouselItem, index: number) => void\n}\n\nconst mod = (a: number, n: number) => ((a % n) + n) % n\nconst clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value))\nconst smoothstep = (e0: number, e1: number, x: number) => {\n  const t = clamp((x - e0) / (e1 - e0), 0, 1)\n  return t * t * (3 - 2 * t)\n}\nconst pad = (value: number) => String(value).padStart(2, \"0\")\n\n/** Wraps a slot's distance to the wall's position, in panels, into the loop [-slots / 2, slots / 2). */\nexport function wrapOffset(value: number, slots: number) {\n  if (slots <= 0) return 0\n  return mod(value + slots / 2, slots) - slots / 2\n}\n\n/** Whether a panel at wall angle `theta` can be seen: in front of the viewer, facing them, and on screen. */\nexport function facesViewer(theta: number, wallRadius: number, perspective: number, viewWidth: number, panelWidth: number) {\n  if (Math.abs(theta) > Math.PI * 0.9) return false\n  const x = wallRadius * Math.sin(theta)\n  const z = wallRadius * (1 - Math.cos(theta))\n  if (z > perspective * 0.92) return false\n  // Its face points away from the viewer.\n  if (wallRadius + (perspective - wallRadius) * Math.cos(theta) <= 0) return false\n  return Math.abs((perspective * x) / (perspective - z)) < viewWidth / 2 + panelWidth\n}\n\n/**\n * The wall for a root of `width` × `height` pixels. Lengths are in pixels: `A` is the space above the caption,\n * `h` and `w` the centred panel, `R` the wall radius, `alpha` the wall angle per panel, `p` the viewer distance\n * (the CSS perspective), `cy` the wall's vertical centre, `sw` a strip's width, `strips` each strip's transform\n * inside its panel. `slots` is how many panels are hung: the items repeat until the point where the wall wraps\n * round is safely out of view.\n */\nexport function wallGeometry({\n  width,\n  height,\n  count,\n  size,\n  aspect,\n  curvature,\n  gap,\n  distance,\n  captions,\n  controls,\n}: {\n  width: number\n  height: number\n  count: number\n  size: number\n  aspect: number\n  curvature: number\n  gap: number\n  distance: number\n  captions: boolean\n  controls: boolean\n}) {\n  const reserve = (captions ? CAPTION_RESERVE : 0) + (controls ? CONTROLS_RESERVE : 0)\n  const A = Math.max(160, height - reserve)\n  const h = Math.max(40, size * A)\n  const w = h * aspect\n  const n = Math.max(count, 1)\n  const R = (CURVE_RADIUS * w) / clamp(curvature, 0.01, 1)\n  // Neighbours sit `gap` apart along the arc.\n  const alpha = (w + gap) / R\n  const p = (VIEW_SLOPE * Math.max(1.2, distance) + VIEW_OFFSET) * h\n  // How many panels away from the centre can still be seen.\n  let reach = 0\n  for (let o = 0; o < 64; o += 0.5) {\n    if (!facesViewer(o * alpha, R, p, width, w)) break\n    reach = o\n  }\n  const slots = n * Math.max(1, Math.ceil((2 * reach + 3) / n))\n  const sw = w / STRIPS\n  const strips = Array.from({ length: STRIPS }, (_, j) => {\n    const d = ((j + 0.5) * sw - w / 2) / R\n    return `translate3d(${(R * Math.sin(d)).toFixed(3)}px,0,${(R * (1 - Math.cos(d))).toFixed(3)}px) rotateY(${(-d).toFixed(5)}rad)`\n  })\n  return { W: width, A, h, w, n, slots, alpha, R, p, cy: A / 2, sw, strips }\n}\n\ntype WallGeometry = ReturnType<typeof wallGeometry>\n\n/** Where a panel `offset` panels from the centre hangs on the wall: its angle and its position, in pixels. */\nexport function panelPose(offset: number, alpha: number, wallRadius: number) {\n  const theta = offset * alpha\n  return { theta, x: wallRadius * Math.sin(theta), z: wallRadius * (1 - Math.cos(theta)) }\n}\n\n/** Screen offset from the view centre of a point on the wall, matching the CSS camera and its tilt. */\nexport function projectPoint(x: number, y: number, z: number, perspective: number, tilt: number) {\n  const a = (-tilt * Math.PI) / 180\n  const y2 = y * Math.cos(a) - (z - perspective) * Math.sin(a)\n  const z2 = perspective + y * Math.sin(a) + (z - perspective) * Math.cos(a)\n  const k = perspective / Math.max(perspective - z2, 1)\n  return [x * k, y2 * k] as const\n}\n\n/** Where a screen point, as an offset from the view centre, hits the wall: its angle, and whether it lands on a panel. */\nexport function hitWall(x: number, y: number, { p, R, h }: Pick<WallGeometry, \"p\" | \"R\" | \"h\">) {\n  // Ray from the viewer through the screen point, against the far side of the wall's cylinder.\n  const a = x * x + p * p\n  const b = -2 * p * (p - R)\n  const c = p * (p - 2 * R)\n  const disc = b * b - 4 * a * c\n  if (disc < 0) return null\n  const t = (-b + Math.sqrt(disc)) / (2 * a)\n  const X = t * x\n  const Z = p * (1 - t)\n  return { theta: Math.atan2(X, R - Z), onPanel: Math.abs((y * (p - Z)) / p) <= h / 2 }\n}\n\n/** Advances the snap spring by `dt` seconds, in fixed substeps. */\nexport function stepSpring(s: { pos: number; vel: number; target: number }, dt: number) {\n  for (let left = dt; left > 0; left -= SUBSTEP) {\n    const h = Math.min(left, SUBSTEP)\n    s.vel += (SPRING_K * (s.target - s.pos) - SPRING_C * s.vel) * h\n    s.pos += s.vel * h\n  }\n}\n\n/** The wall's edge fade as a horizontal mask: 1 in the middle, 1 - dim at the edges. */\nexport function edgeMask(dim: number) {\n  const stops = Array.from({ length: 21 }, (_, k) => {\n    const u = Math.abs(k / 10 - 1)\n    return `rgba(0,0,0,${(1 - dim * smoothstep(0.2, 1, u)).toFixed(3)}) ${k * 5}%`\n  })\n  return `linear-gradient(to right, ${stops.join(\", \")})`\n}\n\nconst restingPos = (s: { mode: Mode; pos: number; target: number }) => (s.mode === \"spring\" ? s.target : s.pos)\n\n// The panels' visibility is written only when it changes, so a frame writes nothing but transform and opacity.\nconst show = (el: HTMLElement, visible: boolean) => {\n  const value = visible ? \"\" : \"hidden\"\n  if (el.style.visibility !== value) el.style.visibility = value\n}\n\nconst subscribeReducedMotion = (onChange: () => void) => {\n  const query = window.matchMedia?.(REDUCED_MOTION)\n  query?.addEventListener(\"change\", onChange)\n  return () => query?.removeEventListener(\"change\", onChange)\n}\nconst readReducedMotion = () => window.matchMedia?.(REDUCED_MOTION).matches ?? false\n\nfunction Chevron({ direction }: { direction: \"left\" | \"right\" }) {\n  return (\n    <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n      <path d={direction === \"left\" ? \"m15 18-6-6 6-6\" : \"m9 18 6-6-6-6\"} />\n    </svg>\n  )\n}\n\nexport function ConcaveCarousel({\n  items = DEFAULT_ITEMS,\n  startIndex = 0,\n  aspect = 1.25,\n  size = 0.46,\n  curvature = 0.72,\n  distance = 4,\n  tilt = 0,\n  gap = 16,\n  radius = 14,\n  reflection = 0.06,\n  dim = 0.35,\n  autoplay = \"drift\",\n  speed = 0.16,\n  interval = 4,\n  snap = true,\n  inertia = 0.5,\n  pauseOnHover = true,\n  draggable = true,\n  wheel = true,\n  captions = true,\n  controls = true,\n  backgroundColor,\n  paused: pausedProp = false,\n  onIndexChange,\n  onSelect,\n  controlsRef,\n  className,\n  style,\n  onKeyDown,\n  ...props\n}: ConcaveCarouselProps) {\n  const count = items.length\n  const start = count ? mod(Math.round(startIndex), count) : 0\n\n  const stageRef = React.useRef<HTMLDivElement>(null)\n  const panelRefs = React.useRef<(HTMLDivElement | null)[]>([])\n  const captionRefs = React.useRef<(HTMLDivElement | null)[]>([])\n  const wakeRef = React.useRef<(() => void) | null>(null)\n\n  const [box, setBox] = React.useState({ w: 0, h: 0 })\n  const [index, setIndex] = React.useState(start)\n  const [dragging, setDragging] = React.useState(false)\n  const [ratios, setRatios] = React.useState<Record<string, number>>({})\n  const reduced = React.useSyncExternalStore(subscribeReducedMotion, readReducedMotion, () => false)\n\n  // Space toggles the pause; a new `paused` prop takes over again.\n  const [paused, setPaused] = React.useState(pausedProp)\n  const [pausedSeen, setPausedSeen] = React.useState(pausedProp)\n  if (pausedSeen !== pausedProp) {\n    setPausedSeen(pausedProp)\n    setPaused(pausedProp)\n  }\n\n  const geo = React.useMemo(\n    () => wallGeometry({ width: box.w, height: box.h, count, size, aspect, curvature, gap, distance, captions, controls }),\n    [box, count, size, aspect, curvature, gap, distance, captions, controls]\n  )\n  const mask = React.useMemo(() => edgeMask(dim), [dim])\n\n  // Motion state lives in a plain object; the loop writes transforms straight to the panels.\n  const motionRef = React.useRef({\n    // In panels; the centred index is round(pos).\n    pos: start,\n    vel: 0,\n    target: start,\n    drift: 0,\n    mode: \"drift\" as Mode,\n    hovered: false,\n    holdUntil: 0,\n    nextStep: 0,\n    raf: 0,\n    timer: 0,\n    last: 0,\n    visible: true,\n  })\n  const indexRef = React.useRef(start)\n  const geoRef = React.useRef(geo)\n  const live: Live = { autoplay, speed, interval, paused, reduced, pauseOnHover, snap, inertia, tilt, gap, captions, items, onIndexChange, onSelect }\n  const liveRef = React.useRef(live)\n\n  // Props and geometry reach the loop and the handlers through refs written here, never during render. It is a\n  // layout effect, declared first, so the layout effects below already read this render's values.\n  React.useLayoutEffect(() => {\n    geoRef.current = geo\n    liveRef.current = live\n  })\n\n  const layout = React.useCallback(() => {\n    const g = geoRef.current\n    if (!g.W) return\n    const { pos } = motionRef.current\n    const { captions: showCaptions, gap: gapPx, tilt: tiltDeg } = liveRef.current\n    for (let i = 0; i < g.slots; i++) {\n      const panel = panelRefs.current[i]\n      if (!panel) continue\n      const o = wrapOffset(i - pos, g.slots)\n      const { theta, x, z } = panelPose(o, g.alpha, g.R)\n      // Hide panels behind the viewer, facing away or off screen (that is also where the wall wraps round).\n      const visible = facesViewer(theta, g.R, g.p, g.W, g.w)\n      show(panel, visible)\n      if (visible) panel.style.transform = `translate3d(${x.toFixed(2)}px,0,${z.toFixed(2)}px) rotateY(${(-theta).toFixed(5)}rad)`\n\n      const caption = captionRefs.current[i]\n      if (!caption || !showCaptions) continue\n      if (!visible || Math.abs(o) > 1.5) {\n        caption.style.opacity = \"0\"\n        show(caption, false)\n        continue\n      }\n      const [bx, by] = projectPoint(x, g.h / 2, z, g.p, tiltDeg)\n      // Each caption rides under its panel and fades out as the panel leaves the centre.\n      const opacity = 1 - smoothstep(0.46, 0.85, Math.abs(bx) / (g.w + gapPx))\n      caption.style.opacity = opacity.toFixed(3)\n      show(caption, opacity > 0.001)\n      caption.style.transform = `translate(${(g.W / 2 + bx).toFixed(2)}px, ${(g.cy + by + CAPTION_OFFSET * g.h).toFixed(2)}px) translateX(-50%)`\n    }\n  }, [])\n\n  const syncIndex = React.useCallback(() => {\n    const next = mod(Math.round(motionRef.current.pos), geoRef.current.n)\n    if (next === indexRef.current) return\n    indexRef.current = next\n    setIndex(next)\n    liveRef.current.onIndexChange?.(next)\n  }, [])\n\n  const kick = React.useCallback(() => wakeRef.current?.(), [])\n\n  /** Holds autoplay for a moment after any input. */\n  const touch = React.useCallback(() => {\n    const now = performance.now()\n    motionRef.current.holdUntil = now + RESUME_AFTER_INPUT\n    motionRef.current.nextStep = now + liveRef.current.interval * 1000\n  }, [])\n\n  const springTo = React.useCallback(\n    (target: number, vel?: number) => {\n      const s = motionRef.current\n      if (vel !== undefined) s.vel = vel\n      else if (s.mode === \"drift\") s.vel = s.drift\n      s.drift = 0\n      s.target = target\n      if (liveRef.current.reduced) {\n        s.pos = target\n        s.vel = 0\n        s.mode = \"drift\"\n        layout()\n        syncIndex()\n        return\n      }\n      s.mode = \"spring\"\n      kick()\n    },\n    [kick, layout, syncIndex]\n  )\n\n  const next = React.useCallback(() => {\n    touch()\n    springTo(Math.round(restingPos(motionRef.current)) + 1)\n  }, [springTo, touch])\n\n  const previous = React.useCallback(() => {\n    touch()\n    springTo(Math.round(restingPos(motionRef.current)) - 1)\n  }, [springTo, touch])\n\n  const goTo = React.useCallback(\n    (i: number) => {\n      const n = geoRef.current.n\n      touch()\n      const from = Math.round(restingPos(motionRef.current))\n      let delta = mod(i - from, n)\n      if (delta > n / 2) delta -= n\n      springTo(from + delta)\n    },\n    [springTo, touch]\n  )\n\n  const select = React.useCallback((i: number) => {\n    const item = liveRef.current.items[i]\n    if (!item) return\n    liveRef.current.onSelect?.(item, i)\n    if (item.href) window.location.assign(item.href)\n  }, [])\n\n  React.useImperativeHandle(controlsRef, () => ({ next, previous, goTo }), [next, previous, goTo])\n\n  React.useLayoutEffect(() => {\n    // The root's ref stays the consumer's, so the root is reached through the stage.\n    const root = stageRef.current?.parentElement\n    if (!root) return\n    const measure = () => {\n      const w = root.clientWidth\n      const h = root.clientHeight\n      setBox((b) => (b.w === w && b.h === h ? b : { w, h }))\n    }\n    measure()\n    const observer = new ResizeObserver(measure)\n    observer.observe(root)\n    return () => observer.disconnect()\n  }, [])\n\n  React.useLayoutEffect(() => {\n    layout()\n  }, [geo, captions, tilt, layout])\n\n  // Re-anchor if the item count changes.\n  React.useLayoutEffect(() => {\n    const s = motionRef.current\n    if (!count) return\n    s.pos = s.target = mod(Math.round(s.pos), count)\n    s.vel = 0\n    s.mode = \"drift\"\n    layout()\n    syncIndex()\n  }, [count, layout, syncIndex])\n\n  // The frame loop. It runs only while something moves, sleeps until autoplay's next move is due, and stops off screen.\n  React.useEffect(() => {\n    const root = stageRef.current?.parentElement\n    if (!root) return\n    const s = motionRef.current\n\n    function frame(now: number) {\n      if (!s.visible) {\n        s.raf = 0\n        return\n      }\n      const dt = clamp((now - s.last) / 1000, MIN_DT, MAX_DT)\n      s.last = now\n      const L = liveRef.current\n      const autoplayOn = L.autoplay !== \"off\" && !L.paused && !L.reduced && L.speed !== 0\n      const braked = L.pauseOnHover && s.hovered\n\n      // Drift eases toward its target speed: it brakes quickly and picks up gently.\n      const want = autoplayOn && L.autoplay === \"drift\" && s.mode === \"drift\" && !braked && now >= s.holdUntil ? L.speed : 0\n      s.drift += (want - s.drift) * (1 - Math.exp(-dt / (Math.abs(want) < Math.abs(s.drift) ? BRAKE_TAU : ACCEL_TAU)))\n\n      if (s.mode === \"drift\") {\n        s.pos += s.drift * dt\n      } else if (s.mode === \"spring\") {\n        stepSpring(s, dt)\n        if (Math.abs(s.target - s.pos) < 1e-4 && Math.abs(s.vel) < 1e-3) {\n          s.pos = s.target\n          s.vel = 0\n          s.mode = \"drift\"\n        }\n      } else if (s.mode === \"coast\") {\n        // Exponential friction: coasts the same distance a snapped flick projects (vel × inertia × COAST_TIME).\n        s.vel *= Math.exp(-dt / Math.max(L.inertia * COAST_TIME, 0.05))\n        s.pos += s.vel * dt\n        if (Math.abs(s.vel) < 0.01) {\n          s.vel = 0\n          s.mode = \"drift\"\n        }\n      }\n\n      if (autoplayOn && L.autoplay === \"step\" && s.mode === \"drift\" && !braked && now >= s.nextStep) {\n        s.mode = \"spring\"\n        s.target = Math.round(s.pos) + Math.sign(L.speed)\n        s.nextStep = now + L.interval * 1000\n      }\n\n      layout()\n      syncIndex()\n\n      const moving = s.mode === \"spring\" || s.mode === \"coast\" || want !== 0 || Math.abs(s.drift) >= 1e-5\n      if (moving) {\n        s.raf = requestAnimationFrame(frame)\n        return\n      }\n      s.raf = 0\n      s.drift = 0\n      // At rest the loop sleeps until autoplay's next move is due, instead of drawing the same frame again.\n      if (autoplayOn && !braked && s.mode === \"drift\") {\n        const due = L.autoplay === \"step\" ? s.nextStep : s.holdUntil\n        s.timer = window.setTimeout(wake, Math.max(0, due - performance.now()))\n      }\n    }\n\n    function wake() {\n      window.clearTimeout(s.timer)\n      s.timer = 0\n      // Never schedule while off screen or in a hidden tab; the observers wake the loop again.\n      if (s.raf || !s.visible || document.hidden) return\n      s.last = performance.now()\n      s.raf = requestAnimationFrame(frame)\n    }\n\n    const stop = () => {\n      cancelAnimationFrame(s.raf)\n      s.raf = 0\n      window.clearTimeout(s.timer)\n      s.timer = 0\n    }\n\n    const intersection = new IntersectionObserver((entries) => {\n      s.visible = entries.some((entry) => entry.isIntersecting)\n      if (s.visible) wake()\n      else stop()\n    })\n    intersection.observe(root)\n    const onVisibility = () => {\n      if (document.hidden) return\n      s.last = performance.now()\n      wake()\n    }\n    document.addEventListener(\"visibilitychange\", onVisibility)\n    wakeRef.current = wake\n\n    return () => {\n      // Reset the ids too: Strict Mode remounts, and the next setup must be able to start a new loop.\n      wakeRef.current = null\n      stop()\n      intersection.disconnect()\n      document.removeEventListener(\"visibilitychange\", onVisibility)\n    }\n  }, [layout, syncIndex])\n\n  React.useEffect(() => {\n    kick()\n  }, [kick, autoplay, speed, paused, reduced, pauseOnHover])\n\n  // Read each image's aspect so it can be cropped to fill its panel.\n  const loadersRef = React.useRef(new Map<string, HTMLImageElement>())\n  React.useEffect(() => {\n    const loaders = loadersRef.current\n    for (const { src } of items) {\n      if (loaders.has(src)) continue\n      const image = new Image()\n      image.onload = () => {\n        if (image.naturalHeight) setRatios((r) => ({ ...r, [src]: image.naturalWidth / image.naturalHeight }))\n      }\n      image.src = src\n      loaders.set(src, image)\n    }\n  }, [items])\n  React.useEffect(() => {\n    const loaders = loadersRef.current\n    return () => {\n      for (const image of loaders.values()) image.onload = null\n      loaders.clear()\n    }\n  }, [])\n\n  // Wheel: one panel per notch; small trackpad deltas add up.\n  React.useEffect(() => {\n    const stage = stageRef.current\n    if (!stage || !wheel) return\n    let acc = 0\n    let idle = 0\n    const onWheel = (event: WheelEvent) => {\n      const raw = Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY\n      if (!raw) return\n      event.preventDefault()\n      acc += raw * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? 400 : 1)\n      window.clearTimeout(idle)\n      idle = window.setTimeout(() => (acc = 0), 200)\n      if (Math.abs(acc) >= WHEEL_STEP) {\n        if (acc > 0) next()\n        else previous()\n        acc = 0\n      }\n    }\n    stage.addEventListener(\"wheel\", onWheel, { passive: false })\n    return () => {\n      stage.removeEventListener(\"wheel\", onWheel)\n      window.clearTimeout(idle)\n    }\n  }, [wheel, next, previous])\n\n  const hit = React.useCallback((clientX: number, clientY: number) => {\n    const stage = stageRef.current\n    if (!stage) return null\n    const g = geoRef.current\n    const rect = stage.getBoundingClientRect()\n    return hitWall(clientX - rect.left - g.W / 2, clientY - rect.top - g.cy, g)\n  }, [])\n\n  // Pointer: a drag turns the wall so the grabbed point stays under the pointer; a tap selects.\n  const dragRef = React.useRef({ id: -1, x: 0, theta: 0, from: 0, moved: false, onPanel: false, grabbed: false, samples: [] as { t: number; pos: number }[] })\n\n  const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {\n    if (event.button !== 0 || !count) return\n    const h = hit(event.clientX, event.clientY)\n    if (!h) return\n    const s = motionRef.current\n    dragRef.current = { id: event.pointerId, x: event.clientX, theta: h.theta, from: s.pos, moved: false, onPanel: h.onPanel, grabbed: draggable, samples: [{ t: event.timeStamp, pos: s.pos }] }\n    if (draggable) {\n      event.currentTarget.setPointerCapture?.(event.pointerId)\n      // Catch the wall: it stops where it is so the held point does not slip.\n      s.mode = \"drag\"\n      s.vel = 0\n      s.drift = 0\n    }\n    touch()\n  }\n\n  const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {\n    const d = dragRef.current\n    if (d.id !== event.pointerId || !d.grabbed) return\n    if (!d.moved && Math.abs(event.clientX - d.x) < DRAG_THRESHOLD) return\n    if (!d.moved) {\n      d.moved = true\n      setDragging(true)\n    }\n    const h = hit(event.clientX, event.clientY)\n    if (!h) return\n    const s = motionRef.current\n    s.pos = d.from - (h.theta - d.theta) / geoRef.current.alpha\n    d.samples.push({ t: event.timeStamp, pos: s.pos })\n    if (d.samples.length > 8) d.samples.shift()\n    touch()\n    layout()\n    syncIndex()\n  }\n\n  const onPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {\n    const d = dragRef.current\n    if (d.id !== event.pointerId) return\n    d.id = -1\n    const s = motionRef.current\n    touch()\n\n    if (!d.moved) {\n      if (event.type === \"pointerup\" && d.onPanel) {\n        const h = hit(event.clientX, event.clientY)\n        const i = h ? mod(Math.round(s.pos + h.theta / geoRef.current.alpha), geoRef.current.n) : indexRef.current\n        if (i === indexRef.current) {\n          select(i)\n          if (d.grabbed) springTo(Math.round(s.pos), 0)\n        } else goTo(i)\n      } else if (d.grabbed) springTo(Math.round(s.pos), 0)\n      return\n    }\n\n    setDragging(false)\n    const recent = d.samples.filter((sample) => event.timeStamp - sample.t < 100)\n    // Panels per second.\n    let vel = 0\n    if (recent.length > 1) {\n      const a = recent[0]\n      const b = recent[recent.length - 1]\n      vel = (b.pos - a.pos) / Math.max((b.t - a.t) / 1000, 0.016)\n    }\n    vel = clamp(vel, -25, 25)\n    const L = liveRef.current\n    if (L.snap) springTo(Math.round(s.pos + vel * L.inertia * COAST_TIME), vel)\n    else {\n      s.vel = vel\n      s.mode = L.reduced ? \"drift\" : \"coast\"\n      kick()\n    }\n  }\n\n  const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    onKeyDown?.(event)\n    // Let the controls handle their own keys.\n    if (event.defaultPrevented || event.target instanceof HTMLButtonElement) return\n    if (event.key === \"ArrowRight\" || event.key === \"ArrowDown\") next()\n    else if (event.key === \"ArrowLeft\" || event.key === \"ArrowUp\") previous()\n    else if (event.key === \" \") setPaused((v) => !v)\n    else if (event.key === \"Enter\") select(indexRef.current)\n    else return\n    event.preventDefault()\n  }\n\n  const { h, w, sw, strips, p, cy, slots } = geo\n  const corner = Math.min(radius, sw)\n\n  // The wall only changes with the geometry and the images, so a new centred index does not re-render it.\n  const wall = React.useMemo(\n    () =>\n      Array.from({ length: count ? slots : 0 }, (_, i) => {\n        const item = items[i % count]\n        // Crop like object-fit: cover.\n        const ratio = ratios[item.src] ?? aspect\n        const bw = ratio > aspect ? h * ratio : w\n        const bh = ratio > aspect ? h : w / ratio\n        const ox = (w - bw) / 2\n        const oy = (h - bh) / 2\n        const image = `url(\"${item.src}\")`\n        const fade = `linear-gradient(to top, rgba(0,0,0,${reflection}) 0%, rgba(0,0,0,0) ${REFLECT_LENGTH * 100}%)`\n        return (\n          <div\n            key={i}\n            ref={(el) => {\n              panelRefs.current[i] = el\n            }}\n            data-slot=\"concave-carousel-panel\"\n            className=\"absolute top-0 left-0 size-0 will-change-transform [transform-style:preserve-3d]\"\n          >\n            {strips.map((transform, j) => {\n              const face: React.CSSProperties = {\n                backgroundImage: image,\n                backgroundSize: `${bw}px ${bh}px`,\n                backgroundPosition: `${(ox - j * sw + STRIP_OVERLAP / 2).toFixed(2)}px ${oy.toFixed(2)}px`,\n                borderRadius: j === 0 ? `${corner}px 0 0 ${corner}px` : j === STRIPS - 1 ? `0 ${corner}px ${corner}px 0` : undefined,\n              }\n              return (\n                <div\n                  key={j}\n                  className=\"absolute [backface-visibility:hidden]\"\n                  style={{ width: sw + STRIP_OVERLAP, height: h, left: -(sw + STRIP_OVERLAP) / 2, top: -h / 2, transform }}\n                >\n                  <div className=\"pointer-events-none absolute top-0 left-0 size-full bg-muted bg-no-repeat\" style={face} />\n                  {reflection > 0 && (\n                    // Mirror image under the panel, faded by a static mask.\n                    <div\n                      className=\"pointer-events-none absolute left-0 size-full -scale-y-100 bg-muted bg-no-repeat\"\n                      style={{ ...face, top: h * (1 + REFLECT_GAP), maskImage: fade, WebkitMaskImage: fade }}\n                    />\n                  )}\n                </div>\n              )\n            })}\n          </div>\n        )\n      }),\n    [count, slots, items, ratios, aspect, h, w, sw, strips, corner, reflection]\n  )\n\n  const captionNodes = React.useMemo(\n    () =>\n      captions && count\n        ? Array.from({ length: slots }, (_, i) => {\n            const item = items[i % count]\n            return (\n              <div\n                key={i}\n                ref={(el) => {\n                  captionRefs.current[i] = el\n                }}\n                className=\"absolute top-0 left-0 text-center whitespace-nowrap opacity-0 will-change-[transform,opacity]\"\n              >\n                {item.title && <div className=\"text-[15px] leading-5 font-semibold tracking-[-0.01em]\">{item.title}</div>}\n                {item.subtitle && <div className=\"mt-1 text-[13px] leading-[18px] opacity-55\">{item.subtitle}</div>}\n              </div>\n            )\n          })\n        : null,\n    [captions, count, slots, items]\n  )\n\n  const current = items[index] ?? items[0]\n  const drifting = autoplay !== \"off\" && !paused && !reduced\n\n  return (\n    <div\n      data-slot=\"concave-carousel\"\n      role=\"region\"\n      aria-roledescription=\"carousel\"\n      aria-label={DEFAULT_LABEL}\n      tabIndex={0}\n      className={cn(\n        \"relative h-full min-h-[420px] w-full overflow-hidden text-foreground outline-none select-none [-webkit-tap-highlight-color:transparent] focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring\",\n        className\n      )}\n      style={{ background: backgroundColor, ...style }}\n      onKeyDown={handleKeyDown}\n      {...props}\n    >\n      <div\n        ref={stageRef}\n        aria-hidden\n        className={cn(\"absolute inset-0 touch-pan-y overflow-hidden\", dragging ? \"cursor-grabbing\" : \"cursor-grab\")}\n        style={{ perspective: `${p}px`, perspectiveOrigin: `50% ${cy}px`, maskImage: mask, WebkitMaskImage: mask }}\n        onPointerDown={onPointerDown}\n        onPointerMove={onPointerMove}\n        onPointerUp={onPointerUp}\n        onPointerCancel={onPointerUp}\n        onPointerEnter={(event) => {\n          if (event.pointerType === \"mouse\") motionRef.current.hovered = true\n        }}\n        onPointerLeave={() => {\n          const s = motionRef.current\n          s.hovered = false\n          s.holdUntil = Math.max(s.holdUntil, performance.now() + RESUME_AFTER_HOVER)\n          kick()\n        }}\n      >\n        <div\n          className=\"absolute left-1/2 size-0 [transform-style:preserve-3d]\"\n          style={{ top: cy, transformOrigin: `0 0 ${p}px`, transform: tilt ? `rotateX(${-tilt}deg)` : undefined }}\n        >\n          {wall}\n        </div>\n      </div>\n\n      {captionNodes && (\n        <div aria-hidden className=\"pointer-events-none absolute inset-0\">\n          {captionNodes}\n        </div>\n      )}\n\n      {current && (\n        <p className=\"sr-only\" aria-live={drifting ? \"off\" : \"polite\"}>\n          {`${current.title ?? current.alt}, ${index + 1} of ${count}${current.subtitle ? `. ${current.subtitle}` : \"\"}. ${current.alt}`}\n        </p>\n      )}\n\n      {controls && count > 0 && (\n        <div className=\"absolute left-1/2 flex -translate-x-1/2 items-center\" style={{ top: geo.A - 16 }}>\n          <button\n            type=\"button\"\n            aria-label=\"Previous\"\n            onClick={previous}\n            className=\"grid size-8 cursor-pointer place-items-center rounded-full bg-foreground/10 p-0 transition-[background-color] duration-160 ease-[ease] hover:bg-foreground/18 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring\"\n          >\n            <Chevron direction=\"left\" />\n          </button>\n          <span aria-hidden className=\"w-[92px] text-center text-[12px] tracking-[0.02em] tabular-nums\">\n            <span className=\"opacity-85\">{pad(index + 1)}</span>\n            <span className=\"opacity-40\"> / {pad(count)}</span>\n          </span>\n          <button\n            type=\"button\"\n            aria-label=\"Next\"\n            onClick={next}\n            className=\"grid size-8 cursor-pointer place-items-center rounded-full bg-foreground/10 p-0 transition-[background-color] duration-160 ease-[ease] hover:bg-foreground/18 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring\"\n          >\n            <Chevron direction=\"right\" />\n          </button>\n        </div>\n      )}\n    </div>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "meta": {
    "added": "2026-10-28"
  },
  "categories": [
    "card"
  ],
  "type": "registry:ui"
}