Dashboard Shell
Container-sized app shell whose sidebar collapses to icons with tooltips and a gliding active pill, a top bar with a Mod+K search field and avatar menu, and a content slot with breadcrumbs, title and actions that cross-fades per page; below its own `mobileBelow` width (768px default) the sidebar moves into a Drawer — a data-driven complement to the viewport-height AnimatedSidebar primitives.
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;
// 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;
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
"use client";
import { type RefObject, useEffect } from "react";
/**
* What the dismissing gesture does to the control it landed on.
*
* `"pass-through"` is the platform norm (native popover light-dismiss): the
* tap closes the overlay *and* activates whatever was under it. Use
* `"consume"` where the open overlay sits over or beside controls that would
* be costly to trigger by accident — the dismissal then swallows the
* activation too, so the gesture only closes.
*/
export type DismissBehavior = "pass-through" | "consume";
export interface DismissOptions {
/** Default `"pass-through"`. */
behavior?: DismissBehavior;
/** Dismiss on Escape as well. Default true. */
escape?: boolean;
/** Return true for an outside target that should *not* dismiss. Must be stable. */
ignore?: (target: Element) => boolean;
}
/**
* What every currently open dismiss scope counts as inside itself. A consumed
* dismissal reads this to tell a stray gesture from one that belongs to an
* overlay in front of it: overlays have no shared z-order to consult, but the
* one the gesture landed in has said as much by registering it.
*/
const openScopes = new Set<(target: Element) => boolean>();
function claimedByAnotherScope(
self: (target: Element) => boolean,
target: Element,
) {
for (const scope of openScopes) {
if (scope !== self && scope(target)) return true;
}
return false;
}
// preventDefault on pointerdown does not suppress the click that follows, so
// consuming a gesture means swallowing that click itself. The swallower
// deliberately outlives the effect that installed it — the dismissal it
// belongs to has already unmounted or re-rendered by the time the click lands.
// It releases on that click, or on the next gesture if the pointer is dragged
// away and no click ever arrives, so it can never eat a later one. A keydown
// releases it too: a gesture that ends with neither a click nor a cancel would
// otherwise leave it armed, and the click Enter synthesizes on some focused
// control is not the one this dismissal was owed.
function consumeActivation(source: Event) {
const swallow = (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
release();
};
const restart = (event: Event) => {
if (event !== source) release();
};
const release = () => {
window.removeEventListener("click", swallow, true);
window.removeEventListener("pointerdown", restart, true);
window.removeEventListener("pointercancel", restart, true);
window.removeEventListener("keydown", release, true);
};
window.addEventListener("click", swallow, true);
window.addEventListener("pointerdown", restart, true);
window.addEventListener("pointercancel", restart, true);
window.addEventListener("keydown", release, true);
}
/**
* Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`
* for `ref` when what counts as inside isn't one element, and say so with
* `ignore` instead.
*
* The pointerdown listener is capture-phase: a bubble-phase one is blinded by
* any handler in between that stops propagation, and an overlay cannot know
* what it is layered over. `onDismiss` and `ignore` must be stable (wrap in
* useCallback) so the listeners aren't re-bound every render while open.
*/
export function useDismiss(
open: boolean,
onDismiss: () => void,
ref: RefObject<HTMLElement | null> | null,
{
behavior = "pass-through",
escape: dismissOnEscape = true,
ignore,
}: DismissOptions = {},
) {
useEffect(() => {
if (!open) return;
const inside = (target: Element) =>
Boolean(ref?.current?.contains(target)) || Boolean(ignore?.(target));
const onKey = (event: KeyboardEvent) => {
if (dismissOnEscape && event.key === "Escape") onDismiss();
};
const onPointer = (event: PointerEvent) => {
const target = event.target as Element | null;
if (!target || inside(target)) return;
// Outside this overlay, but inside one that is also open: the gesture is
// that overlay's to answer, and swallowing its click from behind would
// cost the user the control they actually aimed at.
if (behavior === "consume" && !claimedByAnotherScope(inside, target)) {
consumeActivation(event);
}
onDismiss();
};
openScopes.add(inside);
window.addEventListener("keydown", onKey);
window.addEventListener("pointerdown", onPointer, true);
return () => {
openScopes.delete(inside);
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer, true);
};
}, [open, onDismiss, ref, behavior, dismissOnEscape, ignore]);
}
"use client";
import { useMemo, useRef } from "react";
import { isHoveringPointer } from "@/lib/touch";
interface BoundaryEvent {
pointerId: number;
pointerType: string;
buttons: number;
}
export interface HoverGesture {
/** True when this enter starts a hover: the pointer arrived resting, not pressing. */
enter: (event: BoundaryEvent) => boolean;
/** True when this leave ends a hover that entered as one. */
leave: (event: BoundaryEvent) => boolean;
}
/**
* Pairs a surface's enter with its leave, per pointer.
*
* `isHoveringPointer` answers the question the *enter* asks — is this pointer
* resting on the surface or pressing it — and both boundary cases go wrong if
* the leave is asked the same question again:
*
* - A pen with no hover never rests. It arrives in contact, taps, and the spec
* then requires its boundary events after `pointerup`, so the leave carries
* `buttons: 0` and reads as a mouse gliding off. Hover teardown then undid
* the tap — the panel the pen had just opened closed under it.
* - A mouse pressed on the surface and dragged off leaves with `buttons: 1`.
* Skipping teardown there strands the surface open: the release happens
* outside, and no second leave ever comes.
*
* So the state a hover holds is released by the pointer that took it, whatever
* the buttons say at the boundary, and a pointer that arrived in contact never
* took it in the first place. Contact is the exception tracked here, not
* hover: a leave from a pointer this surface never saw enter — mounted under
* the cursor, say — still counts, since the alternative is state with no way
* out.
*/
export function useHoverGesture(): HoverGesture {
const contact = useRef(new Set<number>());
return useMemo(
() => ({
enter: (event) => {
if (isHoveringPointer(event)) {
contact.current.delete(event.pointerId);
return true;
}
contact.current.add(event.pointerId);
return false;
},
leave: (event) => {
const arrivedInContact = contact.current.delete(event.pointerId);
return !arrivedInContact && event.pointerType !== "touch";
},
}),
[],
);
}
"use client";
import { useMemo, useRef } from "react";
/** What a pointerdown recorded, read back by the click that ends its gesture. */
export interface TapRecord<S> {
/** Which input started the gesture. */
pointerType: string;
/** What the surface was showing when it started. */
state: S;
}
export interface TapGesture<S> {
/** Record the gesture a pointerdown starts, with the state it starts in. */
start: (event: { pointerType: string }, state: S) => void;
/** Read the record and clear it. `null` when no pointer is behind this click. */
take: () => TapRecord<S> | null;
/** Drop the record: this gesture will never spend it on a click. */
drop: () => void;
}
/**
* The pointer gesture behind a click, recorded where the click cannot report
* it. A `click` carries no `pointerType` in the engines that matter, so the
* `pointerdown` before it is the only thing that says which input activated
* the control — and whether one did at all, since keyboard activation
* synthesizes a click with no pointer behind it.
*
* State goes in with the record because a click reports that no better: a
* browser that focuses a control on contact can open the very panel the tap
* was meant to open, and reading "is it open" at click time then undoes it.
* What the gesture started against is what it acts on.
*
* The record is spent by one click and dropped by everything else, because a
* record that outlives its gesture is worse than none:
*
* - A scroll or an OS gesture takes the touch away — `pointercancel`, no click
* ever — and the finger would sit in the record until some later click.
* - That later click is often `Enter` on a keyboard, which arrives with no
* pointerdown of its own and would inherit the abandoned finger. A keydown
* is the start of a keyboard activation and never part of a tap, so it drops
* the record too.
*
* Both ends have to be wired by the surface: `drop` on `onPointerCancel` and
* on `onKeyDown`.
*/
export function useTapGesture<S>(): TapGesture<S> {
const record = useRef<TapRecord<S> | null>(null);
return useMemo(
() => ({
start: (event, state) => {
record.current = { pointerType: event.pointerType, state };
},
take: () => {
const spent = record.current;
record.current = null;
return spent;
},
drop: () => {
record.current = null;
},
}),
[],
);
}
"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";
// karaui.kamisama-v0.my.id/components/blocks/dashboard-shell
import { LogOut, Menu, PanelLeftClose, PanelLeftOpen, Search, Settings, User } from "lucide-react";
import { AnimatePresence, LayoutGroup, motion, useReducedMotion } from "motion/react";
import {
type KeyboardEvent,
type ReactNode,
useCallback,
useEffect,
useId,
useRef,
useState,
} from "react";
import { Breadcrumb, type BreadcrumbDataItem } from "@/components/motion/breadcrumb";
import { Drawer } from "@/components/motion/drawer";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/motion/dropdown-menu";
import { KbdCombo } from "@/components/motion/kbd";
import { Tooltip } from "@/components/motion/tooltip";
import { EASE_OUT, SPRING_LAYOUT } from "@/lib/ease";
import { TOUCH_TARGET_CLASS } from "@/lib/touch";
import { cn } from "@/lib/utils";
export interface DashboardNavItem {
id: string;
label: string;
icon: ReactNode;
/** Small count or text after the label (a dot when collapsed). */
badge?: ReactNode;
}
export interface DashboardNavGroup {
id: string;
label?: string;
items: DashboardNavItem[];
}
export interface DashboardUserMenuItem {
id: string;
label: string;
icon?: ReactNode;
destructive?: boolean;
onSelect?: () => void;
}
export interface DashboardShellProps {
nav: DashboardNavGroup[];
/** Controlled active nav id. */
active?: string;
defaultActive?: string;
onActiveChange?: (id: string) => void;
/** Controlled desktop collapse (icons only). */
collapsed?: boolean;
defaultCollapsed?: boolean;
onCollapsedChange?: (collapsed: boolean) => void;
brand: { name: string; logo?: ReactNode };
user: { name: string; email?: string; avatar?: string };
/** Avatar menu rows. Defaults to Profile, Settings and Sign out. */
userMenu?: DashboardUserMenuItem[];
searchPlaceholder?: string;
/** Fires on Enter in the search field. */
onSearch?: (query: string) => void;
/** Also focus search on Mod+K anywhere on the page (default: only while focus is inside the shell). */
globalShortcut?: boolean;
breadcrumbs?: BreadcrumbDataItem[];
title?: ReactNode;
description?: ReactNode;
/** Page-header actions (buttons). */
actions?: ReactNode;
/**
* Shell width in px below which the sidebar moves into a Drawer behind a
* menu button. Measured on the shell itself (a CSS container query), not the
* viewport. Default 768, which matches `md` when the shell spans the page.
*/
mobileBelow?: number;
children?: ReactNode;
className?: string;
}
function useControllable<T>(
value: T | undefined,
defaultValue: T,
onChange: ((next: T) => void) | undefined,
) {
const [internal, setInternal] = useState(defaultValue);
const controlled = value !== undefined;
const current = controlled ? value : internal;
const set = useCallback(
(next: T) => {
if (!controlled) setInternal(next);
onChange?.(next);
},
[controlled, onChange],
);
return [current, set] as const;
}
const isShortcut = (e: { key: string; metaKey: boolean; ctrlKey: boolean }) =>
(e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k";
const DEFAULT_MENU: DashboardUserMenuItem[] = [
{ id: "profile", label: "Profile", icon: <User aria-hidden /> },
{ id: "settings", label: "Settings", icon: <Settings aria-hidden /> },
{ id: "sign-out", label: "Sign out", icon: <LogOut aria-hidden />, destructive: true },
];
/**
* Container-sized app shell: a sidebar that collapses to icons (labels fade,
* tooltips take over, the active pill glides between rows), a top bar with a
* Mod+K search field and avatar menu, and a content slot with breadcrumbs,
* title and actions that cross-fades per page. When the shell itself is
* narrower than `mobileBelow` (768px) the sidebar moves into a Drawer behind a
* menu button. Fills its parent's box, unlike the viewport-height
* `AnimatedSidebar` primitives.
*
* The switch is a CSS container query on the shell's own width, so it also
* folds inside a docs frame or a split view. Tailwind variants are static and
* the breakpoint is a prop, so the query is a small `<style>` scoped to this
* instance; it renders on the server too, so the first paint already has the
* right layout and nothing is measured or swapped after hydration.
*/
export function DashboardShell({
nav,
active: activeProp,
defaultActive,
onActiveChange,
collapsed: collapsedProp,
defaultCollapsed = false,
onCollapsedChange,
brand,
user,
userMenu = DEFAULT_MENU,
searchPlaceholder = "Search…",
onSearch,
globalShortcut = false,
breadcrumbs,
title,
description,
actions,
mobileBelow = 768,
children,
className,
}: DashboardShellProps) {
const reduce = useReducedMotion();
const baseId = useId();
const [active, setActive] = useControllable(
activeProp,
defaultActive ?? nav[0]?.items[0]?.id ?? "",
onActiveChange,
);
const [collapsed, setCollapsed] = useControllable(
collapsedProp,
defaultCollapsed,
onCollapsedChange,
);
const [drawerOpen, setDrawerOpen] = useState(false);
const [query, setQuery] = useState("");
const searchRef = useRef<HTMLInputElement>(null);
const rootRef = useRef<HTMLDivElement>(null);
// One container name per instance, so nested shells each answer to their
// own width. useId is stable across server and client, so the CSS matches.
const scope = `dash-shell-${baseId.replace(/[^a-zA-Z0-9_-]/g, "")}`;
const breakpoint = Number.isFinite(mobileBelow) ? Math.max(0, mobileBelow) : 768;
// No `<`/`>` or quotes in here: React escapes text children on the server.
const layoutCss =
`@container ${scope} not (min-width: ${breakpoint}px){[data-shell-desktop=${scope}]{display:none}}` +
`@container ${scope} (min-width: ${breakpoint}px){[data-shell-mobile=${scope}]{display:none}[data-shell-pad=${scope}]{padding:1.25rem}}`;
// The drawer only exists in the narrow layout. If the shell widens past the
// breakpoint while it is open (rotation, a resized split), close it rather
// than leave a mobile drawer over the desktop sidebar.
useEffect(() => {
const el = rootRef.current;
if (!drawerOpen || !el || typeof ResizeObserver === "undefined") return;
const ro = new ResizeObserver(() => {
if (el.clientWidth >= breakpoint) setDrawerOpen(false);
});
ro.observe(el);
return () => ro.disconnect();
}, [drawerOpen, breakpoint]);
useEffect(() => {
if (!globalShortcut) return;
const onKey = (e: globalThis.KeyboardEvent) => {
if (!isShortcut(e)) return;
e.preventDefault();
searchRef.current?.focus();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [globalShortcut]);
const onShellKey = (e: KeyboardEvent<HTMLDivElement>) => {
if (globalShortcut || !isShortcut(e)) return;
e.preventDefault();
searchRef.current?.focus();
};
const pick = (id: string) => {
setActive(id);
setDrawerOpen(false);
};
const initials = user.name
.split(/\s+/)
.filter(Boolean)
.slice(0, 2)
.map((p) => p[0]?.toUpperCase())
.join("");
return (
// biome-ignore lint/a11y/noStaticElementInteractions: scoped Mod+K shortcut; every control inside is a real element.
<div
ref={rootRef}
onKeyDown={onShellKey}
style={{ containerName: `shell ${scope}` }}
className={cn(
"@container/shell relative flex h-full min-h-0 w-full overflow-hidden rounded-2xl border border-border bg-background text-foreground",
className,
)}
>
<style>{layoutCss}</style>
{/* Desktop sidebar. Width is animated on purpose: collapsing is a layout
change — the content column has to reflow into the freed space. */}
<motion.aside
aria-label="Sidebar"
initial={false}
animate={{ width: collapsed ? 56 : 200 }}
transition={reduce ? { duration: 0 } : SPRING_LAYOUT}
data-shell-desktop={scope}
className="flex shrink-0 flex-col overflow-hidden border-r border-border bg-muted/40"
>
<div className="flex h-12 shrink-0 items-center gap-2 px-3">
<span className="grid size-7 shrink-0 place-items-center rounded-lg bg-primary text-xs font-bold text-primary-foreground">
{brand.logo ?? brand.name.slice(0, 1)}
</span>
<FadeLabel show={!collapsed} className="text-sm font-semibold">
{brand.name}
</FadeLabel>
</div>
<NavList
nav={nav}
active={active}
collapsed={collapsed}
layoutGroup={`${baseId}-desktop`}
onPick={pick}
/>
</motion.aside>
{/* Mobile drawer */}
<Drawer open={drawerOpen} onOpenChange={setDrawerOpen} side="left" ariaLabel="Navigation" className="w-64">
<div className="flex h-12 items-center gap-2 px-4">
<span className="grid size-7 place-items-center rounded-lg bg-primary text-xs font-bold text-primary-foreground">
{brand.logo ?? brand.name.slice(0, 1)}
</span>
<span className="text-sm font-semibold">{brand.name}</span>
</div>
<NavList
nav={nav}
active={active}
collapsed={false}
layoutGroup={`${baseId}-mobile`}
onPick={pick}
/>
</Drawer>
<div className="flex min-w-0 flex-1 flex-col">
{/* Top bar */}
<header className="flex h-12 shrink-0 items-center gap-2 border-b border-border px-3">
<button
type="button"
aria-label="Open navigation"
onClick={() => setDrawerOpen(true)}
data-shell-mobile={scope}
className={cn(
"relative grid size-8 place-items-center rounded-lg text-muted-foreground outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-primary",
TOUCH_TARGET_CLASS,
)}
>
<Menu aria-hidden className="size-4" />
</button>
<button
type="button"
aria-label={collapsed ? "Expand sidebar" : "Collapse sidebar"}
aria-expanded={!collapsed}
onClick={() => setCollapsed(!collapsed)}
data-shell-desktop={scope}
className={cn(
"relative grid size-8 place-items-center rounded-lg text-muted-foreground outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-primary",
TOUCH_TARGET_CLASS,
)}
>
<AnimatePresence initial={false} mode="popLayout">
<motion.span
key={collapsed ? "open" : "close"}
initial={{ opacity: 0, scale: reduce ? 1 : 0.7 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: reduce ? 1 : 0.7 }}
transition={{ duration: 0.15, ease: EASE_OUT }}
>
{collapsed ? (
<PanelLeftOpen aria-hidden className="size-4" />
) : (
<PanelLeftClose aria-hidden className="size-4" />
)}
</motion.span>
</AnimatePresence>
</button>
<label className="group flex h-8 min-w-0 max-w-64 flex-1 items-center gap-2 rounded-lg border border-border bg-card px-2.5 text-xs transition-colors focus-within:border-border-strong focus-within:ring-2 focus-within:ring-primary/30">
<Search aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
<span className="sr-only">Search</span>
<input
ref={searchRef}
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") onSearch?.(query);
if (e.key === "Escape") e.currentTarget.blur();
}}
placeholder={searchPlaceholder}
className="min-w-0 flex-1 bg-transparent outline-none placeholder:text-muted-foreground pointer-coarse:text-base [&::-webkit-search-cancel-button]:hidden"
/>
<KbdCombo keys={["mod", "k"]} size="sm" className="hidden group-focus-within:opacity-0 @min-[40rem]/shell:inline-flex" />
</label>
<div className="ml-auto">
<DropdownMenu>
<DropdownMenuTrigger>
<button
type="button"
aria-label={`Account menu for ${user.name}`}
className={cn(
"relative grid size-8 place-items-center rounded-full bg-primary/15 text-[11px] font-semibold outline-none ring-offset-2 ring-offset-background focus-visible:ring-2 focus-visible:ring-primary",
TOUCH_TARGET_CLASS,
)}
>
{user.avatar ? (
// biome-ignore lint/performance/noImgElement: library component, framework-agnostic.
<img src={user.avatar} alt="" className="size-full rounded-[inherit] object-cover" />
) : (
initials
)}
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-52">
<DropdownMenuLabel>
<span className="block truncate text-sm font-medium text-foreground">{user.name}</span>
{user.email ? (
<span className="block truncate text-xs font-normal text-muted-foreground">
{user.email}
</span>
) : null}
</DropdownMenuLabel>
<DropdownMenuSeparator />
{userMenu.map((item, i) => (
<MenuRow key={item.id} item={item} separatorBefore={item.destructive && i > 0} />
))}
</DropdownMenuContent>
</DropdownMenu>
</div>
</header>
{/* Content */}
<main className="min-h-0 flex-1 overflow-y-auto [scrollbar-color:var(--border-strong)_transparent] [scrollbar-width:thin]">
<AnimatePresence initial={false} mode="wait">
<motion.div
key={active}
initial={{ opacity: 0, y: reduce ? 0 : 8 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, transition: { duration: 0.1 } }}
transition={{ duration: 0.22, ease: EASE_OUT }}
data-shell-pad={scope}
className="p-4"
>
{breadcrumbs || title || actions ? (
<div className="mb-4 flex flex-wrap items-end gap-3">
<div className="min-w-0 flex-1">
{breadcrumbs ? <Breadcrumb items={breadcrumbs} className="mb-1.5 text-xs" /> : null}
{title ? <h2 className="truncate text-lg font-semibold tracking-tight">{title}</h2> : null}
{description ? (
<p className="mt-0.5 text-xs text-muted-foreground">{description}</p>
) : null}
</div>
{actions ? <div className="flex shrink-0 items-center gap-2">{actions}</div> : null}
</div>
) : null}
{children}
</motion.div>
</AnimatePresence>
</main>
</div>
</div>
);
}
function MenuRow({
item,
separatorBefore,
}: {
item: DashboardUserMenuItem;
separatorBefore?: boolean;
}) {
return (
<>
{separatorBefore ? <DropdownMenuSeparator /> : null}
<DropdownMenuItem
icon={item.icon}
variant={item.destructive ? "destructive" : "default"}
onSelect={() => item.onSelect?.()}
>
{item.label}
</DropdownMenuItem>
</>
);
}
function FadeLabel({
show,
children,
className,
}: {
show: boolean;
children: ReactNode;
className?: string;
}) {
return (
<AnimatePresence initial={false}>
{show ? (
<motion.span
initial={{ opacity: 0 }}
animate={{ opacity: 1, transition: { delay: 0.08, duration: 0.18 } }}
exit={{ opacity: 0, transition: { duration: 0.08 } }}
className={cn("min-w-0 truncate whitespace-nowrap", className)}
>
{children}
</motion.span>
) : null}
</AnimatePresence>
);
}
function NavList({
nav,
active,
collapsed,
layoutGroup,
onPick,
}: {
nav: DashboardNavGroup[];
active: string;
collapsed: boolean;
layoutGroup: string;
onPick: (id: string) => void;
}) {
const reduce = useReducedMotion();
return (
<nav aria-label="Main" className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden px-2 pb-3 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
<LayoutGroup id={layoutGroup}>
{nav.map((group) => (
<div key={group.id} className="flex flex-col gap-0.5">
{group.label ? (
<div className="relative h-5 px-2">
<FadeLabel
show={!collapsed}
className="block text-[10px] font-medium uppercase tracking-wider text-muted-foreground"
>
{group.label}
</FadeLabel>
{collapsed ? (
<span aria-hidden className="absolute inset-x-3 top-1/2 h-px bg-border" />
) : null}
</div>
) : null}
<ul className="flex flex-col gap-0.5">
{group.items.map((item) => {
const isActive = item.id === active;
const row = (
<button
type="button"
aria-current={isActive ? "page" : undefined}
aria-label={collapsed ? item.label : undefined}
onClick={() => onPick(item.id)}
className={cn(
"relative flex h-8 w-full items-center gap-2.5 rounded-lg px-2.5 text-left text-xs font-medium outline-none transition-colors focus-visible:ring-2 focus-visible:ring-primary",
TOUCH_TARGET_CLASS,
isActive ? "text-foreground" : "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
{isActive ? (
<motion.span
layoutId="nav-active"
transition={reduce ? { duration: 0 } : SPRING_LAYOUT}
className="absolute inset-0 rounded-lg border border-border bg-background shadow-sm"
/>
) : null}
<span className="relative shrink-0 [&_svg]:size-4">{item.icon}</span>
<FadeLabel show={!collapsed} className="relative flex-1">
{item.label}
</FadeLabel>
{item.badge !== undefined && item.badge !== null ? (
collapsed ? (
<span aria-hidden className="absolute top-1.5 left-6 size-1.5 rounded-full bg-primary" />
) : (
<span className="relative rounded-full bg-primary/10 px-1.5 text-[10px] tabular-nums text-foreground">
{item.badge}
</span>
)
) : null}
</button>
);
return (
<li key={item.id}>
{collapsed ? (
<Tooltip content={item.label} side="right" wrapperClassName="block w-full">
{row}
</Tooltip>
) : (
row
)}
</li>
);
})}
</ul>
</div>
))}
</LayoutGroup>
</nav>
);
}
"use client";
import { ChevronRight, Ellipsis } from "lucide-react";
import {
AnimatePresence,
LayoutGroup,
motion,
useReducedMotion,
} from "motion/react";
import {
useEffect,
useId,
useRef,
useState,
type ComponentProps,
type ComponentPropsWithoutRef,
type KeyboardEvent,
type ReactElement,
type ReactNode,
} from "react";
import { EASE_OUT_CSS, SPRING_LAYOUT, SPRING_PANEL } from "@/lib/ease";
import { cn } from "@/lib/utils";
/* ------------------------------------------------------------------------ */
/* Composable primitives */
/* ------------------------------------------------------------------------ */
export type BreadcrumbDataItem = {
label: ReactNode;
href?: string;
icon?: ReactNode;
/** Render the link through your router, e.g. `(p) => <Link {...p} />`. */
render?: (props: BreadcrumbLinkRenderProps) => ReactElement;
};
type BreadcrumbNavProps = ComponentPropsWithoutRef<"nav">;
export type BreadcrumbProps = BreadcrumbNavProps & {
/** Data-driven mode. Omit to compose `BreadcrumbList` children yourself. */
items?: BreadcrumbDataItem[];
/** Collapse middle items into "…" when there are more than this many. */
maxItems?: number;
/** "expand" reveals hidden items inline; "menu" lists them in a dropdown. */
collapse?: "expand" | "menu";
separator?: ReactNode;
};
export function Breadcrumb({
items,
maxItems = 4,
collapse = "expand",
separator,
className,
children,
...props
}: BreadcrumbProps) {
return (
<nav aria-label="Breadcrumb" className={cn("min-w-0", className)} {...props}>
{items ? (
<BreadcrumbTrail
items={items}
maxItems={maxItems}
collapse={collapse}
separator={separator}
/>
) : (
children
)}
</nav>
);
}
export function BreadcrumbList({ className, ...props }: ComponentPropsWithoutRef<"ol">) {
return (
<ol
className={cn(
"flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2",
className,
)}
{...props}
/>
);
}
export function BreadcrumbItem({ className, ...props }: ComponentPropsWithoutRef<"li">) {
return <li className={cn("inline-flex min-w-0 items-center gap-1.5", className)} {...props} />;
}
export type BreadcrumbLinkRenderProps = {
href: string;
className: string;
children: ReactNode;
};
export type BreadcrumbLinkProps = Omit<ComponentPropsWithoutRef<"a">, "href" | "children"> & {
href: string;
children: ReactNode;
/** Swap the `<a>` for a router link: `render={(p) => <Link {...p} />}`. */
render?: (props: BreadcrumbLinkRenderProps) => ReactElement;
};
const linkClass =
"group/crumb relative inline-flex min-w-0 items-center gap-1.5 rounded-sm text-muted-foreground outline-none transition-colors duration-200 hover:text-foreground focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background";
function LinkContent({ children }: { children: ReactNode }) {
return (
<>
{children}
{/* Underline slides in from the left and leaves to the right: the origin
flips on hover, so scaleX grows and shrinks in the travel direction. */}
<span
aria-hidden
style={{ transitionTimingFunction: EASE_OUT_CSS }}
className="pointer-events-none absolute inset-x-0 -bottom-0.5 h-px origin-right scale-x-0 bg-current transition-transform duration-300 group-hover/crumb:origin-left group-hover/crumb:scale-x-100 group-focus-visible/crumb:origin-left group-focus-visible/crumb:scale-x-100 motion-reduce:transition-none"
/>
</>
);
}
export function BreadcrumbLink({
href,
render,
className,
children,
...props
}: BreadcrumbLinkProps) {
const merged = cn(linkClass, className);
if (render) {
return render({ href, className: merged, children: <LinkContent>{children}</LinkContent> });
}
return (
<a href={href} className={merged} {...props}>
<LinkContent>{children}</LinkContent>
</a>
);
}
export function BreadcrumbPage({ className, ...props }: ComponentPropsWithoutRef<"span">) {
return (
<span
aria-current="page"
className={cn("inline-flex min-w-0 items-center gap-1.5 truncate font-medium text-foreground", className)}
{...props}
/>
);
}
export function BreadcrumbSeparator({
className,
children,
...props
}: ComponentPropsWithoutRef<"li">) {
return (
<li
aria-hidden="true"
className={cn("inline-flex items-center text-muted-foreground/60 [&>svg]:size-3.5", className)}
{...props}
>
{children ?? <ChevronRight />}
</li>
);
}
export function BreadcrumbEllipsis({ className, ...props }: ComponentProps<"button">) {
return (
<button
type="button"
className={cn(
"inline-flex h-6 w-7 items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
className,
)}
{...props}
>
<Ellipsis className="size-4" aria-hidden />
</button>
);
}
/* ------------------------------------------------------------------------ */
/* Data-driven trail */
/* ------------------------------------------------------------------------ */
function CrumbBody({ item, current }: { item: BreadcrumbDataItem; current: boolean }) {
const content = (
<>
{item.icon ? (
<span aria-hidden className="inline-flex shrink-0 [&>svg]:size-3.5">
{item.icon}
</span>
) : null}
<span className="max-w-[12rem] truncate">{item.label}</span>
</>
);
if (current || !item.href) return <BreadcrumbPage aria-current={current ? "page" : undefined}>{content}</BreadcrumbPage>;
return (
<BreadcrumbLink href={item.href} render={item.render}>
{content}
</BreadcrumbLink>
);
}
type Entry =
| { kind: "item"; item: BreadcrumbDataItem; index: number }
| { kind: "ellipsis"; hidden: { item: BreadcrumbDataItem; index: number }[] };
function BreadcrumbTrail({
items,
maxItems,
collapse,
separator,
}: {
items: BreadcrumbDataItem[];
maxItems: number;
collapse: "expand" | "menu";
separator?: ReactNode;
}) {
const reduce = useReducedMotion();
const [expanded, setExpanded] = useState(false);
const firstRevealed = useRef<HTMLLIElement>(null);
const focusRevealed = useRef(false);
const indexed = items.map((item, index) => ({ item, index }));
const shouldCollapse = !expanded && items.length > Math.max(maxItems, 2);
const tail = Math.max(1, maxItems - 2);
const hidden = shouldCollapse ? indexed.slice(1, items.length - tail) : [];
const entries: Entry[] = shouldCollapse
? [
{ kind: "item", ...indexed[0] },
{ kind: "ellipsis", hidden },
...indexed.slice(items.length - tail).map((e) => ({ kind: "item" as const, ...e })),
]
: indexed.map((e) => ({ kind: "item" as const, ...e }));
// The "…" button unmounts on expand; hand focus to the first revealed link
// so keyboard users are not dropped back on <body>.
useEffect(() => {
if (expanded && focusRevealed.current) {
focusRevealed.current = false;
firstRevealed.current?.querySelector<HTMLElement>("a,[tabindex]")?.focus();
}
}, [expanded]);
const layoutTransition = reduce ? { duration: 0 } : SPRING_LAYOUT;
return (
<LayoutGroup>
{/* relative: popLayout takes exiting crumbs out of flow, absolutely. */}
<BreadcrumbList className="relative">
<AnimatePresence initial={false} mode="popLayout">
{entries.flatMap((entry, i) => {
const key = entry.kind === "item" ? `item-${entry.index}` : "ellipsis";
const last = entry.kind === "item" && entry.index === items.length - 1;
const isFirstRevealed = expanded && entry.kind === "item" && entry.index === 1;
// Flat keyed <li>s (no Fragment) so AnimatePresence tracks each
// separator and crumb on its own and plays their exits.
const nodes: ReactElement[] = [];
if (i > 0) {
nodes.push(
<motion.li
key={`sep-${key}`}
layout="position"
aria-hidden="true"
transition={layoutTransition}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0, transition: { duration: 0.1 } }}
className="inline-flex items-center text-muted-foreground/60 [&>svg]:size-3.5"
>
{separator ?? <ChevronRight />}
</motion.li>,
);
}
nodes.push(
<motion.li
key={key}
ref={isFirstRevealed ? firstRevealed : undefined}
layout="position"
transition={layoutTransition}
initial={reduce ? { opacity: 0 } : { opacity: 0, x: -6, filter: "blur(4px)" }}
animate={{ opacity: 1, x: 0, filter: "blur(0px)" }}
exit={{ opacity: 0, transition: { duration: 0.1 } }}
className="inline-flex min-w-0 items-center gap-1.5"
>
{entry.kind === "item" ? (
<CrumbBody item={entry.item} current={last} />
) : collapse === "menu" ? (
<CollapsedMenu hidden={entry.hidden} />
) : (
<BreadcrumbEllipsis
aria-label={`Show ${entry.hidden.length} more`}
onClick={() => {
focusRevealed.current = true;
setExpanded(true);
}}
/>
)}
</motion.li>,
);
return nodes;
})}
</AnimatePresence>
</BreadcrumbList>
</LayoutGroup>
);
}
function CollapsedMenu({ hidden }: { hidden: { item: BreadcrumbDataItem; index: number }[] }) {
const reduce = useReducedMotion();
const [open, setOpen] = useState(false);
const menuId = useId();
const rootRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
const listRef = useRef<HTMLUListElement>(null);
useEffect(() => {
if (!open) return;
const onPointer = (event: PointerEvent) => {
if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
};
document.addEventListener("pointerdown", onPointer);
listRef.current?.querySelector<HTMLElement>("a")?.focus();
return () => document.removeEventListener("pointerdown", onPointer);
}, [open]);
const close = (refocus: boolean) => {
setOpen(false);
if (refocus) triggerRef.current?.focus();
};
const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (!open) return;
const links = Array.from(listRef.current?.querySelectorAll<HTMLElement>("a") ?? []);
const at = links.indexOf(document.activeElement as HTMLElement);
if (event.key === "Escape") {
event.preventDefault();
close(true);
} else if (event.key === "ArrowDown") {
event.preventDefault();
links[(at + 1) % links.length]?.focus();
} else if (event.key === "ArrowUp") {
event.preventDefault();
links[(at - 1 + links.length) % links.length]?.focus();
} else if (event.key === "Tab") {
setOpen(false);
}
};
return (
// biome-ignore lint/a11y/noStaticElementInteractions: delegates Escape/arrow keys for the popup's links
<div ref={rootRef} className="relative" onKeyDown={onKeyDown}>
<BreadcrumbEllipsis
ref={triggerRef}
aria-label={`Show ${hidden.length} more`}
aria-expanded={open}
aria-controls={open ? menuId : undefined}
onClick={() => setOpen((o) => !o)}
className={cn(open && "bg-muted text-foreground")}
/>
<AnimatePresence>
{open ? (
<motion.div
id={menuId}
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.94, y: -4 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.96, y: -2, transition: { duration: 0.12 } }}
transition={SPRING_PANEL}
className="absolute left-0 top-full z-50 mt-2 min-w-44 origin-top-left rounded-xl border border-border bg-popover p-1 text-popover-foreground shadow-lg"
>
<ul ref={listRef} className="flex flex-col">
{hidden.map(({ item, index }) => (
<li key={index}>
{item.href ? (
(item.render ?? defaultMenuLink)({
href: item.href,
className:
"flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:bg-muted focus-visible:text-foreground [&_svg]:size-3.5",
children: (
<>
{item.icon ? <span aria-hidden className="inline-flex">{item.icon}</span> : null}
<span className="truncate">{item.label}</span>
</>
),
})
) : (
<span className="flex items-center gap-2 px-2.5 py-1.5 text-sm text-muted-foreground">
{item.label}
</span>
)}
</li>
))}
</ul>
</motion.div>
) : null}
</AnimatePresence>
</div>
);
}
function defaultMenuLink({ href, className, children }: BreadcrumbLinkRenderProps) {
return (
<a href={href} className={className}>
{children}
</a>
);
}
"use client";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useEffect, type ReactNode } from "react";
import { EASE_OUT, SPRING_PANEL } from "@/lib/ease";
import { cn } from "@/lib/utils";
export interface DrawerProps {
open: boolean;
onOpenChange: (open: boolean) => void;
side?: "left" | "right";
children: ReactNode;
/** Class for the panel surface. */
className?: string;
/** Class for the backdrop. */
backdropClassName?: string;
ariaLabel?: string;
/** Close when the backdrop is clicked. Default true. */
dismissable?: boolean;
}
export function Drawer({
open,
onOpenChange,
side = "right",
children,
className,
backdropClassName,
ariaLabel,
dismissable = true,
}: DrawerProps) {
const reduce = useReducedMotion();
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onOpenChange(false);
};
window.addEventListener("keydown", onKey);
const prevOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => {
window.removeEventListener("keydown", onKey);
document.body.style.overflow = prevOverflow;
};
}, [open, onOpenChange]);
const offscreen = side === "right" ? "100%" : "-100%";
return (
<AnimatePresence>
{open ? (
<div className="fixed inset-0 z-50">
<motion.button
type="button"
aria-label="Close"
tabIndex={dismissable ? 0 : -1}
onClick={() => dismissable && onOpenChange(false)}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.25, ease: EASE_OUT }}
className={cn(
"absolute inset-0 h-full w-full cursor-default bg-black/40 backdrop-blur-sm",
backdropClassName,
)}
/>
<motion.aside
role="dialog"
aria-modal="true"
aria-label={ariaLabel}
initial={reduce ? { opacity: 0 } : { x: offscreen }}
animate={reduce ? { opacity: 1 } : { x: 0 }}
exit={reduce ? { opacity: 0 } : { x: offscreen }}
transition={reduce ? { duration: 0.2, ease: EASE_OUT } : SPRING_PANEL}
className={cn(
"absolute inset-y-0 flex w-80 max-w-[85vw] flex-col bg-background shadow-2xl",
side === "right"
? "right-0 border-l border-border"
: "left-0 border-r border-border",
className,
)}
>
{children}
</motion.aside>
</div>
) : null}
</AnimatePresence>
);
}
"use client";
import { Check, ChevronRight } from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
cloneElement,
createContext,
isValidElement,
type MutableRefObject,
type ReactElement,
type FocusEvent as ReactFocusEvent,
type KeyboardEvent as ReactKeyboardEvent,
type MouseEvent as ReactMouseEvent,
type ReactNode,
type PointerEvent as ReactPointerEvent,
type Ref,
useCallback,
useContext,
useEffect,
useId,
useMemo,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import {
type PlacementAlign,
type PlacementSide,
resolvePlacement,
} from "@/components/motion/anchored-placement";
import { usePopoverPortalPosition } from "@/components/motion/popover-position";
import { EASE_OUT, SPRING_LAYOUT, SPRING_PANEL } from "@/lib/ease";
import { useDismiss } from "@/lib/hooks/use-dismiss";
import { cn } from "@/lib/utils";
/* -------------------------------------------------------------------------- */
/* Levels */
/* -------------------------------------------------------------------------- */
/** Where focus lands when a panel opens. */
type FocusIntent = "first" | "last" | "content" | "none";
// Hovering a sub trigger waits this long before opening, so a pointer just
// passing over the row on its way down the list doesn't flash a submenu.
const SUB_OPEN_DELAY = 100;
// Leaving the sub trigger (or hovering a sibling) closes the submenu only
// after this grace, so a diagonal move toward the submenu that clips a
// neighbouring row doesn't snap it shut.
const SUB_CLOSE_DELAY = 220;
const TYPEAHEAD_RESET = 500;
/**
* One open panel: the root menu or a submenu. Items, the active-row
* highlight and keyboard navigation all read the nearest level, so a submenu
* is the same machinery one step down.
*/
interface MenuLevel {
/** Shared by every panel and the trigger of one menu tree (dismissal scope). */
rootId: string;
/** Scope for this panel's layoutId highlight. */
levelId: string;
open: boolean;
isSub: boolean;
triggerId: string;
contentId: string;
triggerRef: MutableRefObject<HTMLElement | null>;
contentRef: MutableRefObject<HTMLDivElement | null>;
focusIntent: MutableRefObject<FocusIntent>;
activeId: string | null;
setActiveId: (id: string | null) => void;
/** Id of the child submenu currently open from this panel. */
openSub: string | null;
setOpenSub: (id: string | null) => void;
scheduleSubClose: () => void;
cancelSubClose: () => void;
/** Close this panel only (root: the whole menu). */
close: (restoreFocus: boolean) => void;
/** Close the whole menu tree. */
closeAll: (restoreFocus: boolean) => void;
/** Open the root menu (used by the trigger). */
openRoot: () => void;
reduce: boolean;
}
const MenuLevelContext = createContext<MenuLevel | null>(null);
function useMenuLevel(component: string) {
const level = useContext(MenuLevelContext);
if (!level) throw new Error(`${component} must be used within <DropdownMenu>`);
return level;
}
/** Per-panel state shared by the root and every submenu. */
function useLevelCore(open: boolean) {
const [activeId, setActiveId] = useState<string | null>(null);
const [openSub, setOpenSubState] = useState<string | null>(null);
const subCloseTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const cancelSubClose = useCallback(() => {
if (subCloseTimer.current) clearTimeout(subCloseTimer.current);
subCloseTimer.current = null;
}, []);
const setOpenSub = useCallback(
(id: string | null) => {
cancelSubClose();
setOpenSubState(id);
},
[cancelSubClose],
);
const scheduleSubClose = useCallback(() => {
cancelSubClose();
subCloseTimer.current = setTimeout(() => {
subCloseTimer.current = null;
setOpenSubState(null);
}, SUB_CLOSE_DELAY);
}, [cancelSubClose]);
// Reset the highlight when the panel opens, not when it closes: removing
// the layoutId highlight while the panel is still animating out leaves
// motion waiting on it forever, so the closed panel never unmounts.
useEffect(() => {
if (open) {
setActiveId(null);
return;
}
cancelSubClose();
setOpenSubState(null);
}, [open, cancelSubClose]);
useEffect(() => cancelSubClose, [cancelSubClose]);
return useMemo(
() => ({
activeId,
setActiveId,
openSub,
setOpenSub,
scheduleSubClose,
cancelSubClose,
}),
[activeId, openSub, setOpenSub, scheduleSubClose, cancelSubClose],
);
}
function getItems(container: HTMLElement | null) {
if (!container) return [];
return Array.from(
container.querySelectorAll<HTMLElement>(
'[data-dropdown-menu-item]:not([data-disabled="true"])',
),
);
}
function focusByIntent(container: HTMLElement | null, intent: FocusIntent) {
if (!container || intent === "none") return;
const items = getItems(container);
const target =
intent === "first"
? items[0]
: intent === "last"
? items[items.length - 1]
: container;
(target ?? container).focus({ preventScroll: true });
}
function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {
if (typeof ref === "function") ref(value);
else if (ref) (ref as MutableRefObject<T | null>).current = value;
}
/* -------------------------------------------------------------------------- */
/* Root */
/* -------------------------------------------------------------------------- */
export interface DropdownMenuProps {
children: ReactNode;
/** Controlled open state. */
open?: boolean;
/** Uncontrolled initial open state. */
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
className?: string;
}
/**
* Composable dropdown menu following the WAI-ARIA menu button pattern. The
* panel scales out of the trigger side, an active-row highlight glides
* between items, and submenus open on hover intent or ArrowRight.
*/
export function DropdownMenu({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
className,
}: DropdownMenuProps) {
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const controlled = controlledOpen !== undefined;
const open = controlled ? controlledOpen : internalOpen;
const baseId = useId();
const triggerRef = useRef<HTMLElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);
const focusIntent = useRef<FocusIntent>("content");
const reduce = useReducedMotion() ?? false;
const core = useLevelCore(open);
const setOpen = useCallback(
(next: boolean) => {
if (!controlled) setInternalOpen(next);
onOpenChange?.(next);
},
[controlled, onOpenChange],
);
const closeAll = useCallback(
(restoreFocus: boolean) => {
setOpen(false);
if (restoreFocus) triggerRef.current?.focus({ preventScroll: true });
},
[setOpen],
);
const dismiss = useCallback(() => setOpen(false), [setOpen]);
const openRoot = useCallback(() => setOpen(true), [setOpen]);
const insideTree = useCallback(
(target: Element) =>
Boolean(target.closest(`[data-dropdown-menu="${baseId}"]`)),
[baseId],
);
// Escape is handled by the focused panel, which knows whether it is a
// submenu (close one level) or the root (close and refocus the trigger).
useDismiss(open, dismiss, null, { escape: false, ignore: insideTree });
// Focus moves into the panel on open: the first/last item for keyboard
// opens, the panel itself for pointer opens so arrows work immediately.
useEffect(() => {
if (!open) return;
const frame = requestAnimationFrame(() =>
focusByIntent(contentRef.current, focusIntent.current),
);
return () => cancelAnimationFrame(frame);
}, [open]);
const level = useMemo<MenuLevel>(
() => ({
rootId: baseId,
levelId: `${baseId}-root`,
open,
isSub: false,
triggerId: `${baseId}-trigger`,
contentId: `${baseId}-content`,
triggerRef,
contentRef,
focusIntent,
...core,
close: closeAll,
closeAll,
openRoot,
reduce,
}),
[baseId, open, core, closeAll, openRoot, reduce],
);
return (
<MenuLevelContext.Provider value={level}>
<div className={cn("relative inline-flex", className)}>{children}</div>
</MenuLevelContext.Provider>
);
}
/* -------------------------------------------------------------------------- */
/* Trigger */
/* -------------------------------------------------------------------------- */
type TriggerChildProps = React.HTMLAttributes<HTMLElement> & {
ref?: Ref<HTMLElement>;
[key: `data-${string}`]: string | undefined;
};
export interface DropdownMenuTriggerProps {
/** A single element, normally a `<button>`. Its own handlers still run. */
children: ReactElement<TriggerChildProps>;
className?: string;
}
export function DropdownMenuTrigger({
children,
className,
}: DropdownMenuTriggerProps) {
const level = useMenuLevel("DropdownMenuTrigger");
if (!isValidElement(children)) {
throw new Error("<DropdownMenuTrigger> requires a single React element");
}
const childProps = children.props;
const childRef = childProps.ref;
const openWith = (intent: FocusIntent) => {
level.focusIntent.current = intent;
if (!level.open) {
level.openRoot();
} else {
focusByIntent(level.contentRef.current, intent);
}
};
return cloneElement(children, {
ref: (node: HTMLElement | null) => {
level.triggerRef.current = node;
assignRef(childRef, node);
},
id: level.triggerId,
"aria-haspopup": "menu",
"aria-expanded": level.open,
"aria-controls": level.open ? level.contentId : undefined,
"data-state": level.open ? "open" : "closed",
"data-dropdown-menu": level.rootId,
className: cn(childProps.className, className),
onClick: (event: ReactMouseEvent<HTMLElement>) => {
childProps.onClick?.(event);
if (event.defaultPrevented) return;
if (level.open) {
level.closeAll(false);
return;
}
// `detail` is 0 for a click synthesized by the keyboard.
openWith(event.detail === 0 ? "first" : "content");
},
onKeyDown: (event: ReactKeyboardEvent<HTMLElement>) => {
childProps.onKeyDown?.(event);
if (event.defaultPrevented) return;
if (
event.key === "ArrowDown" ||
event.key === "Enter" ||
event.key === " "
) {
event.preventDefault();
openWith("first");
} else if (event.key === "ArrowUp") {
event.preventDefault();
openWith("last");
}
},
});
}
/* -------------------------------------------------------------------------- */
/* Panel */
/* -------------------------------------------------------------------------- */
interface MenuPanelProps {
level: MenuLevel;
children: ReactNode;
side: PlacementSide;
align: PlacementAlign;
sideOffset: number;
alignOffset: number;
className?: string;
ariaLabel?: string;
onPanelEnter?: () => void;
}
function MenuPanel({
level,
children,
side,
align,
sideOffset,
alignOffset,
className,
ariaLabel,
onPanelEnter,
}: MenuPanelProps) {
const [portalReady, setPortalReady] = useState(false);
const typeahead = useRef("");
const typeaheadTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const layout = usePopoverPortalPosition(
level.triggerRef,
level.contentRef,
portalReady && level.open,
);
useEffect(() => setPortalReady(true), []);
useEffect(
() => () => {
if (typeaheadTimer.current) clearTimeout(typeaheadTimer.current);
},
[],
);
const moveFocus = (direction: 1 | -1) => {
const items = getItems(level.contentRef.current);
if (items.length === 0) return;
const current = items.indexOf(document.activeElement as HTMLElement);
const next =
current < 0
? direction === 1
? 0
: items.length - 1
: (current + direction + items.length) % items.length;
items[next]?.focus();
};
const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
// React bubbles events through portals: a submenu's keys would reach its
// parent panel too. Only answer keys pressed inside this panel's DOM.
if (!event.currentTarget.contains(event.target as Node)) return;
if (event.defaultPrevented) return;
const { key } = event;
if (key === "Escape") {
event.preventDefault();
level.close(true);
return;
}
if (key === "ArrowLeft" && level.isSub) {
event.preventDefault();
level.close(true);
return;
}
if (key === "Tab") {
event.preventDefault();
level.closeAll(true);
return;
}
if (key === "ArrowDown" || key === "ArrowUp") {
event.preventDefault();
moveFocus(key === "ArrowDown" ? 1 : -1);
return;
}
if (key === "Home" || key === "End") {
event.preventDefault();
const items = getItems(level.contentRef.current);
items[key === "Home" ? 0 : items.length - 1]?.focus();
return;
}
const printable =
key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey;
// A leading space is activation, not a search character.
if (!printable || (key === " " && typeahead.current === "")) return;
event.preventDefault();
typeahead.current += key.toLocaleLowerCase();
if (typeaheadTimer.current) clearTimeout(typeaheadTimer.current);
typeaheadTimer.current = setTimeout(() => {
typeahead.current = "";
}, TYPEAHEAD_RESET);
const items = getItems(level.contentRef.current);
const start = items.indexOf(document.activeElement as HTMLElement);
// Search from the row after the current one so repeating a letter cycles.
const ordered =
typeahead.current.length === 1 && start >= 0
? [...items.slice(start + 1), ...items.slice(0, start + 1)]
: items;
const match = ordered.find((item) =>
(item.dataset.label ?? item.textContent ?? "")
.trim()
.toLocaleLowerCase()
.startsWith(typeahead.current),
);
match?.focus();
};
if (!portalReady) return null;
const placement = layout
? resolvePlacement(layout, { side, align, sideOffset, alignOffset })
: null;
return createPortal(
<AnimatePresence>
{level.open ? (
<motion.div
ref={level.contentRef}
id={level.contentId}
role="menu"
aria-label={ariaLabel}
aria-labelledby={ariaLabel ? undefined : level.triggerId}
aria-orientation="vertical"
tabIndex={-1}
data-dropdown-menu={level.rootId}
data-side={placement?.side ?? side}
initial={level.reduce ? { opacity: 0 } : { opacity: 0, scale: 0.94 }}
animate={{ opacity: 1, scale: 1 }}
// pointerEvents flips at the start of the exit, so a closing panel
// can never be hovered or clicked through.
exit={
level.reduce
? { opacity: 0, pointerEvents: "none", transition: { duration: 0.1 } }
: {
opacity: 0,
scale: 0.96,
pointerEvents: "none",
transition: { duration: 0.12, ease: EASE_OUT },
}
}
transition={
level.reduce
? { duration: 0.12, ease: EASE_OUT }
: { ...SPRING_PANEL, opacity: { duration: 0.16, ease: EASE_OUT } }
}
style={{
left: placement?.left ?? 0,
top: placement?.top ?? 0,
// The panel grows out of the trigger's side — transform-origin on
// an HTML element is safe for motion's scale.
transformOrigin: placement?.origin ?? "50% 0%",
visibility: placement ? "visible" : "hidden",
}}
onKeyDown={onKeyDown}
onFocus={(event: ReactFocusEvent<HTMLDivElement>) => {
if (event.target === event.currentTarget) level.setActiveId(null);
else onPanelEnter?.();
}}
onPointerEnter={onPanelEnter}
className={cn(
"fixed z-[100] min-w-52 rounded-xl border border-border bg-card p-1.5 text-foreground shadow-[0_18px_40px_-12px_rgba(0,0,0,0.28)] outline-none",
className,
)}
>
{children}
</motion.div>
) : null}
</AnimatePresence>,
document.body,
);
}
export interface DropdownMenuContentProps {
children: ReactNode;
/** Preferred side; flips when the viewport lacks room. Default "bottom". */
side?: "bottom" | "top";
/** Alignment against the trigger. Default "start". */
align?: PlacementAlign;
/** Gap between trigger and panel, in px. Default 6. */
sideOffset?: number;
alignOffset?: number;
/** Accessible name; defaults to the trigger's text via aria-labelledby. */
ariaLabel?: string;
className?: string;
}
export function DropdownMenuContent({
children,
side = "bottom",
align = "start",
sideOffset = 6,
alignOffset = 0,
ariaLabel,
className,
}: DropdownMenuContentProps) {
const level = useMenuLevel("DropdownMenuContent");
return (
<MenuPanel
level={level}
side={side}
align={align}
sideOffset={sideOffset}
alignOffset={alignOffset}
ariaLabel={ariaLabel}
className={className}
>
{children}
</MenuPanel>
);
}
/* -------------------------------------------------------------------------- */
/* Items */
/* -------------------------------------------------------------------------- */
type ItemVariant = "default" | "destructive";
interface ItemBaseProps {
children: ReactNode;
itemId?: string;
role?: "menuitem" | "menuitemcheckbox" | "menuitemradio";
ariaChecked?: boolean;
disabled?: boolean;
variant?: ItemVariant;
inset?: boolean;
textValue?: string;
className?: string;
closeOnSelect: boolean;
onActivate?: (event: ReactMouseEvent<HTMLButtonElement>) => void;
isSubTrigger?: boolean;
extraProps?: React.ButtonHTMLAttributes<HTMLButtonElement> & {
ref?: Ref<HTMLButtonElement>;
[key: `data-${string}`]: string | undefined;
};
}
function ItemBase({
children,
itemId,
role = "menuitem",
ariaChecked,
disabled = false,
variant = "default",
inset = false,
textValue,
className,
closeOnSelect,
onActivate,
isSubTrigger = false,
extraProps,
}: ItemBaseProps) {
const level = useMenuLevel("DropdownMenuItem");
const autoId = useId();
const id = itemId ?? autoId;
const highlighted = level.activeId === id;
const checkedProps =
role === "menuitem" ? {} : { "aria-checked": ariaChecked ?? false };
const { onPointerEnter, onPointerLeave, onKeyDown, ref, ...rest } =
extraProps ?? {};
return (
<button
{...rest}
ref={ref}
type="button"
id={id}
role={role}
{...checkedProps}
disabled={disabled}
tabIndex={-1}
data-dropdown-menu-item=""
data-disabled={disabled ? "true" : undefined}
data-highlighted={highlighted ? "" : undefined}
data-label={textValue}
onFocus={() => level.setActiveId(id)}
onPointerEnter={(event: ReactPointerEvent<HTMLButtonElement>) => {
onPointerEnter?.(event);
if (!isSubTrigger && event.pointerType !== "touch") {
level.scheduleSubClose();
}
}}
onPointerMove={(event: ReactPointerEvent<HTMLButtonElement>) => {
if (disabled || event.pointerType === "touch") return;
if (document.activeElement !== event.currentTarget) {
event.currentTarget.focus({ preventScroll: true });
}
}}
onPointerLeave={(event: ReactPointerEvent<HTMLButtonElement>) => {
onPointerLeave?.(event);
if (event.pointerType === "touch" || isSubTrigger) return;
// Clearing focus to the panel drops the highlight when the pointer
// leaves the rows, the way native menus behave.
if (document.activeElement === event.currentTarget) {
level.contentRef.current?.focus({ preventScroll: true });
}
}}
onKeyDown={onKeyDown}
onClick={(event) => {
if (disabled) return;
onActivate?.(event);
if (closeOnSelect && !event.defaultPrevented) level.closeAll(true);
}}
className={cn(
"relative isolate flex w-full select-none items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left text-[13px] outline-none",
"disabled:pointer-events-none disabled:opacity-40",
"[&_svg]:size-4 [&_svg]:shrink-0",
inset && "pl-8",
variant === "destructive"
? "text-destructive [&_svg]:text-destructive"
: "text-foreground [&_svg]:text-muted-foreground",
className,
)}
>
{/* Its own presence boundary: a layoutId element registers with the
nearest AnimatePresence, and the panel's exit would otherwise wait
on the highlight's layout animation and never unmount. */}
<AnimatePresence initial={false}>
{highlighted ? (
<motion.span
aria-hidden="true"
layoutId={`${level.levelId}-highlight`}
className={cn(
"absolute inset-0 -z-10 rounded-lg",
variant === "destructive"
? "bg-destructive/10"
: "bg-foreground/[0.07]",
)}
transition={level.reduce ? { duration: 0 } : SPRING_LAYOUT}
/>
) : null}
</AnimatePresence>
{children}
</button>
);
}
function Shortcut({ children }: { children: ReactNode }) {
return (
<span
aria-hidden="true"
className="ml-auto pl-4 font-mono text-[11px] tracking-wide text-muted-foreground"
>
{children}
</span>
);
}
export interface DropdownMenuItemProps {
children: ReactNode;
/** Leading icon (sized to 16px). */
icon?: ReactNode;
/** Trailing shortcut hint, e.g. "⌘K" or a `KbdCombo`. Decorative. */
shortcut?: ReactNode;
variant?: ItemVariant;
disabled?: boolean;
/** Indent to line up with checkbox/radio rows. */
inset?: boolean;
/** Text used by typeahead when children aren't plain text. */
textValue?: string;
/** Call `event.preventDefault()` to keep the menu open. */
onSelect?: (event: ReactMouseEvent<HTMLButtonElement>) => void;
/** Default true. */
closeOnSelect?: boolean;
className?: string;
}
export function DropdownMenuItem({
children,
icon,
shortcut,
onSelect,
closeOnSelect = true,
...props
}: DropdownMenuItemProps) {
return (
<ItemBase {...props} closeOnSelect={closeOnSelect} onActivate={onSelect}>
{icon}
<span className="min-w-0 flex-1 truncate">{children}</span>
{shortcut ? <Shortcut>{shortcut}</Shortcut> : null}
</ItemBase>
);
}
function Indicator({
checked,
kind,
reduce,
}: {
checked: boolean;
kind: "check" | "dot";
reduce: boolean;
}) {
return (
<span
aria-hidden="true"
className="absolute left-2.5 flex size-4 items-center justify-center"
>
<AnimatePresence initial={false}>
{checked ? (
<motion.span
key={kind}
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}
animate={{ opacity: 1, scale: 1 }}
exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}
transition={reduce ? { duration: 0.08 } : SPRING_PANEL}
className="flex items-center justify-center text-foreground"
>
{kind === "check" ? (
<Check className="size-3.5! text-foreground!" strokeWidth={2.6} />
) : (
<span className="size-1.5 rounded-full bg-current" />
)}
</motion.span>
) : null}
</AnimatePresence>
</span>
);
}
export interface DropdownMenuCheckboxItemProps
extends Omit<DropdownMenuItemProps, "onSelect" | "inset" | "icon"> {
checked?: boolean;
defaultChecked?: boolean;
onCheckedChange?: (checked: boolean) => void;
}
/** A toggle row. Stays open on select by default so several can be flipped. */
export function DropdownMenuCheckboxItem({
children,
checked: controlledChecked,
defaultChecked = false,
onCheckedChange,
shortcut,
closeOnSelect = false,
...props
}: DropdownMenuCheckboxItemProps) {
const level = useMenuLevel("DropdownMenuCheckboxItem");
const [internal, setInternal] = useState(defaultChecked);
const checked = controlledChecked ?? internal;
return (
<ItemBase
{...props}
inset
role="menuitemcheckbox"
ariaChecked={checked}
closeOnSelect={closeOnSelect}
onActivate={() => {
if (controlledChecked === undefined) setInternal(!checked);
onCheckedChange?.(!checked);
}}
>
<Indicator checked={checked} kind="check" reduce={level.reduce} />
<span className="min-w-0 flex-1 truncate">{children}</span>
{shortcut ? <Shortcut>{shortcut}</Shortcut> : null}
</ItemBase>
);
}
interface RadioGroupContextValue {
value: string | undefined;
select: (value: string) => void;
}
const RadioGroupContext = createContext<RadioGroupContextValue | null>(null);
export interface DropdownMenuRadioGroupProps {
children: ReactNode;
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
/** Accessible name for the group. */
ariaLabel?: string;
className?: string;
}
export function DropdownMenuRadioGroup({
children,
value: controlledValue,
defaultValue,
onValueChange,
ariaLabel,
className,
}: DropdownMenuRadioGroupProps) {
const [internal, setInternal] = useState(defaultValue);
const value = controlledValue ?? internal;
const ctx = useMemo<RadioGroupContextValue>(
() => ({
value,
select: (next) => {
if (controlledValue === undefined) setInternal(next);
onValueChange?.(next);
},
}),
[value, controlledValue, onValueChange],
);
return (
<RadioGroupContext.Provider value={ctx}>
<fieldset
aria-label={ariaLabel}
className={cn("m-0 min-w-0 border-0 p-0", className)}
>
{children}
</fieldset>
</RadioGroupContext.Provider>
);
}
export interface DropdownMenuRadioItemProps
extends Omit<DropdownMenuItemProps, "onSelect" | "inset" | "icon"> {
value: string;
}
export function DropdownMenuRadioItem({
children,
value,
shortcut,
closeOnSelect = false,
...props
}: DropdownMenuRadioItemProps) {
const level = useMenuLevel("DropdownMenuRadioItem");
const group = useContext(RadioGroupContext);
if (!group) {
throw new Error(
"DropdownMenuRadioItem must be used within <DropdownMenuRadioGroup>",
);
}
const checked = group.value === value;
return (
<ItemBase
{...props}
inset
role="menuitemradio"
ariaChecked={checked}
closeOnSelect={closeOnSelect}
onActivate={() => group.select(value)}
>
<Indicator checked={checked} kind="dot" reduce={level.reduce} />
<span className="min-w-0 flex-1 truncate">{children}</span>
{shortcut ? <Shortcut>{shortcut}</Shortcut> : null}
</ItemBase>
);
}
export interface DropdownMenuLabelProps {
children: ReactNode;
inset?: boolean;
className?: string;
}
export function DropdownMenuLabel({
children,
inset = false,
className,
}: DropdownMenuLabelProps) {
return (
<div
className={cn(
"px-2.5 pb-1 pt-1.5 text-[11px] font-medium text-muted-foreground",
inset && "pl-8",
className,
)}
>
{children}
</div>
);
}
export interface DropdownMenuGroupProps {
children: ReactNode;
ariaLabel?: string;
className?: string;
}
export function DropdownMenuGroup({
children,
ariaLabel,
className,
}: DropdownMenuGroupProps) {
return (
<fieldset
aria-label={ariaLabel}
className={cn("m-0 min-w-0 border-0 p-0", className)}
>
{children}
</fieldset>
);
}
export function DropdownMenuSeparator({ className }: { className?: string }) {
return <hr className={cn("-mx-1.5 my-1.5 h-px border-0 bg-border", className)} />;
}
/* -------------------------------------------------------------------------- */
/* Submenus */
/* -------------------------------------------------------------------------- */
interface SubContextValue {
level: MenuLevel;
parent: MenuLevel;
triggerItemId: string;
openTimer: MutableRefObject<ReturnType<typeof setTimeout> | null>;
openWith: (intent: FocusIntent) => void;
}
const SubContext = createContext<SubContextValue | null>(null);
function useSub(component: string) {
const sub = useContext(SubContext);
if (!sub) throw new Error(`${component} must be used within <DropdownMenuSub>`);
return sub;
}
export interface DropdownMenuSubProps {
children: ReactNode;
}
/** A nested menu opened from a `DropdownMenuSubTrigger` row. */
export function DropdownMenuSub({ children }: DropdownMenuSubProps) {
const parent = useMenuLevel("DropdownMenuSub");
const subId = useId();
const open = parent.open && parent.openSub === subId;
const triggerRef = useRef<HTMLElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);
const focusIntent = useRef<FocusIntent>("none");
const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const core = useLevelCore(open);
const triggerItemId = `${subId}-trigger`;
useEffect(
() => () => {
if (openTimer.current) clearTimeout(openTimer.current);
},
[],
);
// Open submenus take focus only when asked to (keyboard); a hover open
// leaves it on the trigger row.
useEffect(() => {
if (!open) return;
const frame = requestAnimationFrame(() =>
focusByIntent(contentRef.current, focusIntent.current),
);
return () => cancelAnimationFrame(frame);
}, [open]);
const { setOpenSub } = parent;
const close = useCallback(
(restoreFocus: boolean) => {
setOpenSub(null);
if (restoreFocus) triggerRef.current?.focus({ preventScroll: true });
},
[setOpenSub],
);
const openWith = useCallback(
(intent: FocusIntent) => {
if (openTimer.current) clearTimeout(openTimer.current);
openTimer.current = null;
focusIntent.current = intent;
if (open) focusByIntent(contentRef.current, intent);
else setOpenSub(subId);
},
[open, setOpenSub, subId],
);
const level = useMemo<MenuLevel>(
() => ({
rootId: parent.rootId,
levelId: `${subId}-level`,
open,
isSub: true,
triggerId: triggerItemId,
contentId: `${subId}-content`,
triggerRef,
contentRef,
focusIntent,
...core,
close,
closeAll: parent.closeAll,
openRoot: parent.openRoot,
reduce: parent.reduce,
}),
[
parent.rootId,
parent.closeAll,
parent.openRoot,
parent.reduce,
subId,
open,
triggerItemId,
core,
close,
],
);
const ctx = useMemo<SubContextValue>(
() => ({ level, parent, triggerItemId, openTimer, openWith }),
[level, parent, triggerItemId, openWith],
);
return <SubContext.Provider value={ctx}>{children}</SubContext.Provider>;
}
export interface DropdownMenuSubTriggerProps {
children: ReactNode;
icon?: ReactNode;
disabled?: boolean;
inset?: boolean;
textValue?: string;
className?: string;
}
export function DropdownMenuSubTrigger({
children,
icon,
...props
}: DropdownMenuSubTriggerProps) {
const { level, parent, triggerItemId, openTimer, openWith } = useSub(
"DropdownMenuSubTrigger",
);
const clearOpenTimer = () => {
if (openTimer.current) clearTimeout(openTimer.current);
openTimer.current = null;
};
return (
<ItemBase
{...props}
itemId={triggerItemId}
isSubTrigger
closeOnSelect={false}
onActivate={(event) => openWith(event.detail === 0 ? "first" : "none")}
extraProps={{
ref: (node: HTMLButtonElement | null) => {
level.triggerRef.current = node;
},
"aria-haspopup": "menu",
"aria-expanded": level.open,
"aria-controls": level.open ? level.contentId : undefined,
"data-state": level.open ? "open" : "closed",
onPointerEnter: (event) => {
if (event.pointerType === "touch" || props.disabled) return;
parent.cancelSubClose();
if (level.open) return;
clearOpenTimer();
openTimer.current = setTimeout(() => {
openTimer.current = null;
openWith("none");
}, SUB_OPEN_DELAY);
},
onPointerLeave: (event) => {
if (event.pointerType === "touch") return;
clearOpenTimer();
parent.scheduleSubClose();
},
onKeyDown: (event) => {
if (event.key === "ArrowRight") {
event.preventDefault();
openWith("first");
}
},
}}
>
{icon}
<span className="min-w-0 flex-1 truncate">{children}</span>
<ChevronRight
aria-hidden="true"
className="-mr-1 ml-auto size-3.5! text-muted-foreground"
/>
</ItemBase>
);
}
export interface DropdownMenuSubContentProps {
children: ReactNode;
/** Preferred side; flips when the viewport lacks room. Default "right". */
side?: "right" | "left";
/** Gap from the parent panel, in px. Default 8. */
sideOffset?: number;
/** Shift so the first row lines up with the trigger row. Default -7. */
alignOffset?: number;
ariaLabel?: string;
className?: string;
}
export function DropdownMenuSubContent({
children,
side = "right",
sideOffset = 8,
alignOffset = -7,
ariaLabel,
className,
}: DropdownMenuSubContentProps) {
const { level, parent, triggerItemId } = useSub("DropdownMenuSubContent");
const { cancelSubClose, setActiveId } = parent;
// While the pointer or focus is in the submenu, its trigger row keeps the
// parent's highlight and the pending close is called off.
const onPanelEnter = useCallback(() => {
cancelSubClose();
setActiveId(triggerItemId);
}, [cancelSubClose, setActiveId, triggerItemId]);
return (
<MenuLevelContext.Provider value={level}>
<MenuPanel
level={level}
side={side}
align="start"
sideOffset={sideOffset}
alignOffset={alignOffset}
ariaLabel={ariaLabel}
className={cn("min-w-44", className)}
onPanelEnter={onPanelEnter}
>
{children}
</MenuPanel>
</MenuLevelContext.Provider>
);
}
"use client";
import { motion, useReducedMotion } from "motion/react";
import { Fragment, type ReactNode, useEffect, useState } from "react";
import { SPRING_PRESS } from "@/lib/ease";
import { cn } from "@/lib/utils";
/* -------------------------------------------------------------------------- */
/* Platform */
/* -------------------------------------------------------------------------- */
function detectApple() {
const nav = navigator as Navigator & {
userAgentData?: { platform?: string };
};
const platform = nav.userAgentData?.platform ?? nav.platform ?? "";
return /mac|iphone|ipad|ipod/i.test(platform);
}
/**
* True on Apple platforms. Always `true` on the server and the first client
* render (so markup matches), then corrected after mount — `Mod` therefore
* renders ⌘ first and swaps to Ctrl on other platforms.
*/
export function useIsApple() {
const [apple, setApple] = useState(true);
useEffect(() => setApple(detectApple()), []);
return apple;
}
type KeyLabel = { glyph: string; name: string };
/** Display glyph + spoken name for a key token like "mod", "shift", "k". */
export function keyLabel(key: string, apple: boolean): KeyLabel {
const k = key.toLowerCase();
switch (k) {
case "mod":
return apple
? { glyph: "⌘", name: "Command" }
: { glyph: "Ctrl", name: "Control" };
case "cmd":
case "command":
case "meta":
return apple
? { glyph: "⌘", name: "Command" }
: { glyph: "Win", name: "Windows" };
case "ctrl":
case "control":
return apple
? { glyph: "⌃", name: "Control" }
: { glyph: "Ctrl", name: "Control" };
case "shift":
return apple
? { glyph: "⇧", name: "Shift" }
: { glyph: "Shift", name: "Shift" };
case "alt":
case "option":
return apple
? { glyph: "⌥", name: "Option" }
: { glyph: "Alt", name: "Alt" };
case "enter":
case "return":
return { glyph: "↵", name: "Enter" };
case "esc":
case "escape":
return { glyph: "Esc", name: "Escape" };
case "backspace":
return { glyph: "⌫", name: "Backspace" };
case "delete":
return { glyph: "⌦", name: "Delete" };
case "tab":
return { glyph: "⇥", name: "Tab" };
case "space":
return { glyph: "Space", name: "Space" };
case "up":
case "arrowup":
return { glyph: "↑", name: "Up arrow" };
case "down":
case "arrowdown":
return { glyph: "↓", name: "Down arrow" };
case "left":
case "arrowleft":
return { glyph: "←", name: "Left arrow" };
case "right":
case "arrowright":
return { glyph: "→", name: "Right arrow" };
default:
return key.length === 1
? { glyph: key.toUpperCase(), name: key.toUpperCase() }
: { glyph: key, name: key };
}
}
/* -------------------------------------------------------------------------- */
/* Key listening */
/* -------------------------------------------------------------------------- */
/** Does this keyboard event's key correspond to the token? */
function eventMatches(token: string, event: KeyboardEvent, apple: boolean) {
const k = token.toLowerCase();
const key = event.key.toLowerCase();
switch (k) {
case "mod":
return key === (apple ? "meta" : "control");
case "cmd":
case "command":
case "meta":
return key === "meta";
case "ctrl":
case "control":
return key === "control";
case "alt":
case "option":
return key === "alt";
case "esc":
return key === "escape";
case "return":
return key === "enter";
case "space":
return event.code === "Space";
case "up":
case "down":
case "left":
case "right":
return key === `arrow${k}`;
default:
// Letters and digits by physical key, so Shift/Option variants
// ("P" with Shift, "π" with Option) still match.
if (/^[a-z]$/.test(k)) return event.code === `Key${k.toUpperCase()}`;
if (/^[0-9]$/.test(k)) return event.code === `Digit${k}`;
return key === k;
}
}
const MODIFIERS = new Set(["meta", "control", "shift", "alt"]);
/**
* Tracks which of `keys` are physically held. Listens on window without
* preventing default, so it never steals the shortcut from the page.
*/
export function useKeysPressed(keys: string[], enabled = true) {
const apple = useIsApple();
const [held, setHeld] = useState<boolean[]>(() => keys.map(() => false));
const signature = keys.join("+");
useEffect(() => {
const tokens = signature.split("+");
setHeld(tokens.map(() => false));
if (!enabled) return;
const down = new Set<number>();
const sync = () => setHeld(tokens.map((_, i) => down.has(i)));
const onDown = (event: KeyboardEvent) => {
let changed = false;
tokens.forEach((token, i) => {
if (!down.has(i) && eventMatches(token, event, apple)) {
down.add(i);
changed = true;
}
});
if (changed) sync();
};
const onUp = (event: KeyboardEvent) => {
// macOS swallows keyup for other keys while ⌘ is held, so releasing a
// modifier releases everything.
if (MODIFIERS.has(event.key.toLowerCase()) && apple) {
down.clear();
sync();
return;
}
let changed = false;
tokens.forEach((token, i) => {
if (down.has(i) && eventMatches(token, event, apple)) {
down.delete(i);
changed = true;
}
});
if (changed) sync();
};
const reset = () => {
down.clear();
sync();
};
window.addEventListener("keydown", onDown);
window.addEventListener("keyup", onUp);
window.addEventListener("blur", reset);
return () => {
window.removeEventListener("keydown", onDown);
window.removeEventListener("keyup", onUp);
window.removeEventListener("blur", reset);
};
}, [signature, enabled, apple]);
return held;
}
/* -------------------------------------------------------------------------- */
/* Kbd */
/* -------------------------------------------------------------------------- */
type KbdSize = "sm" | "md";
const SIZE: Record<KbdSize, string> = {
sm: "h-5 min-w-5 px-1 text-[11px] rounded-[5px] border-b-[2px]",
md: "h-6 min-w-6 px-1.5 text-xs rounded-md border-b-[3px]",
};
// How far the key drops when pressed, in px — matches the thicker bottom edge
// so the cap visibly sinks into its base.
const DIP: Record<KbdSize, number> = { sm: 1.5, md: 2 };
export interface KbdProps {
/** A key token ("mod", "shift", "k", "enter"…) or any custom content. */
children: ReactNode;
size?: KbdSize;
/** Show the key pressed (spring dip). */
pressed?: boolean;
/** Dip when the real key is held. Needs `children` to be a key token string. */
listen?: boolean;
className?: string;
}
/**
* A single keyboard key. String children are treated as key tokens, so
* `<Kbd>mod</Kbd>` renders ⌘ on Apple platforms and Ctrl elsewhere.
*/
export function Kbd({
children,
size = "md",
pressed = false,
listen = false,
className,
}: KbdProps) {
const apple = useIsApple();
const token = typeof children === "string" ? children : null;
const [held] = useKeysPressed(token ? [token] : [], listen && token !== null);
const label = token ? keyLabel(token, apple) : null;
return (
<KeyCap
size={size}
pressed={pressed || Boolean(held)}
title={label?.name}
className={className}
>
{label ? label.glyph : children}
</KeyCap>
);
}
function KeyCap({
children,
size,
pressed,
title,
className,
}: {
children: ReactNode;
size: KbdSize;
pressed: boolean;
title?: string;
className?: string;
}) {
const reduce = useReducedMotion() ?? false;
return (
<motion.kbd
title={title}
data-pressed={pressed ? "" : undefined}
initial={false}
animate={
reduce
? { opacity: pressed ? 0.7 : 1 }
: { y: pressed ? DIP[size] : 0, scale: pressed ? 0.96 : 1 }
}
transition={reduce ? { duration: 0.1 } : SPRING_PRESS}
className={cn(
"inline-flex select-none items-center justify-center border border-border border-b-border-strong bg-muted font-sans font-medium leading-none text-muted-foreground",
"data-[pressed]:border-b-border data-[pressed]:bg-foreground/[0.08] data-[pressed]:text-foreground",
SIZE[size],
className,
)}
>
{children}
</motion.kbd>
);
}
export interface KbdComboProps {
/** Key tokens, e.g. ["mod", "shift", "p"]. */
keys: string[];
size?: KbdSize;
/** Show every key pressed. */
pressed?: boolean;
/** Dip each key while the real key is held. */
listen?: boolean;
/** Text between keys. Default none on Apple, "+" elsewhere. */
separator?: ReactNode;
className?: string;
}
/**
* A key combination: one chip per key, platform-aware, with a spoken label
* ("Command + Shift + P") for assistive tech.
*/
export function KbdCombo({
keys,
size = "md",
pressed = false,
listen = false,
separator,
className,
}: KbdComboProps) {
const apple = useIsApple();
const held = useKeysPressed(keys, listen);
const labels = keys.map((key) => keyLabel(key, apple));
const sep = separator === undefined ? (apple ? null : "+") : separator;
return (
<kbd
className={cn(
"inline-flex items-center gap-1 font-sans text-muted-foreground",
className,
)}
>
<span className="sr-only">{labels.map((l) => l.name).join(" + ")}</span>
<span aria-hidden="true" className="inline-flex items-center gap-1">
{labels.map((label, i) => (
<Fragment key={keys[i]}>
{i > 0 && sep !== null ? (
<span className="text-[10px] text-muted-foreground/70">{sep}</span>
) : null}
<KeyCap size={size} pressed={pressed || Boolean(held[i])}>
{label.glyph}
</KeyCap>
</Fragment>
))}
</span>
</kbd>
);
}
"use client";
import {
AnimatePresence,
motion,
useReducedMotion,
type Variants,
} from "motion/react";
import {
cloneElement,
isValidElement,
type PointerEvent,
type ReactElement,
type ReactNode,
useCallback,
useEffect,
useId,
useMemo,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { EASE_OUT } from "@/lib/ease";
import { useDismiss } from "@/lib/hooks/use-dismiss";
import { useHoverGesture } from "@/lib/hooks/use-hover-gesture";
import { useTapGesture } from "@/lib/hooks/use-tap-gesture";
import { cn } from "@/lib/utils";
type Side = "top" | "right" | "bottom" | "left";
export interface TooltipProps {
content: ReactNode;
children: ReactElement;
side?: Side;
/** Delay before showing (ms). Default 120. */
delay?: number;
className?: string;
/** Classes for the outer wrapper span. Use to fix baseline / fill parent. */
wrapperClassName?: string;
}
// Gap between trigger and tooltip, in px.
const GAP = 8;
// Centering transform for the fixed-positioned anchor point, per side.
const anchorTransform: Record<Side, string> = {
top: "translate(-50%, -100%)",
bottom: "translate(-50%, 0)",
left: "translate(-100%, -50%)",
right: "translate(0, -50%)",
};
const transformOrigin: Record<Side, string> = {
top: "center bottom",
bottom: "center top",
left: "right center",
right: "left center",
};
// Offset is in the direction *away* from the trigger — content originates near
// the trigger and rises into resting position.
const offsetFrom: Record<Side, { x?: number; y?: number }> = {
top: { y: 8 },
bottom: { y: -8 },
left: { x: 8 },
right: { x: -8 },
};
function buildVariants(side: Side): Variants {
const o = offsetFrom[side];
return {
initial: {
opacity: 0,
scale: 0.9,
filter: "blur(5px)",
x: o.x ?? 0,
y: o.y ?? 0,
},
animate: {
opacity: 1,
scale: 1,
filter: "blur(0px)",
x: 0,
y: 0,
transition: {
type: "spring",
stiffness: 380,
damping: 30,
mass: 0.7,
opacity: { duration: 0.14, ease: EASE_OUT },
filter: { duration: 0.18, ease: EASE_OUT },
},
},
exit: {
opacity: 0,
scale: 0.94,
filter: "blur(3px)",
x: (o.x ?? 0) * 0.6,
y: (o.y ?? 0) * 0.6,
transition: { duration: 0.12, ease: EASE_OUT },
},
};
}
const REDUCED_VARIANTS: Variants = {
initial: { opacity: 0 },
animate: { opacity: 1, transition: { duration: 0.14, ease: EASE_OUT } },
exit: { opacity: 0, transition: { duration: 0.1, ease: EASE_OUT } },
};
// Once any tooltip has just closed, neighbouring tooltips open without the
// initial delay — moving along a toolbar feels instant after the first one.
const WARM_WINDOW_MS = 300;
let lastHiddenAt = 0;
export function Tooltip({
content,
children,
side = "top",
delay = 120,
className,
wrapperClassName,
}: TooltipProps) {
const [open, setOpen] = useState(false);
const [coords, setCoords] = useState<{ top: number; left: number } | null>(
null,
);
const id = useId();
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const anchorRef = useRef<HTMLSpanElement>(null);
const hover = useHoverGesture();
const reduce = useReducedMotion();
// Anchor point in viewport coords, on the edge of the trigger facing `side`.
// Position:fixed means these viewport coords place the tooltip directly, so
// it escapes every ancestor's stacking context and overflow.
const place = useCallback(() => {
const el = anchorRef.current;
if (!el) return;
const r = el.getBoundingClientRect();
const cx = r.left + r.width / 2;
const cy = r.top + r.height / 2;
const point: Record<Side, { top: number; left: number }> = {
top: { top: r.top - GAP, left: cx },
bottom: { top: r.bottom + GAP, left: cx },
left: { top: cy, left: r.left - GAP },
right: { top: cy, left: r.right + GAP },
};
setCoords(point[side]);
}, [side]);
const show = useCallback(() => {
if (timer.current) clearTimeout(timer.current);
const warm = Date.now() - lastHiddenAt < WARM_WINDOW_MS;
timer.current = setTimeout(
() => {
place();
setOpen(true);
},
warm ? 0 : delay,
);
}, [delay, place]);
const hide = useCallback(() => {
if (timer.current) {
clearTimeout(timer.current);
timer.current = null;
}
if (open) lastHiddenAt = Date.now();
setOpen(false);
}, [open]);
// A finger never hovers, and Safari does not focus a button on tap either, so
// the label is only reachable if the tap itself opens the tooltip. A click
// carries no pointerType, so the pointerdown that preceded it is what says
// whether this was a tap; keyboard activation arrives with no pointerdown at
// all, and focus has already shown the label there.
const tap = useTapGesture<boolean>();
const toggleOnTap = useCallback(() => {
const gesture = tap.take();
if (!gesture || gesture.pointerType === "mouse") return;
if (gesture.state) {
hide();
return;
}
if (timer.current) clearTimeout(timer.current);
place();
setOpen(true);
}, [hide, place, tap]);
// ...and closed again by the next tap that lands somewhere else. The label
// covers nothing interactive, so that tap passes through to what it hit.
useDismiss(open, hide, anchorRef);
// Keep the tooltip pinned to the trigger while it's open and the page scrolls
// or resizes (fixed coords are viewport-relative).
useEffect(() => {
if (!open) return;
const onMove = () => place();
window.addEventListener("scroll", onMove, true);
window.addEventListener("resize", onMove);
return () => {
window.removeEventListener("scroll", onMove, true);
window.removeEventListener("resize", onMove);
};
}, [open, place]);
const variants = useMemo(
() => (reduce ? REDUCED_VARIANTS : buildVariants(side)),
[reduce, side],
);
if (!isValidElement(children)) return children;
// The label describes the trigger, so it has to name the trigger itself.
// Everything else the tooltip needs is read off the anchor below instead of
// cloned on: a handler written onto the child is the child's handler as far
// as that child can tell, and a component that owns its activation —
// hard-wiring onClick and spreading the rest of its props over it, as
// ThemeToggle does — then runs the tooltip's instead of its own. Composing
// with `props.onClick` cannot save it either, because a component element's
// props hold nothing the component does internally.
const trigger = cloneElement(children as ReactElement<Record<string, unknown>>, {
"aria-describedby": id,
});
return (
<>
{/* biome-ignore lint/a11y/noStaticElementInteractions: the anchor is not a
control — it observes the trigger it wraps. Every event listed reaches
it on its own (pointerdown/click/keydown/pointercancel bubble, focus
and blur arrive as focusin/focusout, and enter/leave are derived from
pointerover/pointerout along a path the anchor is on), so the trigger
keeps every handler it came with. */}
<span
ref={anchorRef}
className={cn("relative inline-flex align-middle", wrapperClassName)}
// Pointer events, not the mouse pair: a tap fires compatibility
// mouseenter/mouseleave that carry no pointerType, which raced the tap
// path into opening and closing the same label.
onPointerEnter={(event: PointerEvent) => {
if (hover.enter(event)) show();
}}
onPointerLeave={(event: PointerEvent) => {
if (hover.leave(event)) hide();
}}
onFocus={show}
onBlur={hide}
onPointerDown={(event: PointerEvent) => tap.start(event, open)}
// A gesture the platform took away sends no click, and a key press
// starts an activation that never had a pointer behind it. Either way
// the record has to go, or the next click reads a finger that has long
// since lifted.
onPointerCancel={tap.drop}
onKeyDown={tap.drop}
onClick={toggleOnTap}
>
{trigger}
</span>
{typeof document !== "undefined"
? createPortal(
<AnimatePresence>
{open && coords ? (
<span
aria-hidden
className="pointer-events-none fixed z-[9999]"
style={{
top: coords.top,
left: coords.left,
transform: anchorTransform[side],
}}
>
<motion.span
id={id}
role="tooltip"
variants={variants}
initial="initial"
animate="animate"
exit="exit"
style={{ transformOrigin: transformOrigin[side] }}
className={cn(
"block whitespace-nowrap rounded-lg border border-border bg-background px-2.5 py-1 text-xs font-medium text-foreground shadow-lg",
className,
)}
>
{content}
</motion.span>
</span>
) : null}
</AnimatePresence>,
document.body,
)
: null}
</>
);
}
import type { PortalLayout } from "@/components/motion/popover-position";
export type PlacementSide = "top" | "right" | "bottom" | "left";
export type PlacementAlign = "start" | "center" | "end";
export interface PlacementOptions {
side: PlacementSide;
align: PlacementAlign;
/** Gap between trigger and panel along the side axis, in px. */
sideOffset?: number;
/** Shift along the align axis, in px. */
alignOffset?: number;
/** Minimum distance kept from the viewport edges, in px. */
padding?: number;
}
export interface Placement {
left: number;
top: number;
/** The side actually used — differs from the requested one after a flip. */
side: PlacementSide;
/** Trigger-facing point of the panel, as a CSS transform-origin (px). */
origin: string;
}
const OPPOSITE: Record<PlacementSide, PlacementSide> = {
top: "bottom",
bottom: "top",
left: "right",
right: "left",
};
function clamp(value: number, min: number, max: number) {
return Math.min(Math.max(value, min), Math.max(min, max));
}
/**
* Places a portalled panel against its trigger in viewport coordinates
* (pair with `usePopoverPortalPosition`). Flips to the opposite side when the
* requested one lacks room and the other has more, then clamps the panel into
* the viewport on both axes. The returned origin is the trigger's center
* projected onto the panel's facing edge, so a scale entrance grows out of the
* trigger even after a flip or a clamp.
*/
export function resolvePlacement(
layout: PortalLayout,
{
side: requested,
align,
sideOffset = 6,
alignOffset = 0,
padding = 8,
}: PlacementOptions,
): Placement {
const { trigger, content } = layout;
const vw = window.innerWidth;
const vh = window.innerHeight;
const space: Record<PlacementSide, number> = {
top: trigger.top - sideOffset - padding,
bottom: vh - (trigger.top + trigger.height) - sideOffset - padding,
left: trigger.left - sideOffset - padding,
right: vw - (trigger.left + trigger.width) - sideOffset - padding,
};
const vertical = requested === "top" || requested === "bottom";
const need = vertical ? content.height : content.width;
const opposite = OPPOSITE[requested];
const side =
space[requested] < need && space[opposite] > space[requested]
? opposite
: requested;
let left: number;
let top: number;
if (vertical) {
top =
side === "bottom"
? trigger.top + trigger.height + sideOffset
: trigger.top - content.height - sideOffset;
left =
align === "start"
? trigger.left
: align === "end"
? trigger.left + trigger.width - content.width
: trigger.left + trigger.width / 2 - content.width / 2;
left = clamp(left + alignOffset, padding, vw - content.width - padding);
top = clamp(top, padding, vh - content.height - padding);
} else {
left =
side === "right"
? trigger.left + trigger.width + sideOffset
: trigger.left - content.width - sideOffset;
top =
align === "start"
? trigger.top
: align === "end"
? trigger.top + trigger.height - content.height
: trigger.top + trigger.height / 2 - content.height / 2;
top = clamp(top + alignOffset, padding, vh - content.height - padding);
left = clamp(left, padding, vw - content.width - padding);
}
const cx = clamp(trigger.left + trigger.width / 2 - left, 0, content.width);
const cy = clamp(trigger.top + trigger.height / 2 - top, 0, content.height);
const origin =
side === "bottom"
? `${cx}px 0px`
: side === "top"
? `${cx}px ${content.height}px`
: side === "right"
? `0px ${cy}px`
: `${content.width}px ${cy}px`;
return { left, top, side, origin };
}
"use client";
import {
type MutableRefObject,
useCallback,
useLayoutEffect,
useState,
} from "react";
export type PortalLayout = {
trigger: {
left: number;
top: number;
width: number;
height: number;
};
content: {
width: number;
height: number;
};
};
function sameLayout(a: PortalLayout | null, b: PortalLayout) {
return (
a?.trigger.left === b.trigger.left &&
a.trigger.top === b.trigger.top &&
a.trigger.width === b.trigger.width &&
a.trigger.height === b.trigger.height &&
a.content.width === b.content.width &&
a.content.height === b.content.height
);
}
/** Measures a trigger and portalled panel in viewport coordinates. */
export function usePopoverPortalPosition<
TriggerElement extends HTMLElement,
ContentElement extends HTMLElement,
>(
triggerRef: MutableRefObject<TriggerElement | null>,
contentRef: MutableRefObject<ContentElement | null>,
active: boolean,
) {
const [layout, setLayout] = useState<PortalLayout | null>(null);
const update = useCallback(() => {
const trigger = triggerRef.current;
const content = contentRef.current;
if (!trigger || !content) return;
const rect = trigger.getBoundingClientRect();
const next: PortalLayout = {
trigger: {
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height,
},
content: {
width: content.offsetWidth,
height: content.offsetHeight,
},
};
setLayout((current) => (sameLayout(current, next) ? current : next));
}, [contentRef, triggerRef]);
useLayoutEffect(() => {
update();
if (!active) return;
const trigger = triggerRef.current;
const content = contentRef.current;
const observer = new ResizeObserver(update);
if (trigger) observer.observe(trigger);
if (content) observer.observe(content);
window.addEventListener("scroll", update, true);
window.addEventListener("resize", update);
return () => {
observer.disconnect();
window.removeEventListener("scroll", update, true);
window.removeEventListener("resize", update);
};
}, [active, contentRef, triggerRef, update]);
return layout;
}
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, motion, useReducedMotion } from "motion/react";
import {
useCallback,
useId,
useRef,
useState,
type KeyboardEvent,
type ReactNode,
} from "react";
import { SPRING_LAYOUT, SPRING_PRESS, SPRING_SWAP } from "@/lib/ease";
import { cn } from "@/lib/utils";
// SegmentedControl vs Tabs: `Tabs` (tabs.tsx, variants pill/segment/underline)
// switches *panels* with tablist/tab semantics. `SegmentedControl` is a form
// control: it picks one *value* with radiogroup/radio semantics, can post that
// value with a form via `name`, supports disabled options, icon-only options
// and a full-width layout, and its thumb is a raised card surface rather than
// a filled accent pill. Reach for Tabs when each option owns content below it.
export type SegmentedControlSize = "sm" | "md" | "lg";
export interface SegmentedControlOption {
value: string;
label?: ReactNode;
icon?: ReactNode;
disabled?: boolean;
/** Required when the option has only an icon. */
"aria-label"?: string;
}
const trackSize: Record<SegmentedControlSize, string> = {
sm: "h-8 p-0.5 text-xs",
md: "h-10 p-1 text-sm",
lg: "h-12 p-1 text-sm",
};
const itemSize: Record<SegmentedControlSize, string> = {
sm: "gap-1.5 px-2.5 [&_svg]:size-3.5",
md: "gap-2 px-3.5 [&_svg]:size-4",
lg: "gap-2 px-5 [&_svg]:size-[18px]",
};
function useControllable<T>(
value: T | undefined,
defaultValue: T,
onChange: ((next: T) => void) | undefined,
) {
const [internal, setInternal] = useState<T>(defaultValue);
const controlled = value !== undefined;
const current = controlled ? value : internal;
const set = useCallback(
(next: T) => {
if (!controlled) setInternal(next);
onChange?.(next);
},
[controlled, onChange],
);
return [current, set] as const;
}
/** Index of the next enabled option from `from` in `dir`, wrapping around. */
function nextEnabled(options: { disabled?: boolean }[], from: number, dir: 1 | -1) {
const n = options.length;
for (let step = 1; step <= n; step++) {
const i = (((from + dir * step) % n) + n) % n;
if (!options[i].disabled) return i;
}
return from;
}
export interface SegmentedControlProps {
options: SegmentedControlOption[];
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
size?: SegmentedControlSize;
/** Stretch to the container width with equal-width segments. */
fullWidth?: boolean;
disabled?: boolean;
/** When set, a hidden input posts the value with the surrounding form. */
name?: string;
"aria-label"?: string;
"aria-labelledby"?: string;
className?: string;
thumbClassName?: string;
}
export function SegmentedControl({
options,
value,
defaultValue,
onValueChange,
size = "md",
fullWidth = false,
disabled = false,
name,
className,
thumbClassName,
...aria
}: SegmentedControlProps) {
const [current, setValue] = useControllable(
value,
defaultValue ?? options.find((o) => !o.disabled)?.value ?? "",
onValueChange,
);
const reduce = useReducedMotion();
const layoutId = useId();
const refs = useRef<(HTMLButtonElement | null)[]>([]);
const items = options.map((o) => ({ ...o, disabled: disabled || o.disabled }));
const selectedIndex = items.findIndex((o) => o.value === current);
// Roving tab stop: the checked radio, or the first enabled one when none is.
const tabStop = selectedIndex >= 0 && !items[selectedIndex].disabled
? selectedIndex
: items.findIndex((o) => !o.disabled);
const onKeyDown = (event: KeyboardEvent<HTMLButtonElement>, index: number) => {
let next: number | null = null;
switch (event.key) {
case "ArrowRight":
case "ArrowDown":
next = nextEnabled(items, index, 1);
break;
case "ArrowLeft":
case "ArrowUp":
next = nextEnabled(items, index, -1);
break;
case "Home":
next = nextEnabled(items, -1, 1);
break;
case "End":
next = nextEnabled(items, items.length, -1);
break;
default:
return;
}
event.preventDefault();
if (next === null || items[next].disabled) return;
// Selection follows focus, as the WAI-ARIA radio group pattern prescribes.
refs.current[next]?.focus();
if (items[next].value !== current) setValue(items[next].value);
};
return (
// layoutRoot keeps the thumb's shared-layout projection local, so scrolled
// or fixed ancestors never leak offsets into its glide.
<motion.div
layoutRoot
role="radiogroup"
aria-disabled={disabled || undefined}
{...aria}
className={cn(
"relative isolate items-stretch rounded-xl border border-border bg-muted",
fullWidth ? "flex w-full" : "inline-flex",
trackSize[size],
disabled && "opacity-60",
className,
)}
>
{name ? <input type="hidden" name={name} value={current} /> : null}
{items.map((option, index) => {
const checked = option.value === current;
const iconOnly = !option.label;
return (
<motion.button
key={option.value}
ref={(el) => {
refs.current[index] = el;
}}
type="button"
role="radio"
aria-checked={checked}
aria-label={option["aria-label"]}
disabled={option.disabled}
tabIndex={index === tabStop ? 0 : -1}
data-state={checked ? "checked" : "unchecked"}
onClick={() => !checked && setValue(option.value)}
onKeyDown={(e) => onKeyDown(e, index)}
whileTap={reduce || option.disabled ? undefined : { scale: 0.96 }}
transition={SPRING_PRESS}
className={cn(
"relative inline-flex min-w-0 select-none items-center justify-center whitespace-nowrap rounded-[9px] font-medium outline-none transition-colors duration-200",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-muted",
"disabled:cursor-not-allowed disabled:opacity-50",
fullWidth && "flex-1",
itemSize[size],
iconOnly && "aspect-square px-0",
checked
? "text-foreground"
: "text-muted-foreground enabled:hover:text-foreground",
)}
>
{checked ? (
<motion.span
layoutId={layoutId}
aria-hidden
transition={reduce ? { duration: 0 } : SPRING_LAYOUT}
className={cn(
"absolute inset-0 -z-10 rounded-[9px] border border-border bg-card shadow-sm",
thumbClassName,
)}
/>
) : null}
{option.icon ? (
<span aria-hidden className="inline-flex shrink-0">
{option.icon}
</span>
) : null}
{option.label ? <span className="truncate">{option.label}</span> : null}
</motion.button>
);
})}
</motion.div>
);
}
/* ------------------------------------------------------------------------ */
/* ToggleGroup */
/* ------------------------------------------------------------------------ */
export interface ToggleGroupItem {
value: string;
label?: ReactNode;
icon?: ReactNode;
disabled?: boolean;
/** Required when the item has only an icon. */
"aria-label"?: string;
}
type ToggleGroupBase = {
items: ToggleGroupItem[];
size?: SegmentedControlSize;
disabled?: boolean;
"aria-label"?: string;
"aria-labelledby"?: string;
className?: string;
};
export type ToggleGroupSingleProps = ToggleGroupBase & {
type: "single";
/** The pressed item, or `""` when none is pressed. */
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
/** Disallow un-pressing the active item, so one is always pressed. */
required?: boolean;
};
export type ToggleGroupMultipleProps = ToggleGroupBase & {
type: "multiple";
value?: string[];
defaultValue?: string[];
onValueChange?: (value: string[]) => void;
};
export type ToggleGroupProps = ToggleGroupSingleProps | ToggleGroupMultipleProps;
const toggleSize: Record<SegmentedControlSize, string> = {
sm: "h-7 min-w-7 gap-1.5 px-2 text-xs [&_svg]:size-3.5",
md: "h-9 min-w-9 gap-2 px-2.5 text-sm [&_svg]:size-4",
lg: "h-11 min-w-11 gap-2 px-3.5 text-sm [&_svg]:size-[18px]",
};
export function ToggleGroup(props: ToggleGroupProps) {
const { items, size = "md", disabled = false, className } = props;
const reduce = useReducedMotion();
const refs = useRef<(HTMLButtonElement | null)[]>([]);
const [focusIndex, setFocusIndex] = useState<number | null>(null);
// Normalise both modes to a string[] internally.
const single = props.type === "single";
const [current, setCurrent] = useControllable<string[]>(
props.value === undefined ? undefined : single ? (props.value ? [props.value as string] : []) : (props.value as string[]),
single
? props.defaultValue
? [props.defaultValue as string]
: []
: ((props.defaultValue as string[] | undefined) ?? []),
(next) => {
if (props.type === "single") props.onValueChange?.(next[0] ?? "");
else props.onValueChange?.(next);
},
);
const list = items.map((i) => ({ ...i, disabled: disabled || i.disabled }));
const firstEnabled = list.findIndex((i) => !i.disabled);
const tabStop =
focusIndex !== null && !list[focusIndex]?.disabled ? focusIndex : firstEnabled;
const toggle = (itemValue: string) => {
const pressed = current.includes(itemValue);
if (props.type === "single") {
if (pressed && props.required) return;
setCurrent(pressed ? [] : [itemValue]);
} else {
setCurrent(pressed ? current.filter((v) => v !== itemValue) : [...current, itemValue]);
}
};
const onKeyDown = (event: KeyboardEvent<HTMLButtonElement>, index: number) => {
let next: number | null = null;
if (event.key === "ArrowRight" || event.key === "ArrowDown") next = nextEnabled(list, index, 1);
else if (event.key === "ArrowLeft" || event.key === "ArrowUp") next = nextEnabled(list, index, -1);
else if (event.key === "Home") next = nextEnabled(list, -1, 1);
else if (event.key === "End") next = nextEnabled(list, list.length, -1);
if (next === null) return;
event.preventDefault();
// Focus moves; pressing stays on Space/Enter (toggle buttons, not radios).
setFocusIndex(next);
refs.current[next]?.focus();
};
return (
<motion.div
role="group"
aria-label={props["aria-label"]}
aria-labelledby={props["aria-labelledby"]}
className={cn(
"inline-flex items-center gap-0.5 rounded-xl border border-border bg-card p-1",
disabled && "opacity-60",
className,
)}
>
{list.map((item, index) => {
const pressed = current.includes(item.value);
return (
<motion.button
key={item.value}
ref={(el) => {
refs.current[index] = el;
}}
type="button"
aria-pressed={pressed}
aria-label={item["aria-label"]}
disabled={item.disabled}
tabIndex={index === tabStop ? 0 : -1}
data-state={pressed ? "on" : "off"}
onClick={() => {
setFocusIndex(index);
toggle(item.value);
}}
onFocus={() => setFocusIndex(index)}
onKeyDown={(e) => onKeyDown(e, index)}
whileTap={reduce || item.disabled ? undefined : { scale: 0.88 }}
transition={SPRING_PRESS}
className={cn(
"relative isolate inline-flex select-none items-center justify-center rounded-lg font-medium outline-none transition-colors duration-200",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-card",
"disabled:cursor-not-allowed disabled:opacity-50",
toggleSize[size],
pressed
? "text-foreground"
: "text-muted-foreground enabled:hover:bg-muted/60 enabled:hover:text-foreground",
)}
>
<AnimatePresence initial={false}>
{pressed ? (
<motion.span
key="on"
aria-hidden
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}
animate={{ opacity: 1, scale: 1 }}
exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.75, transition: { duration: 0.12 } }}
transition={SPRING_SWAP}
className="absolute inset-0 -z-10 rounded-lg bg-muted ring-1 ring-border-strong"
/>
) : null}
</AnimatePresence>
{item.icon ? (
<span aria-hidden className="inline-flex shrink-0">
{item.icon}
</span>
) : null}
{item.label ? <span>{item.label}</span> : null}
</motion.button>
);
})}
</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 { 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
navDashboardNavGroup[]—active?stringControlled active nav id.
—defaultActive?string—onActiveChange?((id: string) => void)—collapsed?booleanControlled desktop collapse (icons only).
—defaultCollapsed?booleanfalseonCollapsedChange?((collapsed: boolean) => void)—brand{ name: string; logo?: ReactNode; }—user{ name: string; email?: string | undefined; avatar?: string | undefined; }—userMenu?DashboardUserMenuItem[]Avatar menu rows. Defaults to Profile, Settings and Sign out.
[
{ id: "profile", label: "Profile", icon: <User aria-hidden /> },
{ id: "settings", label: "Settings", icon: <Settings aria-hidden /> },
{ id: "sign-out", label: "Sign out", icon: <LogOut aria-hidden />, destructive: true },
]searchPlaceholder?stringSearch…onSearch?((query: string) => void)Fires on Enter in the search field.
—globalShortcut?booleanAlso focus search on Mod+K anywhere on the page (default: only while focus is inside the shell).
falsebreadcrumbs?BreadcrumbDataItem[]—title?ReactNode—description?ReactNode—actions?ReactNodePage-header actions (buttons).
—mobileBelow?numberShell width in px below which the sidebar moves into a Drawer behind a menu button. Measured on the shell itself (a CSS container query), not the viewport. Default 768, which matches `md` when the shell spans the page.
768className?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