Animated Alert
Composable feedback with smooth transitions.
Preview
"use client";
import { useRef, useState } from "react";
import { Alert, AlertClose, AlertContent, AlertDescription, AlertIcon, AlertTitle } from "@/components/motion/alert";
import { Button } from "@/components/motion/button";
export function AlertUsage() {
const [open, setOpen] = useState(true);
const showRef = useRef<HTMLButtonElement>(null);
return (
<div className="w-full max-w-md space-y-4">
<Alert variant="info" open={open} onOpenChange={setOpen} returnFocusRef={showRef}>
<AlertIcon />
<AlertContent>
<AlertTitle>A little heads up</AlertTitle>
<AlertDescription>Your changes are saved automatically as you work.</AlertDescription>
</AlertContent>
<AlertClose />
</Alert>
<Button ref={showRef} variant="outline" size="sm" onClick={() => setOpen(true)} disabled={open}>Show alert</Button>
</div>
);
}
"use client";
// beui.dev/components/motion/alert
import { AlertCircle, CheckCircle2, Info, TriangleAlert, X } from "lucide-react";
import { AnimatePresence, type HTMLMotionProps, motion, useReducedMotion } from "motion/react";
import {
createContext,
type ComponentProps,
type RefObject,
useCallback,
useContext,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { EASE_OUT, EASE_OUT_CSS, SPRING_LAYOUT, SPRING_PRESS } from "@/lib/ease";
import { PresenceGate } from "@/lib/presence-gate";
import { cn } from "@/lib/utils";
export type AlertVariant = "default" | "info" | "success" | "warning" | "destructive";
export type AlertState = {
open: boolean;
variant: AlertVariant;
setOpen: (open: boolean) => void;
dismiss: () => void;
};
const AlertContext = createContext<(AlertState & { reduce: boolean }) | null>(null);
function useAlertContext(component: string) {
const context = useContext(AlertContext);
if (!context) throw new Error(`${component} must be used within <Alert>`);
return context;
}
/** Shared visibility and variant for custom alert children. */
export function useAlert(): AlertState {
return useAlertContext("useAlert");
}
const VARIANT_CLASS: Record<AlertVariant, string> = {
default: "bg-background text-foreground",
info: "bg-primary/5 text-primary",
success: "bg-emerald-500/5 text-emerald-700 dark:text-emerald-400",
warning: "bg-amber-500/5 text-amber-800 dark:text-amber-300",
destructive: "bg-destructive/5 text-destructive",
};
const VARIANT_ICON = {
default: Info,
info: Info,
success: CheckCircle2,
warning: TriangleAlert,
destructive: AlertCircle,
};
export interface AlertProps extends Omit<HTMLMotionProps<"div">, "initial" | "animate" | "exit" | "layout" | "transition" | "role"> {
variant?: AlertVariant;
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
/** Focus this element when closing hides the currently focused alert control. */
returnFocusRef?: RefObject<HTMLElement | null>;
/** Layout classes for the inner row, separate from the animated surface. */
contentClassName?: string;
/** Defaults to alert for warning/destructive, and status for other variants. */
role?: "alert" | "status";
}
export function Alert({
variant = "default",
open: controlledOpen,
defaultOpen = true,
onOpenChange,
returnFocusRef,
contentClassName,
className,
children,
role = variant === "warning" || variant === "destructive" ? "alert" : "status",
style,
ref,
...props
}: AlertProps) {
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const open = controlledOpen ?? internalOpen;
const reduce = useReducedMotion() ?? false;
const surfaceRef = useRef<HTMLDivElement>(null);
const stateRef = useRef({ open, controlled: controlledOpen !== undefined, onOpenChange });
useLayoutEffect(() => {
stateRef.current = { open, controlled: controlledOpen !== undefined, onOpenChange };
}, [controlledOpen, onOpenChange, open]);
const setOpen = useCallback((next: boolean) => {
const state = stateRef.current;
if (next === state.open) return;
if (!state.controlled) {
stateRef.current = { ...state, open: next };
setInternalOpen(next);
}
state.onOpenChange?.(next);
}, []);
const dismiss = useCallback(() => setOpen(false), [setOpen]);
const context = useMemo(() => ({ open, variant, reduce, setOpen, dismiss }), [open, variant, reduce, setOpen, dismiss]);
const setRef = useCallback((node: HTMLDivElement | null) => {
surfaceRef.current = node;
const cleanup = typeof ref === "function" ? ref(node) : undefined;
if (ref && typeof ref !== "function") ref.current = node;
if (!node) return;
return () => {
surfaceRef.current = null;
if (typeof cleanup === "function") cleanup();
else if (typeof ref === "function") ref(null);
else if (ref) ref.current = null;
};
}, [ref]);
useLayoutEffect(() => {
if (!open && surfaceRef.current?.contains(document.activeElement)) {
returnFocusRef?.current?.focus({ preventScroll: true });
}
}, [open, returnFocusRef]);
return (
<AlertContext.Provider value={context}>
<AnimatePresence initial={false}>
{open && (
<PresenceGate key="alert">
{({ gate, isPresent }) => (
<motion.div
{...props}
{...gate}
ref={setRef}
role={role}
aria-hidden={!isPresent || props["aria-hidden"]}
data-slot="alert"
data-variant={variant}
data-state={isPresent ? "open" : "closed"}
initial={{ opacity: 0, transform: reduce ? "none" : "translateY(-6px)" }}
animate={{ opacity: 1, transform: "none" }}
exit={{ opacity: 0, transform: reduce ? "none" : "translateY(-6px)", transition: { duration: 0.12, ease: EASE_OUT } }}
layout={!reduce}
transition={{ opacity: { duration: 0.18, ease: EASE_OUT }, transform: { duration: 0.2, ease: EASE_OUT }, layout: SPRING_LAYOUT }}
style={{ ...style, ...gate.style, originY: 0, transitionTimingFunction: EASE_OUT_CSS }}
className={cn("relative w-full rounded-xl p-4 text-sm transition-colors duration-200", VARIANT_CLASS[variant], className)}
>
<motion.div
layout={reduce ? false : "position"}
transition={{ layout: SPRING_LAYOUT }}
style={{ originY: 0 }}
className={cn("flex min-w-0 items-start gap-3", contentClassName)}
>
{children}
</motion.div>
</motion.div>
)}
</PresenceGate>
)}
</AnimatePresence>
</AlertContext.Provider>
);
}
export interface AlertIconProps extends ComponentProps<"span"> {}
export function AlertIcon({ className, children, ...props }: AlertIconProps) {
const { variant, reduce } = useAlertContext("AlertIcon");
const Icon = VARIANT_ICON[variant];
return (
<span {...props} aria-hidden="true" data-slot="alert-icon" className={cn("mt-0.5 inline-flex size-4 shrink-0 items-center justify-center", className)}>
<AnimatePresence initial={false} mode="popLayout">
<motion.span
key={variant}
initial={{ opacity: 0, transform: reduce ? "translateY(0px) scale(1)" : "translateY(4px) scale(0.9)" }}
animate={{ opacity: 1, transform: "translateY(0px) scale(1)" }}
exit={{ opacity: 0, transform: reduce ? "translateY(0px) scale(1)" : "translateY(-4px) scale(0.9)", transition: { duration: 0.1, ease: EASE_OUT } }}
transition={{ duration: 0.18, ease: EASE_OUT }}
className="inline-flex [&>svg]:size-4"
>
{children ?? <Icon />}
</motion.span>
</AnimatePresence>
</span>
);
}
export interface AlertContentProps extends ComponentProps<"div"> {}
export function AlertContent({ className, ...props }: AlertContentProps) {
return <div {...props} data-slot="alert-content" className={cn("min-w-0 flex-1 space-y-1", className)} />;
}
export interface AlertTitleProps extends ComponentProps<"div"> {}
export function AlertTitle({ className, ...props }: AlertTitleProps) {
return <div {...props} data-slot="alert-title" className={cn("font-medium leading-5 text-pretty", className)} />;
}
export interface AlertDescriptionProps extends ComponentProps<"div"> {}
export function AlertDescription({ className, ...props }: AlertDescriptionProps) {
return <div {...props} data-slot="alert-description" className={cn("text-pretty leading-relaxed text-muted-foreground [&_a]:underline [&_a]:underline-offset-4", className)} />;
}
export interface AlertActionProps extends ComponentProps<"div"> {}
/** Compose buttons or links here; this part never creates a nested button. */
export function AlertAction({ className, ...props }: AlertActionProps) {
return <div {...props} data-slot="alert-action" className={cn("flex flex-wrap items-center gap-2 pt-2", className)} />;
}
export interface AlertCloseProps extends Omit<HTMLMotionProps<"button">, "layout"> {}
export function AlertClose({ className, children, onClick, ...props }: AlertCloseProps) {
const { dismiss, reduce } = useAlertContext("AlertClose");
return (
<motion.button
type="button"
aria-label="Dismiss alert"
{...props}
tabIndex={props.tabIndex ?? 0}
data-slot="alert-close"
layout={reduce ? false : "position"}
transition={SPRING_PRESS}
whileTap={reduce ? undefined : { scale: 0.94 }}
className={cn("-m-1.5 inline-flex size-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground outline-none transition-colors hover:bg-foreground/5 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50", className)}
onClick={(event) => {
onClick?.(event);
if (!event.defaultPrevented) dismiss();
}}
>
{children ?? <X aria-hidden="true" className="size-4" />}
</motion.button>
);
}
Install
Add it with the shadcn CLI, or copy the source manually.
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;
"use client";
import { useIsPresent } from "motion/react";
import type { ReactNode } from "react";
export interface PresenceGateRenderProps {
/**
* False from the render that starts the exit animation onward. An overlay
* kept in the tree by `AnimatePresence` is still the topmost thing on the
* page, so anything it decides from `open` alone stays true for the whole
* exit — this is the boolean that already knows the overlay is leaving.
*/
isPresent: boolean;
/**
* Spread onto every layer that takes pointer events while the overlay is
* open. Interaction releases in the same commit that starts the exit while
* the visual exit keeps playing: pointer events stop landing, and `inert`
* drops the subtree from focus order, from tab order and from the
* accessibility tree — an exiting dialog is not a dialog you can still type
* into. A layer that never takes pointer events (a wrapper that only centres
* the panel) takes `inert={!isPresent}` alone, so its own
* `pointer-events-none` is not overwritten.
*/
gate: {
inert: boolean;
style: { pointerEvents: "auto" | "none" };
};
}
export interface PresenceGateProps {
children: (props: PresenceGateRenderProps) => ReactNode;
}
/**
* Reads the presence of the subtree it renders and hands it down.
*
* `useIsPresent` only answers inside the `AnimatePresence` subtree, and the
* components that own an overlay render the `AnimatePresence` themselves, so
* the boolean has to be read one component further down: this is that
* component, and the render prop is how it reaches the layers.
*/
export function PresenceGate({ children }: PresenceGateProps) {
const isPresent = useIsPresent();
return children({
isPresent,
gate: {
inert: !isPresent,
style: { pointerEvents: isPresent ? "auto" : "none" },
},
});
}
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
"use client";
import { useEffect, useState } from "react";
/**
* Returns true only on devices that have a true hover (mouse / trackpad).
* Touch devices fire phantom `:hover` on tap that sticks until tap-elsewhere
* — gate hover-only effects (scale lifts, magnetic pulls) behind this.
*/
export function useHoverCapable() {
const [canHover, setCanHover] = useState(false);
useEffect(() => {
if (typeof window === "undefined" || !window.matchMedia) return;
const mq = window.matchMedia("(hover: hover) and (pointer: fine)");
const update = () => setCanHover(mq.matches);
update();
mq.addEventListener?.("change", update);
return () => mq.removeEventListener?.("change", update);
}, []);
return canHover;
}
Copy the source code
"use client";
// beui.dev/components/motion/alert
import { AlertCircle, CheckCircle2, Info, TriangleAlert, X } from "lucide-react";
import { AnimatePresence, type HTMLMotionProps, motion, useReducedMotion } from "motion/react";
import {
createContext,
type ComponentProps,
type RefObject,
useCallback,
useContext,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { EASE_OUT, EASE_OUT_CSS, SPRING_LAYOUT, SPRING_PRESS } from "@/lib/ease";
import { PresenceGate } from "@/lib/presence-gate";
import { cn } from "@/lib/utils";
export type AlertVariant = "default" | "info" | "success" | "warning" | "destructive";
export type AlertState = {
open: boolean;
variant: AlertVariant;
setOpen: (open: boolean) => void;
dismiss: () => void;
};
const AlertContext = createContext<(AlertState & { reduce: boolean }) | null>(null);
function useAlertContext(component: string) {
const context = useContext(AlertContext);
if (!context) throw new Error(`${component} must be used within <Alert>`);
return context;
}
/** Shared visibility and variant for custom alert children. */
export function useAlert(): AlertState {
return useAlertContext("useAlert");
}
const VARIANT_CLASS: Record<AlertVariant, string> = {
default: "bg-background text-foreground",
info: "bg-primary/5 text-primary",
success: "bg-emerald-500/5 text-emerald-700 dark:text-emerald-400",
warning: "bg-amber-500/5 text-amber-800 dark:text-amber-300",
destructive: "bg-destructive/5 text-destructive",
};
const VARIANT_ICON = {
default: Info,
info: Info,
success: CheckCircle2,
warning: TriangleAlert,
destructive: AlertCircle,
};
export interface AlertProps extends Omit<HTMLMotionProps<"div">, "initial" | "animate" | "exit" | "layout" | "transition" | "role"> {
variant?: AlertVariant;
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
/** Focus this element when closing hides the currently focused alert control. */
returnFocusRef?: RefObject<HTMLElement | null>;
/** Layout classes for the inner row, separate from the animated surface. */
contentClassName?: string;
/** Defaults to alert for warning/destructive, and status for other variants. */
role?: "alert" | "status";
}
export function Alert({
variant = "default",
open: controlledOpen,
defaultOpen = true,
onOpenChange,
returnFocusRef,
contentClassName,
className,
children,
role = variant === "warning" || variant === "destructive" ? "alert" : "status",
style,
ref,
...props
}: AlertProps) {
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const open = controlledOpen ?? internalOpen;
const reduce = useReducedMotion() ?? false;
const surfaceRef = useRef<HTMLDivElement>(null);
const stateRef = useRef({ open, controlled: controlledOpen !== undefined, onOpenChange });
useLayoutEffect(() => {
stateRef.current = { open, controlled: controlledOpen !== undefined, onOpenChange };
}, [controlledOpen, onOpenChange, open]);
const setOpen = useCallback((next: boolean) => {
const state = stateRef.current;
if (next === state.open) return;
if (!state.controlled) {
stateRef.current = { ...state, open: next };
setInternalOpen(next);
}
state.onOpenChange?.(next);
}, []);
const dismiss = useCallback(() => setOpen(false), [setOpen]);
const context = useMemo(() => ({ open, variant, reduce, setOpen, dismiss }), [open, variant, reduce, setOpen, dismiss]);
const setRef = useCallback((node: HTMLDivElement | null) => {
surfaceRef.current = node;
const cleanup = typeof ref === "function" ? ref(node) : undefined;
if (ref && typeof ref !== "function") ref.current = node;
if (!node) return;
return () => {
surfaceRef.current = null;
if (typeof cleanup === "function") cleanup();
else if (typeof ref === "function") ref(null);
else if (ref) ref.current = null;
};
}, [ref]);
useLayoutEffect(() => {
if (!open && surfaceRef.current?.contains(document.activeElement)) {
returnFocusRef?.current?.focus({ preventScroll: true });
}
}, [open, returnFocusRef]);
return (
<AlertContext.Provider value={context}>
<AnimatePresence initial={false}>
{open && (
<PresenceGate key="alert">
{({ gate, isPresent }) => (
<motion.div
{...props}
{...gate}
ref={setRef}
role={role}
aria-hidden={!isPresent || props["aria-hidden"]}
data-slot="alert"
data-variant={variant}
data-state={isPresent ? "open" : "closed"}
initial={{ opacity: 0, transform: reduce ? "none" : "translateY(-6px)" }}
animate={{ opacity: 1, transform: "none" }}
exit={{ opacity: 0, transform: reduce ? "none" : "translateY(-6px)", transition: { duration: 0.12, ease: EASE_OUT } }}
layout={!reduce}
transition={{ opacity: { duration: 0.18, ease: EASE_OUT }, transform: { duration: 0.2, ease: EASE_OUT }, layout: SPRING_LAYOUT }}
style={{ ...style, ...gate.style, originY: 0, transitionTimingFunction: EASE_OUT_CSS }}
className={cn("relative w-full rounded-xl p-4 text-sm transition-colors duration-200", VARIANT_CLASS[variant], className)}
>
<motion.div
layout={reduce ? false : "position"}
transition={{ layout: SPRING_LAYOUT }}
style={{ originY: 0 }}
className={cn("flex min-w-0 items-start gap-3", contentClassName)}
>
{children}
</motion.div>
</motion.div>
)}
</PresenceGate>
)}
</AnimatePresence>
</AlertContext.Provider>
);
}
export interface AlertIconProps extends ComponentProps<"span"> {}
export function AlertIcon({ className, children, ...props }: AlertIconProps) {
const { variant, reduce } = useAlertContext("AlertIcon");
const Icon = VARIANT_ICON[variant];
return (
<span {...props} aria-hidden="true" data-slot="alert-icon" className={cn("mt-0.5 inline-flex size-4 shrink-0 items-center justify-center", className)}>
<AnimatePresence initial={false} mode="popLayout">
<motion.span
key={variant}
initial={{ opacity: 0, transform: reduce ? "translateY(0px) scale(1)" : "translateY(4px) scale(0.9)" }}
animate={{ opacity: 1, transform: "translateY(0px) scale(1)" }}
exit={{ opacity: 0, transform: reduce ? "translateY(0px) scale(1)" : "translateY(-4px) scale(0.9)", transition: { duration: 0.1, ease: EASE_OUT } }}
transition={{ duration: 0.18, ease: EASE_OUT }}
className="inline-flex [&>svg]:size-4"
>
{children ?? <Icon />}
</motion.span>
</AnimatePresence>
</span>
);
}
export interface AlertContentProps extends ComponentProps<"div"> {}
export function AlertContent({ className, ...props }: AlertContentProps) {
return <div {...props} data-slot="alert-content" className={cn("min-w-0 flex-1 space-y-1", className)} />;
}
export interface AlertTitleProps extends ComponentProps<"div"> {}
export function AlertTitle({ className, ...props }: AlertTitleProps) {
return <div {...props} data-slot="alert-title" className={cn("font-medium leading-5 text-pretty", className)} />;
}
export interface AlertDescriptionProps extends ComponentProps<"div"> {}
export function AlertDescription({ className, ...props }: AlertDescriptionProps) {
return <div {...props} data-slot="alert-description" className={cn("text-pretty leading-relaxed text-muted-foreground [&_a]:underline [&_a]:underline-offset-4", className)} />;
}
export interface AlertActionProps extends ComponentProps<"div"> {}
/** Compose buttons or links here; this part never creates a nested button. */
export function AlertAction({ className, ...props }: AlertActionProps) {
return <div {...props} data-slot="alert-action" className={cn("flex flex-wrap items-center gap-2 pt-2", className)} />;
}
export interface AlertCloseProps extends Omit<HTMLMotionProps<"button">, "layout"> {}
export function AlertClose({ className, children, onClick, ...props }: AlertCloseProps) {
const { dismiss, reduce } = useAlertContext("AlertClose");
return (
<motion.button
type="button"
aria-label="Dismiss alert"
{...props}
tabIndex={props.tabIndex ?? 0}
data-slot="alert-close"
layout={reduce ? false : "position"}
transition={SPRING_PRESS}
whileTap={reduce ? undefined : { scale: 0.94 }}
className={cn("-m-1.5 inline-flex size-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground outline-none transition-colors hover:bg-foreground/5 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50", className)}
onClick={(event) => {
onClick?.(event);
if (!event.defaultPrevented) dismiss();
}}
>
{children ?? <X aria-hidden="true" className="size-4" />}
</motion.button>
);
}
export type {
ButtonLinkProps,
ButtonProps,
ButtonSize,
ButtonVariant,
} from "./base";
export { Button, ButtonLink } from "./base";
export type { MagneticButtonProps } from "./magnetic";
export { MagneticButton } from "./magnetic";
export type { MetallicButtonProps } from "./metallic";
export { MetallicButton } from "./metallic";
export type { ButtonState, StatefulButtonProps } from "./stateful";
export { StatefulButton } from "./stateful";
"use client";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { cancelFrame, frame, motion, MotionConfig, useReducedMotion, type Transition } from "motion/react";
import {
createContext,
useCallback,
useContext,
useId,
useLayoutEffect,
useRef,
useMemo,
useState,
type ButtonHTMLAttributes,
type HTMLAttributes,
type ReactNode,
} from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
type Variant = "pill" | "underline" | "segment";
type Ctx = {
value: string;
setValue: (v: string) => void;
layoutId: string;
variant: Variant;
};
const TabsCtx = createContext<Ctx | null>(null);
function useTabs() {
const ctx = useContext(TabsCtx);
if (!ctx) throw new Error("Tabs.* must be used inside <Tabs>");
return ctx;
}
// Settle without overshoot: a scrollable tab list would turn even a small
// overshoot into a transient scrollbar and layout shift.
// Scale stiffness and damping together for a quicker glide with the same feel.
const transition: Transition = {
type: "spring",
stiffness: 245,
damping: 36,
mass: 1.2,
};
export function Tabs({
defaultValue,
value,
onValueChange,
variant = "pill",
children,
className,
}: {
defaultValue?: string;
value?: string;
onValueChange?: (v: string) => void;
variant?: Variant;
children: ReactNode;
className?: string;
}) {
const [internal, setInternal] = useState(defaultValue ?? "");
const layoutId = useId();
const reduce = useReducedMotion();
const controlled = value !== undefined;
const current = controlled ? value : internal;
const setValue = useCallback(
(v: string) => {
if (!controlled) setInternal(v);
onValueChange?.(v);
},
[controlled, onValueChange],
);
const contextValue = useMemo(
() => ({ value: current, setValue, layoutId, variant }),
[current, layoutId, setValue, variant],
);
return (
<MotionConfig transition={reduce ? { duration: 0 } : transition}>
<TabsCtx.Provider value={contextValue}>
{/* layoutRoot: the indicator's layoutId measures in page coordinates, so
inside fixed/scrolled containers it would replay scroll offsets as
movement. The pill only ever travels within the list, so scoping
projection to the Tabs wrapper is always correct. */}
<motion.div layoutRoot className={className}>
{children}
</motion.div>
</TabsCtx.Provider>
</MotionConfig>
);
}
const listClasses: Record<Variant, string> = {
pill: "inline-flex items-center gap-1 rounded-full bg-card p-1",
underline: "inline-flex items-center gap-1 border-b border-border",
segment: "inline-flex items-center gap-0 rounded-lg bg-card p-0.5",
};
export function TabsList({
children,
className,
wrapperClassName,
...props
}: {
wrapperClassName?: string;
} & HTMLAttributes<HTMLDivElement>) {
const { variant, value } = useTabs();
const reduce = useReducedMotion();
const rootRef = useRef<HTMLDivElement>(null);
const viewportRef = useRef<HTMLDivElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const viewportId = useId();
const [edges, setEdges] = useState({ overflow: false, left: false, right: false });
const measure = useCallback(() => {
const root = rootRef.current;
const viewport = viewportRef.current;
if (!root || !viewport) return;
// Overlay controls do not reduce the viewport or change its scroll range.
const overflow = viewport.scrollWidth > root.clientWidth + 1;
const max = Math.max(0, viewport.scrollWidth - viewport.clientWidth);
const rtl = getComputedStyle(viewport).direction === "rtl";
// Modern browsers expose negative scrollLeft in RTL. Clamp rubber-banding.
const fromLeft = Math.max(0, Math.min(max, rtl ? max + viewport.scrollLeft : viewport.scrollLeft));
const next = { overflow, left: fromLeft > 1, right: fromLeft < max - 1 };
setEdges((previous) => previous.overflow === next.overflow && previous.left === next.left && previous.right === next.right ? previous : next);
}, []);
const reveal = useCallback((tab: HTMLElement | null) => {
const viewport = viewportRef.current;
if (!viewport || !tab) return;
const frame = viewport.getBoundingClientRect();
const item = tab.getBoundingClientRect();
const max = Math.max(0, viewport.scrollWidth - viewport.clientWidth);
const rtl = getComputedStyle(viewport).direction === "rtl";
const fromLeft = Math.max(0, Math.min(max, rtl ? max + viewport.scrollLeft : viewport.scrollLeft));
// Keep the selected/focused label clear of the arrows over the faded edges.
const left = frame.left + (fromLeft > 1 ? 36 : 0);
const right = frame.right - (fromLeft < max - 1 ? 36 : 0);
const delta = item.left < left ? item.left - left : item.right > right ? item.right - right : 0;
// Scroll only this viewport; scrollIntoView can also move the whole page.
if (delta) viewport.scrollBy({ left: delta, behavior: reduce ? "instant" : "smooth" });
}, [reduce]);
useLayoutEffect(() => {
const root = rootRef.current;
const viewport = viewportRef.current;
const list = listRef.current;
if (!root || !viewport || !list) return;
const update = () => {
measure();
reveal(list.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]'));
};
const observer = new ResizeObserver(update);
observer.observe(root);
observer.observe(viewport);
observer.observe(list);
viewport.addEventListener("scroll", measure, { passive: true });
update();
return () => {
observer.disconnect();
viewport.removeEventListener("scroll", measure);
};
}, [measure, reveal]);
useLayoutEffect(() => {
// Children may change without a resize; controlled selection must also reveal.
void children;
void value;
void edges.overflow;
measure();
reveal(listRef.current?.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]') ?? null);
}, [children, value, edges.overflow, measure, reveal]);
useLayoutEffect(() => {
if (variant === "underline") return;
const list = listRef.current;
if (!list) return;
void children;
const labels = Array.from(list.querySelectorAll<HTMLElement>("[data-tabs-label]"));
const indicator = list.querySelector<HTMLElement>("[data-tabs-indicator]");
const target = list.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]');
if (!indicator || !target || target.dataset.tabsValue !== value) {
for (const label of labels) label.style.clipPath = "inset(0 100% 0 0)";
return;
}
let frames = 0;
let stillFrames = 0;
let previous: { left: number; right: number } | undefined;
const syncClips = () => {
const pill = (reduce ? target : indicator).getBoundingClientRect();
// Read ALL geometry before writing ANY masks. A loop per tab interleaved
// reads and writes, forcing the browser to flush styles repeatedly.
const clips = labels.map((label) => {
const bounds = label.getBoundingClientRect();
const left = Math.max(0, Math.min(bounds.width, pill.left - bounds.left));
const right = Math.max(0, Math.min(bounds.width, bounds.right - pill.right));
return left + right >= bounds.width ? "inset(0 100% 0 0)" : `inset(0 ${right}px 0 ${left}px)`;
});
labels.forEach((label, index) => {
if (label.style.clipPath !== clips[index]) label.style.clipPath = clips[index];
});
frames += 1;
stillFrames = previous && Math.abs(pill.left - previous.left) < 0.01 && Math.abs(pill.right - previous.right) < 0.01 ? stillFrames + 1 : 0;
previous = { left: pill.left, right: pill.right };
if (reduce || (frames > 2 && stillFrames >= 2)) cancelFrame(syncClips);
};
// One shared pass after Motion paints the projected pill keeps every label
// in sync, including labels crossed during a long or interrupted glide.
frame.postRender(syncClips, true);
return () => cancelFrame(syncClips);
}, [value, children, variant, reduce]);
const scroll = (direction: number) => {
const viewport = viewportRef.current;
if (viewport) viewport.scrollBy({ left: direction * viewport.clientWidth * 0.8, behavior: reduce ? "instant" : "smooth" });
};
const controlClass = "absolute inset-y-0 z-20 inline-flex w-9 items-center justify-center text-foreground transition-opacity hover:opacity-70 focus-visible:outline-2 focus-visible:-outline-offset-4 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-0";
const surfaceClass = variant === "pill" ? "rounded-full bg-card" : variant === "segment" ? "rounded-lg bg-card" : "";
return (
<div ref={rootRef} className={cn("relative isolate flex w-full max-w-full min-w-0 items-center", edges.overflow && surfaceClass, wrapperClassName)}>
{edges.overflow && (
<button type="button" aria-label="Scroll tabs left" aria-controls={viewportId} disabled={!edges.left} onClick={() => scroll(-1)} className={cn(controlClass, "left-0 rounded-l-full")}>
<ChevronLeft size={20} aria-hidden="true" />
</button>
)}
<motion.div
ref={viewportRef}
id={viewportId}
layoutScroll
className={cn("w-full min-w-0 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden", edges.overflow && "[border-radius:inherit]")}
style={edges.overflow ? {
maskImage: `linear-gradient(to right, ${edges.left ? "transparent, black 40px" : "black, black 0px"}, ${edges.right ? "black calc(100% - 40px), transparent" : "black 100%"})`,
} : undefined}
onFocusCapture={(event) => {
if (event.target instanceof HTMLElement && event.target.getAttribute("role") === "tab") reveal(event.target);
}}
>
<div {...props} ref={listRef} role="tablist" className={cn(listClasses[variant], "w-max", className)}>
{children}
</div>
</motion.div>
{edges.overflow && edges.left && (
<span aria-hidden="true" className="pointer-events-none absolute inset-y-0 left-0 z-10 w-10 rounded-l-[inherit] backdrop-blur-[2px] [mask-image:linear-gradient(to_right,black,transparent)]" />
)}
{edges.overflow && edges.right && (
<span aria-hidden="true" className="pointer-events-none absolute inset-y-0 right-0 z-10 w-10 rounded-r-[inherit] backdrop-blur-[2px] [mask-image:linear-gradient(to_left,black,transparent)]" />
)}
{edges.overflow && (
<button type="button" aria-label="Scroll tabs right" aria-controls={viewportId} disabled={!edges.right} onClick={() => scroll(1)} className={cn(controlClass, "right-0 rounded-r-full")}>
<ChevronRight size={20} aria-hidden="true" />
</button>
)}
</div>
);
}
export function TabsTrigger({
value,
children,
className,
indicatorClassName,
onClick,
...props
}: {
value: string;
indicatorClassName?: string;
} & Omit<ButtonHTMLAttributes<HTMLButtonElement>, "value">) {
const { value: current, setValue, layoutId, variant } = useTabs();
const active = current === value;
// React owns the initial mask only; TabsList synchronizes subsequent masks.
const [initialClip] = useState(() => active ? "inset(0)" : "inset(0 100% 0 0)");
if (variant === "underline") {
return (
<button
{...props}
type="button"
role="tab"
aria-selected={active}
onClick={(event) => {
onClick?.(event);
if (!event.defaultPrevented) setValue(value);
}}
className={cn(
"relative isolate px-3 pb-2.5 pt-1 -mb-px text-sm font-medium transition-colors min-h-[44px] inline-flex items-center whitespace-nowrap shrink-0",
active ? "text-foreground" : "text-muted-foreground hover:text-foreground",
className,
)}
>
{children}
{active ? (
<motion.span
layoutId={layoutId}
layout
className={cn(
"absolute bottom-0 left-0 right-0 h-px bg-primary",
indicatorClassName,
)}
/>
) : null}
</button>
);
}
const radius = variant === "pill" ? "rounded-full" : "rounded-md";
return (
<div className="relative shrink-0">
{active ? (
<motion.span
data-tabs-indicator=""
layoutId={layoutId}
layout
style={{ borderRadius: variant === "pill" ? 9999 : 8 }}
className={cn(
"absolute inset-0 bg-primary",
radius,
indicatorClassName,
)}
/>
) : null}
<button
{...props}
type="button"
role="tab"
aria-selected={active}
data-tabs-value={value}
onClick={(event) => {
onClick?.(event);
if (!event.defaultPrevented) setValue(value);
}}
className={cn(
"relative z-10 inline-flex items-center justify-center whitespace-nowrap bg-transparent px-3.5 py-1.5 text-sm font-medium outline-none",
"text-muted-foreground hover:text-foreground",
radius,
className,
)}
>
{children}
<span
data-tabs-label=""
aria-hidden="true"
inert
className="pointer-events-none absolute inset-0 inline-flex items-center justify-center text-primary-foreground [gap:inherit] [padding:inherit]"
style={{ clipPath: initialClip }}
>
{children}
</span>
</button>
</div>
);
}
export function TabsContent({ value, children, className }: { value: string; children: ReactNode; className?: string }) {
const { value: current } = useTabs();
const reduce = useReducedMotion();
const active = current === value;
// Inactive panels stay mounted but hidden, so their content (e.g. source
// code) is present in the server-rendered HTML for crawlers and assistive
// tech, instead of being dropped from the DOM.
if (!active) {
return (
<div hidden className={className}>
{children}
</div>
);
}
return (
<motion.div
key={value}
initial={{ opacity: 0, y: reduce ? 0 : 4 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.18, ease: EASE_OUT }}
className={cn("mt-4", className)}
>
{children}
</motion.div>
);
}
"use client";
import {
AnimatePresence,
type HTMLMotionProps,
motion,
useReducedMotion,
} from "motion/react";
import {
forwardRef,
type PointerEvent,
type ReactNode,
useCallback,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_PRESS } from "@/lib/ease";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
import { cn } from "@/lib/utils";
export type ButtonVariant = "primary" | "secondary" | "ghost" | "outline";
export type ButtonSize = "sm" | "md" | "lg" | "icon";
export interface ButtonProps extends Omit<
HTMLMotionProps<"button">,
"children"
> {
variant?: ButtonVariant;
size?: ButtonSize;
pressScale?: number;
/** Spawn a Material-style ripple from the press point. Off by default. */
ripple?: boolean;
children?: ReactNode;
}
export interface ButtonLinkProps extends Omit<
HTMLMotionProps<"a">,
"children"
> {
variant?: ButtonVariant;
size?: ButtonSize;
pressScale?: number;
children?: ReactNode;
}
type Ripple = { id: number; x: number; y: number; size: number };
const VARIANT_CLASS: Record<ButtonVariant, string> = {
primary: "bg-primary text-primary-foreground hover:bg-primary/90",
secondary: "border border-border bg-card text-foreground hover:border-border",
ghost: "text-muted-foreground hover:text-foreground hover:bg-muted/60",
outline:
"border border-border bg-transparent text-foreground hover:bg-muted/60",
};
const SIZE_CLASS: Record<ButtonSize, string> = {
sm: "h-8 px-3 text-xs gap-1.5 rounded-full",
md: "h-10 px-5 text-sm gap-2 rounded-full",
lg: "h-12 px-6 text-base gap-2 rounded-full",
icon: "h-8 w-8 rounded-lg",
};
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
function Button(
{
variant = "primary",
size = "md",
pressScale = 0.93,
ripple = false,
className,
children,
onPointerDown,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const canHover = useHoverCapable();
const [ripples, setRipples] = useState<Ripple[]>([]);
const nextId = useRef(0);
const handlePointerDown = useCallback(
(event: PointerEvent<HTMLButtonElement>) => {
if (ripple && !reduce) {
const rect = event.currentTarget.getBoundingClientRect();
const size = Math.max(rect.width, rect.height) * 2;
const id = nextId.current++;
setRipples((prev) => [
...prev,
{
id,
x: event.clientX - rect.left,
y: event.clientY - rect.top,
size,
},
]);
}
onPointerDown?.(event);
},
[ripple, reduce, onPointerDown],
);
return (
<motion.button
ref={ref}
type="button"
whileTap={reduce ? undefined : { scale: pressScale }}
whileHover={reduce || !canHover ? undefined : { scale: 1.02 }}
transition={SPRING_PRESS}
onPointerDown={handlePointerDown}
className={cn(
"inline-flex items-center justify-center font-medium select-none",
"transition-colors",
"disabled:pointer-events-none disabled:opacity-50",
ripple && "relative overflow-hidden",
VARIANT_CLASS[variant],
SIZE_CLASS[size],
className,
)}
{...rest}
>
{ripple && !reduce ? (
<span className="pointer-events-none absolute inset-0 overflow-hidden rounded-[inherit]">
<AnimatePresence>
{ripples.map((r) => (
<motion.span
key={r.id}
className="absolute rounded-full bg-current"
style={{
left: r.x,
top: r.y,
width: r.size,
height: r.size,
x: "-50%",
y: "-50%",
}}
initial={{ scale: 0.05, opacity: 0.3 }}
animate={{ scale: 1, opacity: 0 }}
exit={{ opacity: 0 }}
transition={{ duration: 1.6, ease: EASE_OUT }}
onAnimationComplete={() =>
setRipples((prev) => prev.filter((x) => x.id !== r.id))
}
/>
))}
</AnimatePresence>
</span>
) : null}
{children}
</motion.button>
);
},
);
export const ButtonLink = forwardRef<HTMLAnchorElement, ButtonLinkProps>(
function ButtonLink(
{
variant = "primary",
size = "md",
pressScale = 0.93,
className,
children,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const canHover = useHoverCapable();
return (
<motion.a
ref={ref}
whileTap={reduce ? undefined : { scale: pressScale }}
whileHover={reduce || !canHover ? undefined : { scale: 1.02 }}
transition={SPRING_PRESS}
className={cn(
"inline-flex items-center justify-center font-medium select-none",
"transition-colors",
VARIANT_CLASS[variant],
SIZE_CLASS[size],
className,
)}
{...rest}
>
{children}
</motion.a>
);
},
);
"use client";
import { forwardRef } from "react";
import { Magnetic } from "../magnetic";
import { Button, type ButtonProps } from "./base";
export interface MagneticButtonProps extends ButtonProps {
/** Magnetic pull strength. Default 0.25. */
strength?: number;
/** Class applied to the magnetic wrapper. */
magneticClassName?: string;
}
export const MagneticButton = forwardRef<HTMLButtonElement, MagneticButtonProps>(function MagneticButton(
{ strength = 0.25, magneticClassName, children, ...rest },
ref,
) {
return (
<Magnetic strength={strength} className={magneticClassName}>
<Button ref={ref} {...rest}>
{children}
</Button>
</Magnetic>
);
});
"use client";
import { motion, useReducedMotion } from "motion/react";
import { forwardRef, useState } from "react";
import { EASE_IN_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
import { Button, type ButtonProps } from "./base";
export interface MetallicButtonProps extends Omit<
ButtonProps,
"ripple" | "variant"
> {
/** Stops the traveling reflection while preserving the chrome rim. */
paused?: boolean;
}
// The rim and highlight drift separately so the material stays quiet and reflective.
const SILVER_DRIFT = {
duration: 8,
ease: EASE_IN_OUT,
repeat: Infinity,
};
const CHROME_SHIMMER = {
duration: 2.4,
ease: EASE_IN_OUT,
};
export const MetallicButton = forwardRef<
HTMLButtonElement,
MetallicButtonProps
>(function MetallicButton(
{
size = "md",
paused = false,
className,
children,
onHoverStart,
onHoverEnd,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const still = paused || Boolean(reduce);
const [hovered, setHovered] = useState(false);
return (
<Button
ref={ref}
variant="ghost"
size={size}
onHoverStart={(event, info) => {
setHovered(true);
onHoverStart?.(event, info);
}}
onHoverEnd={(event, info) => {
setHovered(false);
onHoverEnd?.(event, info);
}}
className={cn(
"group relative isolate overflow-hidden border-0 bg-transparent text-foreground",
"hover:bg-transparent hover:text-foreground",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
"shadow-[0_8px_22px_rgba(0,0,0,0.16)]",
size === "icon" && "rounded-full",
className,
)}
{...rest}
>
<motion.span
aria-hidden="true"
className="pointer-events-none absolute inset-y-0 left-[-18%] z-0 w-[136%] rounded-[inherit] bg-[linear-gradient(105deg,#111_0%,#737373_14%,#fafafa_26%,#525252_38%,#0a0a0a_50%,#a3a3a3_64%,#fff_75%,#404040_87%,#111_100%)]"
animate={still ? undefined : { x: ["0%", "13%", "0%"] }}
transition={still ? undefined : SILVER_DRIFT}
/>
<motion.span
aria-hidden="true"
className="pointer-events-none absolute inset-y-0 left-[-58%] z-[1] w-[52%] -skew-x-12 bg-[linear-gradient(90deg,transparent,rgba(255,255,255,0.5)_48%,transparent)] opacity-50 blur-[3px] mix-blend-screen"
animate={still ? undefined : { x: hovered ? "310%" : "0%" }}
transition={still ? undefined : CHROME_SHIMMER}
/>
<span
aria-hidden="true"
className="pointer-events-none absolute inset-[2px] z-[2] rounded-[inherit] bg-background transition-colors group-hover:bg-muted/40"
/>
<span
aria-hidden="true"
className="pointer-events-none absolute inset-[2px] z-[3] rounded-[inherit] shadow-[inset_0_1px_0_rgba(255,255,255,0.28),inset_0_-1px_0_rgba(0,0,0,0.16)]"
/>
<span className="relative z-10 inline-flex items-center justify-center gap-2">
{children}
</span>
</Button>
);
});
"use client";
import { Check, Loader2, X } from "lucide-react";
import {
AnimatePresence,
motion,
useReducedMotion,
type Variants,
} from "motion/react";
import {
forwardRef,
type ReactNode,
useLayoutEffect,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_SWAP } from "@/lib/ease";
import { Button, type ButtonProps } from "./base";
export type ButtonState = "idle" | "loading" | "success" | "error";
export interface StatefulButtonProps extends Omit<ButtonProps, "children"> {
state?: ButtonState;
children: ReactNode;
loadingText?: ReactNode;
successText?: ReactNode;
errorText?: ReactNode;
icon?: ReactNode;
}
const CASCADE_STAGGER = 0.025;
const ROLL_BLUR = "blur(6px)";
const CASCADE_LETTER_VARIANTS: Variants = {
initial: { opacity: 0, y: "105%", filter: ROLL_BLUR },
animate: (delay: number = 0) => ({
opacity: 1,
y: "0%",
filter: "blur(0px)",
transition: { ...SPRING_SWAP, delay },
}),
exit: (delay: number = 0) => ({
opacity: 0,
y: "-105%",
filter: ROLL_BLUR,
transition: { duration: 0.16, ease: EASE_OUT, delay: delay * 0.5 },
}),
};
const ICON_VARIANTS: Variants = {
// Width collapses too, so the icon adds/removes its own space smoothly
// instead of popping the row width in a single frame.
initial: { opacity: 0, width: 0, scale: 0.7, filter: ROLL_BLUR },
animate: {
opacity: 1,
width: "1.5rem",
scale: 1,
filter: "blur(0px)",
transition: SPRING_SWAP,
},
exit: {
opacity: 0,
width: 0,
scale: 0.7,
filter: ROLL_BLUR,
transition: { duration: 0.16, ease: EASE_OUT },
},
};
function IconSlot({ keyId, children }: { keyId: string; children: ReactNode }) {
const reduce = useReducedMotion();
return (
<motion.span
key={keyId}
variants={ICON_VARIANTS}
initial={reduce ? { opacity: 0 } : "initial"}
animate={reduce ? { opacity: 1 } : "animate"}
exit={reduce ? { opacity: 0 } : "exit"}
transition={reduce ? { duration: 0.15 } : undefined}
className="inline-grid shrink-0 place-items-center overflow-hidden"
>
{children}
</motion.span>
);
}
function TextSlot({
value,
children,
}: {
value: string;
children: ReactNode;
}) {
const reduce = useReducedMotion();
const measureRef = useRef<HTMLSpanElement>(null);
const [width, setWidth] = useState<number>();
const label = typeof children === "string" ? children : null;
const cascade = label !== null && !reduce;
// Measure strings with the same per-letter layout as the cascade. Measuring
// the whole string preserves kerning, which can make it narrower than the
// inline-block letters and clip the final glyph during the width animation.
useLayoutEffect(() => {
const nextWidth = measureRef.current?.offsetWidth;
if (!nextWidth) return;
setWidth((current) => (current === nextWidth ? current : nextWidth));
});
return (
<motion.span
initial={false}
animate={{ width }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="relative inline-block overflow-hidden whitespace-nowrap align-bottom"
>
<span
ref={measureRef}
aria-hidden
className="invisible inline-block whitespace-nowrap"
>
{cascade
? label.split("").map((char, index) => (
<span
// biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.
key={index}
className="inline-block whitespace-pre"
>
{char}
</span>
))
: children}
</span>
{cascade ? (
<>
<span className="sr-only">{label}</span>
<AnimatePresence initial={false}>
<motion.span
key={`cascade-${value}`}
aria-hidden
initial="initial"
animate="animate"
exit="exit"
className="absolute left-0 top-0 inline-block whitespace-pre"
>
{label.split("").map((char, index) => (
<motion.span
// biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.
key={index}
custom={index * CASCADE_STAGGER}
variants={CASCADE_LETTER_VARIANTS}
className="inline-block whitespace-pre will-change-[opacity,filter,transform]"
>
{char}
</motion.span>
))}
</motion.span>
</AnimatePresence>
</>
) : (
<AnimatePresence initial={false}>
<motion.span
key={`text-${value}`}
initial={reduce ? { opacity: 0 } : { opacity: 0, y: 14, filter: ROLL_BLUR }}
animate={reduce ? { opacity: 1 } : { opacity: 1, y: 0, filter: "blur(0px)" }}
exit={reduce ? { opacity: 0 } : { opacity: 0, y: -14, filter: ROLL_BLUR }}
transition={reduce ? { duration: 0.15 } : SPRING_SWAP}
className="absolute left-0 top-0 inline-block will-change-[opacity,filter,transform]"
>
{children}
</motion.span>
</AnimatePresence>
)}
</motion.span>
);
}
export const StatefulButton = forwardRef<HTMLButtonElement, StatefulButtonProps>(function StatefulButton(
{
state = "idle",
children,
loadingText = "Loading",
successText = "Done",
errorText = "Try again",
icon,
disabled,
...rest
},
ref,
) {
const isBusy = state === "loading";
const stateText =
state === "loading"
? loadingText
: state === "success"
? successText
: state === "error"
? errorText
: children;
const textKey =
typeof stateText === "string" ? `${state}-${stateText}` : state;
return (
<Button ref={ref} disabled={disabled || isBusy} aria-busy={isBusy} whileHover={undefined} {...rest}>
<span
aria-live="polite"
className="relative inline-flex items-center justify-center overflow-hidden"
>
<AnimatePresence initial={false}>
{state === "loading" ? (
<IconSlot keyId="loading-icon">
<Loader2 className="h-4 w-4 animate-spin" />
</IconSlot>
) : null}
{state === "success" ? (
<IconSlot keyId="success-icon">
<Check className="h-4 w-4" />
</IconSlot>
) : null}
{state === "error" ? (
<IconSlot keyId="error-icon">
<X className="h-4 w-4" />
</IconSlot>
) : null}
</AnimatePresence>
<TextSlot value={textKey}>{stateText}</TextSlot>
<AnimatePresence initial={false}>
{state === "idle" && icon ? (
<IconSlot keyId="idle-icon">{icon}</IconSlot>
) : null}
</AnimatePresence>
</span>
</Button>
);
});
"use client";
import { motion, useMotionValue, useReducedMotion, useSpring } from "motion/react";
import { useRef, type ReactNode } from "react";
import { SPRING_MOUSE } from "@/lib/ease";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
import { cn } from "@/lib/utils";
export interface MagneticProps {
children: ReactNode;
strength?: number;
className?: string;
}
export function Magnetic({ children, strength = 0.35, className }: MagneticProps) {
const ref = useRef<HTMLDivElement>(null);
const reduce = useReducedMotion();
const canHover = useHoverCapable();
// Decorative cursor-follow: skip on touch (phantom hover) and reduced motion.
const enabled = !reduce && canHover;
const x = useMotionValue(0);
const y = useMotionValue(0);
const sx = useSpring(x, SPRING_MOUSE);
const sy = useSpring(y, SPRING_MOUSE);
const onMove = (e: React.MouseEvent<HTMLDivElement>) => {
const el = ref.current;
if (!el || !enabled) return;
const rect = el.getBoundingClientRect();
x.set((e.clientX - rect.left - rect.width / 2) * strength);
y.set((e.clientY - rect.top - rect.height / 2) * strength);
};
const onLeave = () => {
x.set(0);
y.set(0);
};
return (
<motion.div
ref={ref}
onMouseMove={onMove}
onMouseLeave={onLeave}
style={{ x: sx, y: sy }}
className={cn("inline-block", className)}
>
{children}
</motion.div>
);
}
API Reference
Alert
variant?"default" | "success" | "info" | "warning" | "destructive"defaultopen?boolean—defaultOpen?booleantrueonOpenChange?((open: boolean) => void)—returnFocusRef?RefObject<HTMLElement | null>Focus this element when closing hides the currently focused alert control.
—contentClassName?stringLayout classes for the inner row, separate from the animated surface.
—role?"alert" | "status"Defaults to alert for warning/destructive, and status for other variants.
variant === "warning" || variant === "destructive" ? "alert" : "status"className?string—AlertIcon
className?string—AlertContent
className?string—AlertTitle
className?string—AlertDescription
className?string—AlertAction
className?string—AlertClose
className?string—Related components
Aspect Ratio
Responsive media with smooth aspect ratio transitions.
Date Range Picker
Composable date range picker with root, trigger, popover content, calendar, header, grid, summary, footer, clear and preset parts, plus a shared state hook. Compact inline and dropdown compositions, direct month and year selection, and full keyboard navigation.
Animated Color Selector
Composable color swatches with a spring-gliding selection ring, press feedback, native radio keyboard navigation, and controlled or uncontrolled state.
Updated