Team Section
Team page section with member cards that stagger in on view and slide up a bio and links on hover or focus, department filter chips with a gliding pill and spring layout reflow, and a click that opens a focus-managed dialog with the member's full bio, location and links.
Preview
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 { 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;
}
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
// Shared touch primitives. iOS and iPadOS run their own gestures on top of the
// page — the long-press selection callout and the selection it drags in with
// it — and they win: once the platform claims a touch it cancels ours
// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own
// their gesture have to opt out.
//
// What the two classes below cover, precisely:
// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:
// it is not a property other engines have, so it is inert everywhere else.
// - `user-select: none` stops the long-press selection on every engine,
// Android included, and stops a drag from painting a selection under the
// cursor. It is inherited, so it reaches every descendant — which is why the
// two classes differ only in whether they apply it unconditionally.
// What neither covers:
// - Chrome for Android's long-press menu on a link or an image. No CSS
// suppresses it; a gesture surface that wraps one needs its own
// `onContextMenu` with `preventDefault()`.
// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is
// not inherited and plain divs and buttons are not drag sources, so setting
// it on the surface does nothing — the child itself needs `draggable={false}`.
/**
* Classes for a surface that *is* the control: a thumb, a drum, a stage, a
* handle, a hold button. Selection is suppressed on every input, because a
* drag that highlights the control's own label is wrong on a mouse too.
* Compose with `touch-none` when the surface also owns the scroll axis — leave
* it off when the page must still scroll from there.
*/
export const TOUCH_GESTURE_CLASS = "select-none [-webkit-touch-callout:none]";
/**
* The same opt-out for a gesture surface that wraps content the consumer owns:
* a scroller, a context-menu trigger, a sheet header, a list row. Selection is
* suppressed only where the platform runs its own press gestures — a coarse
* pointer — so a mouse user can still select and copy that content. If the
* gesture itself would paint a selection under the cursor, add `select-none`
* for the duration of the gesture rather than reaching for
* `TOUCH_GESTURE_CLASS`.
*
* `pointer: coarse` describes the *primary* pointer and nothing else, so a
* hybrid machine reads it wrong in both directions: a tablet with a mouse
* plugged in keeps touch as primary and loses mouse selection, and a laptop
* with a touchscreen keeps the mouse as primary and leaves selection live
* under a finger. No media query can answer per interaction — the query is
* about the device, and the question is about the gesture in progress. The
* default stays here because it is right on the machines that are one thing or
* the other, and losing a selection is a nuisance; where the miss costs a
* *gesture* instead, the surface pairs it with `holdSelection` on the press.
*/
export const TOUCH_GESTURE_CONTENT_CLASS =
"[-webkit-touch-callout:none] pointer-coarse:select-none";
/**
* Grow a small control's *hit area* to at least 44×44px (WCAG 2.5.5, Apple
* HIG) on a coarse pointer, without changing what it looks like or the space
* it takes in layout. An invisible `::after` box, centered on the control and
* `max(100%, 2.75rem)` on each axis, catches the taps: a 32px icon button
* reaches 6px past each edge, a wide 40px button only grows vertically, and a
* control already 44px or larger is left as it is. Hit-testing a pseudo
* element lands on its owner, so handlers, focus and `:active` all behave.
*
* Mouse and trackpad rendering is untouched — nothing here applies outside
* `pointer: coarse`. Requirements on the element it goes on:
* - It must be the containing block: add `relative` (and keep it mergeable, so
* a consumer's `absolute` still wins through `cn`).
* - It must not clip itself (`overflow-hidden`), or the overhang is clipped
* away along with its hit area.
* - It must render children: `<input>` and other void elements have no
* `::after`. Put it on the wrapper or label instead.
* - It must not already use `::after` for something visible.
*
* Centered 44px means two 32px buttons with a 4px gap overlap by 8px; the
* later one wins that strip, which still ends well short of the earlier
* button's visual center. Below a ~32px pitch the later neighbour starts
* eating into that center — use `TOUCH_TARGET_Y_CLASS` for such dense rows.
*
* The overhang is real geometry: inside a scroll container it counts as
* scrollable overflow, so a control flush against a scroller's edge can add a
* few pixels of scroll on touch screens. Give such a scroller a little padding
* on that side.
*/
export const TOUCH_TARGET_CLASS =
"pointer-coarse:after:absolute pointer-coarse:after:top-1/2 pointer-coarse:after:left-1/2 pointer-coarse:after:size-[max(100%,2.75rem)] pointer-coarse:after:-translate-x-1/2 pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']";
/**
* `TOUCH_TARGET_CLASS` on the vertical axis only, for controls packed tighter
* than ~32px apart in a row (pagination dots, dense swatches), where growing
* sideways would hand most of each control to its neighbour. Same rules.
*/
export const TOUCH_TARGET_Y_CLASS =
"pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:top-1/2 pointer-coarse:after:h-[max(100%,2.75rem)] pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']";
/**
* Suppress selection on `element` for as long as a gesture is running on it,
* whatever the primary pointer of the machine happens to be. Returns the
* release. Inline, so it wins over the class above and is gone again the
* moment the gesture ends.
*
* For the press gestures a native selection would otherwise steal — a
* long-press that opens a menu. Elsewhere prefer the classes: a surface that
* takes selection away for the whole session is a surface whose text nobody
* can copy.
*/
export function holdSelection(element: HTMLElement) {
element.style.setProperty("user-select", "none");
element.style.setProperty("-webkit-user-select", "none");
return () => {
element.style.removeProperty("user-select");
element.style.removeProperty("-webkit-user-select");
};
}
/**
* Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer
* is already gone by the time the handler runs — routine on iOS, where the
* system can claim the touch first — and an uncaught throw takes the rest of
* the handler, the gesture included, down with it. Touch pointers carry
* implicit capture anyway, so losing it is never fatal.
*/
export function capturePointer(element: Element, pointerId: number) {
try {
element.setPointerCapture(pointerId);
} catch {
// Pointer is no longer active — implicit capture still applies on touch.
}
}
/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */
export function releasePointer(element: Element, pointerId: number) {
try {
if (element.hasPointerCapture(pointerId)) {
element.releasePointerCapture(pointerId);
}
} catch {
// Capture was already dropped by the browser.
}
}
/**
* Whether this event came from a pointer that is *hovering*: not a touch, and
* not currently pressed. Which input the user is holding right now is not
* something a device capability can answer — a touchscreen laptop hovers and
* taps, and iPadOS reports a fine hovering pointer for a finger — so both
* paths stay live and each handler branches on the event it was given.
*
* A pen resting on the glass is making contact, not hovering: `buttons` is the
* tell, and it sends a pen tap down the same route a finger takes.
*
* This answers what an *enter* asks. A leave is the other half of a pair and
* has to be read against the enter that started it — `useHoverGesture` in
* `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it
* rather than asking this question twice.
*/
export const isHoveringPointer = (event: {
pointerType: string;
buttons: number;
}) => event.pointerType !== "touch" && event.buttons === 0;
Copy the source code
"use client";
// karaui.kamisama-v0.my.id/components/blocks/team-section
import { ArrowUpRight, MapPin } from "lucide-react";
import {
AnimatePresence,
LayoutGroup,
motion,
useReducedMotion,
type Variants,
} from "motion/react";
import { type ReactNode, useId, useMemo, useState } from "react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/motion/dialog";
import { EASE_OUT, EASE_OUT_CSS, SPRING_LAYOUT } from "@/lib/ease";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
import { cn } from "@/lib/utils";
export interface TeamSocialLink {
/** Accessible name, e.g. "GitHub". */
label: string;
href: string;
icon: ReactNode;
}
export interface TeamMember {
id: string;
name: string;
role: string;
/** Filter group, e.g. "Engineering". */
department?: string;
bio?: ReactNode;
location?: string;
/** Portrait: an image URL or any node (illustration, gradient). Falls back to initials. */
photo?: string | ReactNode;
/** Background for the initials fallback (any CSS color). */
color?: string;
socials?: TeamSocialLink[];
}
export interface TeamSectionProps {
members: TeamMember[];
eyebrow?: ReactNode;
heading?: ReactNode;
description?: ReactNode;
/** Show department chips. Default true when members span 2+ departments. */
filterable?: boolean;
/** Department order. Defaults to first-seen order in `members`. */
departments?: string[];
allLabel?: string;
/** Controlled active department (`allLabel` or a department). */
department?: string;
defaultDepartment?: string;
onDepartmentChange?: (department: string) => void;
/** Most columns at wide container sizes. Default 4. */
columns?: 2 | 3 | 4;
/** Called when a member's detail panel opens. */
onMemberOpen?: (member: TeamMember) => void;
className?: string;
}
// Static class maps so Tailwind sees every class.
const GRID_COLS: Record<2 | 3 | 4, string> = {
2: "@lg:grid-cols-2",
3: "@lg:grid-cols-3",
4: "@lg:grid-cols-3 @3xl:grid-cols-4",
};
const STAGGER = 0.06;
const CHART_VARS = [1, 2, 3, 4, 5].map((n) => `var(--chart-${n})`);
/** Deterministic fallback color from the name, so SSR and client agree. */
function colorFor(member: TeamMember) {
if (member.color) return member.color;
let hash = 0;
for (const ch of member.name) hash = (hash * 31 + ch.charCodeAt(0)) | 0;
return CHART_VARS[Math.abs(hash) % CHART_VARS.length];
}
function initials(name: string) {
const parts = name.trim().split(/\s+/);
const last = parts.length > 1 ? (parts[parts.length - 1]?.[0] ?? "") : "";
return ((parts[0]?.[0] ?? "") + last).toUpperCase();
}
function Portrait({ member, className }: { member: TeamMember; className?: string }) {
if (typeof member.photo === "string") {
return (
// biome-ignore lint/performance/noImgElement: library component, framework-agnostic.
<img src={member.photo} alt="" className={cn("block h-full w-full object-cover", className)} />
);
}
if (member.photo) {
return <div className={cn("h-full w-full", className)}>{member.photo}</div>;
}
const color = colorFor(member);
return (
<div
className={cn("grid h-full w-full place-items-center", className)}
style={{
background: `linear-gradient(140deg, color-mix(in oklab, ${color} 55%, var(--card)), color-mix(in oklab, ${color} 20%, var(--card)))`,
}}
>
<span className="text-3xl font-semibold tracking-tight text-foreground/80">
{initials(member.name)}
</span>
</div>
);
}
function SocialLinks({
socials,
size = "sm",
className,
}: {
socials: TeamSocialLink[];
size?: "sm" | "md";
className?: string;
}) {
return (
<ul className={cn("m-0 flex list-none gap-1.5 p-0", className)}>
{socials.map((social) => (
<li key={social.href}>
<a
href={social.href}
aria-label={social.label}
target="_blank"
rel="noreferrer noopener"
className={cn(
"grid place-items-center rounded-full border border-border bg-card text-muted-foreground outline-none transition-colors hover:border-border-strong hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
size === "sm" ? "size-7 [&_svg]:size-3.5" : "size-9 [&_svg]:size-4",
)}
>
{social.icon}
</a>
</li>
))}
</ul>
);
}
/**
* Team page section: a header (eyebrow, heading, description), department
* filter chips with a gliding pill, and a grid of member cards that stagger in
* on view. Hovering or focusing a card slides up its bio and social links;
* clicking a member opens a detail dialog with the full bio and links. The
* grid reflows with spring layout when the filter changes and picks its
* column count from its own container width.
*/
export function TeamSection({
members,
eyebrow = "Team",
heading = "The people behind the work",
description,
filterable,
departments: departmentsProp,
allLabel = "Everyone",
department: departmentProp,
defaultDepartment,
onDepartmentChange,
columns = 4,
onMemberOpen,
className,
}: TeamSectionProps) {
const reduce = useReducedMotion() ?? false;
const canHover = useHoverCapable();
const uid = useId();
const departments = useMemo(() => {
if (departmentsProp) return departmentsProp;
const seen: string[] = [];
for (const member of members) {
if (member.department && !seen.includes(member.department)) seen.push(member.department);
}
return seen;
}, [members, departmentsProp]);
const showFilters = filterable ?? departments.length > 1;
const [internal, setInternal] = useState(defaultDepartment ?? allLabel);
const active = departmentProp ?? internal;
const setActive = (next: string) => {
if (departmentProp === undefined) setInternal(next);
onDepartmentChange?.(next);
};
const visible = useMemo(
() => (active === allLabel ? members : members.filter((m) => m.department === active)),
[members, active, allLabel],
);
// Keep the last member while the dialog plays its exit.
const [selected, setSelected] = useState<TeamMember | null>(null);
const [open, setOpen] = useState(false);
const openMember = (member: TeamMember) => {
setSelected(member);
setOpen(true);
onMemberOpen?.(member);
};
const layoutTransition = reduce ? { duration: 0 } : SPRING_LAYOUT;
const item: Variants = {
hidden: { opacity: 0, y: reduce ? 0 : 16 },
show: { opacity: 1, y: 0, transition: { duration: 0.45, ease: EASE_OUT } },
exit: {
opacity: 0,
scale: reduce ? 1 : 0.96,
transition: { duration: 0.15, ease: EASE_OUT },
},
};
return (
<section className={cn("@container w-full text-foreground", className)}>
<LayoutGroup id={uid}>
<div className="mb-6 flex flex-col gap-3">
{eyebrow ? (
<p className="text-xs font-medium uppercase tracking-[0.2em] text-muted-foreground">
{eyebrow}
</p>
) : null}
{heading ? (
<h2 className="text-balance text-2xl font-semibold leading-tight tracking-tight @3xl:text-3xl">
{heading}
</h2>
) : null}
{description ? (
<p className="max-w-xl text-pretty text-sm leading-6 text-muted-foreground">
{description}
</p>
) : null}
</div>
{showFilters ? (
<fieldset className="-mx-1 mb-5 flex min-w-0 gap-1 overflow-x-auto px-1 py-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
<legend className="sr-only">Filter by department</legend>
{[allLabel, ...departments].map((name) => {
const isActive = name === active;
return (
<button
key={name}
type="button"
aria-pressed={isActive}
onClick={() => setActive(name)}
className={cn(
"relative h-8 shrink-0 rounded-full px-3.5 text-xs font-medium outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring",
isActive ? "text-primary-foreground" : "text-muted-foreground hover:text-foreground",
)}
>
{isActive ? (
<motion.span
aria-hidden
layoutId={`${uid}-chip`}
transition={layoutTransition}
className="absolute inset-0 rounded-full bg-primary"
/>
) : null}
<span className="relative">{name}</span>
</button>
);
})}
</fieldset>
) : null}
<motion.ul
initial="hidden"
whileInView="show"
viewport={{ once: true, amount: 0.15 }}
variants={{ show: { transition: { staggerChildren: STAGGER } } }}
className={cn("m-0 grid list-none grid-cols-2 gap-3 p-0", GRID_COLS[columns])}
>
<AnimatePresence mode="popLayout">
{visible.map((member) => (
// Layout animation is the point: cards glide into the gaps
// left by members filtered out.
<motion.li
key={member.id}
layout={!reduce}
variants={item}
exit="exit"
transition={{ layout: layoutTransition }}
>
<MemberCard
member={member}
canHover={canHover}
reduce={reduce}
onOpen={() => openMember(member)}
/>
</motion.li>
))}
</AnimatePresence>
</motion.ul>
</LayoutGroup>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="max-w-lg">
{selected ? <MemberDetail member={selected} /> : null}
</DialogContent>
</Dialog>
</section>
);
}
function MemberCard({
member,
canHover,
reduce,
onOpen,
}: {
member: TeamMember;
canHover: boolean;
reduce: boolean;
onOpen: () => void;
}) {
const socials = member.socials ?? [];
const reveal = canHover && (member.bio || socials.length > 0);
return (
<article className="group/member relative isolate flex h-full flex-col overflow-hidden rounded-2xl border border-border bg-card text-card-foreground transition-colors hover:border-border-strong">
<div className="relative aspect-[4/5] overflow-hidden bg-muted">
<div
className={cn(
"h-full w-full transition-transform duration-500",
canHover && !reduce && "group-hover/member:scale-[1.04]",
)}
style={{ transitionTimingFunction: EASE_OUT_CSS }}
>
<Portrait member={member} />
</div>
{reveal ? (
// Hover/focus reveal. Sits above the stretched button (z-20) so the
// social links stay clickable; the panel itself lets clicks through.
<div
className={cn(
"pointer-events-none absolute inset-x-2 bottom-2 z-20 flex flex-col gap-2 rounded-xl border border-border bg-card/90 p-2.5 opacity-0 shadow-lg backdrop-blur transition duration-300",
"group-hover/member:opacity-100 group-focus-within/member:opacity-100",
!reduce &&
"translate-y-3 group-hover/member:translate-y-0 group-focus-within/member:translate-y-0",
)}
style={{ transitionTimingFunction: EASE_OUT_CSS }}
>
{member.bio ? (
<p className="line-clamp-3 text-xs leading-5 text-muted-foreground">{member.bio}</p>
) : null}
{socials.length > 0 ? (
<SocialLinks socials={socials} className="pointer-events-auto" />
) : null}
</div>
) : null}
</div>
<div className="flex flex-1 flex-col gap-0.5 p-3">
<h3 className="text-sm font-semibold leading-snug">
{/* Stretched button: its ::after covers the card, so the whole
card opens the detail panel while staying one tab stop. */}
<button
type="button"
onClick={onOpen}
aria-haspopup="dialog"
className="rounded-sm text-left outline-none after:absolute after:inset-0 after:z-10 after:rounded-[inherit] after:content-[''] focus-visible:ring-2 focus-visible:ring-ring"
>
{member.name}
</button>
</h3>
<p className="text-xs text-muted-foreground">{member.role}</p>
{!canHover && socials.length > 0 ? (
<SocialLinks socials={socials} className="relative z-20 mt-2" />
) : null}
</div>
</article>
);
}
function MemberDetail({ member }: { member: TeamMember }) {
const socials = member.socials ?? [];
return (
<>
<div className="flex items-center gap-4">
<div className="size-20 shrink-0 overflow-hidden rounded-2xl border border-border bg-muted">
<Portrait member={member} className="[&_span]:text-xl" />
</div>
<DialogHeader>
<DialogTitle>{member.name}</DialogTitle>
<DialogDescription>{member.role}</DialogDescription>
<div className="mt-1 flex flex-wrap gap-1.5 text-xs text-muted-foreground">
{member.department ? (
<span className="rounded-full border border-border bg-card px-2 py-0.5">
{member.department}
</span>
) : null}
{member.location ? (
<span className="inline-flex items-center gap-1 rounded-full border border-border bg-card px-2 py-0.5">
<MapPin aria-hidden className="size-3" />
{member.location}
</span>
) : null}
</div>
</DialogHeader>
</div>
{member.bio ? (
<p className="text-pretty text-sm leading-6 text-muted-foreground">{member.bio}</p>
) : null}
{socials.length > 0 ? (
<ul className="m-0 flex list-none flex-wrap gap-2 p-0">
{socials.map((social) => (
<li key={social.href}>
<a
href={social.href}
target="_blank"
rel="noreferrer noopener"
className="inline-flex h-9 items-center gap-2 rounded-full border border-border bg-card px-3 text-sm text-foreground outline-none transition-colors hover:border-border-strong focus-visible:ring-2 focus-visible:ring-ring [&_svg]:size-4"
>
{social.icon}
{social.label}
<ArrowUpRight aria-hidden className="size-3.5 text-muted-foreground" />
</a>
</li>
))}
</ul>
) : null}
</>
);
}
"use client";
import { X } from "lucide-react";
import {
AnimatePresence,
animate,
motion,
useIsPresent,
useReducedMotion,
} from "motion/react";
import {
type ComponentPropsWithoutRef,
type MouseEvent,
type ReactElement,
type ReactNode,
type RefObject,
cloneElement,
createContext,
forwardRef,
isValidElement,
useCallback,
useContext,
useEffect,
useId,
useMemo,
useRef,
useState,
useSyncExternalStore,
} from "react";
import { createPortal } from "react-dom";
import { Button, type ButtonProps } from "@/components/motion/button";
import { Input, type InputProps } from "@/components/motion/input";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
/* -------------------------------------------------------------------------- */
/* Shared plumbing */
/* -------------------------------------------------------------------------- */
const FOCUSABLE_SELECTOR = [
"a[href]",
"button:not([disabled])",
"input:not([disabled]):not([type='hidden'])",
"select:not([disabled])",
"textarea:not([disabled])",
"[contenteditable='true']",
'[tabindex]:not([tabindex="-1"])',
].join(",");
function getFocusable(root: HTMLElement | null) {
if (!root) return [];
return Array.from(root.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).filter(
(el) => el.tabIndex >= 0 && !el.closest("[inert]") && el.getClientRects().length > 0,
);
}
// Open dialogs, innermost last. Only the top one answers Escape and Tab, so an
// AlertDialog opened from inside a Dialog doesn't close both at once.
const dialogStack: string[] = [];
// Reference-counted body scroll lock. The scrollbar's width is put back as
// padding so the page behind doesn't jump sideways when the bar disappears.
let lockCount = 0;
let savedBodyStyle: { overflow: string; paddingRight: string } | null = null;
function lockScroll() {
lockCount += 1;
if (lockCount > 1) return;
const body = document.body;
const scrollbar = window.innerWidth - document.documentElement.clientWidth;
savedBodyStyle = {
overflow: body.style.overflow,
paddingRight: body.style.paddingRight,
};
if (scrollbar > 0) {
const current = Number.parseFloat(getComputedStyle(body).paddingRight) || 0;
body.style.paddingRight = `${current + scrollbar}px`;
}
body.style.overflow = "hidden";
}
function unlockScroll() {
lockCount = Math.max(0, lockCount - 1);
if (lockCount > 0 || !savedBodyStyle) return;
document.body.style.overflow = savedBodyStyle.overflow;
document.body.style.paddingRight = savedBodyStyle.paddingRight;
savedBodyStyle = null;
}
const SM_QUERY = "(max-width: 639.98px)";
function subscribeSmall(callback: () => void) {
const mql = window.matchMedia(SM_QUERY);
mql.addEventListener("change", callback);
return () => mql.removeEventListener("change", callback);
}
/** True below Tailwind's `sm` breakpoint. Always false on the server. */
function useBelowSm() {
return useSyncExternalStore(
subscribeSmall,
() => window.matchMedia(SM_QUERY).matches,
() => false,
);
}
const SHAKE_X = [0, -7, 7, -5, 5, -2, 0];
/* -------------------------------------------------------------------------- */
/* Context */
/* -------------------------------------------------------------------------- */
type DialogContextValue = {
open: boolean;
setOpen: (open: boolean) => void;
alert: boolean;
contentId: string;
titleId: string;
descriptionId: string;
hasDescription: boolean;
setHasDescription: (value: boolean) => void;
/** Type-to-confirm (AlertDialog only). */
confirmText?: string;
confirmValue: string;
setConfirmValue: (value: string) => void;
confirmValid: boolean;
confirmAttempted: boolean;
setConfirmAttempted: (value: boolean) => void;
confirmFieldRef: RefObject<HTMLDivElement | null>;
confirmInputRef: RefObject<HTMLInputElement | null>;
};
const DialogContext = createContext<DialogContextValue | null>(null);
function useDialogContext(component: string) {
const context = useContext(DialogContext);
if (!context) {
throw new Error(`${component} must be used within <Dialog> or <AlertDialog>`);
}
return context;
}
export interface DialogProps {
children: ReactNode;
/** Controlled open state. */
open?: boolean;
/** Initial open state when uncontrolled. */
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
}
function DialogRoot({
children,
open: openProp,
defaultOpen = false,
onOpenChange,
alert,
confirmText,
}: DialogProps & { alert: boolean; confirmText?: string }) {
const id = useId();
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const controlled = openProp !== undefined;
const open = controlled ? openProp : internalOpen;
const [hasDescription, setHasDescription] = useState(false);
const [confirmValue, setConfirmValue] = useState("");
const [confirmAttempted, setConfirmAttempted] = useState(false);
const confirmFieldRef = useRef<HTMLDivElement>(null);
const confirmInputRef = useRef<HTMLInputElement>(null);
const setOpen = useCallback(
(next: boolean) => {
if (!controlled) setInternalOpen(next);
onOpenChange?.(next);
},
[controlled, onOpenChange],
);
// A fresh confirmation every time the dialog opens.
useEffect(() => {
if (!open) return;
setConfirmValue("");
setConfirmAttempted(false);
}, [open]);
const confirmValid =
confirmText === undefined || confirmValue.trim() === confirmText;
const value = useMemo<DialogContextValue>(
() => ({
open,
setOpen,
alert,
contentId: `${id}-content`,
titleId: `${id}-title`,
descriptionId: `${id}-description`,
hasDescription,
setHasDescription,
confirmText,
confirmValue,
setConfirmValue,
confirmValid,
confirmAttempted,
setConfirmAttempted,
confirmFieldRef,
confirmInputRef,
}),
[
open,
setOpen,
alert,
id,
hasDescription,
confirmText,
confirmValue,
confirmValid,
confirmAttempted,
],
);
return <DialogContext.Provider value={value}>{children}</DialogContext.Provider>;
}
/**
* Modal dialog root. Holds open state (controlled via `open`/`onOpenChange`
* or uncontrolled via `defaultOpen`) for its Trigger, Content and Close parts.
*/
export function Dialog(props: DialogProps) {
return <DialogRoot {...props} alert={false} />;
}
export interface AlertDialogProps extends DialogProps {
/**
* Require the user to type this exact text (e.g. the project name) into
* `AlertDialogConfirmInput` before `AlertDialogAction` goes through.
*/
confirmText?: string;
}
/**
* Interrupting confirmation. Renders `role="alertdialog"`, never closes on an
* outside click, and focuses `AlertDialogCancel` first so a stray Enter can't
* confirm a destructive action.
*/
export function AlertDialog({ confirmText, ...props }: AlertDialogProps) {
return <DialogRoot {...props} alert confirmText={confirmText} />;
}
/* -------------------------------------------------------------------------- */
/* Trigger & Close */
/* -------------------------------------------------------------------------- */
type ClonableChild = ReactElement<Record<string, unknown>>;
function composeClick(
child: ClonableChild,
action: () => void,
): (event: MouseEvent<HTMLElement>) => void {
const childOnClick = child.props.onClick as
| ((event: MouseEvent<HTMLElement>) => void)
| undefined;
return (event) => {
childOnClick?.(event);
if (!event.defaultPrevented) action();
};
}
export interface DialogTriggerProps extends ButtonProps {
/** Merge behaviour onto the single child element instead of rendering a `Button`. */
asChild?: boolean;
}
/** Opens the dialog. Renders a library `Button`, or wraps its child with `asChild`. */
export const DialogTrigger = forwardRef<HTMLButtonElement, DialogTriggerProps>(
function DialogTrigger({ asChild, children, onClick, ...rest }, ref) {
const context = useDialogContext("DialogTrigger");
const aria = {
"aria-haspopup": "dialog" as const,
"aria-expanded": context.open,
"aria-controls": context.open ? context.contentId : undefined,
};
if (asChild && isValidElement(children)) {
const child = children as ClonableChild;
return cloneElement(child, {
...aria,
onClick: composeClick(child, () => context.setOpen(true)),
});
}
return (
<Button
ref={ref}
{...rest}
{...aria}
onClick={(event) => {
onClick?.(event);
if (!event.defaultPrevented) context.setOpen(true);
}}
>
{children}
</Button>
);
},
);
export interface DialogCloseProps extends ButtonProps {
/** Merge behaviour onto the single child element instead of rendering a `Button`. */
asChild?: boolean;
}
/** Closes the dialog. Renders a library `Button` (outline by default), or wraps its child. */
export const DialogClose = forwardRef<HTMLButtonElement, DialogCloseProps>(
function DialogClose(
{ asChild, children, onClick, variant = "outline", ...rest },
ref,
) {
const context = useDialogContext("DialogClose");
if (asChild && isValidElement(children)) {
const child = children as ClonableChild;
return cloneElement(child, {
onClick: composeClick(child, () => context.setOpen(false)),
});
}
return (
<Button
ref={ref}
variant={variant}
{...rest}
onClick={(event) => {
onClick?.(event);
if (!event.defaultPrevented) context.setOpen(false);
}}
>
{children}
</Button>
);
},
);
/* -------------------------------------------------------------------------- */
/* Content */
/* -------------------------------------------------------------------------- */
export interface DialogContentProps {
children: ReactNode;
className?: string;
/** Class for the dimmed, blurred backdrop. */
overlayClassName?: string;
/** Show the corner close (X) button. Default true for Dialog, false for AlertDialog. */
showCloseButton?: boolean;
closeLabel?: string;
/**
* Close when the backdrop is pressed. Default true for Dialog; AlertDialog
* ignores it and never closes on an outside press.
*/
closeOnOutsideClick?: boolean;
/** Element to focus on open. Falls back to `[data-dialog-autofocus]`, then the first focusable. */
initialFocus?: RefObject<HTMLElement | null>;
/** Become a bottom-anchored sheet below the `sm` breakpoint. Default true. */
sheetOnMobile?: boolean;
/** Accessible name, when the content has no `DialogTitle`. */
"aria-label"?: string;
}
const ENTER = { duration: 0.22, ease: EASE_OUT } as const;
const EXIT = { duration: 0.14, ease: EASE_OUT } as const;
function DialogContentInner({
children,
className,
overlayClassName,
showCloseButton,
closeLabel = "Close",
closeOnOutsideClick = true,
initialFocus,
sheetOnMobile = true,
"aria-label": ariaLabel,
}: DialogContentProps) {
const context = useDialogContext("DialogContent");
const reduce = useReducedMotion() ?? false;
const isPresent = useIsPresent();
const belowSm = useBelowSm();
const sheet = sheetOnMobile && belowSm;
const panelRef = useRef<HTMLDivElement>(null);
const stackId = useId();
const { setOpen } = context;
// Read through a ref so a new onOpenChange identity (inline handlers) does
// not re-run the focus/scroll-lock effect and yank focus mid-typing.
const setOpenRef = useRef(setOpen);
const initialFocusRef = useRef(initialFocus);
useEffect(() => {
setOpenRef.current = setOpen;
initialFocusRef.current = initialFocus;
});
const dismissOutside = closeOnOutsideClick && !context.alert;
const withClose = showCloseButton ?? !context.alert;
// Scroll lock, stack registration, initial focus, focus trap, Escape and
// focus return. Runs while this panel is mounted *and* present, so the
// exit animation already behaves like a closed dialog.
useEffect(() => {
if (!isPresent) return;
const returnTo =
document.activeElement instanceof HTMLElement ? document.activeElement : null;
dialogStack.push(stackId);
lockScroll();
const frame = requestAnimationFrame(() => {
const panel = panelRef.current;
if (!panel) return;
const target =
initialFocusRef.current?.current ??
panel.querySelector<HTMLElement>("[data-dialog-autofocus]") ??
getFocusable(panel).find((el) => !el.hasAttribute("data-dialog-close-x")) ??
panel;
target.focus({ preventScroll: true });
});
const onKeyDown = (event: KeyboardEvent) => {
if (dialogStack[dialogStack.length - 1] !== stackId) return;
if (event.key === "Escape") {
event.preventDefault();
setOpenRef.current(false);
return;
}
if (event.key !== "Tab") return;
const panel = panelRef.current;
const focusable = getFocusable(panel);
if (focusable.length === 0) {
event.preventDefault();
panel?.focus();
return;
}
const first = focusable[0];
const last = focusable[focusable.length - 1];
const active = document.activeElement;
const outside = !panel?.contains(active);
if (event.shiftKey && (active === first || active === panel || outside)) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && (active === last || outside)) {
event.preventDefault();
first.focus();
}
};
document.addEventListener("keydown", onKeyDown);
return () => {
cancelAnimationFrame(frame);
document.removeEventListener("keydown", onKeyDown);
const index = dialogStack.lastIndexOf(stackId);
if (index !== -1) dialogStack.splice(index, 1);
unlockScroll();
if (returnTo?.isConnected) returnTo.focus({ preventScroll: true });
};
}, [isPresent, stackId]);
const panelInitial = reduce
? { opacity: 0 }
: sheet
? { opacity: 0, y: "100%" }
: { opacity: 0, scale: 0.96 };
const panelExit = reduce
? { opacity: 0, transition: EXIT }
: sheet
? { opacity: 0, y: "100%", transition: { duration: 0.2, ease: EASE_OUT } }
: { opacity: 0, scale: 0.97, transition: EXIT };
return (
<div
className="pointer-events-none fixed inset-0 z-[100]"
style={{ pointerEvents: isPresent ? undefined : "none" }}
>
<motion.button
type="button"
aria-label={closeLabel}
tabIndex={-1}
disabled={!dismissOutside}
onClick={() => setOpen(false)}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0, transition: EXIT }}
transition={ENTER}
className={cn(
"pointer-events-auto absolute inset-0 h-full w-full cursor-default bg-black/35 backdrop-blur-sm disabled:cursor-default dark:bg-black/55",
overlayClassName,
)}
/>
<div
className={cn(
"pointer-events-none absolute inset-0 flex justify-center",
sheet ? "items-end" : "items-center p-4",
)}
>
<motion.div
ref={panelRef}
id={context.contentId}
role={context.alert ? "alertdialog" : "dialog"}
aria-modal="true"
aria-label={ariaLabel}
aria-labelledby={ariaLabel ? undefined : context.titleId}
aria-describedby={context.hasDescription ? context.descriptionId : undefined}
tabIndex={-1}
initial={panelInitial}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={panelExit}
transition={reduce ? ENTER : sheet ? { duration: 0.32, ease: EASE_OUT } : ENTER}
style={{ pointerEvents: isPresent ? "auto" : "none" }}
className={cn(
"relative flex w-full flex-col gap-5 overflow-y-auto border-border bg-background p-6 text-foreground shadow-2xl outline-none",
"[scrollbar-color:var(--border-strong)_transparent] [scrollbar-width:thin]",
sheet
? "max-h-[88dvh] rounded-t-3xl border-t pb-[max(1.5rem,env(safe-area-inset-bottom))]"
: "max-h-[calc(100dvh-2rem)] max-w-md rounded-3xl border",
className,
)}
>
{sheet ? (
<span
aria-hidden="true"
className="mx-auto -mt-2 -mb-1 h-1 w-10 shrink-0 rounded-full bg-foreground/15"
/>
) : null}
{children}
{withClose ? (
<button
type="button"
aria-label={closeLabel}
data-dialog-close-x=""
onClick={() => setOpen(false)}
className="absolute top-4 right-4 inline-flex size-8 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-foreground/[0.06] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<X className="size-4" aria-hidden="true" />
</button>
) : null}
</motion.div>
</div>
</div>
);
}
/**
* The modal surface. Portals to `document.body`, fades a blurred backdrop in,
* scales the panel from 0.96 (fade only under reduced motion), traps focus,
* closes on Escape and returns focus to whatever opened it.
*/
export function DialogContent(props: DialogContentProps) {
const context = useDialogContext("DialogContent");
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if (!mounted) return null;
return createPortal(
<AnimatePresence>
{context.open ? <DialogContentInner key="dialog" {...props} /> : null}
</AnimatePresence>,
document.body,
);
}
/* -------------------------------------------------------------------------- */
/* Text & layout */
/* -------------------------------------------------------------------------- */
export function DialogHeader({
className,
...props
}: ComponentPropsWithoutRef<"div">) {
return (
<div
className={cn("flex flex-col gap-1.5 pr-8 text-left", className)}
{...props}
/>
);
}
export function DialogFooter({
className,
...props
}: ComponentPropsWithoutRef<"div">) {
return (
<div
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className,
)}
{...props}
/>
);
}
export function DialogTitle({
className,
...props
}: Omit<ComponentPropsWithoutRef<"h2">, "id">) {
const context = useDialogContext("DialogTitle");
return (
<h2
id={context.titleId}
className={cn("text-lg font-semibold tracking-tight", className)}
{...props}
/>
);
}
export function DialogDescription({
className,
...props
}: Omit<ComponentPropsWithoutRef<"p">, "id">) {
const context = useDialogContext("DialogDescription");
const { setHasDescription } = context;
useEffect(() => {
setHasDescription(true);
return () => setHasDescription(false);
}, [setHasDescription]);
return (
<p
id={context.descriptionId}
className={cn("text-sm leading-relaxed text-muted-foreground", className)}
{...props}
/>
);
}
/* -------------------------------------------------------------------------- */
/* AlertDialog parts */
/* -------------------------------------------------------------------------- */
export const AlertDialogTrigger = DialogTrigger;
export type AlertDialogTriggerProps = DialogTriggerProps;
export const AlertDialogHeader = DialogHeader;
export const AlertDialogFooter = DialogFooter;
export const AlertDialogTitle = DialogTitle;
export const AlertDialogDescription = DialogDescription;
export type AlertDialogContentProps = Omit<
DialogContentProps,
"closeOnOutsideClick"
>;
export function AlertDialogContent(props: AlertDialogContentProps) {
return <DialogContent {...props} />;
}
export interface AlertDialogCancelProps extends ButtonProps {}
/** The safe choice. Receives initial focus when the AlertDialog opens. */
export const AlertDialogCancel = forwardRef<HTMLButtonElement, AlertDialogCancelProps>(
function AlertDialogCancel({ children = "Cancel", ...props }, ref) {
return (
<DialogClose ref={ref} data-dialog-autofocus="" {...props}>
{children}
</DialogClose>
);
},
);
export interface AlertDialogActionProps extends ButtonProps {
/** `destructive` (default) paints the button in the destructive token. */
tone?: "destructive" | "default";
}
/**
* The confirming action. Closes the dialog after `onClick` unless the handler
* calls `event.preventDefault()`. With `confirmText` set on the AlertDialog it
* stays `aria-disabled` until the text matches; pressing it early shakes the
* confirm field and moves focus there.
*/
export const AlertDialogAction = forwardRef<HTMLButtonElement, AlertDialogActionProps>(
function AlertDialogAction(
{ tone = "destructive", className, onClick, children, ...props },
ref,
) {
const context = useDialogContext("AlertDialogAction");
const reduce = useReducedMotion();
const blocked = !context.confirmValid;
return (
<Button
ref={ref}
variant="primary"
aria-disabled={blocked || undefined}
data-alert-dialog-action=""
{...props}
className={cn(
tone === "destructive" &&
"bg-destructive text-white hover:bg-destructive/90",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
blocked && "opacity-55",
blocked &&
(tone === "destructive" ? "hover:bg-destructive" : "hover:bg-primary"),
className,
)}
onClick={(event) => {
if (blocked) {
event.preventDefault();
// The field's own error shake plays the first time the message
// appears; later attempts shake it here instead.
const errorShowing = context.confirmAttempted;
context.setConfirmAttempted(true);
const field = context.confirmFieldRef.current;
if (field && errorShowing && !reduce) {
animate(field, { x: SHAKE_X }, { duration: 0.4 });
}
context.confirmInputRef.current?.focus();
return;
}
onClick?.(event);
if (!event.defaultPrevented) context.setOpen(false);
}}
>
{children}
</Button>
);
},
);
export interface AlertDialogConfirmInputProps
extends Omit<InputProps, "value" | "defaultValue" | "onChange" | "error"> {
/** Message shown when confirming with a mismatch. */
mismatchMessage?: string;
}
/**
* Type-to-confirm field for an `AlertDialog` with `confirmText`. Enter submits
* through `AlertDialogAction`'s rules.
*/
export function AlertDialogConfirmInput({
label,
mismatchMessage = "That doesn't match. Check the spelling and try again.",
className,
onKeyDown,
...props
}: AlertDialogConfirmInputProps) {
const context = useDialogContext("AlertDialogConfirmInput");
const target = context.confirmText ?? "";
const showError = context.confirmAttempted && !context.confirmValid;
return (
<div ref={context.confirmFieldRef} className={className}>
<Input
ref={context.confirmInputRef}
label={label ?? `Type "${target}" to confirm`}
autoComplete="off"
autoCapitalize="off"
spellCheck={false}
{...props}
value={context.confirmValue}
onChange={context.setConfirmValue}
error={showError ? mismatchMessage : undefined}
success={target !== "" && context.confirmValid}
onKeyDown={(event) => {
onKeyDown?.(event);
if (event.defaultPrevented || event.key !== "Enter") return;
event.preventDefault();
const panel = event.currentTarget.closest<HTMLElement>("[role='alertdialog']");
panel?.querySelector<HTMLButtonElement>("[data-alert-dialog-action]")?.click();
}}
/>
</div>
);
}
export type {
ButtonLinkProps,
ButtonProps,
ButtonSize,
ButtonVariant,
} from "./base";
export { Button, ButtonLink } from "./base";
export type { MagneticButtonProps } from "./magnetic";
export { MagneticButton } from "./magnetic";
export type { ButtonState, StatefulButtonProps } from "./stateful";
export { StatefulButton } from "./stateful";
"use client";
import {
AnimatePresence,
animate,
motion,
useReducedMotion,
} from "motion/react";
import {
forwardRef,
useEffect,
useId,
useRef,
useState,
type InputHTMLAttributes,
type ReactNode,
} from "react";
import { cn } from "@/lib/utils";
export type InputClassNames = {
root?: string;
label?: string;
field?: string;
input?: string;
leftIcon?: string;
rightIcon?: string;
successIcon?: string;
errorMessage?: string;
};
export interface InputProps extends Omit<
InputHTMLAttributes<HTMLInputElement>,
"value" | "defaultValue" | "onChange"
> {
label?: string;
value?: string;
defaultValue?: string;
onChange?: (value: string) => void;
/** Truthy error triggers a shake, red border and (if a string) a message. */
error?: string | boolean;
success?: boolean;
leftIcon?: ReactNode;
rightIcon?: ReactNode;
className?: string;
classNames?: InputClassNames;
}
export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
{
label,
value: valueProp,
defaultValue,
onChange,
onFocus,
onBlur,
error,
success,
leftIcon,
rightIcon,
className,
classNames,
disabled,
id: idProp,
type,
...rest
},
ref,
) {
const reactId = useId();
const id = idProp ?? reactId;
const reduce = useReducedMotion();
const controlled = valueProp !== undefined;
const [internal, setInternal] = useState(defaultValue ?? "");
const value = controlled ? (valueProp ?? "") : internal;
const [focused, setFocused] = useState(false);
const fieldRef = useRef<HTMLDivElement>(null);
const hasError = Boolean(error);
const errorMessage = typeof error === "string" ? error : null;
// Right edge shows the success check, otherwise the caller's right icon.
const rightSlot = success ? null : rightIcon;
// Shake the field when an error appears.
useEffect(() => {
if (!fieldRef.current || reduce || !hasError) return;
animate(
fieldRef.current,
{ x: [0, -6, 6, -4, 4, -2, 0] },
{ duration: 0.45 },
);
}, [hasError, reduce]);
const handleChange = (next: string) => {
if (!controlled) setInternal(next);
onChange?.(next);
};
return (
<div
className={cn("flex flex-col gap-1.5", className, classNames?.root)}
>
{label ? (
<label
htmlFor={id}
className={cn(
"px-1 text-sm font-medium text-foreground",
classNames?.label,
)}
>
{label}
</label>
) : null}
<div
ref={fieldRef}
data-state={
hasError
? "error"
: success
? "success"
: focused
? "focused"
: "idle"
}
className={cn(
"relative h-11 overflow-hidden rounded-full border transition-colors duration-200",
"border-border",
focused && !hasError && "border-foreground/40 ring-2 ring-ring/40",
hasError && "border-destructive ring-2 ring-destructive/25",
disabled && "opacity-60",
classNames?.field,
)}
>
{leftIcon ? (
<span
className={cn(
"pointer-events-none absolute left-3 top-1/2 flex -translate-y-1/2 items-center text-muted-foreground [&_svg]:h-4 [&_svg]:w-4",
classNames?.leftIcon,
)}
>
{leftIcon}
</span>
) : null}
<input
ref={ref}
id={id}
type={type}
value={value}
disabled={disabled}
aria-invalid={hasError || undefined}
aria-describedby={errorMessage ? `${id}-error` : undefined}
{...rest}
onChange={(e) => handleChange(e.target.value)}
onFocus={(event) => {
setFocused(true);
onFocus?.(event);
}}
onBlur={(event) => {
setFocused(false);
onBlur?.(event);
}}
className={cn(
"peer h-full w-full bg-transparent text-base leading-6 text-foreground caret-foreground outline-none",
"placeholder:text-muted-foreground/60",
leftIcon ? "pl-10" : "pl-3.5",
rightSlot || success ? "pr-10" : "pr-3.5",
disabled && "cursor-not-allowed",
classNames?.input,
)}
/>
{success ? (
<motion.svg
viewBox="0 0 24 24"
fill="none"
className={cn(
"absolute right-3.5 top-1/2 h-5 w-5 -translate-y-1/2 text-(--color-success)",
classNames?.successIcon,
)}
>
<motion.path
d="M5 12.5l4.5 4.5L19 7.5"
stroke="currentColor"
strokeWidth={2.5}
strokeLinecap="round"
strokeLinejoin="round"
initial={reduce ? { pathLength: 1 } : { pathLength: 0 }}
animate={{ pathLength: 1 }}
transition={{ duration: 0.35, ease: "easeOut" }}
/>
</motion.svg>
) : rightSlot ? (
<span
className={cn(
"absolute right-0 top-0 flex h-full items-center text-muted-foreground [&_button]:grid [&_button]:size-11 [&_button]:place-items-center [&_svg]:h-4 [&_svg]:w-4",
classNames?.rightIcon,
)}
>
{rightSlot}
</span>
) : null}
</div>
<AnimatePresence initial={false}>
{errorMessage ? (
<motion.p
id={`${id}-error`}
role="alert"
initial={
reduce
? { opacity: 0 }
: { opacity: 0, y: -4, filter: "blur(4px)" }
}
animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
exit={
reduce
? { opacity: 0 }
: { opacity: 0, y: -4, filter: "blur(4px)" }
}
transition={{ duration: 0.2 }}
className={cn(
"px-1 text-xs text-destructive",
classNames?.errorMessage,
)}
>
{errorMessage}
</motion.p>
) : null}
</AnimatePresence>
</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 { TOUCH_TARGET_CLASS } from "@/lib/touch";
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-primary/5",
outline:
"border border-border bg-transparent text-foreground hover:bg-primary/5",
};
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(
"relative inline-flex items-center justify-center font-medium select-none",
"transition-colors",
"disabled:pointer-events-none disabled:opacity-50",
// The ripple layer clips itself, so on a touch screen the button can
// stop clipping and let its enlarged hit area overhang.
ripple && "overflow-hidden pointer-coarse:overflow-visible",
TOUCH_TARGET_CLASS,
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(
"relative inline-flex items-center justify-center font-medium select-none",
"transition-colors",
TOUCH_TARGET_CLASS,
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 { 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>
);
}
@karaui not found? Add it to components.json
{
"registries": {
"@karaui": "https://karaui.kamisama-v0.my.id/r/{name}.json"
}
}@karaui is in shadcn's public registry directory, so the latest CLI needs no setup. On an older CLI, merge this into the existing file once and every @karaui/… install resolves.
API Reference
membersTeamMember[]—eyebrow?ReactNodeTeamheading?ReactNodeThe people behind the workdescription?ReactNode—filterable?booleanShow department chips. Default true when members span 2+ departments.
—departments?string[]Department order. Defaults to first-seen order in `members`.
—allLabel?stringEveryonedepartment?stringControlled active department (`allLabel` or a department).
—defaultDepartment?string—onDepartmentChange?((department: string) => void)—columns?2 | 3 | 4Most columns at wide container sizes. Default 4.
4onMemberOpen?((member: TeamMember) => void)Called when a member's detail panel opens.
—className?string—Keep in mind
Some components on this site are inspired by or recreated from existing work across the web. I'm not here to take credit; just to learn, experiment, and sometimes push things a bit further. If something looks familiar and I forgot to mention you, reach out and I'll fix that right away.
Updated