Preview
"use client";
import { Circle } from "lucide-react";
import {
MultiSelect,
MultiSelectContent,
MultiSelectEmpty,
MultiSelectGroup,
MultiSelectInput,
MultiSelectItem,
MultiSelectLabel,
MultiSelectList,
MultiSelectTrigger,
MultiSelectValue,
} from "@/components/motion/multi-select";
const colors = {
design: "fill-rose-500 text-rose-500",
engineering: "fill-sky-500 text-sky-500",
product: "fill-amber-500 text-amber-500",
research: "fill-cyan-500 text-cyan-500",
marketing: "fill-emerald-500 text-emerald-500",
operations: "fill-slate-500 text-slate-500",
};
function Option({
value,
children,
}: {
value: keyof typeof colors;
children: string;
}) {
return (
<MultiSelectItem value={value} textValue={children}>
<span className="flex items-center gap-2.5">
<Circle aria-hidden="true" className={`size-2.5 ${colors[value]}`} />
{children}
</span>
</MultiSelectItem>
);
}
export function MultiSelectPreview() {
return (
<div className="flex min-h-[420px] w-full items-start justify-center px-4 pt-24">
<div className="w-full max-w-sm">
<MultiSelect defaultValue={["design", "engineering"]}>
<MultiSelectTrigger>
<MultiSelectValue placeholder="Choose teams" />
<MultiSelectInput aria-label="Search teams" />
</MultiSelectTrigger>
<MultiSelectContent>
<MultiSelectList ariaLabel="Teams">
<MultiSelectGroup>
<MultiSelectLabel>Product teams</MultiSelectLabel>
<Option value="design">Design</Option>
<Option value="engineering">Engineering</Option>
<Option value="product">Product</Option>
<Option value="research">Research</Option>
</MultiSelectGroup>
<MultiSelectGroup>
<MultiSelectLabel>Business teams</MultiSelectLabel>
<Option value="marketing">Marketing</Option>
<Option value="operations">Operations</Option>
</MultiSelectGroup>
<MultiSelectEmpty>No teams found.</MultiSelectEmpty>
</MultiSelectList>
</MultiSelectContent>
</MultiSelect>
</div>
</div>
);
}
"use client";
// beui.dev/components/motion/multi-select
export {
MultiSelectContent,
type MultiSelectContentProps,
} from "./content";
export {
MultiSelect,
type MultiSelectFilter,
type MultiSelectProps,
} from "./context";
export {
MultiSelectEmpty,
type MultiSelectEmptyProps,
MultiSelectGroup,
type MultiSelectGroupProps,
MultiSelectItem,
type MultiSelectItemProps,
MultiSelectLabel,
type MultiSelectLabelProps,
MultiSelectList,
type MultiSelectListProps,
MultiSelectSeparator,
type MultiSelectSeparatorProps,
} from "./list";
export {
type MultiSelectMessages,
multiSelectMessages,
} from "./messages";
export {
MultiSelectInput,
type MultiSelectInputProps,
MultiSelectTrigger,
type MultiSelectTriggerProps,
MultiSelectValue,
type MultiSelectValueProps,
} from "./trigger";
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 {
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],
);
}
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
// 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;
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);
};
}
/**
* 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),
);
}
Copy the source code
"use client";
// beui.dev/components/motion/multi-select
export {
MultiSelectContent,
type MultiSelectContentProps,
} from "./content";
export {
MultiSelect,
type MultiSelectFilter,
type MultiSelectProps,
} from "./context";
export {
MultiSelectEmpty,
type MultiSelectEmptyProps,
MultiSelectGroup,
type MultiSelectGroupProps,
MultiSelectItem,
type MultiSelectItemProps,
MultiSelectLabel,
type MultiSelectLabelProps,
MultiSelectList,
type MultiSelectListProps,
MultiSelectSeparator,
type MultiSelectSeparatorProps,
} from "./list";
export {
type MultiSelectMessages,
multiSelectMessages,
} from "./messages";
export {
MultiSelectInput,
type MultiSelectInputProps,
MultiSelectTrigger,
type MultiSelectTriggerProps,
MultiSelectValue,
type MultiSelectValueProps,
} from "./trigger";
"use client";
// beui.dev/components/motion/multi-select
import { useReducedMotion } from "motion/react";
import {
createContext,
type MutableRefObject,
type ReactNode,
useCallback,
useContext,
useEffect,
useId,
useMemo,
useRef,
useState,
} from "react";
import {
defaultOptionFilter,
type OptionFilter,
type RegisteredItem,
useFilteredOptions,
} from "@/components/motion/combobox/use-filtered-options";
import { type DismissReason, useDismiss } from "@/lib/hooks/use-dismiss";
import { useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
import {
type MultiSelectMessages,
type MultiSelectTranslate,
multiSelectMessages,
} from "./messages";
export type RegisteredMultiSelectItem = RegisteredItem;
export type MultiSelectFilter = OptionFilter;
export type MultiSelectContextValue = {
open: boolean;
setOpen: (open: boolean, restoreFocus?: boolean) => void;
values: string[];
toggle: (value: string) => void;
remove: (value: string) => void;
query: string;
setQuery: (query: string) => void;
activeValue: string | null;
setActiveValue: (value: string | null) => void;
moveActive: (direction: 1 | -1 | "first" | "last") => void;
toggleActive: () => void;
registerItem: (item: RegisteredMultiSelectItem) => void;
unregisterItem: (value: string) => void;
labelFor: (value: string) => string;
isVisible: (value: string) => boolean;
hasVisibleItems: (groupId: string) => boolean;
visibleCount: number;
activeItemId: string | undefined;
triggerId: string;
listId: string;
inputId: string;
disabled: boolean;
reduce: boolean;
triggerRef: MutableRefObject<HTMLDivElement | null>;
contentRef: MutableRefObject<HTMLDivElement | null>;
inputRef: MutableRefObject<HTMLInputElement | null>;
activeLayoutId: string;
t: MultiSelectTranslate;
};
export const MultiSelectContext =
createContext<MultiSelectContextValue | null>(null);
export const MultiSelectGroupContext = createContext<string | null>(null);
export function useMultiSelectContext(component: string) {
const context = useContext(MultiSelectContext);
if (!context) {
throw new Error(`${component} must be used within <MultiSelect>`);
}
return context;
}
export interface MultiSelectProps {
children: ReactNode;
/** The selected values, for controlled use. */
value?: string[];
/** The initial selected values when uncontrolled. Default: [] */
defaultValue?: string[];
/** Called with the new list of values when an option is added or removed. */
onValueChange?: (value: string[]) => void;
/** Whether the list is open, for controlled use. */
open?: boolean;
/** Whether the list starts open when uncontrolled. Default: false */
defaultOpen?: boolean;
/** Called with the new state when the list opens or closes. */
onOpenChange?: (open: boolean) => void;
/** The search text, for controlled use. */
query?: string;
/** The initial search text when uncontrolled. Default: "" */
defaultQuery?: string;
/** Called with the new text when the search input changes. */
onQueryChange?: (query: string) => void;
/** Decides which options match the search text. */
filter?: MultiSelectFilter;
/** Blocks opening and changing the selection. Default: false */
disabled?: boolean;
/** Classes merged onto the root element. */
className?: string;
/** Override any built-in string. `{label}` fills the option label. */
labels?: Partial<MultiSelectMessages>;
}
export function MultiSelect({
children,
value: controlledValue,
defaultValue = [],
onValueChange,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
query: controlledQuery,
defaultQuery = "",
onQueryChange,
filter = defaultOptionFilter,
disabled = false,
className,
labels,
}: MultiSelectProps) {
const t = useMessages("multiSelect", multiSelectMessages, labels);
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const rootRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const [internalValue, setInternalValue] = useState(defaultValue);
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const [internalQuery, setInternalQuery] = useState(defaultQuery);
const valueControlled = controlledValue !== undefined;
const openControlled = controlledOpen !== undefined;
const queryControlled = controlledQuery !== undefined;
const values = controlledValue ?? internalValue;
const open = controlledOpen ?? internalOpen;
const query = controlledQuery ?? internalQuery;
const updateQuery = useCallback(
(next: string) => {
if (!queryControlled) setInternalQuery(next);
onQueryChange?.(next);
},
[onQueryChange, queryControlled],
);
const updateOpen = useCallback(
(next: boolean, restoreFocus = false) => {
if (disabled && next) return;
if (next !== open) {
if (!openControlled) setInternalOpen(next);
onOpenChange?.(next);
}
if (!next) updateQuery("");
if (restoreFocus) {
requestAnimationFrame(() =>
inputRef.current?.focus({ preventScroll: true }),
);
}
},
[disabled, onOpenChange, open, openControlled, updateQuery],
);
const {
items,
registerItem,
unregisterItem,
listQuery,
visibleValues,
visibleGroupIds,
visibleCount,
activeValue,
setActiveValue,
moveActive,
activeItemId,
} = useFilteredOptions({ open, query, value: values[0], filter });
const commitValue = useCallback(
(next: string[]) => {
if (!valueControlled) setInternalValue(next);
onValueChange?.(next);
},
[onValueChange, valueControlled],
);
const toggle = useCallback(
(next: string) => {
if (items.get(next)?.disabled) return;
commitValue(
values.includes(next)
? values.filter((value) => value !== next)
: [...values, next],
);
updateQuery("");
requestAnimationFrame(() =>
inputRef.current?.focus({ preventScroll: true }),
);
},
[commitValue, items, updateQuery, values],
);
const remove = useCallback(
(itemValue: string) => {
if (!values.includes(itemValue)) return;
commitValue(values.filter((value) => value !== itemValue));
},
[commitValue, values],
);
const toggleActive = useCallback(() => {
if (activeValue) toggle(activeValue);
}, [activeValue, toggle]);
useEffect(() => {
if (!open) return;
const frame = requestAnimationFrame(() =>
inputRef.current?.focus({ preventScroll: true }),
);
return () => cancelAnimationFrame(frame);
}, [open]);
const insideContent = useCallback(
(target: Element) => Boolean(contentRef.current?.contains(target)),
[],
);
const dismiss = useCallback(
(reason: DismissReason) => updateOpen(false, reason === "escape"),
[updateOpen],
);
useDismiss(open, dismiss, rootRef, { focusOutside: true, ignore: insideContent });
const context = useMemo<MultiSelectContextValue>(
() => ({
open,
setOpen: updateOpen,
values,
toggle,
remove,
query,
setQuery: updateQuery,
activeValue,
setActiveValue,
moveActive,
toggleActive,
registerItem,
unregisterItem,
labelFor: (itemValue) => items.get(itemValue)?.label ?? itemValue,
isVisible: (itemValue) => !listQuery.trim() || visibleValues.has(itemValue),
hasVisibleItems: (groupId) => visibleGroupIds.has(groupId),
visibleCount,
activeItemId,
triggerId: `${baseId}-trigger`,
listId: `${baseId}-list`,
inputId: `${baseId}-input`,
disabled,
reduce,
triggerRef,
contentRef,
inputRef,
activeLayoutId: `${baseId}-active`,
t,
}),
[
activeItemId,
activeValue,
baseId,
disabled,
items,
listQuery,
moveActive,
open,
query,
reduce,
registerItem,
remove,
setActiveValue,
t,
toggle,
toggleActive,
unregisterItem,
updateOpen,
updateQuery,
values,
visibleGroupIds,
visibleCount,
visibleValues,
],
);
return (
<MultiSelectContext.Provider value={context}>
<div ref={rootRef} className={cn("relative w-full", className)}>
{children}
</div>
</MultiSelectContext.Provider>
);
}
"use client";
// beui.dev/components/motion/multi-select
import { ChevronsUpDown, Search, X } from "lucide-react";
import { AnimatePresence, motion } from "motion/react";
import type {
InputHTMLAttributes,
KeyboardEvent as ReactKeyboardEvent,
ReactNode,
Ref,
} from "react";
import { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from "@/lib/ease";
import { cn } from "@/lib/utils";
import { mergeRefs } from "@/lib/merge-refs";
import { useMultiSelectContext } from "./context";
export interface MultiSelectTriggerProps {
children: ReactNode;
/** Classes merged onto the trigger element. */
className?: string;
}
export function MultiSelectTrigger({
children,
className,
}: MultiSelectTriggerProps) {
const context = useMultiSelectContext("MultiSelectTrigger");
return (
<div
ref={context.triggerRef}
id={context.triggerId}
data-state={context.open ? "open" : "closed"}
onPointerDown={(event) => {
const target = event.target as HTMLElement;
if (
context.disabled ||
target === context.inputRef.current ||
target.closest("[data-multi-select-remove]")
) {
return;
}
event.preventDefault();
context.inputRef.current?.focus({ preventScroll: true });
context.setOpen(true);
}}
className={cn(
"relative z-20 flex min-h-11 w-full min-w-52 cursor-text items-center gap-2 rounded-[22px] border border-border bg-transparent px-2.5 py-1.5 text-sm text-foreground transition-[border-color] hover:border-(--color-border-strong)",
"focus-within:ring-2 focus-within:ring-foreground/20",
context.disabled && "pointer-events-none opacity-50",
className,
)}
>
<div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5">
{children}
</div>
<ChevronsUpDown
aria-hidden="true"
className="size-4 shrink-0 text-muted-foreground"
/>
</div>
);
}
export interface MultiSelectValueProps {
/** Shown while nothing is selected and the list is closed. Default: "Select options" */
placeholder?: ReactNode;
children?: (value: string, label: string) => ReactNode;
/** Classes merged onto the wrapper around the chips. */
className?: string;
/** Classes merged onto each selected value chip. */
chipClassName?: string;
}
export function MultiSelectValue({
placeholder,
children,
className,
chipClassName,
}: MultiSelectValueProps) {
const context = useMultiSelectContext("MultiSelectValue");
const showPlaceholder = context.values.length === 0 && !context.open;
return (
<div className={cn("contents", className)}>
<AnimatePresence initial={false} mode="popLayout">
{showPlaceholder ? (
<span key="multi-select-placeholder" className="text-muted-foreground">
{placeholder ?? context.t("valuePlaceholder")}
</span>
) : null}
{context.values.map((value) => {
const label = context.labelFor(value);
return (
<motion.span
layout={context.reduce ? false : "position"}
key={`multi-select-value-${value}`}
initial={{
opacity: 0,
clipPath: "inset(0 0 0 0% round 0.5rem)",
transform: context.reduce
? "translateY(0px) scale(1)"
: "translateY(6px) scale(0.92)",
}}
animate={{
opacity: 1,
clipPath: "inset(0 0 0 0% round 0.5rem)",
transform: "translateY(0px) scale(1)",
}}
exit={{
opacity: 1,
clipPath: context.reduce
? "inset(0 0 0 0% round 0.5rem)"
: "inset(0 0 0 100% round 0.5rem)",
transform: "translateY(0px) scale(1)",
transition: {
clipPath: context.reduce
? { duration: 0 }
: { duration: 0.16, ease: EASE_OUT },
transform: { duration: 0 },
},
}}
transition={
context.reduce
? {
layout: { duration: 0 },
opacity: { duration: 0.15, ease: EASE_OUT },
transform: { duration: 0 },
}
: {
layout: SPRING_LAYOUT,
opacity: { duration: 0.18, ease: EASE_OUT },
transform: SPRING_SWAP,
}
}
className={cn(
"inline-flex h-7 max-w-full items-center gap-1 rounded-full bg-muted px-2.5 text-xs font-medium text-foreground",
chipClassName,
)}
>
<span className="truncate">
{children ? children(value, label) : label}
</span>
<button
type="button"
data-multi-select-remove=""
aria-label={context.t("removeValue", { label })}
disabled={context.disabled}
onPointerDown={(event) => event.stopPropagation()}
onClick={(event) => {
event.stopPropagation();
context.remove(value);
context.inputRef.current?.focus({ preventScroll: true });
}}
className="-mr-1 grid size-5 shrink-0 place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:bg-foreground/10 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
<X aria-hidden="true" className="size-3" />
</button>
</motion.span>
);
})}
</AnimatePresence>
</div>
);
}
export interface MultiSelectInputProps
extends Omit<
InputHTMLAttributes<HTMLInputElement>,
"defaultValue" | "value"
> {
/** Ref to the search input element. */
ref?: Ref<HTMLInputElement>;
/** Shows a search icon before the input. Default: false */
showIcon?: boolean;
}
export function MultiSelectInput({
ref,
className,
"aria-label": ariaLabel,
onChange,
onClick,
onFocus,
onKeyDown,
onPointerDown,
placeholder,
showIcon = false,
...props
}: MultiSelectInputProps) {
const context = useMultiSelectContext("MultiSelectInput");
const handleKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
onKeyDown?.(event);
if (event.defaultPrevented) return;
if (event.key === "Backspace" && !context.query && context.values.length) {
event.preventDefault();
context.remove(context.values.at(-1) ?? "");
} else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
if (!context.open) {
context.setOpen(true);
return;
}
context.moveActive(event.key === "ArrowDown" ? 1 : -1);
} else if (event.key === "Home" && context.open) {
event.preventDefault();
context.moveActive("first");
} else if (event.key === "End" && context.open) {
event.preventDefault();
context.moveActive("last");
} else if (event.key === "Enter") {
if (event.nativeEvent.isComposing || event.keyCode === 229) return;
event.preventDefault();
if (context.open) context.toggleActive();
else context.setOpen(true);
} else if (event.key === "Escape" && context.open) {
event.preventDefault();
context.setOpen(false, true);
}
};
return (
<div className="flex min-w-20 flex-1 items-center gap-1.5">
{showIcon ? (
<Search aria-hidden="true" className="size-3.5 text-muted-foreground" />
) : null}
<input
{...props}
ref={mergeRefs(ref, context.inputRef)}
id={context.inputId}
role="combobox"
aria-label={ariaLabel ?? context.t("inputLabel")}
aria-autocomplete="list"
aria-expanded={context.open}
aria-controls={context.listId}
aria-activedescendant={
context.open ? context.activeItemId : undefined
}
autoComplete="off"
disabled={context.disabled}
value={context.query}
placeholder={
context.values.length
? ""
: (placeholder ?? context.t("inputPlaceholder"))
}
onPointerDown={(event) => {
onPointerDown?.(event);
if (event.defaultPrevented || context.open) return;
context.setOpen(true);
}}
onFocus={(event) => {
context.setOpen(true);
onFocus?.(event);
}}
onClick={(event) => {
context.setOpen(true);
onClick?.(event);
}}
onChange={(event) => {
context.setOpen(true);
context.setQuery(event.target.value);
onChange?.(event);
}}
onKeyDown={handleKeyDown}
className={cn(
"h-7 min-w-12 flex-1 bg-transparent text-sm text-foreground outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed",
className,
)}
/>
</div>
);
}
"use client";
// beui.dev/components/motion/multi-select
import type { ReactNode } from "react";
import { ListboxPanel, type ListboxPanelPlacement } from "@/components/motion/combobox/listbox-panel";
import { useMultiSelectContext } from "./context";
export interface MultiSelectContentProps extends ListboxPanelPlacement {
children: ReactNode;
}
export function MultiSelectContent({
children,
side = "bottom",
align = "start",
sideOffset = 6,
avoidCollisions = true,
className,
}: MultiSelectContentProps) {
const context = useMultiSelectContext("MultiSelectContent");
return (
<ListboxPanel
name="multi-select"
open={context.open}
reduce={context.reduce}
triggerRef={context.triggerRef}
contentRef={context.contentRef}
side={side}
align={align}
sideOffset={sideOffset}
avoidCollisions={avoidCollisions}
className={className}
>
{children}
</ListboxPanel>
);
}
"use client";
// beui.dev/components/motion/multi-select
import { Check } from "lucide-react";
import { motion } from "motion/react";
import {
type ReactNode,
useContext,
useId,
useLayoutEffect,
useMemo,
useRef,
} from "react";
import { EASE_OUT, SPRING_LAYOUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
import {
MultiSelectGroupContext,
useMultiSelectContext,
} from "./context";
export interface MultiSelectListProps {
children: ReactNode;
/** Accessible name for the listbox. Default: "Options" */
ariaLabel?: string;
/** Classes merged onto the scrolling listbox. */
className?: string;
}
export function MultiSelectList({
children,
ariaLabel,
className,
}: MultiSelectListProps) {
const context = useMultiSelectContext("MultiSelectList");
return (
<div
id={context.listId}
role="listbox"
aria-label={ariaLabel ?? context.t("listLabel")}
aria-multiselectable="true"
className={cn(
"relative isolate max-h-64 overflow-y-auto overscroll-contain p-2 [-ms-overflow-style:none] scrollbar-none [&::-webkit-scrollbar]:hidden",
className,
)}
>
{children}
</div>
);
}
export interface MultiSelectGroupProps {
children: ReactNode;
/** Classes merged onto the group fieldset. */
className?: string;
}
export function MultiSelectGroup({
children,
className,
}: MultiSelectGroupProps) {
const context = useMultiSelectContext("MultiSelectGroup");
const groupId = useId();
return (
<MultiSelectGroupContext.Provider value={groupId}>
<fieldset
hidden={!context.hasVisibleItems(groupId)}
className={cn("m-0 min-w-0 border-0 p-0 py-0.5", className)}
>
{children}
</fieldset>
</MultiSelectGroupContext.Provider>
);
}
export interface MultiSelectLabelProps {
children: ReactNode;
/** Classes merged onto the label element. */
className?: string;
}
export function MultiSelectLabel({
children,
className,
}: MultiSelectLabelProps) {
const groupId = useContext(MultiSelectGroupContext);
const labelClassName = cn(
"w-full px-3 py-1.5 text-[11px] font-medium uppercase tracking-[0.12em] text-muted-foreground",
className,
);
return groupId ? (
<legend className={labelClassName}>{children}</legend>
) : (
<div className={labelClassName}>{children}</div>
);
}
export interface MultiSelectItemProps {
/** The option's value, added to or removed from the selection. */
value: string;
children: ReactNode;
/** Text for search and the trigger chip when the label is not plain text. */
textValue?: string;
/** Extra words that match this option in search. */
keywords?: string[];
/** Keeps the option visible but not selectable. Default: false */
disabled?: boolean;
/** Called with the option's value when it is clicked, before it toggles. */
onSelect?: (value: string) => void;
/** Classes merged onto the option row. */
className?: string;
}
export function MultiSelectItem({
value,
children,
textValue,
keywords = [],
disabled = false,
onSelect,
className,
}: MultiSelectItemProps) {
const context = useMultiSelectContext("MultiSelectItem");
const groupId = useContext(MultiSelectGroupContext);
const id = useId();
const itemRef = useRef<HTMLButtonElement>(null);
const label = textValue ?? (typeof children === "string" ? children : value);
const visible = context.isVisible(value);
const active = context.activeValue === value;
const selected = context.values.includes(value);
const keywordKey = keywords.join("\u0000");
const normalizedKeywords = useMemo(
() => (keywordKey ? keywordKey.split("\u0000") : []),
[keywordKey],
);
const { registerItem, unregisterItem } = context;
useLayoutEffect(() => {
registerItem({
value,
label,
keywords: normalizedKeywords,
disabled,
groupId,
id,
ref: itemRef,
});
return () => unregisterItem(value);
}, [
disabled,
groupId,
id,
label,
normalizedKeywords,
registerItem,
unregisterItem,
value,
]);
if (!visible) return null;
return (
<button
ref={itemRef}
id={id}
type="button"
role="option"
aria-selected={selected}
disabled={disabled}
tabIndex={-1}
data-multi-select-item=""
data-active={active || undefined}
data-selected={selected || undefined}
onPointerMove={() => {
if (!disabled) context.setActiveValue(value);
}}
onPointerDown={(event) => event.preventDefault()}
onClick={() => {
if (disabled) return;
onSelect?.(value);
context.toggle(value);
}}
className={cn(
"relative flex w-full items-center gap-2 rounded-lg px-3 py-1.5 text-left text-sm outline-none transition-colors duration-150",
active || selected ? "text-foreground" : "text-muted-foreground",
"disabled:pointer-events-none disabled:opacity-45",
className,
)}
>
{active ? (
<motion.span
aria-hidden="true"
layoutId={context.activeLayoutId}
className="absolute inset-0 -z-10 rounded-lg bg-foreground/[0.07]"
transition={context.reduce ? { duration: 0 } : SPRING_LAYOUT}
/>
) : null}
<span className="min-w-0 flex-1">{children}</span>
<motion.span
aria-hidden="true"
initial={false}
animate={{
opacity: selected ? 1 : 0,
transform: selected ? "scale(1)" : "scale(0.82)",
}}
transition={
context.reduce ? { duration: 0 } : { duration: 0.14, ease: EASE_OUT }
}
className="grid size-5 shrink-0 place-items-center text-foreground"
>
<Check className="size-4" />
</motion.span>
</button>
);
}
export interface MultiSelectEmptyProps {
children?: ReactNode;
/** Classes merged onto the empty message. */
className?: string;
}
export function MultiSelectEmpty({
children,
className,
}: MultiSelectEmptyProps) {
const context = useMultiSelectContext("MultiSelectEmpty");
if (context.visibleCount > 0) return null;
return (
<div
role="status"
className={cn(
"px-3 py-8 text-center text-sm text-muted-foreground",
className,
)}
>
{children ?? context.t("empty")}
</div>
);
}
export interface MultiSelectSeparatorProps {
/** Classes merged onto the separator line. */
className?: string;
}
export function MultiSelectSeparator({
className,
}: MultiSelectSeparatorProps) {
return (
<div aria-hidden="true" className={cn("-mx-1 my-1 h-px bg-border", className)} />
);
}
import type { useMessages } from "@/lib/i18n";
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const multiSelectMessages = {
valuePlaceholder: "Select options",
removeValue: "Remove {label}",
inputLabel: "Search options",
inputPlaceholder: "Search…",
listLabel: "Options",
empty: "No options found.",
};
export type MultiSelectMessages = typeof multiSelectMessages;
/** The resolved translator the root hands to its parts. */
export type MultiSelectTranslate = ReturnType<
typeof useMessages<MultiSelectMessages>
>;
"use client";
import { type MutableRefObject, useCallback, useEffect, useMemo, useState } from "react";
import { useActiveOption } from "./use-active-option";
/** An option as it registers with its list. */
export type RegisteredItem = {
value: string;
label: string;
keywords: string[];
disabled: boolean;
groupId: string | null;
id: string;
ref: MutableRefObject<HTMLButtonElement | null>;
};
export type OptionFilter = (value: string, query: string, keywords: string[]) => boolean;
/** Fuzzy match: the query's characters appear in order in the value or a keyword. */
export const defaultOptionFilter: OptionFilter = (value, query, keywords) => {
const needle = query.trim().toLocaleLowerCase();
if (!needle) return true;
const haystack = [value, ...keywords].join(" ").toLocaleLowerCase();
let queryIndex = 0;
for (const character of haystack) {
if (character === needle[queryIndex]) queryIndex += 1;
if (queryIndex === needle.length) return true;
}
return false;
};
/**
* The options a searchable list registers, filtered by its query, with the
* active option resolved during render and kept scrolled into view. Shared by
* Combobox and Multi Select, which differ only in what a pick does.
*/
export function useFilteredOptions({
open,
query,
value,
filter,
}: {
open: boolean;
query: string;
/** The selected value the cursor starts on when the list opens. */
value: string | undefined;
filter: OptionFilter;
}) {
const [items, setItems] = useState<Map<string, RegisteredItem>>(new Map());
const registerItem = useCallback((item: RegisteredItem) => {
setItems((current) => {
const existing = current.get(item.value);
if (
existing?.label === item.label &&
existing.disabled === item.disabled &&
existing.id === item.id &&
existing.ref === item.ref &&
existing.groupId === item.groupId &&
existing.keywords.join("\u0000") === item.keywords.join("\u0000")
) {
return current;
}
const next = new Map(current);
next.set(item.value, item);
return next;
});
}, []);
const unregisterItem = useCallback((itemValue: string) => {
setItems((current) => {
if (!current.has(itemValue)) return current;
const next = new Map(current);
next.delete(itemValue);
return next;
});
}, []);
// The query the list filters by. Closing clears `query`, but the panel is
// still on screen for its exit, so it keeps filtering by the query it was
// open with rather than repopulating mid-collapse. The input already reads
// `query` only while open, so nothing the user can see reads the other one.
const [openQuery, setOpenQuery] = useState(query);
if (open && openQuery !== query) setOpenQuery(query);
const listQuery = open ? query : openQuery;
const visibleItems = useMemo(
() =>
Array.from(items.values()).filter((item) =>
filter(item.value, listQuery, [item.label, ...item.keywords]),
),
[filter, items, listQuery],
);
const enabledVisibleItems = useMemo(
() => visibleItems.filter((item) => !item.disabled),
[visibleItems],
);
const visibleValues = useMemo(
() => new Set(visibleItems.map((item) => item.value)),
[visibleItems],
);
const visibleGroupIds = useMemo(
() => new Set(visibleItems.map((item) => item.groupId)),
[visibleItems],
);
const { activeValue, setActiveValue, moveActive } = useActiveOption({
open,
query: listQuery,
value,
enabledItems: enabledVisibleItems,
});
useEffect(() => {
if (!activeValue || !open) return;
const item = items.get(activeValue)?.ref.current;
const list = item?.closest<HTMLElement>("[role='listbox']");
if (!item || !list) return;
const itemRect = item.getBoundingClientRect();
const listRect = list.getBoundingClientRect();
if (itemRect.top < listRect.top) list.scrollTop -= listRect.top - itemRect.top;
else if (itemRect.bottom > listRect.bottom) list.scrollTop += itemRect.bottom - listRect.bottom;
}, [activeValue, items, open]);
return {
items,
registerItem,
unregisterItem,
listQuery,
visibleValues,
visibleGroupIds,
visibleCount: visibleItems.length,
activeValue,
setActiveValue,
moveActive,
activeItemId: activeValue ? items.get(activeValue)?.id : undefined,
};
}
"use client";
import { motion } from "motion/react";
import {
type CSSProperties,
type ReactNode,
type RefObject,
useEffect,
useLayoutEffect,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { usePopoverPortalPosition } from "@/components/motion/popover-position";
import { SPRING_MORPH } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type ListboxPanelSide = "top" | "bottom";
export type ListboxPanelAlign = "start" | "center" | "end";
const VIEWPORT_PADDING = 8;
export interface ListboxPanelPlacement {
/** Preferred side of the field to open on. Default: "bottom" */
side?: ListboxPanelSide;
/** Horizontal alignment against the field. Default: "start" */
align?: ListboxPanelAlign;
/** Gap between the field and the panel, in px. Default: 6 */
sideOffset?: number;
/** Flip to the other side when there is more room there. Default: true */
avoidCollisions?: boolean;
/** Classes merged onto the panel element. */
className?: string;
}
/**
* The portaled panel Combobox and Multi Select open into: anchored to the
* field, flipped to the side with room, and revealed from the field's edge on
* one spring. Each component passes its own open state and refs, and `name` keeps
* its `data-<name>-content` attribute and `--<name>-trigger-width` variable.
*/
export function ListboxPanel({
name,
open,
reduce,
triggerRef,
contentRef,
children,
side = "bottom",
align = "start",
sideOffset = 6,
avoidCollisions = true,
className,
}: ListboxPanelPlacement & {
name: "combobox" | "multi-select";
open: boolean;
reduce: boolean;
triggerRef: RefObject<HTMLDivElement | null>;
contentRef: RefObject<HTMLDivElement | null>;
children: ReactNode;
}) {
const measureRef = useRef<HTMLDivElement>(null);
const [portalReady, setPortalReady] = useState(false);
const [actualSide, setActualSide] = useState<ListboxPanelSide>(side);
const [morphReady, setMorphReady] = useState(false);
// Fully closed: the close animation has finished, or nothing has opened yet.
const [settledClosed, setSettledClosed] = useState(!open);
if (open && settledClosed) setSettledClosed(false);
const layout = usePopoverPortalPosition(triggerRef, measureRef, portalReady);
useEffect(() => setPortalReady(true), []);
useLayoutEffect(() => {
if (!portalReady) return;
const readyFrame = requestAnimationFrame(() => setMorphReady(true));
return () => cancelAnimationFrame(readyFrame);
}, [portalReady]);
useLayoutEffect(() => {
// Preserve the resolved side during exit, so top panels close upward. Once
// closed it follows the field again, so the next reveal starts from the
// edge the panel will open on.
if (!layout || (!open && !settledClosed)) return;
if (!avoidCollisions) {
setActualSide(side);
return;
}
const below = window.innerHeight - (layout.trigger.top + layout.trigger.height);
const above = layout.trigger.top;
if (side === "bottom" && below < layout.content.height + sideOffset && above > below)
setActualSide("top");
else if (side === "top" && above < layout.content.height + sideOffset && below > above)
setActualSide("bottom");
else setActualSide(side);
}, [avoidCollisions, open, settledClosed, layout, side, sideOffset]);
if (!portalReady) return null;
const triggerLeft = layout?.trigger.left ?? 0;
const triggerWidth = layout?.trigger.width ?? 0;
const contentWidth = layout?.content.width ?? triggerWidth;
const desiredLeft =
align === "end"
? triggerLeft + triggerWidth - contentWidth
: align === "center"
? triggerLeft + (triggerWidth - contentWidth) / 2
: triggerLeft;
const maxLeft = Math.max(VIEWPORT_PADDING, window.innerWidth - contentWidth - VIEWPORT_PADDING);
const left = Math.min(Math.max(desiredLeft, VIEWPORT_PADDING), maxLeft);
const transition = reduce || !morphReady ? { duration: 0 } : SPRING_MORPH;
// Revealed from the field's edge by a clip, so the panel keeps its size and
// nothing reflows while it opens. Percentages throughout, so motion can
// interpolate every edge.
const clipClosed =
actualSide === "bottom" ? "inset(0% 0% 100% 0% round 16px)" : "inset(100% 0% 0% 0% round 16px)";
const clipOpen = "inset(0% 0% 0% 0% round 16px)";
return createPortal(
<motion.div
ref={contentRef}
{...{ [`data-${name}-content`]: "" }}
data-side={actualSide}
aria-hidden={!open}
inert={!open}
initial={false}
animate={{
clipPath: open ? clipOpen : clipClosed,
opacity: open ? 1 : 0,
y: open ? (actualSide === "bottom" ? sideOffset : -sideOffset) : 0,
}}
transition={transition}
onAnimationComplete={() => {
if (!open) setSettledClosed(true);
}}
style={
{
left,
top:
actualSide === "bottom" && layout ? layout.trigger.top + layout.trigger.height : undefined,
bottom: actualSide === "top" && layout ? window.innerHeight - layout.trigger.top : undefined,
minWidth: triggerWidth,
pointerEvents: open ? "auto" : "none",
transformOrigin: actualSide === "bottom" ? "top" : "bottom",
visibility: layout ? "visible" : "hidden",
"--listbox-trigger-width": `${triggerWidth}px`,
[`--${name}-trigger-width`]: `${triggerWidth}px`,
} as CSSProperties
}
className={cn(
"fixed z-[9999] w-(--listbox-trigger-width) overflow-hidden rounded-2xl border border-border bg-background text-popover-foreground outline-none will-change-[clip-path,transform]",
className,
)}
>
<motion.div ref={measureRef} initial={false} animate={{ opacity: open ? 1 : 0 }} transition={transition}>
{children}
</motion.div>
</motion.div>,
document.body,
);
}
"use client";
import { useCallback, useLayoutEffect, useRef, useState } from "react";
/**
* Where the keyboard or the pointer last moved to, stamped with the query it
* was placed under. Which option is *active* is resolved from this during
* render, never in an effect: a passive effect runs after the commit, so a list
* would briefly have none of its options active, and a key arriving in that
* window would move from nowhere onto the row it was already about to
* highlight.
*/
type ActiveCursor = { value: string; query: string };
type Options = {
query: string;
value: string | undefined;
/** The enabled, visible options in list order - all this hook reads of them. */
enabledItems: readonly { value: string }[];
};
const isEnabled = (
enabledItems: Options["enabledItems"],
candidate: string | undefined,
): candidate is string =>
candidate !== undefined && enabledItems.some((i) => i.value === candidate);
/**
* The cursor's option, or null once the query or the result set it was placed
* in has changed. A cursor that outlived either would steal Enter from the row
* the user is aiming at. The result-set half costs something: a live search
* that blanks its rows while fetching and returns the same ones loses the moved
* highlight. That is deliberate - a highlight visibly back at the top beats one
* silently in the wrong place.
*
* It is stamped with the query rather than with the identity of the visible
* list because callers routinely pass an inline `filter`, which makes that list
* a fresh array on every render.
*/
function liveCursorValue(cursor: ActiveCursor | null, options: Options) {
if (cursor === null || cursor.query !== options.query) return null;
return isEnabled(options.enabledItems, cursor.value) ? cursor.value : null;
}
/**
* Where the highlight sits with no live cursor: the selection if it can be
* selected, otherwise the first option that can. Only enabled options qualify -
* an active disabled option would point `aria-activedescendant` at a row Enter
* then refuses to select.
*/
function fallbackActive({ value, enabledItems }: Options) {
return isEnabled(enabledItems, value) ? value : (enabledItems[0]?.value ?? null);
}
/** The active option, from a cursor that may or may not still be live. */
const resolveActive = (cursor: ActiveCursor | null, options: Options) =>
liveCursorValue(cursor, options) ?? fallbackActive(options);
export function useActiveOption({ open, ...options }: Options & { open: boolean }) {
const { query, value, enabledItems } = options;
const [cursor, setCursor] = useState<ActiveCursor | null>(null);
const live = liveCursorValue(cursor, options);
// Cleared rather than ignored: React re-runs this render with the cursor
// gone, so a value that reappears later cannot revive it.
if (cursor !== null && live === null) setCursor(null);
const derived = live ?? fallbackActive(options);
// Nothing is active until the list has been opened once. After that the
// resolution above is already stable across a close - the list keeps
// filtering by the query it was open with - so the highlight holds its row
// through the exit without being frozen separately.
const [opened, setOpened] = useState(open);
if (open && !opened) setOpened(true);
const activeValue = opened ? derived : null;
// Both callbacks keep one identity for the life of the component, and read
// the list through a ref to do it. A caller will put them in a `useMemo` or
// an effect's dependencies - the exhaustive-deps rule makes it - and
// `enabledItems` is a fresh array on every render for any consumer passing an
// inline `filter`, so a callback keyed to it would be rebuilt every render.
// Written after commit rather than during render: a render React discards
// still runs the component body, and a handler reading this in that window
// would step against a list the committed tree does not have.
const latest = useRef({ open, query, value, enabledItems });
useLayoutEffect(() => {
latest.current = { open, query, value, enabledItems };
});
const setActiveValue = useCallback((next: string | null) => {
setCursor(
next === null ? null : { value: next, query: latest.current.query },
);
}, []);
// Steps from the option the cursor really resolves to, inside the update, so
// that two keys landing in one batch move two rows rather than one.
const moveActive = useCallback(
(direction: 1 | -1 | "first" | "last") => {
const options = latest.current;
// While closed the list is still filtering by the query it was open
// with, so a step taken now would be measured against rows the next
// render replaces. Opening is the caller's job; stepping waits for it.
if (!options.open) return;
const rows = options.enabledItems;
const last = rows.length - 1;
if (last < 0) {
setCursor(null);
return;
}
setCursor((current) => {
// `resolveActive` always lands on a member of `enabledItems` once the
// list is non-empty, which the early return above guarantees, so there
// is always a row to step from.
const from = resolveActive(current, options);
const at = rows.findIndex((item) => item.value === from);
const index =
direction === "first"
? 0
: direction === "last"
? last
: (at + direction + rows.length) % rows.length;
return { value: rows[index].value, query: options.query };
});
},
[],
);
return { activeValue, setActiveValue, moveActive };
}
"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;
}
side?"top" | "bottom"Preferred side of the field to open on. Default: "bottom"
bottomalign?"center" | "end" | "start"Horizontal alignment against the field. Default: "start"
startsideOffset?numberGap between the field and the panel, in px. Default: 6
6avoidCollisions?booleanFlip to the other side when there is more room there. Default: true
trueclassName?stringClasses merged onto the panel element.
value?string[]The selected values, for controlled use.
defaultValue?string[]The initial selected values when uncontrolled. Default: []
[]onValueChange?((value: string[]) => void)Called with the new list of values when an option is added or removed.
open?booleanWhether the list is open, for controlled use.
defaultOpen?booleanWhether the list starts open when uncontrolled. Default: false
falseonOpenChange?((open: boolean) => void)Called with the new state when the list opens or closes.
query?stringThe search text, for controlled use.
defaultQuery?stringThe initial search text when uncontrolled. Default: ""
onQueryChange?((query: string) => void)Called with the new text when the search input changes.
filter?OptionFilterDecides which options match the search text.
(value, query, keywords) => {
const needle = query.trim().toLocaleLowerCase();
if (!needle) return true;
const haystack = [value, ...keywords].join(" ").toLocaleLowerCase();
let queryIndex = 0;
for (const character of haystack) {
if (character === needle[queryIndex]) queryIndex += 1;
if (queryIndex === needle.length) return true;
}
return false;
}disabled?booleanBlocks opening and changing the selection. Default: false
falseclassName?stringClasses merged onto the root element.
labels?Partial<{ valuePlaceholder: string; removeValue: string; inputLabel: string; inputPlaceholder: string; listLabel: string; empty: string; }>Override any built-in string. `{label}` fills the option label.
valuestringThe option's value, added to or removed from the selection.
textValue?stringText for search and the trigger chip when the label is not plain text.
keywords?string[]Extra words that match this option in search.
[]disabled?booleanKeeps the option visible but not selectable. Default: false
falseonSelect?((value: string) => void)Called with the option's value when it is clicked, before it toggles.
className?stringClasses merged onto the option row.
ariaLabel?stringAccessible name for the listbox. Default: "Options"
className?stringClasses merged onto the scrolling listbox.
ref?Ref<HTMLInputElement>Ref to the search input element.
showIcon?booleanShows a search icon before the input. Default: false
falseclassName?stringClasses merged onto the root element.
Combobox
Searchable combobox with a morphing portal, grouped filtering, keyboard navigation, and controlled or uncontrolled state.
Select
Composable select primitives whose panel unfolds out of the trigger on one spring and pulls away into its own pill, plus a Morph variant where the trigger grows into the panel via shared layout.
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