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.
Select
select.tsxComposable primitives (Select, SelectTrigger, SelectValue, SelectContent, SelectItem); the panel pinches off the trigger and separates, with a short, shared row reveal. Position-aware (opens upward when needed).
"use client";
import { useState } from "react";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/motion/select";
export function SelectPreview() {
const [value, setValue] = useState("next");
return (
<div className="w-56">
<Select value={value} onValueChange={setValue}>
<SelectTrigger>
<SelectValue placeholder="Pick a framework" />
</SelectTrigger>
<SelectContent>
<SelectItem value="next">Next.js</SelectItem>
<SelectItem value="remix">Remix</SelectItem>
<SelectItem value="astro">Astro</SelectItem>
<SelectItem value="vite">Vite</SelectItem>
</SelectContent>
</Select>
</div>
);
}
"use client";
// beui.dev/components/motion/select
import { Check, ChevronDown } from "lucide-react";
import {
animate,
type MotionValue,
motion,
useMotionValue,
useMotionValueEvent,
useReducedMotion,
useTransform,
type Variants,
} from "motion/react";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
// One progress value drives the surface, gap, corners and chevron. This short
// spring suits the full reveal distance; each reader clamps its small internal
// overshoot, so all visible endpoints settle together. Rows share a short
// reveal so long lists have no late entries.
const UNFOLD_SPRING = {
type: "spring",
visualDuration: 0.2,
bounce: 0.12,
} as const;
// Exits are faster than entrances: the panel folds back on a short ease.
const UNFOLD_EXIT = { duration: 0.2, ease: EASE_OUT } as const;
const RADIUS = 12;
// How far the open panel sits from the trigger once it has pulled away.
const GAP = 8;
// The surface starts as a thin lip flush against the trigger's edge.
const LIP = 8;
const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
const ITEM_VARIANTS: Variants = {
// A shared short reveal keeps late rows in long, scrolled lists ready with
// the surface. Per-index staggering can delay visible rows by over a second.
hidden: { opacity: 0, y: -4, transition: { duration: 0.08, ease: EASE_OUT } },
show: { opacity: 1, y: 0, transition: { duration: 0.12, ease: EASE_OUT } },
};
type Placement = "bottom" | "top";
interface SelectContextValue {
value: string | undefined;
open: boolean;
setOpen: (open: boolean) => void;
select: (value: string) => void;
register: (value: string, label: string) => void;
unregister: (value: string) => void;
labelFor: (value: string | undefined) => string | undefined;
reduce: boolean;
progress: MotionValue<number>;
triggerId: string;
listId: string;
disabled: boolean;
placement: Placement;
setPlacement: (p: Placement) => void;
}
const SelectContext = createContext<SelectContextValue | null>(null);
function useSelectContext(component: string) {
const ctx = useContext(SelectContext);
if (!ctx) throw new Error(`${component} must be used within <Select>`);
return ctx;
}
export interface SelectProps {
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
/**
* Controlled open state of the panel. A layout that stacks selects can hold
* this to keep exactly one panel open — the panel is absolutely positioned
* inside its field, so two open at once paint over each other's options.
*/
open?: boolean;
/** Uncontrolled initial open state. Default false. */
defaultOpen?: boolean;
/**
* Fires whenever the panel opens or closes. The panel is absolutely
* positioned inside the field, so a layout that stacks selects has to know
* which one is open to paint it above its neighbours.
*/
onOpenChange?: (open: boolean) => void;
disabled?: boolean;
className?: string;
children: ReactNode;
}
export function Select({
value,
defaultValue,
onValueChange,
open: openProp,
defaultOpen = false,
onOpenChange,
disabled = false,
className,
children,
}: SelectProps) {
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const rootRef = useRef<HTMLDivElement>(null);
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const [internal, setInternal] = useState(defaultValue);
const [labels, setLabels] = useState<Map<string, string>>(new Map());
const [placement, setPlacement] = useState<Placement>("bottom");
const controlled = value !== undefined;
const current = controlled ? value : internal;
const openControlled = openProp !== undefined;
const open = openControlled ? openProp : internalOpen;
const progress = useMotionValue(open ? 1 : 0);
const setOpen = useCallback(
(next: boolean) => {
if (!openControlled) setInternalOpen(next);
onOpenChange?.(next);
},
[onOpenChange, openControlled],
);
const select = useCallback(
(next: string) => {
if (!controlled) setInternal(next);
onValueChange?.(next);
setOpen(false);
},
[controlled, onValueChange, setOpen],
);
const register = useCallback((v: string, label: string) => {
setLabels((m) => (m.get(v) === label ? m : new Map(m).set(v, label)));
}, []);
const unregister = useCallback((v: string) => {
setLabels((m) => {
if (!m.has(v)) return m;
const next = new Map(m);
next.delete(v);
return next;
});
}, []);
// Reduced motion has no travel, so the progress only carries a short fade.
useEffect(() => {
const animation = animate(
progress,
open ? 1 : 0,
reduce ? { duration: 0.12 } : open ? UNFOLD_SPRING : UNFOLD_EXIT,
);
return () => animation.stop();
}, [open, progress, reduce]);
// close on outside pointer / escape
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => e.key === "Escape" && setOpen(false);
const onPointer = (e: PointerEvent) => {
if (rootRef.current && !rootRef.current.contains(e.target as Node))
setOpen(false);
};
window.addEventListener("keydown", onKey);
window.addEventListener("pointerdown", onPointer);
return () => {
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer);
};
}, [open, setOpen]);
const ctx = useMemo<SelectContextValue>(
() => ({
value: current,
open,
setOpen,
select,
register,
unregister,
labelFor: (v) => (v === undefined ? undefined : labels.get(v)),
reduce,
progress,
triggerId: `${baseId}-trigger`,
listId: `${baseId}-list`,
disabled,
placement,
setPlacement,
}),
[
current,
open,
setOpen,
select,
register,
unregister,
labels,
reduce,
progress,
baseId,
disabled,
placement,
],
);
return (
<SelectContext.Provider value={ctx}>
<div ref={rootRef} className={cn("relative", className)}>
{children}
</div>
</SelectContext.Provider>
);
}
export interface SelectTriggerProps {
className?: string;
children: ReactNode;
}
export function SelectTrigger({ className, children }: SelectTriggerProps) {
const ctx = useSelectContext("SelectTrigger");
const isTop = ctx.placement === "top";
// The edge facing the panel flattens while the panel is attached to it and
// rounds back as the panel pulls away — the two pinch apart — on the same
// curve the panel moves on. The far edge stays rounded.
const nearRadius = useTransform(
ctx.progress,
[0, 0.2, 0.4, 1],
[RADIUS, 0, 0, RADIUS],
);
const rotate = useTransform(ctx.progress, (p) =>
ctx.reduce ? (ctx.open ? 180 : 0) : Math.min(1, Math.max(0, p)) * 180,
);
return (
<motion.button
type="button"
id={ctx.triggerId}
disabled={ctx.disabled}
aria-haspopup="listbox"
aria-expanded={ctx.open}
aria-controls={ctx.listId}
onClick={() => ctx.setOpen(!ctx.open)}
style={{
borderTopLeftRadius: ctx.reduce || !isTop ? RADIUS : nearRadius,
borderTopRightRadius: ctx.reduce || !isTop ? RADIUS : nearRadius,
borderBottomLeftRadius: ctx.reduce || isTop ? RADIUS : nearRadius,
borderBottomRightRadius: ctx.reduce || isTop ? RADIUS : nearRadius,
}}
className={cn(
"relative z-10 flex w-full items-center justify-between gap-2 border border-border bg-background px-3 py-2 text-sm 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,
)}
>
{children}
<motion.span
aria-hidden
style={{ rotate }}
className="text-muted-foreground"
>
<ChevronDown className="h-4 w-4" />
</motion.span>
</motion.button>
);
}
export interface SelectValueProps {
placeholder?: string;
className?: string;
}
export function SelectValue({ placeholder, className }: SelectValueProps) {
const ctx = useSelectContext("SelectValue");
const label = ctx.labelFor(ctx.value);
return (
<span
className={cn(label ? "text-foreground" : "text-muted-foreground", className)}
>
{label ?? placeholder ?? "Select"}
</span>
);
}
export interface SelectContentProps {
className?: string;
children: ReactNode;
}
export function SelectContent({ className, children }: SelectContentProps) {
const ctx = useSelectContext("SelectContent");
const panelRef = useRef<HTMLDivElement>(null);
const [height, setHeight] = useState(0);
const { open, progress, reduce, setPlacement } = ctx;
// Keep descendants laid out while hidden: display:none resets nested
// scrollers in Chromium. Collapse only the hidden outer footprint after
// exit so it cannot extend page scrolling. Opening restores the full box
// before measurement or focus; neither layout change is animated.
const [exiting, setExiting] = useState(false);
const [wasOpen, setWasOpen] = useState(open);
if (open !== wasOpen) {
setWasOpen(open);
if (!open) setExiting(true);
}
const present = open || exiting;
useMotionValueEvent(progress, "animationComplete", () => {
if (progress.get() === 0) setExiting(false);
});
useLayoutEffect(() => {
const node = panelRef.current;
if (!node || !present) return;
const measure = () => setHeight(node.offsetHeight);
measure();
const observer = new ResizeObserver(measure);
observer.observe(node);
return () => observer.disconnect();
}, [present]);
// On open, flip upward when there isn't room below and there's more above.
useLayoutEffect(() => {
if (!open) return;
const trigger = document.getElementById(ctx.triggerId);
const node = panelRef.current;
if (!trigger || !node) return;
const rect = trigger.getBoundingClientRect();
const h = node.offsetHeight;
const below = window.innerHeight - rect.bottom;
const above = rect.top;
setPlacement(below < h + 16 && above > below ? "top" : "bottom");
}, [open, ctx.triggerId, setPlacement]);
const isTop = ctx.placement === "top";
// Reveal a full-size panel from its near edge. No ancestor scales the list,
// so rows, borders and shadow keep their natural thickness. The clip and
// corner writes can paint; only the gap uses a transform. All read one
// progress value, with no animated layout properties.
const ready = height > 0 && !reduce;
const fromY = ready ? (isTop ? GAP : -GAP) : 0;
const detach = useTransform(progress, [0.4, 1], [0, 1]);
const y = useTransform(detach, (d) => lerp(fromY, 0, d));
const nearRadius = useTransform(detach, (d) => (ready ? RADIUS * d : RADIUS));
const borderRadius = useTransform(nearRadius, (near) =>
isTop
? `${RADIUS}px ${RADIUS}px ${near}px ${near}px`
: `${near}px ${near}px ${RADIUS}px ${RADIUS}px`,
);
const clipPath = useTransform([progress, nearRadius], ([p, near]: number[]) => {
if (!ready) return "none";
// Clamp overshoot so the clip never extends into the trigger or exposes
// overflowing children. At rest remove it so the native shadow is whole.
const reveal = Math.min(1, Math.max(0, p));
if (reveal === 1) return "none";
const hidden = Math.max(0, (height - LIP) * (1 - reveal));
const inset = isTop ? `${hidden}px 0 0 0` : `0 0 ${hidden}px 0`;
const corners = isTop
? `${RADIUS}px ${RADIUS}px ${near}px ${near}px`
: `${near}px ${near}px ${RADIUS}px ${RADIUS}px`;
return `inset(${inset} round ${corners})`;
});
// The surface materialises over its first frames rather than popping in as
// a lip; with reduced motion the fade is the whole entrance.
const opacity = useTransform(progress, reduce ? [0, 1] : [0, 0.12], [0, 1]);
return (
<motion.div
ref={panelRef}
id={ctx.listId}
role="listbox"
aria-labelledby={ctx.triggerId}
aria-hidden={!open}
inert={!open}
style={{
visibility: present ? undefined : "hidden",
maxHeight: present ? undefined : 0,
borderWidth: present ? undefined : 0,
y,
clipPath,
borderRadius,
opacity,
pointerEvents: open ? "auto" : "none",
marginTop: isTop ? 0 : GAP,
marginBottom: isTop ? GAP : 0,
}}
// flush against the trigger, then separates into its own rounded pill;
// sits above or below depending on available space
className={cn(
"absolute left-0 right-0 z-20 overflow-hidden border border-border bg-background shadow-lg",
isTop ? "bottom-full" : "top-full",
className,
)}
>
<motion.div
initial={false}
animate={open ? "show" : "hidden"}
className="p-1"
>
{children}
</motion.div>
</motion.div>
);
}
export interface SelectItemProps {
value: string;
disabled?: boolean;
className?: string;
children: ReactNode;
}
export function SelectItem({
value,
disabled = false,
className,
children,
}: SelectItemProps) {
const ctx = useSelectContext("SelectItem");
const selected = ctx.value === value;
const label = typeof children === "string" ? children : value;
useLayoutEffect(() => {
ctx.register(value, label);
return () => ctx.unregister(value);
}, [ctx.register, ctx.unregister, value, label]);
return (
<motion.div variants={ctx.reduce ? undefined : ITEM_VARIANTS}>
<button
type="button"
role="option"
aria-selected={selected}
disabled={disabled}
onClick={() => ctx.select(value)}
className={cn(
"flex w-full items-center justify-between gap-2 rounded-lg px-2.5 py-1.5 text-left text-sm outline-none transition-colors",
selected
? "bg-muted text-foreground"
: "text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:bg-muted",
"disabled:pointer-events-none disabled:opacity-50",
className,
)}
>
{children}
{selected ? <Check className="h-3.5 w-3.5 shrink-0" /> : null}
</button>
</motion.div>
);
}
Install
shadcn init? You are set. 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;
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;
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
Copy the source code
"use client";
// beui.dev/components/motion/select
import { Check, ChevronDown } from "lucide-react";
import {
animate,
type MotionValue,
motion,
useMotionValue,
useMotionValueEvent,
useReducedMotion,
useTransform,
type Variants,
} from "motion/react";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
// One progress value drives the surface, gap, corners and chevron. This short
// spring suits the full reveal distance; each reader clamps its small internal
// overshoot, so all visible endpoints settle together. Rows share a short
// reveal so long lists have no late entries.
const UNFOLD_SPRING = {
type: "spring",
visualDuration: 0.2,
bounce: 0.12,
} as const;
// Exits are faster than entrances: the panel folds back on a short ease.
const UNFOLD_EXIT = { duration: 0.2, ease: EASE_OUT } as const;
const RADIUS = 12;
// How far the open panel sits from the trigger once it has pulled away.
const GAP = 8;
// The surface starts as a thin lip flush against the trigger's edge.
const LIP = 8;
const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
const ITEM_VARIANTS: Variants = {
// A shared short reveal keeps late rows in long, scrolled lists ready with
// the surface. Per-index staggering can delay visible rows by over a second.
hidden: { opacity: 0, y: -4, transition: { duration: 0.08, ease: EASE_OUT } },
show: { opacity: 1, y: 0, transition: { duration: 0.12, ease: EASE_OUT } },
};
type Placement = "bottom" | "top";
interface SelectContextValue {
value: string | undefined;
open: boolean;
setOpen: (open: boolean) => void;
select: (value: string) => void;
register: (value: string, label: string) => void;
unregister: (value: string) => void;
labelFor: (value: string | undefined) => string | undefined;
reduce: boolean;
progress: MotionValue<number>;
triggerId: string;
listId: string;
disabled: boolean;
placement: Placement;
setPlacement: (p: Placement) => void;
}
const SelectContext = createContext<SelectContextValue | null>(null);
function useSelectContext(component: string) {
const ctx = useContext(SelectContext);
if (!ctx) throw new Error(`${component} must be used within <Select>`);
return ctx;
}
export interface SelectProps {
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
/**
* Controlled open state of the panel. A layout that stacks selects can hold
* this to keep exactly one panel open — the panel is absolutely positioned
* inside its field, so two open at once paint over each other's options.
*/
open?: boolean;
/** Uncontrolled initial open state. Default false. */
defaultOpen?: boolean;
/**
* Fires whenever the panel opens or closes. The panel is absolutely
* positioned inside the field, so a layout that stacks selects has to know
* which one is open to paint it above its neighbours.
*/
onOpenChange?: (open: boolean) => void;
disabled?: boolean;
className?: string;
children: ReactNode;
}
export function Select({
value,
defaultValue,
onValueChange,
open: openProp,
defaultOpen = false,
onOpenChange,
disabled = false,
className,
children,
}: SelectProps) {
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const rootRef = useRef<HTMLDivElement>(null);
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const [internal, setInternal] = useState(defaultValue);
const [labels, setLabels] = useState<Map<string, string>>(new Map());
const [placement, setPlacement] = useState<Placement>("bottom");
const controlled = value !== undefined;
const current = controlled ? value : internal;
const openControlled = openProp !== undefined;
const open = openControlled ? openProp : internalOpen;
const progress = useMotionValue(open ? 1 : 0);
const setOpen = useCallback(
(next: boolean) => {
if (!openControlled) setInternalOpen(next);
onOpenChange?.(next);
},
[onOpenChange, openControlled],
);
const select = useCallback(
(next: string) => {
if (!controlled) setInternal(next);
onValueChange?.(next);
setOpen(false);
},
[controlled, onValueChange, setOpen],
);
const register = useCallback((v: string, label: string) => {
setLabels((m) => (m.get(v) === label ? m : new Map(m).set(v, label)));
}, []);
const unregister = useCallback((v: string) => {
setLabels((m) => {
if (!m.has(v)) return m;
const next = new Map(m);
next.delete(v);
return next;
});
}, []);
// Reduced motion has no travel, so the progress only carries a short fade.
useEffect(() => {
const animation = animate(
progress,
open ? 1 : 0,
reduce ? { duration: 0.12 } : open ? UNFOLD_SPRING : UNFOLD_EXIT,
);
return () => animation.stop();
}, [open, progress, reduce]);
// close on outside pointer / escape
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => e.key === "Escape" && setOpen(false);
const onPointer = (e: PointerEvent) => {
if (rootRef.current && !rootRef.current.contains(e.target as Node))
setOpen(false);
};
window.addEventListener("keydown", onKey);
window.addEventListener("pointerdown", onPointer);
return () => {
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer);
};
}, [open, setOpen]);
const ctx = useMemo<SelectContextValue>(
() => ({
value: current,
open,
setOpen,
select,
register,
unregister,
labelFor: (v) => (v === undefined ? undefined : labels.get(v)),
reduce,
progress,
triggerId: `${baseId}-trigger`,
listId: `${baseId}-list`,
disabled,
placement,
setPlacement,
}),
[
current,
open,
setOpen,
select,
register,
unregister,
labels,
reduce,
progress,
baseId,
disabled,
placement,
],
);
return (
<SelectContext.Provider value={ctx}>
<div ref={rootRef} className={cn("relative", className)}>
{children}
</div>
</SelectContext.Provider>
);
}
export interface SelectTriggerProps {
className?: string;
children: ReactNode;
}
export function SelectTrigger({ className, children }: SelectTriggerProps) {
const ctx = useSelectContext("SelectTrigger");
const isTop = ctx.placement === "top";
// The edge facing the panel flattens while the panel is attached to it and
// rounds back as the panel pulls away — the two pinch apart — on the same
// curve the panel moves on. The far edge stays rounded.
const nearRadius = useTransform(
ctx.progress,
[0, 0.2, 0.4, 1],
[RADIUS, 0, 0, RADIUS],
);
const rotate = useTransform(ctx.progress, (p) =>
ctx.reduce ? (ctx.open ? 180 : 0) : Math.min(1, Math.max(0, p)) * 180,
);
return (
<motion.button
type="button"
id={ctx.triggerId}
disabled={ctx.disabled}
aria-haspopup="listbox"
aria-expanded={ctx.open}
aria-controls={ctx.listId}
onClick={() => ctx.setOpen(!ctx.open)}
style={{
borderTopLeftRadius: ctx.reduce || !isTop ? RADIUS : nearRadius,
borderTopRightRadius: ctx.reduce || !isTop ? RADIUS : nearRadius,
borderBottomLeftRadius: ctx.reduce || isTop ? RADIUS : nearRadius,
borderBottomRightRadius: ctx.reduce || isTop ? RADIUS : nearRadius,
}}
className={cn(
"relative z-10 flex w-full items-center justify-between gap-2 border border-border bg-background px-3 py-2 text-sm 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,
)}
>
{children}
<motion.span
aria-hidden
style={{ rotate }}
className="text-muted-foreground"
>
<ChevronDown className="h-4 w-4" />
</motion.span>
</motion.button>
);
}
export interface SelectValueProps {
placeholder?: string;
className?: string;
}
export function SelectValue({ placeholder, className }: SelectValueProps) {
const ctx = useSelectContext("SelectValue");
const label = ctx.labelFor(ctx.value);
return (
<span
className={cn(label ? "text-foreground" : "text-muted-foreground", className)}
>
{label ?? placeholder ?? "Select"}
</span>
);
}
export interface SelectContentProps {
className?: string;
children: ReactNode;
}
export function SelectContent({ className, children }: SelectContentProps) {
const ctx = useSelectContext("SelectContent");
const panelRef = useRef<HTMLDivElement>(null);
const [height, setHeight] = useState(0);
const { open, progress, reduce, setPlacement } = ctx;
// Keep descendants laid out while hidden: display:none resets nested
// scrollers in Chromium. Collapse only the hidden outer footprint after
// exit so it cannot extend page scrolling. Opening restores the full box
// before measurement or focus; neither layout change is animated.
const [exiting, setExiting] = useState(false);
const [wasOpen, setWasOpen] = useState(open);
if (open !== wasOpen) {
setWasOpen(open);
if (!open) setExiting(true);
}
const present = open || exiting;
useMotionValueEvent(progress, "animationComplete", () => {
if (progress.get() === 0) setExiting(false);
});
useLayoutEffect(() => {
const node = panelRef.current;
if (!node || !present) return;
const measure = () => setHeight(node.offsetHeight);
measure();
const observer = new ResizeObserver(measure);
observer.observe(node);
return () => observer.disconnect();
}, [present]);
// On open, flip upward when there isn't room below and there's more above.
useLayoutEffect(() => {
if (!open) return;
const trigger = document.getElementById(ctx.triggerId);
const node = panelRef.current;
if (!trigger || !node) return;
const rect = trigger.getBoundingClientRect();
const h = node.offsetHeight;
const below = window.innerHeight - rect.bottom;
const above = rect.top;
setPlacement(below < h + 16 && above > below ? "top" : "bottom");
}, [open, ctx.triggerId, setPlacement]);
const isTop = ctx.placement === "top";
// Reveal a full-size panel from its near edge. No ancestor scales the list,
// so rows, borders and shadow keep their natural thickness. The clip and
// corner writes can paint; only the gap uses a transform. All read one
// progress value, with no animated layout properties.
const ready = height > 0 && !reduce;
const fromY = ready ? (isTop ? GAP : -GAP) : 0;
const detach = useTransform(progress, [0.4, 1], [0, 1]);
const y = useTransform(detach, (d) => lerp(fromY, 0, d));
const nearRadius = useTransform(detach, (d) => (ready ? RADIUS * d : RADIUS));
const borderRadius = useTransform(nearRadius, (near) =>
isTop
? `${RADIUS}px ${RADIUS}px ${near}px ${near}px`
: `${near}px ${near}px ${RADIUS}px ${RADIUS}px`,
);
const clipPath = useTransform([progress, nearRadius], ([p, near]: number[]) => {
if (!ready) return "none";
// Clamp overshoot so the clip never extends into the trigger or exposes
// overflowing children. At rest remove it so the native shadow is whole.
const reveal = Math.min(1, Math.max(0, p));
if (reveal === 1) return "none";
const hidden = Math.max(0, (height - LIP) * (1 - reveal));
const inset = isTop ? `${hidden}px 0 0 0` : `0 0 ${hidden}px 0`;
const corners = isTop
? `${RADIUS}px ${RADIUS}px ${near}px ${near}px`
: `${near}px ${near}px ${RADIUS}px ${RADIUS}px`;
return `inset(${inset} round ${corners})`;
});
// The surface materialises over its first frames rather than popping in as
// a lip; with reduced motion the fade is the whole entrance.
const opacity = useTransform(progress, reduce ? [0, 1] : [0, 0.12], [0, 1]);
return (
<motion.div
ref={panelRef}
id={ctx.listId}
role="listbox"
aria-labelledby={ctx.triggerId}
aria-hidden={!open}
inert={!open}
style={{
visibility: present ? undefined : "hidden",
maxHeight: present ? undefined : 0,
borderWidth: present ? undefined : 0,
y,
clipPath,
borderRadius,
opacity,
pointerEvents: open ? "auto" : "none",
marginTop: isTop ? 0 : GAP,
marginBottom: isTop ? GAP : 0,
}}
// flush against the trigger, then separates into its own rounded pill;
// sits above or below depending on available space
className={cn(
"absolute left-0 right-0 z-20 overflow-hidden border border-border bg-background shadow-lg",
isTop ? "bottom-full" : "top-full",
className,
)}
>
<motion.div
initial={false}
animate={open ? "show" : "hidden"}
className="p-1"
>
{children}
</motion.div>
</motion.div>
);
}
export interface SelectItemProps {
value: string;
disabled?: boolean;
className?: string;
children: ReactNode;
}
export function SelectItem({
value,
disabled = false,
className,
children,
}: SelectItemProps) {
const ctx = useSelectContext("SelectItem");
const selected = ctx.value === value;
const label = typeof children === "string" ? children : value;
useLayoutEffect(() => {
ctx.register(value, label);
return () => ctx.unregister(value);
}, [ctx.register, ctx.unregister, value, label]);
return (
<motion.div variants={ctx.reduce ? undefined : ITEM_VARIANTS}>
<button
type="button"
role="option"
aria-selected={selected}
disabled={disabled}
onClick={() => ctx.select(value)}
className={cn(
"flex w-full items-center justify-between gap-2 rounded-lg px-2.5 py-1.5 text-left text-sm outline-none transition-colors",
selected
? "bg-muted text-foreground"
: "text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:bg-muted",
"disabled:pointer-events-none disabled:opacity-50",
className,
)}
>
{children}
{selected ? <Check className="h-3.5 w-3.5 shrink-0" /> : null}
</button>
</motion.div>
);
}
API Reference
Select
value?string—defaultValue?string—onValueChange?((value: string) => void)—open?booleanControlled open state of the panel. A layout that stacks selects can hold this to keep exactly one panel open — the panel is absolutely positioned inside its field, so two open at once paint over each other's options.
—defaultOpen?booleanUncontrolled initial open state. Default false.
falseonOpenChange?((open: boolean) => void)Fires whenever the panel opens or closes. The panel is absolutely positioned inside the field, so a layout that stacks selects has to know which one is open to paint it above its neighbours.
—disabled?booleanfalseclassName?string—SelectTrigger
className?string—SelectValue
placeholder?string—className?string—SelectContent
className?string—SelectItem
valuestring—disabled?booleanfalseclassName?string—Morph Select
select-morph.tsxComposable primitives (MorphSelect, MorphSelectTrigger, MorphSelectValue, MorphSelectContent, MorphSelectItem) where the trigger morphs into the panel via a shared layoutId — one continuous surface that grows open and shrinks back, never detaching.
"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 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
import { Check, ChevronDown } from "lucide-react";
import {
AnimatePresence,
motion,
type Transition,
useReducedMotion,
type Variants,
} from "motion/react";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { cn } from "@/lib/utils";
// Shared-layout morph: trigger box grows into the panel and back, one surface.
const MORPH: Transition = { type: "spring", duration: 0.5, bounce: 0.22 };
// Trigger and panel header share this row so the morph stays seamless.
const ROW = "flex w-full items-center justify-between gap-2 px-3.5 py-2.5 text-sm";
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;
setOpen: (open: boolean) => void;
select: (value: string) => void;
register: (value: string, label: string) => void;
unregister: (value: string) => void;
labelFor: (value: string | undefined) => string | undefined;
placeholder: string;
setPlaceholder: (p: string) => void;
reduce: boolean;
layoutId: string;
triggerId: string;
listId: string;
disabled: boolean;
}
const MorphContext = createContext<MorphContextValue | null>(null);
function useMorphContext(component: string) {
const ctx = useContext(MorphContext);
if (!ctx) throw new Error(`${component} must be used within <MorphSelect>`);
return ctx;
}
export interface MorphSelectProps {
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
disabled?: boolean;
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 gooey variant).
*/
export function MorphSelect({
value,
defaultValue,
onValueChange,
disabled = false,
className,
children,
}: MorphSelectProps) {
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const rootRef = useRef<HTMLDivElement>(null);
const [open, setOpen] = useState(false);
const [internal, setInternal] = useState(defaultValue);
// 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; count: number }>
>(new Map());
const [placeholder, setPlaceholder] = useState("Select");
const controlled = value !== undefined;
const current = controlled ? value : internal;
const select = useCallback(
(next: string) => {
if (!controlled) setInternal(next);
onValueChange?.(next);
setOpen(false);
},
[controlled, onValueChange],
);
const register = useCallback((v: string, label: string) => {
setLabels((m) => {
const next = new Map(m);
next.set(v, { label, 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, { label: entry.label, count: entry.count - 1 });
return next;
});
}, []);
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => e.key === "Escape" && setOpen(false);
const onPointer = (e: PointerEvent) => {
if (rootRef.current && !rootRef.current.contains(e.target as Node))
setOpen(false);
};
window.addEventListener("keydown", onKey);
window.addEventListener("pointerdown", onPointer);
return () => {
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer);
};
}, [open]);
const ctx = useMemo<MorphContextValue>(
() => ({
value: current,
open,
setOpen,
select,
register,
unregister,
labelFor: (v) => (v === undefined ? undefined : labels.get(v)?.label),
placeholder,
setPlaceholder,
reduce,
layoutId: `${baseId}-surface`,
triggerId: `${baseId}-trigger`,
listId: `${baseId}-list`,
disabled,
}),
[
current,
open,
select,
register,
unregister,
labels,
placeholder,
reduce,
baseId,
disabled,
],
);
return (
<MorphContext.Provider value={ctx}>
<div ref={rootRef} className={cn("relative", className)}>
{children}
</div>
</MorphContext.Provider>
);
}
export interface MorphSelectValueProps {
placeholder?: string;
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 {
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-xl border border-border")}
>
{children}
<ChevronDown className="h-4 w-4" />
</div>
<AnimatePresence initial={false} mode="popLayout">
{!ctx.open ? (
<motion.button
key="trigger"
layoutId={ctx.layoutId}
type="button"
id={ctx.triggerId}
disabled={ctx.disabled}
aria-haspopup="listbox"
aria-expanded={ctx.open}
aria-controls={ctx.listId}
onClick={() => ctx.setOpen(true)}
transition={ctx.reduce ? { duration: 0 } : MORPH}
style={{ borderRadius: 12 }}
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 {
className?: string;
children: ReactNode;
}
export function MorphSelectContent({
className,
children,
}: MorphSelectContentProps) {
const ctx = useMorphContext("MorphSelectContent");
const label = ctx.labelFor(ctx.value);
return (
<>
{/* always-mounted, hidden — keeps item label registrations alive while
closed so the trigger shows the selected value before first open */}
<div className="hidden">{children}</div>
<AnimatePresence initial={false} mode="popLayout">
{ctx.open ? (
<motion.div
key="panel"
layoutId={ctx.layoutId}
id={ctx.listId}
role="listbox"
aria-labelledby={ctx.triggerId}
transition={ctx.reduce ? { duration: 0 } : MORPH}
style={{ borderRadius: 12 }}
className={cn(
"absolute inset-x-0 top-0 z-30 overflow-hidden border border-border bg-background shadow-lg",
className,
)}
>
{/* header mirrors the trigger (continuous morph) and collapses the
panel back into the trigger when clicked */}
<motion.button
type="button"
layout="position"
aria-expanded
onClick={() => ctx.setOpen(false)}
className={cn(ROW, "outline-none")}
>
<span
className={cn(
"min-w-0 truncate",
label ? "text-foreground" : "text-muted-foreground",
)}
>
{label ?? ctx.placeholder}
</span>
<motion.span
animate={{ rotate: 180 }}
transition={ctx.reduce ? { duration: 0 } : MORPH}
className="text-muted-foreground"
>
<ChevronDown className="h-4 w-4" />
</motion.span>
</motion.button>
<div className="h-px bg-border" />
<motion.ul
initial="hidden"
animate="show"
variants={ctx.reduce ? undefined : LIST}
className="p-1"
>
{children}
</motion.ul>
</motion.div>
) : null}
</AnimatePresence>
</>
);
}
export interface MorphSelectItemProps {
value: string;
disabled?: boolean;
className?: string;
children: ReactNode;
}
export function MorphSelectItem({
value,
disabled = false,
className,
children,
}: MorphSelectItemProps) {
const ctx = useMorphContext("MorphSelectItem");
const selected = ctx.value === value;
const label = typeof children === "string" ? children : value;
useLayoutEffect(() => {
ctx.register(value, label);
return () => ctx.unregister(value);
}, [ctx.register, ctx.unregister, value, label]);
return (
<motion.li variants={ctx.reduce ? undefined : ITEM}>
<button
type="button"
role="option"
aria-selected={selected}
disabled={disabled}
onClick={() => ctx.select(value)}
className={cn(
"flex w-full items-center justify-between gap-2 rounded-lg px-2.5 py-1.5 text-left text-sm outline-none transition-colors",
selected
? "bg-muted text-foreground"
: "text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:bg-muted",
"disabled:pointer-events-none disabled:opacity-50",
className,
)}
>
{children}
{selected ? <Check className="h-3.5 w-3.5 shrink-0" /> : null}
</button>
</motion.li>
);
}
Install
shadcn init? You are set. Theme setupInstall dependencies
npm i clsx lucide-react motion tailwind-mergeAdd util file
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
Copy the source code
"use client";
// beui.dev/components/motion/select
import { Check, ChevronDown } from "lucide-react";
import {
AnimatePresence,
motion,
type Transition,
useReducedMotion,
type Variants,
} from "motion/react";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { cn } from "@/lib/utils";
// Shared-layout morph: trigger box grows into the panel and back, one surface.
const MORPH: Transition = { type: "spring", duration: 0.5, bounce: 0.22 };
// Trigger and panel header share this row so the morph stays seamless.
const ROW = "flex w-full items-center justify-between gap-2 px-3.5 py-2.5 text-sm";
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;
setOpen: (open: boolean) => void;
select: (value: string) => void;
register: (value: string, label: string) => void;
unregister: (value: string) => void;
labelFor: (value: string | undefined) => string | undefined;
placeholder: string;
setPlaceholder: (p: string) => void;
reduce: boolean;
layoutId: string;
triggerId: string;
listId: string;
disabled: boolean;
}
const MorphContext = createContext<MorphContextValue | null>(null);
function useMorphContext(component: string) {
const ctx = useContext(MorphContext);
if (!ctx) throw new Error(`${component} must be used within <MorphSelect>`);
return ctx;
}
export interface MorphSelectProps {
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
disabled?: boolean;
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 gooey variant).
*/
export function MorphSelect({
value,
defaultValue,
onValueChange,
disabled = false,
className,
children,
}: MorphSelectProps) {
const reduce = useReducedMotion() ?? false;
const baseId = useId();
const rootRef = useRef<HTMLDivElement>(null);
const [open, setOpen] = useState(false);
const [internal, setInternal] = useState(defaultValue);
// 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; count: number }>
>(new Map());
const [placeholder, setPlaceholder] = useState("Select");
const controlled = value !== undefined;
const current = controlled ? value : internal;
const select = useCallback(
(next: string) => {
if (!controlled) setInternal(next);
onValueChange?.(next);
setOpen(false);
},
[controlled, onValueChange],
);
const register = useCallback((v: string, label: string) => {
setLabels((m) => {
const next = new Map(m);
next.set(v, { label, 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, { label: entry.label, count: entry.count - 1 });
return next;
});
}, []);
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => e.key === "Escape" && setOpen(false);
const onPointer = (e: PointerEvent) => {
if (rootRef.current && !rootRef.current.contains(e.target as Node))
setOpen(false);
};
window.addEventListener("keydown", onKey);
window.addEventListener("pointerdown", onPointer);
return () => {
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer);
};
}, [open]);
const ctx = useMemo<MorphContextValue>(
() => ({
value: current,
open,
setOpen,
select,
register,
unregister,
labelFor: (v) => (v === undefined ? undefined : labels.get(v)?.label),
placeholder,
setPlaceholder,
reduce,
layoutId: `${baseId}-surface`,
triggerId: `${baseId}-trigger`,
listId: `${baseId}-list`,
disabled,
}),
[
current,
open,
select,
register,
unregister,
labels,
placeholder,
reduce,
baseId,
disabled,
],
);
return (
<MorphContext.Provider value={ctx}>
<div ref={rootRef} className={cn("relative", className)}>
{children}
</div>
</MorphContext.Provider>
);
}
export interface MorphSelectValueProps {
placeholder?: string;
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 {
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-xl border border-border")}
>
{children}
<ChevronDown className="h-4 w-4" />
</div>
<AnimatePresence initial={false} mode="popLayout">
{!ctx.open ? (
<motion.button
key="trigger"
layoutId={ctx.layoutId}
type="button"
id={ctx.triggerId}
disabled={ctx.disabled}
aria-haspopup="listbox"
aria-expanded={ctx.open}
aria-controls={ctx.listId}
onClick={() => ctx.setOpen(true)}
transition={ctx.reduce ? { duration: 0 } : MORPH}
style={{ borderRadius: 12 }}
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 {
className?: string;
children: ReactNode;
}
export function MorphSelectContent({
className,
children,
}: MorphSelectContentProps) {
const ctx = useMorphContext("MorphSelectContent");
const label = ctx.labelFor(ctx.value);
return (
<>
{/* always-mounted, hidden — keeps item label registrations alive while
closed so the trigger shows the selected value before first open */}
<div className="hidden">{children}</div>
<AnimatePresence initial={false} mode="popLayout">
{ctx.open ? (
<motion.div
key="panel"
layoutId={ctx.layoutId}
id={ctx.listId}
role="listbox"
aria-labelledby={ctx.triggerId}
transition={ctx.reduce ? { duration: 0 } : MORPH}
style={{ borderRadius: 12 }}
className={cn(
"absolute inset-x-0 top-0 z-30 overflow-hidden border border-border bg-background shadow-lg",
className,
)}
>
{/* header mirrors the trigger (continuous morph) and collapses the
panel back into the trigger when clicked */}
<motion.button
type="button"
layout="position"
aria-expanded
onClick={() => ctx.setOpen(false)}
className={cn(ROW, "outline-none")}
>
<span
className={cn(
"min-w-0 truncate",
label ? "text-foreground" : "text-muted-foreground",
)}
>
{label ?? ctx.placeholder}
</span>
<motion.span
animate={{ rotate: 180 }}
transition={ctx.reduce ? { duration: 0 } : MORPH}
className="text-muted-foreground"
>
<ChevronDown className="h-4 w-4" />
</motion.span>
</motion.button>
<div className="h-px bg-border" />
<motion.ul
initial="hidden"
animate="show"
variants={ctx.reduce ? undefined : LIST}
className="p-1"
>
{children}
</motion.ul>
</motion.div>
) : null}
</AnimatePresence>
</>
);
}
export interface MorphSelectItemProps {
value: string;
disabled?: boolean;
className?: string;
children: ReactNode;
}
export function MorphSelectItem({
value,
disabled = false,
className,
children,
}: MorphSelectItemProps) {
const ctx = useMorphContext("MorphSelectItem");
const selected = ctx.value === value;
const label = typeof children === "string" ? children : value;
useLayoutEffect(() => {
ctx.register(value, label);
return () => ctx.unregister(value);
}, [ctx.register, ctx.unregister, value, label]);
return (
<motion.li variants={ctx.reduce ? undefined : ITEM}>
<button
type="button"
role="option"
aria-selected={selected}
disabled={disabled}
onClick={() => ctx.select(value)}
className={cn(
"flex w-full items-center justify-between gap-2 rounded-lg px-2.5 py-1.5 text-left text-sm outline-none transition-colors",
selected
? "bg-muted text-foreground"
: "text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:bg-muted",
"disabled:pointer-events-none disabled:opacity-50",
className,
)}
>
{children}
{selected ? <Check className="h-3.5 w-3.5 shrink-0" /> : null}
</button>
</motion.li>
);
}
API Reference
MorphSelect
value?string—defaultValue?string—onValueChange?((value: string) => void)—disabled?booleanfalseclassName?string—MorphSelectValue
placeholder?string—className?string—MorphSelectTrigger
className?string—MorphSelectContent
className?string—MorphSelectItem
valuestring—disabled?booleanfalseclassName?string—Related components
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