Preview
"use client";
import { AddToCart } from "@/components/motion/add-to-cart";
export function AddToCartUsage() {
return <AddToCart />;
}
"use client";
// beui.dev/micro-interactions/add-to-cart
import { Minus, Plus, ShoppingBag, Trash2 } from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { DigitSwap } from "@/components/motion/digit-swap";
import { EASE_OUT, SPRING_SWAP } from "@/lib/ease";
import { useMessages } from "@/lib/i18n";
import { useSound } from "@/lib/sound";
import { deleteSound } from "@/lib/sounds/delete";
import { dropSound } from "@/lib/sounds/drop";
import { tickSound } from "@/lib/sounds/tick";
import { cn } from "@/lib/utils";
export const addToCartMessages = {
add: "Add to cart",
increase: "Add one",
decrease: "Remove one",
remove: "Remove from cart",
quantity: "{count} in cart",
};
export type AddToCartMessages = typeof addToCartMessages;
export interface AddToCartProps {
/** Items in the cart, for controlled use. 0 shows the add button. */
quantity?: number;
/** The initial quantity when uncontrolled. Default: 0 */
defaultQuantity?: number;
/** Called with the new quantity when an item is added or removed. */
onQuantityChange?: (quantity: number) => void;
/** Most items one cart line can hold. */
max?: number;
/** Blocks adding and stepping, and dims the button. Default: false */
disabled?: boolean;
/** Override any built-in string, e.g. for translation. */
labels?: Partial<AddToCartMessages>;
/** Play a drop on add, a tick per step and a crumple on remove. Off by default; a `SoundProvider` can mute it app-wide. */
sound?: boolean;
/**
* Resize the pill to fit each face (default). Turn it off and give it a
* width, for example `w-full`, to keep one size in both states.
*/
morphWidth?: boolean;
/** Classes merged onto the root element. */
className?: string;
}
const EXIT = { duration: 0.14, ease: EASE_OUT } as const;
// Faces fade in fast so the swap never shows an empty pill.
const FADE_IN = { duration: 0.12, ease: EASE_OUT } as const;
// The controls start this far toward the centre, so the stepper unfolds out
// of the spot the label left, and folds back into it.
const SPREAD = 10;
/**
* An add to cart button that morphs into a quantity stepper: the pill
* resizes, the label folds away, and minus and plus open out from the
* centre around a rolling count. Removing the last item folds it back.
*/
export function AddToCart({
quantity: quantityProp,
defaultQuantity = 0,
onQuantityChange,
max = 99,
disabled = false,
labels,
sound = false,
morphWidth = true,
className,
}: AddToCartProps) {
const t = useMessages("AddToCart", addToCartMessages, labels);
const reduce = Boolean(useReducedMotion());
const [internal, setInternal] = useState(defaultQuantity);
const quantity = quantityProp ?? internal;
const playAdd = useSound(dropSound, { enabled: sound });
const playStep = useSound(tickSound, { enabled: sound });
const playRemove = useSound(deleteSound, { enabled: sound });
const [direction, setDirection] = useState<"up" | "down">("up");
const inCart = quantity > 0;
// Focus follows the face the user's own press swapped in.
const moveFocus = useRef(false);
const addRef = useRef<HTMLButtonElement>(null);
const increaseRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
if (!moveFocus.current) return;
moveFocus.current = false;
(inCart ? increaseRef : addRef).current?.focus();
}, [inCart]);
const change = (next: number) => {
const clamped = Math.max(0, Math.min(max, next));
if (clamped === quantity) return;
if (quantity === 0) playAdd();
else if (clamped === 0) playRemove();
else playStep({ pitch: clamped > quantity ? 1.1 : 0.9 });
if (clamped > 0 !== inCart) moveFocus.current = true;
setDirection(clamped > quantity ? "up" : "down");
if (quantityProp === undefined) setInternal(clamped);
onQuantityChange?.(clamped);
};
// The pill springs to the measured width of the face on show. Measured
// and animated directly rather than through layout projection, which
// can misplace children inside columns or transformed parents.
const faceRef = useRef<HTMLElement | null>(null);
const [width, setWidth] = useState<number>();
useLayoutEffect(() => {
if (!morphWidth) return;
const next = faceRef.current?.offsetWidth;
if (!next) return;
setWidth((current) => (current === next ? current : next));
});
const blur = reduce ? "blur(0px)" : "blur(3px)";
const side = (offset: number) => ({
initial: { opacity: 0, x: reduce ? 0 : offset, filter: blur },
animate: { opacity: 1, x: 0, filter: "blur(0px)" },
exit: { opacity: 0, x: reduce ? 0 : offset, filter: blur, transition: EXIT },
transition: { ...SPRING_SWAP, opacity: FADE_IN },
});
const stepButton = cn(
"inline-flex size-8 shrink-0 items-center justify-center rounded-full transition-colors",
// Inset rings: the pill clips anything drawn outside it.
"hover:bg-primary-foreground/15 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary-foreground/60",
"disabled:pointer-events-none disabled:opacity-50",
);
return (
<motion.div
initial={false}
animate={morphWidth && width ? { width } : undefined}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className={cn(
"relative inline-flex h-10 items-center justify-center overflow-hidden rounded-full bg-primary text-sm font-medium text-primary-foreground",
disabled && "opacity-50",
className,
)}
>
{/* The face on show stays in flow and sets the target width; the one
leaving pops out of flow and fades over it. */}
<AnimatePresence initial={false} mode="popLayout">
{inCart ? (
<motion.div
key="stepper"
ref={(node) => {
faceRef.current = node;
}}
className="flex shrink-0 items-center gap-1 px-1"
>
<motion.button
type="button"
className={stepButton}
disabled={disabled}
aria-label={quantity === 1 ? t("remove") : t("decrease")}
onClick={() => change(quantity - 1)}
{...side(SPREAD)}
>
<span aria-hidden="true" className="relative inline-flex size-4 items-center justify-center">
<AnimatePresence initial={false}>
<motion.span
key={quantity === 1 ? "trash" : "minus"}
className="absolute inset-0 inline-flex items-center justify-center"
initial={{ opacity: 0, y: reduce ? 0 : 6, filter: blur }}
animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
exit={{ opacity: 0, y: reduce ? 0 : -6, filter: blur, transition: EXIT }}
transition={SPRING_SWAP}
>
{quantity === 1 ? <Trash2 className="size-4" /> : <Minus className="size-4" />}
</motion.span>
</AnimatePresence>
</span>
</motion.button>
<motion.span
aria-live="polite"
className="min-w-8 text-center tabular-nums"
initial={{ opacity: 0, filter: blur }}
animate={{ opacity: 1, filter: "blur(0px)" }}
exit={{ opacity: 0, filter: blur, transition: EXIT }}
transition={SPRING_SWAP}
>
<span className="sr-only">{t("quantity", { count: quantity })}</span>
<span aria-hidden="true">
<DigitSwap value={quantity} direction={direction} />
</span>
</motion.span>
<motion.button
ref={increaseRef}
type="button"
className={stepButton}
disabled={disabled || quantity >= max}
aria-label={t("increase")}
onClick={() => change(quantity + 1)}
{...side(-SPREAD)}
>
<Plus aria-hidden="true" className="size-4" />
</motion.button>
</motion.div>
) : (
<motion.button
key="add"
ref={(node) => {
addRef.current = node;
faceRef.current = node;
}}
type="button"
disabled={disabled}
onClick={() => change(1)}
initial={{ opacity: 0, scale: reduce ? 1 : 0.92, filter: blur }}
animate={{ opacity: 1, scale: 1, filter: "blur(0px)" }}
exit={{ opacity: 0, scale: reduce ? 1 : 0.92, filter: blur, transition: EXIT }}
transition={{ ...SPRING_SWAP, opacity: FADE_IN }}
className={cn(
"inline-flex h-10 shrink-0 items-center justify-center gap-2 rounded-full px-5 whitespace-nowrap",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary-foreground/60",
)}
>
<ShoppingBag aria-hidden="true" className="size-4" />
{t("add")}
</motion.button>
)}
</AnimatePresence>
</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;
"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 short paper crumple that drops away, for removing or trashing an item. */
export const deleteSound = defineSound({
name: "Delete",
duration: 0.2,
room: 0.15,
build: (v) => {
// Crackles at random moments, each a little lower and quieter, so every
// crumple is different.
for (let i = 0; i < 7; i++) {
const at = i * 0.016 + Math.random() * 0.012;
v.click({ freq: 3000 - i * 300, q: 1.2, at, decay: 0.006 + Math.random() * 0.006, gain: 0.7 - i * 0.07 });
}
v.noise({ filter: "lowpass", freq: 2200, to: 300, q: 0.7, attack: 0.005, decay: 0.14, gain: 0.5 });
v.tone({ freq: 240, to: 110, attack: 0.004, decay: 0.12, gain: 0.35 });
},
});
import { defineSound } from "./engine";
/** A soft thud with a small bounce, like an item settling on a desk, for dropping a dragged item into place. */
export const dropSound = defineSound({
name: "Drop",
duration: 0.14,
room: 0.12,
build: (v) => {
v.click({ freq: 1500, q: 1, decay: 0.005, gain: 0.18 });
v.noise({ filter: "lowpass", freq: 700, attack: 0.001, decay: 0.03, gain: 0.35 });
v.strike({ freq: 140, material: "wood", bend: 1.4, decay: 0.09, gain: 0.9 });
v.click({ freq: 1500, q: 1, at: 0.075, decay: 0.004, gain: 0.07 });
v.strike({ freq: 150, material: "wood", bend: 1.3, at: 0.075, decay: 0.05, gain: 0.3 });
},
});
import { defineSound } from "./engine";
/** A tiny dry metal tick, for counters, sliders, pickers and loading steps. */
export const tickSound = defineSound({
name: "Tick",
duration: 0.02,
vary: 0.02,
// Dry, so fast repeats on a slider stay separate.
room: 0,
build: (v) => {
v.click({ freq: 5000, q: 3, decay: 0.0025, gain: 0.4 });
v.strike({ freq: 3400, material: "metal", decay: 0.01, gain: 0.32 });
},
});
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: 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/micro-interactions/add-to-cart
import { Minus, Plus, ShoppingBag, Trash2 } from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { DigitSwap } from "@/components/motion/digit-swap";
import { EASE_OUT, SPRING_SWAP } from "@/lib/ease";
import { useMessages } from "@/lib/i18n";
import { useSound } from "@/lib/sound";
import { deleteSound } from "@/lib/sounds/delete";
import { dropSound } from "@/lib/sounds/drop";
import { tickSound } from "@/lib/sounds/tick";
import { cn } from "@/lib/utils";
export const addToCartMessages = {
add: "Add to cart",
increase: "Add one",
decrease: "Remove one",
remove: "Remove from cart",
quantity: "{count} in cart",
};
export type AddToCartMessages = typeof addToCartMessages;
export interface AddToCartProps {
/** Items in the cart, for controlled use. 0 shows the add button. */
quantity?: number;
/** The initial quantity when uncontrolled. Default: 0 */
defaultQuantity?: number;
/** Called with the new quantity when an item is added or removed. */
onQuantityChange?: (quantity: number) => void;
/** Most items one cart line can hold. */
max?: number;
/** Blocks adding and stepping, and dims the button. Default: false */
disabled?: boolean;
/** Override any built-in string, e.g. for translation. */
labels?: Partial<AddToCartMessages>;
/** Play a drop on add, a tick per step and a crumple on remove. Off by default; a `SoundProvider` can mute it app-wide. */
sound?: boolean;
/**
* Resize the pill to fit each face (default). Turn it off and give it a
* width, for example `w-full`, to keep one size in both states.
*/
morphWidth?: boolean;
/** Classes merged onto the root element. */
className?: string;
}
const EXIT = { duration: 0.14, ease: EASE_OUT } as const;
// Faces fade in fast so the swap never shows an empty pill.
const FADE_IN = { duration: 0.12, ease: EASE_OUT } as const;
// The controls start this far toward the centre, so the stepper unfolds out
// of the spot the label left, and folds back into it.
const SPREAD = 10;
/**
* An add to cart button that morphs into a quantity stepper: the pill
* resizes, the label folds away, and minus and plus open out from the
* centre around a rolling count. Removing the last item folds it back.
*/
export function AddToCart({
quantity: quantityProp,
defaultQuantity = 0,
onQuantityChange,
max = 99,
disabled = false,
labels,
sound = false,
morphWidth = true,
className,
}: AddToCartProps) {
const t = useMessages("AddToCart", addToCartMessages, labels);
const reduce = Boolean(useReducedMotion());
const [internal, setInternal] = useState(defaultQuantity);
const quantity = quantityProp ?? internal;
const playAdd = useSound(dropSound, { enabled: sound });
const playStep = useSound(tickSound, { enabled: sound });
const playRemove = useSound(deleteSound, { enabled: sound });
const [direction, setDirection] = useState<"up" | "down">("up");
const inCart = quantity > 0;
// Focus follows the face the user's own press swapped in.
const moveFocus = useRef(false);
const addRef = useRef<HTMLButtonElement>(null);
const increaseRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
if (!moveFocus.current) return;
moveFocus.current = false;
(inCart ? increaseRef : addRef).current?.focus();
}, [inCart]);
const change = (next: number) => {
const clamped = Math.max(0, Math.min(max, next));
if (clamped === quantity) return;
if (quantity === 0) playAdd();
else if (clamped === 0) playRemove();
else playStep({ pitch: clamped > quantity ? 1.1 : 0.9 });
if (clamped > 0 !== inCart) moveFocus.current = true;
setDirection(clamped > quantity ? "up" : "down");
if (quantityProp === undefined) setInternal(clamped);
onQuantityChange?.(clamped);
};
// The pill springs to the measured width of the face on show. Measured
// and animated directly rather than through layout projection, which
// can misplace children inside columns or transformed parents.
const faceRef = useRef<HTMLElement | null>(null);
const [width, setWidth] = useState<number>();
useLayoutEffect(() => {
if (!morphWidth) return;
const next = faceRef.current?.offsetWidth;
if (!next) return;
setWidth((current) => (current === next ? current : next));
});
const blur = reduce ? "blur(0px)" : "blur(3px)";
const side = (offset: number) => ({
initial: { opacity: 0, x: reduce ? 0 : offset, filter: blur },
animate: { opacity: 1, x: 0, filter: "blur(0px)" },
exit: { opacity: 0, x: reduce ? 0 : offset, filter: blur, transition: EXIT },
transition: { ...SPRING_SWAP, opacity: FADE_IN },
});
const stepButton = cn(
"inline-flex size-8 shrink-0 items-center justify-center rounded-full transition-colors",
// Inset rings: the pill clips anything drawn outside it.
"hover:bg-primary-foreground/15 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary-foreground/60",
"disabled:pointer-events-none disabled:opacity-50",
);
return (
<motion.div
initial={false}
animate={morphWidth && width ? { width } : undefined}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className={cn(
"relative inline-flex h-10 items-center justify-center overflow-hidden rounded-full bg-primary text-sm font-medium text-primary-foreground",
disabled && "opacity-50",
className,
)}
>
{/* The face on show stays in flow and sets the target width; the one
leaving pops out of flow and fades over it. */}
<AnimatePresence initial={false} mode="popLayout">
{inCart ? (
<motion.div
key="stepper"
ref={(node) => {
faceRef.current = node;
}}
className="flex shrink-0 items-center gap-1 px-1"
>
<motion.button
type="button"
className={stepButton}
disabled={disabled}
aria-label={quantity === 1 ? t("remove") : t("decrease")}
onClick={() => change(quantity - 1)}
{...side(SPREAD)}
>
<span aria-hidden="true" className="relative inline-flex size-4 items-center justify-center">
<AnimatePresence initial={false}>
<motion.span
key={quantity === 1 ? "trash" : "minus"}
className="absolute inset-0 inline-flex items-center justify-center"
initial={{ opacity: 0, y: reduce ? 0 : 6, filter: blur }}
animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
exit={{ opacity: 0, y: reduce ? 0 : -6, filter: blur, transition: EXIT }}
transition={SPRING_SWAP}
>
{quantity === 1 ? <Trash2 className="size-4" /> : <Minus className="size-4" />}
</motion.span>
</AnimatePresence>
</span>
</motion.button>
<motion.span
aria-live="polite"
className="min-w-8 text-center tabular-nums"
initial={{ opacity: 0, filter: blur }}
animate={{ opacity: 1, filter: "blur(0px)" }}
exit={{ opacity: 0, filter: blur, transition: EXIT }}
transition={SPRING_SWAP}
>
<span className="sr-only">{t("quantity", { count: quantity })}</span>
<span aria-hidden="true">
<DigitSwap value={quantity} direction={direction} />
</span>
</motion.span>
<motion.button
ref={increaseRef}
type="button"
className={stepButton}
disabled={disabled || quantity >= max}
aria-label={t("increase")}
onClick={() => change(quantity + 1)}
{...side(-SPREAD)}
>
<Plus aria-hidden="true" className="size-4" />
</motion.button>
</motion.div>
) : (
<motion.button
key="add"
ref={(node) => {
addRef.current = node;
faceRef.current = node;
}}
type="button"
disabled={disabled}
onClick={() => change(1)}
initial={{ opacity: 0, scale: reduce ? 1 : 0.92, filter: blur }}
animate={{ opacity: 1, scale: 1, filter: "blur(0px)" }}
exit={{ opacity: 0, scale: reduce ? 1 : 0.92, filter: blur, transition: EXIT }}
transition={{ ...SPRING_SWAP, opacity: FADE_IN }}
className={cn(
"inline-flex h-10 shrink-0 items-center justify-center gap-2 rounded-full px-5 whitespace-nowrap",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary-foreground/60",
)}
>
<ShoppingBag aria-hidden="true" className="size-4" />
{t("add")}
</motion.button>
)}
</AnimatePresence>
</motion.div>
);
}
"use client";
// beui.dev/micro-interactions/add-to-cart
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type DigitSwapDirection = "up" | "down";
export interface DigitSwapProps {
/** Numeric or masked value rendered in fixed character slots. */
value: string | number;
/** Replays every glyph when the value itself contains unchanged characters. */
animationKey?: string | number;
/** Direction the next glyph enters from. */
direction?: DigitSwapDirection;
/** Per-glyph transition duration in seconds. */
duration?: number;
/** Delay in seconds between neighboring glyphs. */
stagger?: number;
/** Number of final characters that receive `suffixClassName`. */
suffixLength?: number;
/** Classes merged onto the root element. */
className?: string;
/** Classes merged onto every animated character. */
glyphClassName?: string;
/** Classes added to the last `suffixLength` characters. */
suffixClassName?: string;
}
type GlyphMotionContext = {
direction: DigitSwapDirection;
reduceMotion: boolean;
};
const GLYPH_VARIANTS = {
enter: ({ direction, reduceMotion }: GlyphMotionContext) => ({
opacity: 0,
transform: reduceMotion
? "none"
: `translateY(${direction === "up" ? "45%" : "-45%"})`,
}),
visible: {
opacity: 1,
transform: "translateY(0%)",
},
exit: ({ direction, reduceMotion }: GlyphMotionContext) => ({
opacity: 0,
transform: reduceMotion
? "none"
: `translateY(${direction === "up" ? "-45%" : "45%"})`,
}),
};
/**
* Fixed-slot digits and mask glyphs that roll when their value changes.
*
* Each slot holds an invisible in-flow copy of its character, so the slot has
* a real text baseline (it lines up with neighbouring text) and punctuation
* keeps its natural width. Digits use a fixed 1ch slot so rolls never jitter.
* Slots clip with `clip-path`, which, unlike `overflow: hidden`, leaves the
* baseline alone.
*/
export function DigitSwap({
value,
animationKey,
direction = "up",
duration = 0.18,
stagger = 0.006,
suffixLength = 0,
className,
glyphClassName,
suffixClassName,
}: DigitSwapProps) {
const reduceMotion = useReducedMotion() ?? false;
const text = String(value);
const suffixStart = Math.max(0, text.length - Math.max(0, suffixLength));
const motionContext: GlyphMotionContext = { direction, reduceMotion };
const glyphs = Array.from(text, (character, position) => ({
character,
id: `glyph-${position}`,
position,
}));
return (
<span
data-slot="digit-swap"
data-direction={direction}
className={cn("inline-flex items-baseline whitespace-nowrap", className)}
>
<span className="sr-only">{text}</span>
<span aria-hidden="true" className="inline-flex items-baseline">
{glyphs.map(({ character, id, position }) => {
if (character === " ") {
return <span key={id} className="inline-block w-[0.7ch]" />;
}
const glyphKey =
animationKey === undefined
? `${id}-${character}`
: `${id}-${character}-${animationKey}`;
return (
<span
key={id}
data-slot="digit-swap-glyph"
className={cn(
"relative inline-block h-[1.1em] shrink-0 leading-[1.1em] [clip-path:inset(0)]",
/\d/.test(character) && "w-[1ch] text-center",
)}
>
<span className="invisible">{character}</span>
<AnimatePresence initial={false} custom={motionContext}>
<motion.span
key={glyphKey}
custom={motionContext}
variants={GLYPH_VARIANTS}
initial="enter"
animate="visible"
exit="exit"
transition={{
duration: reduceMotion ? Math.min(duration, 0.12) : duration,
delay: reduceMotion ? 0 : position * stagger,
ease: EASE_OUT,
}}
className={cn(
"absolute inset-0 flex items-center justify-center leading-none",
glyphClassName,
position >= suffixStart ? suffixClassName : undefined,
)}
>
{character}
</motion.span>
</AnimatePresence>
</span>
);
})}
</span>
</span>
);
}
"use client";
import { useInView, useReducedMotion } from "motion/react";
import { createContext, type RefObject, useContext, useEffect, useRef, useState } from "react";
/**
* Lets a parent decide when previews play. The micro interactions gallery
* provides it, so its cards start still and play only from their play
* button. Without it a preview plays on its own.
*/
export const AutoplayContext = createContext<{ playing: boolean } | null>(null);
/**
* Plays a preview: calls `tick` every `interval` ms while the stage is on
* screen and the tab is visible. Under an AutoplayContext it plays only
* while `playing` is set; on its own it plays unless someone is hovering or
* focused inside it. Off entirely with reduced motion. Spread the returned
* props on the element that wraps the preview.
*/
export function useAutoplay(tick: () => void, interval: number) {
const ref = useRef<HTMLDivElement>(null);
const inView = useInView(ref as RefObject<Element>, { amount: 0.5 });
const reduce = useReducedMotion();
const control = useContext(AutoplayContext);
const [paused, setPaused] = useState(false);
// The latest tick, so the timer never restarts when the callback changes.
const tickRef = useRef(tick);
useEffect(() => {
tickRef.current = tick;
});
const running = control ? control.playing : !paused;
useEffect(() => {
if (!inView || !running || reduce) return;
// The first step plays right away, so pressing play answers at once.
if (control) tickRef.current();
const id = window.setInterval(() => {
if (document.visibilityState === "visible") tickRef.current();
}, interval);
return () => window.clearInterval(id);
}, [inView, running, reduce, interval, control]);
return {
ref,
onPointerEnter: () => setPaused(true),
onPointerLeave: () => setPaused(false),
onFocus: () => setPaused(true),
onBlur: () => setPaused(false),
};
}
quantity?numberItems in the cart, for controlled use. 0 shows the add button.
—defaultQuantity?numberThe initial quantity when uncontrolled. Default: 0
0onQuantityChange?((quantity: number) => void)Called with the new quantity when an item is added or removed.
—max?numberMost items one cart line can hold.
99disabled?booleanBlocks adding and stepping, and dims the button. Default: false
falselabels?Partial<{ add: string; increase: string; decrease: string; remove: string; quantity: string; }>Override any built-in string, e.g. for translation.
—sound?booleanPlay a drop on add, a tick per step and a crumple on remove. Off by default; a `SoundProvider` can mute it app-wide.
falsemorphWidth?booleanResize the pill to fit each face (default). Turn it off and give it a width, for example `w-full`, to keep one size in both states.
trueclassName?stringClasses merged onto the root element.
—Upvote Button
A vote toggle that fills with colour from the bottom as the arrow shoots out the top, a +1 floats away and the count rolls up.
Copy Button
Copies text and confirms it: the pill tints, the icon blurs into a check that draws its stroke, and Copy morphs letter by letter into Copied.
Refresh Button
Arrows that wind back, spin up into a breathing spinner arc, then coast to land upright and hand over to a check as Refresh morphs to Updated.
Updated