Gooey Popover
A panel that oozes out of its trigger like liquid, with crisp content.
Preview
"use client";
import { Button } from "@/components/motion/button";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/motion/popover";
export function PopoverPreview() {
return (
<div className="flex flex-wrap items-center justify-center gap-4">
<Popover side="bottom" align="start">
<PopoverTrigger>
<Button variant="secondary">Edit profile</Button>
</PopoverTrigger>
<PopoverContent className="w-72">
<p className="text-sm font-medium text-foreground">Dimensions</p>
<p className="mt-1 text-xs text-muted-foreground">
Set the width and height for the layer.
</p>
<div className="mt-3 flex flex-col gap-2">
<label className="flex items-center justify-between gap-3 text-sm">
<span className="text-muted-foreground">Width</span>
<input
defaultValue="100%"
className="h-8 w-32 rounded-full border border-border bg-background px-3 text-sm text-foreground outline-none focus-visible:ring-2 focus-visible:ring-foreground/20"
/>
</label>
<label className="flex items-center justify-between gap-3 text-sm">
<span className="text-muted-foreground">Height</span>
<input
defaultValue="auto"
className="h-8 w-32 rounded-full border border-border bg-background px-3 text-sm text-foreground outline-none focus-visible:ring-2 focus-visible:ring-foreground/20"
/>
</label>
</div>
</PopoverContent>
</Popover>
<Popover trigger="hover" side="top">
<PopoverTrigger>
<Button variant="outline">Hover me</Button>
</PopoverTrigger>
<PopoverContent className="w-56">
<p className="text-sm text-foreground">
Opens on hover, with a grace window so you can move into the panel.
</p>
</PopoverContent>
</Popover>
</div>
);
}
"use client";
// beui.dev/components/motion/popover/gooey
import {
animate,
type MotionValue,
motion,
useMotionValue,
useMotionValueEvent,
useReducedMotion,
} from "motion/react";
import {
cloneElement,
createContext,
isValidElement,
type ReactElement,
type ReactNode,
type Ref,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { usePopoverPortalPosition } from "@/components/motion/popover-position";
import { useDismiss } from "@/lib/hooks/use-dismiss";
import {
type HoverGesture,
useHoverGesture,
} from "@/lib/hooks/use-hover-gesture";
import { useTapGesture } from "@/lib/hooks/use-tap-gesture";
import { mergeRefs } from "@/lib/merge-refs";
import { cn } from "@/lib/utils";
type Side = "top" | "bottom";
type Align = "start" | "center" | "end";
type TriggerMode = "click" | "hover";
// This morph needs less bounce than layout motion: too much overshoot makes
// the liquid neck balloon past the final panel edges.
const GOO_OPEN_SPRING = {
type: "spring",
visualDuration: 0.3,
bounce: 0.15,
} as const;
const GOO_CLOSE_SPRING = {
type: "spring",
visualDuration: 0.21,
bounce: 0.15,
} as const;
// A pointer crossing the trigger on its way elsewhere should not burst the
// panel open; one that stops for a moment means it.
const HOVER_OPEN_DELAY = 100;
const HOVER_CLOSE_DELAY = 120;
// Reduced motion trades the morph for a plain fade, out faster than in.
const FADE_IN = { duration: 0.15 } as const;
const FADE_OUT = { duration: 0.12 } as const;
const CIRCLE_KAPPA = 0.5523;
// `onPointerEnter`/`onPointerLeave` rather than the mouse pair: a tap fires
// compatibility mouseenter/mouseleave that carry no pointerType at all, and
// they are what made the panel flicker open and shut under a finger. The
// gesture pairs the two, so the panel a pen tap opened is not closed again by
// the boundary event that ends the same tap.
function makeHoverHandlers(
hover: HoverGesture,
enter: () => void,
leave: () => void,
) {
return {
onPointerEnter: (event: React.PointerEvent) => {
if (hover.enter(event)) enter();
},
onPointerLeave: (event: React.PointerEvent) => {
if (hover.leave(event)) leave();
},
};
}
const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
interface Rect {
x: number;
y: number;
w: number;
h: number;
r: number;
}
interface Geo {
layerW: number;
layerH: number;
left: number;
top: number;
trigger: Rect;
panel: Rect;
}
// Trigger rect and panel rect in a shared local coordinate box.
function buildGeo(
tW: number,
tH: number,
cW: number,
cH: number,
side: Side,
align: Align,
gap: number,
panelRadius: number,
): Geo {
const py = side === "bottom" ? tH + gap : -(gap + cH);
const px = align === "start" ? 0 : align === "end" ? tW - cW : (tW - cW) / 2;
const left = Math.min(0, px);
const top = Math.min(0, py);
const layerW = Math.max(tW, px + cW) - left;
const layerH = Math.max(tH, py + cH) - top;
const triggerRadius = Math.min(tH / 2, panelRadius);
return {
layerW,
layerH,
left,
top,
trigger: { x: -left, y: -top, w: tW, h: tH, r: triggerRadius },
panel: { x: px - left, y: py - top, w: cW, h: cH, r: panelRadius },
};
}
function rectAtProgress(geo: Geo, progress: number): Rect {
const trigger = geo.trigger;
const panel = geo.panel;
return {
x: lerp(trigger.x, panel.x, progress),
y: lerp(trigger.y, panel.y, progress),
w: lerp(trigger.w, panel.w, progress),
h: lerp(trigger.h, panel.h, progress),
r: lerp(trigger.r, panel.r, progress),
};
}
function insetFor(rect: Rect, layerW: number, layerH: number) {
const top = rect.y;
const right = layerW - (rect.x + rect.w);
const bottom = layerH - (rect.y + rect.h);
const left = rect.x;
return `inset(${top}px ${right}px ${bottom}px ${left}px round ${rect.r}px)`;
}
function roundedRectShape(rect: Rect) {
const radius = Math.max(0, Math.min(rect.r, rect.w / 2, rect.h / 2));
const control = radius * CIRCLE_KAPPA;
const x1 = rect.x;
const y1 = rect.y;
const x2 = rect.x + rect.w;
const y2 = rect.y + rect.h;
const px = (value: number) => `${value.toFixed(3)}px`;
return (
`shape(from ${px(x1 + radius)} ${px(y1)}, ` +
`line to ${px(x2 - radius)} ${px(y1)}, ` +
`curve to ${px(x2)} ${px(y1 + radius)} with ${px(x2 - radius + control)} ${px(y1)} / ${px(x2)} ${px(y1 + radius - control)}, ` +
`line to ${px(x2)} ${px(y2 - radius)}, ` +
`curve to ${px(x2 - radius)} ${px(y2)} with ${px(x2)} ${px(y2 - radius + control)} / ${px(x2 - radius + control)} ${px(y2)}, ` +
`line to ${px(x1 + radius)} ${px(y2)}, ` +
`curve to ${px(x1)} ${px(y2 - radius)} with ${px(x1 + radius - control)} ${px(y2)} / ${px(x1)} ${px(y2 - radius + control)}, ` +
`line to ${px(x1)} ${px(y1 + radius)}, ` +
`curve to ${px(x1 + radius)} ${px(y1)} with ${px(x1)} ${px(y1 + radius - control)} / ${px(x1 + radius - control)} ${px(y1)}, ` +
"close)"
);
}
function clipForProgress(geo: Geo, progress: number, supportsShape: boolean) {
const rect = rectAtProgress(geo, progress);
return supportsShape
? roundedRectShape(rect)
: insetFor(rect, geo.layerW, geo.layerH);
}
function roundedRectPath(rect: Rect) {
const radius = Math.max(0, Math.min(rect.r, rect.w / 2, rect.h / 2));
const n = (value: number) => value.toFixed(3);
const x1 = rect.x;
const y1 = rect.y;
const x2 = rect.x + rect.w;
const y2 = rect.y + rect.h;
const arc = `A${n(radius)} ${n(radius)} 0 0 1`;
// A zero radius makes every arc degenerate to a line, so this also draws
// plain rectangles.
return (
`M${n(x1 + radius)} ${n(y1)}` +
`H${n(x2 - radius)}${arc} ${n(x2)} ${n(y1 + radius)}` +
`V${n(y2 - radius)}${arc} ${n(x2 - radius)} ${n(y2)}` +
`H${n(x1 + radius)}${arc} ${n(x1)} ${n(y2 - radius)}` +
`V${n(y1 + radius)}${arc} ${n(x1 + radius)} ${n(y1)}Z`
);
}
// The goo layer is portalled above the page, so its copy of the trigger pill
// would cover the real trigger's label and focus ring. Punching the trigger
// back out keeps the real one visible and clips the blur to the layer box.
// This is a clip path rather than a CSS mask on purpose: WebKit silently
// ignores `mask: url(#id)` pointing at an SVG <mask> element, which left the
// label hidden behind the goo in Safari.
function triggerCutout(geo: Geo) {
const layer = { x: 0, y: 0, w: geo.layerW, h: geo.layerH, r: 0 };
return `path(evenodd, "${roundedRectPath(layer)} ${roundedRectPath(geo.trigger)}")`;
}
interface PopoverContextValue {
open: boolean;
setOpen: (open: boolean) => void;
toggle: () => void;
/** Open now (focus). */
openHover: () => void;
/** Open after a short intent delay (pointer). */
openHoverSoon: () => void;
scheduleClose: () => void;
triggerMode: TriggerMode;
side: Side;
align: Align;
gap: number;
panelRadius: number;
gooStrength: number;
reduce: boolean;
gooId: string;
contentId: string;
progress: MotionValue<number>;
fade: MotionValue<number>;
triggerRef: React.MutableRefObject<HTMLElement | null>;
contentRef: React.MutableRefObject<HTMLDivElement | null>;
}
const PopoverContext = createContext<PopoverContextValue | null>(null);
function usePopoverContext(component: string) {
const ctx = useContext(PopoverContext);
if (!ctx) throw new Error(`${component} must be used within <Popover>`);
return ctx;
}
export interface PopoverProps {
children: ReactNode;
/** Controlled open state. */
open?: boolean;
/** Uncontrolled initial open state. */
defaultOpen?: boolean;
/** Called with the new open state when the panel opens or closes. */
onOpenChange?: (open: boolean) => void;
/** How the popover is summoned. Default "click". */
trigger?: TriggerMode;
/** Which side of the trigger the panel oozes out of. Default "bottom". */
side?: Side;
/** Alignment along the trigger's edge. Default "center". */
align?: Align;
/** Gap between trigger and panel, in px — the length of the gooey neck. Default 14. */
sideOffset?: number;
/** Corner radius of the open panel, in px. Default 16. */
panelRadius?: number;
/** Blur radius feeding the goo filter — higher melts more. Default 8. */
gooStrength?: number;
/** Classes merged onto the wrapper around the trigger. */
className?: string;
}
export function Popover({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
trigger = "click",
side = "bottom",
align = "center",
sideOffset = 14,
panelRadius = 16,
gooStrength = 8,
className,
}: PopoverProps) {
const reduce = useReducedMotion() ?? false;
const gooId = useId().replace(/:/g, "");
const contentId = useId();
const rootRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);
const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const rootHover = useHoverGesture();
const progress = useMotionValue(defaultOpen ? 1 : 0);
// The whole layer's opacity: 1 throughout the morph, faded under reduced motion.
const fade = useMotionValue(1);
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const controlled = controlledOpen !== undefined;
const open = controlled ? controlledOpen : internalOpen;
const setOpen = useCallback(
(next: boolean) => {
if (!controlled) setInternalOpen(next);
onOpenChange?.(next);
},
[controlled, onOpenChange],
);
const cancelClose = useCallback(() => {
if (closeTimer.current) {
clearTimeout(closeTimer.current);
closeTimer.current = null;
}
}, []);
const cancelOpen = useCallback(() => {
if (openTimer.current) {
clearTimeout(openTimer.current);
openTimer.current = null;
}
}, []);
// Focus opens at once; it is deliberate.
const openHover = useCallback(() => {
cancelClose();
cancelOpen();
setOpen(true);
}, [cancelClose, cancelOpen, setOpen]);
// A pointer waits a beat first. Moving back onto an open panel just keeps it.
const openHoverSoon = useCallback(() => {
cancelClose();
if (open || openTimer.current) return;
openTimer.current = setTimeout(() => {
openTimer.current = null;
setOpen(true);
}, HOVER_OPEN_DELAY);
}, [cancelClose, open, setOpen]);
const scheduleClose = useCallback(() => {
cancelClose();
cancelOpen();
closeTimer.current = setTimeout(() => setOpen(false), HOVER_CLOSE_DELAY);
}, [cancelClose, cancelOpen, setOpen]);
const toggle = useCallback(() => setOpen(!open), [setOpen, open]);
useEffect(
() => () => {
cancelClose();
cancelOpen();
},
[cancelClose, cancelOpen],
);
useEffect(() => {
if (!reduce) {
fade.set(1);
const animation = animate(progress, open ? 1 : 0, open ? GOO_OPEN_SPRING : GOO_CLOSE_SPRING);
return () => animation.stop();
}
// Reduced motion: the panel is at full size the whole time it shows, and
// only its opacity moves. It folds away once it has faded out.
if (open) {
// From fully closed, start transparent; mid-fade, carry on from there.
if (progress.get() === 0) fade.set(0);
progress.set(1);
const animation = animate(fade, 1, FADE_IN);
return () => animation.stop();
}
const animation = animate(fade, 0, FADE_OUT);
animation.then(() => animate(progress, 0, { duration: 0 }));
return () => animation.stop();
}, [open, progress, fade, reduce]);
// The panel is a `role="dialog"` and goes inert the moment it closes, so
// focus cannot be left sitting inside it: Escape hands it back to the
// trigger, the way the ARIA dialog pattern asks. A pointer dismissal takes
// the focus onward itself when it lands on something focusable — this only
// catches the case where it would otherwise be stranded.
const close = useCallback(() => {
setOpen(false);
const focused = document.activeElement;
const inPanel =
focused instanceof HTMLElement && contentRef.current?.contains(focused);
if (inPanel) triggerRef.current?.focus();
}, [setOpen]);
// The panel is portalled, so both trees participate in outside detection.
const ignoreContent = useCallback(
(target: Element) => Boolean(contentRef.current?.contains(target)),
[],
);
// A hover trigger opens on tap as well now, so it needs the same outside
// dismissal the click trigger always had. The gesture passes through to
// whatever it landed on, which is the light-dismiss bargain the platform's
// own popovers strike.
useDismiss(open, close, rootRef, { ignore: ignoreContent });
const ctx = useMemo<PopoverContextValue>(
() => ({
open,
setOpen,
toggle,
openHover,
openHoverSoon,
scheduleClose,
triggerMode: trigger,
side,
align,
gap: sideOffset,
panelRadius,
gooStrength,
reduce,
gooId,
contentId,
progress,
fade,
triggerRef,
contentRef,
}),
[
open,
setOpen,
toggle,
openHover,
openHoverSoon,
scheduleClose,
trigger,
side,
align,
sideOffset,
panelRadius,
gooStrength,
reduce,
gooId,
contentId,
progress,
fade,
],
);
const hoverHandlers =
trigger === "hover"
? makeHoverHandlers(rootHover, openHoverSoon, scheduleClose)
: {};
return (
<PopoverContext.Provider value={ctx}>
<div
ref={rootRef}
className={cn("relative inline-flex isolate", className)}
{...hoverHandlers}
>
{children}
</div>
</PopoverContext.Provider>
);
}
export interface PopoverTriggerProps {
/** A single focusable element (e.g. a Button) that opens the popover. */
children: ReactElement;
}
export function PopoverTrigger({ children }: PopoverTriggerProps) {
const ctx = usePopoverContext("PopoverTrigger");
// What the last gesture on the trigger was, and whether the panel was
// already open when it started. A click reports neither.
const tap = useTapGesture<boolean>();
if (!isValidElement(children)) return children;
const child = children as ReactElement<Record<string, unknown>>;
const childProps = child.props;
const childRef = (childProps as { ref?: Ref<HTMLElement> }).ref;
const compose =
<E extends { defaultPrevented?: boolean }>(
name: string,
handler: (event: E) => void,
) =>
(event: E) => {
(childProps[name] as ((e: unknown) => void) | undefined)?.(event);
if (!event.defaultPrevented) handler(event);
};
// Observation, not action. `compose` steps aside for a child that handled
// the event itself, which is right for anything that *does* something — but
// a child preventing the pointerdown default (to hold focus, say) has not
// said the gesture didn't happen. Skipping the record there left the panel
// reading whatever the gesture before it had put in.
const observe =
<E,>(name: string, handler: (event: E) => void) =>
(event: E) => {
(childProps[name] as ((e: unknown) => void) | undefined)?.(event);
handler(event);
};
// The hover trigger keeps its hover path and *adds* a tap one, rather than
// swapping mode on a device that reports a touchscreen: a touchscreen laptop
// has both inputs and the mouse must keep working. A hovering pointer has
// already opened the panel on its way in, and a keyboard press arrives with
// no pointerdown behind it, so only a tap toggles here. Which panel state
// the tap acts on is read from the gesture's start, because a browser that
// focuses the trigger on contact would otherwise open it mid-gesture and let
// the click close it again.
const handlers: Record<string, unknown> =
ctx.triggerMode === "hover"
? {
onFocus: compose("onFocus", ctx.openHover),
onBlur: compose("onBlur", ctx.scheduleClose),
onPointerDown: observe<React.PointerEvent>(
"onPointerDown",
(event) => tap.start(event, ctx.open),
),
onPointerCancel: observe("onPointerCancel", tap.drop),
onKeyDown: observe("onKeyDown", tap.drop),
onClick: compose("onClick", () => {
const gesture = tap.take();
if (!gesture || gesture.pointerType === "mouse") return;
ctx.setOpen(!gesture.state);
}),
}
: { onClick: compose("onClick", ctx.toggle) };
return cloneElement(child, {
...handlers,
ref: mergeRefs(childRef, (node: HTMLElement | null) => {
ctx.triggerRef.current = node;
}),
// Above the goo layer (z-[-1]) so the neck reads behind it.
className: cn("relative z-0", childProps.className as string | undefined),
"aria-haspopup": "dialog",
"aria-expanded": ctx.open,
"aria-controls": ctx.open ? ctx.contentId : undefined,
"data-state": ctx.open ? "open" : "closed",
});
}
const ALIGN_ORIGIN: Record<Align, string> = {
start: "left",
center: "center",
end: "right",
};
export interface PopoverContentProps {
children: ReactNode;
/** Classes merged onto the panel's content box. */
className?: string;
}
export function PopoverContent({ children, className }: PopoverContentProps) {
const ctx = usePopoverContext("PopoverContent");
const [portalReady, setPortalReady] = useState(false);
const {
side,
align,
gap,
panelRadius,
gooStrength,
reduce,
gooId,
contentId,
progress,
triggerRef,
contentRef,
open,
triggerMode,
openHoverSoon,
scheduleClose,
fade,
} = ctx;
const measureRef = contentRef;
const panelHover = useHoverGesture();
const blobRef = useRef<HTMLDivElement>(null);
const clipRef = useRef<HTMLDivElement>(null);
const geoRef = useRef<Geo | null>(null);
const supportsShapeRef = useRef(false);
const layout = usePopoverPortalPosition(
triggerRef,
measureRef,
portalReady,
);
useEffect(() => setPortalReady(true), []);
const geo = useMemo(
() =>
buildGeo(
layout?.trigger.width ?? 0,
layout?.trigger.height ?? 0,
layout?.content.width ?? 0,
layout?.content.height ?? 0,
side,
align,
gap,
panelRadius,
),
[layout, side, align, gap, panelRadius],
);
// Morph the same clip on the goo body and the content, so the whole popover
// oozes as one and the text reveals with it.
const render = useCallback((g: Geo | null, p: number) => {
if (!g || g.layerW === 0) return;
const clip = clipForProgress(g, p, supportsShapeRef.current);
if (blobRef.current) blobRef.current.style.clipPath = clip;
if (clipRef.current) clipRef.current.style.clipPath = clip;
}, []);
useLayoutEffect(() => {
supportsShapeRef.current =
typeof CSS !== "undefined" &&
typeof CSS.supports === "function" &&
CSS.supports(
"clip-path",
"shape(from 0px 0px, line to 1px 1px, close)",
);
geoRef.current = geo;
render(geo, progress.get());
}, [geo, progress, render]);
useMotionValueEvent(progress, "change", (p) => render(geoRef.current, p));
// While closed, the layer still paints its copy of the trigger pill, and the
// cutout's antialiased edge leaves a faint rim around the real trigger. It
// matches the page, but shows as hairlines over any dimmed backdrop below
// the layer. Hide it once the close has settled, and show it again in the
// render that opens.
const [closedAtRest, setClosedAtRest] = useState(
() => !open && progress.get() === 0,
);
if (open && closedAtRest) setClosedAtRest(false);
const handleAnimationComplete = useCallback(() => {
if (!open && progress.get() === 0) setClosedAtRest(true);
}, [open, progress]);
useMotionValueEvent(progress, "animationComplete", handleAnimationComplete);
const hoverHandlers =
triggerMode === "hover"
? makeHoverHandlers(panelHover, openHoverSoon, scheduleClose)
: {};
// Match the server and first client render, then attach the portal after
// hydration. This preserves SSR without regenerating the page on the client.
if (!portalReady) return null;
return createPortal(
<div
data-popover-portal=""
className="pointer-events-none fixed left-0 top-0 z-[9999] isolate size-0"
style={{
visibility: layout && !closedAtRest ? "visible" : "hidden",
transform: `translate3d(${layout?.trigger.left ?? 0}px, ${layout?.trigger.top ?? 0}px, 0)`,
}}
>
{/* Fully opaque through the morph; carries the fade under reduced motion. */}
<motion.div className="absolute left-0 top-0" style={{ opacity: fade }}>
{/* Goo filter: blur, sharpen the alpha back into solid shapes, then lay
the crisp original on top so blobs merge with liquid edges. */}
<svg aria-hidden width="0" height="0" className="absolute">
<title>Popover visual effects</title>
<defs>
<filter id={gooId} x="-50%" y="-50%" width="200%" height="200%">
<feGaussianBlur
in="SourceGraphic"
stdDeviation={gooStrength}
result="blur"
/>
<feColorMatrix
in="blur"
mode="matrix"
values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 22 -10"
result="goo"
/>
<feComposite in="SourceGraphic" in2="goo" operator="atop" />
</filter>
</defs>
</svg>
{/* Goo body: static trigger pill + morphing blob. */}
<div
aria-hidden
className="pointer-events-none absolute z-[-1]"
style={{
left: geo.left,
top: geo.top,
width: geo.layerW,
height: geo.layerH,
filter: reduce ? undefined : `url(#${gooId})`,
clipPath: triggerCutout(geo),
}}
>
<div
className="absolute bg-popover"
style={{
left: geo.trigger.x,
top: geo.trigger.y,
width: geo.trigger.w,
height: geo.trigger.h,
borderRadius: geo.trigger.r,
}}
/>
<div
ref={blobRef}
className="absolute inset-0 bg-popover"
style={{
clipPath: clipForProgress(geo, progress.get(), false),
}}
/>
</div>
{/* Content is clipped by the same morph. The portal wrapper stays
pointer-transparent; only the fully open panel accepts interaction. */}
<div
className="pointer-events-none absolute z-10"
style={{
left: geo.left,
top: geo.top,
width: geo.layerW,
height: geo.layerH,
}}
>
<div
ref={clipRef}
inert={!open}
className="absolute inset-0"
style={{
clipPath: clipForProgress(geo, progress.get(), false),
pointerEvents: open ? "auto" : "none",
}}
>
<div
ref={measureRef}
id={contentId}
role="dialog"
{...hoverHandlers}
style={{
position: "absolute",
left: geo.panel.x,
top: geo.panel.y,
transformOrigin: `${ALIGN_ORIGIN[align]} ${side === "bottom" ? "top" : "bottom"}`,
}}
className={cn(
"w-max max-w-[min(92vw,20rem)] p-4 text-popover-foreground outline-none",
className,
)}
>
{children}
</div>
</div>
</div>
</motion.div>
</div>,
document.body,
);
}
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
"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 { useMemo, useRef } from "react";
import { isHoveringPointer } from "@/lib/touch";
interface BoundaryEvent {
pointerId: number;
pointerType: string;
buttons: number;
}
export interface HoverGesture {
/** True when this enter starts a hover: the pointer arrived resting, not pressing. */
enter: (event: BoundaryEvent) => boolean;
/** True when this leave ends a hover that entered as one. */
leave: (event: BoundaryEvent) => boolean;
}
/**
* Pairs a surface's enter with its leave, per pointer.
*
* `isHoveringPointer` answers the question the *enter* asks — is this pointer
* resting on the surface or pressing it — and both boundary cases go wrong if
* the leave is asked the same question again:
*
* - A pen with no hover never rests. It arrives in contact, taps, and the spec
* then requires its boundary events after `pointerup`, so the leave carries
* `buttons: 0` and reads as a mouse gliding off. Hover teardown then undid
* the tap — the panel the pen had just opened closed under it.
* - A mouse pressed on the surface and dragged off leaves with `buttons: 1`.
* Skipping teardown there strands the surface open: the release happens
* outside, and no second leave ever comes.
*
* So the state a hover holds is released by the pointer that took it, whatever
* the buttons say at the boundary, and a pointer that arrived in contact never
* took it in the first place. Contact is the exception tracked here, not
* hover: a leave from a pointer this surface never saw enter — mounted under
* the cursor, say — still counts, since the alternative is state with no way
* out.
*/
export function useHoverGesture(): HoverGesture {
const contact = useRef(new Set<number>());
return useMemo(
() => ({
enter: (event) => {
if (isHoveringPointer(event)) {
contact.current.delete(event.pointerId);
return true;
}
contact.current.add(event.pointerId);
return false;
},
leave: (event) => {
const arrivedInContact = contact.current.delete(event.pointerId);
return !arrivedInContact && event.pointerType !== "touch";
},
}),
[],
);
}
"use client";
import { useMemo, useRef } from "react";
/** What a pointerdown recorded, read back by the click that ends its gesture. */
export interface TapRecord<S> {
/** Which input started the gesture. */
pointerType: string;
/** What the surface was showing when it started. */
state: S;
}
export interface TapGesture<S> {
/** Record the gesture a pointerdown starts, with the state it starts in. */
start: (event: { pointerType: string }, state: S) => void;
/** Read the record and clear it. `null` when no pointer is behind this click. */
take: () => TapRecord<S> | null;
/** Drop the record: this gesture will never spend it on a click. */
drop: () => void;
}
/**
* The pointer gesture behind a click, recorded where the click cannot report
* it. A `click` carries no `pointerType` in the engines that matter, so the
* `pointerdown` before it is the only thing that says which input activated
* the control — and whether one did at all, since keyboard activation
* synthesizes a click with no pointer behind it.
*
* State goes in with the record because a click reports that no better: a
* browser that focuses a control on contact can open the very panel the tap
* was meant to open, and reading "is it open" at click time then undoes it.
* What the gesture started against is what it acts on.
*
* The record is spent by one click and dropped by everything else, because a
* record that outlives its gesture is worse than none:
*
* - A scroll or an OS gesture takes the touch away — `pointercancel`, no click
* ever — and the finger would sit in the record until some later click.
* - That later click is often `Enter` on a keyboard, which arrives with no
* pointerdown of its own and would inherit the abandoned finger. A keydown
* is the start of a keyboard activation and never part of a tap, so it drops
* the record too.
*
* Both ends have to be wired by the surface: `drop` on `onPointerCancel` and
* on `onKeyDown`.
*/
export function useTapGesture<S>(): TapGesture<S> {
const record = useRef<TapRecord<S> | null>(null);
return useMemo(
() => ({
start: (event, state) => {
record.current = { pointerType: event.pointerType, state };
},
take: () => {
const spent = record.current;
record.current = null;
return spent;
},
drop: () => {
record.current = null;
},
}),
[],
);
}
import type { Ref } from "react";
/** Points a callback or object ref at `value`. */
export function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {
if (typeof ref === "function") ref(value);
else if (ref) ref.current = value;
}
/** One callback ref that sets every ref it is given. */
export function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {
return (node: T | null) => {
for (const ref of refs) assignRef(ref, node);
};
}
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),
);
}
// Shared touch primitives. iOS and iPadOS run their own gestures on top of the
// page — the long-press selection callout and the selection it drags in with
// it — and they win: once the platform claims a touch it cancels ours
// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own
// their gesture have to opt out.
//
// What the two classes below cover, precisely:
// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:
// it is not a property other engines have, so it is inert everywhere else.
// - `user-select: none` stops the long-press selection on every engine,
// Android included, and stops a drag from painting a selection under the
// cursor. It is inherited, so it reaches every descendant — which is why the
// two classes differ only in whether they apply it unconditionally.
// What neither covers:
// - Chrome for Android's long-press menu on a link or an image. No CSS
// suppresses it; a gesture surface that wraps one needs its own
// `onContextMenu` with `preventDefault()`.
// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is
// not inherited and plain divs and buttons are not drag sources, so setting
// it on the surface does nothing — the child itself needs `draggable={false}`.
/**
* Classes for a surface that *is* the control: a thumb, a drum, a stage, a
* handle, a hold button. Selection is suppressed on every input, because a
* drag that highlights the control's own label is wrong on a mouse too.
* Compose with `touch-none` when the surface also owns the scroll axis — leave
* it off when the page must still scroll from there.
*/
export const TOUCH_GESTURE_CLASS = "select-none [-webkit-touch-callout:none]";
/**
* The same opt-out for a gesture surface that wraps content the consumer owns:
* a scroller, a context-menu trigger, a sheet header, a list row. Selection is
* suppressed only where the platform runs its own press gestures — a coarse
* pointer — so a mouse user can still select and copy that content. If the
* gesture itself would paint a selection under the cursor, add `select-none`
* for the duration of the gesture rather than reaching for
* `TOUCH_GESTURE_CLASS`.
*
* `pointer: coarse` describes the *primary* pointer and nothing else, so a
* hybrid machine reads it wrong in both directions: a tablet with a mouse
* plugged in keeps touch as primary and loses mouse selection, and a laptop
* with a touchscreen keeps the mouse as primary and leaves selection live
* under a finger. No media query can answer per interaction — the query is
* about the device, and the question is about the gesture in progress. The
* default stays here because it is right on the machines that are one thing or
* the other, and losing a selection is a nuisance; where the miss costs a
* *gesture* instead, the surface pairs it with `holdSelection` on the press.
*/
export const TOUCH_GESTURE_CONTENT_CLASS =
"[-webkit-touch-callout:none] pointer-coarse:select-none";
/**
* Suppress selection on `element` for as long as a gesture is running on it,
* whatever the primary pointer of the machine happens to be. Returns the
* release. Inline, so it wins over the class above and is gone again the
* moment the gesture ends.
*
* For the press gestures a native selection would otherwise steal — a
* long-press that opens a menu. Elsewhere prefer the classes: a surface that
* takes selection away for the whole session is a surface whose text nobody
* can copy.
*/
export function holdSelection(element: HTMLElement) {
element.style.setProperty("user-select", "none");
element.style.setProperty("-webkit-user-select", "none");
return () => {
element.style.removeProperty("user-select");
element.style.removeProperty("-webkit-user-select");
};
}
/**
* Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer
* is already gone by the time the handler runs — routine on iOS, where the
* system can claim the touch first — and an uncaught throw takes the rest of
* the handler, the gesture included, down with it. Touch pointers carry
* implicit capture anyway, so losing it is never fatal.
*/
export function capturePointer(element: Element, pointerId: number) {
try {
element.setPointerCapture(pointerId);
} catch {
// Pointer is no longer active — implicit capture still applies on touch.
}
}
/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */
export function releasePointer(element: Element, pointerId: number) {
try {
if (element.hasPointerCapture(pointerId)) {
element.releasePointerCapture(pointerId);
}
} catch {
// Capture was already dropped by the browser.
}
}
/**
* Whether this event came from a pointer that is *hovering*: not a touch, and
* not currently pressed. Which input the user is holding right now is not
* something a device capability can answer — a touchscreen laptop hovers and
* taps, and iPadOS reports a fine hovering pointer for a finger — so both
* paths stay live and each handler branches on the event it was given.
*
* A pen resting on the glass is making contact, not hovering: `buttons` is the
* tell, and it sends a pen tap down the same route a finger takes.
*
* This answers what an *enter* asks. A leave is the other half of a pair and
* has to be read against the enter that started it — `useHoverGesture` in
* `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it
* rather than asking this question twice.
*/
export const isHoveringPointer = (event: {
pointerType: string;
buttons: number;
}) => event.pointerType !== "touch" && event.buttons === 0;
// 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,
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 physical button: a switch click that settles twice over a soft thump and a little casing ring. */
export const pressSound = defineSound({
name: "Press",
duration: 0.1,
vary: 0.03,
room: 0.1,
build: (v) => {
v.click({ freq: 2800, q: 1.8, decay: 0.005, gain: 0.5 });
v.click({ freq: 4200, q: 2.5, at: 0.011, decay: 0.003, gain: 0.16 });
v.strike({ freq: 150, material: "wood", bend: 1.5, decay: 0.07, gain: 0.75 });
v.strike({ freq: 1250, material: "plastic", decay: 0.022, gain: 0.14 });
},
});
"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],
);
}
// 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,
});
},
};
}
"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;
}
Copy the source code
"use client";
// beui.dev/components/motion/popover/gooey
import {
animate,
type MotionValue,
motion,
useMotionValue,
useMotionValueEvent,
useReducedMotion,
} from "motion/react";
import {
cloneElement,
createContext,
isValidElement,
type ReactElement,
type ReactNode,
type Ref,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { usePopoverPortalPosition } from "@/components/motion/popover-position";
import { useDismiss } from "@/lib/hooks/use-dismiss";
import {
type HoverGesture,
useHoverGesture,
} from "@/lib/hooks/use-hover-gesture";
import { useTapGesture } from "@/lib/hooks/use-tap-gesture";
import { mergeRefs } from "@/lib/merge-refs";
import { cn } from "@/lib/utils";
type Side = "top" | "bottom";
type Align = "start" | "center" | "end";
type TriggerMode = "click" | "hover";
// This morph needs less bounce than layout motion: too much overshoot makes
// the liquid neck balloon past the final panel edges.
const GOO_OPEN_SPRING = {
type: "spring",
visualDuration: 0.3,
bounce: 0.15,
} as const;
const GOO_CLOSE_SPRING = {
type: "spring",
visualDuration: 0.21,
bounce: 0.15,
} as const;
// A pointer crossing the trigger on its way elsewhere should not burst the
// panel open; one that stops for a moment means it.
const HOVER_OPEN_DELAY = 100;
const HOVER_CLOSE_DELAY = 120;
// Reduced motion trades the morph for a plain fade, out faster than in.
const FADE_IN = { duration: 0.15 } as const;
const FADE_OUT = { duration: 0.12 } as const;
const CIRCLE_KAPPA = 0.5523;
// `onPointerEnter`/`onPointerLeave` rather than the mouse pair: a tap fires
// compatibility mouseenter/mouseleave that carry no pointerType at all, and
// they are what made the panel flicker open and shut under a finger. The
// gesture pairs the two, so the panel a pen tap opened is not closed again by
// the boundary event that ends the same tap.
function makeHoverHandlers(
hover: HoverGesture,
enter: () => void,
leave: () => void,
) {
return {
onPointerEnter: (event: React.PointerEvent) => {
if (hover.enter(event)) enter();
},
onPointerLeave: (event: React.PointerEvent) => {
if (hover.leave(event)) leave();
},
};
}
const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
interface Rect {
x: number;
y: number;
w: number;
h: number;
r: number;
}
interface Geo {
layerW: number;
layerH: number;
left: number;
top: number;
trigger: Rect;
panel: Rect;
}
// Trigger rect and panel rect in a shared local coordinate box.
function buildGeo(
tW: number,
tH: number,
cW: number,
cH: number,
side: Side,
align: Align,
gap: number,
panelRadius: number,
): Geo {
const py = side === "bottom" ? tH + gap : -(gap + cH);
const px = align === "start" ? 0 : align === "end" ? tW - cW : (tW - cW) / 2;
const left = Math.min(0, px);
const top = Math.min(0, py);
const layerW = Math.max(tW, px + cW) - left;
const layerH = Math.max(tH, py + cH) - top;
const triggerRadius = Math.min(tH / 2, panelRadius);
return {
layerW,
layerH,
left,
top,
trigger: { x: -left, y: -top, w: tW, h: tH, r: triggerRadius },
panel: { x: px - left, y: py - top, w: cW, h: cH, r: panelRadius },
};
}
function rectAtProgress(geo: Geo, progress: number): Rect {
const trigger = geo.trigger;
const panel = geo.panel;
return {
x: lerp(trigger.x, panel.x, progress),
y: lerp(trigger.y, panel.y, progress),
w: lerp(trigger.w, panel.w, progress),
h: lerp(trigger.h, panel.h, progress),
r: lerp(trigger.r, panel.r, progress),
};
}
function insetFor(rect: Rect, layerW: number, layerH: number) {
const top = rect.y;
const right = layerW - (rect.x + rect.w);
const bottom = layerH - (rect.y + rect.h);
const left = rect.x;
return `inset(${top}px ${right}px ${bottom}px ${left}px round ${rect.r}px)`;
}
function roundedRectShape(rect: Rect) {
const radius = Math.max(0, Math.min(rect.r, rect.w / 2, rect.h / 2));
const control = radius * CIRCLE_KAPPA;
const x1 = rect.x;
const y1 = rect.y;
const x2 = rect.x + rect.w;
const y2 = rect.y + rect.h;
const px = (value: number) => `${value.toFixed(3)}px`;
return (
`shape(from ${px(x1 + radius)} ${px(y1)}, ` +
`line to ${px(x2 - radius)} ${px(y1)}, ` +
`curve to ${px(x2)} ${px(y1 + radius)} with ${px(x2 - radius + control)} ${px(y1)} / ${px(x2)} ${px(y1 + radius - control)}, ` +
`line to ${px(x2)} ${px(y2 - radius)}, ` +
`curve to ${px(x2 - radius)} ${px(y2)} with ${px(x2)} ${px(y2 - radius + control)} / ${px(x2 - radius + control)} ${px(y2)}, ` +
`line to ${px(x1 + radius)} ${px(y2)}, ` +
`curve to ${px(x1)} ${px(y2 - radius)} with ${px(x1 + radius - control)} ${px(y2)} / ${px(x1)} ${px(y2 - radius + control)}, ` +
`line to ${px(x1)} ${px(y1 + radius)}, ` +
`curve to ${px(x1 + radius)} ${px(y1)} with ${px(x1)} ${px(y1 + radius - control)} / ${px(x1 + radius - control)} ${px(y1)}, ` +
"close)"
);
}
function clipForProgress(geo: Geo, progress: number, supportsShape: boolean) {
const rect = rectAtProgress(geo, progress);
return supportsShape
? roundedRectShape(rect)
: insetFor(rect, geo.layerW, geo.layerH);
}
function roundedRectPath(rect: Rect) {
const radius = Math.max(0, Math.min(rect.r, rect.w / 2, rect.h / 2));
const n = (value: number) => value.toFixed(3);
const x1 = rect.x;
const y1 = rect.y;
const x2 = rect.x + rect.w;
const y2 = rect.y + rect.h;
const arc = `A${n(radius)} ${n(radius)} 0 0 1`;
// A zero radius makes every arc degenerate to a line, so this also draws
// plain rectangles.
return (
`M${n(x1 + radius)} ${n(y1)}` +
`H${n(x2 - radius)}${arc} ${n(x2)} ${n(y1 + radius)}` +
`V${n(y2 - radius)}${arc} ${n(x2 - radius)} ${n(y2)}` +
`H${n(x1 + radius)}${arc} ${n(x1)} ${n(y2 - radius)}` +
`V${n(y1 + radius)}${arc} ${n(x1 + radius)} ${n(y1)}Z`
);
}
// The goo layer is portalled above the page, so its copy of the trigger pill
// would cover the real trigger's label and focus ring. Punching the trigger
// back out keeps the real one visible and clips the blur to the layer box.
// This is a clip path rather than a CSS mask on purpose: WebKit silently
// ignores `mask: url(#id)` pointing at an SVG <mask> element, which left the
// label hidden behind the goo in Safari.
function triggerCutout(geo: Geo) {
const layer = { x: 0, y: 0, w: geo.layerW, h: geo.layerH, r: 0 };
return `path(evenodd, "${roundedRectPath(layer)} ${roundedRectPath(geo.trigger)}")`;
}
interface PopoverContextValue {
open: boolean;
setOpen: (open: boolean) => void;
toggle: () => void;
/** Open now (focus). */
openHover: () => void;
/** Open after a short intent delay (pointer). */
openHoverSoon: () => void;
scheduleClose: () => void;
triggerMode: TriggerMode;
side: Side;
align: Align;
gap: number;
panelRadius: number;
gooStrength: number;
reduce: boolean;
gooId: string;
contentId: string;
progress: MotionValue<number>;
fade: MotionValue<number>;
triggerRef: React.MutableRefObject<HTMLElement | null>;
contentRef: React.MutableRefObject<HTMLDivElement | null>;
}
const PopoverContext = createContext<PopoverContextValue | null>(null);
function usePopoverContext(component: string) {
const ctx = useContext(PopoverContext);
if (!ctx) throw new Error(`${component} must be used within <Popover>`);
return ctx;
}
export interface PopoverProps {
children: ReactNode;
/** Controlled open state. */
open?: boolean;
/** Uncontrolled initial open state. */
defaultOpen?: boolean;
/** Called with the new open state when the panel opens or closes. */
onOpenChange?: (open: boolean) => void;
/** How the popover is summoned. Default "click". */
trigger?: TriggerMode;
/** Which side of the trigger the panel oozes out of. Default "bottom". */
side?: Side;
/** Alignment along the trigger's edge. Default "center". */
align?: Align;
/** Gap between trigger and panel, in px — the length of the gooey neck. Default 14. */
sideOffset?: number;
/** Corner radius of the open panel, in px. Default 16. */
panelRadius?: number;
/** Blur radius feeding the goo filter — higher melts more. Default 8. */
gooStrength?: number;
/** Classes merged onto the wrapper around the trigger. */
className?: string;
}
export function Popover({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
trigger = "click",
side = "bottom",
align = "center",
sideOffset = 14,
panelRadius = 16,
gooStrength = 8,
className,
}: PopoverProps) {
const reduce = useReducedMotion() ?? false;
const gooId = useId().replace(/:/g, "");
const contentId = useId();
const rootRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);
const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const rootHover = useHoverGesture();
const progress = useMotionValue(defaultOpen ? 1 : 0);
// The whole layer's opacity: 1 throughout the morph, faded under reduced motion.
const fade = useMotionValue(1);
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const controlled = controlledOpen !== undefined;
const open = controlled ? controlledOpen : internalOpen;
const setOpen = useCallback(
(next: boolean) => {
if (!controlled) setInternalOpen(next);
onOpenChange?.(next);
},
[controlled, onOpenChange],
);
const cancelClose = useCallback(() => {
if (closeTimer.current) {
clearTimeout(closeTimer.current);
closeTimer.current = null;
}
}, []);
const cancelOpen = useCallback(() => {
if (openTimer.current) {
clearTimeout(openTimer.current);
openTimer.current = null;
}
}, []);
// Focus opens at once; it is deliberate.
const openHover = useCallback(() => {
cancelClose();
cancelOpen();
setOpen(true);
}, [cancelClose, cancelOpen, setOpen]);
// A pointer waits a beat first. Moving back onto an open panel just keeps it.
const openHoverSoon = useCallback(() => {
cancelClose();
if (open || openTimer.current) return;
openTimer.current = setTimeout(() => {
openTimer.current = null;
setOpen(true);
}, HOVER_OPEN_DELAY);
}, [cancelClose, open, setOpen]);
const scheduleClose = useCallback(() => {
cancelClose();
cancelOpen();
closeTimer.current = setTimeout(() => setOpen(false), HOVER_CLOSE_DELAY);
}, [cancelClose, cancelOpen, setOpen]);
const toggle = useCallback(() => setOpen(!open), [setOpen, open]);
useEffect(
() => () => {
cancelClose();
cancelOpen();
},
[cancelClose, cancelOpen],
);
useEffect(() => {
if (!reduce) {
fade.set(1);
const animation = animate(progress, open ? 1 : 0, open ? GOO_OPEN_SPRING : GOO_CLOSE_SPRING);
return () => animation.stop();
}
// Reduced motion: the panel is at full size the whole time it shows, and
// only its opacity moves. It folds away once it has faded out.
if (open) {
// From fully closed, start transparent; mid-fade, carry on from there.
if (progress.get() === 0) fade.set(0);
progress.set(1);
const animation = animate(fade, 1, FADE_IN);
return () => animation.stop();
}
const animation = animate(fade, 0, FADE_OUT);
animation.then(() => animate(progress, 0, { duration: 0 }));
return () => animation.stop();
}, [open, progress, fade, reduce]);
// The panel is a `role="dialog"` and goes inert the moment it closes, so
// focus cannot be left sitting inside it: Escape hands it back to the
// trigger, the way the ARIA dialog pattern asks. A pointer dismissal takes
// the focus onward itself when it lands on something focusable — this only
// catches the case where it would otherwise be stranded.
const close = useCallback(() => {
setOpen(false);
const focused = document.activeElement;
const inPanel =
focused instanceof HTMLElement && contentRef.current?.contains(focused);
if (inPanel) triggerRef.current?.focus();
}, [setOpen]);
// The panel is portalled, so both trees participate in outside detection.
const ignoreContent = useCallback(
(target: Element) => Boolean(contentRef.current?.contains(target)),
[],
);
// A hover trigger opens on tap as well now, so it needs the same outside
// dismissal the click trigger always had. The gesture passes through to
// whatever it landed on, which is the light-dismiss bargain the platform's
// own popovers strike.
useDismiss(open, close, rootRef, { ignore: ignoreContent });
const ctx = useMemo<PopoverContextValue>(
() => ({
open,
setOpen,
toggle,
openHover,
openHoverSoon,
scheduleClose,
triggerMode: trigger,
side,
align,
gap: sideOffset,
panelRadius,
gooStrength,
reduce,
gooId,
contentId,
progress,
fade,
triggerRef,
contentRef,
}),
[
open,
setOpen,
toggle,
openHover,
openHoverSoon,
scheduleClose,
trigger,
side,
align,
sideOffset,
panelRadius,
gooStrength,
reduce,
gooId,
contentId,
progress,
fade,
],
);
const hoverHandlers =
trigger === "hover"
? makeHoverHandlers(rootHover, openHoverSoon, scheduleClose)
: {};
return (
<PopoverContext.Provider value={ctx}>
<div
ref={rootRef}
className={cn("relative inline-flex isolate", className)}
{...hoverHandlers}
>
{children}
</div>
</PopoverContext.Provider>
);
}
export interface PopoverTriggerProps {
/** A single focusable element (e.g. a Button) that opens the popover. */
children: ReactElement;
}
export function PopoverTrigger({ children }: PopoverTriggerProps) {
const ctx = usePopoverContext("PopoverTrigger");
// What the last gesture on the trigger was, and whether the panel was
// already open when it started. A click reports neither.
const tap = useTapGesture<boolean>();
if (!isValidElement(children)) return children;
const child = children as ReactElement<Record<string, unknown>>;
const childProps = child.props;
const childRef = (childProps as { ref?: Ref<HTMLElement> }).ref;
const compose =
<E extends { defaultPrevented?: boolean }>(
name: string,
handler: (event: E) => void,
) =>
(event: E) => {
(childProps[name] as ((e: unknown) => void) | undefined)?.(event);
if (!event.defaultPrevented) handler(event);
};
// Observation, not action. `compose` steps aside for a child that handled
// the event itself, which is right for anything that *does* something — but
// a child preventing the pointerdown default (to hold focus, say) has not
// said the gesture didn't happen. Skipping the record there left the panel
// reading whatever the gesture before it had put in.
const observe =
<E,>(name: string, handler: (event: E) => void) =>
(event: E) => {
(childProps[name] as ((e: unknown) => void) | undefined)?.(event);
handler(event);
};
// The hover trigger keeps its hover path and *adds* a tap one, rather than
// swapping mode on a device that reports a touchscreen: a touchscreen laptop
// has both inputs and the mouse must keep working. A hovering pointer has
// already opened the panel on its way in, and a keyboard press arrives with
// no pointerdown behind it, so only a tap toggles here. Which panel state
// the tap acts on is read from the gesture's start, because a browser that
// focuses the trigger on contact would otherwise open it mid-gesture and let
// the click close it again.
const handlers: Record<string, unknown> =
ctx.triggerMode === "hover"
? {
onFocus: compose("onFocus", ctx.openHover),
onBlur: compose("onBlur", ctx.scheduleClose),
onPointerDown: observe<React.PointerEvent>(
"onPointerDown",
(event) => tap.start(event, ctx.open),
),
onPointerCancel: observe("onPointerCancel", tap.drop),
onKeyDown: observe("onKeyDown", tap.drop),
onClick: compose("onClick", () => {
const gesture = tap.take();
if (!gesture || gesture.pointerType === "mouse") return;
ctx.setOpen(!gesture.state);
}),
}
: { onClick: compose("onClick", ctx.toggle) };
return cloneElement(child, {
...handlers,
ref: mergeRefs(childRef, (node: HTMLElement | null) => {
ctx.triggerRef.current = node;
}),
// Above the goo layer (z-[-1]) so the neck reads behind it.
className: cn("relative z-0", childProps.className as string | undefined),
"aria-haspopup": "dialog",
"aria-expanded": ctx.open,
"aria-controls": ctx.open ? ctx.contentId : undefined,
"data-state": ctx.open ? "open" : "closed",
});
}
const ALIGN_ORIGIN: Record<Align, string> = {
start: "left",
center: "center",
end: "right",
};
export interface PopoverContentProps {
children: ReactNode;
/** Classes merged onto the panel's content box. */
className?: string;
}
export function PopoverContent({ children, className }: PopoverContentProps) {
const ctx = usePopoverContext("PopoverContent");
const [portalReady, setPortalReady] = useState(false);
const {
side,
align,
gap,
panelRadius,
gooStrength,
reduce,
gooId,
contentId,
progress,
triggerRef,
contentRef,
open,
triggerMode,
openHoverSoon,
scheduleClose,
fade,
} = ctx;
const measureRef = contentRef;
const panelHover = useHoverGesture();
const blobRef = useRef<HTMLDivElement>(null);
const clipRef = useRef<HTMLDivElement>(null);
const geoRef = useRef<Geo | null>(null);
const supportsShapeRef = useRef(false);
const layout = usePopoverPortalPosition(
triggerRef,
measureRef,
portalReady,
);
useEffect(() => setPortalReady(true), []);
const geo = useMemo(
() =>
buildGeo(
layout?.trigger.width ?? 0,
layout?.trigger.height ?? 0,
layout?.content.width ?? 0,
layout?.content.height ?? 0,
side,
align,
gap,
panelRadius,
),
[layout, side, align, gap, panelRadius],
);
// Morph the same clip on the goo body and the content, so the whole popover
// oozes as one and the text reveals with it.
const render = useCallback((g: Geo | null, p: number) => {
if (!g || g.layerW === 0) return;
const clip = clipForProgress(g, p, supportsShapeRef.current);
if (blobRef.current) blobRef.current.style.clipPath = clip;
if (clipRef.current) clipRef.current.style.clipPath = clip;
}, []);
useLayoutEffect(() => {
supportsShapeRef.current =
typeof CSS !== "undefined" &&
typeof CSS.supports === "function" &&
CSS.supports(
"clip-path",
"shape(from 0px 0px, line to 1px 1px, close)",
);
geoRef.current = geo;
render(geo, progress.get());
}, [geo, progress, render]);
useMotionValueEvent(progress, "change", (p) => render(geoRef.current, p));
// While closed, the layer still paints its copy of the trigger pill, and the
// cutout's antialiased edge leaves a faint rim around the real trigger. It
// matches the page, but shows as hairlines over any dimmed backdrop below
// the layer. Hide it once the close has settled, and show it again in the
// render that opens.
const [closedAtRest, setClosedAtRest] = useState(
() => !open && progress.get() === 0,
);
if (open && closedAtRest) setClosedAtRest(false);
const handleAnimationComplete = useCallback(() => {
if (!open && progress.get() === 0) setClosedAtRest(true);
}, [open, progress]);
useMotionValueEvent(progress, "animationComplete", handleAnimationComplete);
const hoverHandlers =
triggerMode === "hover"
? makeHoverHandlers(panelHover, openHoverSoon, scheduleClose)
: {};
// Match the server and first client render, then attach the portal after
// hydration. This preserves SSR without regenerating the page on the client.
if (!portalReady) return null;
return createPortal(
<div
data-popover-portal=""
className="pointer-events-none fixed left-0 top-0 z-[9999] isolate size-0"
style={{
visibility: layout && !closedAtRest ? "visible" : "hidden",
transform: `translate3d(${layout?.trigger.left ?? 0}px, ${layout?.trigger.top ?? 0}px, 0)`,
}}
>
{/* Fully opaque through the morph; carries the fade under reduced motion. */}
<motion.div className="absolute left-0 top-0" style={{ opacity: fade }}>
{/* Goo filter: blur, sharpen the alpha back into solid shapes, then lay
the crisp original on top so blobs merge with liquid edges. */}
<svg aria-hidden width="0" height="0" className="absolute">
<title>Popover visual effects</title>
<defs>
<filter id={gooId} x="-50%" y="-50%" width="200%" height="200%">
<feGaussianBlur
in="SourceGraphic"
stdDeviation={gooStrength}
result="blur"
/>
<feColorMatrix
in="blur"
mode="matrix"
values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 22 -10"
result="goo"
/>
<feComposite in="SourceGraphic" in2="goo" operator="atop" />
</filter>
</defs>
</svg>
{/* Goo body: static trigger pill + morphing blob. */}
<div
aria-hidden
className="pointer-events-none absolute z-[-1]"
style={{
left: geo.left,
top: geo.top,
width: geo.layerW,
height: geo.layerH,
filter: reduce ? undefined : `url(#${gooId})`,
clipPath: triggerCutout(geo),
}}
>
<div
className="absolute bg-popover"
style={{
left: geo.trigger.x,
top: geo.trigger.y,
width: geo.trigger.w,
height: geo.trigger.h,
borderRadius: geo.trigger.r,
}}
/>
<div
ref={blobRef}
className="absolute inset-0 bg-popover"
style={{
clipPath: clipForProgress(geo, progress.get(), false),
}}
/>
</div>
{/* Content is clipped by the same morph. The portal wrapper stays
pointer-transparent; only the fully open panel accepts interaction. */}
<div
className="pointer-events-none absolute z-10"
style={{
left: geo.left,
top: geo.top,
width: geo.layerW,
height: geo.layerH,
}}
>
<div
ref={clipRef}
inert={!open}
className="absolute inset-0"
style={{
clipPath: clipForProgress(geo, progress.get(), false),
pointerEvents: open ? "auto" : "none",
}}
>
<div
ref={measureRef}
id={contentId}
role="dialog"
{...hoverHandlers}
style={{
position: "absolute",
left: geo.panel.x,
top: geo.panel.y,
transformOrigin: `${ALIGN_ORIGIN[align]} ${side === "bottom" ? "top" : "bottom"}`,
}}
className={cn(
"w-max max-w-[min(92vw,20rem)] p-4 text-popover-foreground outline-none",
className,
)}
>
{children}
</div>
</div>
</div>
</motion.div>
</div>,
document.body,
);
}
"use client";
import {
type MutableRefObject,
useCallback,
useLayoutEffect,
useState,
} from "react";
export type PortalLayout = {
trigger: {
left: number;
top: number;
width: number;
height: number;
};
content: {
width: number;
height: number;
};
};
function sameLayout(a: PortalLayout | null, b: PortalLayout) {
return (
a?.trigger.left === b.trigger.left &&
a.trigger.top === b.trigger.top &&
a.trigger.width === b.trigger.width &&
a.trigger.height === b.trigger.height &&
a.content.width === b.content.width &&
a.content.height === b.content.height
);
}
/** Measures a trigger and portalled panel in viewport coordinates. */
export function usePopoverPortalPosition<
TriggerElement extends HTMLElement,
ContentElement extends HTMLElement,
>(
triggerRef: MutableRefObject<TriggerElement | null>,
contentRef: MutableRefObject<ContentElement | null>,
active: boolean,
) {
const [layout, setLayout] = useState<PortalLayout | null>(null);
const update = useCallback(() => {
const trigger = triggerRef.current;
const content = contentRef.current;
if (!trigger || !content) return;
const rect = trigger.getBoundingClientRect();
const next: PortalLayout = {
trigger: {
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height,
},
content: {
width: content.offsetWidth,
height: content.offsetHeight,
},
};
setLayout((current) => (sameLayout(current, next) ? current : next));
}, [contentRef, triggerRef]);
useLayoutEffect(() => {
update();
if (!active) return;
const trigger = triggerRef.current;
const content = contentRef.current;
const observer = new ResizeObserver(update);
if (trigger) observer.observe(trigger);
if (content) observer.observe(content);
window.addEventListener("scroll", update, true);
window.addEventListener("resize", update);
return () => {
observer.disconnect();
window.removeEventListener("scroll", update, true);
window.removeEventListener("resize", update);
};
}, [active, contentRef, triggerRef, update]);
return layout;
}
export type {
ButtonLinkProps,
ButtonProps,
ButtonSize,
ButtonVariant,
} from "./base";
export { Button, ButtonLink } from "./base";
export type { MagneticButtonProps } from "./magnetic";
export { MagneticButton } from "./magnetic";
export type { MetallicButtonProps } from "./metallic";
export { MetallicButton } from "./metallic";
export type {
ButtonState,
StatefulButtonMessages,
StatefulButtonProps,
} from "./stateful";
export { StatefulButton, statefulButtonMessages } from "./stateful";
"use client";
import {
AnimatePresence,
type HTMLMotionProps,
motion,
useReducedMotion,
} from "motion/react";
import {
forwardRef,
type MouseEvent,
type PointerEvent,
type ReactNode,
useCallback,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_PRESS } from "@/lib/ease";
import { useSound } from "@/lib/sound";
import { pressSound } from "@/lib/sounds/press";
import { cn } from "@/lib/utils";
export type ButtonVariant = "primary" | "secondary" | "ghost" | "outline";
export type ButtonSize = "sm" | "md" | "lg" | "icon";
export interface ButtonProps extends Omit<
HTMLMotionProps<"button">,
"children"
> {
/** Visual style: filled, card, ghost or outline. Default: "primary" */
variant?: ButtonVariant;
/** Height and padding; "icon" is a square icon-only button. Default: "md" */
size?: ButtonSize;
/** Scale while pressed. Default 0.97: subtle, so the press reads as feedback, not a squash. */
pressScale?: number;
/** Spawn a Material-style ripple from the press point. Off by default. */
ripple?: boolean;
/** Play a soft press sound. Off by default; a `SoundProvider` can mute it app-wide. */
sound?: boolean;
children?: ReactNode;
}
export interface ButtonLinkProps extends Omit<
HTMLMotionProps<"a">,
"children"
> {
/** Visual style: filled, card, ghost or outline. Default: "primary" */
variant?: ButtonVariant;
/** Height and padding; "icon" is a square icon-only link. Default: "md" */
size?: ButtonSize;
/** Scale while pressed. Default 0.97. */
pressScale?: number;
children?: ReactNode;
}
type Ripple = { id: number; x: number; y: number; size: number };
const VARIANT_CLASS: Record<ButtonVariant, string> = {
primary: "bg-primary text-primary-foreground hover:bg-primary/90",
secondary: "border border-border bg-card text-foreground hover:border-border",
ghost: "text-muted-foreground hover:text-foreground hover:bg-muted/60",
outline:
"border border-border bg-transparent text-foreground hover:bg-muted/60",
};
const SIZE_CLASS: Record<ButtonSize, string> = {
sm: "h-8 px-3 text-xs gap-1.5 rounded-full",
md: "h-10 px-5 text-sm gap-2 rounded-full",
lg: "h-12 px-6 text-base gap-2 rounded-full",
icon: "h-8 w-8 rounded-full",
};
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
function Button(
{
variant = "primary",
size = "md",
pressScale = 0.97,
ripple = false,
sound = false,
className,
children,
onPointerDown,
onClick,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const [ripples, setRipples] = useState<Ripple[]>([]);
const nextId = useRef(0);
const play = useSound(pressSound, { enabled: sound });
const handleClick = useCallback(
(event: MouseEvent<HTMLButtonElement>) => {
// `detail` is 0 for a click the keyboard made; a pointer press already sounded.
if (event.detail === 0) play();
onClick?.(event);
},
[play, onClick],
);
const handlePointerDown = useCallback(
(event: PointerEvent<HTMLButtonElement>) => {
play();
if (ripple && !reduce) {
const rect = event.currentTarget.getBoundingClientRect();
const size = Math.max(rect.width, rect.height) * 2;
const id = nextId.current++;
setRipples((prev) => [
...prev,
{
id,
x: event.clientX - rect.left,
y: event.clientY - rect.top,
size,
},
]);
}
onPointerDown?.(event);
},
[ripple, reduce, onPointerDown, play],
);
return (
// Hover changes colour only: a hover scale blurs the label, and buttons
// are hovered far too often for movement to earn its place.
<motion.button
ref={ref}
type="button"
whileTap={reduce ? undefined : { scale: pressScale }}
transition={SPRING_PRESS}
onPointerDown={handlePointerDown}
onClick={handleClick}
className={cn(
"inline-flex items-center justify-center font-medium select-none",
"transition-colors",
"disabled:pointer-events-none disabled:opacity-50",
ripple && "relative overflow-hidden",
VARIANT_CLASS[variant],
SIZE_CLASS[size],
className,
)}
{...rest}
>
{ripple && !reduce ? (
<span className="pointer-events-none absolute inset-0 overflow-hidden rounded-[inherit]">
<AnimatePresence>
{ripples.map((r) => (
<motion.span
key={r.id}
className="absolute rounded-full bg-current"
style={{
left: r.x,
top: r.y,
width: r.size,
height: r.size,
x: "-50%",
y: "-50%",
}}
initial={{ scale: 0.05, opacity: 0.3 }}
animate={{ scale: 1, opacity: 0 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.8, ease: EASE_OUT }}
onAnimationComplete={() =>
setRipples((prev) => prev.filter((x) => x.id !== r.id))
}
/>
))}
</AnimatePresence>
</span>
) : null}
{children}
</motion.button>
);
},
);
export const ButtonLink = forwardRef<HTMLAnchorElement, ButtonLinkProps>(
function ButtonLink(
{
variant = "primary",
size = "md",
pressScale = 0.97,
className,
children,
...rest
},
ref,
) {
const reduce = useReducedMotion();
return (
<motion.a
ref={ref}
whileTap={reduce ? undefined : { scale: pressScale }}
transition={SPRING_PRESS}
className={cn(
"inline-flex items-center justify-center font-medium select-none",
"transition-colors",
VARIANT_CLASS[variant],
SIZE_CLASS[size],
className,
)}
{...rest}
>
{children}
</motion.a>
);
},
);
"use client";
import { forwardRef } from "react";
import { Magnetic } from "../magnetic";
import { Button, type ButtonProps } from "./base";
export interface MagneticButtonProps extends ButtonProps {
/** Magnetic pull strength. Default 0.25. */
strength?: number;
/** Class applied to the magnetic wrapper. */
magneticClassName?: string;
}
export const MagneticButton = forwardRef<HTMLButtonElement, MagneticButtonProps>(function MagneticButton(
{ strength = 0.25, magneticClassName, children, ...rest },
ref,
) {
return (
<Magnetic strength={strength} className={magneticClassName}>
<Button ref={ref} {...rest}>
{children}
</Button>
</Magnetic>
);
});
"use client";
import { motion, useReducedMotion } from "motion/react";
import { forwardRef, useState } from "react";
import { EASE_IN_OUT, EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
import { Button, type ButtonProps } from "./base";
export interface MetallicButtonProps extends Omit<
ButtonProps,
"ripple" | "variant"
> {
/** Stops the traveling reflection while preserving the chrome rim. */
paused?: boolean;
}
// The rim and highlight drift separately so the material stays quiet and reflective.
const SILVER_DRIFT = {
duration: 8,
ease: EASE_IN_OUT,
repeat: Infinity,
};
// One quick sweep on hover. Leaving resets it instantly: both ends sit outside
// the button, so the jump is invisible and no reverse sweep plays.
const CHROME_SHIMMER = {
duration: 0.9,
ease: EASE_OUT,
};
const CHROME_RESET = { duration: 0 };
export const MetallicButton = forwardRef<
HTMLButtonElement,
MetallicButtonProps
>(function MetallicButton(
{
size = "md",
paused = false,
className,
children,
onHoverStart,
onHoverEnd,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const still = paused || Boolean(reduce);
const [hovered, setHovered] = useState(false);
return (
<Button
ref={ref}
variant="ghost"
size={size}
onHoverStart={(event, info) => {
setHovered(true);
onHoverStart?.(event, info);
}}
onHoverEnd={(event, info) => {
setHovered(false);
onHoverEnd?.(event, info);
}}
className={cn(
"group relative isolate overflow-hidden border-0 bg-transparent text-foreground",
"hover:bg-transparent hover:text-foreground",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
"shadow-[0_8px_22px_rgba(0,0,0,0.16)]",
size === "icon" && "rounded-full",
className,
)}
{...rest}
>
<motion.span
aria-hidden="true"
className="pointer-events-none absolute inset-y-0 left-[-18%] z-0 w-[136%] rounded-[inherit] bg-[linear-gradient(105deg,#111_0%,#737373_14%,#fafafa_26%,#525252_38%,#0a0a0a_50%,#a3a3a3_64%,#fff_75%,#404040_87%,#111_100%)]"
animate={still ? undefined : { x: ["0%", "13%", "0%"] }}
transition={still ? undefined : SILVER_DRIFT}
/>
<motion.span
aria-hidden="true"
className="pointer-events-none absolute inset-y-0 left-[-58%] z-[1] w-[52%] -skew-x-12 bg-[linear-gradient(90deg,transparent,rgba(255,255,255,0.5)_48%,transparent)] opacity-50 blur-[3px] mix-blend-screen"
animate={still ? undefined : { x: hovered ? "310%" : "0%" }}
transition={still ? undefined : hovered ? CHROME_SHIMMER : CHROME_RESET}
/>
<span
aria-hidden="true"
className="pointer-events-none absolute inset-[2px] z-[2] rounded-[inherit] bg-background transition-colors group-hover:bg-muted/40"
/>
<span
aria-hidden="true"
className="pointer-events-none absolute inset-[2px] z-[3] rounded-[inherit] shadow-[inset_0_1px_0_rgba(255,255,255,0.28),inset_0_-1px_0_rgba(0,0,0,0.16)]"
/>
<span className="relative z-10 inline-flex items-center justify-center gap-2">
{children}
</span>
</Button>
);
});
"use client";
import { Check, Loader2, X } from "lucide-react";
import {
AnimatePresence,
motion,
useReducedMotion,
type Variants,
} from "motion/react";
import {
forwardRef,
type ReactNode,
useLayoutEffect,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_SWAP } from "@/lib/ease";
import { useMessages } from "@/lib/i18n";
import { Button, type ButtonProps } from "./base";
export type ButtonState = "idle" | "loading" | "success" | "error";
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const statefulButtonMessages = {
loading: "Loading",
success: "Done",
error: "Try again",
};
export type StatefulButtonMessages = typeof statefulButtonMessages;
export interface StatefulButtonProps extends Omit<ButtonProps, "children"> {
/** Which state to show. Loading also disables the button. Default: "idle" */
state?: ButtonState;
children: ReactNode;
/** Text shown while loading. Default: "Loading" */
loadingText?: ReactNode;
/** Text shown on success. Default: "Done" */
successText?: ReactNode;
/** Text shown on error. Default: "Try again" */
errorText?: ReactNode;
/** Trailing icon shown only while idle. */
icon?: ReactNode;
/** Override any built-in string. */
labels?: Partial<StatefulButtonMessages>;
}
const CASCADE_STAGGER = 0.025;
const ROLL_BLUR = "blur(6px)";
const CASCADE_LETTER_VARIANTS: Variants = {
initial: { opacity: 0, y: "105%", filter: ROLL_BLUR },
animate: (delay: number = 0) => ({
opacity: 1,
y: "0%",
filter: "blur(0px)",
transition: { ...SPRING_SWAP, delay },
}),
exit: (delay: number = 0) => ({
opacity: 0,
y: "-105%",
filter: ROLL_BLUR,
transition: { duration: 0.16, ease: EASE_OUT, delay: delay * 0.5 },
}),
};
const ICON_VARIANTS: Variants = {
// Width collapses too, so the icon adds/removes its own space smoothly
// instead of popping the row width in a single frame.
initial: { opacity: 0, width: 0, scale: 0.7, filter: ROLL_BLUR },
animate: {
opacity: 1,
width: "1.5rem",
scale: 1,
filter: "blur(0px)",
transition: SPRING_SWAP,
},
exit: {
opacity: 0,
width: 0,
scale: 0.7,
filter: ROLL_BLUR,
transition: { duration: 0.16, ease: EASE_OUT },
},
};
function IconSlot({ keyId, children }: { keyId: string; children: ReactNode }) {
const reduce = useReducedMotion();
return (
<motion.span
key={keyId}
variants={ICON_VARIANTS}
initial={reduce ? { opacity: 0 } : "initial"}
animate={reduce ? { opacity: 1 } : "animate"}
exit={reduce ? { opacity: 0 } : "exit"}
transition={reduce ? { duration: 0.15 } : undefined}
className="inline-grid shrink-0 place-items-center overflow-hidden"
>
{children}
</motion.span>
);
}
function TextSlot({
value,
children,
}: {
value: string;
children: ReactNode;
}) {
const reduce = useReducedMotion();
const measureRef = useRef<HTMLSpanElement>(null);
const [width, setWidth] = useState<number>();
const label = typeof children === "string" ? children : null;
const cascade = label !== null && !reduce;
// Measure strings with the same per-letter layout as the cascade. Measuring
// the whole string preserves kerning, which can make it narrower than the
// inline-block letters and clip the final glyph during the width animation.
useLayoutEffect(() => {
const nextWidth = measureRef.current?.offsetWidth;
if (!nextWidth) return;
setWidth((current) => (current === nextWidth ? current : nextWidth));
});
return (
<motion.span
initial={false}
animate={{ width }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="relative inline-block overflow-hidden whitespace-nowrap align-bottom"
>
<span
ref={measureRef}
aria-hidden
className="invisible inline-block whitespace-nowrap"
>
{cascade
? label.split("").map((char, index) => (
<span
// biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.
key={index}
className="inline-block whitespace-pre"
>
{char}
</span>
))
: children}
</span>
{cascade ? (
<>
<span className="sr-only">{label}</span>
<AnimatePresence initial={false}>
<motion.span
key={`cascade-${value}`}
aria-hidden
initial="initial"
animate="animate"
exit="exit"
className="absolute left-0 top-0 inline-block whitespace-pre"
>
{label.split("").map((char, index) => (
<motion.span
// biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.
key={index}
custom={index * CASCADE_STAGGER}
variants={CASCADE_LETTER_VARIANTS}
// Own states: a label that swaps away and straight back
// re-enters mid-exit, and only owned targets are restored.
initial="initial"
animate="animate"
exit="exit"
className="inline-block whitespace-pre will-change-[opacity,filter,transform]"
>
{char}
</motion.span>
))}
</motion.span>
</AnimatePresence>
</>
) : (
<AnimatePresence initial={false}>
<motion.span
key={`text-${value}`}
initial={reduce ? { opacity: 0 } : { opacity: 0, y: 14, filter: ROLL_BLUR }}
animate={reduce ? { opacity: 1 } : { opacity: 1, y: 0, filter: "blur(0px)" }}
exit={reduce ? { opacity: 0 } : { opacity: 0, y: -14, filter: ROLL_BLUR }}
transition={reduce ? { duration: 0.15 } : SPRING_SWAP}
className="absolute left-0 top-0 inline-block will-change-[opacity,filter,transform]"
>
{children}
</motion.span>
</AnimatePresence>
)}
</motion.span>
);
}
export const StatefulButton = forwardRef<HTMLButtonElement, StatefulButtonProps>(function StatefulButton(
{
state = "idle",
children,
loadingText,
successText,
errorText,
icon,
labels,
disabled,
...rest
},
ref,
) {
const t = useMessages("statefulButton", statefulButtonMessages, labels);
const isBusy = state === "loading";
const stateText =
state === "loading"
? (loadingText ?? t("loading"))
: state === "success"
? (successText ?? t("success"))
: state === "error"
? (errorText ?? t("error"))
: children;
const textKey =
typeof stateText === "string" ? `${state}-${stateText}` : state;
return (
<Button ref={ref} disabled={disabled || isBusy} aria-busy={isBusy} {...rest}>
<span
aria-live="polite"
className="relative inline-flex items-center justify-center overflow-hidden"
>
<AnimatePresence initial={false}>
{state === "loading" ? (
<IconSlot keyId="loading-icon">
<Loader2 className="h-4 w-4 animate-spin" />
</IconSlot>
) : null}
{state === "success" ? (
<IconSlot keyId="success-icon">
<Check className="h-4 w-4" />
</IconSlot>
) : null}
{state === "error" ? (
<IconSlot keyId="error-icon">
<X className="h-4 w-4" />
</IconSlot>
) : null}
</AnimatePresence>
<TextSlot value={textKey}>{stateText}</TextSlot>
<AnimatePresence initial={false}>
{state === "idle" && icon ? (
<IconSlot keyId="idle-icon">{icon}</IconSlot>
) : null}
</AnimatePresence>
</span>
</Button>
);
});
"use client";
import { motion, useMotionValue, useReducedMotion, useSpring } from "motion/react";
import { useRef, type ReactNode } from "react";
import { SPRING_MOUSE } from "@/lib/ease";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
import { cn } from "@/lib/utils";
export interface MagneticProps {
children: ReactNode;
strength?: number;
className?: string;
}
export function Magnetic({ children, strength = 0.35, className }: MagneticProps) {
const ref = useRef<HTMLDivElement>(null);
const reduce = useReducedMotion();
const canHover = useHoverCapable();
// Decorative cursor-follow: skip on touch (phantom hover) and reduced motion.
const enabled = !reduce && canHover;
const x = useMotionValue(0);
const y = useMotionValue(0);
const sx = useSpring(x, SPRING_MOUSE);
const sy = useSpring(y, SPRING_MOUSE);
const onMove = (e: React.MouseEvent<HTMLDivElement>) => {
const el = ref.current;
if (!el || !enabled) return;
const rect = el.getBoundingClientRect();
x.set((e.clientX - rect.left - rect.width / 2) * strength);
y.set((e.clientY - rect.top - rect.height / 2) * strength);
};
const onLeave = () => {
x.set(0);
y.set(0);
};
return (
<motion.div
ref={ref}
onMouseMove={onMove}
onMouseLeave={onLeave}
style={{ x: sx, y: sy }}
className={cn("inline-block", className)}
>
{children}
</motion.div>
);
}
open?booleanControlled open state.
—defaultOpen?booleanUncontrolled initial open state.
falseonOpenChange?((open: boolean) => void)Called with the new open state when the panel opens or closes.
—trigger?"click" | "hover"How the popover is summoned. Default "click".
clickside?"top" | "bottom"Which side of the trigger the panel oozes out of. Default "bottom".
bottomalign?"center" | "end" | "start"Alignment along the trigger's edge. Default "center".
centersideOffset?numberGap between trigger and panel, in px — the length of the gooey neck. Default 14.
14panelRadius?numberCorner radius of the open panel, in px. Default 16.
16gooStrength?numberBlur radius feeding the goo filter — higher melts more. Default 8.
8className?stringClasses merged onto the wrapper around the trigger.
—childrenReactElement<unknown, string | JSXElementConstructor<any>>A single focusable element (e.g. a Button) that opens the popover.
—Morphing Modal
Family-app-style modal. A single panel that morphs its height as you navigate between inner views, with blur cross-fade on content.
Drawer
Side panel that slides in from the left or right with a spring, backdrop blur, body scroll lock and esc-to-close.
Tooltip
Composable hover, focus and tap tooltip with a subtle scale and fade, collision-aware side and alignment, an optional arrow, a pointer corridor onto hoverable content, one label at a time, keyboard-only focus reveal and optional cursor tracking.
Updated