Morph Select
A dropdown where the trigger grows into the list as one surface.
Preview
"use client";
import { useState } from "react";
import {
MorphSelect,
MorphSelectContent,
MorphSelectItem,
MorphSelectTrigger,
MorphSelectValue,
} from "@/components/motion/select-morph";
export function SelectMorphPreview() {
const [value, setValue] = useState("next");
return (
<div className="w-56">
<MorphSelect sound value={value} onValueChange={setValue}>
<MorphSelectTrigger>
<MorphSelectValue placeholder="Pick a framework" />
</MorphSelectTrigger>
<MorphSelectContent>
<MorphSelectItem value="next">Next.js</MorphSelectItem>
<MorphSelectItem value="remix">Remix</MorphSelectItem>
<MorphSelectItem value="astro">Astro</MorphSelectItem>
<MorphSelectItem value="vite">Vite</MorphSelectItem>
</MorphSelectContent>
</MorphSelect>
</div>
);
}
"use client";
// beui.dev/components/motion/select/morph
import { Check, ChevronDown } from "lucide-react";
import {
AnimatePresence,
motion,
useReducedMotion,
type Variants,
} from "motion/react";
import {
createContext,
type ReactNode,
type RefObject,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { MENU_ITEM_CLASS, MenuItemHighlight } from "@/components/motion/menu/menu-item-highlight";
import { SPRING_MORPH } from "@/lib/ease";
import { type DismissReason, useDismiss } from "@/lib/hooks/use-dismiss";
import { type ListboxRow, useListbox } from "@/lib/hooks/use-listbox";
import { useSound } from "@/lib/sound";
import { closeSound } from "@/lib/sounds/close";
import { openSound } from "@/lib/sounds/open";
import { selectSound } from "@/lib/sounds/select";
import { PresenceGate } from "@/lib/presence-gate";
import { cn } from "@/lib/utils";
// Shared-layout morph: trigger box grows into the panel and back, one surface.
const MORPH = SPRING_MORPH;
// The fold back into the trigger: shorter than the open and without bounce,
// so the panel settles as it leaves instead of wobbling out. Local because it
// only exists as this morph's close.
const MORPH_CLOSE = { type: "spring", duration: 0.35, bounce: 0 } as const;
// Opened or closed from the keyboard: no motion at all.
const INSTANT = { duration: 0 } as const;
// Trigger and panel header share this row so the morph stays seamless.
const ROW = "flex h-10 w-full items-center justify-between gap-2 px-4 text-sm";
// The closed trigger is a pill (half its h-10 height). The open panel is
// rounded-2xl, the radius every floating list in the library uses.
const TRIGGER_RADIUS = 20;
const PANEL_RADIUS = 16;
const LIST: Variants = {
hidden: {},
show: { transition: { staggerChildren: 0.035, delayChildren: 0.08 } },
};
const ITEM: Variants = {
hidden: { opacity: 0, y: -6, filter: "blur(3px)" },
show: { opacity: 1, y: 0, filter: "blur(0px)" },
};
interface MorphContextValue {
value: string | undefined;
open: boolean;
/** `instant` skips the morph: the keyboard asked for it. */
setOpen: (open: boolean, quiet?: boolean, instant?: boolean) => void;
select: (value: string, instant?: boolean) => void;
/** Whether the latest open or close skips its animation. */
instant: boolean;
register: (value: string, label: string, disabled: boolean) => void;
unregister: (value: string) => void;
labelFor: (value: string | undefined) => string | undefined;
rows: ListboxRow[];
/** Closes the panel; focus inside it returns to the trigger. */
close: (quiet?: boolean, instant?: boolean) => void;
triggerRef: RefObject<HTMLButtonElement | null>;
placeholder: string;
setPlaceholder: (p: string) => void;
reduce: boolean;
layoutId: string;
triggerId: string;
listId: string;
headerId: string;
disabled: boolean;
}
const MorphContext = createContext<MorphContextValue | null>(null);
// The option keyboard focus is on, resolved during render by the content.
// The active option (resolved during render by the content), whether its
// highlight glides (after the pointer) or jumps (after a key), and how a
// pointer resting on an option makes it the active one.
interface ActiveOption {
activeId: string | undefined;
glide: boolean;
setActive: (id: string) => void;
}
const ActiveOptionContext = createContext<ActiveOption>({
activeId: undefined,
glide: true,
setActive: () => {},
});
// True inside the hidden copy that only keeps labels registered while closed.
const RegistrarContext = createContext(false);
function useMorphContext(component: string) {
const ctx = useContext(MorphContext);
if (!ctx) throw new Error(`${component} must be used within <MorphSelect>`);
return ctx;
}
export interface MorphSelectProps {
/** The selected value, for controlled use. */
value?: string;
/** The initial value when uncontrolled. */
defaultValue?: string;
/** Called with the option's value when the user picks one. */
onValueChange?: (value: string) => void;
/** Disable the trigger so the panel cannot open. Default: false */
disabled?: boolean;
/** Play open and close swishes and a select on a pick. Off by default; a `SoundProvider` can mute it app-wide. */
sound?: boolean;
/** Classes merged onto the root element. */
className?: string;
children: ReactNode;
}
/**
* Select whose trigger morphs into the panel via a shared layoutId — instead of
* a separate dropdown opening, the trigger itself grows into the menu and
* shrinks back, never detaching. Composable like `Select` (the unfold variant).
*/
export function MorphSelect({
value,
defaultValue,
onValueChange,
disabled = false,
sound = false,
className,
children,
}: MorphSelectProps) {
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const rootRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
// Set when the panel closes holding focus: the trigger is unmounted while
// open, so focus can only go back once it has mounted again.
const restoreFocus = useRef(false);
const [open, setOpenState] = useState(false);
const [instant, setInstant] = useState(false);
const [internal, setInternal] = useState(defaultValue);
const playOpen = useSound(openSound, { enabled: sound });
const playClose = useSound(closeSound, { enabled: sound });
const playSelect = useSound(selectSound, { enabled: sound });
// `quiet` skips the close sweep when a pick already made its own sound.
const setOpen = useCallback(
(next: boolean, quiet = false, now = false) => {
if (next !== open) {
if (!quiet) {
if (next) playOpen();
else playClose();
}
setInstant(now);
}
setOpenState(next);
},
[open, playOpen, playClose],
);
// ref-counted: items render twice (hidden registrar + open panel), so a
// label is only dropped once every copy with that value has unmounted.
const [labels, setLabels] = useState<
Map<string, { label: string; disabled: boolean; count: number }>
>(new Map());
const [placeholder, setPlaceholder] = useState("Select");
const controlled = value !== undefined;
const current = controlled ? value : internal;
const close = useCallback(
(quiet = false, now = false) => {
if (rootRef.current?.contains(document.activeElement))
restoreFocus.current = true;
setOpen(false, quiet, now);
},
[setOpen],
);
useEffect(() => {
if (open || !restoreFocus.current) return;
restoreFocus.current = false;
triggerRef.current?.focus();
}, [open]);
const select = useCallback(
(next: string, now = false) => {
playSelect();
if (!controlled) setInternal(next);
onValueChange?.(next);
close(true, now);
},
[controlled, onValueChange, close, playSelect],
);
const register = useCallback((v: string, label: string, disabled: boolean) => {
setLabels((m) => {
const next = new Map(m);
next.set(v, { label, disabled, count: (m.get(v)?.count ?? 0) + 1 });
return next;
});
}, []);
const unregister = useCallback((v: string) => {
setLabels((m) => {
const entry = m.get(v);
if (!entry) return m;
const next = new Map(m);
if (entry.count <= 1) next.delete(v);
else next.set(v, { ...entry, count: entry.count - 1 });
return next;
});
}, []);
// Escape closes at once; an outside press folds the panel back.
const dismiss = useCallback(
(reason: DismissReason) => (reason === "escape" ? close(false, true) : setOpen(false)),
[close, setOpen],
);
useDismiss(open, dismiss, rootRef);
const rows = useMemo(
() =>
Array.from(labels, ([id, entry]) => ({
id,
label: entry.label,
disabled: entry.disabled,
})),
[labels],
);
const ctx = useMemo<MorphContextValue>(
() => ({
value: current,
open,
setOpen,
select,
instant,
register,
unregister,
labelFor: (v) => (v === undefined ? undefined : labels.get(v)?.label),
rows,
close,
triggerRef,
placeholder,
setPlaceholder,
reduce,
layoutId: `${baseId}-surface`,
triggerId: `${baseId}-trigger`,
listId: `${baseId}-list`,
headerId: `${baseId}-header`,
disabled,
}),
[
current,
open,
setOpen,
select,
instant,
register,
unregister,
labels,
rows,
close,
placeholder,
reduce,
baseId,
disabled,
],
);
return (
<MorphContext.Provider value={ctx}>
<div ref={rootRef} className={cn("relative", className)}>
{children}
</div>
</MorphContext.Provider>
);
}
export interface MorphSelectValueProps {
/** Text shown in the trigger and panel header before anything is picked. Default: "Select" */
placeholder?: string;
/** Classes merged onto the value text. */
className?: string;
}
export function MorphSelectValue({
placeholder,
className,
}: MorphSelectValueProps) {
const ctx = useMorphContext("MorphSelectValue");
// surface the placeholder so the morph header (rendered by content) matches
useEffect(() => {
if (placeholder) ctx.setPlaceholder(placeholder);
}, [placeholder, ctx.setPlaceholder]);
const label = ctx.labelFor(ctx.value);
return (
<span
className={cn(label ? "text-foreground" : "text-muted-foreground", className)}
>
{label ?? placeholder ?? "Select"}
</span>
);
}
export interface MorphSelectTriggerProps {
/** Classes merged onto the trigger button. */
className?: string;
children: ReactNode;
}
export function MorphSelectTrigger({
className,
children,
}: MorphSelectTriggerProps) {
const ctx = useMorphContext("MorphSelectTrigger");
return (
<>
{/* invisible sizer reserves the closed height (the morph surface is
absolute, so this keeps surrounding layout from shifting) */}
<div
aria-hidden
inert
className={cn(ROW, "invisible rounded-full border border-border")}
>
{children}
<ChevronDown className="h-4 w-4" />
</div>
<AnimatePresence initial={false} mode="popLayout">
{!ctx.open ? (
<motion.button
key="trigger"
ref={ctx.triggerRef}
layoutId={ctx.layoutId}
type="button"
id={ctx.triggerId}
disabled={ctx.disabled}
aria-haspopup="listbox"
aria-expanded={ctx.open}
aria-controls={ctx.listId}
// `detail` is 0 for a click the keyboard made (Enter, Space): no morph.
onClick={(event) => ctx.setOpen(true, false, event.detail === 0)}
onKeyDown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
ctx.setOpen(true, false, true);
}
}}
// The trigger is what the panel morphs back into, so its
// transition is the close.
transition={ctx.reduce || ctx.instant ? INSTANT : MORPH_CLOSE}
style={{ borderRadius: TRIGGER_RADIUS }}
className={cn(
ROW,
"absolute inset-x-0 top-0 z-10 border border-border bg-background text-foreground outline-none transition-colors",
"hover:border-(--color-border-strong) focus-visible:ring-2 focus-visible:ring-foreground/20",
"disabled:pointer-events-none disabled:opacity-50",
className,
)}
>
<motion.span layout="position" className="min-w-0 truncate">
{children}
</motion.span>
<motion.span layout="position" className="text-muted-foreground">
<ChevronDown className="h-4 w-4" />
</motion.span>
</motion.button>
) : null}
</AnimatePresence>
</>
);
}
export interface MorphSelectContentProps {
/** Classes merged onto the open panel. */
className?: string;
children: ReactNode;
}
export function MorphSelectContent({
className,
children,
}: MorphSelectContentProps) {
const ctx = useMorphContext("MorphSelectContent");
const label = ctx.labelFor(ctx.value);
const listRef = useRef<HTMLUListElement>(null);
const { activeId, onKeyDown, moveTo } = useListbox({
open: ctx.open,
rows: ctx.rows,
selected: ctx.value,
list: listRef,
});
const [glide, setGlide] = useState(true);
const active = useMemo<ActiveOption>(
() => ({ activeId, glide, setActive: moveTo }),
[activeId, glide, moveTo],
);
return (
<>
{/* always-mounted, hidden — keeps item label registrations alive while
closed so the trigger shows the selected value before first open */}
<RegistrarContext.Provider value={true}>
<div hidden>{children}</div>
</RegistrarContext.Provider>
<AnimatePresence initial={false} mode="popLayout">
{ctx.open ? (
<motion.div
key="panel"
layoutId={ctx.layoutId}
transition={ctx.reduce || ctx.instant ? INSTANT : MORPH}
style={{ borderRadius: PANEL_RADIUS }}
className={cn(
// The same soft shadow as the menus, so floating lists read as one family.
"pointer-events-none absolute inset-x-0 top-0 z-30 overflow-hidden border border-border bg-background shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)]",
className,
)}
>
{/* The panel sits over the returning trigger for the whole morph
back, so its contents stop taking clicks and focus as soon as
it starts leaving. The surface itself never takes pointer
events, so the gate goes on this wrapper. */}
<PresenceGate>
{({ gate }) => (
<div {...gate}>
{/* header mirrors the trigger (continuous morph) and
collapses the panel back into the trigger when clicked */}
<motion.button
type="button"
id={ctx.headerId}
layout="position"
aria-haspopup="listbox"
aria-expanded
aria-controls={ctx.listId}
onClick={(event) => ctx.close(false, event.detail === 0)}
className={cn(ROW, "outline-none")}
>
<span
className={cn(
"min-w-0 truncate",
label ? "text-foreground" : "text-muted-foreground",
)}
>
{label ?? ctx.placeholder}
</span>
<motion.span
aria-hidden
animate={{ rotate: 180 }}
transition={ctx.reduce || ctx.instant ? INSTANT : MORPH}
className="text-muted-foreground"
>
<ChevronDown className="h-4 w-4" />
</motion.span>
</motion.button>
<div className="h-px bg-border" />
<ActiveOptionContext.Provider value={active}>
<motion.ul
ref={listRef}
id={ctx.listId}
role="listbox"
aria-labelledby={ctx.headerId}
initial="hidden"
animate="show"
// The panel mounts fresh each open, so a keyboard open
// can simply leave the stagger out.
variants={ctx.reduce || ctx.instant ? undefined : LIST}
onKeyDown={(event) => {
// Set before the key moves the active option, so its highlight jumps.
setGlide(false);
if (event.key === "Tab") {
event.preventDefault();
ctx.close(false, true);
} else onKeyDown(event);
}}
onPointerMove={(event) => {
if (event.pointerType !== "touch") setGlide(true);
}}
className="p-2"
>
{children}
</motion.ul>
</ActiveOptionContext.Provider>
</div>
)}
</PresenceGate>
</motion.div>
) : null}
</AnimatePresence>
</>
);
}
export interface MorphSelectItemProps {
/** Value reported when this option is picked. */
value: string;
/** Make the option unselectable and skip it in keyboard navigation. Default: false */
disabled?: boolean;
/** Classes merged onto the option button. */
className?: string;
children: ReactNode;
}
export function MorphSelectItem({
value,
disabled = false,
className,
children,
}: MorphSelectItemProps) {
const ctx = useMorphContext("MorphSelectItem");
const { activeId, glide, setActive } = useContext(ActiveOptionContext);
const registrarOnly = useContext(RegistrarContext);
const selected = ctx.value === value;
const active = activeId === value;
const label = typeof children === "string" ? children : value;
useLayoutEffect(() => {
ctx.register(value, label, disabled);
return () => ctx.unregister(value);
}, [ctx.register, ctx.unregister, value, label, disabled]);
// The hidden copy only registers; no stray options outside the listbox.
if (registrarOnly) return null;
return (
<motion.li role="none" variants={ctx.reduce || ctx.instant ? undefined : ITEM}>
<button
type="button"
role="option"
aria-selected={selected}
disabled={disabled}
// One tab stop: the active option, which focus follows while open.
tabIndex={active ? 0 : -1}
data-listbox-id={value}
// A resting pointer makes this the active option, so the highlight
// follows the mouse the same way it follows the arrow keys.
onPointerMove={(event) => {
if (event.pointerType !== "touch" && !disabled && !active) setActive(value);
}}
// Enter or Space on the option (`detail` 0) closes without the morph.
onClick={(event) => ctx.select(value, event.detail === 0)}
className={cn(
MENU_ITEM_CLASS,
"justify-between gap-2 text-foreground",
"disabled:pointer-events-none disabled:opacity-50",
className,
)}
>
{/* One highlight for the whole list: it glides after the pointer and
jumps after a key. The selected option is marked by its check. */}
{active && !disabled ? (
<MenuItemHighlight
layoutId={`${ctx.listId}-highlight`}
reduce={ctx.reduce}
instant={!glide}
/>
) : null}
<span className="flex min-w-0 flex-1 items-center gap-2">{children}</span>
{selected ? <Check aria-hidden="true" className="h-3.5 w-3.5 shrink-0" /> : null}
</button>
</motion.li>
);
}
Add it with the shadcn CLI, or copy the source manually.
npx shadcn add https://beui.dev/r/theme.json. Theme setupInstall dependencies
npm i clsx lucide-react motion tailwind-mergeAdd util files
// Shared motion tokens. Easing curves mirror the CSS custom properties in
// globals.css; springs are the canonical physics used across components.
// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */
export const EASE_IN = [0.55, 0, 1, 0.45] as const;
export const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;
export const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;
/** CSS string form of EASE_OUT for inline style transitions. */
export const EASE_OUT_CSS = "cubic-bezier(0.16, 1, 0.3, 1)";
/** Press feedback on buttons and other tappable surfaces. */
export const SPRING_PRESS = {
type: "spring",
stiffness: 500,
damping: 30,
mass: 0.6,
} as const;
/** Content swaps — label/icon slots trading places inside a control. */
export const SPRING_SWAP = {
type: "spring",
stiffness: 460,
damping: 30,
mass: 0.55,
} as const;
/** Overlay panel entrances — modals and sheets summoned by pointer. */
export const SPRING_PANEL = {
type: "spring",
stiffness: 420,
damping: 40,
mass: 0.5,
} as const;
/** Shared-layout glides — pills, indicators and panels morphing between positions. */
export const SPRING_LAYOUT = {
type: "spring",
stiffness: 360,
damping: 32,
mass: 0.6,
} as const;
/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */
export const SPRING_MOUSE = {
stiffness: 200,
damping: 15,
mass: 0.3,
} as const;
/** Dragged handles and fills (sliders) — critically damped `useSpring` config,
* so the value follows the pointer butterily and never rebounds off an end. */
export const SPRING_GLIDE = {
stiffness: 700,
damping: 50,
mass: 0.5,
} as const;
/** Shared-surface morphs: a trigger growing into its panel and back on one
* weighted spring, so opening and closing travel the same path. */
export const SPRING_MORPH = {
type: "spring",
duration: 0.5,
bounce: 0.22,
} as const;
"use client";
import { type RefObject, useEffect, useLayoutEffect, useRef } from "react";
import { inOtherLayer, type Layer, openLayer, ownsEscape } from "@/lib/layers";
/**
* What the dismissing gesture does to the control it landed on.
*
* `"pass-through"` is the platform norm (native popover light-dismiss): the
* tap closes the overlay *and* activates whatever was under it. Use
* `"consume"` where the open overlay sits over or beside controls that would
* be costly to trigger by accident — the dismissal then swallows the
* activation too, so the gesture only closes.
*/
export type DismissBehavior = "pass-through" | "consume";
/** What closed the overlay: Escape, a pointerdown outside it, or focus leaving it. */
export type DismissReason = "escape" | "pointer" | "focus";
export interface DismissOptions {
/** Default `"pass-through"`. */
behavior?: DismissBehavior;
/** Dismiss on Escape as well. Default true. */
escape?: boolean;
/** Dismiss when focus moves outside, as a combobox does on Tab. Default false. */
focusOutside?: boolean;
/**
* Dismiss on a pointerdown outside. Default true. Turn it off for an overlay
* whose own backdrop handles presses and only needs Escape and layering.
*/
outsidePress?: boolean;
/** Return true for an outside target that should *not* dismiss. */
ignore?: (target: Element) => boolean;
}
// preventDefault on pointerdown does not suppress the click that follows, so
// consuming a gesture means swallowing that click itself. The swallower
// deliberately outlives the effect that installed it — the dismissal it
// belongs to has already unmounted or re-rendered by the time the click lands.
// It releases on that click, or on the next gesture if the pointer is dragged
// away and no click ever arrives, so it can never eat a later one. A keydown
// releases it too: a gesture that ends with neither a click nor a cancel would
// otherwise leave it armed, and the click Enter synthesizes on some focused
// control is not the one this dismissal was owed.
function consumeActivation(source: Event) {
const swallow = (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
release();
};
const restart = (event: Event) => {
if (event !== source) release();
};
const release = () => {
window.removeEventListener("click", swallow, true);
window.removeEventListener("pointerdown", restart, true);
window.removeEventListener("pointercancel", restart, true);
window.removeEventListener("keydown", release, true);
};
window.addEventListener("click", swallow, true);
window.addEventListener("pointerdown", restart, true);
window.addEventListener("pointercancel", restart, true);
window.addEventListener("keydown", release, true);
}
/**
* Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`
* for `ref` when what counts as inside isn't one element, and say so with
* `ignore` instead.
*
* The pointerdown listener is capture-phase: a bubble-phase one is blinded by
* any handler in between that stops propagation, and an overlay cannot know
* what it is layered over.
*
* Each open dismissal is a layer in `lib/layers.ts`, so only the innermost
* open overlay answers Escape (a menu inside a drawer closes, the drawer
* stays), and a drawer's focus trap leaves focus in a menu it portaled out.
*/
export function useDismiss(
open: boolean,
onDismiss: (reason: DismissReason) => void,
ref: RefObject<HTMLElement | SVGElement | null> | null,
{
behavior = "pass-through",
escape: dismissOnEscape = true,
focusOutside = false,
outsidePress = true,
ignore,
}: DismissOptions = {},
) {
// Read through refs, so a callback rebuilt each render neither re-binds the
// listeners nor moves this layer to the top of the stack.
const dismissRef = useRef(onDismiss);
const ignoreRef = useRef(ignore);
useLayoutEffect(() => {
dismissRef.current = onDismiss;
ignoreRef.current = ignore;
});
useEffect(() => {
if (!open) return;
const inside = (target: Node) =>
Boolean(ref?.current?.contains(target)) ||
(target instanceof Element && Boolean(ignoreRef.current?.(target)));
const layer: Layer = { contains: inside, escape: dismissOnEscape };
const closeLayer = openLayer(layer);
const onKey = (event: KeyboardEvent) => {
if (!dismissOnEscape || event.key !== "Escape" || !ownsEscape(layer, event)) return;
event.preventDefault();
dismissRef.current("escape");
};
const onPointer = (event: PointerEvent) => {
const target = event.target as Element | null;
if (!target || inside(target)) return;
// Outside this overlay, but inside another open one: the gesture is
// that overlay's to answer, and swallowing its click from behind would
// cost the user the control they actually aimed at.
if (behavior === "consume" && !inOtherLayer(layer, target, { traps: false })) {
consumeActivation(event);
}
dismissRef.current("pointer");
};
const onFocus = (event: FocusEvent) => {
const target = event.target;
if (target instanceof Node && !inside(target)) dismissRef.current("focus");
};
window.addEventListener("keydown", onKey);
if (outsidePress) window.addEventListener("pointerdown", onPointer, true);
if (focusOutside) window.addEventListener("focusin", onFocus);
return () => {
closeLayer();
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer, true);
window.removeEventListener("focusin", onFocus);
};
}, [open, ref, behavior, dismissOnEscape, focusOutside, outsidePress]);
}
"use client";
import {
type KeyboardEvent,
type RefObject,
useEffect,
useMemo,
useRef,
} from "react";
import { useOnOpen } from "@/lib/hooks/use-on-open";
import { useRowCursor } from "@/lib/hooks/use-row-cursor";
export interface ListboxRow {
id: string;
label: string;
disabled?: boolean;
}
// How long typed characters keep building one typeahead query.
const TYPEAHEAD_MS = 500;
/**
* Keyboard model for a popup listbox whose options are focusable buttons.
*
* The active option is resolved during render through `useRowCursor`, so the
* roving `tabIndex` and the next key press always agree with what is on
* screen. Opening starts on the selected option, or the first enabled one.
* Arrow keys, Home and End move between enabled options, and printable
* characters jump to the next option whose label starts with what was typed.
* DOM focus follows the active option while the list is open; each option
* carries its id in `data-listbox-id` so the list can find it.
*/
export function useListbox({
open,
rows,
selected,
list,
}: {
open: boolean;
rows: readonly ListboxRow[];
selected: string | undefined;
list: RefObject<HTMLElement | null>;
}) {
const enabled = useMemo(() => rows.filter((row) => !row.disabled), [rows]);
const { activeIndex, moveTo, moveActive } = useRowCursor(enabled, "");
useOnOpen(open, () =>
moveTo(enabled.some((row) => row.id === selected) ? (selected ?? null) : null),
);
const activeId = enabled[activeIndex]?.id;
const typed = useRef({ text: "", at: 0 });
// A list rendered open does not take focus from the page on mount; focus
// follows only once it has been opened, or once focus is already inside.
const openedOnMount = useRef(open);
useEffect(() => {
if (!open) openedOnMount.current = false;
}, [open]);
useEffect(() => {
if (!open || activeId === undefined) return;
if (
openedOnMount.current &&
!list.current?.contains(document.activeElement)
)
return;
const option = Array.from(
list.current?.querySelectorAll<HTMLElement>("[data-listbox-id]") ?? [],
).find((element) => element.dataset.listboxId === activeId);
option?.focus({ preventScroll: false });
}, [open, activeId, list]);
const onKeyDown = (event: KeyboardEvent) => {
const { key } = event;
if (key === "ArrowDown" || key === "ArrowUp") {
event.preventDefault();
moveActive(key === "ArrowDown" ? 1 : -1);
} else if (key === "Home" || key === "End") {
event.preventDefault();
const row = key === "Home" ? enabled[0] : enabled[enabled.length - 1];
if (row) moveTo(row.id);
} else if (
key.length === 1 &&
key !== " " &&
!event.ctrlKey &&
!event.metaKey &&
!event.altKey
) {
const now = Date.now();
const char = key.toLowerCase();
const text =
now - typed.current.at < TYPEAHEAD_MS ? typed.current.text + char : char;
typed.current = { text, at: now };
// A repeated single letter cycles through the options that start with it.
const from = text.length === 1 ? activeIndex + 1 : activeIndex;
for (let step = 0; step < enabled.length; step++) {
const row = enabled[(from + step) % enabled.length];
if (row.label.toLowerCase().startsWith(text)) {
moveTo(row.id);
break;
}
}
}
};
// `moveTo` lets a pointer resting on an option make it the active one, so a
// highlight drawn from `activeId` follows the mouse as well as the keys.
return { activeId, onKeyDown, moveTo };
}
"use client";
import { useIsPresent } from "motion/react";
import type { ReactNode } from "react";
export interface PresenceGateRenderProps {
/**
* False from the render that starts the exit animation onward. An overlay
* kept in the tree by `AnimatePresence` is still the topmost thing on the
* page, so anything it decides from `open` alone stays true for the whole
* exit — this is the boolean that already knows the overlay is leaving.
*/
isPresent: boolean;
/**
* Spread onto every layer that takes pointer events while the overlay is
* open. Interaction releases in the same commit that starts the exit while
* the visual exit keeps playing: pointer events stop landing, and `inert`
* drops the subtree from focus order, from tab order and from the
* accessibility tree — an exiting dialog is not a dialog you can still type
* into. A layer that never takes pointer events (a wrapper that only centres
* the panel) takes `inert={!isPresent}` alone, so its own
* `pointer-events-none` is not overwritten.
*/
gate: {
inert: boolean;
style: { pointerEvents: "auto" | "none" };
};
}
export interface PresenceGateProps {
children: (props: PresenceGateRenderProps) => ReactNode;
}
/**
* Reads the presence of the subtree it renders and hands it down.
*
* `useIsPresent` only answers inside the `AnimatePresence` subtree, and the
* components that own an overlay render the `AnimatePresence` themselves, so
* the boolean has to be read one component further down: this is that
* component, and the render prop is how it reaches the layers.
*/
export function PresenceGate({ children }: PresenceGateProps) {
const isPresent = useIsPresent();
return children({
isPresent,
gate: {
inert: !isPresent,
style: { pointerEvents: isPresent ? "auto" : "none" },
},
});
}
"use client";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useRef,
} from "react";
import {
registerSoundSettings,
retainAudioContext,
type SoundSettingsEntry,
} from "@/lib/audio-context";
import type { PlayOptions, Sound } from "@/lib/sounds/engine";
export interface SoundSettings {
/** False mutes every beUI sound under the provider. */
enabled: boolean;
/** 0 to 1, scales every beUI sound. */
volume: number;
}
const SoundContext = createContext<SoundSettings & { depth: number }>({
enabled: true,
volume: 1,
depth: 0,
});
/**
* App-wide sound settings. `enabled={false}` mutes every beUI sound, from
* component `sound` props and `useSound` to the games, Wheel Picker and
* Bookshelf, and `volume` scales them all. Without a provider, sounds play at
* full volume. A nested provider overrides the one around it.
*/
export function SoundProvider({
enabled = true,
volume = 1,
children,
}: Partial<SoundSettings> & { children: ReactNode }) {
const depth = useContext(SoundContext).depth + 1;
const value = useMemo(() => ({ enabled, volume, depth }), [enabled, volume, depth]);
// Module-level as well (lib/audio-context.ts), so players outside React
// and `sound.play()` obey it too.
const entry = useRef<SoundSettingsEntry>({ depth, enabled, volume });
const registration = useRef<ReturnType<typeof registerSoundSettings> | null>(null);
useEffect(() => {
registration.current = registerSoundSettings(entry.current);
return () => {
registration.current?.release();
registration.current = null;
};
}, []);
useEffect(() => {
Object.assign(entry.current, { depth, enabled, volume });
registration.current?.update();
}, [depth, enabled, volume]);
return <SoundContext.Provider value={value}>{children}</SoundContext.Provider>;
}
export function useSoundSettings(): SoundSettings {
return useContext(SoundContext);
}
export interface UseSoundOptions {
/** False makes `play` do nothing, for a component's `sound` prop. */
enabled?: boolean;
/** 0 to 1 for this sound, on top of the provider volume. */
volume?: number;
}
/**
* A stable `play()` for one sound. It does nothing while disabled or muted,
* and keeps the shared audio context warm only while it can play.
*/
export function useSound(sound: Sound, { enabled = true, volume = 1 }: UseSoundOptions = {}) {
const settings = useSoundSettings();
const on = enabled && settings.enabled && settings.volume > 0 && volume > 0;
// Read by the stable callback, so a caller's effects don't re-run when
// the settings change.
const latest = useRef({ on, volume, sound });
useLayoutEffect(() => {
latest.current = { on, volume, sound };
});
useEffect(() => {
if (!on) return;
return retainAudioContext();
}, [on]);
return useCallback((options?: PlayOptions) => {
const current = latest.current;
if (!current.on) return;
current.sound.play({ ...options, volume: (options?.volume ?? 1) * current.volume });
}, []);
}
import { defineSound } from "./engine";
/** The open whoosh falling and a little quicker, settling with a soft low tap, for things closing. */
export const closeSound = defineSound({
name: "Close",
duration: 0.16,
room: 0.18,
build: (v) => {
v.noise({ freq: 2600, to: 700, q: 1.2, attack: 0.012, decay: 0.09, gain: 0.7 });
v.click({ freq: 1400, q: 1.2, at: 0.05, decay: 0.006, gain: 0.2 });
v.strike({ freq: 260, material: "wood", bend: 1.2, at: 0.05, decay: 0.045, gain: 0.3 });
},
});
import { defineSound } from "./engine";
/** A soft rising whoosh that lands with a light glass touch, for menus, popovers and dialogs opening. */
export const openSound = defineSound({
name: "Open",
duration: 0.2,
room: 0.2,
build: (v) => {
v.noise({ freq: 600, to: 2600, q: 1.2, attack: 0.035, decay: 0.11, gain: 0.75 });
v.noise({ freq: 4500, to: 6000, q: 1, attack: 0.03, decay: 0.07, gain: 0.05 });
v.strike({ freq: 1320, material: "glass", at: 0.05, decay: 0.07, gain: 0.12 });
},
});
import { defineSound } from "./engine";
/** A crisp detent, like a dial clicking into a notch, for tabs, segmented controls and menu choices. */
export const selectSound = defineSound({
name: "Select",
duration: 0.05,
room: 0.08,
build: (v) => {
v.click({ freq: 4500, q: 2.5, decay: 0.003, gain: 0.45 });
v.strike({ freq: 1700, material: "metal", decay: 0.028, gain: 0.3 });
v.strike({ freq: 520, material: "wood", bend: 1.15, decay: 0.012, gain: 0.25 });
},
});
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
/**
* Every open overlay on the page, innermost last: focus traps, modal scopes
* and dismissable menus all register here. Overlays have no shared z-order to
* consult, and a menu inside a drawer portals out of it, so this stack is how
* they agree on who answers Escape and where focus may go.
*/
export interface Layer {
/** Whether `target` belongs to this layer (its panel, portals, trigger). */
contains: (target: Node) => boolean;
/** True for focus traps and modal scopes, which pull stray focus back. */
traps?: boolean;
/** False for a layer that ignores Escape, so the key reaches the one below. */
escape?: boolean;
}
const stack: Layer[] = [];
// The innermost layer when each Escape began, read before any handler runs,
// so a layer that closes itself mid-event can't hand the key to the one below.
const escapeOwners = new WeakMap<Event, Layer | undefined>();
let listening = false;
function innermostEscapeLayer() {
for (let index = stack.length - 1; index >= 0; index--) {
if (stack[index].escape !== false) return stack[index];
}
return undefined;
}
function recordEscapeOwner(event: KeyboardEvent) {
if (event.key === "Escape") escapeOwners.set(event, innermostEscapeLayer());
}
/** Registers an open layer. Call the returned function when it closes. */
export function openLayer(layer: Layer) {
if (!listening) {
document.addEventListener("keydown", recordEscapeOwner, true);
listening = true;
}
stack.push(layer);
return () => {
const index = stack.indexOf(layer);
if (index !== -1) stack.splice(index, 1);
};
}
/** Whether this Escape is `layer`'s to answer: it was innermost when the key went down. */
export function ownsEscape(layer: Layer, event: KeyboardEvent) {
if (event.defaultPrevented) return false;
const owner = escapeOwners.has(event)
? escapeOwners.get(event)
: innermostEscapeLayer();
return owner === layer;
}
/** Whether `target` sits in a layer opened on top of `layer`. */
export function inLayerAbove(layer: Layer, target: Node) {
const index = stack.indexOf(layer);
return stack.slice(index + 1).some((above) => above.contains(target));
}
/** Whether a focus trap is open on top of `layer`; stray focus is that one's to pull back. */
export function trapAbove(layer: Layer) {
const index = stack.indexOf(layer);
return stack.slice(index + 1).some((above) => above.traps);
}
/**
* Whether `target` belongs to any open layer other than `layer`. Pass
* `traps: false` to count only dismissable overlays, not the traps under them.
*/
export function inOtherLayer(layer: Layer, target: Node, { traps = true } = {}) {
return stack.some(
(other) => other !== layer && (traps || !other.traps) && other.contains(target),
);
}
"use client";
import { useState } from "react";
/**
* Runs `start` during the render in which `open` becomes true.
*
* Opening a list starts a fresh session — an empty query, the highlight back at
* the top — and that is a resolution, not a side effect: a passive effect runs
* after the commit, so the new session would carry the last one's state for a
* window in which a key press can land.
*
* `start` may only set state belonging to the calling component. Anything that
* reaches outside it — a consumer's callback, a DOM write, moving focus — is a
* side effect, and React rejects a callback that sets another component's state
* during this one's render. Put those in an effect keyed to `open`.
*/
export function useOnOpen(open: boolean, start: () => void) {
const [wasOpen, setWasOpen] = useState(open);
if (open !== wasOpen) {
setWasOpen(open);
if (open) start();
}
}
"use client";
import { useCallback, useLayoutEffect, useRef, useState } from "react";
/**
* Where the keyboard or the pointer last moved to: the row's id, stamped with
* the query it was placed under.
*/
type RowCursor = { id: string; query: string };
/** The cursor's row, or -1 once the query has moved on or the row has left. */
function indexOfCursor(
rows: readonly { id: string }[],
query: string,
cursor: RowCursor | null,
) {
if (cursor === null || cursor.query !== query) return -1;
return rows.findIndex((row) => row.id === cursor.id);
}
/**
* The highlighted row of a list whose rows can change under it.
*
* Which row is highlighted is resolved during render, never in a passive
* effect: a passive effect runs after the commit, so a list that had just
* changed would carry an `aria-activedescendant` naming a row that has left it,
* and a key pressed in that window would commit the wrong row or nothing at
* all.
*
* The cursor holds the row's id, not its position. A position alone cannot tell
* a list that shrank from one that swapped its rows for a different set of the
* same length, and the second case is the one that silently hands Enter to a
* row the user never chose. A cursor whose row has left the list returns the
* highlight to the first row rather than to the nearest surviving one: the row
* the user aimed at is gone, and the first row is where a new query already
* puts the highlight.
*
* Pass the query the list is filtered by. The cursor is stamped with it and
* dropped when it changes, so a caller cannot forget to clear it — including a
* caller whose query arrives as a prop and so never runs its own handler. Rows
* that come back under a query that has moved on cannot revive it either.
* `moveTo(null)` is for deliberate resets, such as reopening the list.
*
* Both callbacks keep one identity for the life of the component, and read the
* rows and the query through a ref to do it. A caller will put them in an
* effect's dependencies — the exhaustive-deps rule makes it — and a `moveTo`
* rebuilt on every keystroke would re-run that effect on every keystroke.
*/
export function useRowCursor(rows: readonly { id: string }[], query: string) {
const [cursor, setCursor] = useState<RowCursor | null>(null);
// Written after commit, not during render: a render React discards or has not
// finished still runs the component body, and an event handler that read this
// in that window would stamp the cursor with a query the committed tree does
// not have.
const latest = useRef({ rows, query });
useLayoutEffect(() => {
latest.current = { rows, query };
});
const cursorRow = indexOfCursor(rows, query, cursor);
// Cleared rather than ignored: React re-runs this render with the cursor
// already gone, so rows that come back cannot revive a highlight the user has
// stopped aiming at.
if (cursor !== null && cursorRow < 0) setCursor(null);
const moveTo = useCallback(
(id: string | null) =>
setCursor(id === null ? null : { id, query: latest.current.query }),
[],
);
const moveActive = useCallback((direction: 1 | -1) => {
const { rows: live, query: liveQuery } = latest.current;
const last = live.length - 1;
if (last < 0) return;
// Steps from the row the cursor is really on, inside the update, so that
// two keys landing in one batch move two rows rather than one.
setCursor((current) => {
const at = Math.max(indexOfCursor(live, liveQuery, current), 0);
const next = Math.min(Math.max(at + direction, 0), last);
return { id: live[next].id, query: liveQuery };
});
}, []);
return { activeIndex: cursorRow < 0 ? 0 : cursorRow, moveTo, moveActive };
}
// One AudioContext for every synthesized sound on the page: the sounds
// library (lib/sounds/), the WheelPicker tick (lib/tick-sound.ts), the casino
// games (lib/game-sounds.ts) and Bookshelf (lib/book-sounds.ts). Browsers cap
// concurrent contexts, and a page can show a date made of several WheelPickers
// next to a game, so they all share this one. It is created on first use and
// closed once every player is disposed.
//
// Every player connects to `audioOutput()` rather than the context's
// destination, so the page-wide volume and mute from `SoundProvider`
// (lib/sound.tsx) reach all of them in one place.
type AudioContextCtor = typeof AudioContext;
let context: AudioContext | null = null;
let master: GainNode | null = null;
let users = 0;
/** Settings one mounted `SoundProvider` asks for. */
export interface SoundSettingsEntry {
/** Nesting depth: the deepest provider decides. */
depth: number;
enabled: boolean;
volume: number;
}
// Mounted providers in mount order. Module state, so `sound.play()` called
// outside React obeys them too. The deepest provider wins; among equals, the
// one mounted last. Effects run child first, so this can't be "whoever ran
// last".
const providers = new Set<SoundSettingsEntry>();
let allowed = true;
let volume = 1;
function applySettings() {
let chosen: SoundSettingsEntry | undefined;
for (const entry of providers) {
if (!chosen || entry.depth >= chosen.depth) chosen = entry;
}
allowed = chosen?.enabled ?? true;
volume = Math.min(1, Math.max(0, chosen?.volume ?? 1));
if (master) master.gain.value = volume;
}
/**
* Registers a provider's settings; call `update` after changing the entry and
* the returned release function when the provider unmounts.
*/
export function registerSoundSettings(entry: SoundSettingsEntry) {
providers.add(entry);
applySettings();
return {
update: applySettings,
release() {
providers.delete(entry);
applySettings();
},
};
}
/**
* Registers a sound player. Call the returned function when the player is
* disposed; the context closes after the last one.
*/
export function retainAudioContext() {
users++;
let released = false;
return () => {
if (released) return;
released = true;
users--;
if (users === 0 && context) {
void context.close();
context = null;
master = null;
}
};
}
/**
* The shared context, created on first call and resumed if suspended. Null
* during SSR, in browsers without Web Audio, and while sounds are muted or at
* zero volume.
*/
export function getAudioContext(): AudioContext | null {
if (!allowed || volume <= 0) return null;
if (!context) {
if (typeof window === "undefined") return null;
const Ctor =
window.AudioContext ??
(window as unknown as { webkitAudioContext?: AudioContextCtor }).webkitAudioContext;
if (!Ctor) return null;
context = new Ctor();
}
// Browsers may refuse outside a user gesture. Players call this from
// pointer and key handlers first, so a later call finds it running.
if (context.state === "suspended") void context.resume().catch(() => undefined);
return context;
}
/** The node every player connects to: the page-wide volume, then the speakers. */
export function audioOutput(ctx: AudioContext): AudioNode {
if (master?.context !== ctx) {
master = ctx.createGain();
master.gain.value = volume;
master.connect(ctx.destination);
}
return master;
}
const gains = new WeakMap<BaseAudioContext, Map<string, GainNode>>();
/**
* A player's own level, made once per context and routed into `audioOutput`.
* Players keep their mix this way without rebuilding nodes on every play, and
* a context closed and recreated gets fresh ones.
*/
export function playerGain(ctx: AudioContext, key: string, level: number): GainNode {
let byKey = gains.get(ctx);
if (!byKey) {
byKey = new Map();
gains.set(ctx, byKey);
}
let gain = byKey.get(key);
if (!gain) {
gain = ctx.createGain();
gain.gain.value = level;
gain.connect(audioOutput(ctx));
byKey.set(key, gain);
}
return gain;
}
import { audioOutput, getAudioContext } from "@/lib/audio-context";
// Every beUI sound is a short recipe played with Web Audio the moment it is
// asked for. Nothing is downloaded. Recipes are built the way a real tap
// sounds: a contact click (a millisecond of filtered noise), a body that
// rings at a few inharmonic partials of a material and settles in pitch, and
// a little of a small room behind it.
/** Options for one play of a sound. */
export interface PlayOptions {
/** 0 to 1, multiplied with the page-wide volume from `SoundProvider`. */
volume?: number;
/** Pitch multiplier; 1 is the designed pitch. */
pitch?: number;
}
/** Where a sound renders: the live context, or an offline one for drawing. */
export interface SoundTarget {
context: BaseAudioContext;
destination: AudioNode;
/** Start time on the context clock, in seconds. */
when: number;
volume: number;
pitch: number;
}
/** A plain oscillator with an attack, a decay and an optional glide. */
export interface ToneSpec {
type?: OscillatorType;
/** Start frequency in Hz. */
freq: number;
/** End frequency in Hz; glides from `freq` over `glide`. */
to?: number;
/** Glide time in seconds; defaults to the attack plus decay. */
glide?: number;
/** Starts this many times higher and settles to `freq` in about 15 ms, like a struck object. */
bend?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Fade-in time in seconds. */
attack?: number;
/** Time to fade to silence after the attack, in seconds. */
decay: number;
gain: number;
}
/** A burst of filtered white noise. */
export interface NoiseSpec {
filter?: BiquadFilterType;
/** Filter frequency in Hz. */
freq: number;
/** End filter frequency in Hz; sweeps from `freq` over the decay. */
to?: number;
q?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Fade-in time in seconds. */
attack?: number;
/** Time to fade to silence after the attack, in seconds. */
decay: number;
gain: number;
}
/** The contact of a tap: a few milliseconds of band-passed noise with an instant attack. */
export interface ClickSpec {
/** Band center in Hz: 1-2 kHz is a soft knock, 3-5 kHz a crisp click. */
freq: number;
/** Band width; higher is narrower and more tonal. */
q?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Time to fade to silence, in seconds. */
decay?: number;
gain: number;
}
/** How a material rings: partials as [frequency ratio, level], and how fast high ones die. */
export interface Material {
partials: readonly (readonly [ratio: number, level: number])[];
/** Higher partials decay in `decay / ratio ** damping`; wood is high, metal low. */
damping: number;
}
// Partial ratios follow the modes of small struck objects: a free bar for
// wood and metal, a cup for glass, a tuned bar for the mallet.
export const MATERIALS = {
wood: { partials: [[1, 1], [2.76, 0.3], [5.4, 0.08]], damping: 1.3 },
plastic: { partials: [[1, 1], [2.43, 0.4], [4.86, 0.14]], damping: 0.9 },
glass: { partials: [[1, 1], [2.32, 0.42], [4.25, 0.2], [6.63, 0.08]], damping: 0.55 },
metal: { partials: [[1, 1], [2.76, 0.5], [5.4, 0.26], [8.93, 0.1]], damping: 0.4 },
mallet: { partials: [[1, 1], [3.99, 0.2], [9.14, 0.05]], damping: 0.8 },
bell: { partials: [[1, 1], [2.0, 0.34], [2.76, 0.2], [5.4, 0.07]], damping: 0.5 },
} satisfies Record<string, Material>;
/** A struck object: one partial per mode of its material, each with its own decay. */
export interface StrikeSpec {
/** Fundamental in Hz. */
freq: number;
/** A name from `MATERIALS` or your own partials. Default: "plastic". */
material?: keyof typeof MATERIALS | Material;
/** Starts this many times higher and settles in about 15 ms. Default: 1.01. */
bend?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Time for the fundamental to fade to silence, in seconds. */
decay: number;
gain: number;
}
export interface Voice {
tone(spec: ToneSpec): void;
noise(spec: NoiseSpec): void;
click(spec: ClickSpec): void;
strike(spec: StrikeSpec): void;
}
export interface Sound {
/** Display name, like "Tap". */
name: string;
/** Length in seconds; the room tail rings a little past it. */
duration: number;
/** Plays the sound now. Silent during SSR and while sounds are muted. */
play(options?: PlayOptions): void;
/** Schedules the sound on any context; `play` uses the live one. */
render(target: SoundTarget): void;
}
export interface SoundRecipe {
/** Display name, like "Tap". */
name: string;
/** Length in seconds; the room tail rings a little past it. */
duration: number;
/** Random pitch spread per play (0.04 = ±4%), so repeats don't sound stamped. */
vary?: number;
/** How much of the small room the sound is played in, 0 (dry) to 1. Default: 0.12. */
room?: number;
/** Adds the sound's layers to the voice on each play. */
build: (voice: Voice) => void;
}
// Keeps a sum of voices well under clipping at volume 1.
const MASTER_GAIN = 0.16;
const SILENT = 0.0001;
// Time a strike or bend takes to settle onto its pitch.
const SETTLE = 0.015;
const noiseBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();
/** One second of white noise per context, shared by every noise voice. */
export function noiseBuffer(context: BaseAudioContext) {
let buffer = noiseBuffers.get(context);
if (!buffer) {
buffer = context.createBuffer(1, context.sampleRate, context.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;
noiseBuffers.set(context, buffer);
}
return buffer;
}
// A small, soft room: 8 early reflections, then a diffuse tail that falls
// 60 dB in 0.3 s and darkens as it fades, the way air and soft walls
// absorb highs first. Generated once per context.
const ROOM_LENGTH = 0.3;
// The convolver's equal-power normalization leaves the room about 15 dB
// under the dry sound; this brings `room: 0.12` to a tail heard only as space.
const ROOM_GAIN = 6;
const roomBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();
function roomBuffer(context: BaseAudioContext) {
let buffer = roomBuffers.get(context);
if (!buffer) {
const rate = context.sampleRate;
const length = Math.ceil(ROOM_LENGTH * rate);
buffer = context.createBuffer(2, length, rate);
for (let channel = 0; channel < 2; channel++) {
const data = buffer.getChannelData(channel);
let smooth = 0;
for (let i = Math.floor(0.004 * rate); i < length; i++) {
const t = i / rate;
// One-pole low-pass whose cutoff closes over the tail.
const brightness = 0.7 * Math.exp(-t / 0.08) + 0.08;
smooth += brightness * (Math.random() * 2 - 1 - smooth);
data[i] = smooth * Math.exp(-t / 0.043);
}
for (let r = 0; r < 8; r++) {
const at = Math.floor((0.005 + Math.random() * 0.022) * rate);
data[at] += (Math.random() < 0.5 ? -1 : 1) * (0.5 - r * 0.05);
}
}
roomBuffers.set(context, buffer);
}
return buffer;
}
// One convolver per output node, shared by every play: building one is the
// expensive part, sending to it is cheap.
const rooms = new WeakMap<AudioNode, ConvolverNode>();
function roomFor(context: BaseAudioContext, destination: AudioNode) {
let room = rooms.get(destination);
if (!room) {
room = context.createConvolver();
room.buffer = roomBuffer(context);
room.connect(destination);
rooms.set(destination, room);
}
return room;
}
/** A linear attack to `peak`, then an exponential fall to silence. */
function envelope(param: AudioParam, start: number, attack: number, decay: number, peak: number) {
param.setValueAtTime(0, start);
param.linearRampToValueAtTime(Math.max(peak, SILENT), start + attack);
param.exponentialRampToValueAtTime(SILENT, start + attack + decay);
}
function voiceFor(target: SoundTarget, output: AudioNode): Voice {
const { context, when, pitch } = target;
// Partials above this only add hiss on small speakers, or alias near Nyquist.
const ceiling = Math.min(12000, context.sampleRate * 0.45);
const tone: Voice["tone"] = ({ type = "sine", freq, to, glide, bend, at = 0, attack = 0.002, decay, gain }) => {
const start = when + at;
const osc = context.createOscillator();
const amp = context.createGain();
osc.type = type;
const base = freq * pitch;
osc.frequency.setValueAtTime(base * (bend ?? 1), start);
if (bend !== undefined) osc.frequency.exponentialRampToValueAtTime(base, start + SETTLE);
if (to !== undefined) {
osc.frequency.exponentialRampToValueAtTime(to * pitch, start + Math.max(glide ?? attack + decay, SETTLE));
}
envelope(amp.gain, start, attack, decay, gain);
osc.connect(amp).connect(output);
osc.start(start);
osc.stop(start + attack + decay + 0.02);
};
const noise: Voice["noise"] = ({ filter = "bandpass", freq, to, q = 1, at = 0, attack = 0.002, decay, gain }) => {
const start = when + at;
const source = context.createBufferSource();
const shape = context.createBiquadFilter();
const amp = context.createGain();
source.buffer = noiseBuffer(context);
shape.type = filter;
shape.Q.value = q;
shape.frequency.setValueAtTime(freq * pitch, start);
if (to !== undefined) {
shape.frequency.exponentialRampToValueAtTime(to * pitch, start + attack + decay);
}
envelope(amp.gain, start, attack, decay, gain);
source.connect(shape).connect(amp).connect(output);
// A random offset into the buffer keeps each burst a little different.
source.start(start, Math.random() * 0.5);
source.stop(start + attack + decay + 0.02);
};
return {
tone,
noise,
click({ freq, q = 2, at = 0, decay = 0.005, gain }) {
// A little spread on the band, so no two contacts are identical.
noise({ freq: freq * (0.94 + Math.random() * 0.12), q, at, attack: 0.0005, decay, gain });
},
strike({ freq, material = "plastic", bend = 1.01, at = 0, decay, gain }) {
const { partials, damping } = typeof material === "string" ? MATERIALS[material] : material;
for (const [ratio, level] of partials) {
if (freq * ratio * pitch * bend > ceiling) continue;
tone({
// Real objects are never perfectly tuned; a hair of detune per partial.
freq: freq * ratio * (1 + (Math.random() * 2 - 1) * 0.003),
bend,
at,
attack: 0.001,
decay: decay / ratio ** damping,
gain: gain * level,
});
}
},
};
}
/** Turns a recipe into a playable sound. */
export function defineSound({ name, duration, vary = 0, room = 0.12, build }: SoundRecipe): Sound {
const render = (target: SoundTarget) => {
const { context, destination } = target;
const output = context.createGain();
output.gain.value = MASTER_GAIN * target.volume;
output.connect(destination);
if (room > 0) {
const send = context.createGain();
send.gain.value = room * ROOM_GAIN;
output.connect(send).connect(roomFor(context, destination));
}
build(voiceFor(target, output));
};
return {
name,
duration,
render,
play({ volume = 1, pitch = 1 } = {}) {
const context = getAudioContext();
if (!context || volume <= 0) return;
const spread = vary ? 1 + (Math.random() * 2 - 1) * vary : 1;
render({
context,
// The page-wide volume is applied there.
destination: audioOutput(context),
when: context.currentTime + 0.005,
volume,
pitch: pitch * spread,
});
},
};
}
Copy the source code
"use client";
// beui.dev/components/motion/select/morph
import { Check, ChevronDown } from "lucide-react";
import {
AnimatePresence,
motion,
useReducedMotion,
type Variants,
} from "motion/react";
import {
createContext,
type ReactNode,
type RefObject,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { MENU_ITEM_CLASS, MenuItemHighlight } from "@/components/motion/menu/menu-item-highlight";
import { SPRING_MORPH } from "@/lib/ease";
import { type DismissReason, useDismiss } from "@/lib/hooks/use-dismiss";
import { type ListboxRow, useListbox } from "@/lib/hooks/use-listbox";
import { useSound } from "@/lib/sound";
import { closeSound } from "@/lib/sounds/close";
import { openSound } from "@/lib/sounds/open";
import { selectSound } from "@/lib/sounds/select";
import { PresenceGate } from "@/lib/presence-gate";
import { cn } from "@/lib/utils";
// Shared-layout morph: trigger box grows into the panel and back, one surface.
const MORPH = SPRING_MORPH;
// The fold back into the trigger: shorter than the open and without bounce,
// so the panel settles as it leaves instead of wobbling out. Local because it
// only exists as this morph's close.
const MORPH_CLOSE = { type: "spring", duration: 0.35, bounce: 0 } as const;
// Opened or closed from the keyboard: no motion at all.
const INSTANT = { duration: 0 } as const;
// Trigger and panel header share this row so the morph stays seamless.
const ROW = "flex h-10 w-full items-center justify-between gap-2 px-4 text-sm";
// The closed trigger is a pill (half its h-10 height). The open panel is
// rounded-2xl, the radius every floating list in the library uses.
const TRIGGER_RADIUS = 20;
const PANEL_RADIUS = 16;
const LIST: Variants = {
hidden: {},
show: { transition: { staggerChildren: 0.035, delayChildren: 0.08 } },
};
const ITEM: Variants = {
hidden: { opacity: 0, y: -6, filter: "blur(3px)" },
show: { opacity: 1, y: 0, filter: "blur(0px)" },
};
interface MorphContextValue {
value: string | undefined;
open: boolean;
/** `instant` skips the morph: the keyboard asked for it. */
setOpen: (open: boolean, quiet?: boolean, instant?: boolean) => void;
select: (value: string, instant?: boolean) => void;
/** Whether the latest open or close skips its animation. */
instant: boolean;
register: (value: string, label: string, disabled: boolean) => void;
unregister: (value: string) => void;
labelFor: (value: string | undefined) => string | undefined;
rows: ListboxRow[];
/** Closes the panel; focus inside it returns to the trigger. */
close: (quiet?: boolean, instant?: boolean) => void;
triggerRef: RefObject<HTMLButtonElement | null>;
placeholder: string;
setPlaceholder: (p: string) => void;
reduce: boolean;
layoutId: string;
triggerId: string;
listId: string;
headerId: string;
disabled: boolean;
}
const MorphContext = createContext<MorphContextValue | null>(null);
// The option keyboard focus is on, resolved during render by the content.
// The active option (resolved during render by the content), whether its
// highlight glides (after the pointer) or jumps (after a key), and how a
// pointer resting on an option makes it the active one.
interface ActiveOption {
activeId: string | undefined;
glide: boolean;
setActive: (id: string) => void;
}
const ActiveOptionContext = createContext<ActiveOption>({
activeId: undefined,
glide: true,
setActive: () => {},
});
// True inside the hidden copy that only keeps labels registered while closed.
const RegistrarContext = createContext(false);
function useMorphContext(component: string) {
const ctx = useContext(MorphContext);
if (!ctx) throw new Error(`${component} must be used within <MorphSelect>`);
return ctx;
}
export interface MorphSelectProps {
/** The selected value, for controlled use. */
value?: string;
/** The initial value when uncontrolled. */
defaultValue?: string;
/** Called with the option's value when the user picks one. */
onValueChange?: (value: string) => void;
/** Disable the trigger so the panel cannot open. Default: false */
disabled?: boolean;
/** Play open and close swishes and a select on a pick. Off by default; a `SoundProvider` can mute it app-wide. */
sound?: boolean;
/** Classes merged onto the root element. */
className?: string;
children: ReactNode;
}
/**
* Select whose trigger morphs into the panel via a shared layoutId — instead of
* a separate dropdown opening, the trigger itself grows into the menu and
* shrinks back, never detaching. Composable like `Select` (the unfold variant).
*/
export function MorphSelect({
value,
defaultValue,
onValueChange,
disabled = false,
sound = false,
className,
children,
}: MorphSelectProps) {
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const rootRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
// Set when the panel closes holding focus: the trigger is unmounted while
// open, so focus can only go back once it has mounted again.
const restoreFocus = useRef(false);
const [open, setOpenState] = useState(false);
const [instant, setInstant] = useState(false);
const [internal, setInternal] = useState(defaultValue);
const playOpen = useSound(openSound, { enabled: sound });
const playClose = useSound(closeSound, { enabled: sound });
const playSelect = useSound(selectSound, { enabled: sound });
// `quiet` skips the close sweep when a pick already made its own sound.
const setOpen = useCallback(
(next: boolean, quiet = false, now = false) => {
if (next !== open) {
if (!quiet) {
if (next) playOpen();
else playClose();
}
setInstant(now);
}
setOpenState(next);
},
[open, playOpen, playClose],
);
// ref-counted: items render twice (hidden registrar + open panel), so a
// label is only dropped once every copy with that value has unmounted.
const [labels, setLabels] = useState<
Map<string, { label: string; disabled: boolean; count: number }>
>(new Map());
const [placeholder, setPlaceholder] = useState("Select");
const controlled = value !== undefined;
const current = controlled ? value : internal;
const close = useCallback(
(quiet = false, now = false) => {
if (rootRef.current?.contains(document.activeElement))
restoreFocus.current = true;
setOpen(false, quiet, now);
},
[setOpen],
);
useEffect(() => {
if (open || !restoreFocus.current) return;
restoreFocus.current = false;
triggerRef.current?.focus();
}, [open]);
const select = useCallback(
(next: string, now = false) => {
playSelect();
if (!controlled) setInternal(next);
onValueChange?.(next);
close(true, now);
},
[controlled, onValueChange, close, playSelect],
);
const register = useCallback((v: string, label: string, disabled: boolean) => {
setLabels((m) => {
const next = new Map(m);
next.set(v, { label, disabled, count: (m.get(v)?.count ?? 0) + 1 });
return next;
});
}, []);
const unregister = useCallback((v: string) => {
setLabels((m) => {
const entry = m.get(v);
if (!entry) return m;
const next = new Map(m);
if (entry.count <= 1) next.delete(v);
else next.set(v, { ...entry, count: entry.count - 1 });
return next;
});
}, []);
// Escape closes at once; an outside press folds the panel back.
const dismiss = useCallback(
(reason: DismissReason) => (reason === "escape" ? close(false, true) : setOpen(false)),
[close, setOpen],
);
useDismiss(open, dismiss, rootRef);
const rows = useMemo(
() =>
Array.from(labels, ([id, entry]) => ({
id,
label: entry.label,
disabled: entry.disabled,
})),
[labels],
);
const ctx = useMemo<MorphContextValue>(
() => ({
value: current,
open,
setOpen,
select,
instant,
register,
unregister,
labelFor: (v) => (v === undefined ? undefined : labels.get(v)?.label),
rows,
close,
triggerRef,
placeholder,
setPlaceholder,
reduce,
layoutId: `${baseId}-surface`,
triggerId: `${baseId}-trigger`,
listId: `${baseId}-list`,
headerId: `${baseId}-header`,
disabled,
}),
[
current,
open,
setOpen,
select,
instant,
register,
unregister,
labels,
rows,
close,
placeholder,
reduce,
baseId,
disabled,
],
);
return (
<MorphContext.Provider value={ctx}>
<div ref={rootRef} className={cn("relative", className)}>
{children}
</div>
</MorphContext.Provider>
);
}
export interface MorphSelectValueProps {
/** Text shown in the trigger and panel header before anything is picked. Default: "Select" */
placeholder?: string;
/** Classes merged onto the value text. */
className?: string;
}
export function MorphSelectValue({
placeholder,
className,
}: MorphSelectValueProps) {
const ctx = useMorphContext("MorphSelectValue");
// surface the placeholder so the morph header (rendered by content) matches
useEffect(() => {
if (placeholder) ctx.setPlaceholder(placeholder);
}, [placeholder, ctx.setPlaceholder]);
const label = ctx.labelFor(ctx.value);
return (
<span
className={cn(label ? "text-foreground" : "text-muted-foreground", className)}
>
{label ?? placeholder ?? "Select"}
</span>
);
}
export interface MorphSelectTriggerProps {
/** Classes merged onto the trigger button. */
className?: string;
children: ReactNode;
}
export function MorphSelectTrigger({
className,
children,
}: MorphSelectTriggerProps) {
const ctx = useMorphContext("MorphSelectTrigger");
return (
<>
{/* invisible sizer reserves the closed height (the morph surface is
absolute, so this keeps surrounding layout from shifting) */}
<div
aria-hidden
inert
className={cn(ROW, "invisible rounded-full border border-border")}
>
{children}
<ChevronDown className="h-4 w-4" />
</div>
<AnimatePresence initial={false} mode="popLayout">
{!ctx.open ? (
<motion.button
key="trigger"
ref={ctx.triggerRef}
layoutId={ctx.layoutId}
type="button"
id={ctx.triggerId}
disabled={ctx.disabled}
aria-haspopup="listbox"
aria-expanded={ctx.open}
aria-controls={ctx.listId}
// `detail` is 0 for a click the keyboard made (Enter, Space): no morph.
onClick={(event) => ctx.setOpen(true, false, event.detail === 0)}
onKeyDown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
ctx.setOpen(true, false, true);
}
}}
// The trigger is what the panel morphs back into, so its
// transition is the close.
transition={ctx.reduce || ctx.instant ? INSTANT : MORPH_CLOSE}
style={{ borderRadius: TRIGGER_RADIUS }}
className={cn(
ROW,
"absolute inset-x-0 top-0 z-10 border border-border bg-background text-foreground outline-none transition-colors",
"hover:border-(--color-border-strong) focus-visible:ring-2 focus-visible:ring-foreground/20",
"disabled:pointer-events-none disabled:opacity-50",
className,
)}
>
<motion.span layout="position" className="min-w-0 truncate">
{children}
</motion.span>
<motion.span layout="position" className="text-muted-foreground">
<ChevronDown className="h-4 w-4" />
</motion.span>
</motion.button>
) : null}
</AnimatePresence>
</>
);
}
export interface MorphSelectContentProps {
/** Classes merged onto the open panel. */
className?: string;
children: ReactNode;
}
export function MorphSelectContent({
className,
children,
}: MorphSelectContentProps) {
const ctx = useMorphContext("MorphSelectContent");
const label = ctx.labelFor(ctx.value);
const listRef = useRef<HTMLUListElement>(null);
const { activeId, onKeyDown, moveTo } = useListbox({
open: ctx.open,
rows: ctx.rows,
selected: ctx.value,
list: listRef,
});
const [glide, setGlide] = useState(true);
const active = useMemo<ActiveOption>(
() => ({ activeId, glide, setActive: moveTo }),
[activeId, glide, moveTo],
);
return (
<>
{/* always-mounted, hidden — keeps item label registrations alive while
closed so the trigger shows the selected value before first open */}
<RegistrarContext.Provider value={true}>
<div hidden>{children}</div>
</RegistrarContext.Provider>
<AnimatePresence initial={false} mode="popLayout">
{ctx.open ? (
<motion.div
key="panel"
layoutId={ctx.layoutId}
transition={ctx.reduce || ctx.instant ? INSTANT : MORPH}
style={{ borderRadius: PANEL_RADIUS }}
className={cn(
// The same soft shadow as the menus, so floating lists read as one family.
"pointer-events-none absolute inset-x-0 top-0 z-30 overflow-hidden border border-border bg-background shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)]",
className,
)}
>
{/* The panel sits over the returning trigger for the whole morph
back, so its contents stop taking clicks and focus as soon as
it starts leaving. The surface itself never takes pointer
events, so the gate goes on this wrapper. */}
<PresenceGate>
{({ gate }) => (
<div {...gate}>
{/* header mirrors the trigger (continuous morph) and
collapses the panel back into the trigger when clicked */}
<motion.button
type="button"
id={ctx.headerId}
layout="position"
aria-haspopup="listbox"
aria-expanded
aria-controls={ctx.listId}
onClick={(event) => ctx.close(false, event.detail === 0)}
className={cn(ROW, "outline-none")}
>
<span
className={cn(
"min-w-0 truncate",
label ? "text-foreground" : "text-muted-foreground",
)}
>
{label ?? ctx.placeholder}
</span>
<motion.span
aria-hidden
animate={{ rotate: 180 }}
transition={ctx.reduce || ctx.instant ? INSTANT : MORPH}
className="text-muted-foreground"
>
<ChevronDown className="h-4 w-4" />
</motion.span>
</motion.button>
<div className="h-px bg-border" />
<ActiveOptionContext.Provider value={active}>
<motion.ul
ref={listRef}
id={ctx.listId}
role="listbox"
aria-labelledby={ctx.headerId}
initial="hidden"
animate="show"
// The panel mounts fresh each open, so a keyboard open
// can simply leave the stagger out.
variants={ctx.reduce || ctx.instant ? undefined : LIST}
onKeyDown={(event) => {
// Set before the key moves the active option, so its highlight jumps.
setGlide(false);
if (event.key === "Tab") {
event.preventDefault();
ctx.close(false, true);
} else onKeyDown(event);
}}
onPointerMove={(event) => {
if (event.pointerType !== "touch") setGlide(true);
}}
className="p-2"
>
{children}
</motion.ul>
</ActiveOptionContext.Provider>
</div>
)}
</PresenceGate>
</motion.div>
) : null}
</AnimatePresence>
</>
);
}
export interface MorphSelectItemProps {
/** Value reported when this option is picked. */
value: string;
/** Make the option unselectable and skip it in keyboard navigation. Default: false */
disabled?: boolean;
/** Classes merged onto the option button. */
className?: string;
children: ReactNode;
}
export function MorphSelectItem({
value,
disabled = false,
className,
children,
}: MorphSelectItemProps) {
const ctx = useMorphContext("MorphSelectItem");
const { activeId, glide, setActive } = useContext(ActiveOptionContext);
const registrarOnly = useContext(RegistrarContext);
const selected = ctx.value === value;
const active = activeId === value;
const label = typeof children === "string" ? children : value;
useLayoutEffect(() => {
ctx.register(value, label, disabled);
return () => ctx.unregister(value);
}, [ctx.register, ctx.unregister, value, label, disabled]);
// The hidden copy only registers; no stray options outside the listbox.
if (registrarOnly) return null;
return (
<motion.li role="none" variants={ctx.reduce || ctx.instant ? undefined : ITEM}>
<button
type="button"
role="option"
aria-selected={selected}
disabled={disabled}
// One tab stop: the active option, which focus follows while open.
tabIndex={active ? 0 : -1}
data-listbox-id={value}
// A resting pointer makes this the active option, so the highlight
// follows the mouse the same way it follows the arrow keys.
onPointerMove={(event) => {
if (event.pointerType !== "touch" && !disabled && !active) setActive(value);
}}
// Enter or Space on the option (`detail` 0) closes without the morph.
onClick={(event) => ctx.select(value, event.detail === 0)}
className={cn(
MENU_ITEM_CLASS,
"justify-between gap-2 text-foreground",
"disabled:pointer-events-none disabled:opacity-50",
className,
)}
>
{/* One highlight for the whole list: it glides after the pointer and
jumps after a key. The selected option is marked by its check. */}
{active && !disabled ? (
<MenuItemHighlight
layoutId={`${ctx.listId}-highlight`}
reduce={ctx.reduce}
instant={!glide}
/>
) : null}
<span className="flex min-w-0 flex-1 items-center gap-2">{children}</span>
{selected ? <Check aria-hidden="true" className="h-3.5 w-3.5 shrink-0" /> : null}
</button>
</motion.li>
);
}
"use client";
import { motion } from "motion/react";
import { SPRING_LAYOUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
/** The row shape every menu item shares. Menus add their own gap and states. */
export const MENU_ITEM_CLASS =
"relative isolate flex w-full select-none items-center rounded-lg px-3 py-1.5 text-left text-sm outline-none";
export interface MenuItemHighlightProps {
/** Shared by every row of one panel, so the highlight glides between them. */
layoutId: string;
tone?: "default" | "destructive";
reduce: boolean;
/**
* Jump instead of gliding: the highlight was moved by the keyboard, where a
* spring only trails behind fast arrowing.
*/
instant?: boolean;
}
/** The highlight behind the active row. Render it only inside the active row. */
export function MenuItemHighlight({
layoutId,
tone = "default",
reduce,
instant = false,
}: MenuItemHighlightProps) {
return (
<motion.span
aria-hidden="true"
layoutId={layoutId}
className={cn(
"absolute inset-0 -z-10 rounded-lg",
tone === "destructive" ? "bg-destructive/10" : "bg-foreground/[0.07]",
)}
transition={reduce || instant ? { duration: 0 } : SPRING_LAYOUT}
/>
);
}
value?stringThe selected value, for controlled use.
—defaultValue?stringThe initial value when uncontrolled.
—onValueChange?((value: string) => void)Called with the option's value when the user picks one.
—disabled?booleanDisable the trigger so the panel cannot open. Default: false
falsesound?booleanPlay open and close swishes and a select on a pick. Off by default; a `SoundProvider` can mute it app-wide.
falseclassName?stringClasses merged onto the root element.
—placeholder?stringText shown in the trigger and panel header before anything is picked. Default: "Select"
—className?stringClasses merged onto the value text.
—Radio Group
Single-select choice control with a gliding layoutId indicator dot and spring press feedback.
Checkbox
Form choice control with a draw-on checkmark, spring press feedback and indeterminate state support.
Input
Text input with label, left/right icons, optional stable error row, error shake and success check draw.
Updated