Fling gallery
A horizontal strip of rounded image frames you can grab and throw. Drag, horizontal scroll or the arrow keys move it, and a throw keeps its speed then slows with smooth friction. Loop mode repeats the set seamlessly and drifts at an idle pace, picking the drift back up after a throw; free mode has springy ends. Images sit wider than their frames and slide against the motion for depth, frames lean slightly in the direction of a fast throw, and a caption fades in under the centre frame once the strip comes to rest. Items without images get a generated gradient from your chart colours. It is a labelled carousel with focusable slides, a drag never triggers a click, hover and focus pause the drift, a pause button appears when it moves on its own, and reduced motion steps item by item without drift, inertia or parallax.
Source
"use client";
import { useCallback, useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type PointerEvent } from "react";
import { ChevronLeft, ChevronRight, Pause, Play } from "lucide-react";
import { cn } from "@/lib/utils";
export type FlingItem = {
/** Image URL. Leave it out to paint a generated gradient instead. */
src?: string;
alt: string;
title: string;
href?: string;
/** Any CSS background, used when there is no `src`. */
gradient?: string;
};
export type FlingGalleryProps = {
items: FlingItem[];
/** Accessible name for the carousel. */
label?: string;
aspect?: "portrait" | "landscape" | "square";
/** "loop" repeats forever and drifts at idle; "free" has soft, springy ends. */
mode?: "loop" | "free";
/** Idle drift in pixels per second (loop mode). 0 turns it off. */
autoSpeed?: number;
/** How far images slide inside their frames, 0 to 0.3. */
parallax?: number;
/** Lean frames in the direction of travel while the strip is moving fast. */
tilt?: boolean;
/** Space between frames, in pixels. */
gap?: number;
/** Called when an item without `href` is chosen. */
onSelect?: (item: FlingItem, index: number) => void;
className?: string;
};
const FRICTION = 2.4; // per second: how quickly a throw loses speed
const DRAG_SLOP = 6; // pixels a press may move and still count as a click
function hash(value: string) {
let h = 2166136261;
for (let i = 0; i < value.length; i++) h = Math.imul(h ^ value.charCodeAt(i), 16777619);
return h >>> 0;
}
/** An abstract "artwork" painted from the chart tokens, so frames need no remote images. */
export function artworkGradient(seed: string) {
const h = hash(seed);
const c = (k: number) => `var(--chart-${((h >>> (k * 3)) % 5) + 1})`;
const a = h % 360;
const x = 22 + ((h >>> 7) % 56);
const y = 18 + ((h >>> 11) % 50);
const deep = (k: number) => `color-mix(in oklab, ${c(k)} 62%, #0b0b10)`;
switch (h % 3) {
case 0:
return `radial-gradient(circle at ${x}% ${y}%, ${c(0)} 0 16%, transparent 16.5%), radial-gradient(110% 80% at ${100 - x}% 100%, ${c(1)}, transparent 62%), linear-gradient(${a}deg, ${deep(2)}, ${c(3)})`;
case 1:
return `repeating-linear-gradient(${a}deg, transparent 0 18px, color-mix(in oklab, ${c(4)} 30%, transparent) 18px 20px), radial-gradient(90% 70% at ${x}% ${y}%, ${c(0)}, transparent 70%), linear-gradient(180deg, ${c(1)}, ${deep(2)})`;
default:
return `radial-gradient(70% 45% at ${x}% ${y}%, color-mix(in oklab, ${c(4)} 55%, transparent), transparent 70%), linear-gradient(180deg, ${c(0)} 0%, ${c(0)} 30%, ${c(1)} 44%, ${c(1)} 62%, ${deep(2)} 76%, ${deep(3)} 100%)`;
}
}
function frameSize(aspect: NonNullable<FlingGalleryProps["aspect"]>, viewport: number) {
const clamp = (min: number, value: number, max: number) => Math.max(min, Math.min(max, value));
if (aspect === "landscape") {
const w = Math.round(clamp(240, viewport * 0.68, 360));
return { w, h: Math.round(w * 0.66) };
}
if (aspect === "square") {
const w = Math.round(clamp(160, viewport * 0.42, 250));
return { w, h: w };
}
const w = Math.round(clamp(148, viewport * 0.36, 228));
return { w, h: Math.round(w * 1.32) };
}
function useReducedMotion() {
const [reduce, setReduce] = useState(false);
useEffect(() => {
const query = window.matchMedia?.("(prefers-reduced-motion: reduce)");
if (!query) return;
setReduce(query.matches);
const on = () => setReduce(query.matches);
query.addEventListener("change", on);
return () => query.removeEventListener("change", on);
}, []);
return reduce;
}
const mod = (a: number, n: number) => ((a % n) + n) % n;
export function FlingGallery({
items,
label = "Gallery",
aspect = "portrait",
mode = "loop",
autoSpeed = 28,
parallax = 0.18,
tilt = true,
gap = 18,
onSelect,
className,
}: FlingGalleryProps) {
const reduce = useReducedMotion();
const viewport = useRef<HTMLDivElement>(null);
const frames = useRef<(HTMLDivElement | null)[]>([]);
const cards = useRef<(HTMLDivElement | null)[]>([]);
const arts = useRef<(HTMLDivElement | null)[]>([]);
const captions = useRef<(HTMLDivElement | null)[]>([]);
const fade = useRef<number[]>([]);
const [size, setSize] = useState({ vw: 0, w: 0, h: 0, copies: 1 });
const [paused, setPaused] = useState(false);
const n = items.length;
const stride = size.w + gap;
const count = n * size.copies;
const loop = mode === "loop";
const pad = 16;
// Motion state lives in refs: the frame loop writes styles directly instead of re-rendering React.
const s = useRef({ x: 0, v: 0, target: null as number | null, tilt: 0, started: false });
const pointer = useRef({ down: false, id: -1, startX: 0, lastX: 0, lastT: 0, moved: false, cancelClick: false });
const hold = useRef({ hover: false, focus: false });
const live = useRef({ reduce, paused, size, stride, count, loop, autoSpeed, parallax, tilt, n, pad });
live.current = { reduce, paused, size, stride, count, loop, autoSpeed, parallax, tilt, n, pad };
const bounds = useCallback(() => {
const { size: z, stride: st, n: total, pad: p } = live.current;
const content = total * st - gap;
return { max: p, min: Math.min(p, z.vw - p - content) };
}, [gap]);
const positionOf = useCallback((k: number, x: number) => {
const { stride: st, count: c, loop: l } = live.current;
return l ? mod(k * st + x, c * st) - st : k * st + x;
}, []);
const nearest = useCallback(() => {
const { size: z, count: c } = live.current;
let best = 0;
let dist = Infinity;
for (let k = 0; k < c; k++) {
const d = Math.abs(positionOf(k, s.current.x) + z.w / 2 - z.vw / 2);
if (d < dist) {
dist = d;
best = k;
}
}
return best;
}, [positionOf]);
const goTo = useCallback((k: number) => {
const { size: z, loop: l, reduce: r } = live.current;
const state = s.current;
let target = state.x + ((z.vw - z.w) / 2 - positionOf(k, state.x));
if (!l) {
const b = bounds();
target = Math.max(b.min, Math.min(b.max, target));
}
state.v = 0;
if (r) {
state.x = target;
state.target = null;
} else state.target = target;
}, [bounds, positionOf]);
// Size frames from the viewport width, and repeat the set when a loop would otherwise show a gap.
useLayoutEffect(() => {
const node = viewport.current;
if (!node) return;
const measure = () => {
const vw = node.clientWidth;
const { w, h } = frameSize(aspect, vw);
const set = n * (w + gap);
const copies = loop && set > 0 ? Math.max(1, Math.ceil((vw + 3 * (w + gap)) / set)) : 1;
setSize((prev) => (prev.vw === vw && prev.w === w && prev.copies === copies ? prev : { vw, w, h, copies }));
};
measure();
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure);
observer?.observe(node);
return () => observer?.disconnect();
}, [aspect, gap, n, loop]);
// Place everything for the current x. Runs every frame and once after each layout change.
const paint = useCallback((dt: number) => {
const { size: z, count: c, parallax: px, tilt: tl, reduce: r } = live.current;
const state = s.current;
if (!z.vw) return;
const lean = r || !tl ? 0 : Math.max(-9, Math.min(9, -state.v * 0.0075));
state.tilt += (lean - state.tilt) * (1 - Math.exp(-9 * dt));
const still = !pointer.current.down && state.target === null && Math.abs(state.v) < 6;
const centre = still ? nearest() : -1;
for (let k = 0; k < c; k++) {
const pos = positionOf(k, state.x);
const frame = frames.current[k];
if (!frame) continue;
frame.style.transform = `translate3d(${pos.toFixed(2)}px,0,0)`;
const card = cards.current[k];
if (card) card.style.transform = Math.abs(state.tilt) > 0.02 ? `skewX(${state.tilt.toFixed(2)}deg)` : "";
const art = arts.current[k];
if (art) {
const d = (pos + z.w / 2 - z.vw / 2) / (z.vw / 2 || 1);
const shift = r ? 0 : Math.max(-1, Math.min(1, -d)) * Math.min(0.3, Math.max(0, px)) * z.w * 0.33;
art.style.transform = `translate3d(${shift.toFixed(2)}px,0,0)`;
}
const goal = k === centre ? 1 : 0;
const prev = fade.current[k] ?? 0;
const next = r || dt === 0 ? goal : prev + (goal - prev) * (1 - Math.exp(-10 * dt));
fade.current[k] = next;
const caption = captions.current[k];
if (caption) {
caption.style.opacity = next.toFixed(3);
caption.style.transform = `translate3d(0,${((1 - next) * 6).toFixed(2)}px,0)`;
}
}
}, [nearest, positionOf]);
const step = useCallback((dt: number) => {
const { loop: l, paused: p, autoSpeed: speed, reduce: r, stride: st, count: c } = live.current;
const state = s.current;
if (!pointer.current.down) {
if (state.target !== null) {
const before = state.x;
state.x += (state.target - state.x) * (1 - Math.exp(-11 * dt));
state.v = dt > 0 ? (state.x - before) / dt : 0;
if (Math.abs(state.target - state.x) < 0.4) {
state.x = state.target;
state.target = null;
state.v = 0;
}
} else if (r) {
state.v = 0;
} else {
const cruise = l && !p && !hold.current.hover && !hold.current.focus ? -Math.max(0, speed) : 0;
state.v = cruise + (state.v - cruise) * Math.exp(-FRICTION * dt);
if (Math.abs(state.v) < 0.5 && cruise === 0) state.v = 0;
state.x += state.v * dt;
if (!l) {
const b = bounds();
const edge = state.x > b.max ? b.max : state.x < b.min ? b.min : null;
if (edge !== null) {
state.x += (edge - state.x) * (1 - Math.exp(-12 * dt));
state.v *= Math.exp(-14 * dt);
if (Math.abs(edge - state.x) < 0.4) state.x = edge;
}
}
}
}
if (l && c > 0) {
const span = c * st;
if (Math.abs(state.x) > span * 4) {
const shift = Math.trunc(state.x / span) * span;
state.x -= shift;
if (state.target !== null) state.target -= shift;
}
}
paint(dt);
}, [bounds, paint]);
// Start position, then a frame loop that only runs while the strip is on screen.
useLayoutEffect(() => {
if (!size.vw) return;
if (!s.current.started) {
s.current.started = true;
s.current.x = loop ? stride + pad : pad;
}
paint(0);
}, [size, stride, loop, paint]);
const stepRef = useRef(step);
stepRef.current = step;
useEffect(() => {
const node = viewport.current;
if (!node) return;
let frame = 0;
let timer: ReturnType<typeof setTimeout> | undefined;
let last = performance.now();
let running = false;
const tick = () => {
cancelAnimationFrame(frame);
clearTimeout(timer);
const now = performance.now();
const dt = Math.min(0.05, (now - last) / 1000);
last = now;
stepRef.current(dt);
if (!running) return;
frame = requestAnimationFrame(tick);
// Keeps the strip alive where frames are throttled; frames win whenever they arrive.
timer = setTimeout(tick, 34);
};
const start = () => {
if (running) return;
running = true;
last = performance.now();
tick();
};
const stop = () => {
running = false;
cancelAnimationFrame(frame);
clearTimeout(timer);
};
const observer = typeof IntersectionObserver === "undefined"
? null
: new IntersectionObserver(([entry]) => (entry?.isIntersecting ? start() : stop()));
observer?.observe(node);
const rect = node.getBoundingClientRect();
if (!observer || (rect.bottom > 0 && rect.top < window.innerHeight)) start();
return () => {
observer?.disconnect();
stop();
};
}, []);
// Horizontal wheel and trackpad swipes move the strip; vertical scrolling is left to the page.
useEffect(() => {
const node = viewport.current;
if (!node) return;
const onWheel = (event: WheelEvent) => {
const dx = Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.shiftKey ? event.deltaY : 0;
if (!dx) return;
event.preventDefault();
const state = s.current;
state.target = null;
let move = -dx;
if (!live.current.loop) {
const b = bounds();
if (state.x > b.max || state.x < b.min) move *= 0.3;
}
state.x += move;
state.v = live.current.reduce ? 0 : move * 24;
if (live.current.reduce) paint(0);
};
node.addEventListener("wheel", onWheel, { passive: false });
return () => node.removeEventListener("wheel", onWheel);
}, [bounds, paint]);
const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
if (event.button !== 0) return;
pointer.current = { down: true, id: event.pointerId, startX: event.clientX, lastX: event.clientX, lastT: event.timeStamp, moved: false, cancelClick: false };
s.current.target = null;
s.current.v = 0;
};
const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
const p = pointer.current;
if (!p.down || event.pointerId !== p.id) return;
const dx = event.clientX - p.lastX;
const dt = Math.max(1, event.timeStamp - p.lastT);
if (!p.moved && Math.abs(event.clientX - p.startX) > DRAG_SLOP) {
p.moved = true;
// Capture only once it is a real drag, so a plain tap still reaches the link underneath.
event.currentTarget.setPointerCapture?.(event.pointerId);
}
p.lastX = event.clientX;
p.lastT = event.timeStamp;
if (!p.moved) return;
const state = s.current;
let move = dx;
if (!live.current.loop) {
const b = bounds();
if (state.x > b.max || state.x < b.min) move *= 0.35;
}
state.x += move;
state.v = state.v * 0.55 + (dx / dt) * 1000 * 0.45;
paint(0);
};
const onPointerUp = (event: PointerEvent<HTMLDivElement>) => {
const p = pointer.current;
if (!p.down || event.pointerId !== p.id) return;
p.down = false;
if (!p.moved) return;
p.cancelClick = true;
window.setTimeout(() => {
p.cancelClick = false;
}, 0);
const state = s.current;
if (event.timeStamp - p.lastT > 90) state.v = 0;
state.v = Math.max(-4200, Math.min(4200, state.v));
if (live.current.reduce) {
// No inertia: settle on the item nearest the centre, nudged one step in the drag direction.
const k = nearest();
const dir = event.clientX - p.startX;
const off = positionOf(k, state.x) + live.current.size.w / 2 - live.current.size.vw / 2;
const next = Math.abs(off) < 12 ? k + (dir < 0 ? 1 : -1) : k;
goTo(mod(next, live.current.count));
}
};
const primaryOf = (k: number) => mod(k, n);
const move = (delta: number, focus: boolean) => {
if (!n) return;
const from = nearest();
let k = from + delta;
if (live.current.loop) k = mod(k, count);
else k = Math.max(0, Math.min(n - 1, k));
// Prefer the real item over a repeat so focus lands on something keyboard users can reach.
const primary = primaryOf(k);
const pick = size.copies > 1 && k !== primary ? primary : k;
goTo(pick);
if (focus) (frames.current[pick]?.querySelector("a,button") as HTMLElement | null)?.focus({ preventScroll: true });
};
const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
const inside = (event.target as HTMLElement).closest?.("[data-fling-item]");
if (event.key === "ArrowRight") move(1, !!inside);
else if (event.key === "ArrowLeft") move(-1, !!inside);
else if (event.key === "Home" && !loop) goTo(0);
else if (event.key === "End" && !loop) goTo(n - 1);
else return;
event.preventDefault();
};
const showPause = loop && autoSpeed > 0 && !reduce;
const height = size.h + 40;
return (
<div
role="region"
aria-roledescription="carousel"
aria-label={label}
className={cn("relative", className)}
onKeyDown={onKeyDown}
onPointerEnter={() => {
hold.current.hover = true;
}}
onPointerLeave={() => {
hold.current.hover = false;
}}
onFocus={(event) => {
if ((event.target as HTMLElement).matches?.(":focus-visible")) hold.current.focus = true;
}}
onBlur={(event) => {
if (!event.currentTarget.contains(event.relatedTarget as Node | null)) hold.current.focus = false;
}}
>
<div
ref={viewport}
className="relative cursor-grab select-none overflow-hidden [touch-action:pan-y] active:cursor-grabbing [mask-image:linear-gradient(to_right,transparent,#000_7%,#000_93%,transparent)]"
style={{ height: size.vw ? height : undefined, minHeight: size.vw ? undefined : 240 }}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={onPointerUp}
onClickCapture={(event) => {
if (pointer.current.cancelClick) {
event.preventDefault();
event.stopPropagation();
}
}}
onScroll={(event) => {
// Focus can scroll an overflow box; the strip does its own positioning.
event.currentTarget.scrollLeft = 0;
}}
onDragStart={(event) => event.preventDefault()}
>
{size.vw > 0 &&
Array.from({ length: count }, (_, k) => {
const i = k % n;
const item = items[i]!;
const repeat = k >= n;
const art = item.gradient ?? artworkGradient(item.title + i);
const inner = (
<>
<div
ref={(node) => {
cards.current[k] = node;
}}
className="relative overflow-hidden rounded-2xl bg-muted shadow-[0_1px_2px_rgb(0_0_0/0.06),0_12px_32px_-14px_rgb(0_0_0/0.35)] ring-offset-2 ring-offset-background group-focus-visible:ring-2 group-focus-visible:ring-ring"
style={{ height: size.h, transformOrigin: "50% 100%" }}
>
<div
ref={(node) => {
arts.current[k] = node;
}}
className="absolute inset-y-0 -left-[10%] w-[120%]"
style={item.src ? undefined : { background: art }}
role={item.src ? undefined : "img"}
aria-label={item.src ? undefined : item.alt}
>
{item.src && <img src={item.src} alt={item.alt} draggable={false} className="size-full object-cover" />}
</div>
</div>
<div
ref={(node) => {
captions.current[k] = node;
}}
className="mt-3 truncate px-1 text-sm font-medium text-foreground"
style={{ opacity: 0 }}
>
{item.title}
</div>
</>
);
const shared = {
"data-fling-item": "",
tabIndex: repeat ? -1 : undefined,
draggable: false,
onFocus: (event: React.FocusEvent<HTMLElement>) => {
if (event.currentTarget.matches(":focus-visible")) goTo(k);
},
className: "group block w-full rounded-2xl text-left outline-none",
};
return (
<div
key={k}
ref={(node) => {
frames.current[k] = node;
}}
role={repeat ? undefined : "group"}
aria-roledescription={repeat ? undefined : "slide"}
aria-label={repeat ? undefined : `${i + 1} of ${n}`}
aria-hidden={repeat || undefined}
className="absolute left-0 top-1 will-change-transform"
style={{ width: size.w }}
>
{item.href ? (
<a href={item.href} {...shared}>
{inner}
</a>
) : (
<button type="button" onClick={() => onSelect?.(item, i)} {...shared}>
{inner}
</button>
)}
</div>
);
})}
</div>
<div className="mt-2 flex items-center justify-end gap-1.5 px-4">
<button
type="button"
aria-label="Previous"
onClick={() => move(-1, false)}
className="inline-flex size-9 items-center justify-center rounded-full border border-border text-foreground outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"
>
<ChevronLeft className="size-4" aria-hidden="true" />
</button>
<button
type="button"
aria-label="Next"
onClick={() => move(1, false)}
className="inline-flex size-9 items-center justify-center rounded-full border border-border text-foreground outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"
>
<ChevronRight className="size-4" aria-hidden="true" />
</button>
{showPause && (
<button
type="button"
aria-pressed={paused}
aria-label={paused ? "Resume motion" : "Pause motion"}
onClick={() => setPaused((value) => !value)}
className="inline-flex size-9 items-center justify-center rounded-full border border-border text-foreground outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"
>
{paused ? <Play className="size-4" aria-hidden="true" /> : <Pause className="size-4" aria-hidden="true" />}
</button>
)}
</div>
</div>
);
}
