Bookshelf
Preview
"use client";
import { useState } from "react";
import { Bookshelf, type BookshelfBook } from "@/components/motion/bookshelf";
import { Switch } from "@/components/motion/switch";
const BOOKS: BookshelfBook[] = [
{ id: "walden", title: "Walden", author: "Henry David Thoreau", color: "#5b6248", thickness: 38 },
{ id: "meditations", title: "Meditations", author: "Marcus Aurelius", color: "#2f3a4a", thickness: 34 },
{ id: "art-of-war", title: "The Art of War", author: "Sun Tzu", color: "#b5452f", thickness: 28 },
{ id: "middlemarch", title: "Middlemarch", author: "George Eliot", color: "#e3d7b8", thickness: 52 },
{ id: "moby-dick", title: "Moby-Dick", author: "Herman Melville", color: "#1f4e79", thickness: 48 },
{ id: "frankenstein", title: "Frankenstein", author: "Mary Shelley", color: "#3b3b3b", thickness: 36 },
{ id: "the-prince", title: "The Prince", author: "Niccolò Machiavelli", color: "#d9a93f", thickness: 30 },
{ id: "leaves-of-grass", title: "Leaves of Grass", author: "Walt Whitman", color: "#3f6b4f", thickness: 42 },
{ id: "on-liberty", title: "On Liberty", author: "John Stuart Mill", color: "#8a8174", thickness: 32 },
{ id: "the-odyssey", title: "The Odyssey", author: "Homer", color: "#7a3b2e", thickness: 46 },
];
export function BookshelfPreview() {
const [sound, setSound] = useState(true);
return (
<div className="flex w-full flex-col items-center gap-3 p-6">
<Bookshelf
books={BOOKS}
defaultValue="middlemarch"
sound={sound}
className="w-full"
/>
<p className="text-xs text-muted-foreground">
Click a book to pull it out. Arrow keys browse the shelf.
</p>
<Switch
checked={sound}
onCheckedChange={setSound}
label="Sound"
className="origin-center scale-[0.85] [&_label]:text-sm"
/>
</div>
);
}
"use client";
// beui.dev/components/motion/bookshelf
import {
animate,
type MotionValue,
motion,
type Transition,
useMotionValue,
useReducedMotion,
useSpring,
useTransform,
} from "motion/react";
import {
type KeyboardEvent,
type PointerEvent as ReactPointerEvent,
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
type WheelEvent as ReactWheelEvent,
} from "react";
import { type BookSounds, createBookSounds } from "@/lib/book-sounds";
import { EASE_OUT, SPRING_MOUSE } from "@/lib/ease";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
import { useMessages } from "@/lib/i18n";
import { capturePointer, releasePointer, TOUCH_GESTURE_CLASS } from "@/lib/touch";
import { cn } from "@/lib/utils";
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const bookshelfMessages = {
label: "Bookshelf",
book: "{title}",
bookWithAuthor: "{title} by {author}",
};
export type BookshelfMessages = typeof bookshelfMessages;
export type BookshelfBook = {
id: string;
title: string;
author?: string;
/** Cloth color of the spine and cover. Any CSS color. */
color: string;
/** Text color on the spine and cover. Defaults to black or white, picked
* from `color` when it is a hex value, else white. */
textColor?: string;
/** Front cover image. Without one, the cover is typeset from the title and author. */
coverImage?: string;
/** Spine width in px. */
thickness?: number;
};
export interface BookshelfProps {
books: BookshelfBook[];
/** Id of the open book, or null. Pass to control the shelf. */
value?: string | null;
defaultValue?: string | null;
onValueChange?: (id: string | null) => void;
/** Book height in px. */
height?: number;
/** Cover width as a fraction of the height. */
coverRatio?: number;
/** Space between closed books in px. */
gap?: number;
/** Extra space on each side of the open book in px. */
openGap?: number;
/** Tilt the open cover toward the mouse. Mouse only, off with reduced motion. */
tilt?: boolean;
/** Play a slide as a book comes out or goes back, and a soft tap as the
* mouse runs along the spines. Default false. */
sound?: boolean;
/** Override any built-in string. */
labels?: Partial<BookshelfMessages>;
className?: string;
}
// A book turning in 3D reads as a physical object, so it gets a little more
// time than a UI transition. EASE_OUT front-loads most of each move.
// Opening pulls the book forward first and turns it a beat later; closing
// turns it back first and pushes it in a beat later, so the exit mirrors the
// entry.
const PULL = { duration: 0.42, ease: EASE_OUT };
const TURN = { duration: 0.5, ease: EASE_OUT };
const LAG = 0.08;
const INSTANT = { duration: 0 };
const FADE = { duration: 0.2, ease: EASE_OUT };
const DEFAULT_THICKNESS = 40;
const PERSPECTIVE = 1600;
// How far the open book comes toward the viewer, past the spines.
const PULL_DEPTH = 40;
// Hover: a finger hooks the top of the spine, lifts it and tips it out a little.
const HOVER_LIFT = 8;
const HOVER_DEPTH = 10;
const HOVER_TIP = 5;
// Largest cursor tilt of the open cover, in degrees.
const MAX_TILT = 6;
// Shade at the far end of a turn: a face turned side-on to the viewer.
const SIDE_SHADE = 0.5;
// A drag starts after this many px sideways, so a tap stays a tap.
const DRAG_SLOP = 6;
// How far a released drag keeps gliding: velocity (px/s) times this.
const FLING = 0.22;
// Past either end, the row follows the finger at this fraction.
const RUBBER = 0.3;
function readableText(color: string) {
const hex = color.trim().match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i)?.[1];
if (!hex) return "#ffffff";
const full =
hex.length === 3
? hex
.split("")
.map((c) => c + c)
.join("")
: hex;
const [r, g, b] = [0, 2, 4].map(
(i) => Number.parseInt(full.slice(i, i + 2), 16) / 255,
);
const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
return luminance > 0.55 ? "#1c1917" : "#fafaf9";
}
type Layout = { slots: number[]; width: number };
function layoutShelf(
books: BookshelfBook[],
openIndex: number,
cover: number,
gap: number,
openGap: number,
): Layout {
const slots: number[] = [];
let x = 0;
books.forEach((book, i) => {
const open = i === openIndex;
if (i > 0) x += open || i - 1 === openIndex ? openGap : gap;
slots.push(x);
x += open ? cover : (book.thickness ?? DEFAULT_THICKNESS);
});
return { slots, width: x };
}
// The focus outline is drawn on the book's faces, so it follows the 3D book
// rather than the flat hit button that holds focus.
const FOCUS_RING =
"group-has-[button:focus-visible]:outline-2 group-has-[button:focus-visible]:outline-offset-2 group-has-[button:focus-visible]:outline-ring";
function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
export function Bookshelf({
books,
value,
defaultValue = null,
onValueChange,
height = 300,
coverRatio = 0.68,
gap = 3,
openGap = 16,
tilt = true,
sound = false,
labels,
className,
}: BookshelfProps) {
const t = useMessages("bookshelf", bookshelfMessages, labels);
const reduce = useReducedMotion() ?? false;
const canHover = useHoverCapable();
// Created on first use, so a silent shelf never touches Web Audio.
const soundsRef = useRef<BookSounds | null>(null);
const sounds = useCallback(() => {
if (!sound) return null;
soundsRef.current ??= createBookSounds();
return soundsRef.current;
}, [sound]);
useEffect(
() => () => {
soundsRef.current?.dispose();
soundsRef.current = null;
},
[],
);
const [uncontrolled, setUncontrolled] = useState<string | null>(defaultValue);
const openId = value !== undefined ? value : uncontrolled;
const openIndex = books.findIndex((b) => b.id === openId);
// The book that just closed keeps painting above its neighbours until it
// is back on the shelf, so it never slips under them mid-turn.
const [closingId, setClosingId] = useState<string | null>(null);
const setOpen = useCallback(
(id: string | null) => {
if (id === openId) return;
setClosingId(openId);
if (value === undefined) setUncontrolled(id);
onValueChange?.(id);
// A switch plays only the new book's slide; two at once is noise.
if (id === null) sounds()?.push();
else sounds()?.pull();
},
[openId, value, onValueChange, sounds],
);
const cover = Math.round(height * coverRatio);
const closed = layoutShelf(books, -1, cover, gap, openGap);
const shelf = layoutShelf(books, openIndex, cover, gap, openGap);
// Fit the closed shelf to the container; an open book that no longer fits
// pans the row so it stays in view.
const frameRef = useRef<HTMLDivElement>(null);
const [frameWidth, setFrameWidth] = useState(0);
useLayoutEffect(() => {
const el = frameRef.current;
if (!el) return;
setFrameWidth(el.clientWidth);
const ro = new ResizeObserver(([entry]) =>
setFrameWidth(entry.contentRect.width),
);
ro.observe(el);
return () => ro.disconnect();
}, []);
const fit = frameWidth ? Math.min(1, frameWidth / closed.width) : 1;
const visible = frameWidth ? frameWidth / fit : shelf.width;
// Static per width, so the fade doesn't pop in and out as books open.
const canOverflow =
frameWidth > 0 && closed.width + cover + 2 * openGap > visible;
const overflowing = openIndex >= 0 && shelf.width > visible;
let rowX = -shelf.width / 2;
if (overflowing) {
const center = shelf.slots[openIndex] + cover / 2;
rowX = clamp(-center, visible / 2 - shelf.width, -visible / 2);
}
// Swipe (or scroll sideways) to see books cut off by the edges. The pan
// rides on top of the automatic centring and resets when a book opens.
const pan = useMotionValue(0);
const panMin = overflowing ? visible / 2 - shelf.width - rowX : 0;
const panMax = overflowing ? -visible / 2 - rowX : 0;
const panRange = useRef({ min: panMin, max: panMax, fit });
panRange.current = { min: panMin, max: panMax, fit };
useEffect(() => {
// Re-centre on every open, close or switch; the row's own move runs on
// the same timing, so the two read as one.
void openId;
if (pan.get() === 0) return;
const controls = animate(pan, 0, reduce ? INSTANT : TURN);
return () => controls.stop();
}, [openId, pan, reduce]);
const drag = useRef<{
id: number;
x: number;
y: number;
pan: number;
dragging: boolean;
lastX: number;
lastT: number;
vx: number;
} | null>(null);
const swallowClick = useRef(false);
const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {
swallowClick.current = false;
// Browsers only start audio from a gesture; unlock it on the first press.
sounds()?.prepare();
if (!overflowing) return;
pan.stop();
drag.current = {
id: e.pointerId,
x: e.clientX,
y: e.clientY,
pan: pan.get(),
dragging: false,
lastX: e.clientX,
lastT: performance.now(),
vx: 0,
};
};
const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {
const d = drag.current;
if (!d || d.id !== e.pointerId) return;
const dx = e.clientX - d.x;
if (!d.dragging) {
if (Math.abs(dx) < DRAG_SLOP || Math.abs(dx) < Math.abs(e.clientY - d.y)) {
return;
}
d.dragging = true;
capturePointer(e.currentTarget, e.pointerId);
}
const { min, max, fit: scale } = panRange.current;
const raw = d.pan + dx / scale;
const over = raw > max ? raw - max : raw < min ? raw - min : 0;
pan.set(raw - over + over * RUBBER);
const now = performance.now();
const dt = now - d.lastT;
if (dt > 0) d.vx = ((e.clientX - d.lastX) / dt) * 1000;
d.lastX = e.clientX;
d.lastT = now;
};
const onPointerUp = (e: ReactPointerEvent<HTMLDivElement>) => {
const d = drag.current;
if (!d || d.id !== e.pointerId) return;
drag.current = null;
if (!d.dragging) return;
releasePointer(e.currentTarget, e.pointerId);
swallowClick.current = true;
const { min, max, fit: scale } = panRange.current;
const target = clamp(pan.get() + (d.vx * FLING) / scale, min, max);
if (reduce) pan.set(target);
else animate(pan, target, TURN);
};
const onWheel = (e: ReactWheelEvent<HTMLDivElement>) => {
if (!overflowing || Math.abs(e.deltaX) <= Math.abs(e.deltaY)) return;
pan.stop();
const { min, max, fit: scale } = panRange.current;
pan.set(clamp(pan.get() - e.deltaX / scale, min, max));
};
const buttonsRef = useRef<(HTMLButtonElement | null)[]>([]);
const onKeyDown = (e: KeyboardEvent<HTMLUListElement>) => {
const index = buttonsRef.current.indexOf(e.target as HTMLButtonElement);
if (index < 0) return;
let next = index;
if (e.key === "ArrowRight" || e.key === "ArrowDown") next = index + 1;
else if (e.key === "ArrowLeft" || e.key === "ArrowUp") next = index - 1;
else if (e.key === "Home") next = 0;
else if (e.key === "End") next = books.length - 1;
else if (e.key === "Escape" && openId !== null) {
e.preventDefault();
setOpen(null);
return;
} else return;
e.preventDefault();
next = clamp(next, 0, books.length - 1);
buttonsRef.current[next]?.focus();
// Browsing with a book open keeps one open, like pulling the next one out.
if (openId !== null) setOpen(books[next].id);
};
const [hoverId, setHoverId] = useState<string | null>(null);
// Neighbours make room as the open book turns, so they share its lag.
const slide = reduce
? INSTANT
: { ...TURN, delay: openIndex >= 0 ? LAG : 0 };
return (
<div
ref={frameRef}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={onPointerUp}
onWheel={onWheel}
onClickCapture={(e) => {
// A swipe that ends on a book must not open it.
if (!swallowClick.current) return;
swallowClick.current = false;
e.preventDefault();
e.stopPropagation();
}}
className={cn(
"relative w-full touch-pan-y [clip-path:inset(0)]",
TOUCH_GESTURE_CLASS,
// Books cut by the edge fade out, so the row reads as continuing.
canOverflow &&
"[mask-image:linear-gradient(90deg,transparent,#000_28px,#000_calc(100%-28px),transparent)]",
className,
)}
// Room above and below for the open book coming forward and its shadow.
style={{ height: (height + 64) * fit }}
>
<div
className="absolute top-1/2 left-1/2"
style={{
width: 0,
height,
marginTop: -height / 2,
transform: `scale(${fit})`,
}}
>
{/* Flat on purpose: each book is its own 3D scene, painted in z-index
order, so an open book always sits in front of its neighbours.
The vanishing point is the centre of the frame. */}
<ul
aria-label={t("label")}
onKeyDown={onKeyDown}
className="absolute top-0 left-0 m-0 w-0 list-none p-0"
style={{
height,
perspective: PERSPECTIVE,
perspectiveOrigin: "0 50%",
}}
>
{books.map((book, i) => (
<Book
key={book.id}
book={book}
name={
book.author
? t("bookWithAuthor", { title: book.title, author: book.author })
: t("book", { title: book.title })
}
x={rowX + shelf.slots[i]}
slide={slide}
pan={pan}
open={i === openIndex}
closing={book.id === closingId}
hovered={canHover && hoverId === book.id}
tilt={tilt && canHover}
reduce={reduce}
height={height}
cover={cover}
buttonRef={(el) => {
buttonsRef.current[i] = el;
}}
onToggle={() => setOpen(i === openIndex ? null : book.id)}
onHover={(over) => {
setHoverId((id) => (over ? book.id : id === book.id ? null : id));
if (over && i !== openIndex) sounds()?.tap();
}}
onSettled={() =>
setClosingId((id) => (id === book.id ? null : id))
}
/>
))}
</ul>
</div>
</div>
);
}
function Book({
book,
name,
x,
slide,
pan,
open,
closing,
hovered,
tilt,
reduce,
height,
cover,
buttonRef,
onToggle,
onHover,
onSettled,
}: {
book: BookshelfBook;
name: string;
x: number;
slide: Transition;
pan: MotionValue<number>;
open: boolean;
closing: boolean;
hovered: boolean;
tilt: boolean;
reduce: boolean;
height: number;
cover: number;
buttonRef: (el: HTMLButtonElement | null) => void;
onToggle: () => void;
onHover: (over: boolean) => void;
onSettled: () => void;
}) {
const thickness = book.thickness ?? DEFAULT_THICKNESS;
const text = book.textColor ?? readableText(book.color);
const turned = open && !reduce;
const lifted = hovered && !open && !reduce;
// Offset that keeps the turned book's cover inside its slot and level with
// the spines: the box turns around its middle, then shifts by this much.
const turn = (cover - thickness) / 2;
// Each face darkens as it turns side-on to the viewer and lights up as it
// comes round to face them, tied to the angle so it stays in step when a
// turn is interrupted.
const angle = useMotionValue(turned ? -90 : 0);
const coverShade = useTransform(angle, [-90, 0], [0, SIDE_SHADE]);
const spineShade = useTransform(angle, [-90, 0], [SIDE_SHADE, 0]);
// Paint order follows the turn. While the cover is more than half turned
// toward the viewer the book is in front of its neighbours, so it paints
// over them (the open book over a closing one). Once it is side-on again,
// its cover runs back into the shelf; books left of centre show that side
// face, and it must stay behind the next spine instead of painting across
// it.
const frontZ = useTransform(angle, (a) => (a < -45 ? 3 : 1));
const backZ = useTransform(angle, (a) => (a < -45 ? 2 : 1));
// Reduced motion never turns: the flat open cover simply sits on top.
const zIndex = reduce ? (open ? 3 : 1) : open ? frontZ : closing ? backZ : 1;
const tiltX = useSpring(0, SPRING_MOUSE);
const tiltY = useSpring(0, SPRING_MOUSE);
const canTilt = tilt && turned;
useEffect(() => {
if (canTilt) return;
tiltX.set(0);
tiltY.set(0);
}, [canTilt, tiltX, tiltY]);
const onPointerMove = (e: ReactPointerEvent<HTMLButtonElement>) => {
if (!canTilt || e.pointerType !== "mouse") return;
// The hit button lies flat over the open cover, so its box is the cover's.
const rect = e.currentTarget.getBoundingClientRect();
if (!rect.width) return;
const px = clamp((e.clientX - rect.left) / rect.width, 0, 1);
const py = clamp((e.clientY - rect.top) / rect.height, 0, 1);
tiltY.set((px - 0.5) * 2 * MAX_TILT);
tiltX.set((0.5 - py) * 2 * MAX_TILT);
};
return (
<motion.li
className="group absolute top-0 left-0 [transform-style:preserve-3d]"
style={{ width: thickness, height, zIndex }}
initial={false}
animate={{ x }}
transition={slide}
>
<motion.span
className="absolute inset-0 block [transform-style:preserve-3d]"
style={{ x: pan }}
>
{/* The book is picture only. A browser hit-tests a 3D-turned cover
only inside its parent's box, which is the spine's, so the open
cover would ignore most clicks. A flat button over the book's
footprint (spine closed, cover open) takes the input instead. */}
<span
aria-hidden
className="pointer-events-none absolute inset-0 block [transform-style:preserve-3d]"
>
{/* Pull: off the shelf toward the viewer, or a lift and tip on hover. */}
<motion.span
className="absolute top-0 left-0 block [transform-style:preserve-3d]"
style={{
width: thickness,
height,
// Tips on the front-bottom edge, like a book hooked by its top.
transformOrigin: "50% 100% 0",
}}
initial={false}
animate={{
y: lifted ? -HOVER_LIFT : 0,
z: turned ? PULL_DEPTH : lifted ? HOVER_DEPTH : 0,
rotateX: lifted ? -HOVER_TIP : 0,
}}
transition={
reduce ? INSTANT : { ...PULL, delay: closing && !open ? LAG : 0 }
}
onAnimationComplete={() => {
if (closing && !open) onSettled();
}}
>
<Shadow open={open} cover={cover} height={height} reduce={reduce} />
{/* Tilt: the open cover leans toward the mouse. */}
<motion.span
className="absolute top-0 left-0 block [transform-style:preserve-3d]"
style={{
width: thickness,
height,
rotateX: tiltX,
rotateY: tiltY,
transformOrigin: `${cover / 2}px 50% 0`,
}}
>
{/* Turn: spine to cover, around the middle of the book. */}
<motion.span
className="absolute top-0 left-0 block [transform-style:preserve-3d]"
style={{
width: thickness,
height,
transformOrigin: `${thickness / 2}px 50% ${-cover / 2}px`,
}}
initial={false}
animate={{
x: turned ? turn : 0,
z: turned ? turn : 0,
rotateY: turned ? -90 : 0,
}}
transition={reduce ? INSTANT : { ...TURN, delay: open ? LAG : 0 }}
onUpdate={(latest) => {
const value = Number.parseFloat(String(latest.rotateY));
if (!Number.isNaN(value)) angle.set(value);
}}
>
<Spine
book={book}
text={text}
thickness={thickness}
height={height}
hidden={open && reduce}
shade={reduce ? null : spineShade}
/>
<Cover
book={book}
text={text}
thickness={thickness}
width={cover}
height={height}
reduce={reduce}
open={open}
shade={reduce ? null : coverShade}
/>
</motion.span>
</motion.span>
</motion.span>
</span>
<button
ref={buttonRef}
type="button"
aria-label={name}
aria-pressed={open}
onClick={onToggle}
onPointerEnter={(e) => {
if (e.pointerType === "mouse") onHover(true);
}}
onPointerLeave={() => {
onHover(false);
tiltX.set(0);
tiltY.set(0);
}}
onPointerMove={onPointerMove}
className="absolute top-0 left-0 cursor-pointer border-0 bg-transparent p-0 outline-none"
style={{ width: open ? cover : thickness, height }}
/>
</motion.span>
</motion.li>
);
}
function Shadow({
open,
cover,
height,
reduce,
}: {
open: boolean;
cover: number;
height: number;
reduce: boolean;
}) {
// A soft pool under the open book that spreads as it comes off the shelf.
// It sits where the turned cover lands, and paints first so the book
// covers its top edge.
return (
<motion.span
className="pointer-events-none absolute left-0 block bg-[radial-gradient(closest-side,rgba(0,0,0,0.42),rgba(0,0,0,0))]"
// A hair behind the cover's plane, so the two never fight for depth.
style={{ top: height - 12, width: cover, height: 28, z: -2 }}
initial={false}
animate={{ opacity: open ? 1 : 0, scaleX: open || reduce ? 1 : 0.6 }}
transition={reduce ? FADE : PULL}
/>
);
}
function Shade({ opacity }: { opacity: MotionValue<number> | null }) {
if (!opacity) return null;
return (
<motion.span
className="pointer-events-none absolute inset-0 bg-black"
style={{ opacity }}
/>
);
}
function Spine({
book,
text,
thickness,
height,
hidden,
shade,
}: {
book: BookshelfBook;
text: string;
thickness: number;
height: number;
hidden: boolean;
shade: MotionValue<number> | null;
}) {
return (
<motion.span
className={cn(
"absolute top-0 left-0 flex flex-col items-center overflow-hidden rounded-[2px] py-3 [backface-visibility:hidden]",
FOCUS_RING,
)}
style={{ width: thickness, height, backgroundColor: book.color, color: text }}
initial={false}
animate={{ opacity: hidden ? 0 : 1 }}
transition={FADE}
>
{/* Rounded cloth: a dark rim on each edge and a soft highlight. */}
<span className="pointer-events-none absolute inset-0 bg-[linear-gradient(90deg,rgba(0,0,0,0.28),rgba(255,255,255,0.14)_28%,rgba(255,255,255,0)_55%,rgba(0,0,0,0.22))]" />
<span className="pointer-events-none absolute inset-x-0 top-2 h-px bg-current opacity-30" />
<span className="pointer-events-none absolute inset-x-0 bottom-2 h-px bg-current opacity-30" />
{book.author ? (
<span className="relative max-h-[30%] min-h-0 overflow-hidden text-ellipsis whitespace-nowrap font-sans text-[9px] uppercase tracking-[0.14em] opacity-75 [writing-mode:vertical-rl]">
{book.author}
</span>
) : null}
<span className="relative mt-3 min-h-0 flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-serif text-[13px] leading-none [writing-mode:vertical-rl]">
{book.title}
</span>
<Shade opacity={shade} />
</motion.span>
);
}
function Cover({
book,
text,
thickness,
width,
height,
reduce,
open,
shade,
}: {
book: BookshelfBook;
text: string;
thickness: number;
width: number;
height: number;
reduce: boolean;
open: boolean;
shade: MotionValue<number> | null;
}) {
// Closed, the cover runs back from the spine's right edge into the shelf,
// facing right: books left of centre show it, books right of centre hide
// its back face. With reduced motion the book never turns: the cover lies
// flat and fades in over the spine instead.
const flat = reduce;
return (
<motion.span
className={cn(
"absolute top-0 left-0 flex flex-col justify-between overflow-hidden rounded-r-[3px] rounded-l-[2px] p-5 text-left [backface-visibility:hidden]",
FOCUS_RING,
)}
style={{
width,
height,
backgroundColor: book.color,
color: text,
transformOrigin: "0 50%",
transform: flat ? "none" : `translateX(${thickness}px) rotateY(90deg)`,
}}
initial={false}
animate={{ opacity: flat && !open ? 0 : 1 }}
transition={FADE}
>
{book.coverImage ? (
<img
src={book.coverImage}
alt=""
draggable={false}
className="absolute inset-0 h-full w-full object-cover"
/>
) : (
<>
<span className="relative line-clamp-4 font-serif text-xl leading-tight">
{book.title}
</span>
{book.author ? (
<span className="relative font-sans text-[10px] uppercase tracking-[0.14em] opacity-75">
{book.author}
</span>
) : null}
</>
)}
{/* Hinge: the board folds into the spine a few px in from the edge. */}
<span className="pointer-events-none absolute inset-0 bg-[linear-gradient(90deg,rgba(0,0,0,0.35),rgba(255,255,255,0.1)_3%,rgba(0,0,0,0.12)_5%,rgba(0,0,0,0)_9%)]" />
<Shade opacity={shade} />
</motion.span>
);
}
Install
Add it with the shadcn CLI, or copy the source manually.
shadcn init? You are set. Theme setupInstall dependencies
npm i clsx motion tailwind-mergeAdd util files
// Synthesized bookshelf feedback, built from noise and a sine at runtime so
// there are no audio files to ship:
// - pull: a finger catches the spine, the book drags out against its
// neighbours with a grainy cloth-on-wood friction, and the board lands
// face-on with a soft papery thump;
// - push: the same friction going back in, then a woody tock as it seats;
// - tap: a dry tick as a finger runs along the spines.
// Every sound is noise shaped by a filter and an envelope; pitched tones only
// add a short, low body under a thump, never a melody, so nothing reads as
// a synth.
import { getAudioContext, retainAudioContext } from "@/lib/audio-context";
const MASTER_GAIN = 0.2;
// Running the pointer quickly along the spines riffles them, but not faster
// than this, so a fast sweep stays a texture instead of a buzz.
const MIN_TAP_GAP = 0.045; // seconds
// When the animation reaches the moment each sound marks. The book pulls
// most of the way out and its cover comes round by about here...
const LAND_AT = 0.2;
// ...and on the way back the push, which starts a beat after the turn,
// seats the book about here.
const SEAT_AT = 0.22;
type Output = { master: GainNode; white: AudioBuffer; friction: AudioBuffer };
// The context is shared page-wide (lib/audio-context.ts). The master gain and
// the noise buffers belong to it, so they are rebuilt if it was closed and
// recreated.
let output: Output | null = null;
function whiteNoise(ctx: AudioContext, seconds: number) {
const length = Math.ceil(ctx.sampleRate * seconds);
const buffer = ctx.createBuffer(1, length, ctx.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < length; i++) data[i] = Math.random() * 2 - 1;
return buffer;
}
/**
* Noise with a stick-slip grain: its loudness wanders every few
* milliseconds, with the odd louder catch, the way cloth judders across
* wood. Filtered, it reads as friction rather than air.
*/
function frictionNoise(ctx: AudioContext, seconds: number) {
const length = Math.ceil(ctx.sampleRate * seconds);
const buffer = ctx.createBuffer(1, length, ctx.sampleRate);
const data = buffer.getChannelData(0);
const grain = Math.max(1, Math.round(ctx.sampleRate * 0.003));
let target = 0.6;
let amp = 0.6;
for (let i = 0; i < length; i++) {
if (i % grain === 0) {
target = Math.random() < 0.06 ? 1.5 : 0.3 + Math.random() * 0.7;
}
amp += (target - amp) * 0.02;
data[i] = (Math.random() * 2 - 1) * amp;
}
return buffer;
}
function ensureOutput() {
const ctx = getAudioContext();
if (!ctx) return null;
if (output?.master.context !== ctx) {
const master = ctx.createGain();
master.gain.value = MASTER_GAIN;
master.connect(ctx.destination);
output = {
master,
white: whiteNoise(ctx, 0.5),
friction: frictionNoise(ctx, 0.6),
};
}
return { ctx, ...output };
}
/**
* Filtered noise that rises over `attack` and then tails off over about
* `decay`. The tail is a natural decay toward silence rather than a ramp to
* a fixed floor: a ramp to near-zero falls ~80dB and is gone by its first
* third, so a slide would sound like a click.
*/
function burst(
ctx: AudioContext,
out: Output,
buffer: AudioBuffer,
at: number,
{
type,
frequency,
to,
q = 0.8,
attack,
decay,
gain,
}: {
type: BiquadFilterType;
frequency: number;
/** Sweep the filter to this frequency over the sound. */
to?: number;
q?: number;
attack: number;
decay: number;
gain: number;
},
) {
const peakAt = at + attack;
// Three time constants of decay is about -26dB, where the sound reads as
// over; it keeps running to ~-42dB so the tail never cuts off.
const end = peakAt + decay * 1.6;
const source = ctx.createBufferSource();
source.buffer = buffer;
const filter = ctx.createBiquadFilter();
filter.type = type;
filter.Q.value = q;
filter.frequency.setValueAtTime(frequency, at);
if (to) filter.frequency.exponentialRampToValueAtTime(to, peakAt + decay);
const env = ctx.createGain();
env.gain.setValueAtTime(0, at);
env.gain.linearRampToValueAtTime(gain, peakAt);
env.gain.setTargetAtTime(0, peakAt, decay / 3);
source.connect(filter).connect(env).connect(out.master);
// A random start in the buffer, so repeats never sound identical.
const offset = Math.random() * Math.max(0, buffer.duration - (end - at) - 0.01);
source.start(at, offset);
source.stop(end + 0.02);
source.onended = () => env.disconnect();
}
/** A short low sine under a thump: the hollow of a board or a shelf. */
function body(
ctx: AudioContext,
out: Output,
at: number,
{ frequency, decay, gain }: { frequency: number; decay: number; gain: number },
) {
const osc = ctx.createOscillator();
const env = ctx.createGain();
osc.type = "sine";
osc.frequency.setValueAtTime(frequency, at);
// Settles a touch flat, like a struck panel, without the drum-like drop.
osc.frequency.exponentialRampToValueAtTime(frequency * 0.88, at + decay);
env.gain.setValueAtTime(0.0001, at);
env.gain.exponentialRampToValueAtTime(gain, at + 0.003);
env.gain.exponentialRampToValueAtTime(0.0001, at + decay);
osc.connect(env).connect(out.master);
osc.start(at);
osc.stop(at + decay + 0.02);
osc.onended = () => env.disconnect();
}
export interface BookSounds {
/** Unlock audio; call from a click, tap or key handler. */
prepare: () => void;
/** A book sliding off the shelf and turning to face the viewer. */
pull: () => void;
/** A book sliding back in and seating. */
push: () => void;
/** A finger catching a spine. */
tap: () => void;
dispose: () => void;
}
/**
* Lazily-initialized bookshelf sounds on the page's shared AudioContext.
* Nothing is created until the first call. Safe during SSR and without Web
* Audio: every call becomes a silent no-op.
*/
export function createBookSounds(): BookSounds {
const release = retainAudioContext();
let disposed = false;
let lastTap = Number.NEGATIVE_INFINITY;
const live = () => (disposed ? null : ensureOutput());
return {
prepare() {
live();
},
pull() {
const out = live();
if (!out) return;
const { ctx } = out;
const now = ctx.currentTime;
// The finger catches the spine: a tiny dry tick.
burst(ctx, out, out.white, now, {
type: "highpass",
frequency: 3200,
attack: 0.001,
decay: 0.012,
gain: 0.3,
});
// Out it drags, brightening as it frees from its neighbours.
burst(ctx, out, out.friction, now + 0.008, {
type: "bandpass",
frequency: 850,
to: 2000,
q: 0.7,
attack: 0.05,
decay: 0.17,
gain: 0.75,
});
// The board comes round and lands face-on: soft, papery, a little hollow.
burst(ctx, out, out.white, now + LAND_AT, {
type: "lowpass",
frequency: 1100,
q: 0.5,
attack: 0.002,
decay: 0.06,
gain: 0.45,
});
body(ctx, out, now + LAND_AT, { frequency: 190, decay: 0.07, gain: 0.22 });
},
push() {
const out = live();
if (!out) return;
const { ctx } = out;
const now = ctx.currentTime;
// Back in it drags, darkening as it slides between its neighbours.
burst(ctx, out, out.friction, now, {
type: "bandpass",
frequency: 1800,
to: 750,
q: 0.7,
attack: 0.04,
decay: 0.17,
gain: 0.65,
});
// It seats with a woody tock: the contact click, the thump of the
// board on the shelf, and the shelf's low hollow under it.
burst(ctx, out, out.white, now + SEAT_AT, {
type: "highpass",
frequency: 2200,
attack: 0.001,
decay: 0.01,
gain: 0.35,
});
burst(ctx, out, out.white, now + SEAT_AT, {
type: "lowpass",
frequency: 600,
q: 0.6,
attack: 0.002,
decay: 0.08,
gain: 0.75,
});
body(ctx, out, now + SEAT_AT, { frequency: 115, decay: 0.09, gain: 0.4 });
},
tap() {
const out = live();
if (!out) return;
const { ctx } = out;
const now = ctx.currentTime;
if (now - lastTap < MIN_TAP_GAP) return;
lastTap = now;
// Barely there, and a little different each time, like real spines.
burst(ctx, out, out.friction, now, {
type: "bandpass",
frequency: 2600 + Math.random() * 900,
to: 1800,
attack: 0.004,
decay: 0.04,
gain: 0.3,
});
},
dispose() {
if (disposed) return;
disposed = true;
release();
},
};
}
// 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;
"use client";
import { useEffect, useState } from "react";
/**
* Returns true only on devices that have a true hover (mouse / trackpad).
* Touch devices fire phantom `:hover` on tap that sticks until tap-elsewhere
* — gate hover-only effects (scale lifts, magnetic pulls) behind this.
*/
export function useHoverCapable() {
const [canHover, setCanHover] = useState(false);
useEffect(() => {
if (typeof window === "undefined" || !window.matchMedia) return;
const mq = window.matchMedia("(hover: hover) and (pointer: fine)");
const update = () => setCanHover(mq.matches);
update();
mq.addEventListener?.("change", update);
return () => mq.removeEventListener?.("change", update);
}, []);
return canHover;
}
"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],
);
}
// Shared touch primitives. iOS and iPadOS run their own gestures on top of the
// page — the long-press selection callout and the selection it drags in with
// it — and they win: once the platform claims a touch it cancels ours
// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own
// their gesture have to opt out.
//
// What the two classes below cover, precisely:
// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:
// it is not a property other engines have, so it is inert everywhere else.
// - `user-select: none` stops the long-press selection on every engine,
// Android included, and stops a drag from painting a selection under the
// cursor. It is inherited, so it reaches every descendant — which is why the
// two classes differ only in whether they apply it unconditionally.
// What neither covers:
// - Chrome for Android's long-press menu on a link or an image. No CSS
// suppresses it; a gesture surface that wraps one needs its own
// `onContextMenu` with `preventDefault()`.
// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is
// not inherited and plain divs and buttons are not drag sources, so setting
// it on the surface does nothing — the child itself needs `draggable={false}`.
/**
* Classes for a surface that *is* the control: a thumb, a drum, a stage, a
* handle, a hold button. Selection is suppressed on every input, because a
* drag that highlights the control's own label is wrong on a mouse too.
* Compose with `touch-none` when the surface also owns the scroll axis — leave
* it off when the page must still scroll from there.
*/
export const TOUCH_GESTURE_CLASS = "select-none [-webkit-touch-callout:none]";
/**
* The same opt-out for a gesture surface that wraps content the consumer owns:
* a scroller, a context-menu trigger, a sheet header, a list row. Selection is
* suppressed only where the platform runs its own press gestures — a coarse
* pointer — so a mouse user can still select and copy that content. If the
* gesture itself would paint a selection under the cursor, add `select-none`
* for the duration of the gesture rather than reaching for
* `TOUCH_GESTURE_CLASS`.
*
* `pointer: coarse` describes the *primary* pointer and nothing else, so a
* hybrid machine reads it wrong in both directions: a tablet with a mouse
* plugged in keeps touch as primary and loses mouse selection, and a laptop
* with a touchscreen keeps the mouse as primary and leaves selection live
* under a finger. No media query can answer per interaction — the query is
* about the device, and the question is about the gesture in progress. The
* default stays here because it is right on the machines that are one thing or
* the other, and losing a selection is a nuisance; where the miss costs a
* *gesture* instead, the surface pairs it with `holdSelection` on the press.
*/
export const TOUCH_GESTURE_CONTENT_CLASS =
"[-webkit-touch-callout:none] pointer-coarse:select-none";
/**
* Suppress selection on `element` for as long as a gesture is running on it,
* whatever the primary pointer of the machine happens to be. Returns the
* release. Inline, so it wins over the class above and is gone again the
* moment the gesture ends.
*
* For the press gestures a native selection would otherwise steal — a
* long-press that opens a menu. Elsewhere prefer the classes: a surface that
* takes selection away for the whole session is a surface whose text nobody
* can copy.
*/
export function holdSelection(element: HTMLElement) {
element.style.setProperty("user-select", "none");
element.style.setProperty("-webkit-user-select", "none");
return () => {
element.style.removeProperty("user-select");
element.style.removeProperty("-webkit-user-select");
};
}
/**
* Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer
* is already gone by the time the handler runs — routine on iOS, where the
* system can claim the touch first — and an uncaught throw takes the rest of
* the handler, the gesture included, down with it. Touch pointers carry
* implicit capture anyway, so losing it is never fatal.
*/
export function capturePointer(element: Element, pointerId: number) {
try {
element.setPointerCapture(pointerId);
} catch {
// Pointer is no longer active — implicit capture still applies on touch.
}
}
/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */
export function releasePointer(element: Element, pointerId: number) {
try {
if (element.hasPointerCapture(pointerId)) {
element.releasePointerCapture(pointerId);
}
} catch {
// Capture was already dropped by the browser.
}
}
/**
* Whether this event came from a pointer that is *hovering*: not a touch, and
* not currently pressed. Which input the user is holding right now is not
* something a device capability can answer — a touchscreen laptop hovers and
* taps, and iPadOS reports a fine hovering pointer for a finger — so both
* paths stay live and each handler branches on the event it was given.
*
* A pen resting on the glass is making contact, not hovering: `buttons` is the
* tell, and it sends a pen tap down the same route a finger takes.
*
* This answers what an *enter* asks. A leave is the other half of a pair and
* has to be read against the enter that started it — `useHoverGesture` in
* `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it
* rather than asking this question twice.
*/
export const isHoveringPointer = (event: {
pointerType: string;
buttons: number;
}) => event.pointerType !== "touch" && event.buttons === 0;
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
// One AudioContext for every synthesized sound on the page (lib/tick-sound.ts,
// lib/game-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.
type AudioContextCtor = typeof AudioContext;
let context: AudioContext | null = null;
let users = 0;
/**
* 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;
}
};
}
/**
* The shared context, created on first call and resumed if suspended. Null
* during SSR and in browsers without Web Audio.
*/
export function getAudioContext(): AudioContext | 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;
}
Copy the source code
"use client";
// beui.dev/components/motion/bookshelf
import {
animate,
type MotionValue,
motion,
type Transition,
useMotionValue,
useReducedMotion,
useSpring,
useTransform,
} from "motion/react";
import {
type KeyboardEvent,
type PointerEvent as ReactPointerEvent,
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
type WheelEvent as ReactWheelEvent,
} from "react";
import { type BookSounds, createBookSounds } from "@/lib/book-sounds";
import { EASE_OUT, SPRING_MOUSE } from "@/lib/ease";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
import { useMessages } from "@/lib/i18n";
import { capturePointer, releasePointer, TOUCH_GESTURE_CLASS } from "@/lib/touch";
import { cn } from "@/lib/utils";
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const bookshelfMessages = {
label: "Bookshelf",
book: "{title}",
bookWithAuthor: "{title} by {author}",
};
export type BookshelfMessages = typeof bookshelfMessages;
export type BookshelfBook = {
id: string;
title: string;
author?: string;
/** Cloth color of the spine and cover. Any CSS color. */
color: string;
/** Text color on the spine and cover. Defaults to black or white, picked
* from `color` when it is a hex value, else white. */
textColor?: string;
/** Front cover image. Without one, the cover is typeset from the title and author. */
coverImage?: string;
/** Spine width in px. */
thickness?: number;
};
export interface BookshelfProps {
books: BookshelfBook[];
/** Id of the open book, or null. Pass to control the shelf. */
value?: string | null;
defaultValue?: string | null;
onValueChange?: (id: string | null) => void;
/** Book height in px. */
height?: number;
/** Cover width as a fraction of the height. */
coverRatio?: number;
/** Space between closed books in px. */
gap?: number;
/** Extra space on each side of the open book in px. */
openGap?: number;
/** Tilt the open cover toward the mouse. Mouse only, off with reduced motion. */
tilt?: boolean;
/** Play a slide as a book comes out or goes back, and a soft tap as the
* mouse runs along the spines. Default false. */
sound?: boolean;
/** Override any built-in string. */
labels?: Partial<BookshelfMessages>;
className?: string;
}
// A book turning in 3D reads as a physical object, so it gets a little more
// time than a UI transition. EASE_OUT front-loads most of each move.
// Opening pulls the book forward first and turns it a beat later; closing
// turns it back first and pushes it in a beat later, so the exit mirrors the
// entry.
const PULL = { duration: 0.42, ease: EASE_OUT };
const TURN = { duration: 0.5, ease: EASE_OUT };
const LAG = 0.08;
const INSTANT = { duration: 0 };
const FADE = { duration: 0.2, ease: EASE_OUT };
const DEFAULT_THICKNESS = 40;
const PERSPECTIVE = 1600;
// How far the open book comes toward the viewer, past the spines.
const PULL_DEPTH = 40;
// Hover: a finger hooks the top of the spine, lifts it and tips it out a little.
const HOVER_LIFT = 8;
const HOVER_DEPTH = 10;
const HOVER_TIP = 5;
// Largest cursor tilt of the open cover, in degrees.
const MAX_TILT = 6;
// Shade at the far end of a turn: a face turned side-on to the viewer.
const SIDE_SHADE = 0.5;
// A drag starts after this many px sideways, so a tap stays a tap.
const DRAG_SLOP = 6;
// How far a released drag keeps gliding: velocity (px/s) times this.
const FLING = 0.22;
// Past either end, the row follows the finger at this fraction.
const RUBBER = 0.3;
function readableText(color: string) {
const hex = color.trim().match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i)?.[1];
if (!hex) return "#ffffff";
const full =
hex.length === 3
? hex
.split("")
.map((c) => c + c)
.join("")
: hex;
const [r, g, b] = [0, 2, 4].map(
(i) => Number.parseInt(full.slice(i, i + 2), 16) / 255,
);
const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
return luminance > 0.55 ? "#1c1917" : "#fafaf9";
}
type Layout = { slots: number[]; width: number };
function layoutShelf(
books: BookshelfBook[],
openIndex: number,
cover: number,
gap: number,
openGap: number,
): Layout {
const slots: number[] = [];
let x = 0;
books.forEach((book, i) => {
const open = i === openIndex;
if (i > 0) x += open || i - 1 === openIndex ? openGap : gap;
slots.push(x);
x += open ? cover : (book.thickness ?? DEFAULT_THICKNESS);
});
return { slots, width: x };
}
// The focus outline is drawn on the book's faces, so it follows the 3D book
// rather than the flat hit button that holds focus.
const FOCUS_RING =
"group-has-[button:focus-visible]:outline-2 group-has-[button:focus-visible]:outline-offset-2 group-has-[button:focus-visible]:outline-ring";
function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
export function Bookshelf({
books,
value,
defaultValue = null,
onValueChange,
height = 300,
coverRatio = 0.68,
gap = 3,
openGap = 16,
tilt = true,
sound = false,
labels,
className,
}: BookshelfProps) {
const t = useMessages("bookshelf", bookshelfMessages, labels);
const reduce = useReducedMotion() ?? false;
const canHover = useHoverCapable();
// Created on first use, so a silent shelf never touches Web Audio.
const soundsRef = useRef<BookSounds | null>(null);
const sounds = useCallback(() => {
if (!sound) return null;
soundsRef.current ??= createBookSounds();
return soundsRef.current;
}, [sound]);
useEffect(
() => () => {
soundsRef.current?.dispose();
soundsRef.current = null;
},
[],
);
const [uncontrolled, setUncontrolled] = useState<string | null>(defaultValue);
const openId = value !== undefined ? value : uncontrolled;
const openIndex = books.findIndex((b) => b.id === openId);
// The book that just closed keeps painting above its neighbours until it
// is back on the shelf, so it never slips under them mid-turn.
const [closingId, setClosingId] = useState<string | null>(null);
const setOpen = useCallback(
(id: string | null) => {
if (id === openId) return;
setClosingId(openId);
if (value === undefined) setUncontrolled(id);
onValueChange?.(id);
// A switch plays only the new book's slide; two at once is noise.
if (id === null) sounds()?.push();
else sounds()?.pull();
},
[openId, value, onValueChange, sounds],
);
const cover = Math.round(height * coverRatio);
const closed = layoutShelf(books, -1, cover, gap, openGap);
const shelf = layoutShelf(books, openIndex, cover, gap, openGap);
// Fit the closed shelf to the container; an open book that no longer fits
// pans the row so it stays in view.
const frameRef = useRef<HTMLDivElement>(null);
const [frameWidth, setFrameWidth] = useState(0);
useLayoutEffect(() => {
const el = frameRef.current;
if (!el) return;
setFrameWidth(el.clientWidth);
const ro = new ResizeObserver(([entry]) =>
setFrameWidth(entry.contentRect.width),
);
ro.observe(el);
return () => ro.disconnect();
}, []);
const fit = frameWidth ? Math.min(1, frameWidth / closed.width) : 1;
const visible = frameWidth ? frameWidth / fit : shelf.width;
// Static per width, so the fade doesn't pop in and out as books open.
const canOverflow =
frameWidth > 0 && closed.width + cover + 2 * openGap > visible;
const overflowing = openIndex >= 0 && shelf.width > visible;
let rowX = -shelf.width / 2;
if (overflowing) {
const center = shelf.slots[openIndex] + cover / 2;
rowX = clamp(-center, visible / 2 - shelf.width, -visible / 2);
}
// Swipe (or scroll sideways) to see books cut off by the edges. The pan
// rides on top of the automatic centring and resets when a book opens.
const pan = useMotionValue(0);
const panMin = overflowing ? visible / 2 - shelf.width - rowX : 0;
const panMax = overflowing ? -visible / 2 - rowX : 0;
const panRange = useRef({ min: panMin, max: panMax, fit });
panRange.current = { min: panMin, max: panMax, fit };
useEffect(() => {
// Re-centre on every open, close or switch; the row's own move runs on
// the same timing, so the two read as one.
void openId;
if (pan.get() === 0) return;
const controls = animate(pan, 0, reduce ? INSTANT : TURN);
return () => controls.stop();
}, [openId, pan, reduce]);
const drag = useRef<{
id: number;
x: number;
y: number;
pan: number;
dragging: boolean;
lastX: number;
lastT: number;
vx: number;
} | null>(null);
const swallowClick = useRef(false);
const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {
swallowClick.current = false;
// Browsers only start audio from a gesture; unlock it on the first press.
sounds()?.prepare();
if (!overflowing) return;
pan.stop();
drag.current = {
id: e.pointerId,
x: e.clientX,
y: e.clientY,
pan: pan.get(),
dragging: false,
lastX: e.clientX,
lastT: performance.now(),
vx: 0,
};
};
const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {
const d = drag.current;
if (!d || d.id !== e.pointerId) return;
const dx = e.clientX - d.x;
if (!d.dragging) {
if (Math.abs(dx) < DRAG_SLOP || Math.abs(dx) < Math.abs(e.clientY - d.y)) {
return;
}
d.dragging = true;
capturePointer(e.currentTarget, e.pointerId);
}
const { min, max, fit: scale } = panRange.current;
const raw = d.pan + dx / scale;
const over = raw > max ? raw - max : raw < min ? raw - min : 0;
pan.set(raw - over + over * RUBBER);
const now = performance.now();
const dt = now - d.lastT;
if (dt > 0) d.vx = ((e.clientX - d.lastX) / dt) * 1000;
d.lastX = e.clientX;
d.lastT = now;
};
const onPointerUp = (e: ReactPointerEvent<HTMLDivElement>) => {
const d = drag.current;
if (!d || d.id !== e.pointerId) return;
drag.current = null;
if (!d.dragging) return;
releasePointer(e.currentTarget, e.pointerId);
swallowClick.current = true;
const { min, max, fit: scale } = panRange.current;
const target = clamp(pan.get() + (d.vx * FLING) / scale, min, max);
if (reduce) pan.set(target);
else animate(pan, target, TURN);
};
const onWheel = (e: ReactWheelEvent<HTMLDivElement>) => {
if (!overflowing || Math.abs(e.deltaX) <= Math.abs(e.deltaY)) return;
pan.stop();
const { min, max, fit: scale } = panRange.current;
pan.set(clamp(pan.get() - e.deltaX / scale, min, max));
};
const buttonsRef = useRef<(HTMLButtonElement | null)[]>([]);
const onKeyDown = (e: KeyboardEvent<HTMLUListElement>) => {
const index = buttonsRef.current.indexOf(e.target as HTMLButtonElement);
if (index < 0) return;
let next = index;
if (e.key === "ArrowRight" || e.key === "ArrowDown") next = index + 1;
else if (e.key === "ArrowLeft" || e.key === "ArrowUp") next = index - 1;
else if (e.key === "Home") next = 0;
else if (e.key === "End") next = books.length - 1;
else if (e.key === "Escape" && openId !== null) {
e.preventDefault();
setOpen(null);
return;
} else return;
e.preventDefault();
next = clamp(next, 0, books.length - 1);
buttonsRef.current[next]?.focus();
// Browsing with a book open keeps one open, like pulling the next one out.
if (openId !== null) setOpen(books[next].id);
};
const [hoverId, setHoverId] = useState<string | null>(null);
// Neighbours make room as the open book turns, so they share its lag.
const slide = reduce
? INSTANT
: { ...TURN, delay: openIndex >= 0 ? LAG : 0 };
return (
<div
ref={frameRef}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={onPointerUp}
onWheel={onWheel}
onClickCapture={(e) => {
// A swipe that ends on a book must not open it.
if (!swallowClick.current) return;
swallowClick.current = false;
e.preventDefault();
e.stopPropagation();
}}
className={cn(
"relative w-full touch-pan-y [clip-path:inset(0)]",
TOUCH_GESTURE_CLASS,
// Books cut by the edge fade out, so the row reads as continuing.
canOverflow &&
"[mask-image:linear-gradient(90deg,transparent,#000_28px,#000_calc(100%-28px),transparent)]",
className,
)}
// Room above and below for the open book coming forward and its shadow.
style={{ height: (height + 64) * fit }}
>
<div
className="absolute top-1/2 left-1/2"
style={{
width: 0,
height,
marginTop: -height / 2,
transform: `scale(${fit})`,
}}
>
{/* Flat on purpose: each book is its own 3D scene, painted in z-index
order, so an open book always sits in front of its neighbours.
The vanishing point is the centre of the frame. */}
<ul
aria-label={t("label")}
onKeyDown={onKeyDown}
className="absolute top-0 left-0 m-0 w-0 list-none p-0"
style={{
height,
perspective: PERSPECTIVE,
perspectiveOrigin: "0 50%",
}}
>
{books.map((book, i) => (
<Book
key={book.id}
book={book}
name={
book.author
? t("bookWithAuthor", { title: book.title, author: book.author })
: t("book", { title: book.title })
}
x={rowX + shelf.slots[i]}
slide={slide}
pan={pan}
open={i === openIndex}
closing={book.id === closingId}
hovered={canHover && hoverId === book.id}
tilt={tilt && canHover}
reduce={reduce}
height={height}
cover={cover}
buttonRef={(el) => {
buttonsRef.current[i] = el;
}}
onToggle={() => setOpen(i === openIndex ? null : book.id)}
onHover={(over) => {
setHoverId((id) => (over ? book.id : id === book.id ? null : id));
if (over && i !== openIndex) sounds()?.tap();
}}
onSettled={() =>
setClosingId((id) => (id === book.id ? null : id))
}
/>
))}
</ul>
</div>
</div>
);
}
function Book({
book,
name,
x,
slide,
pan,
open,
closing,
hovered,
tilt,
reduce,
height,
cover,
buttonRef,
onToggle,
onHover,
onSettled,
}: {
book: BookshelfBook;
name: string;
x: number;
slide: Transition;
pan: MotionValue<number>;
open: boolean;
closing: boolean;
hovered: boolean;
tilt: boolean;
reduce: boolean;
height: number;
cover: number;
buttonRef: (el: HTMLButtonElement | null) => void;
onToggle: () => void;
onHover: (over: boolean) => void;
onSettled: () => void;
}) {
const thickness = book.thickness ?? DEFAULT_THICKNESS;
const text = book.textColor ?? readableText(book.color);
const turned = open && !reduce;
const lifted = hovered && !open && !reduce;
// Offset that keeps the turned book's cover inside its slot and level with
// the spines: the box turns around its middle, then shifts by this much.
const turn = (cover - thickness) / 2;
// Each face darkens as it turns side-on to the viewer and lights up as it
// comes round to face them, tied to the angle so it stays in step when a
// turn is interrupted.
const angle = useMotionValue(turned ? -90 : 0);
const coverShade = useTransform(angle, [-90, 0], [0, SIDE_SHADE]);
const spineShade = useTransform(angle, [-90, 0], [SIDE_SHADE, 0]);
// Paint order follows the turn. While the cover is more than half turned
// toward the viewer the book is in front of its neighbours, so it paints
// over them (the open book over a closing one). Once it is side-on again,
// its cover runs back into the shelf; books left of centre show that side
// face, and it must stay behind the next spine instead of painting across
// it.
const frontZ = useTransform(angle, (a) => (a < -45 ? 3 : 1));
const backZ = useTransform(angle, (a) => (a < -45 ? 2 : 1));
// Reduced motion never turns: the flat open cover simply sits on top.
const zIndex = reduce ? (open ? 3 : 1) : open ? frontZ : closing ? backZ : 1;
const tiltX = useSpring(0, SPRING_MOUSE);
const tiltY = useSpring(0, SPRING_MOUSE);
const canTilt = tilt && turned;
useEffect(() => {
if (canTilt) return;
tiltX.set(0);
tiltY.set(0);
}, [canTilt, tiltX, tiltY]);
const onPointerMove = (e: ReactPointerEvent<HTMLButtonElement>) => {
if (!canTilt || e.pointerType !== "mouse") return;
// The hit button lies flat over the open cover, so its box is the cover's.
const rect = e.currentTarget.getBoundingClientRect();
if (!rect.width) return;
const px = clamp((e.clientX - rect.left) / rect.width, 0, 1);
const py = clamp((e.clientY - rect.top) / rect.height, 0, 1);
tiltY.set((px - 0.5) * 2 * MAX_TILT);
tiltX.set((0.5 - py) * 2 * MAX_TILT);
};
return (
<motion.li
className="group absolute top-0 left-0 [transform-style:preserve-3d]"
style={{ width: thickness, height, zIndex }}
initial={false}
animate={{ x }}
transition={slide}
>
<motion.span
className="absolute inset-0 block [transform-style:preserve-3d]"
style={{ x: pan }}
>
{/* The book is picture only. A browser hit-tests a 3D-turned cover
only inside its parent's box, which is the spine's, so the open
cover would ignore most clicks. A flat button over the book's
footprint (spine closed, cover open) takes the input instead. */}
<span
aria-hidden
className="pointer-events-none absolute inset-0 block [transform-style:preserve-3d]"
>
{/* Pull: off the shelf toward the viewer, or a lift and tip on hover. */}
<motion.span
className="absolute top-0 left-0 block [transform-style:preserve-3d]"
style={{
width: thickness,
height,
// Tips on the front-bottom edge, like a book hooked by its top.
transformOrigin: "50% 100% 0",
}}
initial={false}
animate={{
y: lifted ? -HOVER_LIFT : 0,
z: turned ? PULL_DEPTH : lifted ? HOVER_DEPTH : 0,
rotateX: lifted ? -HOVER_TIP : 0,
}}
transition={
reduce ? INSTANT : { ...PULL, delay: closing && !open ? LAG : 0 }
}
onAnimationComplete={() => {
if (closing && !open) onSettled();
}}
>
<Shadow open={open} cover={cover} height={height} reduce={reduce} />
{/* Tilt: the open cover leans toward the mouse. */}
<motion.span
className="absolute top-0 left-0 block [transform-style:preserve-3d]"
style={{
width: thickness,
height,
rotateX: tiltX,
rotateY: tiltY,
transformOrigin: `${cover / 2}px 50% 0`,
}}
>
{/* Turn: spine to cover, around the middle of the book. */}
<motion.span
className="absolute top-0 left-0 block [transform-style:preserve-3d]"
style={{
width: thickness,
height,
transformOrigin: `${thickness / 2}px 50% ${-cover / 2}px`,
}}
initial={false}
animate={{
x: turned ? turn : 0,
z: turned ? turn : 0,
rotateY: turned ? -90 : 0,
}}
transition={reduce ? INSTANT : { ...TURN, delay: open ? LAG : 0 }}
onUpdate={(latest) => {
const value = Number.parseFloat(String(latest.rotateY));
if (!Number.isNaN(value)) angle.set(value);
}}
>
<Spine
book={book}
text={text}
thickness={thickness}
height={height}
hidden={open && reduce}
shade={reduce ? null : spineShade}
/>
<Cover
book={book}
text={text}
thickness={thickness}
width={cover}
height={height}
reduce={reduce}
open={open}
shade={reduce ? null : coverShade}
/>
</motion.span>
</motion.span>
</motion.span>
</span>
<button
ref={buttonRef}
type="button"
aria-label={name}
aria-pressed={open}
onClick={onToggle}
onPointerEnter={(e) => {
if (e.pointerType === "mouse") onHover(true);
}}
onPointerLeave={() => {
onHover(false);
tiltX.set(0);
tiltY.set(0);
}}
onPointerMove={onPointerMove}
className="absolute top-0 left-0 cursor-pointer border-0 bg-transparent p-0 outline-none"
style={{ width: open ? cover : thickness, height }}
/>
</motion.span>
</motion.li>
);
}
function Shadow({
open,
cover,
height,
reduce,
}: {
open: boolean;
cover: number;
height: number;
reduce: boolean;
}) {
// A soft pool under the open book that spreads as it comes off the shelf.
// It sits where the turned cover lands, and paints first so the book
// covers its top edge.
return (
<motion.span
className="pointer-events-none absolute left-0 block bg-[radial-gradient(closest-side,rgba(0,0,0,0.42),rgba(0,0,0,0))]"
// A hair behind the cover's plane, so the two never fight for depth.
style={{ top: height - 12, width: cover, height: 28, z: -2 }}
initial={false}
animate={{ opacity: open ? 1 : 0, scaleX: open || reduce ? 1 : 0.6 }}
transition={reduce ? FADE : PULL}
/>
);
}
function Shade({ opacity }: { opacity: MotionValue<number> | null }) {
if (!opacity) return null;
return (
<motion.span
className="pointer-events-none absolute inset-0 bg-black"
style={{ opacity }}
/>
);
}
function Spine({
book,
text,
thickness,
height,
hidden,
shade,
}: {
book: BookshelfBook;
text: string;
thickness: number;
height: number;
hidden: boolean;
shade: MotionValue<number> | null;
}) {
return (
<motion.span
className={cn(
"absolute top-0 left-0 flex flex-col items-center overflow-hidden rounded-[2px] py-3 [backface-visibility:hidden]",
FOCUS_RING,
)}
style={{ width: thickness, height, backgroundColor: book.color, color: text }}
initial={false}
animate={{ opacity: hidden ? 0 : 1 }}
transition={FADE}
>
{/* Rounded cloth: a dark rim on each edge and a soft highlight. */}
<span className="pointer-events-none absolute inset-0 bg-[linear-gradient(90deg,rgba(0,0,0,0.28),rgba(255,255,255,0.14)_28%,rgba(255,255,255,0)_55%,rgba(0,0,0,0.22))]" />
<span className="pointer-events-none absolute inset-x-0 top-2 h-px bg-current opacity-30" />
<span className="pointer-events-none absolute inset-x-0 bottom-2 h-px bg-current opacity-30" />
{book.author ? (
<span className="relative max-h-[30%] min-h-0 overflow-hidden text-ellipsis whitespace-nowrap font-sans text-[9px] uppercase tracking-[0.14em] opacity-75 [writing-mode:vertical-rl]">
{book.author}
</span>
) : null}
<span className="relative mt-3 min-h-0 flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-serif text-[13px] leading-none [writing-mode:vertical-rl]">
{book.title}
</span>
<Shade opacity={shade} />
</motion.span>
);
}
function Cover({
book,
text,
thickness,
width,
height,
reduce,
open,
shade,
}: {
book: BookshelfBook;
text: string;
thickness: number;
width: number;
height: number;
reduce: boolean;
open: boolean;
shade: MotionValue<number> | null;
}) {
// Closed, the cover runs back from the spine's right edge into the shelf,
// facing right: books left of centre show it, books right of centre hide
// its back face. With reduced motion the book never turns: the cover lies
// flat and fades in over the spine instead.
const flat = reduce;
return (
<motion.span
className={cn(
"absolute top-0 left-0 flex flex-col justify-between overflow-hidden rounded-r-[3px] rounded-l-[2px] p-5 text-left [backface-visibility:hidden]",
FOCUS_RING,
)}
style={{
width,
height,
backgroundColor: book.color,
color: text,
transformOrigin: "0 50%",
transform: flat ? "none" : `translateX(${thickness}px) rotateY(90deg)`,
}}
initial={false}
animate={{ opacity: flat && !open ? 0 : 1 }}
transition={FADE}
>
{book.coverImage ? (
<img
src={book.coverImage}
alt=""
draggable={false}
className="absolute inset-0 h-full w-full object-cover"
/>
) : (
<>
<span className="relative line-clamp-4 font-serif text-xl leading-tight">
{book.title}
</span>
{book.author ? (
<span className="relative font-sans text-[10px] uppercase tracking-[0.14em] opacity-75">
{book.author}
</span>
) : null}
</>
)}
{/* Hinge: the board folds into the spine a few px in from the edge. */}
<span className="pointer-events-none absolute inset-0 bg-[linear-gradient(90deg,rgba(0,0,0,0.35),rgba(255,255,255,0.1)_3%,rgba(0,0,0,0.12)_5%,rgba(0,0,0,0)_9%)]" />
<Shade opacity={shade} />
</motion.span>
);
}
"use client";
import { animate, motion, MotionConfig, useReducedMotion } from "motion/react";
import { useEffect, useId, useRef, useState } from "react";
import { cn } from "@/lib/utils";
// Heavy, deliberate thumb — high mass keeps the travel weighty without wobble.
const THUMB_SPRING = { type: "spring", stiffness: 800, damping: 80, mass: 4 } as const;
export interface SwitchProps {
checked: boolean;
onCheckedChange: (checked: boolean) => void;
disabled?: boolean;
label?: string;
ariaLabel?: string;
className?: string;
}
export function Switch({
checked,
onCheckedChange,
disabled,
label,
ariaLabel,
className,
}: SwitchProps) {
const id = useId();
const thumbRef = useRef<HTMLDivElement>(null);
const reduce = useReducedMotion();
const [isPressed, setIsPressed] = useState(false);
// Disabled shake feedback when pressed.
useEffect(() => {
if (!thumbRef.current || reduce) return;
if (disabled && isPressed) {
animate(
thumbRef.current,
{ x: [0, -2, 2, -1, 0] },
{ delay: 0.2, duration: 0.6 },
);
}
}, [disabled, isPressed, reduce]);
const squish = !disabled && isPressed && !reduce;
return (
<MotionConfig transition={reduce ? { duration: 0 } : THUMB_SPRING}>
<span className={cn("inline-flex items-center gap-3", className)}>
<motion.button
id={id}
type="button"
role="switch"
aria-checked={checked}
aria-label={ariaLabel}
disabled={disabled}
onClick={() => !disabled && onCheckedChange(!checked)}
onPointerDown={() => setIsPressed(true)}
onPointerUp={() => setIsPressed(false)}
onPointerLeave={() => setIsPressed(false)}
initial={false}
data-state={checked ? "checked" : "unchecked"}
className={cn(
"group peer inline-flex h-7 w-12 shrink-0 cursor-pointer items-center px-1 rounded-full outline-none transition-colors duration-200",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
"disabled:cursor-not-allowed disabled:opacity-60",
checked ? "justify-end bg-primary" : "justify-start bg-muted-foreground/60",
)}
>
<motion.div
ref={thumbRef}
layout
animate={{ scale: squish ? 0.9 : 1 }}
className="pointer-events-none block h-5 w-5 rounded-full bg-background shadow-md"
>
{/* Stretch toward the destination while active. */}
<div
className={cn(
"size-5",
squish && (checked ? "ml-1" : "mr-1"),
)}
/>
</motion.div>
</motion.button>
{label ? (
<label htmlFor={id} className="cursor-pointer text-sm text-foreground">
{label}
</label>
) : null}
</span>
</MotionConfig>
);
}
API Reference
booksBookshelfBook[]—value?string | nullId of the open book, or null. Pass to control the shelf.
—defaultValue?string | nullnullonValueChange?((id: string | null) => void)—height?numberBook height in px.
300coverRatio?numberCover width as a fraction of the height.
0.68gap?numberSpace between closed books in px.
3openGap?numberExtra space on each side of the open book in px.
16tilt?booleanTilt the open cover toward the mouse. Mouse only, off with reduced motion.
truesound?booleanPlay a slide as a book comes out or goes back, and a soft tap as the mouse runs along the spines. Default false.
falselabels?Partial<{ label: string; book: string; bookWithAuthor: string; }>Override any built-in string.
—className?string—Related components
Popover
Gooey popover whose panel oozes out of the trigger through an SVG goo filter with a liquid neck that stretches and pinches, then crisp content fades in on top. The Morph variant reveals its full-size panel from the corner nearest the trigger on one synchronized spring clip. Click or hover trigger, controlled or uncontrolled.
Before After Slider
Compare two images with a draggable divider. Drag or click anywhere on the frame, use the arrow keys, and keep vertical page scroll on touch.
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.
Updated