Cylinder Carousel
A carousel whose items line the inside of a cylinder, receding into the center and growing toward the edges. Drag, scroll or arrow-key to roll it, with a springy glide and snap. Reduced-motion drops the glide.
Preview
Drag, scroll or use arrow keys to roll
"use client";
import { type ComponentType, useState } from "react";
import { CylinderCarousel } from "@/components/motion/cylinder-carousel";
import {
ShaderBackground,
type ShaderBackgroundVariant,
} from "@/components/motion/shader-background";
import { Tabs, TabsList, TabsTrigger } from "@/components/motion/tabs";
// Each variant has its own prop shape; the slides only spread their own preset.
const Background = ShaderBackground as ComponentType<
{ variant: ShaderBackgroundVariant; className?: string } & Record<
string,
unknown
>
>;
const SLIDES: { variant: ShaderBackgroundVariant; props: Record<string, unknown> }[] = [
{
variant: "dithering",
props: { colorBack: "#1a1030", colorFront: "#b98cff", speed: 0.3 },
},
{
variant: "metaballs",
props: { colors: ["#e8e8ef", "#8a8a9a", "#1a1a22"], colorBack: "#c9b9a8", speed: 0.4 },
},
{
variant: "warp",
props: { colors: ["#c8ff00", "#3a5a00", "#c8ff00", "#88bb00"], speed: 0.4 },
},
{
variant: "god-rays",
props: { colors: ["#6a7bff", "#00114d"], colorBack: "#000000", speed: 0.5 },
},
{
variant: "swirl",
props: { colorBack: "#1a0000", colors: ["#ffd1a8", "#ff6a3d", "#b31a57"], speed: 0.3 },
},
{
variant: "mesh-gradient",
props: { colors: ["#e0eaff", "#241d9a", "#f75092", "#9f50d3"], speed: 0.3 },
},
{
variant: "voronoi",
props: { colors: ["#ff8247", "#ffe53d"], speed: 0.3 },
},
{
variant: "neuro-noise",
props: { colorFront: "#ffffff", colorMid: "#47a6ff", colorBack: "#000000", speed: 0.4 },
},
];
export function CylinderCarouselPreview() {
const [variant, setVariant] = useState<"concave" | "convex">("concave");
return (
<div className="flex w-full flex-col items-center gap-4 p-6">
<Tabs
value={variant}
onValueChange={(v) => setVariant(v as "concave" | "convex")}
variant="segment"
>
<TabsList>
<TabsTrigger value="concave">Concave</TabsTrigger>
<TabsTrigger value="convex">Convex</TabsTrigger>
</TabsList>
</Tabs>
{/* clip-path (not overflow) so the rounded corner also clips the GPU-composited balls */}
<div className="w-full rounded-3xl border border-border/60 bg-muted/20 py-6 [clip-path:inset(0_round_1.5rem)]">
<CylinderCarousel
variant={variant}
itemSize={230}
height={310}
className="w-full"
>
{SLIDES.map((slide) => (
<div
key={slide.variant}
className="h-full w-full overflow-hidden rounded-full border border-border/40"
>
<Background
variant={slide.variant}
className="h-full w-full"
{...slide.props}
/>
</div>
))}
</CylinderCarousel>
</div>
<p className="text-xs text-muted-foreground">
Drag, scroll or use arrow keys to roll
</p>
</div>
);
}
"use client";
// beui.dev/components/motion/cylinder-carousel
import {
animate,
type AnimationPlaybackControls,
motion,
type MotionValue,
useMotionValue,
useReducedMotion,
useTransform,
} from "motion/react";
import {
Children,
type PointerEvent as ReactPointerEvent,
type ReactNode,
useCallback,
useEffect,
useRef,
useState,
type WheelEvent as ReactWheelEvent,
} from "react";
import {
capturePointer,
releasePointer,
TOUCH_GESTURE_CLASS,
} from "@/lib/touch";
import { cn } from "@/lib/utils";
// Carousel-specific: a soft spring that receives the release velocity, so a
// flick keeps rolling freely, drifts past the snap point and eases back.
const GLIDE_SPRING = { stiffness: 40, damping: 20, mass: 3 };
// How far a flick keeps rolling: projected items = release velocity * momentum.
const FLICK_MOMENTUM = 0.45;
const MAX_FLICK_ITEMS = 6;
export interface CylinderCarouselProps {
children: ReactNode;
/** Max item box size in px (square) at full size, i.e. at the container
* edge. Balls shrink below this automatically so the row keeps breathing
* room in narrow containers. */
itemSize?: number;
/** How many item slots span the container width. */
visibleItems?: number;
/** "concave" (default): inside of the cylinder — center ball smallest and
* dipped, growing toward the edges. "convex": outside of the cylinder —
* center ball biggest and raised, shrinking toward the edges. */
variant?: "concave" | "convex";
/** Scale of the smallest ball (center for concave, edges for convex);
* the biggest reaches 1. */
minScale?: number;
/** Items rolled per item-width dragged — above 1 the wall outruns the
* pointer, which reads as a lighter, freer roll. */
dragSpeed?: number;
/** Curve depth in px: for concave, how far the edge balls ride above the
* center one (valley); for convex, how far below (arch). 0 = flat line.
* Defaults to 35% of the item size. */
arc?: number;
/** Snap to the nearest item when the roll settles. */
snap?: boolean;
/** Roll on its own until interacted with. */
autoRotate?: boolean;
/** Auto-roll speed in items per second. */
autoRotateSpeed?: number;
defaultIndex?: number;
onIndexChange?: (index: number) => void;
/** Stage height in px. Defaults to `itemSize`. */
height?: number;
className?: string;
}
// The frame edge sits at this wall angle; how far the wall curves in frame.
const THETA_EDGE = (72 * Math.PI) / 180;
// Wall angle past which a ball is parked far off-stage (always hidden there).
const THETA_CLAMP = (95 * Math.PI) / 180;
/**
* One ball on the inside wall of the cylinder, rendered through a single
* perspective projection: the ball sits at wall angle θ, the camera slightly
* above the ball line, so horizontal position, size and height all share one
* 1/(cosθ + k) depth term. Center = far wall: smallest, highest, moving
* slowest; edges = nearest: full size, level, moving fastest, sliding off to
* be clipped. Nothing overlaps, fades or reorders — the edge is the exit.
*/
function CarouselBall({
scroll,
index,
count,
alpha,
k,
projection,
gap,
edgeOffset,
minScale,
convex,
arc,
halfWidth,
itemSize,
children,
}: {
scroll: MotionValue<number>;
index: number;
count: number;
/** Wall angle per item step, in radians. */
alpha: number;
/** Camera distance term for the horizontal projection. */
k: number;
/** Projection strength: maps sinθ/(cosθ+k) to px so θE lands on the edge. */
projection: number;
/** Uniform slot width in px — convex spacing. */
gap: number;
/** Offset at which a ball's center sits on the container edge. */
edgeOffset: number;
minScale: number;
convex: boolean;
/** Curve depth in px between the center ball and the edge balls. */
arc: number;
halfWidth: number;
itemSize: number;
children: ReactNode;
}) {
// Nearest wrapped offset so items loop around continuously.
const offset = useTransform(scroll, (s) => {
let o = index - s;
o -= Math.round(o / count) * count;
return o;
});
// Concave spacing follows the interior perspective (slow, tight center);
// convex pairs its big center balls with uniform spacing — the interior
// projection would collapse them into each other.
const x = useTransform(offset, (o) => {
if (convex) return o * gap;
const th = Math.max(-THETA_CLAMP, Math.min(THETA_CLAMP, o * alpha));
return (projection * Math.sin(th)) / (Math.cos(th) + k);
});
// Linear in wall angle, not in depth (the depth curve is near-flat around
// the center, which made the middle three read as equal): every step is
// visibly bigger than the last — growing outward (concave) or inward
// (convex).
const scale = useTransform(offset, (o) => {
const t = Math.min(Math.abs(o) / edgeOffset, THETA_CLAMP / THETA_EDGE);
return convex
? 1 - (1 - minScale) * t
: minScale + (1 - minScale) * t;
});
// Parabola centered on the stage — valley for concave (center ball dips
// arc/2 below the midline, edges rise arc/2 above), arch for convex — and
// deliberately unclamped: a ball keeps following the same curve as it
// crosses the edge, so entries never pop.
const y = useTransform(x, (px) => {
const t = px / halfWidth;
const valley = arc * (0.5 - t * t);
return convex ? -valley : valley;
});
// Fully off-stage balls stop painting (matters for canvas/shader children).
const visibility = useTransform(x, (px) =>
Math.abs(px) > halfWidth + itemSize ? "hidden" : "visible",
);
return (
<motion.div
className="absolute top-1/2 left-1/2"
style={{
x,
y,
scale,
visibility,
width: itemSize,
height: itemSize,
marginLeft: -itemSize / 2,
marginTop: -itemSize / 2,
}}
>
{children}
</motion.div>
);
}
export function CylinderCarousel({
children,
itemSize = 200,
visibleItems = 5,
variant = "concave",
minScale = 0.55,
dragSpeed = 1.5,
arc: arcProp,
snap = true,
autoRotate = false,
autoRotateSpeed = 0.4,
defaultIndex = 0,
onIndexChange,
height,
className,
}: CylinderCarouselProps) {
const reduce = useReducedMotion() ?? false;
const items = Children.toArray(children);
const count = items.length;
const stageRef = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(0);
useEffect(() => {
const el = stageRef.current;
if (!el) return;
const ro = new ResizeObserver(([entry]) => {
setWidth(entry.contentRect.width);
});
ro.observe(el);
return () => ro.disconnect();
}, []);
// Sized so `visibleItems` balls sit fully in frame and the next one out on
// each side straddles the container edge, half visible.
const stageWidth = width || 800;
const halfWidth = stageWidth / 2;
const edgeOffset = (visibleItems + 1) / 2;
// Fit: the resting row's diameters may take at most ~66% of the stage — the
// rest is air between balls plus the half-visible ball on each edge.
// `itemSize` only caps the result.
const convex = variant === "convex";
let scaleSum = 0;
for (let i = 0; i < visibleItems; i++) {
const t = Math.abs(i - (visibleItems - 1) / 2) / edgeOffset;
scaleSum += convex
? 1 - (1 - minScale) * t
: minScale + (1 - minScale) * t;
}
const size = Math.min(itemSize, (stageWidth * 0.65) / scaleSum);
const gap = stageWidth / (visibleItems + 1);
const arc = arcProp ?? size * 0.35;
// Perspective constants. The ball one slot past the frame edge sits at wall
// angle THETA_EDGE with its center right on the container edge — scale 1,
// half of it in view; k falls out of the requested minScale (clamped so the
// projection stays monotonic up to THETA_CLAMP).
const alpha = THETA_EDGE / edgeOffset;
const k = Math.max(0.2, (minScale - Math.cos(THETA_EDGE)) / (1 - minScale));
const projection =
(halfWidth * (Math.cos(THETA_EDGE) + k)) / Math.sin(THETA_EDGE);
// scroll is in item units (continuous); item i sits at x = (i - scroll) * gap.
// Drags write it 1:1 so the wall sticks to the pointer; releases hand the
// pointer velocity to a soft spring so the roll glides on and settles free.
const scroll = useMotionValue(defaultIndex);
const indexRef = useRef(defaultIndex);
const [, setActiveIndex] = useState(defaultIndex);
const glideRef = useRef<AnimationPlaybackControls | null>(null);
const draggingRef = useRef(false);
const hoverRef = useRef(false);
useEffect(() => {
if (count === 0) return;
const unsub = scroll.on("change", (v) => {
const idx = ((Math.round(v) % count) + count) % count;
if (idx !== indexRef.current) {
indexRef.current = idx;
setActiveIndex(idx);
onIndexChange?.(idx);
}
});
return unsub;
}, [scroll, count, onIndexChange]);
const stopGlide = useCallback(() => {
glideRef.current?.stop();
glideRef.current = null;
}, []);
// Spring toward `to`, carrying `velocity` (items/s) through so motion never
// steps — the roll leaves the finger at finger speed.
const glideTo = useCallback(
(to: number, velocity: number) => {
stopGlide();
if (reduce) {
scroll.set(to);
return;
}
glideRef.current = animate(scroll, to, {
type: "spring",
...GLIDE_SPRING,
velocity,
restDelta: 0.001,
restSpeed: 0.005,
});
},
[scroll, stopGlide, reduce],
);
const settle = useCallback(
(velocity: number) => {
const projected =
scroll.get() +
Math.max(
-MAX_FLICK_ITEMS,
Math.min(MAX_FLICK_ITEMS, velocity * FLICK_MOMENTUM),
);
glideTo(snap ? Math.round(projected) : projected, velocity);
},
[scroll, snap, glideTo],
);
const drag = useRef({
startX: 0,
startScroll: 0,
lastX: 0,
lastT: 0,
prevX: 0,
prevT: 0,
});
const onPointerDown = useCallback(
(e: ReactPointerEvent) => {
e.preventDefault();
stopGlide();
draggingRef.current = true;
capturePointer(e.currentTarget, e.pointerId);
const now = performance.now();
drag.current = {
startX: e.clientX,
startScroll: scroll.get(),
lastX: e.clientX,
lastT: now,
prevX: e.clientX,
prevT: now,
};
},
[scroll, stopGlide],
);
const onPointerMove = useCallback(
(e: ReactPointerEvent) => {
if (!draggingRef.current) return;
const d = drag.current;
scroll.set(d.startScroll - ((e.clientX - d.startX) * dragSpeed) / gap);
d.prevX = d.lastX;
d.prevT = d.lastT;
d.lastX = e.clientX;
d.lastT = performance.now();
},
[scroll, gap, dragSpeed],
);
const onPointerUp = useCallback(
(e: ReactPointerEvent) => {
if (!draggingRef.current) return;
draggingRef.current = false;
releasePointer(e.currentTarget, e.pointerId);
const d = drag.current;
const dt = d.lastT - d.prevT;
const vpx = dt > 0 ? (d.lastX - d.prevX) / dt : 0; // px per ms
settle((-vpx * dragSpeed * 1000) / gap); // items per second
},
[settle, gap, dragSpeed],
);
const rollBy = useCallback(
(dir: number) => {
glideTo(Math.round(scroll.get()) + dir, scroll.getVelocity());
},
[scroll, glideTo],
);
const wheelSettleRef = useRef<number | undefined>(undefined);
const onWheel = useCallback(
(e: ReactWheelEvent) => {
stopGlide();
const delta =
Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;
scroll.set(scroll.get() + delta / gap);
if (wheelSettleRef.current) window.clearTimeout(wheelSettleRef.current);
wheelSettleRef.current = window.setTimeout(
() => settle(scroll.getVelocity()),
140,
);
},
[scroll, gap, settle, stopGlide],
);
useEffect(() => {
if (!autoRotate || reduce || count === 0) return;
let raf = 0;
let last = performance.now();
const tick = (now: number) => {
const dt = (now - last) / 1000;
last = now;
if (!draggingRef.current && !hoverRef.current && !glideRef.current) {
scroll.set(scroll.get() + autoRotateSpeed * dt);
}
raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, [autoRotate, autoRotateSpeed, reduce, count, scroll]);
const stageHeight = height ?? size;
return (
<div
ref={stageRef}
role="application"
aria-roledescription="carousel"
// biome-ignore lint/a11y/noNoninteractiveTabindex: focusable custom carousel widget
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "ArrowRight") {
e.preventDefault();
rollBy(1);
} else if (e.key === "ArrowLeft") {
e.preventDefault();
rollBy(-1);
}
}}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={onPointerUp}
onWheel={onWheel}
onPointerEnter={() => {
hoverRef.current = true;
}}
onPointerLeave={() => {
hoverRef.current = false;
}}
className={cn(
// clip-path, not overflow: it also clips the GPU-composited balls
"relative w-full touch-none outline-none [clip-path:inset(0)]",
// The stage drives the roll from the press itself, so iOS must not
// claim the same touch for its callout or a slide drag.
TOUCH_GESTURE_CLASS,
"cursor-grab active:cursor-grabbing",
"focus-visible:ring-2 focus-visible:ring-foreground/20",
className,
)}
style={{ height: stageHeight }}
>
{items.map((item, i) => (
<CarouselBall
// biome-ignore lint/suspicious/noArrayIndexKey: slides are positional and stable
key={i}
scroll={scroll}
index={i}
count={count}
alpha={alpha}
k={k}
projection={projection}
gap={gap}
edgeOffset={edgeOffset}
minScale={minScale}
convex={convex}
arc={arc}
halfWidth={halfWidth}
itemSize={size}
>
{item}
</CarouselBall>
))}
</div>
);
}
Install
Add it with the shadcn CLI, or copy the source manually.
shadcn init? You are set. Theme setupInstall dependencies
npm i @paper-design/shaders-react clsx motion tailwind-mergeAdd util files
// Shared touch primitives. iOS and iPadOS run their own gestures on top of the
// page — the long-press selection callout and the selection it drags in with
// it — and they win: once the platform claims a touch it cancels ours
// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own
// their gesture have to opt out.
//
// What the two classes below cover, precisely:
// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:
// it is not a property other engines have, so it is inert everywhere else.
// - `user-select: none` stops the long-press selection on every engine,
// Android included, and stops a drag from painting a selection under the
// cursor. It is inherited, so it reaches every descendant — which is why the
// two classes differ only in whether they apply it unconditionally.
// What neither covers:
// - Chrome for Android's long-press menu on a link or an image. No CSS
// suppresses it; a gesture surface that wraps one needs its own
// `onContextMenu` with `preventDefault()`.
// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is
// not inherited and plain divs and buttons are not drag sources, so setting
// it on the surface does nothing — the child itself needs `draggable={false}`.
/**
* Classes for a surface that *is* the control: a thumb, a drum, a stage, a
* handle, a hold button. Selection is suppressed on every input, because a
* drag that highlights the control's own label is wrong on a mouse too.
* Compose with `touch-none` when the surface also owns the scroll axis — leave
* it off when the page must still scroll from there.
*/
export const TOUCH_GESTURE_CLASS = "select-none [-webkit-touch-callout:none]";
/**
* The same opt-out for a gesture surface that wraps content the consumer owns:
* a scroller, a context-menu trigger, a sheet header, a list row. Selection is
* suppressed only where the platform runs its own press gestures — a coarse
* pointer — so a mouse user can still select and copy that content. If the
* gesture itself would paint a selection under the cursor, add `select-none`
* for the duration of the gesture rather than reaching for
* `TOUCH_GESTURE_CLASS`.
*
* `pointer: coarse` describes the *primary* pointer and nothing else, so a
* hybrid machine reads it wrong in both directions: a tablet with a mouse
* plugged in keeps touch as primary and loses mouse selection, and a laptop
* with a touchscreen keeps the mouse as primary and leaves selection live
* under a finger. No media query can answer per interaction — the query is
* about the device, and the question is about the gesture in progress. The
* default stays here because it is right on the machines that are one thing or
* the other, and losing a selection is a nuisance; where the miss costs a
* *gesture* instead, the surface pairs it with `holdSelection` on the press.
*/
export const TOUCH_GESTURE_CONTENT_CLASS =
"[-webkit-touch-callout:none] pointer-coarse:select-none";
/**
* Suppress selection on `element` for as long as a gesture is running on it,
* whatever the primary pointer of the machine happens to be. Returns the
* release. Inline, so it wins over the class above and is gone again the
* moment the gesture ends.
*
* For the press gestures a native selection would otherwise steal — a
* long-press that opens a menu. Elsewhere prefer the classes: a surface that
* takes selection away for the whole session is a surface whose text nobody
* can copy.
*/
export function holdSelection(element: HTMLElement) {
element.style.setProperty("user-select", "none");
element.style.setProperty("-webkit-user-select", "none");
return () => {
element.style.removeProperty("user-select");
element.style.removeProperty("-webkit-user-select");
};
}
/**
* Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer
* is already gone by the time the handler runs — routine on iOS, where the
* system can claim the touch first — and an uncaught throw takes the rest of
* the handler, the gesture included, down with it. Touch pointers carry
* implicit capture anyway, so losing it is never fatal.
*/
export function capturePointer(element: Element, pointerId: number) {
try {
element.setPointerCapture(pointerId);
} catch {
// Pointer is no longer active — implicit capture still applies on touch.
}
}
/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */
export function releasePointer(element: Element, pointerId: number) {
try {
if (element.hasPointerCapture(pointerId)) {
element.releasePointerCapture(pointerId);
}
} catch {
// Capture was already dropped by the browser.
}
}
/**
* Whether this event came from a pointer that is *hovering*: not a touch, and
* not currently pressed. Which input the user is holding right now is not
* something a device capability can answer — a touchscreen laptop hovers and
* taps, and iPadOS reports a fine hovering pointer for a finger — so both
* paths stay live and each handler branches on the event it was given.
*
* A pen resting on the glass is making contact, not hovering: `buttons` is the
* tell, and it sends a pen tap down the same route a finger takes.
*
* This answers what an *enter* asks. A leave is the other half of a pair and
* has to be read against the enter that started it — `useHoverGesture` in
* `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it
* rather than asking this question twice.
*/
export const isHoveringPointer = (event: {
pointerType: string;
buttons: number;
}) => event.pointerType !== "touch" && event.buttons === 0;
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
// Shared motion tokens. Easing curves mirror the CSS custom properties in
// globals.css; springs are the canonical physics used across components.
// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
export const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;
export const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;
/** CSS string form of EASE_OUT for inline style transitions. */
export const EASE_OUT_CSS = "cubic-bezier(0.16, 1, 0.3, 1)";
/** Press feedback on buttons and other tappable surfaces. */
export const SPRING_PRESS = {
type: "spring",
stiffness: 500,
damping: 30,
mass: 0.6,
} as const;
/** Content swaps — label/icon slots trading places inside a control. */
export const SPRING_SWAP = {
type: "spring",
stiffness: 460,
damping: 30,
mass: 0.55,
} as const;
/** Overlay panel entrances — modals and sheets summoned by pointer. */
export const SPRING_PANEL = {
type: "spring",
stiffness: 420,
damping: 40,
mass: 0.5,
} as const;
/** Shared-layout glides — pills, indicators and panels morphing between positions. */
export const SPRING_LAYOUT = {
type: "spring",
stiffness: 360,
damping: 32,
mass: 0.6,
} as const;
/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */
export const SPRING_MOUSE = {
stiffness: 200,
damping: 15,
mass: 0.3,
} as const;
/** Dragged handles and fills (sliders) — critically damped `useSpring` config,
* so the value follows the pointer butterily and never rebounds off an end. */
export const SPRING_GLIDE = {
stiffness: 700,
damping: 50,
mass: 0.5,
} as const;
Copy the source code
"use client";
// beui.dev/components/motion/cylinder-carousel
import {
animate,
type AnimationPlaybackControls,
motion,
type MotionValue,
useMotionValue,
useReducedMotion,
useTransform,
} from "motion/react";
import {
Children,
type PointerEvent as ReactPointerEvent,
type ReactNode,
useCallback,
useEffect,
useRef,
useState,
type WheelEvent as ReactWheelEvent,
} from "react";
import {
capturePointer,
releasePointer,
TOUCH_GESTURE_CLASS,
} from "@/lib/touch";
import { cn } from "@/lib/utils";
// Carousel-specific: a soft spring that receives the release velocity, so a
// flick keeps rolling freely, drifts past the snap point and eases back.
const GLIDE_SPRING = { stiffness: 40, damping: 20, mass: 3 };
// How far a flick keeps rolling: projected items = release velocity * momentum.
const FLICK_MOMENTUM = 0.45;
const MAX_FLICK_ITEMS = 6;
export interface CylinderCarouselProps {
children: ReactNode;
/** Max item box size in px (square) at full size, i.e. at the container
* edge. Balls shrink below this automatically so the row keeps breathing
* room in narrow containers. */
itemSize?: number;
/** How many item slots span the container width. */
visibleItems?: number;
/** "concave" (default): inside of the cylinder — center ball smallest and
* dipped, growing toward the edges. "convex": outside of the cylinder —
* center ball biggest and raised, shrinking toward the edges. */
variant?: "concave" | "convex";
/** Scale of the smallest ball (center for concave, edges for convex);
* the biggest reaches 1. */
minScale?: number;
/** Items rolled per item-width dragged — above 1 the wall outruns the
* pointer, which reads as a lighter, freer roll. */
dragSpeed?: number;
/** Curve depth in px: for concave, how far the edge balls ride above the
* center one (valley); for convex, how far below (arch). 0 = flat line.
* Defaults to 35% of the item size. */
arc?: number;
/** Snap to the nearest item when the roll settles. */
snap?: boolean;
/** Roll on its own until interacted with. */
autoRotate?: boolean;
/** Auto-roll speed in items per second. */
autoRotateSpeed?: number;
defaultIndex?: number;
onIndexChange?: (index: number) => void;
/** Stage height in px. Defaults to `itemSize`. */
height?: number;
className?: string;
}
// The frame edge sits at this wall angle; how far the wall curves in frame.
const THETA_EDGE = (72 * Math.PI) / 180;
// Wall angle past which a ball is parked far off-stage (always hidden there).
const THETA_CLAMP = (95 * Math.PI) / 180;
/**
* One ball on the inside wall of the cylinder, rendered through a single
* perspective projection: the ball sits at wall angle θ, the camera slightly
* above the ball line, so horizontal position, size and height all share one
* 1/(cosθ + k) depth term. Center = far wall: smallest, highest, moving
* slowest; edges = nearest: full size, level, moving fastest, sliding off to
* be clipped. Nothing overlaps, fades or reorders — the edge is the exit.
*/
function CarouselBall({
scroll,
index,
count,
alpha,
k,
projection,
gap,
edgeOffset,
minScale,
convex,
arc,
halfWidth,
itemSize,
children,
}: {
scroll: MotionValue<number>;
index: number;
count: number;
/** Wall angle per item step, in radians. */
alpha: number;
/** Camera distance term for the horizontal projection. */
k: number;
/** Projection strength: maps sinθ/(cosθ+k) to px so θE lands on the edge. */
projection: number;
/** Uniform slot width in px — convex spacing. */
gap: number;
/** Offset at which a ball's center sits on the container edge. */
edgeOffset: number;
minScale: number;
convex: boolean;
/** Curve depth in px between the center ball and the edge balls. */
arc: number;
halfWidth: number;
itemSize: number;
children: ReactNode;
}) {
// Nearest wrapped offset so items loop around continuously.
const offset = useTransform(scroll, (s) => {
let o = index - s;
o -= Math.round(o / count) * count;
return o;
});
// Concave spacing follows the interior perspective (slow, tight center);
// convex pairs its big center balls with uniform spacing — the interior
// projection would collapse them into each other.
const x = useTransform(offset, (o) => {
if (convex) return o * gap;
const th = Math.max(-THETA_CLAMP, Math.min(THETA_CLAMP, o * alpha));
return (projection * Math.sin(th)) / (Math.cos(th) + k);
});
// Linear in wall angle, not in depth (the depth curve is near-flat around
// the center, which made the middle three read as equal): every step is
// visibly bigger than the last — growing outward (concave) or inward
// (convex).
const scale = useTransform(offset, (o) => {
const t = Math.min(Math.abs(o) / edgeOffset, THETA_CLAMP / THETA_EDGE);
return convex
? 1 - (1 - minScale) * t
: minScale + (1 - minScale) * t;
});
// Parabola centered on the stage — valley for concave (center ball dips
// arc/2 below the midline, edges rise arc/2 above), arch for convex — and
// deliberately unclamped: a ball keeps following the same curve as it
// crosses the edge, so entries never pop.
const y = useTransform(x, (px) => {
const t = px / halfWidth;
const valley = arc * (0.5 - t * t);
return convex ? -valley : valley;
});
// Fully off-stage balls stop painting (matters for canvas/shader children).
const visibility = useTransform(x, (px) =>
Math.abs(px) > halfWidth + itemSize ? "hidden" : "visible",
);
return (
<motion.div
className="absolute top-1/2 left-1/2"
style={{
x,
y,
scale,
visibility,
width: itemSize,
height: itemSize,
marginLeft: -itemSize / 2,
marginTop: -itemSize / 2,
}}
>
{children}
</motion.div>
);
}
export function CylinderCarousel({
children,
itemSize = 200,
visibleItems = 5,
variant = "concave",
minScale = 0.55,
dragSpeed = 1.5,
arc: arcProp,
snap = true,
autoRotate = false,
autoRotateSpeed = 0.4,
defaultIndex = 0,
onIndexChange,
height,
className,
}: CylinderCarouselProps) {
const reduce = useReducedMotion() ?? false;
const items = Children.toArray(children);
const count = items.length;
const stageRef = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(0);
useEffect(() => {
const el = stageRef.current;
if (!el) return;
const ro = new ResizeObserver(([entry]) => {
setWidth(entry.contentRect.width);
});
ro.observe(el);
return () => ro.disconnect();
}, []);
// Sized so `visibleItems` balls sit fully in frame and the next one out on
// each side straddles the container edge, half visible.
const stageWidth = width || 800;
const halfWidth = stageWidth / 2;
const edgeOffset = (visibleItems + 1) / 2;
// Fit: the resting row's diameters may take at most ~66% of the stage — the
// rest is air between balls plus the half-visible ball on each edge.
// `itemSize` only caps the result.
const convex = variant === "convex";
let scaleSum = 0;
for (let i = 0; i < visibleItems; i++) {
const t = Math.abs(i - (visibleItems - 1) / 2) / edgeOffset;
scaleSum += convex
? 1 - (1 - minScale) * t
: minScale + (1 - minScale) * t;
}
const size = Math.min(itemSize, (stageWidth * 0.65) / scaleSum);
const gap = stageWidth / (visibleItems + 1);
const arc = arcProp ?? size * 0.35;
// Perspective constants. The ball one slot past the frame edge sits at wall
// angle THETA_EDGE with its center right on the container edge — scale 1,
// half of it in view; k falls out of the requested minScale (clamped so the
// projection stays monotonic up to THETA_CLAMP).
const alpha = THETA_EDGE / edgeOffset;
const k = Math.max(0.2, (minScale - Math.cos(THETA_EDGE)) / (1 - minScale));
const projection =
(halfWidth * (Math.cos(THETA_EDGE) + k)) / Math.sin(THETA_EDGE);
// scroll is in item units (continuous); item i sits at x = (i - scroll) * gap.
// Drags write it 1:1 so the wall sticks to the pointer; releases hand the
// pointer velocity to a soft spring so the roll glides on and settles free.
const scroll = useMotionValue(defaultIndex);
const indexRef = useRef(defaultIndex);
const [, setActiveIndex] = useState(defaultIndex);
const glideRef = useRef<AnimationPlaybackControls | null>(null);
const draggingRef = useRef(false);
const hoverRef = useRef(false);
useEffect(() => {
if (count === 0) return;
const unsub = scroll.on("change", (v) => {
const idx = ((Math.round(v) % count) + count) % count;
if (idx !== indexRef.current) {
indexRef.current = idx;
setActiveIndex(idx);
onIndexChange?.(idx);
}
});
return unsub;
}, [scroll, count, onIndexChange]);
const stopGlide = useCallback(() => {
glideRef.current?.stop();
glideRef.current = null;
}, []);
// Spring toward `to`, carrying `velocity` (items/s) through so motion never
// steps — the roll leaves the finger at finger speed.
const glideTo = useCallback(
(to: number, velocity: number) => {
stopGlide();
if (reduce) {
scroll.set(to);
return;
}
glideRef.current = animate(scroll, to, {
type: "spring",
...GLIDE_SPRING,
velocity,
restDelta: 0.001,
restSpeed: 0.005,
});
},
[scroll, stopGlide, reduce],
);
const settle = useCallback(
(velocity: number) => {
const projected =
scroll.get() +
Math.max(
-MAX_FLICK_ITEMS,
Math.min(MAX_FLICK_ITEMS, velocity * FLICK_MOMENTUM),
);
glideTo(snap ? Math.round(projected) : projected, velocity);
},
[scroll, snap, glideTo],
);
const drag = useRef({
startX: 0,
startScroll: 0,
lastX: 0,
lastT: 0,
prevX: 0,
prevT: 0,
});
const onPointerDown = useCallback(
(e: ReactPointerEvent) => {
e.preventDefault();
stopGlide();
draggingRef.current = true;
capturePointer(e.currentTarget, e.pointerId);
const now = performance.now();
drag.current = {
startX: e.clientX,
startScroll: scroll.get(),
lastX: e.clientX,
lastT: now,
prevX: e.clientX,
prevT: now,
};
},
[scroll, stopGlide],
);
const onPointerMove = useCallback(
(e: ReactPointerEvent) => {
if (!draggingRef.current) return;
const d = drag.current;
scroll.set(d.startScroll - ((e.clientX - d.startX) * dragSpeed) / gap);
d.prevX = d.lastX;
d.prevT = d.lastT;
d.lastX = e.clientX;
d.lastT = performance.now();
},
[scroll, gap, dragSpeed],
);
const onPointerUp = useCallback(
(e: ReactPointerEvent) => {
if (!draggingRef.current) return;
draggingRef.current = false;
releasePointer(e.currentTarget, e.pointerId);
const d = drag.current;
const dt = d.lastT - d.prevT;
const vpx = dt > 0 ? (d.lastX - d.prevX) / dt : 0; // px per ms
settle((-vpx * dragSpeed * 1000) / gap); // items per second
},
[settle, gap, dragSpeed],
);
const rollBy = useCallback(
(dir: number) => {
glideTo(Math.round(scroll.get()) + dir, scroll.getVelocity());
},
[scroll, glideTo],
);
const wheelSettleRef = useRef<number | undefined>(undefined);
const onWheel = useCallback(
(e: ReactWheelEvent) => {
stopGlide();
const delta =
Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;
scroll.set(scroll.get() + delta / gap);
if (wheelSettleRef.current) window.clearTimeout(wheelSettleRef.current);
wheelSettleRef.current = window.setTimeout(
() => settle(scroll.getVelocity()),
140,
);
},
[scroll, gap, settle, stopGlide],
);
useEffect(() => {
if (!autoRotate || reduce || count === 0) return;
let raf = 0;
let last = performance.now();
const tick = (now: number) => {
const dt = (now - last) / 1000;
last = now;
if (!draggingRef.current && !hoverRef.current && !glideRef.current) {
scroll.set(scroll.get() + autoRotateSpeed * dt);
}
raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, [autoRotate, autoRotateSpeed, reduce, count, scroll]);
const stageHeight = height ?? size;
return (
<div
ref={stageRef}
role="application"
aria-roledescription="carousel"
// biome-ignore lint/a11y/noNoninteractiveTabindex: focusable custom carousel widget
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "ArrowRight") {
e.preventDefault();
rollBy(1);
} else if (e.key === "ArrowLeft") {
e.preventDefault();
rollBy(-1);
}
}}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={onPointerUp}
onWheel={onWheel}
onPointerEnter={() => {
hoverRef.current = true;
}}
onPointerLeave={() => {
hoverRef.current = false;
}}
className={cn(
// clip-path, not overflow: it also clips the GPU-composited balls
"relative w-full touch-none outline-none [clip-path:inset(0)]",
// The stage drives the roll from the press itself, so iOS must not
// claim the same touch for its callout or a slide drag.
TOUCH_GESTURE_CLASS,
"cursor-grab active:cursor-grabbing",
"focus-visible:ring-2 focus-visible:ring-foreground/20",
className,
)}
style={{ height: stageHeight }}
>
{items.map((item, i) => (
<CarouselBall
// biome-ignore lint/suspicious/noArrayIndexKey: slides are positional and stable
key={i}
scroll={scroll}
index={i}
count={count}
alpha={alpha}
k={k}
projection={projection}
gap={gap}
edgeOffset={edgeOffset}
minScale={minScale}
convex={convex}
arc={arc}
halfWidth={halfWidth}
itemSize={size}
>
{item}
</CarouselBall>
))}
</div>
);
}
"use client";
import {
ColorPanels,
type ColorPanelsProps,
Dithering,
type DitheringProps,
DotGrid,
type DotGridProps,
DotOrbit,
type DotOrbitProps,
GodRays,
type GodRaysProps,
GrainGradient,
type GrainGradientProps,
Metaballs,
type MetaballsProps,
MeshGradient,
type MeshGradientProps,
NeuroNoise,
type NeuroNoiseProps,
PerlinNoise,
type PerlinNoiseProps,
PulsingBorder,
type PulsingBorderProps,
SimplexNoise,
type SimplexNoiseProps,
SmokeRing,
type SmokeRingProps,
Spiral,
type SpiralProps,
StaticMeshGradient,
type StaticMeshGradientProps,
StaticRadialGradient,
type StaticRadialGradientProps,
Swirl,
type SwirlProps,
Voronoi,
type VoronoiProps,
Warp,
type WarpProps,
Water,
type WaterProps,
Waves,
type WavesProps,
} from "@paper-design/shaders-react";
import { useReducedMotion } from "motion/react";
import type { ComponentType } from "react";
import { cn } from "@/lib/utils";
type ShaderVariantProps = {
"mesh-gradient": MeshGradientProps;
"grain-gradient": GrainGradientProps;
"dot-grid": DotGridProps;
"dot-orbit": DotOrbitProps;
warp: WarpProps;
waves: WavesProps;
water: WaterProps;
voronoi: VoronoiProps;
swirl: SwirlProps;
"smoke-ring": SmokeRingProps;
"static-radial-gradient": StaticRadialGradientProps;
"neuro-noise": NeuroNoiseProps;
metaballs: MetaballsProps;
"god-rays": GodRaysProps;
spiral: SpiralProps;
dithering: DitheringProps;
"pulsing-border": PulsingBorderProps;
"color-panels": ColorPanelsProps;
"static-mesh-gradient": StaticMeshGradientProps;
"simplex-noise": SimplexNoiseProps;
"perlin-noise": PerlinNoiseProps;
};
export type ShaderBackgroundVariant = keyof ShaderVariantProps;
export type ShaderBackgroundProps = {
[K in ShaderBackgroundVariant]: { variant: K } & ShaderVariantProps[K];
}[ShaderBackgroundVariant];
const VARIANT_COMPONENTS: {
[K in ShaderBackgroundVariant]: ComponentType<ShaderVariantProps[K]>;
} = {
"mesh-gradient": MeshGradient,
"grain-gradient": GrainGradient,
"dot-grid": DotGrid,
"dot-orbit": DotOrbit,
warp: Warp,
waves: Waves,
water: Water,
voronoi: Voronoi,
swirl: Swirl,
"smoke-ring": SmokeRing,
"static-radial-gradient": StaticRadialGradient,
"neuro-noise": NeuroNoise,
metaballs: Metaballs,
"god-rays": GodRays,
spiral: Spiral,
dithering: Dithering,
"pulsing-border": PulsingBorder,
"color-panels": ColorPanels,
"static-mesh-gradient": StaticMeshGradient,
"simplex-noise": SimplexNoise,
"perlin-noise": PerlinNoise,
};
export const SHADER_BACKGROUND_VARIANTS = Object.keys(
VARIANT_COMPONENTS,
) as ShaderBackgroundVariant[];
/**
* Not every variant animates (e.g. dot-grid is a static pattern), so `speed`
* is only frozen for reduced motion when the variant actually exposes it.
*/
export function ShaderBackground({
variant,
className,
...rest
}: ShaderBackgroundProps) {
const reducedMotion = useReducedMotion();
const Shader = VARIANT_COMPONENTS[variant] as ComponentType<
Record<string, unknown>
>;
const props = rest as Record<string, unknown>;
const speedProps = reducedMotion && "speed" in props ? { speed: 0 } : {};
return (
<Shader
{...props}
{...speedProps}
className={cn("h-full w-full", className)}
/>
);
}
"use client";
import { motion, MotionConfig, useReducedMotion, type Transition } from "motion/react";
import {
createContext,
useCallback,
useContext,
useId,
useMemo,
useState,
type ReactNode,
} from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
type Variant = "pill" | "underline" | "segment";
type Ctx = {
value: string;
setValue: (v: string) => void;
layoutId: string;
variant: Variant;
};
const TabsCtx = createContext<Ctx | null>(null);
function useTabs() {
const ctx = useContext(TabsCtx);
if (!ctx) throw new Error("Tabs.* must be used inside <Tabs>");
return ctx;
}
// Weighty spring for the active-tab indicator: a touch of overshoot so it
// settles with life instead of snapping.
const transition: Transition = {
type: "spring",
stiffness: 170,
damping: 24,
mass: 1.2,
};
export function Tabs({
defaultValue,
value,
onValueChange,
variant = "pill",
children,
className,
}: {
defaultValue?: string;
value?: string;
onValueChange?: (v: string) => void;
variant?: Variant;
children: ReactNode;
className?: string;
}) {
const [internal, setInternal] = useState(defaultValue ?? "");
const layoutId = useId();
const reduce = useReducedMotion();
const controlled = value !== undefined;
const current = controlled ? value : internal;
const setValue = useCallback(
(v: string) => {
if (!controlled) setInternal(v);
onValueChange?.(v);
},
[controlled, onValueChange],
);
const contextValue = useMemo(
() => ({ value: current, setValue, layoutId, variant }),
[current, layoutId, setValue, variant],
);
return (
<MotionConfig transition={reduce ? { duration: 0 } : transition}>
<TabsCtx.Provider value={contextValue}>
{/* layoutRoot: the indicator's layoutId measures in page coordinates, so
inside fixed/scrolled containers it would replay scroll offsets as
movement. The pill only ever travels within the list, so scoping
projection to the Tabs wrapper is always correct. */}
<motion.div layoutRoot className={className}>
{children}
</motion.div>
</TabsCtx.Provider>
</MotionConfig>
);
}
const listClasses: Record<Variant, string> = {
pill: "inline-flex items-center gap-1 rounded-full bg-card p-1",
underline: "inline-flex items-center gap-1 border-b border-border",
segment: "inline-flex items-center gap-0 rounded-lg bg-card p-0.5",
};
export function TabsList({ children, className }: { children: ReactNode; className?: string }) {
const { variant } = useTabs();
return (
<div role="tablist" className={cn(listClasses[variant], className)}>
{children}
</div>
);
}
export function TabsTrigger({
value,
children,
className,
indicatorClassName,
}: {
value: string;
children: ReactNode;
className?: string;
indicatorClassName?: string;
}) {
const { value: current, setValue, layoutId, variant } = useTabs();
const active = current === value;
if (variant === "underline") {
return (
<button
type="button"
role="tab"
aria-selected={active}
onClick={() => setValue(value)}
className={cn(
"relative isolate px-3 pb-2.5 pt-1 -mb-px text-sm font-medium transition-colors min-h-[44px] inline-flex items-center",
active ? "text-foreground" : "text-muted-foreground hover:text-foreground",
className,
)}
>
{children}
{active ? (
<motion.span
layoutId={layoutId}
layout="position"
className={cn(
"absolute -bottom-px left-0 right-0 h-px bg-primary",
indicatorClassName,
)}
/>
) : null}
</button>
);
}
const radius = variant === "pill" ? "rounded-full" : "rounded-md";
return (
<div className="relative">
{active ? (
<motion.span
layoutId={layoutId}
layout="position"
style={{ borderRadius: variant === "pill" ? 9999 : 8 }}
className={cn(
"absolute inset-0 bg-primary",
radius,
indicatorClassName,
)}
/>
) : null}
<button
type="button"
role="tab"
aria-selected={active}
onClick={() => setValue(value)}
className={cn(
"relative z-10 inline-flex items-center justify-center whitespace-nowrap bg-transparent px-3.5 py-1.5 text-sm font-medium outline-none",
"transition-colors",
active
? "text-primary-foreground"
: "text-muted-foreground hover:text-foreground",
radius,
className,
)}
>
{children}
</button>
</div>
);
}
export function TabsContent({ value, children, className }: { value: string; children: ReactNode; className?: string }) {
const { value: current } = useTabs();
const reduce = useReducedMotion();
const active = current === value;
// Inactive panels stay mounted but hidden, so their content (e.g. source
// code) is present in the server-rendered HTML for crawlers and assistive
// tech, instead of being dropped from the DOM.
if (!active) {
return (
<div hidden className={className}>
{children}
</div>
);
}
return (
<motion.div
key={value}
initial={{ opacity: 0, y: reduce ? 0 : 4 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.18, ease: EASE_OUT }}
className={cn("mt-4", className)}
>
{children}
</motion.div>
);
}
API Reference
itemSize?numberMax item box size in px (square) at full size, i.e. at the container edge. Balls shrink below this automatically so the row keeps breathing room in narrow containers.
200visibleItems?numberHow many item slots span the container width.
5variant?"concave" | "convex""concave" (default): inside of the cylinder — center ball smallest and dipped, growing toward the edges. "convex": outside of the cylinder — center ball biggest and raised, shrinking toward the edges.
concaveminScale?numberScale of the smallest ball (center for concave, edges for convex); the biggest reaches 1.
0.55dragSpeed?numberItems rolled per item-width dragged — above 1 the wall outruns the pointer, which reads as a lighter, freer roll.
1.5arc?numberCurve depth in px: for concave, how far the edge balls ride above the center one (valley); for convex, how far below (arch). 0 = flat line. Defaults to 35% of the item size.
—snap?booleanSnap to the nearest item when the roll settles.
trueautoRotate?booleanRoll on its own until interacted with.
falseautoRotateSpeed?numberAuto-roll speed in items per second.
0.4defaultIndex?number0onIndexChange?((index: number) => void)—height?numberStage height in px. Defaults to `itemSize`.
—className?string—Updated