Preview
"use client";
import { ReactionPicker } from "@/components/motion/reaction-picker";
export function ReactionPickerUsage() {
return (
<div className="pt-12">
<ReactionPicker count={24} />
</div>
);
}
"use client";
// beui.dev/micro-interactions/reaction-picker
import { Flame, Heart, Laugh, PartyPopper, SmilePlus, ThumbsUp } from "lucide-react";
import {
AnimatePresence,
animate,
motion,
useMotionTemplate,
useMotionValue,
useReducedMotion,
useSpring,
useTransform,
useVelocity,
} from "motion/react";
import { type KeyboardEvent, type ReactNode, useEffect, useRef, useState } from "react";
import { DigitSwap } from "@/components/motion/digit-swap";
import { EASE_IN, EASE_IN_OUT, EASE_OUT, SPRING_PANEL, SPRING_PRESS } from "@/lib/ease";
import { useDismiss } from "@/lib/hooks/use-dismiss";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
import { useMessages } from "@/lib/i18n";
import { PresenceGate } from "@/lib/presence-gate";
import { useSound } from "@/lib/sound";
import { closeSound } from "@/lib/sounds/close";
import { openSound } from "@/lib/sounds/open";
import { selectSound } from "@/lib/sounds/select";
import { cn } from "@/lib/utils";
export const reactionPickerMessages = {
react: "Add reaction",
reacted: "Reacted with {reaction}",
reactions: "Reactions",
like: "Like",
love: "Love",
haha: "Haha",
fire: "Fire",
party: "Party",
};
export type ReactionPickerMessages = typeof reactionPickerMessages;
export type Reaction = {
/** Unique key, used as the picker's value. */
id: string;
/** Name shown above the reaction on hover and used as its accessible name. */
label: string;
/** Icon or emoji in the tray, which flies to the trigger once picked. */
icon: ReactNode;
/** Text colour class for the icon, e.g. "text-rose-500". */
color?: string;
/** Classes for the button once this reaction is picked. */
tint?: string;
};
export interface ReactionPickerProps {
/** The choices, in order. Defaults to like, love, haha, fire and party. */
reactions?: Reaction[];
/** The viewer's reaction id, or null for none. */
value?: string | null;
/** The initial reaction id when uncontrolled. Default: null */
defaultValue?: string | null;
/** Called with the picked reaction id, or null when the same one is picked again. */
onValueChange?: (value: string | null) => void;
/** Reactions from everyone else. The viewer's own is added on top. */
count?: number;
/** Override any built-in string, e.g. for translation. */
labels?: Partial<ReactionPickerMessages>;
/** Play open and close swishes for the tray and a select on a pick. Off by default; a `SoundProvider` can mute it app-wide. */
sound?: boolean;
/** Classes merged onto the root element. */
className?: string;
}
// Each reaction rises into the tray a beat after the one before it.
const STAGGER = 0.035;
const RISE = 12;
// Looser than SPRING_SWAP on purpose: each icon lands with a small settle.
const SPRING_RISE = { type: "spring", stiffness: 520, damping: 22, mass: 0.6 } as const;
// The hovered reaction lifts and grows quickly, and settles back as quickly.
const SPRING_HOVER = { type: "spring", stiffness: 600, damping: 26, mass: 0.5 } as const;
const OUT = { duration: 0.14, ease: EASE_OUT } as const;
// The flight: across evenly, up slowing into the peak and down speeding out
// of it, so it traces one smooth arc instead of stalling at the top.
const FLIGHT_SECONDS = 0.46;
const LIFT_SCALE = 1.25;
// It lands a touch large and the button's icon settles from there.
const LAND_SCALE = 1.15;
// The tray morphs out of the button: a pill clip that springs open from a
// circle the tray's height over the icon. Near critical, so it never snaps
// past open.
const SPRING_REVEAL = { type: "spring", stiffness: 340, damping: 32, mass: 0.8 } as const;
const TRAY_HEIGHT = 46;
// The hover blob glides between reactions, stretching with its speed.
const SPRING_BLOB = { stiffness: 520, damping: 34, mass: 0.6 } as const;
// One reaction slot: a 36px button plus the 2px gap.
const SLOT = 38;
// The catch: the icon lands squashed and wobbles back to shape.
const SPRING_JELLY = { type: "spring", stiffness: 620, damping: 14, mass: 0.6 } as const;
const SQUASH = { scaleX: 1.3, scaleY: 0.78 } as const;
// Sparks from the button when it catches a reaction, alternating near and far.
const SPARKS = Array.from({ length: 8 }, (_, index) => {
const angle = (index / 8) * Math.PI * 2;
const far = index % 2 === 0;
return { id: index, x: Math.cos(angle) * (far ? 18 : 13), y: Math.sin(angle) * (far ? 18 : 13), far };
});
type Point = { x: number; y: number };
/** A reaction in the air, and what the button showed before it was picked. */
type Flight = { id: number; reaction: Reaction; previous: Reaction | null; from: Point; to: Point; scale: number };
/** The centre of an element, relative to an origin rect. */
function centre(el: Element | null | undefined, origin: DOMRect): Point | null {
if (!el) return null;
const rect = el.getBoundingClientRect();
return { x: rect.left + rect.width / 2 - origin.left, y: rect.top + rect.height / 2 - origin.top };
}
/**
* A reaction button. Pressing it grows a tray out of the button with each
* reaction rising in turn; hovering one lifts it and shows its name. The one
* you pick arcs down onto the button, which catches it with a pop and a burst
* in the reaction's colour as the count rolls. Picking it again takes it back.
*/
export function ReactionPicker({
reactions: reactionsProp,
value: valueProp,
defaultValue = null,
onValueChange,
count = 0,
labels,
sound = false,
className,
}: ReactionPickerProps) {
const t = useMessages("ReactionPicker", reactionPickerMessages, labels);
const playOpen = useSound(openSound, { enabled: sound });
const playClose = useSound(closeSound, { enabled: sound });
const playPick = useSound(selectSound, { enabled: sound });
const reduce = Boolean(useReducedMotion());
const canHover = useHoverCapable();
const [internal, setInternal] = useState<string | null>(defaultValue);
const value = valueProp === undefined ? internal : valueProp;
const [open, setOpen] = useState(false);
const [active, setActive] = useState<string | null>(null);
const [flight, setFlight] = useState<Flight | null>(null);
// Counts catches, so each landing replays the pop and the sparks.
const [catches, setCatches] = useState(0);
const reactions: Reaction[] = reactionsProp ?? [
{
id: "like",
label: t("like"),
icon: <ThumbsUp className="size-5" />,
color: "text-sky-500",
tint: "border-sky-500/30 bg-sky-500/10 text-sky-600 dark:text-sky-400",
},
{
id: "love",
label: t("love"),
icon: <Heart className="size-5" />,
color: "text-rose-500",
tint: "border-rose-500/30 bg-rose-500/10 text-rose-600 dark:text-rose-400",
},
{
id: "haha",
label: t("haha"),
icon: <Laugh className="size-5" />,
color: "text-amber-500",
tint: "border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400",
},
{
id: "fire",
label: t("fire"),
icon: <Flame className="size-5" />,
color: "text-orange-500",
tint: "border-orange-500/30 bg-orange-500/10 text-orange-600 dark:text-orange-400",
},
{
id: "party",
label: t("party"),
icon: <PartyPopper className="size-5" />,
color: "text-emerald-500",
tint: "border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",
},
];
const chosen = reactions.find((reaction) => reaction.id === value) ?? null;
// While a reaction is in the air, the button still shows what it had, so
// nothing changes on it until the catch.
const shown = flight ? flight.previous : chosen;
const rootRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
const iconRef = useRef<HTMLSpanElement>(null);
const optionRefs = useRef<(HTMLButtonElement | null)[]>([]);
const optionIconRefs = useRef<(HTMLSpanElement | null)[]>([]);
// The tray's reveal: 1 is a circle over the icon, 0 is fully open. It
// springs open on open and morphs back into the circle as the tray leaves,
// so it is already closed when the next tray mounts and never flashes open
// for a frame (motion writes a reset value only on its next frame).
const reveal = useMotionValue(reduce ? 0 : 1);
const trayClip = useMotionTemplate`inset(0 calc((100% - ${TRAY_HEIGHT}px) * ${reveal}) 0 0 round 999px)`;
useEffect(() => {
if (reduce) {
reveal.jump(0);
return;
}
const controls = open ? animate(reveal, 0, SPRING_REVEAL) : animate(reveal, 1, OUT);
return () => controls.stop();
}, [open, reduce, reveal]);
// The hover blob: springs between slots and stretches with its speed.
const blobX = useSpring(0, SPRING_BLOB);
const blobSpeed = useVelocity(blobX);
const blobScaleX = useTransform(blobSpeed, (speed) => 1 + Math.min(Math.abs(speed) / 2200, 0.45));
const blobScaleY = useTransform(blobScaleX, (stretch) => 1 - (stretch - 1) * 0.35);
const activeIndex = reactions.findIndex((reaction) => reaction.id === active);
// Move the blob with the hover: it appears in place, then glides.
const hover = (id: string) => {
const index = reactions.findIndex((reaction) => reaction.id === id);
if (active === null || reduce) blobX.jump(index * SLOT);
else blobX.set(index * SLOT);
setActive(id);
};
// Close and hand focus back to the button when it was inside the tray.
const close = () => {
if (rootRef.current?.contains(document.activeElement)) triggerRef.current?.focus();
setOpen(false);
setActive(null);
};
// Closing without a pick; a pick closes quietly behind its own sound.
const dismiss = () => {
playClose();
close();
};
useDismiss(open, dismiss, rootRef);
// Opening by keyboard moves focus to the current reaction, or the first.
const focusOnOpen = useRef(false);
const startIndex = Math.max(0, reactions.findIndex((reaction) => reaction.id === value));
useEffect(() => {
if (!open || !focusOnOpen.current) return;
focusOnOpen.current = false;
optionRefs.current[startIndex]?.focus();
}, [open, startIndex]);
const pick = (reaction: Reaction, index: number) => {
const next = reaction.id === value ? null : reaction.id;
playPick({ pitch: next ? 1.1 : 0.85 });
// Measure both ends now, from the event, while the tray is still open:
// the icon itself, so a lifted one leaves from where it is drawn.
const root = rootRef.current?.getBoundingClientRect();
const source = optionIconRefs.current[index];
const from = root && centre(source, root);
const to = root && centre(iconRef.current, root);
if (next && from && to && !reduce) {
const scale = active === reaction.id ? LIFT_SCALE : 1;
setFlight({ id: Date.now(), reaction, previous: chosen, from, to, scale });
// The flying copy takes over from here; hide the original so it does
// not shrink away inside the closing tray beside it.
if (source) source.style.visibility = "hidden";
} else if (next) setCatches((value) => value + 1);
if (valueProp === undefined) setInternal(next);
onValueChange?.(next);
close();
};
const onTrayKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
const index = optionRefs.current.indexOf(document.activeElement as HTMLButtonElement);
const step = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0;
if (!step || index === -1) return;
event.preventDefault();
optionRefs.current[(index + step + reactions.length) % reactions.length]?.focus();
};
const total = count + (value ? 1 : 0);
return (
<div ref={rootRef} className={cn("relative inline-flex", className)}>
<motion.button
ref={triggerRef}
type="button"
aria-haspopup="true"
aria-expanded={open}
aria-label={chosen ? t("reacted", { reaction: chosen.label }) : t("react")}
whileTap={reduce ? undefined : { scale: 0.94 }}
transition={SPRING_PRESS}
onClick={() => {
if (open) return dismiss();
playOpen();
setOpen(true);
}}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " " || event.key === "ArrowUp") focusOnOpen.current = true;
if (event.key === "ArrowUp" && !open) {
event.preventDefault();
playOpen();
setOpen(true);
}
}}
className={cn(
"relative inline-flex h-9 items-center gap-1.5 rounded-full border pr-3.5 pl-2.5 text-sm font-medium tabular-nums transition-colors duration-200",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
shown?.tint ?? "border-border text-muted-foreground hover:bg-muted/60 hover:text-foreground",
)}
>
<span ref={iconRef} aria-hidden="true" className="relative inline-flex size-5 items-center justify-center">
{/* The catch: sparks in the reaction's colour from where it lands. */}
{catches > 0 && !reduce && chosen ? (
<span key={catches} className={cn("pointer-events-none absolute inset-0", chosen.color)}>
{SPARKS.map((spark) => (
<motion.span
key={spark.id}
className={cn("absolute top-1/2 left-1/2 rounded-full bg-current", spark.far ? "size-1" : "size-[3px]")}
style={{ translate: "-50% -50%" }}
initial={{ opacity: 0, x: 0, y: 0 }}
animate={{ opacity: [0, 1, 0], x: spark.x, y: spark.y }}
transition={{ duration: 0.5, ease: EASE_OUT, delay: spark.far ? 0 : 0.04 }}
/>
))}
</span>
) : null}
<AnimatePresence initial={false} mode="popLayout">
<motion.span
key={`${shown?.id ?? "none"}-${shown ? catches : 0}`}
className="inline-flex"
// A caught reaction takes over from the flying copy at its size
// and settles; the smiley comes back from above.
initial={
reduce
? { opacity: 0 }
: shown
? { opacity: 1, scaleX: LAND_SCALE * SQUASH.scaleX, scaleY: LAND_SCALE * SQUASH.scaleY, y: 0 }
: { opacity: 0, scaleX: 0.5, scaleY: 0.5, y: -6 }
}
animate={{ opacity: 1, scaleX: 1, scaleY: 1, y: 0 }}
exit={
reduce
? { opacity: 0, transition: OUT }
: { opacity: 0, y: 6, scaleX: 0.8, scaleY: 0.8, transition: OUT }
}
// A caught reaction wobbles back from the squash; the smiley just settles.
transition={shown ? SPRING_JELLY : SPRING_PRESS}
>
{shown ? shown.icon : <SmilePlus className="size-5" />}
</motion.span>
</AnimatePresence>
</span>
{total > 0 ? <DigitSwap value={total} direction={value ? "up" : "down"} /> : null}
</motion.button>
<AnimatePresence>
{open ? (
<PresenceGate>
{({ gate }) => (
<motion.div
role="group"
aria-label={t("reactions")}
onKeyDown={onTrayKeyDown}
onPointerLeave={() => setActive(null)}
// Rises out of the button's icon and sinks back into it: 20px in
// (padding plus half the icon), 26px below the tray (gap plus half the button).
style={{ transformOrigin: "20px calc(100% + 26px)", clipPath: trayClip, ...gate.style }}
inert={gate.inert}
className="absolute bottom-full left-0 z-20 mb-2 flex items-center gap-0.5 rounded-full border border-border bg-background p-1"
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.85, y: 8 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={reduce ? { opacity: 0, transition: OUT } : { opacity: 0, scale: 0.85, y: 6, transition: OUT }}
transition={{ ...SPRING_PANEL, opacity: { duration: 0.12, ease: EASE_OUT } }}
>
{/* The hover blob, gliding under whichever reaction is lifted. */}
<motion.span
aria-hidden="true"
className="pointer-events-none absolute top-1 left-1 size-9 rounded-full bg-muted"
style={{ x: blobX, scaleX: blobScaleX, scaleY: blobScaleY }}
initial={false}
animate={{ opacity: active ? 1 : 0 }}
transition={{ duration: 0.14, ease: EASE_OUT }}
/>
{reactions.map((reaction, index) => {
const lifted = active === reaction.id && !reduce;
// The reactions either side lean in a little, like a dock.
const near = !reduce && activeIndex !== -1 && Math.abs(index - activeIndex) === 1;
return (
<motion.button
key={reaction.id}
ref={(node) => {
optionRefs.current[index] = node;
}}
type="button"
aria-label={reaction.label}
aria-pressed={reaction.id === value}
tabIndex={index === startIndex ? 0 : -1}
onClick={() => pick(reaction, index)}
onPointerEnter={() => canHover && hover(reaction.id)}
onFocus={() => hover(reaction.id)}
onBlur={() => setActive((current) => (current === reaction.id ? null : current))}
className={cn(
"relative inline-flex size-9 items-center justify-center rounded-full transition-colors",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
reaction.color,
reaction.id === value && "bg-muted",
)}
initial={{ opacity: 0, y: reduce ? 0 : RISE }}
animate={{ opacity: 1, y: 0 }}
transition={{
opacity: { duration: 0.12, ease: EASE_OUT, delay: reduce ? 0 : index * STAGGER },
y: { ...SPRING_RISE, delay: reduce ? 0 : index * STAGGER },
}}
>
{/* Only the icon lifts and grows, so the name chip stays crisp. */}
<motion.span
ref={(node) => {
optionIconRefs.current[index] = node;
}}
className="inline-flex"
initial={false}
animate={{ y: lifted ? -6 : near ? -2 : 0, scale: lifted ? LIFT_SCALE : near ? 1.08 : 1 }}
transition={SPRING_HOVER}
>
{reaction.icon}
</motion.span>
{/* The name rides above the lifted reaction. */}
<AnimatePresence>
{lifted ? (
<motion.span
aria-hidden="true"
className="pointer-events-none absolute bottom-full left-1/2 mb-2.5 rounded-full border border-border bg-background px-2 py-0.5 text-[11px] font-medium whitespace-nowrap text-foreground"
style={{ translate: "-50% 0" }}
initial={{ opacity: 0, y: 4 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 4, transition: OUT }}
transition={SPRING_HOVER}
>
{reaction.label}
</motion.span>
) : null}
</AnimatePresence>
</motion.button>
);
})}
</motion.div>
)}
</PresenceGate>
) : null}
</AnimatePresence>
{/* The picked reaction in the air: across on one curve, up then down on another. */}
{flight ? (
<motion.span
key={flight.id}
aria-hidden="true"
className={cn("pointer-events-none absolute top-0 left-0 z-30 inline-flex", flight.reaction.color)}
style={{ translate: "-50% -50%" }}
initial={{ x: flight.from.x, y: flight.from.y, scale: flight.scale }}
animate={{
x: flight.to.x,
y: [flight.from.y, Math.min(flight.from.y, flight.to.y) - 18, flight.to.y],
scale: [flight.scale, 1.4, LAND_SCALE],
// It tips back on the way up and levels out to land.
rotate: [0, -12, 0],
}}
transition={{
x: { duration: FLIGHT_SECONDS, ease: EASE_IN_OUT },
y: { duration: FLIGHT_SECONDS, ease: [EASE_OUT, EASE_IN], times: [0, 0.4, 1] },
scale: { duration: FLIGHT_SECONDS, ease: [EASE_OUT, EASE_IN], times: [0, 0.4, 1] },
rotate: { duration: FLIGHT_SECONDS, ease: [EASE_OUT, EASE_IN_OUT], times: [0, 0.4, 1] },
}}
onAnimationComplete={() => {
setFlight(null);
setCatches((value) => value + 1);
}}
>
{flight.reaction.icon}
</motion.span>
) : null}
</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 { type RefObject, useEffect, useLayoutEffect, useRef } from "react";
import { inOtherLayer, type Layer, openLayer, ownsEscape } from "@/lib/layers";
/**
* What the dismissing gesture does to the control it landed on.
*
* `"pass-through"` is the platform norm (native popover light-dismiss): the
* tap closes the overlay *and* activates whatever was under it. Use
* `"consume"` where the open overlay sits over or beside controls that would
* be costly to trigger by accident — the dismissal then swallows the
* activation too, so the gesture only closes.
*/
export type DismissBehavior = "pass-through" | "consume";
/** What closed the overlay: Escape, a pointerdown outside it, or focus leaving it. */
export type DismissReason = "escape" | "pointer" | "focus";
export interface DismissOptions {
/** Default `"pass-through"`. */
behavior?: DismissBehavior;
/** Dismiss on Escape as well. Default true. */
escape?: boolean;
/** Dismiss when focus moves outside, as a combobox does on Tab. Default false. */
focusOutside?: boolean;
/**
* Dismiss on a pointerdown outside. Default true. Turn it off for an overlay
* whose own backdrop handles presses and only needs Escape and layering.
*/
outsidePress?: boolean;
/** Return true for an outside target that should *not* dismiss. */
ignore?: (target: Element) => boolean;
}
// preventDefault on pointerdown does not suppress the click that follows, so
// consuming a gesture means swallowing that click itself. The swallower
// deliberately outlives the effect that installed it — the dismissal it
// belongs to has already unmounted or re-rendered by the time the click lands.
// It releases on that click, or on the next gesture if the pointer is dragged
// away and no click ever arrives, so it can never eat a later one. A keydown
// releases it too: a gesture that ends with neither a click nor a cancel would
// otherwise leave it armed, and the click Enter synthesizes on some focused
// control is not the one this dismissal was owed.
function consumeActivation(source: Event) {
const swallow = (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
release();
};
const restart = (event: Event) => {
if (event !== source) release();
};
const release = () => {
window.removeEventListener("click", swallow, true);
window.removeEventListener("pointerdown", restart, true);
window.removeEventListener("pointercancel", restart, true);
window.removeEventListener("keydown", release, true);
};
window.addEventListener("click", swallow, true);
window.addEventListener("pointerdown", restart, true);
window.addEventListener("pointercancel", restart, true);
window.addEventListener("keydown", release, true);
}
/**
* Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`
* for `ref` when what counts as inside isn't one element, and say so with
* `ignore` instead.
*
* The pointerdown listener is capture-phase: a bubble-phase one is blinded by
* any handler in between that stops propagation, and an overlay cannot know
* what it is layered over.
*
* Each open dismissal is a layer in `lib/layers.ts`, so only the innermost
* open overlay answers Escape (a menu inside a drawer closes, the drawer
* stays), and a drawer's focus trap leaves focus in a menu it portaled out.
*/
export function useDismiss(
open: boolean,
onDismiss: (reason: DismissReason) => void,
ref: RefObject<HTMLElement | SVGElement | null> | null,
{
behavior = "pass-through",
escape: dismissOnEscape = true,
focusOutside = false,
outsidePress = true,
ignore,
}: DismissOptions = {},
) {
// Read through refs, so a callback rebuilt each render neither re-binds the
// listeners nor moves this layer to the top of the stack.
const dismissRef = useRef(onDismiss);
const ignoreRef = useRef(ignore);
useLayoutEffect(() => {
dismissRef.current = onDismiss;
ignoreRef.current = ignore;
});
useEffect(() => {
if (!open) return;
const inside = (target: Node) =>
Boolean(ref?.current?.contains(target)) ||
(target instanceof Element && Boolean(ignoreRef.current?.(target)));
const layer: Layer = { contains: inside, escape: dismissOnEscape };
const closeLayer = openLayer(layer);
const onKey = (event: KeyboardEvent) => {
if (!dismissOnEscape || event.key !== "Escape" || !ownsEscape(layer, event)) return;
event.preventDefault();
dismissRef.current("escape");
};
const onPointer = (event: PointerEvent) => {
const target = event.target as Element | null;
if (!target || inside(target)) return;
// Outside this overlay, but inside another open one: the gesture is
// that overlay's to answer, and swallowing its click from behind would
// cost the user the control they actually aimed at.
if (behavior === "consume" && !inOtherLayer(layer, target, { traps: false })) {
consumeActivation(event);
}
dismissRef.current("pointer");
};
const onFocus = (event: FocusEvent) => {
const target = event.target;
if (target instanceof Node && !inside(target)) dismissRef.current("focus");
};
window.addEventListener("keydown", onKey);
if (outsidePress) window.addEventListener("pointerdown", onPointer, true);
if (focusOutside) window.addEventListener("focusin", onFocus);
return () => {
closeLayer();
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer, true);
window.removeEventListener("focusin", onFocus);
};
}, [open, ref, behavior, dismissOnEscape, focusOutside, outsidePress]);
}
"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],
);
}
"use client";
import { useIsPresent } from "motion/react";
import type { ReactNode } from "react";
export interface PresenceGateRenderProps {
/**
* False from the render that starts the exit animation onward. An overlay
* kept in the tree by `AnimatePresence` is still the topmost thing on the
* page, so anything it decides from `open` alone stays true for the whole
* exit — this is the boolean that already knows the overlay is leaving.
*/
isPresent: boolean;
/**
* Spread onto every layer that takes pointer events while the overlay is
* open. Interaction releases in the same commit that starts the exit while
* the visual exit keeps playing: pointer events stop landing, and `inert`
* drops the subtree from focus order, from tab order and from the
* accessibility tree — an exiting dialog is not a dialog you can still type
* into. A layer that never takes pointer events (a wrapper that only centres
* the panel) takes `inert={!isPresent}` alone, so its own
* `pointer-events-none` is not overwritten.
*/
gate: {
inert: boolean;
style: { pointerEvents: "auto" | "none" };
};
}
export interface PresenceGateProps {
children: (props: PresenceGateRenderProps) => ReactNode;
}
/**
* Reads the presence of the subtree it renders and hands it down.
*
* `useIsPresent` only answers inside the `AnimatePresence` subtree, and the
* components that own an overlay render the `AnimatePresence` themselves, so
* the boolean has to be read one component further down: this is that
* component, and the render prop is how it reaches the layers.
*/
export function PresenceGate({ children }: PresenceGateProps) {
const isPresent = useIsPresent();
return children({
isPresent,
gate: {
inert: !isPresent,
style: { pointerEvents: isPresent ? "auto" : "none" },
},
});
}
"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";
/** The open whoosh falling and a little quicker, settling with a soft low tap, for things closing. */
export const closeSound = defineSound({
name: "Close",
duration: 0.16,
room: 0.18,
build: (v) => {
v.noise({ freq: 2600, to: 700, q: 1.2, attack: 0.012, decay: 0.09, gain: 0.7 });
v.click({ freq: 1400, q: 1.2, at: 0.05, decay: 0.006, gain: 0.2 });
v.strike({ freq: 260, material: "wood", bend: 1.2, at: 0.05, decay: 0.045, gain: 0.3 });
},
});
import { defineSound } from "./engine";
/** A soft rising whoosh that lands with a light glass touch, for menus, popovers and dialogs opening. */
export const openSound = defineSound({
name: "Open",
duration: 0.2,
room: 0.2,
build: (v) => {
v.noise({ freq: 600, to: 2600, q: 1.2, attack: 0.035, decay: 0.11, gain: 0.75 });
v.noise({ freq: 4500, to: 6000, q: 1, attack: 0.03, decay: 0.07, gain: 0.05 });
v.strike({ freq: 1320, material: "glass", at: 0.05, decay: 0.07, gain: 0.12 });
},
});
import { defineSound } from "./engine";
/** A crisp detent, like a dial clicking into a notch, for tabs, segmented controls and menu choices. */
export const selectSound = defineSound({
name: "Select",
duration: 0.05,
room: 0.08,
build: (v) => {
v.click({ freq: 4500, q: 2.5, decay: 0.003, gain: 0.45 });
v.strike({ freq: 1700, material: "metal", decay: 0.028, gain: 0.3 });
v.strike({ freq: 520, material: "wood", bend: 1.15, decay: 0.012, gain: 0.25 });
},
});
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
/**
* Every open overlay on the page, innermost last: focus traps, modal scopes
* and dismissable menus all register here. Overlays have no shared z-order to
* consult, and a menu inside a drawer portals out of it, so this stack is how
* they agree on who answers Escape and where focus may go.
*/
export interface Layer {
/** Whether `target` belongs to this layer (its panel, portals, trigger). */
contains: (target: Node) => boolean;
/** True for focus traps and modal scopes, which pull stray focus back. */
traps?: boolean;
/** False for a layer that ignores Escape, so the key reaches the one below. */
escape?: boolean;
}
const stack: Layer[] = [];
// The innermost layer when each Escape began, read before any handler runs,
// so a layer that closes itself mid-event can't hand the key to the one below.
const escapeOwners = new WeakMap<Event, Layer | undefined>();
let listening = false;
function innermostEscapeLayer() {
for (let index = stack.length - 1; index >= 0; index--) {
if (stack[index].escape !== false) return stack[index];
}
return undefined;
}
function recordEscapeOwner(event: KeyboardEvent) {
if (event.key === "Escape") escapeOwners.set(event, innermostEscapeLayer());
}
/** Registers an open layer. Call the returned function when it closes. */
export function openLayer(layer: Layer) {
if (!listening) {
document.addEventListener("keydown", recordEscapeOwner, true);
listening = true;
}
stack.push(layer);
return () => {
const index = stack.indexOf(layer);
if (index !== -1) stack.splice(index, 1);
};
}
/** Whether this Escape is `layer`'s to answer: it was innermost when the key went down. */
export function ownsEscape(layer: Layer, event: KeyboardEvent) {
if (event.defaultPrevented) return false;
const owner = escapeOwners.has(event)
? escapeOwners.get(event)
: innermostEscapeLayer();
return owner === layer;
}
/** Whether `target` sits in a layer opened on top of `layer`. */
export function inLayerAbove(layer: Layer, target: Node) {
const index = stack.indexOf(layer);
return stack.slice(index + 1).some((above) => above.contains(target));
}
/** Whether a focus trap is open on top of `layer`; stray focus is that one's to pull back. */
export function trapAbove(layer: Layer) {
const index = stack.indexOf(layer);
return stack.slice(index + 1).some((above) => above.traps);
}
/**
* Whether `target` belongs to any open layer other than `layer`. Pass
* `traps: false` to count only dismissable overlays, not the traps under them.
*/
export function inOtherLayer(layer: Layer, target: Node, { traps = true } = {}) {
return stack.some(
(other) => other !== layer && (traps || !other.traps) && other.contains(target),
);
}
// 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/reaction-picker
import { Flame, Heart, Laugh, PartyPopper, SmilePlus, ThumbsUp } from "lucide-react";
import {
AnimatePresence,
animate,
motion,
useMotionTemplate,
useMotionValue,
useReducedMotion,
useSpring,
useTransform,
useVelocity,
} from "motion/react";
import { type KeyboardEvent, type ReactNode, useEffect, useRef, useState } from "react";
import { DigitSwap } from "@/components/motion/digit-swap";
import { EASE_IN, EASE_IN_OUT, EASE_OUT, SPRING_PANEL, SPRING_PRESS } from "@/lib/ease";
import { useDismiss } from "@/lib/hooks/use-dismiss";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
import { useMessages } from "@/lib/i18n";
import { PresenceGate } from "@/lib/presence-gate";
import { useSound } from "@/lib/sound";
import { closeSound } from "@/lib/sounds/close";
import { openSound } from "@/lib/sounds/open";
import { selectSound } from "@/lib/sounds/select";
import { cn } from "@/lib/utils";
export const reactionPickerMessages = {
react: "Add reaction",
reacted: "Reacted with {reaction}",
reactions: "Reactions",
like: "Like",
love: "Love",
haha: "Haha",
fire: "Fire",
party: "Party",
};
export type ReactionPickerMessages = typeof reactionPickerMessages;
export type Reaction = {
/** Unique key, used as the picker's value. */
id: string;
/** Name shown above the reaction on hover and used as its accessible name. */
label: string;
/** Icon or emoji in the tray, which flies to the trigger once picked. */
icon: ReactNode;
/** Text colour class for the icon, e.g. "text-rose-500". */
color?: string;
/** Classes for the button once this reaction is picked. */
tint?: string;
};
export interface ReactionPickerProps {
/** The choices, in order. Defaults to like, love, haha, fire and party. */
reactions?: Reaction[];
/** The viewer's reaction id, or null for none. */
value?: string | null;
/** The initial reaction id when uncontrolled. Default: null */
defaultValue?: string | null;
/** Called with the picked reaction id, or null when the same one is picked again. */
onValueChange?: (value: string | null) => void;
/** Reactions from everyone else. The viewer's own is added on top. */
count?: number;
/** Override any built-in string, e.g. for translation. */
labels?: Partial<ReactionPickerMessages>;
/** Play open and close swishes for the tray and a select on a pick. Off by default; a `SoundProvider` can mute it app-wide. */
sound?: boolean;
/** Classes merged onto the root element. */
className?: string;
}
// Each reaction rises into the tray a beat after the one before it.
const STAGGER = 0.035;
const RISE = 12;
// Looser than SPRING_SWAP on purpose: each icon lands with a small settle.
const SPRING_RISE = { type: "spring", stiffness: 520, damping: 22, mass: 0.6 } as const;
// The hovered reaction lifts and grows quickly, and settles back as quickly.
const SPRING_HOVER = { type: "spring", stiffness: 600, damping: 26, mass: 0.5 } as const;
const OUT = { duration: 0.14, ease: EASE_OUT } as const;
// The flight: across evenly, up slowing into the peak and down speeding out
// of it, so it traces one smooth arc instead of stalling at the top.
const FLIGHT_SECONDS = 0.46;
const LIFT_SCALE = 1.25;
// It lands a touch large and the button's icon settles from there.
const LAND_SCALE = 1.15;
// The tray morphs out of the button: a pill clip that springs open from a
// circle the tray's height over the icon. Near critical, so it never snaps
// past open.
const SPRING_REVEAL = { type: "spring", stiffness: 340, damping: 32, mass: 0.8 } as const;
const TRAY_HEIGHT = 46;
// The hover blob glides between reactions, stretching with its speed.
const SPRING_BLOB = { stiffness: 520, damping: 34, mass: 0.6 } as const;
// One reaction slot: a 36px button plus the 2px gap.
const SLOT = 38;
// The catch: the icon lands squashed and wobbles back to shape.
const SPRING_JELLY = { type: "spring", stiffness: 620, damping: 14, mass: 0.6 } as const;
const SQUASH = { scaleX: 1.3, scaleY: 0.78 } as const;
// Sparks from the button when it catches a reaction, alternating near and far.
const SPARKS = Array.from({ length: 8 }, (_, index) => {
const angle = (index / 8) * Math.PI * 2;
const far = index % 2 === 0;
return { id: index, x: Math.cos(angle) * (far ? 18 : 13), y: Math.sin(angle) * (far ? 18 : 13), far };
});
type Point = { x: number; y: number };
/** A reaction in the air, and what the button showed before it was picked. */
type Flight = { id: number; reaction: Reaction; previous: Reaction | null; from: Point; to: Point; scale: number };
/** The centre of an element, relative to an origin rect. */
function centre(el: Element | null | undefined, origin: DOMRect): Point | null {
if (!el) return null;
const rect = el.getBoundingClientRect();
return { x: rect.left + rect.width / 2 - origin.left, y: rect.top + rect.height / 2 - origin.top };
}
/**
* A reaction button. Pressing it grows a tray out of the button with each
* reaction rising in turn; hovering one lifts it and shows its name. The one
* you pick arcs down onto the button, which catches it with a pop and a burst
* in the reaction's colour as the count rolls. Picking it again takes it back.
*/
export function ReactionPicker({
reactions: reactionsProp,
value: valueProp,
defaultValue = null,
onValueChange,
count = 0,
labels,
sound = false,
className,
}: ReactionPickerProps) {
const t = useMessages("ReactionPicker", reactionPickerMessages, labels);
const playOpen = useSound(openSound, { enabled: sound });
const playClose = useSound(closeSound, { enabled: sound });
const playPick = useSound(selectSound, { enabled: sound });
const reduce = Boolean(useReducedMotion());
const canHover = useHoverCapable();
const [internal, setInternal] = useState<string | null>(defaultValue);
const value = valueProp === undefined ? internal : valueProp;
const [open, setOpen] = useState(false);
const [active, setActive] = useState<string | null>(null);
const [flight, setFlight] = useState<Flight | null>(null);
// Counts catches, so each landing replays the pop and the sparks.
const [catches, setCatches] = useState(0);
const reactions: Reaction[] = reactionsProp ?? [
{
id: "like",
label: t("like"),
icon: <ThumbsUp className="size-5" />,
color: "text-sky-500",
tint: "border-sky-500/30 bg-sky-500/10 text-sky-600 dark:text-sky-400",
},
{
id: "love",
label: t("love"),
icon: <Heart className="size-5" />,
color: "text-rose-500",
tint: "border-rose-500/30 bg-rose-500/10 text-rose-600 dark:text-rose-400",
},
{
id: "haha",
label: t("haha"),
icon: <Laugh className="size-5" />,
color: "text-amber-500",
tint: "border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400",
},
{
id: "fire",
label: t("fire"),
icon: <Flame className="size-5" />,
color: "text-orange-500",
tint: "border-orange-500/30 bg-orange-500/10 text-orange-600 dark:text-orange-400",
},
{
id: "party",
label: t("party"),
icon: <PartyPopper className="size-5" />,
color: "text-emerald-500",
tint: "border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",
},
];
const chosen = reactions.find((reaction) => reaction.id === value) ?? null;
// While a reaction is in the air, the button still shows what it had, so
// nothing changes on it until the catch.
const shown = flight ? flight.previous : chosen;
const rootRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
const iconRef = useRef<HTMLSpanElement>(null);
const optionRefs = useRef<(HTMLButtonElement | null)[]>([]);
const optionIconRefs = useRef<(HTMLSpanElement | null)[]>([]);
// The tray's reveal: 1 is a circle over the icon, 0 is fully open. It
// springs open on open and morphs back into the circle as the tray leaves,
// so it is already closed when the next tray mounts and never flashes open
// for a frame (motion writes a reset value only on its next frame).
const reveal = useMotionValue(reduce ? 0 : 1);
const trayClip = useMotionTemplate`inset(0 calc((100% - ${TRAY_HEIGHT}px) * ${reveal}) 0 0 round 999px)`;
useEffect(() => {
if (reduce) {
reveal.jump(0);
return;
}
const controls = open ? animate(reveal, 0, SPRING_REVEAL) : animate(reveal, 1, OUT);
return () => controls.stop();
}, [open, reduce, reveal]);
// The hover blob: springs between slots and stretches with its speed.
const blobX = useSpring(0, SPRING_BLOB);
const blobSpeed = useVelocity(blobX);
const blobScaleX = useTransform(blobSpeed, (speed) => 1 + Math.min(Math.abs(speed) / 2200, 0.45));
const blobScaleY = useTransform(blobScaleX, (stretch) => 1 - (stretch - 1) * 0.35);
const activeIndex = reactions.findIndex((reaction) => reaction.id === active);
// Move the blob with the hover: it appears in place, then glides.
const hover = (id: string) => {
const index = reactions.findIndex((reaction) => reaction.id === id);
if (active === null || reduce) blobX.jump(index * SLOT);
else blobX.set(index * SLOT);
setActive(id);
};
// Close and hand focus back to the button when it was inside the tray.
const close = () => {
if (rootRef.current?.contains(document.activeElement)) triggerRef.current?.focus();
setOpen(false);
setActive(null);
};
// Closing without a pick; a pick closes quietly behind its own sound.
const dismiss = () => {
playClose();
close();
};
useDismiss(open, dismiss, rootRef);
// Opening by keyboard moves focus to the current reaction, or the first.
const focusOnOpen = useRef(false);
const startIndex = Math.max(0, reactions.findIndex((reaction) => reaction.id === value));
useEffect(() => {
if (!open || !focusOnOpen.current) return;
focusOnOpen.current = false;
optionRefs.current[startIndex]?.focus();
}, [open, startIndex]);
const pick = (reaction: Reaction, index: number) => {
const next = reaction.id === value ? null : reaction.id;
playPick({ pitch: next ? 1.1 : 0.85 });
// Measure both ends now, from the event, while the tray is still open:
// the icon itself, so a lifted one leaves from where it is drawn.
const root = rootRef.current?.getBoundingClientRect();
const source = optionIconRefs.current[index];
const from = root && centre(source, root);
const to = root && centre(iconRef.current, root);
if (next && from && to && !reduce) {
const scale = active === reaction.id ? LIFT_SCALE : 1;
setFlight({ id: Date.now(), reaction, previous: chosen, from, to, scale });
// The flying copy takes over from here; hide the original so it does
// not shrink away inside the closing tray beside it.
if (source) source.style.visibility = "hidden";
} else if (next) setCatches((value) => value + 1);
if (valueProp === undefined) setInternal(next);
onValueChange?.(next);
close();
};
const onTrayKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
const index = optionRefs.current.indexOf(document.activeElement as HTMLButtonElement);
const step = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0;
if (!step || index === -1) return;
event.preventDefault();
optionRefs.current[(index + step + reactions.length) % reactions.length]?.focus();
};
const total = count + (value ? 1 : 0);
return (
<div ref={rootRef} className={cn("relative inline-flex", className)}>
<motion.button
ref={triggerRef}
type="button"
aria-haspopup="true"
aria-expanded={open}
aria-label={chosen ? t("reacted", { reaction: chosen.label }) : t("react")}
whileTap={reduce ? undefined : { scale: 0.94 }}
transition={SPRING_PRESS}
onClick={() => {
if (open) return dismiss();
playOpen();
setOpen(true);
}}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " " || event.key === "ArrowUp") focusOnOpen.current = true;
if (event.key === "ArrowUp" && !open) {
event.preventDefault();
playOpen();
setOpen(true);
}
}}
className={cn(
"relative inline-flex h-9 items-center gap-1.5 rounded-full border pr-3.5 pl-2.5 text-sm font-medium tabular-nums transition-colors duration-200",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
shown?.tint ?? "border-border text-muted-foreground hover:bg-muted/60 hover:text-foreground",
)}
>
<span ref={iconRef} aria-hidden="true" className="relative inline-flex size-5 items-center justify-center">
{/* The catch: sparks in the reaction's colour from where it lands. */}
{catches > 0 && !reduce && chosen ? (
<span key={catches} className={cn("pointer-events-none absolute inset-0", chosen.color)}>
{SPARKS.map((spark) => (
<motion.span
key={spark.id}
className={cn("absolute top-1/2 left-1/2 rounded-full bg-current", spark.far ? "size-1" : "size-[3px]")}
style={{ translate: "-50% -50%" }}
initial={{ opacity: 0, x: 0, y: 0 }}
animate={{ opacity: [0, 1, 0], x: spark.x, y: spark.y }}
transition={{ duration: 0.5, ease: EASE_OUT, delay: spark.far ? 0 : 0.04 }}
/>
))}
</span>
) : null}
<AnimatePresence initial={false} mode="popLayout">
<motion.span
key={`${shown?.id ?? "none"}-${shown ? catches : 0}`}
className="inline-flex"
// A caught reaction takes over from the flying copy at its size
// and settles; the smiley comes back from above.
initial={
reduce
? { opacity: 0 }
: shown
? { opacity: 1, scaleX: LAND_SCALE * SQUASH.scaleX, scaleY: LAND_SCALE * SQUASH.scaleY, y: 0 }
: { opacity: 0, scaleX: 0.5, scaleY: 0.5, y: -6 }
}
animate={{ opacity: 1, scaleX: 1, scaleY: 1, y: 0 }}
exit={
reduce
? { opacity: 0, transition: OUT }
: { opacity: 0, y: 6, scaleX: 0.8, scaleY: 0.8, transition: OUT }
}
// A caught reaction wobbles back from the squash; the smiley just settles.
transition={shown ? SPRING_JELLY : SPRING_PRESS}
>
{shown ? shown.icon : <SmilePlus className="size-5" />}
</motion.span>
</AnimatePresence>
</span>
{total > 0 ? <DigitSwap value={total} direction={value ? "up" : "down"} /> : null}
</motion.button>
<AnimatePresence>
{open ? (
<PresenceGate>
{({ gate }) => (
<motion.div
role="group"
aria-label={t("reactions")}
onKeyDown={onTrayKeyDown}
onPointerLeave={() => setActive(null)}
// Rises out of the button's icon and sinks back into it: 20px in
// (padding plus half the icon), 26px below the tray (gap plus half the button).
style={{ transformOrigin: "20px calc(100% + 26px)", clipPath: trayClip, ...gate.style }}
inert={gate.inert}
className="absolute bottom-full left-0 z-20 mb-2 flex items-center gap-0.5 rounded-full border border-border bg-background p-1"
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.85, y: 8 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={reduce ? { opacity: 0, transition: OUT } : { opacity: 0, scale: 0.85, y: 6, transition: OUT }}
transition={{ ...SPRING_PANEL, opacity: { duration: 0.12, ease: EASE_OUT } }}
>
{/* The hover blob, gliding under whichever reaction is lifted. */}
<motion.span
aria-hidden="true"
className="pointer-events-none absolute top-1 left-1 size-9 rounded-full bg-muted"
style={{ x: blobX, scaleX: blobScaleX, scaleY: blobScaleY }}
initial={false}
animate={{ opacity: active ? 1 : 0 }}
transition={{ duration: 0.14, ease: EASE_OUT }}
/>
{reactions.map((reaction, index) => {
const lifted = active === reaction.id && !reduce;
// The reactions either side lean in a little, like a dock.
const near = !reduce && activeIndex !== -1 && Math.abs(index - activeIndex) === 1;
return (
<motion.button
key={reaction.id}
ref={(node) => {
optionRefs.current[index] = node;
}}
type="button"
aria-label={reaction.label}
aria-pressed={reaction.id === value}
tabIndex={index === startIndex ? 0 : -1}
onClick={() => pick(reaction, index)}
onPointerEnter={() => canHover && hover(reaction.id)}
onFocus={() => hover(reaction.id)}
onBlur={() => setActive((current) => (current === reaction.id ? null : current))}
className={cn(
"relative inline-flex size-9 items-center justify-center rounded-full transition-colors",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
reaction.color,
reaction.id === value && "bg-muted",
)}
initial={{ opacity: 0, y: reduce ? 0 : RISE }}
animate={{ opacity: 1, y: 0 }}
transition={{
opacity: { duration: 0.12, ease: EASE_OUT, delay: reduce ? 0 : index * STAGGER },
y: { ...SPRING_RISE, delay: reduce ? 0 : index * STAGGER },
}}
>
{/* Only the icon lifts and grows, so the name chip stays crisp. */}
<motion.span
ref={(node) => {
optionIconRefs.current[index] = node;
}}
className="inline-flex"
initial={false}
animate={{ y: lifted ? -6 : near ? -2 : 0, scale: lifted ? LIFT_SCALE : near ? 1.08 : 1 }}
transition={SPRING_HOVER}
>
{reaction.icon}
</motion.span>
{/* The name rides above the lifted reaction. */}
<AnimatePresence>
{lifted ? (
<motion.span
aria-hidden="true"
className="pointer-events-none absolute bottom-full left-1/2 mb-2.5 rounded-full border border-border bg-background px-2 py-0.5 text-[11px] font-medium whitespace-nowrap text-foreground"
style={{ translate: "-50% 0" }}
initial={{ opacity: 0, y: 4 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 4, transition: OUT }}
transition={SPRING_HOVER}
>
{reaction.label}
</motion.span>
) : null}
</AnimatePresence>
</motion.button>
);
})}
</motion.div>
)}
</PresenceGate>
) : null}
</AnimatePresence>
{/* The picked reaction in the air: across on one curve, up then down on another. */}
{flight ? (
<motion.span
key={flight.id}
aria-hidden="true"
className={cn("pointer-events-none absolute top-0 left-0 z-30 inline-flex", flight.reaction.color)}
style={{ translate: "-50% -50%" }}
initial={{ x: flight.from.x, y: flight.from.y, scale: flight.scale }}
animate={{
x: flight.to.x,
y: [flight.from.y, Math.min(flight.from.y, flight.to.y) - 18, flight.to.y],
scale: [flight.scale, 1.4, LAND_SCALE],
// It tips back on the way up and levels out to land.
rotate: [0, -12, 0],
}}
transition={{
x: { duration: FLIGHT_SECONDS, ease: EASE_IN_OUT },
y: { duration: FLIGHT_SECONDS, ease: [EASE_OUT, EASE_IN], times: [0, 0.4, 1] },
scale: { duration: FLIGHT_SECONDS, ease: [EASE_OUT, EASE_IN], times: [0, 0.4, 1] },
rotate: { duration: FLIGHT_SECONDS, ease: [EASE_OUT, EASE_IN_OUT], times: [0, 0.4, 1] },
}}
onAnimationComplete={() => {
setFlight(null);
setCatches((value) => value + 1);
}}
>
{flight.reaction.icon}
</motion.span>
) : null}
</div>
);
}
"use client";
// beui.dev/micro-interactions/reaction-picker
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),
};
}
reactions?Reaction[]The choices, in order. Defaults to like, love, haha, fire and party.
—value?string | nullThe viewer's reaction id, or null for none.
—defaultValue?string | nullThe initial reaction id when uncontrolled. Default: null
nullonValueChange?((value: string | null) => void)Called with the picked reaction id, or null when the same one is picked again.
—count?numberReactions from everyone else. The viewer's own is added on top.
0labels?Partial<{ react: string; reacted: string; reactions: string; like: string; love: string; haha: string; fire: string; party: string; }>Override any built-in string, e.g. for translation.
—sound?booleanPlay open and close swishes for the tray and a select on a pick. Off by default; a `SoundProvider` can mute it app-wide.
falseclassName?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.
Share Button
A round share button that fans its actions out on an arc, names each on hover, and turns the chosen one into a check. You decide what each action does.
Like Button
A heart toggle that pops, throws a ring of sparks and rolls its count up when liked, and drains back quietly when unliked.
Updated