Preview
"use client";
import { useState } from "react";
import { WaveReveal } from "@/components/motion/wave-reveal";
export function WaveRevealUsage() {
const [sent, setSent] = useState(false);
return (
// The wave leaves from wherever the button was pressed.
<WaveReveal
revealed={sent}
className="w-72 rounded-2xl border border-border"
revealedContent={
<div className="flex flex-col gap-3 p-5">
<p className="text-sm font-medium">Invite sent</p>
<button
type="button"
onClick={() => setSent(false)}
className="h-10 rounded-full border border-border text-sm"
>
Done
</button>
</div>
}
>
<div className="flex flex-col gap-3 p-5">
<p className="text-sm font-medium">Invite your team</p>
<button
type="button"
onClick={() => setSent(true)}
className="h-10 rounded-full bg-primary text-sm text-primary-foreground"
>
Send invite
</button>
</div>
</WaveReveal>
);
}
"use client";
// beui.dev/components/motion/wave-reveal
import {
animate,
cubicBezier,
type HTMLMotionProps,
type MotionValue,
motion,
useMotionValue,
useMotionValueEvent,
useReducedMotion,
useTransform,
} from "motion/react";
import {
type ReactNode,
type RefObject,
useEffect,
useId,
useLayoutEffect,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_PRESS } from "@/lib/ease";
import { focusFirstIn } from "@/lib/focusable";
import { cn } from "@/lib/utils";
export type WaveRevealType = "vertical" | "horizontal" | "center";
export interface WaveRevealProps
extends Omit<
HTMLMotionProps<"div">,
"children" | "style" | "onAnimationStart" | "onDrag" | "onDragStart" | "onDragEnd"
> {
/** The first screen, shown while `revealed` is false. */
children: ReactNode;
/** The screen the wave carries in when `revealed` turns true. */
revealedContent: ReactNode;
/** Which screen shows. Flip it to play the wave; flipping it back plays the wave again toward the first screen. */
revealed: boolean;
/** Shape of the wave front: a wide arc that travels up or down, a tall arc that travels sideways, or a ring from the centre. Default: "vertical" */
type?: WaveRevealType;
/** Element the wave leaves from, such as the confirm button. Without it the wave leaves from the last press inside, else from the bottom edge, the left edge or the centre. */
sourceRef?: RefObject<HTMLElement | null>;
/** Time the wave takes to cross the screen, in seconds. A short gather before it and the fading edge glow after it add about 1.3s. Default: 1.6 */
duration?: number;
/** Colours of the wave and the glow it leaves on the edges, any CSS colour. Default: amber, sky, pink, peach and cyan */
colors?: string[];
/** How far the wave swells the screen under it, in px. 0 turns the swell off. Default: 26 */
distortion?: number;
/** Called when a wave finishes, with the `revealed` value it carried in. */
onRevealComplete?: (revealed: boolean) => void;
}
const DEFAULT_COLORS = ["#ffc915", "#7ec4ff", "#eb64a0", "#ffb07a", "#7fd9ee"];
/** Tints laid over the palette just ahead of the front and deep in its tail. */
const AHEAD = "rgb(255 122 182 / 0.55)";
const BEHIND = "rgb(90 190 255 / 0.5)";
/** Anticipation: the screen pulls toward the source and gathers light there. */
const GATHER_S = 0.42;
/** How long the edge glow stays after the front has left, fading out. */
const LINGER_S = 0.9;
const REDUCED_S = 0.2;
/** How far the screen pulls in toward the source while it gathers. */
const PULL = 0.962;
/** Width of the soft seam between the two screens, in px. */
const SEAM = 24;
/** Colour reaching ahead of the front, in px. */
const LEAD = 110;
/** Colour trailing behind the front, in px. */
const TAIL = 280;
/** Extra travel past the farthest corner so the colour fully leaves. */
const OVERSHOOT = 140;
/** Width of the glow the wave leaves on the edges, in px. */
const RIM = 18;
/** How much wider (vertical) or taller (horizontal) the arc is than it is deep. */
const ARC = 1.45;
/** Backdrop blur under the front, in px. */
const BLUR = 8;
/** Where the front sits in the lens map, as a share of its radius. */
const LENS_FRONT = 0.8;
const DOTS = 26;
/** Sparks thrown off the front as it travels. */
const SPARKS = 44;
const SPARK_LIFE_S = 0.9;
/** How far the front ripples either way, in px. */
const RIPPLE = 18;
/** The colour layers reach this far past the card, so the ripple never pulls in a bare edge. */
const PAD = 24;
const NOISE_PERIOD = 1024;
const NOISE_SPAN = 2048;
// The front leaves briskly and eases as it reaches the far edge, like a wave
// spreading from a touch. EASE_OUT reaches the edge too soon for a sweep this
// long; EASE_IN_OUT stalls at the start.
const WAVE_EASE = cubicBezier(0.3, 0.1, 0.3, 1);
type Run = { id: number; target: boolean };
type Dot = { angle: number; reach: number; delay: number; size: number; color: string };
type Spark = { at: number; angle: number; drift: number; size: number; color: string };
const clamp01 = (value: number) => Math.min(1, Math.max(0, value));
const smooth = (edge0: number, edge1: number, value: number) => {
const x = clamp01((value - edge0) / (edge1 - edge0));
return x * x * (3 - 2 * x);
};
/**
* The swell as a displacement map: red and green carry the inward direction,
* scaled by a bump centred on the front (at LENS_FRONT of the radius),
* narrow ahead of it and wider behind. The filter stretches it over the
* wave's ellipse every frame.
*/
let lensMap: string | null = null;
function getLensMap() {
if (lensMap || typeof document === "undefined") return lensMap;
const size = 256;
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d");
if (!ctx) return null;
const image = ctx.createImageData(size, size);
for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
const nx = ((x + 0.5) / size) * 2 - 1;
const ny = ((y + 0.5) / size) * 2 - 1;
const d = Math.hypot(nx, ny);
const u = (d - LENS_FRONT) / (d > LENS_FRONT ? 0.07 : 0.17);
const lift = d < 1 ? Math.exp(-u * u) : 0;
const ux = d > 0 ? nx / d : 0;
const uy = d > 0 ? ny / d : 0;
const i = (y * size + x) * 4;
image.data[i] = 128 - 127 * ux * lift;
image.data[i + 1] = 128 - 127 * uy * lift;
image.data[i + 2] = 128;
image.data[i + 3] = 255;
}
}
ctx.putImageData(image, 0, 0);
lensMap = canvas.toDataURL();
return lensMap;
}
/**
* Slow, smooth noise that tiles every NOISE_PERIOD px, as a displacement map.
* Sliding it under the colour makes the front ripple the way a real wave's
* crest does instead of staying a perfect ellipse.
*/
let noiseMap: string | null = null;
function getNoiseMap() {
if (noiseMap || typeof document === "undefined") return noiseMap;
const size = NOISE_SPAN / 8;
const period = NOISE_PERIOD / 8;
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d");
if (!ctx) return null;
const image = ctx.createImageData(size, size);
const turn = (Math.PI * 2) / period;
for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
const r = 0.6 * Math.sin(turn * (x + y) + 1.3) + 0.4 * Math.sin(turn * (2 * x - y) + 4.1);
const g = 0.6 * Math.sin(turn * (x - y) + 2.2) + 0.4 * Math.sin(turn * (x + 2 * y) + 0.7);
const i = (y * size + x) * 4;
image.data[i] = 128 + 127 * r;
image.data[i + 1] = 128 + 127 * g;
image.data[i + 2] = 128;
image.data[i + 3] = 255;
}
}
ctx.putImageData(image, 0, 0);
noiseMap = canvas.toDataURL();
return noiseMap;
}
/** The palette as gradient stops that wrap seamlessly, repeated `times` over. */
function loop(colors: string[], times = 1) {
const list = colors.length > 0 ? colors : DEFAULT_COLORS;
return [...Array.from({ length: times }, () => list).flat(), list[0]].join(", ");
}
/** A radial gradient on the wave's ellipse; stops are px from the front, + ahead. */
function ellipseGradient(
rx: number,
ry: number,
ox: number,
oy: number,
ax: number,
stops: [number, string][],
) {
const list = stops
.map(([offset, color]) => `${color} ${(rx + offset * ax).toFixed(1)}px`)
.join(", ");
return `radial-gradient(${rx.toFixed(1)}px ${ry.toFixed(1)}px at ${ox.toFixed(1)}px ${oy.toFixed(1)}px, ${list})`;
}
const a = (alpha: number) => `rgb(0 0 0 / ${alpha})`;
export function WaveReveal({
children,
revealedContent,
revealed,
type = "vertical",
sourceRef,
duration = 1.6,
colors = DEFAULT_COLORS,
distortion = 26,
onRevealComplete,
className,
onPointerDownCapture,
...props
}: WaveRevealProps) {
const reduce = useReducedMotion() ?? false;
const filterId = `wave-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;
// `shown` is the settled screen; a run carries the other one in on top.
const [shown, setShown] = useState(revealed);
const [run, setRun] = useState<Run | null>(null);
const [lastRevealed, setLastRevealed] = useState(revealed);
if (revealed !== lastRevealed) {
setLastRevealed(revealed);
setRun((current) => ({ id: (current?.id ?? 0) + 1, target: revealed }));
}
const target = run ? run.target : shown;
const stageRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const layerRefs = useRef<(HTMLDivElement | null)[]>([null, null]);
const imageRef = useRef<SVGFEImageElement>(null);
const displaceRefs = useRef<(SVGFEDisplacementMapElement | null)[]>([null, null, null]);
const pressRef = useRef<{ x: number; y: number; at: number } | null>(null);
const dotsRef = useRef<Dot[]>([]);
const sparksRef = useRef<Spark[]>([]);
const noiseRef = useRef<SVGFEImageElement>(null);
const completeRef = useRef(onRevealComplete);
const colorsRef = useRef(colors);
useLayoutEffect(() => {
completeRef.current = onRevealComplete;
colorsRef.current = colors;
});
const [map, setMap] = useState<string | null>(null);
const [noise, setNoise] = useState<string | null>(null);
useEffect(() => {
setMap(getLensMap());
setNoise(getNoiseMap());
}, []);
// Geometry of the current run, in px from the stage's top-left corner.
const ox = useMotionValue(0);
const oy = useMotionValue(0);
const ax = useMotionValue(ARC);
const ay = useMotionValue(1);
const reach = useMotionValue(1);
const travel = useMotionValue(duration);
// Seconds since the run began: gather, then travel, then linger.
const t = useMotionValue(0);
const fade = useMotionValue(1);
const scale = useMotionValue(1);
const progress = useTransform(() => clamp01((t.get() - GATHER_S) / travel.get()));
const front = useTransform(() => WAVE_EASE(progress.get()));
const radius = useTransform(() => Math.max(0.5, front.get() * reach.get()));
const rx = useTransform(() => radius.get() * ax.get());
const ry = useTransform(() => radius.get() * ay.get());
const released = useTransform(() => smooth(GATHER_S, GATHER_S + 0.14, t.get()));
const bandOpacity = useTransform(() => released.get() * (1 - smooth(0.62, 1, progress.get())));
// The core only lights once the front has room, so the first frames are not a white disc.
const coreOpacity = useTransform(() => bandOpacity.get() * smooth(24, 110, radius.get()));
const energy = useTransform(() => released.get() * (1 - smooth(0.45, 1, progress.get())));
const rimOpacity = useTransform(
() => released.get() * (1 - smooth(0, LINGER_S, t.get() - GATHER_S - travel.get())),
);
const gatherOpacity = useTransform(
() => 0.55 * smooth(0, GATHER_S, t.get()) * (1 - smooth(GATHER_S, GATHER_S + 0.3, t.get())),
);
const gatherScale = useTransform(() => 0.55 + 0.45 * smooth(0, GATHER_S, t.get()));
const shape = (stops: [number, string][], pad = 0) =>
ellipseGradient(rx.get(), ry.get(), ox.get() + pad, oy.get() + pad, ax.get(), stops);
const insideMask = useTransform(() => shape([[-SEAM, "#000"], [0, "transparent"]]));
const outsideMask = useTransform(() => shape([[-SEAM, "transparent"], [0, "#000"]]));
// The colour is strongest toward the card's edges and lighter over its middle,
// so the content stays readable through the wave.
const bandMask = useTransform(
() =>
`${shape(
[
[-TAIL, a(0)],
[-TAIL * 0.72, a(0.14)],
[-TAIL * 0.42, a(0.45)],
[-TAIL * 0.14, a(0.84)],
[0, a(0.97)],
[LEAD * 0.22, a(0.6)],
[LEAD * 0.58, a(0.2)],
[LEAD, a(0)],
],
PAD,
)}, radial-gradient(closest-side at 50% 50%, ${a(0.62)} 35%, #000 100%)`,
);
const coreMask = useTransform(() =>
shape(
[
[-36, a(0)],
[-10, a(0.55)],
[2, a(0.8)],
[14, a(0)],
],
PAD,
),
);
const blurMask = useTransform(() =>
shape([
[-320, a(0)],
[-230, a(0.2)],
[-110, a(0.7)],
[0, a(1)],
[40, a(0.55)],
[95, a(0)],
]),
);
const reached = useTransform(() =>
shape([
[LEAD * 0.25, "#000"],
[LEAD * 0.7, "transparent"],
]),
);
const tints = useTransform(() =>
shape(
[
[-160, "transparent"],
[-84, BEHIND],
[-24, "transparent"],
[8, "transparent"],
[32, AHEAD],
[84, "transparent"],
],
PAD,
),
);
const palette = loop(colors);
const doubled = loop(colors, 2);
// The colour flows along the front as it travels.
const bandFill = useTransform(() => {
const flow = ((t.get() * 9) % 100).toFixed(2);
if (type === "center") {
return `${tints.get()}, conic-gradient(from ${(t.get() * 40).toFixed(1)}deg at ${(ox.get() + PAD).toFixed(1)}px ${(oy.get() + PAD).toFixed(1)}px, ${palette})`;
}
const along = type === "vertical" ? `90deg` : `180deg`;
const place = type === "vertical" ? `${flow}% 0 / 200% 100%` : `0 ${flow}% / 100% 200%`;
return `${tints.get()}, linear-gradient(${along}, ${doubled}) ${place}`;
});
const rimFill = useTransform(
() => `conic-gradient(from ${(t.get() * 55).toFixed(1)}deg at 50% 50%, ${palette})`,
);
const hairFill = useTransform(
() => `linear-gradient(rgb(255 255 255 / 0.6), rgb(255 255 255 / 0.6)), ${rimFill.get()}`,
);
// Uneven rim: lumps of thickness that drift around the edge.
const lumps = useTransform(
() =>
`conic-gradient(from ${(-t.get() * 25).toFixed(1)}deg at 50% 50%, ${a(0.35)}, #000 10%, ${a(0.5)} 24%, #000 41%, ${a(0.3)} 57%, #000 73%, ${a(0.55)} 86%, ${a(0.35)})`,
);
const rimMask = useTransform(
() =>
`${reached.get()}, ${lumps.get()}, linear-gradient(to right, #000, ${a(0.45)} ${RIM * 0.45}px, transparent ${RIM}px, transparent calc(100% - ${RIM}px), ${a(0.45)} calc(100% - ${RIM * 0.45}px), #000), linear-gradient(to bottom, #000, ${a(0.45)} ${RIM * 0.45}px, transparent ${RIM}px, transparent calc(100% - ${RIM}px), ${a(0.45)} calc(100% - ${RIM * 0.45}px), #000)`,
);
const hairMask = useTransform(
() => `${reached.get()}, linear-gradient(#000, #000), linear-gradient(#000, #000)`,
);
const gatherFill = `radial-gradient(circle, rgb(255 255 255 / 0.9) 0%, ${colors[0] ?? DEFAULT_COLORS[0]} 22%, ${colors[2] ?? DEFAULT_COLORS[2]} 42%, transparent 70%)`;
const transformOrigin = useTransform(() => `${ox.get()}px ${oy.get()}px`);
const fadeIn = useTransform(fade, (value) => 1 - value);
const distort = !reduce && distortion > 0 && map !== null && run !== null;
// Drive the lens filter and the gathering dots from the same clock as the masks.
useMotionValueEvent(t, "change", (time) => {
if (distort) {
const image = imageRef.current;
const width = Math.max(1, (rx.get() * 2) / LENS_FRONT);
const height = Math.max(1, (ry.get() * 2) / LENS_FRONT);
if (image) {
image.setAttribute("x", String(ox.get() - width / 2));
image.setAttribute("y", String(oy.get() - height / 2));
image.setAttribute("width", String(width));
image.setAttribute("height", String(height));
}
const strength = energy.get() * distortion * 2;
displaceRefs.current.forEach((node, index) => {
node?.setAttribute("scale", String(strength * (0.72 + index * 0.28)));
});
}
// Slide the ripple noise slowly, so the crest moves like water.
const ripple = noiseRef.current;
if (ripple) {
ripple.setAttribute("x", String(-((time * 70) % NOISE_PERIOD)));
ripple.setAttribute("y", String(-((time * 40) % NOISE_PERIOD)));
}
const canvas = canvasRef.current;
const ctx = canvas?.getContext("2d");
if (!canvas || !ctx) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
const dpr = canvas.width / Math.max(1, canvas.offsetWidth);
// Sparks thrown off the front: each leaves the crest where it is at its
// birth, drifts a little further out and fades.
for (const spark of sparksRef.current) {
const age = time - spark.at;
if (age <= 0 || age >= SPARK_LIFE_S) continue;
const born = WAVE_EASE(clamp01((spark.at - GATHER_S) / travel.get())) * reach.get();
const out = born + spark.drift * (1 - Math.exp(-age * 3));
const x = ox.get() + Math.cos(spark.angle) * out * ax.get();
const y = oy.get() + Math.sin(spark.angle) * out * ay.get();
ctx.globalAlpha = Math.sin(Math.PI * (age / SPARK_LIFE_S)) * 0.9;
ctx.fillStyle = spark.color;
ctx.beginPath();
ctx.arc(x * dpr, y * dpr, spark.size * dpr * (1 - (age / SPARK_LIFE_S) * 0.5), 0, Math.PI * 2);
ctx.fill();
}
if (time > GATHER_S + 0.1) return;
for (const dot of dotsRef.current) {
const span = GATHER_S - dot.delay;
const k = clamp01((time - dot.delay) / span);
if (k <= 0) continue;
const eased = 1 - (1 - k) ** 3;
const distance = dot.reach * (1 - eased);
const x = ox.get() + Math.cos(dot.angle) * distance * ax.get();
const y = oy.get() + Math.sin(dot.angle) * distance * ay.get();
ctx.globalAlpha = Math.sin(Math.PI * k) * (1 - smooth(GATHER_S, GATHER_S + 0.1, time));
ctx.fillStyle = dot.color;
ctx.beginPath();
ctx.arc(x * dpr, y * dpr, dot.size * dpr, 0, Math.PI * 2);
ctx.fill();
}
});
useLayoutEffect(() => {
if (!run) return;
const stage = stageRef.current;
if (!stage) return;
const rect = stage.getBoundingClientRect();
const width = stage.offsetWidth;
const height = stage.offsetHeight;
const zoom = rect.width > 0 ? width / rect.width : 1;
let x = type === "horizontal" ? 0 : width / 2;
let y = type === "vertical" ? height : height / 2;
const source = sourceRef?.current;
const press = pressRef.current;
if (type !== "center" && source) {
const box = source.getBoundingClientRect();
x = (box.left + box.width / 2 - rect.left) * zoom;
y = (box.top + box.height / 2 - rect.top) * zoom;
} else if (type !== "center" && press && performance.now() - press.at < 1500) {
x = (press.x - rect.left) * zoom;
y = (press.y - rect.top) * zoom;
}
pressRef.current = null;
const arcX = type === "vertical" ? ARC : 1;
const arcY = type === "horizontal" ? ARC : 1;
let far = 0;
for (const [cx, cy] of [
[0, 0],
[width, 0],
[0, height],
[width, height],
]) {
far = Math.max(far, Math.hypot((cx - x) / arcX, (cy - y) / arcY));
}
ox.set(x);
oy.set(y);
ax.set(arcX);
ay.set(arcY);
reach.set(far + OVERSHOOT);
travel.set(duration);
const palette = colorsRef.current.length > 0 ? colorsRef.current : DEFAULT_COLORS;
dotsRef.current = Array.from({ length: DOTS }, (_, index) => ({
angle: (index / DOTS) * Math.PI * 2 + Math.random() * 0.4,
reach: 46 + Math.random() * 90,
delay: Math.random() * GATHER_S * 0.45,
size: 1 + Math.random() * 1,
color: palette[index % palette.length],
}));
sparksRef.current = Array.from({ length: SPARKS }, (_, index) => ({
at: GATHER_S + Math.random() * duration * 0.7,
angle: Math.random() * Math.PI * 2,
drift: 14 + Math.random() * 30,
size: 0.7 + Math.random() * 1.1,
color: index % 3 === 0 ? "#ffffff" : palette[index % palette.length],
}));
const canvas = canvasRef.current;
if (canvas) {
const dpr = Math.min(2, window.devicePixelRatio || 1);
canvas.width = Math.round(width * dpr);
canvas.height = Math.round(height * dpr);
}
// Hand focus to the incoming screen when it was in the outgoing one.
const incoming = layerRefs.current[run.target ? 1 : 0];
const outgoing = layerRefs.current[run.target ? 0 : 1];
if (outgoing?.contains(document.activeElement)) focusFirstIn(incoming);
const finish = () => {
setShown(run.target);
setRun((current) => (current?.id === run.id ? null : current));
completeRef.current?.(run.target);
};
if (reduce) {
fade.set(1);
const crossfade = animate(fade, 0, { duration: REDUCED_S, ease: "linear", onComplete: finish });
return () => crossfade.stop();
}
t.set(0);
const pull = animate(scale, PULL, {
duration: GATHER_S,
ease: EASE_OUT,
onComplete: () => {
animate(scale, 1, SPRING_PRESS);
},
});
const clock = animate(t, GATHER_S + duration + LINGER_S, {
duration: GATHER_S + duration + LINGER_S,
ease: "linear",
onComplete: finish,
});
return () => {
pull.stop();
clock.stop();
scale.set(1);
};
}, [run, type, sourceRef, duration, reduce, ox, oy, ax, ay, reach, travel, t, fade, scale]);
const layer = (index: 0 | 1, content: ReactNode) => {
const isTarget = (index === 1) === target;
const visible = isTarget || run !== null;
const mask = run && !reduce ? (isTarget ? insideMask : outsideMask) : undefined;
let opacity: MotionValue<number> | number = 1;
if (run && reduce) opacity = isTarget ? fadeIn : fade;
return (
<motion.div
ref={(node) => {
layerRefs.current[index] = node;
}}
aria-hidden={isTarget ? undefined : true}
inert={!isTarget}
className={cn("[grid-area:1/1]", !visible && "invisible")}
style={{ maskImage: mask, WebkitMaskImage: mask, opacity }}
>
{content}
</motion.div>
);
};
const wave = run !== null && !reduce;
return (
<motion.div
className={cn("relative isolate overflow-hidden", className)}
style={{ scale, transformOrigin }}
onPointerDownCapture={(event) => {
pressRef.current = { x: event.clientX, y: event.clientY, at: performance.now() };
onPointerDownCapture?.(event);
}}
{...props}
>
<div
ref={stageRef}
className="grid"
style={{ filter: distort ? `url(#${filterId})` : undefined }}
>
{layer(0, children)}
{layer(1, revealedContent)}
</div>
{wave ? (
<div aria-hidden="true" className="pointer-events-none absolute inset-0 rounded-[inherit]">
{/* Blur under the front, strongest at it and trailing far behind. */}
<motion.div
className="absolute inset-0"
style={{
backdropFilter: `blur(${BLUR}px)`,
WebkitBackdropFilter: `blur(${BLUR}px)`,
maskImage: blurMask,
WebkitMaskImage: blurMask,
opacity: bandOpacity,
}}
/>
{/* The colour, rippled by slow noise. Its own layer, so the ripple
filter never becomes the backdrop root of the blur above. */}
<div
className="absolute"
style={{
inset: -PAD,
filter: noise ? `url(#${filterId}-ripple)` : undefined,
}}
>
{/* A soft lead ahead, a long tail behind. */}
<motion.div
className="absolute inset-0"
style={{
background: bandFill,
maskImage: bandMask,
WebkitMaskImage: bandMask,
maskComposite: "intersect",
opacity: bandOpacity,
}}
/>
{/* A bright core right at the front. */}
<motion.div
className="absolute inset-0 bg-white"
style={{ maskImage: coreMask, WebkitMaskImage: coreMask, opacity: coreOpacity }}
/>
</div>
{/* The glow left on the edges, uneven and drifting, with a hairline. */}
<motion.div
className="absolute inset-0 rounded-[inherit]"
style={{
background: rimFill,
maskImage: rimMask,
maskComposite: "intersect, intersect, add",
opacity: rimOpacity,
}}
/>
<motion.div
className="absolute inset-0 rounded-[inherit] p-[1.5px]"
style={{
background: hairFill,
maskImage: hairMask,
maskClip: "border-box, content-box, border-box",
maskComposite: "intersect, exclude",
opacity: rimOpacity,
}}
/>
{/* Light gathering at the source before the wave leaves. */}
<motion.div
className="absolute size-28 -translate-x-1/2 -translate-y-1/2 rounded-full blur-[10px]"
style={{ left: ox, top: oy, background: gatherFill, opacity: gatherOpacity, scale: gatherScale }}
/>
<canvas ref={canvasRef} className="absolute inset-0 size-full" />
</div>
) : null}
{map ? (
<svg aria-hidden="true" className="pointer-events-none absolute size-0" focusable="false">
{noise ? (
<filter
id={`${filterId}-ripple`}
x="0"
y="0"
width="100%"
height="100%"
colorInterpolationFilters="sRGB"
>
<feImage
ref={noiseRef}
href={noise}
width={NOISE_SPAN}
height={NOISE_SPAN}
preserveAspectRatio="none"
result="noise"
/>
{/* Past the noise image, a still surface rather than a shift. */}
<feFlood floodColor="rgb(128, 128, 128)" result="still" />
<feComposite in="noise" in2="still" operator="over" result="ripple" />
<feDisplacementMap
in="SourceGraphic"
in2="ripple"
scale={RIPPLE * 2}
xChannelSelector="R"
yChannelSelector="G"
/>
</filter>
) : null}
<filter
id={filterId}
x="-10%"
y="-10%"
width="120%"
height="120%"
colorInterpolationFilters="sRGB"
>
<feFlood floodColor="rgb(128, 128, 128)" result="flat" />
<feImage ref={imageRef} href={map} preserveAspectRatio="none" result="lens" />
<feComposite in="lens" in2="flat" operator="over" result="map" />
{(["r", "g", "b"] as const).map((channel, index) => (
<feDisplacementMap
key={channel}
ref={(node) => {
displaceRefs.current[index] = node;
}}
in="SourceGraphic"
in2="map"
scale={0}
xChannelSelector="R"
yChannelSelector="G"
result={`shift-${channel}`}
/>
))}
<feColorMatrix
in="shift-r"
values="1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0"
result="only-r"
/>
<feColorMatrix
in="shift-g"
values="0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0"
result="only-g"
/>
<feColorMatrix
in="shift-b"
values="0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0"
result="only-b"
/>
<feBlend in="only-r" in2="only-g" mode="screen" result="rg" />
<feBlend in="rg" in2="only-b" mode="screen" />
</filter>
</svg>
) : null}
</motion.div>
);
}
Add it with the shadcn CLI, or copy the source manually.
npx shadcn add https://beui.dev/r/theme.json. Theme setupInstall dependencies
npm i clsx lucide-react motion tailwind-mergeAdd util files
// 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;
/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */
export const EASE_IN = [0.55, 0, 1, 0.45] 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;
/** Shared-surface morphs: a trigger growing into its panel and back on one
* weighted spring, so opening and closing travel the same path. */
export const SPRING_MORPH = {
type: "spring",
duration: 0.5,
bounce: 0.22,
} as const;
/**
* Elements that can usually take keyboard focus. The selector cannot see
* everything focus() checks (an element under `display: none`, say), so a
* caller that needs certainty tries focus() and checks where it landed.
*/
export const FOCUSABLE_SELECTOR = [
"a[href]",
"button:not(:disabled)",
"input:not(:disabled):not([type='hidden'])",
"select:not(:disabled)",
"textarea:not(:disabled)",
"[tabindex]:not([tabindex='-1'])",
].join(",");
/** Elements inside `container` that Tab can reach, in DOM order. */
export function focusablesIn(container: Element | null | undefined) {
return Array.from(
container?.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR) ?? [],
).filter((element) => element.tabIndex >= 0 && !element.closest("[inert]"));
}
/** Focuses the first tabbable element in `panel`, or the panel itself. */
export function focusFirstIn(panel: HTMLElement | null | undefined) {
(focusablesIn(panel)[0] ?? panel)?.focus({ preventScroll: true });
}
/**
* Keeps a Tab keypress inside `panel`, wrapping from the last tabbable element
* to the first and back. Give the panel `tabIndex={-1}` so it can hold focus
* when it has nothing tabbable.
*/
export function cycleTab(event: KeyboardEvent, panel: HTMLElement | null) {
if (event.key !== "Tab" || !panel) return;
const elements = focusablesIn(panel);
const first = elements[0];
const last = elements[elements.length - 1];
const active = document.activeElement;
if (!first || !last) {
event.preventDefault();
panel.focus({ preventScroll: true });
} else if (event.shiftKey && (active === first || active === panel)) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && active === last) {
event.preventDefault();
first.focus();
}
}
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
"use client";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useMemo,
} from "react";
/**
* A component's messages. Plain strings with `{name}` placeholders, so a
* dictionary stays JSON-serializable and can be passed from a server layout.
* There are no plural forms: write messages that read correctly for any count.
*/
export type Messages = Record<string, string>;
/** A language file: component namespace → any subset of that component's messages. */
export type LocaleMessages = Record<string, Partial<Messages>>;
type LocaleContextValue = {
locale?: string;
messages: LocaleMessages;
};
const NO_MESSAGES: LocaleMessages = {};
const LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });
/** Without a locale, digits stay plain so server and client render the same text. */
export function formatNumber(value: number, locale?: string) {
return locale ? new Intl.NumberFormat(locale).format(value) : String(value);
}
export interface LocaleProviderProps {
/** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */
locale: string;
/**
* Component namespace → translated strings. Missing keys fall back to English.
* Pass a stable object (a module constant, imported JSON or a memoized value):
* a new object each render gives every translated component a new `t`.
*/
messages?: LocaleMessages;
children: ReactNode;
}
export function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {
const value = useMemo(() => ({ locale, messages }), [locale, messages]);
return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;
}
export function useLocale(): { locale?: string } {
return { locale: useContext(LocaleContext).locale };
}
/**
* Resolves a component's strings: `labels` prop, then the provider's
* messages for `namespace`, then the component's English `defaults`.
* Numbers passed as values are formatted for the provider's locale.
*/
export function useMessages<T extends Messages>(
namespace: string,
defaults: T,
labels?: Partial<T>,
) {
const { locale, messages } = useContext(LocaleContext);
const provided = messages[namespace];
// Inline `labels={{ … }}` is a new object every render. Keying it by content
// keeps `t` one identity until a label changes, so effects and memos that
// depend on `t` don't re-run per render, and render-time reads never lag.
const labelsKey = labels ? JSON.stringify(labels) : "";
const stableLabels = useMemo(
() => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),
[labelsKey],
);
return useCallback(
(key: keyof T & string, values?: Record<string, string | number>) => {
const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];
if (!values) return template;
return template.replace(/\{(\w+)\}/g, (match, name: string) => {
const value = values[name];
if (value === undefined) return match;
return typeof value === "number" ? formatNumber(value, locale) : value;
});
},
[defaults, stableLabels, locale, provided],
);
}
"use client";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useRef,
} from "react";
import {
registerSoundSettings,
retainAudioContext,
type SoundSettingsEntry,
} from "@/lib/audio-context";
import type { PlayOptions, Sound } from "@/lib/sounds/engine";
export interface SoundSettings {
/** False mutes every beUI sound under the provider. */
enabled: boolean;
/** 0 to 1, scales every beUI sound. */
volume: number;
}
const SoundContext = createContext<SoundSettings & { depth: number }>({
enabled: true,
volume: 1,
depth: 0,
});
/**
* App-wide sound settings. `enabled={false}` mutes every beUI sound, from
* component `sound` props and `useSound` to the games, Wheel Picker and
* Bookshelf, and `volume` scales them all. Without a provider, sounds play at
* full volume. A nested provider overrides the one around it.
*/
export function SoundProvider({
enabled = true,
volume = 1,
children,
}: Partial<SoundSettings> & { children: ReactNode }) {
const depth = useContext(SoundContext).depth + 1;
const value = useMemo(() => ({ enabled, volume, depth }), [enabled, volume, depth]);
// Module-level as well (lib/audio-context.ts), so players outside React
// and `sound.play()` obey it too.
const entry = useRef<SoundSettingsEntry>({ depth, enabled, volume });
const registration = useRef<ReturnType<typeof registerSoundSettings> | null>(null);
useEffect(() => {
registration.current = registerSoundSettings(entry.current);
return () => {
registration.current?.release();
registration.current = null;
};
}, []);
useEffect(() => {
Object.assign(entry.current, { depth, enabled, volume });
registration.current?.update();
}, [depth, enabled, volume]);
return <SoundContext.Provider value={value}>{children}</SoundContext.Provider>;
}
export function useSoundSettings(): SoundSettings {
return useContext(SoundContext);
}
export interface UseSoundOptions {
/** False makes `play` do nothing, for a component's `sound` prop. */
enabled?: boolean;
/** 0 to 1 for this sound, on top of the provider volume. */
volume?: number;
}
/**
* A stable `play()` for one sound. It does nothing while disabled or muted,
* and keeps the shared audio context warm only while it can play.
*/
export function useSound(sound: Sound, { enabled = true, volume = 1 }: UseSoundOptions = {}) {
const settings = useSoundSettings();
const on = enabled && settings.enabled && settings.volume > 0 && volume > 0;
// Read by the stable callback, so a caller's effects don't re-run when
// the settings change.
const latest = useRef({ on, volume, sound });
useLayoutEffect(() => {
latest.current = { on, volume, sound };
});
useEffect(() => {
if (!on) return;
return retainAudioContext();
}, [on]);
return useCallback((options?: PlayOptions) => {
const current = latest.current;
if (!current.on) return;
current.sound.play({ ...options, volume: (options?.volume ?? 1) * current.volume });
}, []);
}
import { defineSound } from "./engine";
/** A crisp detent, like a dial clicking into a notch, for tabs, segmented controls and menu choices. */
export const selectSound = defineSound({
name: "Select",
duration: 0.05,
room: 0.08,
build: (v) => {
v.click({ freq: 4500, q: 2.5, decay: 0.003, gain: 0.45 });
v.strike({ freq: 1700, material: "metal", decay: 0.028, gain: 0.3 });
v.strike({ freq: 520, material: "wood", bend: 1.15, decay: 0.012, gain: 0.25 });
},
});
// One AudioContext for every synthesized sound on the page: the sounds
// library (lib/sounds/), the WheelPicker tick (lib/tick-sound.ts), the casino
// games (lib/game-sounds.ts) and Bookshelf (lib/book-sounds.ts). Browsers cap
// concurrent contexts, and a page can show a date made of several WheelPickers
// next to a game, so they all share this one. It is created on first use and
// closed once every player is disposed.
//
// Every player connects to `audioOutput()` rather than the context's
// destination, so the page-wide volume and mute from `SoundProvider`
// (lib/sound.tsx) reach all of them in one place.
type AudioContextCtor = typeof AudioContext;
let context: AudioContext | null = null;
let master: GainNode | null = null;
let users = 0;
/** Settings one mounted `SoundProvider` asks for. */
export interface SoundSettingsEntry {
/** Nesting depth: the deepest provider decides. */
depth: number;
enabled: boolean;
volume: number;
}
// Mounted providers in mount order. Module state, so `sound.play()` called
// outside React obeys them too. The deepest provider wins; among equals, the
// one mounted last. Effects run child first, so this can't be "whoever ran
// last".
const providers = new Set<SoundSettingsEntry>();
let allowed = true;
let volume = 1;
function applySettings() {
let chosen: SoundSettingsEntry | undefined;
for (const entry of providers) {
if (!chosen || entry.depth >= chosen.depth) chosen = entry;
}
allowed = chosen?.enabled ?? true;
volume = Math.min(1, Math.max(0, chosen?.volume ?? 1));
if (master) master.gain.value = volume;
}
/**
* Registers a provider's settings; call `update` after changing the entry and
* the returned release function when the provider unmounts.
*/
export function registerSoundSettings(entry: SoundSettingsEntry) {
providers.add(entry);
applySettings();
return {
update: applySettings,
release() {
providers.delete(entry);
applySettings();
},
};
}
/**
* Registers a sound player. Call the returned function when the player is
* disposed; the context closes after the last one.
*/
export function retainAudioContext() {
users++;
let released = false;
return () => {
if (released) return;
released = true;
users--;
if (users === 0 && context) {
void context.close();
context = null;
master = null;
}
};
}
/**
* The shared context, created on first call and resumed if suspended. Null
* during SSR, in browsers without Web Audio, and while sounds are muted or at
* zero volume.
*/
export function getAudioContext(): AudioContext | null {
if (!allowed || volume <= 0) return null;
if (!context) {
if (typeof window === "undefined") return null;
const Ctor =
window.AudioContext ??
(window as unknown as { webkitAudioContext?: AudioContextCtor }).webkitAudioContext;
if (!Ctor) return null;
context = new Ctor();
}
// Browsers may refuse outside a user gesture. Players call this from
// pointer and key handlers first, so a later call finds it running.
if (context.state === "suspended") void context.resume().catch(() => undefined);
return context;
}
/** The node every player connects to: the page-wide volume, then the speakers. */
export function audioOutput(ctx: AudioContext): AudioNode {
if (master?.context !== ctx) {
master = ctx.createGain();
master.gain.value = volume;
master.connect(ctx.destination);
}
return master;
}
const gains = new WeakMap<BaseAudioContext, Map<string, GainNode>>();
/**
* A player's own level, made once per context and routed into `audioOutput`.
* Players keep their mix this way without rebuilding nodes on every play, and
* a context closed and recreated gets fresh ones.
*/
export function playerGain(ctx: AudioContext, key: string, level: number): GainNode {
let byKey = gains.get(ctx);
if (!byKey) {
byKey = new Map();
gains.set(ctx, byKey);
}
let gain = byKey.get(key);
if (!gain) {
gain = ctx.createGain();
gain.gain.value = level;
gain.connect(audioOutput(ctx));
byKey.set(key, gain);
}
return gain;
}
import { audioOutput, getAudioContext } from "@/lib/audio-context";
// Every beUI sound is a short recipe played with Web Audio the moment it is
// asked for. Nothing is downloaded. Recipes are built the way a real tap
// sounds: a contact click (a millisecond of filtered noise), a body that
// rings at a few inharmonic partials of a material and settles in pitch, and
// a little of a small room behind it.
/** Options for one play of a sound. */
export interface PlayOptions {
/** 0 to 1, multiplied with the page-wide volume from `SoundProvider`. */
volume?: number;
/** Pitch multiplier; 1 is the designed pitch. */
pitch?: number;
}
/** Where a sound renders: the live context, or an offline one for drawing. */
export interface SoundTarget {
context: BaseAudioContext;
destination: AudioNode;
/** Start time on the context clock, in seconds. */
when: number;
volume: number;
pitch: number;
}
/** A plain oscillator with an attack, a decay and an optional glide. */
export interface ToneSpec {
type?: OscillatorType;
/** Start frequency in Hz. */
freq: number;
/** End frequency in Hz; glides from `freq` over `glide`. */
to?: number;
/** Glide time in seconds; defaults to the attack plus decay. */
glide?: number;
/** Starts this many times higher and settles to `freq` in about 15 ms, like a struck object. */
bend?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Fade-in time in seconds. */
attack?: number;
/** Time to fade to silence after the attack, in seconds. */
decay: number;
gain: number;
}
/** A burst of filtered white noise. */
export interface NoiseSpec {
filter?: BiquadFilterType;
/** Filter frequency in Hz. */
freq: number;
/** End filter frequency in Hz; sweeps from `freq` over the decay. */
to?: number;
q?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Fade-in time in seconds. */
attack?: number;
/** Time to fade to silence after the attack, in seconds. */
decay: number;
gain: number;
}
/** The contact of a tap: a few milliseconds of band-passed noise with an instant attack. */
export interface ClickSpec {
/** Band center in Hz: 1-2 kHz is a soft knock, 3-5 kHz a crisp click. */
freq: number;
/** Band width; higher is narrower and more tonal. */
q?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Time to fade to silence, in seconds. */
decay?: number;
gain: number;
}
/** How a material rings: partials as [frequency ratio, level], and how fast high ones die. */
export interface Material {
partials: readonly (readonly [ratio: number, level: number])[];
/** Higher partials decay in `decay / ratio ** damping`; wood is high, metal low. */
damping: number;
}
// Partial ratios follow the modes of small struck objects: a free bar for
// wood and metal, a cup for glass, a tuned bar for the mallet.
export const MATERIALS = {
wood: { partials: [[1, 1], [2.76, 0.3], [5.4, 0.08]], damping: 1.3 },
plastic: { partials: [[1, 1], [2.43, 0.4], [4.86, 0.14]], damping: 0.9 },
glass: { partials: [[1, 1], [2.32, 0.42], [4.25, 0.2], [6.63, 0.08]], damping: 0.55 },
metal: { partials: [[1, 1], [2.76, 0.5], [5.4, 0.26], [8.93, 0.1]], damping: 0.4 },
mallet: { partials: [[1, 1], [3.99, 0.2], [9.14, 0.05]], damping: 0.8 },
bell: { partials: [[1, 1], [2.0, 0.34], [2.76, 0.2], [5.4, 0.07]], damping: 0.5 },
} satisfies Record<string, Material>;
/** A struck object: one partial per mode of its material, each with its own decay. */
export interface StrikeSpec {
/** Fundamental in Hz. */
freq: number;
/** A name from `MATERIALS` or your own partials. Default: "plastic". */
material?: keyof typeof MATERIALS | Material;
/** Starts this many times higher and settles in about 15 ms. Default: 1.01. */
bend?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Time for the fundamental to fade to silence, in seconds. */
decay: number;
gain: number;
}
export interface Voice {
tone(spec: ToneSpec): void;
noise(spec: NoiseSpec): void;
click(spec: ClickSpec): void;
strike(spec: StrikeSpec): void;
}
export interface Sound {
/** Display name, like "Tap". */
name: string;
/** Length in seconds; the room tail rings a little past it. */
duration: number;
/** Plays the sound now. Silent during SSR and while sounds are muted. */
play(options?: PlayOptions): void;
/** Schedules the sound on any context; `play` uses the live one. */
render(target: SoundTarget): void;
}
export interface SoundRecipe {
/** Display name, like "Tap". */
name: string;
/** Length in seconds; the room tail rings a little past it. */
duration: number;
/** Random pitch spread per play (0.04 = ±4%), so repeats don't sound stamped. */
vary?: number;
/** How much of the small room the sound is played in, 0 (dry) to 1. Default: 0.12. */
room?: number;
/** Adds the sound's layers to the voice on each play. */
build: (voice: Voice) => void;
}
// Keeps a sum of voices well under clipping at volume 1.
const MASTER_GAIN = 0.16;
const SILENT = 0.0001;
// Time a strike or bend takes to settle onto its pitch.
const SETTLE = 0.015;
const noiseBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();
/** One second of white noise per context, shared by every noise voice. */
export function noiseBuffer(context: BaseAudioContext) {
let buffer = noiseBuffers.get(context);
if (!buffer) {
buffer = context.createBuffer(1, context.sampleRate, context.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;
noiseBuffers.set(context, buffer);
}
return buffer;
}
// A small, soft room: 8 early reflections, then a diffuse tail that falls
// 60 dB in 0.3 s and darkens as it fades, the way air and soft walls
// absorb highs first. Generated once per context.
const ROOM_LENGTH = 0.3;
// The convolver's equal-power normalization leaves the room about 15 dB
// under the dry sound; this brings `room: 0.12` to a tail heard only as space.
const ROOM_GAIN = 6;
const roomBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();
function roomBuffer(context: BaseAudioContext) {
let buffer = roomBuffers.get(context);
if (!buffer) {
const rate = context.sampleRate;
const length = Math.ceil(ROOM_LENGTH * rate);
buffer = context.createBuffer(2, length, rate);
for (let channel = 0; channel < 2; channel++) {
const data = buffer.getChannelData(channel);
let smooth = 0;
for (let i = Math.floor(0.004 * rate); i < length; i++) {
const t = i / rate;
// One-pole low-pass whose cutoff closes over the tail.
const brightness = 0.7 * Math.exp(-t / 0.08) + 0.08;
smooth += brightness * (Math.random() * 2 - 1 - smooth);
data[i] = smooth * Math.exp(-t / 0.043);
}
for (let r = 0; r < 8; r++) {
const at = Math.floor((0.005 + Math.random() * 0.022) * rate);
data[at] += (Math.random() < 0.5 ? -1 : 1) * (0.5 - r * 0.05);
}
}
roomBuffers.set(context, buffer);
}
return buffer;
}
// One convolver per output node, shared by every play: building one is the
// expensive part, sending to it is cheap.
const rooms = new WeakMap<AudioNode, ConvolverNode>();
function roomFor(context: BaseAudioContext, destination: AudioNode) {
let room = rooms.get(destination);
if (!room) {
room = context.createConvolver();
room.buffer = roomBuffer(context);
room.connect(destination);
rooms.set(destination, room);
}
return room;
}
/** A linear attack to `peak`, then an exponential fall to silence. */
function envelope(param: AudioParam, start: number, attack: number, decay: number, peak: number) {
param.setValueAtTime(0, start);
param.linearRampToValueAtTime(Math.max(peak, SILENT), start + attack);
param.exponentialRampToValueAtTime(SILENT, start + attack + decay);
}
function voiceFor(target: SoundTarget, output: AudioNode): Voice {
const { context, when, pitch } = target;
// Partials above this only add hiss on small speakers, or alias near Nyquist.
const ceiling = Math.min(12000, context.sampleRate * 0.45);
const tone: Voice["tone"] = ({ type = "sine", freq, to, glide, bend, at = 0, attack = 0.002, decay, gain }) => {
const start = when + at;
const osc = context.createOscillator();
const amp = context.createGain();
osc.type = type;
const base = freq * pitch;
osc.frequency.setValueAtTime(base * (bend ?? 1), start);
if (bend !== undefined) osc.frequency.exponentialRampToValueAtTime(base, start + SETTLE);
if (to !== undefined) {
osc.frequency.exponentialRampToValueAtTime(to * pitch, start + Math.max(glide ?? attack + decay, SETTLE));
}
envelope(amp.gain, start, attack, decay, gain);
osc.connect(amp).connect(output);
osc.start(start);
osc.stop(start + attack + decay + 0.02);
};
const noise: Voice["noise"] = ({ filter = "bandpass", freq, to, q = 1, at = 0, attack = 0.002, decay, gain }) => {
const start = when + at;
const source = context.createBufferSource();
const shape = context.createBiquadFilter();
const amp = context.createGain();
source.buffer = noiseBuffer(context);
shape.type = filter;
shape.Q.value = q;
shape.frequency.setValueAtTime(freq * pitch, start);
if (to !== undefined) {
shape.frequency.exponentialRampToValueAtTime(to * pitch, start + attack + decay);
}
envelope(amp.gain, start, attack, decay, gain);
source.connect(shape).connect(amp).connect(output);
// A random offset into the buffer keeps each burst a little different.
source.start(start, Math.random() * 0.5);
source.stop(start + attack + decay + 0.02);
};
return {
tone,
noise,
click({ freq, q = 2, at = 0, decay = 0.005, gain }) {
// A little spread on the band, so no two contacts are identical.
noise({ freq: freq * (0.94 + Math.random() * 0.12), q, at, attack: 0.0005, decay, gain });
},
strike({ freq, material = "plastic", bend = 1.01, at = 0, decay, gain }) {
const { partials, damping } = typeof material === "string" ? MATERIALS[material] : material;
for (const [ratio, level] of partials) {
if (freq * ratio * pitch * bend > ceiling) continue;
tone({
// Real objects are never perfectly tuned; a hair of detune per partial.
freq: freq * ratio * (1 + (Math.random() * 2 - 1) * 0.003),
bend,
at,
attack: 0.001,
decay: decay / ratio ** damping,
gain: gain * level,
});
}
},
};
}
/** Turns a recipe into a playable sound. */
export function defineSound({ name, duration, vary = 0, room = 0.12, build }: SoundRecipe): Sound {
const render = (target: SoundTarget) => {
const { context, destination } = target;
const output = context.createGain();
output.gain.value = MASTER_GAIN * target.volume;
output.connect(destination);
if (room > 0) {
const send = context.createGain();
send.gain.value = room * ROOM_GAIN;
output.connect(send).connect(roomFor(context, destination));
}
build(voiceFor(target, output));
};
return {
name,
duration,
render,
play({ volume = 1, pitch = 1 } = {}) {
const context = getAudioContext();
if (!context || volume <= 0) return;
const spread = vary ? 1 + (Math.random() * 2 - 1) * vary : 1;
render({
context,
// The page-wide volume is applied there.
destination: audioOutput(context),
when: context.currentTime + 0.005,
volume,
pitch: pitch * spread,
});
},
};
}
Copy the source code
"use client";
// beui.dev/components/motion/wave-reveal
import {
animate,
cubicBezier,
type HTMLMotionProps,
type MotionValue,
motion,
useMotionValue,
useMotionValueEvent,
useReducedMotion,
useTransform,
} from "motion/react";
import {
type ReactNode,
type RefObject,
useEffect,
useId,
useLayoutEffect,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_PRESS } from "@/lib/ease";
import { focusFirstIn } from "@/lib/focusable";
import { cn } from "@/lib/utils";
export type WaveRevealType = "vertical" | "horizontal" | "center";
export interface WaveRevealProps
extends Omit<
HTMLMotionProps<"div">,
"children" | "style" | "onAnimationStart" | "onDrag" | "onDragStart" | "onDragEnd"
> {
/** The first screen, shown while `revealed` is false. */
children: ReactNode;
/** The screen the wave carries in when `revealed` turns true. */
revealedContent: ReactNode;
/** Which screen shows. Flip it to play the wave; flipping it back plays the wave again toward the first screen. */
revealed: boolean;
/** Shape of the wave front: a wide arc that travels up or down, a tall arc that travels sideways, or a ring from the centre. Default: "vertical" */
type?: WaveRevealType;
/** Element the wave leaves from, such as the confirm button. Without it the wave leaves from the last press inside, else from the bottom edge, the left edge or the centre. */
sourceRef?: RefObject<HTMLElement | null>;
/** Time the wave takes to cross the screen, in seconds. A short gather before it and the fading edge glow after it add about 1.3s. Default: 1.6 */
duration?: number;
/** Colours of the wave and the glow it leaves on the edges, any CSS colour. Default: amber, sky, pink, peach and cyan */
colors?: string[];
/** How far the wave swells the screen under it, in px. 0 turns the swell off. Default: 26 */
distortion?: number;
/** Called when a wave finishes, with the `revealed` value it carried in. */
onRevealComplete?: (revealed: boolean) => void;
}
const DEFAULT_COLORS = ["#ffc915", "#7ec4ff", "#eb64a0", "#ffb07a", "#7fd9ee"];
/** Tints laid over the palette just ahead of the front and deep in its tail. */
const AHEAD = "rgb(255 122 182 / 0.55)";
const BEHIND = "rgb(90 190 255 / 0.5)";
/** Anticipation: the screen pulls toward the source and gathers light there. */
const GATHER_S = 0.42;
/** How long the edge glow stays after the front has left, fading out. */
const LINGER_S = 0.9;
const REDUCED_S = 0.2;
/** How far the screen pulls in toward the source while it gathers. */
const PULL = 0.962;
/** Width of the soft seam between the two screens, in px. */
const SEAM = 24;
/** Colour reaching ahead of the front, in px. */
const LEAD = 110;
/** Colour trailing behind the front, in px. */
const TAIL = 280;
/** Extra travel past the farthest corner so the colour fully leaves. */
const OVERSHOOT = 140;
/** Width of the glow the wave leaves on the edges, in px. */
const RIM = 18;
/** How much wider (vertical) or taller (horizontal) the arc is than it is deep. */
const ARC = 1.45;
/** Backdrop blur under the front, in px. */
const BLUR = 8;
/** Where the front sits in the lens map, as a share of its radius. */
const LENS_FRONT = 0.8;
const DOTS = 26;
/** Sparks thrown off the front as it travels. */
const SPARKS = 44;
const SPARK_LIFE_S = 0.9;
/** How far the front ripples either way, in px. */
const RIPPLE = 18;
/** The colour layers reach this far past the card, so the ripple never pulls in a bare edge. */
const PAD = 24;
const NOISE_PERIOD = 1024;
const NOISE_SPAN = 2048;
// The front leaves briskly and eases as it reaches the far edge, like a wave
// spreading from a touch. EASE_OUT reaches the edge too soon for a sweep this
// long; EASE_IN_OUT stalls at the start.
const WAVE_EASE = cubicBezier(0.3, 0.1, 0.3, 1);
type Run = { id: number; target: boolean };
type Dot = { angle: number; reach: number; delay: number; size: number; color: string };
type Spark = { at: number; angle: number; drift: number; size: number; color: string };
const clamp01 = (value: number) => Math.min(1, Math.max(0, value));
const smooth = (edge0: number, edge1: number, value: number) => {
const x = clamp01((value - edge0) / (edge1 - edge0));
return x * x * (3 - 2 * x);
};
/**
* The swell as a displacement map: red and green carry the inward direction,
* scaled by a bump centred on the front (at LENS_FRONT of the radius),
* narrow ahead of it and wider behind. The filter stretches it over the
* wave's ellipse every frame.
*/
let lensMap: string | null = null;
function getLensMap() {
if (lensMap || typeof document === "undefined") return lensMap;
const size = 256;
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d");
if (!ctx) return null;
const image = ctx.createImageData(size, size);
for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
const nx = ((x + 0.5) / size) * 2 - 1;
const ny = ((y + 0.5) / size) * 2 - 1;
const d = Math.hypot(nx, ny);
const u = (d - LENS_FRONT) / (d > LENS_FRONT ? 0.07 : 0.17);
const lift = d < 1 ? Math.exp(-u * u) : 0;
const ux = d > 0 ? nx / d : 0;
const uy = d > 0 ? ny / d : 0;
const i = (y * size + x) * 4;
image.data[i] = 128 - 127 * ux * lift;
image.data[i + 1] = 128 - 127 * uy * lift;
image.data[i + 2] = 128;
image.data[i + 3] = 255;
}
}
ctx.putImageData(image, 0, 0);
lensMap = canvas.toDataURL();
return lensMap;
}
/**
* Slow, smooth noise that tiles every NOISE_PERIOD px, as a displacement map.
* Sliding it under the colour makes the front ripple the way a real wave's
* crest does instead of staying a perfect ellipse.
*/
let noiseMap: string | null = null;
function getNoiseMap() {
if (noiseMap || typeof document === "undefined") return noiseMap;
const size = NOISE_SPAN / 8;
const period = NOISE_PERIOD / 8;
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d");
if (!ctx) return null;
const image = ctx.createImageData(size, size);
const turn = (Math.PI * 2) / period;
for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
const r = 0.6 * Math.sin(turn * (x + y) + 1.3) + 0.4 * Math.sin(turn * (2 * x - y) + 4.1);
const g = 0.6 * Math.sin(turn * (x - y) + 2.2) + 0.4 * Math.sin(turn * (x + 2 * y) + 0.7);
const i = (y * size + x) * 4;
image.data[i] = 128 + 127 * r;
image.data[i + 1] = 128 + 127 * g;
image.data[i + 2] = 128;
image.data[i + 3] = 255;
}
}
ctx.putImageData(image, 0, 0);
noiseMap = canvas.toDataURL();
return noiseMap;
}
/** The palette as gradient stops that wrap seamlessly, repeated `times` over. */
function loop(colors: string[], times = 1) {
const list = colors.length > 0 ? colors : DEFAULT_COLORS;
return [...Array.from({ length: times }, () => list).flat(), list[0]].join(", ");
}
/** A radial gradient on the wave's ellipse; stops are px from the front, + ahead. */
function ellipseGradient(
rx: number,
ry: number,
ox: number,
oy: number,
ax: number,
stops: [number, string][],
) {
const list = stops
.map(([offset, color]) => `${color} ${(rx + offset * ax).toFixed(1)}px`)
.join(", ");
return `radial-gradient(${rx.toFixed(1)}px ${ry.toFixed(1)}px at ${ox.toFixed(1)}px ${oy.toFixed(1)}px, ${list})`;
}
const a = (alpha: number) => `rgb(0 0 0 / ${alpha})`;
export function WaveReveal({
children,
revealedContent,
revealed,
type = "vertical",
sourceRef,
duration = 1.6,
colors = DEFAULT_COLORS,
distortion = 26,
onRevealComplete,
className,
onPointerDownCapture,
...props
}: WaveRevealProps) {
const reduce = useReducedMotion() ?? false;
const filterId = `wave-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;
// `shown` is the settled screen; a run carries the other one in on top.
const [shown, setShown] = useState(revealed);
const [run, setRun] = useState<Run | null>(null);
const [lastRevealed, setLastRevealed] = useState(revealed);
if (revealed !== lastRevealed) {
setLastRevealed(revealed);
setRun((current) => ({ id: (current?.id ?? 0) + 1, target: revealed }));
}
const target = run ? run.target : shown;
const stageRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const layerRefs = useRef<(HTMLDivElement | null)[]>([null, null]);
const imageRef = useRef<SVGFEImageElement>(null);
const displaceRefs = useRef<(SVGFEDisplacementMapElement | null)[]>([null, null, null]);
const pressRef = useRef<{ x: number; y: number; at: number } | null>(null);
const dotsRef = useRef<Dot[]>([]);
const sparksRef = useRef<Spark[]>([]);
const noiseRef = useRef<SVGFEImageElement>(null);
const completeRef = useRef(onRevealComplete);
const colorsRef = useRef(colors);
useLayoutEffect(() => {
completeRef.current = onRevealComplete;
colorsRef.current = colors;
});
const [map, setMap] = useState<string | null>(null);
const [noise, setNoise] = useState<string | null>(null);
useEffect(() => {
setMap(getLensMap());
setNoise(getNoiseMap());
}, []);
// Geometry of the current run, in px from the stage's top-left corner.
const ox = useMotionValue(0);
const oy = useMotionValue(0);
const ax = useMotionValue(ARC);
const ay = useMotionValue(1);
const reach = useMotionValue(1);
const travel = useMotionValue(duration);
// Seconds since the run began: gather, then travel, then linger.
const t = useMotionValue(0);
const fade = useMotionValue(1);
const scale = useMotionValue(1);
const progress = useTransform(() => clamp01((t.get() - GATHER_S) / travel.get()));
const front = useTransform(() => WAVE_EASE(progress.get()));
const radius = useTransform(() => Math.max(0.5, front.get() * reach.get()));
const rx = useTransform(() => radius.get() * ax.get());
const ry = useTransform(() => radius.get() * ay.get());
const released = useTransform(() => smooth(GATHER_S, GATHER_S + 0.14, t.get()));
const bandOpacity = useTransform(() => released.get() * (1 - smooth(0.62, 1, progress.get())));
// The core only lights once the front has room, so the first frames are not a white disc.
const coreOpacity = useTransform(() => bandOpacity.get() * smooth(24, 110, radius.get()));
const energy = useTransform(() => released.get() * (1 - smooth(0.45, 1, progress.get())));
const rimOpacity = useTransform(
() => released.get() * (1 - smooth(0, LINGER_S, t.get() - GATHER_S - travel.get())),
);
const gatherOpacity = useTransform(
() => 0.55 * smooth(0, GATHER_S, t.get()) * (1 - smooth(GATHER_S, GATHER_S + 0.3, t.get())),
);
const gatherScale = useTransform(() => 0.55 + 0.45 * smooth(0, GATHER_S, t.get()));
const shape = (stops: [number, string][], pad = 0) =>
ellipseGradient(rx.get(), ry.get(), ox.get() + pad, oy.get() + pad, ax.get(), stops);
const insideMask = useTransform(() => shape([[-SEAM, "#000"], [0, "transparent"]]));
const outsideMask = useTransform(() => shape([[-SEAM, "transparent"], [0, "#000"]]));
// The colour is strongest toward the card's edges and lighter over its middle,
// so the content stays readable through the wave.
const bandMask = useTransform(
() =>
`${shape(
[
[-TAIL, a(0)],
[-TAIL * 0.72, a(0.14)],
[-TAIL * 0.42, a(0.45)],
[-TAIL * 0.14, a(0.84)],
[0, a(0.97)],
[LEAD * 0.22, a(0.6)],
[LEAD * 0.58, a(0.2)],
[LEAD, a(0)],
],
PAD,
)}, radial-gradient(closest-side at 50% 50%, ${a(0.62)} 35%, #000 100%)`,
);
const coreMask = useTransform(() =>
shape(
[
[-36, a(0)],
[-10, a(0.55)],
[2, a(0.8)],
[14, a(0)],
],
PAD,
),
);
const blurMask = useTransform(() =>
shape([
[-320, a(0)],
[-230, a(0.2)],
[-110, a(0.7)],
[0, a(1)],
[40, a(0.55)],
[95, a(0)],
]),
);
const reached = useTransform(() =>
shape([
[LEAD * 0.25, "#000"],
[LEAD * 0.7, "transparent"],
]),
);
const tints = useTransform(() =>
shape(
[
[-160, "transparent"],
[-84, BEHIND],
[-24, "transparent"],
[8, "transparent"],
[32, AHEAD],
[84, "transparent"],
],
PAD,
),
);
const palette = loop(colors);
const doubled = loop(colors, 2);
// The colour flows along the front as it travels.
const bandFill = useTransform(() => {
const flow = ((t.get() * 9) % 100).toFixed(2);
if (type === "center") {
return `${tints.get()}, conic-gradient(from ${(t.get() * 40).toFixed(1)}deg at ${(ox.get() + PAD).toFixed(1)}px ${(oy.get() + PAD).toFixed(1)}px, ${palette})`;
}
const along = type === "vertical" ? `90deg` : `180deg`;
const place = type === "vertical" ? `${flow}% 0 / 200% 100%` : `0 ${flow}% / 100% 200%`;
return `${tints.get()}, linear-gradient(${along}, ${doubled}) ${place}`;
});
const rimFill = useTransform(
() => `conic-gradient(from ${(t.get() * 55).toFixed(1)}deg at 50% 50%, ${palette})`,
);
const hairFill = useTransform(
() => `linear-gradient(rgb(255 255 255 / 0.6), rgb(255 255 255 / 0.6)), ${rimFill.get()}`,
);
// Uneven rim: lumps of thickness that drift around the edge.
const lumps = useTransform(
() =>
`conic-gradient(from ${(-t.get() * 25).toFixed(1)}deg at 50% 50%, ${a(0.35)}, #000 10%, ${a(0.5)} 24%, #000 41%, ${a(0.3)} 57%, #000 73%, ${a(0.55)} 86%, ${a(0.35)})`,
);
const rimMask = useTransform(
() =>
`${reached.get()}, ${lumps.get()}, linear-gradient(to right, #000, ${a(0.45)} ${RIM * 0.45}px, transparent ${RIM}px, transparent calc(100% - ${RIM}px), ${a(0.45)} calc(100% - ${RIM * 0.45}px), #000), linear-gradient(to bottom, #000, ${a(0.45)} ${RIM * 0.45}px, transparent ${RIM}px, transparent calc(100% - ${RIM}px), ${a(0.45)} calc(100% - ${RIM * 0.45}px), #000)`,
);
const hairMask = useTransform(
() => `${reached.get()}, linear-gradient(#000, #000), linear-gradient(#000, #000)`,
);
const gatherFill = `radial-gradient(circle, rgb(255 255 255 / 0.9) 0%, ${colors[0] ?? DEFAULT_COLORS[0]} 22%, ${colors[2] ?? DEFAULT_COLORS[2]} 42%, transparent 70%)`;
const transformOrigin = useTransform(() => `${ox.get()}px ${oy.get()}px`);
const fadeIn = useTransform(fade, (value) => 1 - value);
const distort = !reduce && distortion > 0 && map !== null && run !== null;
// Drive the lens filter and the gathering dots from the same clock as the masks.
useMotionValueEvent(t, "change", (time) => {
if (distort) {
const image = imageRef.current;
const width = Math.max(1, (rx.get() * 2) / LENS_FRONT);
const height = Math.max(1, (ry.get() * 2) / LENS_FRONT);
if (image) {
image.setAttribute("x", String(ox.get() - width / 2));
image.setAttribute("y", String(oy.get() - height / 2));
image.setAttribute("width", String(width));
image.setAttribute("height", String(height));
}
const strength = energy.get() * distortion * 2;
displaceRefs.current.forEach((node, index) => {
node?.setAttribute("scale", String(strength * (0.72 + index * 0.28)));
});
}
// Slide the ripple noise slowly, so the crest moves like water.
const ripple = noiseRef.current;
if (ripple) {
ripple.setAttribute("x", String(-((time * 70) % NOISE_PERIOD)));
ripple.setAttribute("y", String(-((time * 40) % NOISE_PERIOD)));
}
const canvas = canvasRef.current;
const ctx = canvas?.getContext("2d");
if (!canvas || !ctx) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
const dpr = canvas.width / Math.max(1, canvas.offsetWidth);
// Sparks thrown off the front: each leaves the crest where it is at its
// birth, drifts a little further out and fades.
for (const spark of sparksRef.current) {
const age = time - spark.at;
if (age <= 0 || age >= SPARK_LIFE_S) continue;
const born = WAVE_EASE(clamp01((spark.at - GATHER_S) / travel.get())) * reach.get();
const out = born + spark.drift * (1 - Math.exp(-age * 3));
const x = ox.get() + Math.cos(spark.angle) * out * ax.get();
const y = oy.get() + Math.sin(spark.angle) * out * ay.get();
ctx.globalAlpha = Math.sin(Math.PI * (age / SPARK_LIFE_S)) * 0.9;
ctx.fillStyle = spark.color;
ctx.beginPath();
ctx.arc(x * dpr, y * dpr, spark.size * dpr * (1 - (age / SPARK_LIFE_S) * 0.5), 0, Math.PI * 2);
ctx.fill();
}
if (time > GATHER_S + 0.1) return;
for (const dot of dotsRef.current) {
const span = GATHER_S - dot.delay;
const k = clamp01((time - dot.delay) / span);
if (k <= 0) continue;
const eased = 1 - (1 - k) ** 3;
const distance = dot.reach * (1 - eased);
const x = ox.get() + Math.cos(dot.angle) * distance * ax.get();
const y = oy.get() + Math.sin(dot.angle) * distance * ay.get();
ctx.globalAlpha = Math.sin(Math.PI * k) * (1 - smooth(GATHER_S, GATHER_S + 0.1, time));
ctx.fillStyle = dot.color;
ctx.beginPath();
ctx.arc(x * dpr, y * dpr, dot.size * dpr, 0, Math.PI * 2);
ctx.fill();
}
});
useLayoutEffect(() => {
if (!run) return;
const stage = stageRef.current;
if (!stage) return;
const rect = stage.getBoundingClientRect();
const width = stage.offsetWidth;
const height = stage.offsetHeight;
const zoom = rect.width > 0 ? width / rect.width : 1;
let x = type === "horizontal" ? 0 : width / 2;
let y = type === "vertical" ? height : height / 2;
const source = sourceRef?.current;
const press = pressRef.current;
if (type !== "center" && source) {
const box = source.getBoundingClientRect();
x = (box.left + box.width / 2 - rect.left) * zoom;
y = (box.top + box.height / 2 - rect.top) * zoom;
} else if (type !== "center" && press && performance.now() - press.at < 1500) {
x = (press.x - rect.left) * zoom;
y = (press.y - rect.top) * zoom;
}
pressRef.current = null;
const arcX = type === "vertical" ? ARC : 1;
const arcY = type === "horizontal" ? ARC : 1;
let far = 0;
for (const [cx, cy] of [
[0, 0],
[width, 0],
[0, height],
[width, height],
]) {
far = Math.max(far, Math.hypot((cx - x) / arcX, (cy - y) / arcY));
}
ox.set(x);
oy.set(y);
ax.set(arcX);
ay.set(arcY);
reach.set(far + OVERSHOOT);
travel.set(duration);
const palette = colorsRef.current.length > 0 ? colorsRef.current : DEFAULT_COLORS;
dotsRef.current = Array.from({ length: DOTS }, (_, index) => ({
angle: (index / DOTS) * Math.PI * 2 + Math.random() * 0.4,
reach: 46 + Math.random() * 90,
delay: Math.random() * GATHER_S * 0.45,
size: 1 + Math.random() * 1,
color: palette[index % palette.length],
}));
sparksRef.current = Array.from({ length: SPARKS }, (_, index) => ({
at: GATHER_S + Math.random() * duration * 0.7,
angle: Math.random() * Math.PI * 2,
drift: 14 + Math.random() * 30,
size: 0.7 + Math.random() * 1.1,
color: index % 3 === 0 ? "#ffffff" : palette[index % palette.length],
}));
const canvas = canvasRef.current;
if (canvas) {
const dpr = Math.min(2, window.devicePixelRatio || 1);
canvas.width = Math.round(width * dpr);
canvas.height = Math.round(height * dpr);
}
// Hand focus to the incoming screen when it was in the outgoing one.
const incoming = layerRefs.current[run.target ? 1 : 0];
const outgoing = layerRefs.current[run.target ? 0 : 1];
if (outgoing?.contains(document.activeElement)) focusFirstIn(incoming);
const finish = () => {
setShown(run.target);
setRun((current) => (current?.id === run.id ? null : current));
completeRef.current?.(run.target);
};
if (reduce) {
fade.set(1);
const crossfade = animate(fade, 0, { duration: REDUCED_S, ease: "linear", onComplete: finish });
return () => crossfade.stop();
}
t.set(0);
const pull = animate(scale, PULL, {
duration: GATHER_S,
ease: EASE_OUT,
onComplete: () => {
animate(scale, 1, SPRING_PRESS);
},
});
const clock = animate(t, GATHER_S + duration + LINGER_S, {
duration: GATHER_S + duration + LINGER_S,
ease: "linear",
onComplete: finish,
});
return () => {
pull.stop();
clock.stop();
scale.set(1);
};
}, [run, type, sourceRef, duration, reduce, ox, oy, ax, ay, reach, travel, t, fade, scale]);
const layer = (index: 0 | 1, content: ReactNode) => {
const isTarget = (index === 1) === target;
const visible = isTarget || run !== null;
const mask = run && !reduce ? (isTarget ? insideMask : outsideMask) : undefined;
let opacity: MotionValue<number> | number = 1;
if (run && reduce) opacity = isTarget ? fadeIn : fade;
return (
<motion.div
ref={(node) => {
layerRefs.current[index] = node;
}}
aria-hidden={isTarget ? undefined : true}
inert={!isTarget}
className={cn("[grid-area:1/1]", !visible && "invisible")}
style={{ maskImage: mask, WebkitMaskImage: mask, opacity }}
>
{content}
</motion.div>
);
};
const wave = run !== null && !reduce;
return (
<motion.div
className={cn("relative isolate overflow-hidden", className)}
style={{ scale, transformOrigin }}
onPointerDownCapture={(event) => {
pressRef.current = { x: event.clientX, y: event.clientY, at: performance.now() };
onPointerDownCapture?.(event);
}}
{...props}
>
<div
ref={stageRef}
className="grid"
style={{ filter: distort ? `url(#${filterId})` : undefined }}
>
{layer(0, children)}
{layer(1, revealedContent)}
</div>
{wave ? (
<div aria-hidden="true" className="pointer-events-none absolute inset-0 rounded-[inherit]">
{/* Blur under the front, strongest at it and trailing far behind. */}
<motion.div
className="absolute inset-0"
style={{
backdropFilter: `blur(${BLUR}px)`,
WebkitBackdropFilter: `blur(${BLUR}px)`,
maskImage: blurMask,
WebkitMaskImage: blurMask,
opacity: bandOpacity,
}}
/>
{/* The colour, rippled by slow noise. Its own layer, so the ripple
filter never becomes the backdrop root of the blur above. */}
<div
className="absolute"
style={{
inset: -PAD,
filter: noise ? `url(#${filterId}-ripple)` : undefined,
}}
>
{/* A soft lead ahead, a long tail behind. */}
<motion.div
className="absolute inset-0"
style={{
background: bandFill,
maskImage: bandMask,
WebkitMaskImage: bandMask,
maskComposite: "intersect",
opacity: bandOpacity,
}}
/>
{/* A bright core right at the front. */}
<motion.div
className="absolute inset-0 bg-white"
style={{ maskImage: coreMask, WebkitMaskImage: coreMask, opacity: coreOpacity }}
/>
</div>
{/* The glow left on the edges, uneven and drifting, with a hairline. */}
<motion.div
className="absolute inset-0 rounded-[inherit]"
style={{
background: rimFill,
maskImage: rimMask,
maskComposite: "intersect, intersect, add",
opacity: rimOpacity,
}}
/>
<motion.div
className="absolute inset-0 rounded-[inherit] p-[1.5px]"
style={{
background: hairFill,
maskImage: hairMask,
maskClip: "border-box, content-box, border-box",
maskComposite: "intersect, exclude",
opacity: rimOpacity,
}}
/>
{/* Light gathering at the source before the wave leaves. */}
<motion.div
className="absolute size-28 -translate-x-1/2 -translate-y-1/2 rounded-full blur-[10px]"
style={{ left: ox, top: oy, background: gatherFill, opacity: gatherOpacity, scale: gatherScale }}
/>
<canvas ref={canvasRef} className="absolute inset-0 size-full" />
</div>
) : null}
{map ? (
<svg aria-hidden="true" className="pointer-events-none absolute size-0" focusable="false">
{noise ? (
<filter
id={`${filterId}-ripple`}
x="0"
y="0"
width="100%"
height="100%"
colorInterpolationFilters="sRGB"
>
<feImage
ref={noiseRef}
href={noise}
width={NOISE_SPAN}
height={NOISE_SPAN}
preserveAspectRatio="none"
result="noise"
/>
{/* Past the noise image, a still surface rather than a shift. */}
<feFlood floodColor="rgb(128, 128, 128)" result="still" />
<feComposite in="noise" in2="still" operator="over" result="ripple" />
<feDisplacementMap
in="SourceGraphic"
in2="ripple"
scale={RIPPLE * 2}
xChannelSelector="R"
yChannelSelector="G"
/>
</filter>
) : null}
<filter
id={filterId}
x="-10%"
y="-10%"
width="120%"
height="120%"
colorInterpolationFilters="sRGB"
>
<feFlood floodColor="rgb(128, 128, 128)" result="flat" />
<feImage ref={imageRef} href={map} preserveAspectRatio="none" result="lens" />
<feComposite in="lens" in2="flat" operator="over" result="map" />
{(["r", "g", "b"] as const).map((channel, index) => (
<feDisplacementMap
key={channel}
ref={(node) => {
displaceRefs.current[index] = node;
}}
in="SourceGraphic"
in2="map"
scale={0}
xChannelSelector="R"
yChannelSelector="G"
result={`shift-${channel}`}
/>
))}
<feColorMatrix
in="shift-r"
values="1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0"
result="only-r"
/>
<feColorMatrix
in="shift-g"
values="0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0"
result="only-g"
/>
<feColorMatrix
in="shift-b"
values="0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0"
result="only-b"
/>
<feBlend in="only-r" in2="only-g" mode="screen" result="rg" />
<feBlend in="rg" in2="only-b" mode="screen" />
</filter>
</svg>
) : null}
</motion.div>
);
}
"use client";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { cancelFrame, frame, motion, MotionConfig, useReducedMotion, useSpring, type MotionValue, type Transition } from "motion/react";
import {
createContext,
useCallback,
useContext,
useId,
useLayoutEffect,
useRef,
useMemo,
useState,
type ButtonHTMLAttributes,
type HTMLAttributes,
type KeyboardEvent,
type ReactNode,
} from "react";
import { EASE_OUT, SPRING_SWAP } from "@/lib/ease";
import { useMessages } from "@/lib/i18n";
import { useSound } from "@/lib/sound";
import { selectSound } from "@/lib/sounds/select";
import { cn } from "@/lib/utils";
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const tabsMessages = {
scrollLeft: "Scroll tabs left",
scrollRight: "Scroll tabs right",
};
export type TabsMessages = typeof tabsMessages;
type Variant = "pill" | "underline" | "segment";
/** Whether trigger icons show on every tab or only on the selected one. */
type IconDisplay = "always" | "selected";
type Ctx = {
value: string;
setValue: (v: string) => void;
layoutId: string;
variant: Variant;
icons: IconDisplay;
/** The pill's box in the list, for tabs whose width changes as they're selected. */
track: Track;
/** Whether the tracked pill has been measured; until then CSS places it. */
placed: boolean;
setPlaced: (placed: boolean) => void;
/**
* The one tab Tab reaches: the selected tab, or the first enabled one when
* nothing enabled is selected. `null` until the triggers have registered,
* when every enabled tab stays reachable.
*/
tabStop: string | null;
registerTab: (value: string, disabled: boolean) => void;
unregisterTab: (value: string) => void;
/** Values with a mounted panel, so triggers only point at panels that exist. */
panels: ReadonlySet<string>;
registerPanel: (value: string) => void;
unregisterPanel: (value: string) => void;
tabId: (value: string) => string;
panelId: (value: string) => string;
t: (key: keyof TabsMessages) => string;
};
type Track = Record<"x" | "y" | "width" | "height", MotionValue<number>>;
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;
}
// Settle without overshoot: a scrollable tab list would turn even a small
// overshoot into a transient scrollbar and layout shift.
// Scale stiffness and damping together for a quicker glide with the same feel.
const transition: Transition = {
type: "spring",
stiffness: 245,
damping: 36,
mass: 1.2,
};
/**
* Pass a union of tab values as `T` (or let `value` infer it) and
* `onValueChange` receives that union. Every trigger's `value` must be one of
* them.
*/
export function Tabs<T extends string = string>({
defaultValue,
value,
onValueChange,
variant = "pill",
icons = "always",
labels,
sound = false,
children,
className,
}: {
/** The tab selected at first when uncontrolled. */
defaultValue?: T;
/** The selected tab's value, for controlled use. */
value?: T;
/** Called with the tab's value when a tab is picked. */
onValueChange?: (v: T) => void;
/** Selection style: "pill", "underline" or "segment". Default: "pill" */
variant?: Variant;
/**
* With "selected", a trigger's icon springs open only on the selected tab
* and folds away when another is chosen. Defaults to "always".
*/
icons?: IconDisplay;
/** Override any built-in string. */
labels?: Partial<TabsMessages>;
/** Play a soft tick when the user picks another tab. Off by default; a `SoundProvider` can mute it app-wide. */
sound?: boolean;
children: ReactNode;
className?: string;
}) {
const t = useMessages("tabs", tabsMessages, labels);
const [internal, setInternal] = useState<string>(defaultValue ?? "");
const layoutId = useId();
const reduce = useReducedMotion();
const controlled = value !== undefined;
const current = controlled ? value : internal;
const play = useSound(selectSound, { enabled: sound });
const setValue = useCallback(
(v: string) => {
if (v !== current) play();
if (!controlled) setInternal(v);
// Triggers only carry values from `T`, so the string is one of them.
onValueChange?.(v as T);
},
[controlled, onValueChange, current, play],
);
const x = useSpring(0, transition);
const y = useSpring(0, transition);
const width = useSpring(0, transition);
const height = useSpring(0, transition);
const track = useMemo(() => ({ x, y, width, height }), [x, y, width, height]);
const [placed, setPlaced] = useState(false);
const [tabs, setTabs] = useState<Map<string, boolean>>(new Map());
const registerTab = useCallback((tab: string, disabled: boolean) => {
setTabs((map) => (map.get(tab) === disabled ? map : new Map(map).set(tab, disabled)));
}, []);
const unregisterTab = useCallback((tab: string) => {
setTabs((map) => {
if (!map.has(tab)) return map;
const next = new Map(map);
next.delete(tab);
return next;
});
}, []);
const [panels, setPanels] = useState<ReadonlySet<string>>(new Set());
const registerPanel = useCallback((panel: string) => {
setPanels((set) => (set.has(panel) ? set : new Set(set).add(panel)));
}, []);
const unregisterPanel = useCallback((panel: string) => {
setPanels((set) => {
if (!set.has(panel)) return set;
const next = new Set(set);
next.delete(panel);
return next;
});
}, []);
// Resolved during render so the list has exactly one tab stop in the same
// commit that changes the selection or the tabs.
let tabStop: string | null = null;
if (tabs.size > 0) {
const enabled = Array.from(tabs).filter(([, disabled]) => !disabled);
tabStop = enabled.some(([tab]) => tab === current) ? current : (enabled[0]?.[0] ?? "");
}
const baseId = useId();
const tabId = useCallback((tab: string) => `${baseId}-tab-${tab.replace(/[^\w-]/g, "_")}`, [baseId]);
const panelId = useCallback((tab: string) => `${baseId}-panel-${tab.replace(/[^\w-]/g, "_")}`, [baseId]);
const contextValue = useMemo(
() => ({
value: current,
setValue,
layoutId,
variant,
icons,
track,
placed,
setPlaced,
tabStop,
registerTab,
unregisterTab,
panels,
registerPanel,
unregisterPanel,
tabId,
panelId,
t,
}),
[current, icons, layoutId, setValue, variant, track, placed, tabStop, registerTab, unregisterTab, panels, registerPanel, unregisterPanel, tabId, panelId, t],
);
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-full bg-card p-0.5",
};
export function TabsList({
children,
className,
wrapperClassName,
onKeyDown,
...props
}: {
wrapperClassName?: string;
} & HTMLAttributes<HTMLDivElement>) {
const { variant, value, icons, track, placed, setPlaced, t } = useTabs();
const reduce = useReducedMotion();
const tracked = icons === "selected" && variant !== "underline";
const rootRef = useRef<HTMLDivElement>(null);
const viewportRef = useRef<HTMLDivElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const viewportId = useId();
const [edges, setEdges] = useState({ overflow: false, left: false, right: false });
const measure = useCallback(() => {
const root = rootRef.current;
const viewport = viewportRef.current;
if (!root || !viewport) return;
// Overlay controls do not reduce the viewport or change its scroll range.
const overflow = viewport.scrollWidth > root.clientWidth + 1;
const max = Math.max(0, viewport.scrollWidth - viewport.clientWidth);
const rtl = getComputedStyle(viewport).direction === "rtl";
// Modern browsers expose negative scrollLeft in RTL. Clamp rubber-banding.
const fromLeft = Math.max(0, Math.min(max, rtl ? max + viewport.scrollLeft : viewport.scrollLeft));
const next = { overflow, left: fromLeft > 1, right: fromLeft < max - 1 };
setEdges((previous) => previous.overflow === next.overflow && previous.left === next.left && previous.right === next.right ? previous : next);
}, []);
const reveal = useCallback((tab: HTMLElement | null) => {
const viewport = viewportRef.current;
if (!viewport || !tab) return;
const frame = viewport.getBoundingClientRect();
const item = tab.getBoundingClientRect();
const max = Math.max(0, viewport.scrollWidth - viewport.clientWidth);
const rtl = getComputedStyle(viewport).direction === "rtl";
const fromLeft = Math.max(0, Math.min(max, rtl ? max + viewport.scrollLeft : viewport.scrollLeft));
// Keep the selected/focused label clear of the arrows over the faded edges.
const left = frame.left + (fromLeft > 1 ? 36 : 0);
const right = frame.right - (fromLeft < max - 1 ? 36 : 0);
const delta = item.left < left ? item.left - left : item.right > right ? item.right - right : 0;
// Scroll only this viewport; scrollIntoView can also move the whole page.
if (delta) viewport.scrollBy({ left: delta, behavior: reduce ? "instant" : "smooth" });
}, [reduce]);
useLayoutEffect(() => {
const root = rootRef.current;
const viewport = viewportRef.current;
const list = listRef.current;
if (!root || !viewport || !list) return;
const update = () => {
measure();
reveal(list.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]'));
};
const observer = new ResizeObserver(update);
observer.observe(root);
observer.observe(viewport);
observer.observe(list);
viewport.addEventListener("scroll", measure, { passive: true });
update();
return () => {
observer.disconnect();
viewport.removeEventListener("scroll", measure);
};
}, [measure, reveal]);
useLayoutEffect(() => {
// Children may change without a resize; controlled selection must also reveal.
void children;
void value;
void edges.overflow;
measure();
reveal(listRef.current?.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]') ?? null);
}, [children, value, edges.overflow, measure, reveal]);
useLayoutEffect(() => {
// With icons="selected" the chosen tab grows as its icon opens and the
// last one shrinks. A layout animation measures the tabs mid-change, so
// the pill would squeeze and catch up. Instead the pill springs straight
// to where the selected tab will settle, with every icon open or closed.
if (!tracked) return;
const list = listRef.current;
if (!list) return;
void children;
const place = () => {
const tabs = Array.from(list.querySelectorAll<HTMLElement>('[role="tab"]'));
const target = tabs.find((tab) => tab.dataset.tabsValue === value)?.parentElement;
if (!target) return;
// Measure the settled layout: open the selected icon and fold the rest
// for one synchronous read, then hand the styles back to Motion before
// anything paints. Exact in any layout, from flex rows to grids.
const icons = Array.from(list.querySelectorAll<HTMLElement>('[role="tab"] > [data-tabs-icon]'));
const saved = icons.map((icon) => [icon.style.width, icon.style.marginRight]);
for (const icon of icons) {
const open = icon.parentElement?.parentElement === target;
icon.style.width = open ? "auto" : "0px";
icon.style.marginRight = open ? `${ICON_GAP}px` : "0px";
}
const box = {
x: target.offsetLeft,
y: target.offsetTop,
// Fractional: a rounded width leaves the pill a hair off its tab.
width: target.getBoundingClientRect().width,
height: target.offsetHeight,
};
icons.forEach((icon, index) => {
[icon.style.width, icon.style.marginRight] = saved[index];
});
// A first measurement, or one after the list was hidden, lands in place.
const instant = reduce || track.width.get() === 0;
for (const key of ["x", "y", "width", "height"] as const) {
if (instant) track[key].jump(box[key]);
else track[key].set(box[key]);
}
// Hand over from the CSS pill once there's a real box, before paint.
if (box.width > 0) setPlaced(true);
};
place();
const observer = new ResizeObserver(place);
for (const tab of list.querySelectorAll('[role="tab"]')) if (tab.parentElement) observer.observe(tab.parentElement);
return () => observer.disconnect();
}, [tracked, value, children, reduce, track, setPlaced]);
useLayoutEffect(() => {
if (variant === "underline") return;
const list = listRef.current;
if (!list) return;
void children;
// `placed` swaps the indicator element, so measure the new one.
void placed;
const labels = Array.from(list.querySelectorAll<HTMLElement>("[data-tabs-label]"));
const indicator = list.querySelector<HTMLElement>("[data-tabs-indicator]");
const target = list.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]');
if (!indicator || !target || target.dataset.tabsValue !== value) {
for (const label of labels) label.style.clipPath = "inset(0 100% 0 0)";
return;
}
let frames = 0;
let stillFrames = 0;
let previous: { left: number; right: number } | undefined;
const syncClips = () => {
const pill = (reduce ? target : indicator).getBoundingClientRect();
// Read ALL geometry before writing ANY masks. A loop per tab interleaved
// reads and writes, forcing the browser to flush styles repeatedly.
const clips = labels.map((label) => {
const bounds = label.getBoundingClientRect();
const left = Math.max(0, Math.min(bounds.width, pill.left - bounds.left));
const right = Math.max(0, Math.min(bounds.width, bounds.right - pill.right));
return left + right >= bounds.width ? "inset(0 100% 0 0)" : `inset(0 ${right}px 0 ${left}px)`;
});
labels.forEach((label, index) => {
if (label.style.clipPath !== clips[index]) label.style.clipPath = clips[index];
});
frames += 1;
stillFrames = previous && Math.abs(pill.left - previous.left) < 0.01 && Math.abs(pill.right - previous.right) < 0.01 ? stillFrames + 1 : 0;
previous = { left: pill.left, right: pill.right };
if (reduce || (frames > 2 && stillFrames >= 2)) cancelFrame(syncClips);
};
// One shared pass after Motion paints the projected pill keeps every label
// in sync, including labels crossed during a long or interrupted glide.
frame.postRender(syncClips, true);
// A list measured while hidden (display: none, a closed panel, a
// breakpoint) gets every mask closed. Sync again once it has a size, or
// the selected label stays invisible until the value changes.
const resync = () => {
frames = 0;
stillFrames = 0;
previous = undefined;
cancelFrame(syncClips);
frame.postRender(syncClips, true);
};
const observer = new ResizeObserver(resync);
observer.observe(list);
return () => {
observer.disconnect();
cancelFrame(syncClips);
};
}, [value, children, variant, reduce, placed]);
// Arrow keys move along the list and select as focus arrives, wrapping at
// the ends; Home and End jump to the first and last enabled tab.
const onListKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
onKeyDown?.(event);
if (event.defaultPrevented) return;
const list = listRef.current;
if (!list || !(event.target instanceof HTMLElement)) return;
const tabs = Array.from(list.querySelectorAll<HTMLButtonElement>('[role="tab"]')).filter(
(tab) => !tab.disabled && tab.closest('[role="tablist"]') === list,
);
const at = tabs.indexOf(event.target as HTMLButtonElement);
if (at < 0) return;
const rtl = getComputedStyle(list).direction === "rtl";
const forward = rtl ? "ArrowLeft" : "ArrowRight";
const back = rtl ? "ArrowRight" : "ArrowLeft";
const next =
event.key === forward
? tabs[(at + 1) % tabs.length]
: event.key === back
? tabs[(at - 1 + tabs.length) % tabs.length]
: event.key === "Home"
? tabs[0]
: event.key === "End"
? tabs[tabs.length - 1]
: null;
if (!next) return;
event.preventDefault();
next.focus();
next.click();
};
const scroll = (direction: number) => {
const viewport = viewportRef.current;
if (viewport) viewport.scrollBy({ left: direction * viewport.clientWidth * 0.8, behavior: reduce ? "instant" : "smooth" });
};
const controlClass = "absolute inset-y-0 z-20 inline-flex w-9 items-center justify-center text-foreground transition-opacity hover:opacity-70 focus-visible:outline-2 focus-visible:-outline-offset-4 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-0";
const surfaceClass = variant === "pill" ? "rounded-full bg-card" : variant === "segment" ? "rounded-full bg-card" : "";
return (
<div ref={rootRef} className={cn("relative isolate flex w-full max-w-full min-w-0 items-center", edges.overflow && surfaceClass, wrapperClassName)}>
{edges.overflow && (
<button type="button" aria-label={t("scrollLeft")} aria-controls={viewportId} disabled={!edges.left} onClick={() => scroll(-1)} className={cn(controlClass, "left-0 rounded-l-full")}>
<ChevronLeft size={20} aria-hidden="true" />
</button>
)}
<motion.div
ref={viewportRef}
id={viewportId}
layoutScroll
className={cn("w-full min-w-0 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden", edges.overflow && "[border-radius:inherit]")}
style={edges.overflow ? {
maskImage: `linear-gradient(to right, ${edges.left ? "transparent, black 40px" : "black, black 0px"}, ${edges.right ? "black calc(100% - 40px), transparent" : "black 100%"})`,
} : undefined}
onFocusCapture={(event) => {
if (event.target instanceof HTMLElement && event.target.getAttribute("role") === "tab") reveal(event.target);
}}
>
<div {...props} ref={listRef} role="tablist" onKeyDown={onListKeyDown} className={cn(listClasses[variant], "w-max", tracked && "relative", className)}>
{children}
</div>
</motion.div>
{edges.overflow && edges.left && (
<span aria-hidden="true" className="pointer-events-none absolute inset-y-0 left-0 z-10 w-10 rounded-l-[inherit] backdrop-blur-[2px] [mask-image:linear-gradient(to_right,black,transparent)]" />
)}
{edges.overflow && edges.right && (
<span aria-hidden="true" className="pointer-events-none absolute inset-y-0 right-0 z-10 w-10 rounded-r-[inherit] backdrop-blur-[2px] [mask-image:linear-gradient(to_left,black,transparent)]" />
)}
{edges.overflow && (
<button type="button" aria-label={t("scrollRight")} aria-controls={viewportId} disabled={!edges.right} onClick={() => scroll(1)} className={cn(controlClass, "right-0 rounded-r-full")}>
<ChevronRight size={20} aria-hidden="true" />
</button>
)}
</div>
);
}
/** Space between a selected-only icon and its label, in pixels. */
const ICON_GAP = 6;
/**
* A trigger's icon before its label. Shown on every tab, or with
* `icons="selected"` springing open on the selected tab only.
*/
function TriggerIcon({ icon, active }: { icon: ReactNode; active: boolean }) {
const { icons } = useTabs();
const reduce = useReducedMotion();
if (icons === "always") {
return (
<span aria-hidden="true" className="mr-1.5 inline-flex shrink-0 items-center">
{icon}
</span>
);
}
return (
<motion.span
aria-hidden="true"
data-tabs-icon=""
initial={false}
animate={{
width: active ? "auto" : 0,
marginRight: active ? ICON_GAP : 0,
opacity: active ? 1 : 0,
scale: active ? 1 : 0.6,
}}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="inline-flex shrink-0 items-center justify-center overflow-hidden"
>
{icon}
</motion.span>
);
}
export function TabsTrigger({
value,
icon,
children,
className,
indicatorClassName,
onClick,
...props
}: {
value: string;
/** An icon before the label, such as a Lucide icon element. */
icon?: ReactNode;
indicatorClassName?: string;
} & Omit<ButtonHTMLAttributes<HTMLButtonElement>, "value">) {
const {
value: current,
setValue,
layoutId,
variant,
icons,
track,
placed,
tabStop,
registerTab,
unregisterTab,
panels,
tabId,
panelId,
} = useTabs();
const active = current === value;
const disabled = Boolean(props.disabled);
useLayoutEffect(() => {
registerTab(value, disabled);
}, [registerTab, value, disabled]);
useLayoutEffect(() => () => unregisterTab(value), [unregisterTab, value]);
const a11y = {
id: tabId(value),
"aria-controls": panels.has(value) ? panelId(value) : undefined,
tabIndex: !disabled && (tabStop === null || tabStop === value) ? 0 : -1,
};
const content = icon ? (
<>
<TriggerIcon icon={icon} active={active} />
{children}
</>
) : (
children
);
// React owns the initial mask only; TabsList synchronizes subsequent masks.
const [initialClip] = useState(() => active ? "inset(0)" : "inset(0 100% 0 0)");
if (variant === "underline") {
return (
<button
// Consumer ids and wiring win, e.g. several tabs sharing one panel.
{...a11y}
{...props}
type="button"
role="tab"
aria-selected={active}
onClick={(event) => {
onClick?.(event);
if (!event.defaultPrevented) 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 whitespace-nowrap shrink-0",
active ? "text-foreground" : "text-muted-foreground hover:text-foreground",
className,
)}
>
{content}
{active ? (
<motion.span
layoutId={layoutId}
layout
className={cn(
"absolute bottom-0 left-0 right-0 h-px bg-primary",
indicatorClassName,
)}
/>
) : null}
</button>
);
}
// Tracked pills are placed in the list, so this wrapper must not be their
// containing block. Server HTML can't measure, so until the first
// measurement the pill fills the selected tab with CSS, like the others.
const tracked = icons === "selected" && placed;
return (
<div className={cn("shrink-0", !tracked && "relative")}>
{/* Distinct keys: reused across the swap, the CSS pill's leftover
`transform: none` would hide the tracked pill's offset until the
next value change. */}
{active && tracked ? (
<motion.span
key="tracked"
data-tabs-indicator=""
style={{ ...track, borderRadius: 9999 }}
className={cn("absolute top-0 left-0 rounded-full bg-primary", indicatorClassName)}
/>
) : active ? (
<motion.span
key="layout"
data-tabs-indicator=""
layoutId={layoutId}
layout
style={{ borderRadius: 9999 }}
className={cn("absolute inset-0 rounded-full bg-primary", indicatorClassName)}
/>
) : null}
<button
// Consumer ids and wiring win, e.g. several tabs sharing one panel.
{...a11y}
{...props}
type="button"
role="tab"
aria-selected={active}
data-tabs-value={value}
onClick={(event) => {
onClick?.(event);
if (!event.defaultPrevented) 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",
"text-muted-foreground hover:text-foreground rounded-full",
className,
)}
>
{content}
<span
data-tabs-label=""
aria-hidden="true"
inert
className="pointer-events-none absolute inset-0 inline-flex items-center justify-center text-primary-foreground [gap:inherit] [padding:inherit]"
style={{ clipPath: initialClip }}
>
{content}
</span>
</button>
</div>
);
}
export function TabsContent({
value,
children,
className,
}: {
/** The trigger value that shows this panel. */
value: string;
children: ReactNode;
className?: string;
}) {
const { value: current, registerPanel, unregisterPanel, tabId, panelId } = useTabs();
const reduce = useReducedMotion();
const active = current === value;
useLayoutEffect(() => {
registerPanel(value);
return () => unregisterPanel(value);
}, [registerPanel, unregisterPanel, value]);
const a11y = {
id: panelId(value),
role: "tabpanel",
"aria-labelledby": tabId(value),
} as const;
// 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 {...a11y} hidden className={className}>
{children}
</div>
);
}
return (
<motion.div
{...a11y}
// Reachable with Tab so a panel without controls can still be read.
tabIndex={0}
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 outline-none focus-visible:ring-2 focus-visible:ring-ring/40 rounded-md", className)}
>
{children}
</motion.div>
);
}
childrenReactNodeThe first screen, shown while `revealed` is false.
—revealedContentReactNodeThe screen the wave carries in when `revealed` turns true.
—revealedbooleanWhich screen shows. Flip it to play the wave; flipping it back plays the wave again toward the first screen.
—type?"vertical" | "horizontal" | "center"Shape of the wave front: a wide arc that travels up or down, a tall arc that travels sideways, or a ring from the centre. Default: "vertical"
verticalsourceRef?RefObject<HTMLElement | null>Element the wave leaves from, such as the confirm button. Without it the wave leaves from the last press inside, else from the bottom edge, the left edge or the centre.
—duration?numberTime the wave takes to cross the screen, in seconds. A short gather before it and the fading edge glow after it add about 1.3s. Default: 1.6
1.6colors?string[]Colours of the wave and the glow it leaves on the edges, any CSS colour. Default: amber, sky, pink, peach and cyan
["#ffc915", "#7ec4ff", "#eb64a0", "#ffb07a", "#7fd9ee"]distortion?numberHow far the wave swells the screen under it, in px. 0 turns the swell off. Default: 26
26onRevealComplete?((revealed: boolean) => void)Called when a wave finishes, with the `revealed` value it carried in.
—className?stringClasses merged onto the root element.
—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.
Select
Composable select primitives whose panel unfolds out of the trigger on one spring and pulls away into its own pill, plus a Morph variant where the trigger grows into the panel via shared layout.
Theme Toggle
Theme toggle button that repaints the whole page through the View Transition API: a rectangle or circle clip-path reveal, or slats that open across the screen like a shutter.
Updated