Cylinder Carousel
NewA 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.
Drag, scroll or use arrow keys to roll
TSXcomponents/previews/motion/cylinder-carousel.preview.tsx
"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>
);
}
TSXcomponents/motion/cylinder-carousel.tsx
"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 { 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;
e.currentTarget.setPointerCapture(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;
if (e.currentTarget.hasPointerCapture(e.pointerId)) {
e.currentTarget.releasePointerCapture(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 (
<>
{/* biome-ignore lint/a11y/noStaticElementInteractions: custom draggable + keyboard carousel */}
<div
ref={stageRef}
// 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 select-none outline-none [clip-path:inset(0)]",
"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.
$ bunx --bun shadcn add @beui/cylinder-carousel
Needs the theme tokens once. Already ran
shadcn init? You are set. Theme setupInstall dependencies
npm i @paper-design/shaders-react clsx motion tailwind-mergeAdd util files
TSXlib/utils.ts
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
TSXlib/ease.ts
// 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;
Copy the source code
TSXcomponents/motion/cylinder-carousel.tsx
"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 { 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;
e.currentTarget.setPointerCapture(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;
if (e.currentTarget.hasPointerCapture(e.pointerId)) {
e.currentTarget.releasePointerCapture(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 (
<>
{/* biome-ignore lint/a11y/noStaticElementInteractions: custom draggable + keyboard carousel */}
<div
ref={stageRef}
// 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 select-none outline-none [clip-path:inset(0)]",
"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>
</>
);
}
TSXcomponents/motion/shader-background.tsx
"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)}
/>
);
}
TSXcomponents/motion/tabs.tsx
"use client";
import { motion, MotionConfig, useReducedMotion, type Transition } from "motion/react";
import { createContext, useContext, useId, 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 = (v: string) => {
if (!controlled) setInternal(v);
onValueChange?.(v);
};
return (
<MotionConfig transition={reduce ? { duration: 0 } : transition}>
<TabsCtx.Provider value={{ value: current, setValue, layoutId, variant }}>
{/* 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;
const usesDefaultIndicator = indicatorClassName === undefined;
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}
className={cn(
"absolute -bottom-px left-0 right-0 h-px bg-primary",
indicatorClassName,
)}
/>
) : null}
</button>
);
}
// The default max-contrast pill uses exclusion so labels invert exactly as
// the indicator passes beneath them. Custom indicators retain explicit text
// colors because their background may not be suitable for blending.
const radius = variant === "pill" ? "rounded-full" : "rounded-md";
return (
<div className="relative">
{active ? (
<motion.span
layoutId={layoutId}
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",
usesDefaultIndicator
? "text-white mix-blend-exclusion transition-opacity"
: "transition-colors",
usesDefaultIndicator
? active
? "opacity-100"
: "opacity-70 hover:opacity-100"
: 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>
);
}