Morph Popover
A panel that unfolds from the corner nearest its trigger on a spring.
Preview
"use client";
import { ChevronDown, Copy, Pencil, Share2, Trash2 } from "lucide-react";
import { useState } from "react";
import {
MorphPopover,
MorphPopoverContent,
MorphPopoverTrigger,
} from "@/components/motion/popover-morph";
const ACTIONS = [
{ icon: Pencil, label: "Edit" },
{ icon: Copy, label: "Duplicate" },
{ icon: Share2, label: "Share" },
{ icon: Trash2, label: "Delete" },
];
export function MorphPopoverPreview() {
const [open, setOpen] = useState(false);
return (
<MorphPopover open={open} onOpenChange={setOpen}>
<MorphPopoverTrigger>
<button
type="button"
className="inline-flex h-10 items-center gap-2 rounded-full border border-border bg-background px-4 text-sm font-medium text-foreground outline-none transition-colors hover:border-border-strong focus-visible:ring-2 focus-visible:ring-ring"
>
Options
<ChevronDown className="h-4 w-4 text-muted-foreground" />
</button>
</MorphPopoverTrigger>
<MorphPopoverContent align="start" className="w-48 p-2">
{ACTIONS.map(({ icon: Icon, label }) => (
<button
key={label}
type="button"
onClick={() => setOpen(false)}
className="flex w-full items-center gap-2.5 rounded-full px-3 py-1.5 text-left text-sm text-foreground outline-none transition-colors hover:bg-muted focus-visible:bg-muted"
>
<Icon className="h-4 w-4 text-muted-foreground" />
{label}
</button>
))}
</MorphPopoverContent>
</MorphPopover>
);
}
"use client";
// beui.dev/components/motion/popover/morph
import {
AnimatePresence,
animate,
motion,
useMotionValue,
usePresence,
useReducedMotion,
useTransform,
} from "motion/react";
import {
cloneElement,
createContext,
isValidElement,
type ReactElement,
type ReactNode,
type Ref,
type RefObject,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { usePopoverPortalPosition } from "@/components/motion/popover-position";
import { EASE_OUT } from "@/lib/ease";
import { FOCUSABLE_SELECTOR } from "@/lib/focusable";
import { useDismiss } from "@/lib/hooks/use-dismiss";
import { mergeRefs } from "@/lib/merge-refs";
import { cn } from "@/lib/utils";
type Side = "top" | "bottom";
type Align = "start" | "end";
type MorphContextValue = {
open: boolean;
setOpen: (open: boolean) => void;
toggle: () => void;
triggerId: string;
contentId: string;
/** The element the panel measures against — see `registerTrigger`. */
triggerRef: React.MutableRefObject<HTMLElement | null>;
registerTrigger: (node: HTMLElement | null) => void;
contentRef: React.MutableRefObject<HTMLDivElement | null>;
/** Arms or disarms moving focus into the panel as it next appears. */
armFocusOnOpen: (armed: boolean) => void;
/** Reads and disarms the flag set by `armFocusOnOpen`. */
takeFocusOnOpen: () => boolean;
};
const MorphContext = createContext<MorphContextValue | null>(null);
function useMorphContext(component: string) {
const ctx = useContext(MorphContext);
if (!ctx) throw new Error(`${component} must be used within <MorphPopover>`);
return ctx;
}
export interface MorphPopoverProps {
children: ReactNode;
/** Controlled open state. */
open?: boolean;
/** Uncontrolled initial open state. */
defaultOpen?: boolean;
/** Called with the new open state when the panel opens or closes. */
onOpenChange?: (open: boolean) => void;
/** Classes merged onto the wrapper around the trigger. */
className?: string;
}
/**
* A popover whose full-size panel reveals from the corner nearest the trigger
* on one spring, then retraces the same clip on close. Content and surface
* edges keep their size throughout. Closes on outside pointer / Escape.
* Controlled or uncontrolled.
*/
export function MorphPopover({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
className,
}: MorphPopoverProps) {
const baseId = useId();
const [root, setRoot] = useState<HTMLDivElement | null>(null);
const [trigger, setTrigger] = useState<HTMLElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const controlled = controlledOpen !== undefined;
const open = controlled ? controlledOpen : internalOpen;
const setOpen = useCallback(
(next: boolean) => {
if (!controlled) setInternalOpen(next);
onOpenChange?.(next);
},
[controlled, onOpenChange],
);
const toggle = useCallback(() => setOpen(!open), [setOpen, open]);
// A keyboard open arms focus for the panel to take as it appears. Any later
// key or pointer press disarms it, so an open the parent declined cannot
// leave it armed for a later open that nobody asked to focus.
const focusOnOpenRef = useRef(false);
const disarmRef = useRef<AbortController | null>(null);
const armFocusOnOpen = useCallback((armed: boolean) => {
disarmRef.current?.abort();
disarmRef.current = null;
focusOnOpenRef.current = armed;
if (!armed) return;
const controller = new AbortController();
const disarm = () => {
focusOnOpenRef.current = false;
controller.abort();
};
const options = { capture: true, signal: controller.signal };
document.addEventListener("keydown", disarm, options);
document.addEventListener("pointerdown", disarm, options);
disarmRef.current = controller;
}, []);
const takeFocusOnOpen = useCallback(() => {
const armed = focusOnOpenRef.current;
armFocusOnOpen(false);
return armed;
}, [armFocusOnOpen]);
useEffect(() => () => disarmRef.current?.abort(), []);
// A trigger normally registers itself through MorphPopoverTrigger. It can't
// when something else already clones the element — a Tooltip wrapping the
// button, say — and an unregistered trigger leaves the panel with nothing to
// measure against, so it renders permanently invisible. The root boxes the
// trigger exactly (the content portals out of it), so it stands in until a
// real trigger registers, and stands in again if that one unmounts. Both are
// state, so a trigger arriving while the panel is open re-anchors it.
const anchorRef = useMemo<React.MutableRefObject<HTMLElement | null>>(
() => ({ current: trigger ?? root }),
[root, trigger],
);
// The panel is a `role="dialog"` and goes inert the moment it closes, so
// focus cannot be left sitting inside it: a dismissal hands it back to the
// trigger, the way the ARIA dialog pattern asks. A pointer dismissal takes
// the focus onward itself when it lands on something focusable — this only
// catches the case where it would otherwise be stranded. When no trigger has
// registered, the root anchor stands in only if it can actually hold focus;
// there is nowhere better than where the keyboard already is, so leave it.
const close = useCallback(() => {
setOpen(false);
const focused = document.activeElement;
const inPanel =
focused instanceof HTMLElement && contentRef.current?.contains(focused);
if (!inPanel) return;
const restore = trigger ?? (root && root.tabIndex >= 0 ? root : null);
restore?.focus();
}, [root, setOpen, trigger]);
// Inside is the root anchor and the portaled panel. Until the root mounts
// there is nothing to measure "outside" against, so nothing dismisses.
const insidePopover = useCallback(
(target: Element) =>
!root || root.contains(target) || Boolean(contentRef.current?.contains(target)),
[root],
);
useDismiss(open, close, null, { ignore: insidePopover });
const ctx = useMemo<MorphContextValue>(
() => ({
open,
setOpen,
toggle,
triggerId: `${baseId}-trigger`,
contentId: `${baseId}-content`,
triggerRef: anchorRef,
registerTrigger: setTrigger,
contentRef,
armFocusOnOpen,
takeFocusOnOpen,
}),
[open, setOpen, toggle, baseId, anchorRef, armFocusOnOpen, takeFocusOnOpen],
);
return (
<MorphContext.Provider value={ctx}>
<div ref={setRoot} className={cn("relative inline-flex", className)}>
{children}
</div>
</MorphContext.Provider>
);
}
export interface MorphPopoverTriggerProps {
children: ReactElement;
}
/** Wraps a single element, toggling the popover on click. */
export function MorphPopoverTrigger({ children }: MorphPopoverTriggerProps) {
const ctx = useMorphContext("MorphPopoverTrigger");
const child = children as ReactElement<Record<string, unknown>>;
const childOnClick = child?.props?.onClick as
| ((e: unknown) => void)
| undefined;
const childOnKeyDown = child?.props?.onKeyDown as
| ((e: unknown) => void)
| undefined;
const childOnPointerDown = child?.props?.onPointerDown as
| ((e: unknown) => void)
| undefined;
// Set by an Enter or Space keydown on the trigger, cleared by a pointer
// press, read by the click that follows.
const keyboardRef = useRef(false);
const childRef = (child?.props as { ref?: Ref<HTMLElement> } | undefined)
?.ref;
// Register once per actual ref change, not once per open-state render.
const mergedRef = useMemo(
() => mergeRefs(childRef, ctx.registerTrigger),
[childRef, ctx.registerTrigger],
);
if (!isValidElement(children)) return children;
return cloneElement(child, {
id: ctx.triggerId,
ref: mergedRef,
onKeyDown: (e: unknown) => {
childOnKeyDown?.(e);
const key = (e as { key?: string } | undefined)?.key;
keyboardRef.current = key === "Enter" || key === " ";
},
onPointerDown: (e: unknown) => {
childOnPointerDown?.(e);
keyboardRef.current = false;
},
onClick: (e: unknown) => {
childOnClick?.(e);
// Enter and Space reach here as a click with `detail` 0 after their
// keydown on this element. A pointer click counts at least 1, and a
// scripted click() has no keydown before it. Only a keyboard open
// moves focus into the panel.
const keyboard =
keyboardRef.current &&
(e as { detail?: number } | undefined)?.detail === 0;
keyboardRef.current = false;
ctx.armFocusOnOpen(!ctx.open && keyboard);
ctx.toggle();
},
"aria-haspopup": "dialog",
"aria-expanded": ctx.open,
"aria-controls": ctx.open ? ctx.contentId : undefined,
});
}
// Full-distance clip travel needs a shorter curve than SPRING_PANEL's slow
// overdamped tail. A non-bouncing spring reaches its rest within 260 ms.
const MORPH_ENTER = { type: "spring", duration: 0.26, bounce: 0 } as const;
const MORPH_EXIT = { duration: 0.2, ease: EASE_OUT } as const;
// Keep the panel and content at their final size. An inset clip reveals the
// nearest corner without scaling borders, shadows or keyboard-focus geometry.
// A full-size clip keeps content at its final coordinates without box-to-box
// scale correction. One progress value keeps clip and opacity synchronized;
// clip-path and the shadow may paint, so this is not a compositor-only morph.
function clipAt(side: Side, align: Align, radius: number, inset: number) {
return `inset(${side === "top" ? inset : 0}% ${align === "start" ? inset : 0}% ${side === "bottom" ? inset : 0}% ${align === "end" ? inset : 0}% round ${radius}px)`;
}
export interface MorphPopoverContentProps {
children: ReactNode;
/** Preferred side of the trigger. Flips when there is no room. Default: "bottom" */
side?: Side;
/** Lines the panel up with the trigger's start or end edge. Default: "end" */
align?: Align;
/** Gap between trigger and panel, in px. Default 8. */
sideOffset?: number;
/** Panel corner radius, in px. Default 16 (rounded-2xl), like every floating panel. */
radius?: number;
/** Draw the surface shadow. Default true. */
shadow?: boolean;
/**
* Runs after the portalled surface is positioned and visible. Passing it
* hands focus to the caller: the panel then moves no focus on its own.
*/
onOpenAutoFocus?: (content: HTMLDivElement) => void;
/**
* Element to focus when the trigger opens the panel by keyboard. Defaults
* to the first focusable element in the panel, or the panel itself. A
* pointer open does not move focus. Ignored with `onOpenAutoFocus`.
*/
initialFocus?: RefObject<HTMLElement | null>;
/** Classes merged onto the panel surface. */
className?: string;
}
export function MorphPopoverContent(props: MorphPopoverContentProps) {
const ctx = useMorphContext("MorphPopoverContent");
const [portalReady, setPortalReady] = useState(false);
useEffect(() => setPortalReady(true), []);
if (!portalReady) return null;
return createPortal(
<AnimatePresence>
{ctx.open && <MorphPopoverSurface {...props} />}
</AnimatePresence>,
document.body,
);
}
// Measurement belongs to the mounted portal session: reopening must not start
// an entrance at the previous session's coordinates before measuring this one.
function MorphPopoverSurface({
children,
side = "bottom",
align = "end",
sideOffset = 8,
radius = 16,
shadow = true,
onOpenAutoFocus,
initialFocus,
className,
}: MorphPopoverContentProps) {
const ctx = useMorphContext("MorphPopoverContent");
const reduce = useReducedMotion() ?? false;
const [isPresent, safeToRemove] = usePresence();
const layout = usePopoverPortalPosition(
ctx.triggerRef,
ctx.contentRef,
isPresent,
);
const preferredLeft = layout
? align === "end"
? layout.trigger.left + layout.trigger.width - layout.content.width
: layout.trigger.left
: 0;
// Keep larger compositions, such as calendars, inside the viewport. Prefer
// the requested side, then use the roomier side when it cannot fit there.
const gutter = 12;
const below = layout
? Math.max(
0,
window.innerHeight -
layout.trigger.top -
layout.trigger.height -
sideOffset -
gutter,
)
: 0;
const above = layout
? Math.max(0, layout.trigger.top - sideOffset - gutter)
: 0;
const requestedSpace = side === "bottom" ? below : above;
const otherSpace = side === "bottom" ? above : below;
const resolvedSide =
layout &&
layout.content.height > requestedSpace &&
otherSpace > requestedSpace
? side === "bottom"
? "top"
: "bottom"
: side;
const availableHeight = resolvedSide === "bottom" ? below : above;
const left = layout
? Math.max(
gutter,
Math.min(
preferredLeft,
window.innerWidth - layout.content.width - gutter,
),
)
: 0;
const top = layout
? resolvedSide === "bottom"
? layout.trigger.top + layout.trigger.height + sideOffset
: Math.max(
gutter,
layout.trigger.top - layout.content.height - sideOffset,
)
: 0;
const progress = useMotionValue(0);
const clipPath = useTransform(progress, (p) =>
clipAt(resolvedSide, align, radius, 92 * (1 - p)),
);
const surfaceOpacity = useTransform(progress, [0, 0.15], [0, 1]);
// Reduced motion has no travel, so a short fade carries the whole entrance
// and exit on its own.
const fade = useMotionValue(reduce ? 0 : 1);
const ready = layout !== null;
const focusedOnOpen = useRef(false);
useEffect(() => {
if (
!ready ||
!isPresent ||
focusedOnOpen.current ||
!ctx.contentRef.current
)
return;
focusedOnOpen.current = true;
onOpenAutoFocus?.(ctx.contentRef.current);
}, [ready, isPresent, ctx.contentRef, onOpenAutoFocus]);
// `safeToRemove` is a new function on every render: AnimatePresence
// rebuilds its context each time its parent renders. Read it through a ref
// so a render during the exit (a consumer's state change, a list streaming
// in) does not restart the exit from where it got to — restarted every
// render, it would close in ever smaller steps and never report completion,
// leaving an inert, invisible panel mounted for good.
const safeToRemoveRef = useRef(safeToRemove);
useLayoutEffect(() => {
safeToRemoveRef.current = safeToRemove;
});
useEffect(() => {
if (!ready) {
if (!isPresent) safeToRemoveRef.current?.();
return;
}
const settle = () => {
if (!isPresent) safeToRemoveRef.current?.();
};
if (reduce) {
progress.jump(1);
const animation = animate(fade, isPresent ? 1 : 0, {
duration: 0.12,
onComplete: settle,
});
return () => animation.stop();
}
const animation = animate(progress, isPresent ? 1 : 0, {
...(isPresent ? MORPH_ENTER : MORPH_EXIT),
onComplete: settle,
});
return () => animation.stop();
}, [fade, progress, ready, isPresent, reduce]);
// The wrapper stays `visibility: hidden` until the first measurement, and
// focus() inside a hidden subtree is silently ignored. So move focus in the
// commit that makes the panel visible, not when it mounts. A CSS transition
// on `visibility` can still hold the controls hidden for a moment after
// that commit (a reduced-motion reset that gives every element a short
// transition-duration does), so while focus rests on the panel or has not
// moved, each such transition that ends tries the candidates again, until
// the user presses a key or pointer. The effect runs once per open, so it
// reads the caller's props through refs: a new ref or callback passed
// mid-open must not tear down a pending retry.
const initialFocusRef = useRef(initialFocus);
const callerFocusesRef = useRef(onOpenAutoFocus !== undefined);
useLayoutEffect(() => {
initialFocusRef.current = initialFocus;
callerFocusesRef.current = onOpenAutoFocus !== undefined;
});
const { contentRef, takeFocusOnOpen } = ctx;
useLayoutEffect(() => {
if (!ready || !isPresent) return;
if (!takeFocusOnOpen() || callerFocusesRef.current) return;
const panel = contentRef.current;
const wrapper = panel?.parentElement;
if (!panel || !wrapper) return;
const from = document.activeElement;
const unmoved = () =>
document.activeElement === from || document.activeElement === panel;
// The selector also matches elements focus() refuses: a hidden input, a
// disabled button that carries a tabindex, anything under display: none.
// Keep the first candidate that takes focus, else hold it on the panel.
const focusFirst = () => {
const candidates = [
initialFocusRef.current?.current,
...panel.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
];
for (const candidate of candidates) {
if (!candidate) continue;
candidate.focus({ preventScroll: true });
if (unmoved()) continue;
// preventScroll keeps the page still, but it also stops the panel's
// own scroll area from bringing a row below the fold into view.
candidate.scrollIntoView?.({ block: "nearest" });
return true;
}
panel.focus({ preventScroll: true });
return false;
};
if (focusFirst()) return;
const retry = (event: TransitionEvent) => {
if (event.propertyName !== "visibility") return;
if (!unmoved() || focusFirst()) stop();
};
const stop = () => {
wrapper.removeEventListener("transitionend", retry);
document.removeEventListener("keydown", stop, true);
document.removeEventListener("pointerdown", stop, true);
};
wrapper.addEventListener("transitionend", retry);
document.addEventListener("keydown", stop, true);
document.addEventListener("pointerdown", stop, true);
return stop;
}, [ready, isPresent, contentRef, takeFocusOnOpen]);
return (
<motion.div
data-morph-popover-portal=""
inert={!isPresent}
style={{
left,
top,
opacity: reduce ? fade : surfaceOpacity,
pointerEvents: isPresent ? "auto" : "none",
visibility: layout ? "visible" : "hidden",
}}
// A drop-shadow follows the clipped surface; box-shadow would be cut
// off by its own clip. Caller surface classes retain their old target.
className={cn(
"fixed z-[9999]",
shadow && "[filter:drop-shadow(0_10px_18px_rgba(0,0,0,0.14))]",
)}
>
<motion.div
ref={ctx.contentRef}
id={ctx.contentId}
role="dialog"
aria-labelledby={ctx.triggerId}
tabIndex={-1}
style={{
clipPath: reduce ? undefined : clipPath,
borderRadius: radius,
maxHeight: layout ? availableHeight : undefined,
overflowX: "hidden",
overflowY: "auto",
}}
className={cn(
// The panel holds focus when nothing inside it can. An inset ring
// stays inside the clip that would cut off an outline.
"border border-border bg-background outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
className,
)}
>
{children}
</motion.div>
</motion.div>
);
}
Add it with the shadcn CLI, or copy the source manually.
npx shadcn add https://beui.dev/r/theme.json. Theme setupInstall dependencies
npm i clsx lucide-react motion tailwind-mergeAdd util files
// Shared motion tokens. Easing curves mirror the CSS custom properties in
// globals.css; springs are the canonical physics used across components.
// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */
export const EASE_IN = [0.55, 0, 1, 0.45] as const;
export const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;
export const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;
/** CSS string form of EASE_OUT for inline style transitions. */
export const EASE_OUT_CSS = "cubic-bezier(0.16, 1, 0.3, 1)";
/** Press feedback on buttons and other tappable surfaces. */
export const SPRING_PRESS = {
type: "spring",
stiffness: 500,
damping: 30,
mass: 0.6,
} as const;
/** Content swaps — label/icon slots trading places inside a control. */
export const SPRING_SWAP = {
type: "spring",
stiffness: 460,
damping: 30,
mass: 0.55,
} as const;
/** Overlay panel entrances — modals and sheets summoned by pointer. */
export const SPRING_PANEL = {
type: "spring",
stiffness: 420,
damping: 40,
mass: 0.5,
} as const;
/** Shared-layout glides — pills, indicators and panels morphing between positions. */
export const SPRING_LAYOUT = {
type: "spring",
stiffness: 360,
damping: 32,
mass: 0.6,
} as const;
/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */
export const SPRING_MOUSE = {
stiffness: 200,
damping: 15,
mass: 0.3,
} as const;
/** Dragged handles and fills (sliders) — critically damped `useSpring` config,
* so the value follows the pointer butterily and never rebounds off an end. */
export const SPRING_GLIDE = {
stiffness: 700,
damping: 50,
mass: 0.5,
} as const;
/** Shared-surface morphs: a trigger growing into its panel and back on one
* weighted spring, so opening and closing travel the same path. */
export const SPRING_MORPH = {
type: "spring",
duration: 0.5,
bounce: 0.22,
} as const;
/**
* Elements that can usually take keyboard focus. The selector cannot see
* everything focus() checks (an element under `display: none`, say), so a
* caller that needs certainty tries focus() and checks where it landed.
*/
export const FOCUSABLE_SELECTOR = [
"a[href]",
"button:not(:disabled)",
"input:not(:disabled):not([type='hidden'])",
"select:not(:disabled)",
"textarea:not(:disabled)",
"[tabindex]:not([tabindex='-1'])",
].join(",");
/** Elements inside `container` that Tab can reach, in DOM order. */
export function focusablesIn(container: Element | null | undefined) {
return Array.from(
container?.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR) ?? [],
).filter((element) => element.tabIndex >= 0 && !element.closest("[inert]"));
}
/** Focuses the first tabbable element in `panel`, or the panel itself. */
export function focusFirstIn(panel: HTMLElement | null | undefined) {
(focusablesIn(panel)[0] ?? panel)?.focus({ preventScroll: true });
}
/**
* Keeps a Tab keypress inside `panel`, wrapping from the last tabbable element
* to the first and back. Give the panel `tabIndex={-1}` so it can hold focus
* when it has nothing tabbable.
*/
export function cycleTab(event: KeyboardEvent, panel: HTMLElement | null) {
if (event.key !== "Tab" || !panel) return;
const elements = focusablesIn(panel);
const first = elements[0];
const last = elements[elements.length - 1];
const active = document.activeElement;
if (!first || !last) {
event.preventDefault();
panel.focus({ preventScroll: true });
} else if (event.shiftKey && (active === first || active === panel)) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && active === last) {
event.preventDefault();
first.focus();
}
}
"use client";
import { type RefObject, useEffect, useLayoutEffect, useRef } from "react";
import { inOtherLayer, type Layer, openLayer, ownsEscape } from "@/lib/layers";
/**
* What the dismissing gesture does to the control it landed on.
*
* `"pass-through"` is the platform norm (native popover light-dismiss): the
* tap closes the overlay *and* activates whatever was under it. Use
* `"consume"` where the open overlay sits over or beside controls that would
* be costly to trigger by accident — the dismissal then swallows the
* activation too, so the gesture only closes.
*/
export type DismissBehavior = "pass-through" | "consume";
/** What closed the overlay: Escape, a pointerdown outside it, or focus leaving it. */
export type DismissReason = "escape" | "pointer" | "focus";
export interface DismissOptions {
/** Default `"pass-through"`. */
behavior?: DismissBehavior;
/** Dismiss on Escape as well. Default true. */
escape?: boolean;
/** Dismiss when focus moves outside, as a combobox does on Tab. Default false. */
focusOutside?: boolean;
/**
* Dismiss on a pointerdown outside. Default true. Turn it off for an overlay
* whose own backdrop handles presses and only needs Escape and layering.
*/
outsidePress?: boolean;
/** Return true for an outside target that should *not* dismiss. */
ignore?: (target: Element) => boolean;
}
// preventDefault on pointerdown does not suppress the click that follows, so
// consuming a gesture means swallowing that click itself. The swallower
// deliberately outlives the effect that installed it — the dismissal it
// belongs to has already unmounted or re-rendered by the time the click lands.
// It releases on that click, or on the next gesture if the pointer is dragged
// away and no click ever arrives, so it can never eat a later one. A keydown
// releases it too: a gesture that ends with neither a click nor a cancel would
// otherwise leave it armed, and the click Enter synthesizes on some focused
// control is not the one this dismissal was owed.
function consumeActivation(source: Event) {
const swallow = (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
release();
};
const restart = (event: Event) => {
if (event !== source) release();
};
const release = () => {
window.removeEventListener("click", swallow, true);
window.removeEventListener("pointerdown", restart, true);
window.removeEventListener("pointercancel", restart, true);
window.removeEventListener("keydown", release, true);
};
window.addEventListener("click", swallow, true);
window.addEventListener("pointerdown", restart, true);
window.addEventListener("pointercancel", restart, true);
window.addEventListener("keydown", release, true);
}
/**
* Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`
* for `ref` when what counts as inside isn't one element, and say so with
* `ignore` instead.
*
* The pointerdown listener is capture-phase: a bubble-phase one is blinded by
* any handler in between that stops propagation, and an overlay cannot know
* what it is layered over.
*
* Each open dismissal is a layer in `lib/layers.ts`, so only the innermost
* open overlay answers Escape (a menu inside a drawer closes, the drawer
* stays), and a drawer's focus trap leaves focus in a menu it portaled out.
*/
export function useDismiss(
open: boolean,
onDismiss: (reason: DismissReason) => void,
ref: RefObject<HTMLElement | SVGElement | null> | null,
{
behavior = "pass-through",
escape: dismissOnEscape = true,
focusOutside = false,
outsidePress = true,
ignore,
}: DismissOptions = {},
) {
// Read through refs, so a callback rebuilt each render neither re-binds the
// listeners nor moves this layer to the top of the stack.
const dismissRef = useRef(onDismiss);
const ignoreRef = useRef(ignore);
useLayoutEffect(() => {
dismissRef.current = onDismiss;
ignoreRef.current = ignore;
});
useEffect(() => {
if (!open) return;
const inside = (target: Node) =>
Boolean(ref?.current?.contains(target)) ||
(target instanceof Element && Boolean(ignoreRef.current?.(target)));
const layer: Layer = { contains: inside, escape: dismissOnEscape };
const closeLayer = openLayer(layer);
const onKey = (event: KeyboardEvent) => {
if (!dismissOnEscape || event.key !== "Escape" || !ownsEscape(layer, event)) return;
event.preventDefault();
dismissRef.current("escape");
};
const onPointer = (event: PointerEvent) => {
const target = event.target as Element | null;
if (!target || inside(target)) return;
// Outside this overlay, but inside another open one: the gesture is
// that overlay's to answer, and swallowing its click from behind would
// cost the user the control they actually aimed at.
if (behavior === "consume" && !inOtherLayer(layer, target, { traps: false })) {
consumeActivation(event);
}
dismissRef.current("pointer");
};
const onFocus = (event: FocusEvent) => {
const target = event.target;
if (target instanceof Node && !inside(target)) dismissRef.current("focus");
};
window.addEventListener("keydown", onKey);
if (outsidePress) window.addEventListener("pointerdown", onPointer, true);
if (focusOutside) window.addEventListener("focusin", onFocus);
return () => {
closeLayer();
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer, true);
window.removeEventListener("focusin", onFocus);
};
}, [open, ref, behavior, dismissOnEscape, focusOutside, outsidePress]);
}
import type { Ref } from "react";
/** Points a callback or object ref at `value`. */
export function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {
if (typeof ref === "function") ref(value);
else if (ref) ref.current = value;
}
/** One callback ref that sets every ref it is given. */
export function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {
return (node: T | null) => {
for (const ref of refs) assignRef(ref, node);
};
}
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
/**
* Every open overlay on the page, innermost last: focus traps, modal scopes
* and dismissable menus all register here. Overlays have no shared z-order to
* consult, and a menu inside a drawer portals out of it, so this stack is how
* they agree on who answers Escape and where focus may go.
*/
export interface Layer {
/** Whether `target` belongs to this layer (its panel, portals, trigger). */
contains: (target: Node) => boolean;
/** True for focus traps and modal scopes, which pull stray focus back. */
traps?: boolean;
/** False for a layer that ignores Escape, so the key reaches the one below. */
escape?: boolean;
}
const stack: Layer[] = [];
// The innermost layer when each Escape began, read before any handler runs,
// so a layer that closes itself mid-event can't hand the key to the one below.
const escapeOwners = new WeakMap<Event, Layer | undefined>();
let listening = false;
function innermostEscapeLayer() {
for (let index = stack.length - 1; index >= 0; index--) {
if (stack[index].escape !== false) return stack[index];
}
return undefined;
}
function recordEscapeOwner(event: KeyboardEvent) {
if (event.key === "Escape") escapeOwners.set(event, innermostEscapeLayer());
}
/** Registers an open layer. Call the returned function when it closes. */
export function openLayer(layer: Layer) {
if (!listening) {
document.addEventListener("keydown", recordEscapeOwner, true);
listening = true;
}
stack.push(layer);
return () => {
const index = stack.indexOf(layer);
if (index !== -1) stack.splice(index, 1);
};
}
/** Whether this Escape is `layer`'s to answer: it was innermost when the key went down. */
export function ownsEscape(layer: Layer, event: KeyboardEvent) {
if (event.defaultPrevented) return false;
const owner = escapeOwners.has(event)
? escapeOwners.get(event)
: innermostEscapeLayer();
return owner === layer;
}
/** Whether `target` sits in a layer opened on top of `layer`. */
export function inLayerAbove(layer: Layer, target: Node) {
const index = stack.indexOf(layer);
return stack.slice(index + 1).some((above) => above.contains(target));
}
/** Whether a focus trap is open on top of `layer`; stray focus is that one's to pull back. */
export function trapAbove(layer: Layer) {
const index = stack.indexOf(layer);
return stack.slice(index + 1).some((above) => above.traps);
}
/**
* Whether `target` belongs to any open layer other than `layer`. Pass
* `traps: false` to count only dismissable overlays, not the traps under them.
*/
export function inOtherLayer(layer: Layer, target: Node, { traps = true } = {}) {
return stack.some(
(other) => other !== layer && (traps || !other.traps) && other.contains(target),
);
}
Copy the source code
"use client";
// beui.dev/components/motion/popover/morph
import {
AnimatePresence,
animate,
motion,
useMotionValue,
usePresence,
useReducedMotion,
useTransform,
} from "motion/react";
import {
cloneElement,
createContext,
isValidElement,
type ReactElement,
type ReactNode,
type Ref,
type RefObject,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { usePopoverPortalPosition } from "@/components/motion/popover-position";
import { EASE_OUT } from "@/lib/ease";
import { FOCUSABLE_SELECTOR } from "@/lib/focusable";
import { useDismiss } from "@/lib/hooks/use-dismiss";
import { mergeRefs } from "@/lib/merge-refs";
import { cn } from "@/lib/utils";
type Side = "top" | "bottom";
type Align = "start" | "end";
type MorphContextValue = {
open: boolean;
setOpen: (open: boolean) => void;
toggle: () => void;
triggerId: string;
contentId: string;
/** The element the panel measures against — see `registerTrigger`. */
triggerRef: React.MutableRefObject<HTMLElement | null>;
registerTrigger: (node: HTMLElement | null) => void;
contentRef: React.MutableRefObject<HTMLDivElement | null>;
/** Arms or disarms moving focus into the panel as it next appears. */
armFocusOnOpen: (armed: boolean) => void;
/** Reads and disarms the flag set by `armFocusOnOpen`. */
takeFocusOnOpen: () => boolean;
};
const MorphContext = createContext<MorphContextValue | null>(null);
function useMorphContext(component: string) {
const ctx = useContext(MorphContext);
if (!ctx) throw new Error(`${component} must be used within <MorphPopover>`);
return ctx;
}
export interface MorphPopoverProps {
children: ReactNode;
/** Controlled open state. */
open?: boolean;
/** Uncontrolled initial open state. */
defaultOpen?: boolean;
/** Called with the new open state when the panel opens or closes. */
onOpenChange?: (open: boolean) => void;
/** Classes merged onto the wrapper around the trigger. */
className?: string;
}
/**
* A popover whose full-size panel reveals from the corner nearest the trigger
* on one spring, then retraces the same clip on close. Content and surface
* edges keep their size throughout. Closes on outside pointer / Escape.
* Controlled or uncontrolled.
*/
export function MorphPopover({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
className,
}: MorphPopoverProps) {
const baseId = useId();
const [root, setRoot] = useState<HTMLDivElement | null>(null);
const [trigger, setTrigger] = useState<HTMLElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const controlled = controlledOpen !== undefined;
const open = controlled ? controlledOpen : internalOpen;
const setOpen = useCallback(
(next: boolean) => {
if (!controlled) setInternalOpen(next);
onOpenChange?.(next);
},
[controlled, onOpenChange],
);
const toggle = useCallback(() => setOpen(!open), [setOpen, open]);
// A keyboard open arms focus for the panel to take as it appears. Any later
// key or pointer press disarms it, so an open the parent declined cannot
// leave it armed for a later open that nobody asked to focus.
const focusOnOpenRef = useRef(false);
const disarmRef = useRef<AbortController | null>(null);
const armFocusOnOpen = useCallback((armed: boolean) => {
disarmRef.current?.abort();
disarmRef.current = null;
focusOnOpenRef.current = armed;
if (!armed) return;
const controller = new AbortController();
const disarm = () => {
focusOnOpenRef.current = false;
controller.abort();
};
const options = { capture: true, signal: controller.signal };
document.addEventListener("keydown", disarm, options);
document.addEventListener("pointerdown", disarm, options);
disarmRef.current = controller;
}, []);
const takeFocusOnOpen = useCallback(() => {
const armed = focusOnOpenRef.current;
armFocusOnOpen(false);
return armed;
}, [armFocusOnOpen]);
useEffect(() => () => disarmRef.current?.abort(), []);
// A trigger normally registers itself through MorphPopoverTrigger. It can't
// when something else already clones the element — a Tooltip wrapping the
// button, say — and an unregistered trigger leaves the panel with nothing to
// measure against, so it renders permanently invisible. The root boxes the
// trigger exactly (the content portals out of it), so it stands in until a
// real trigger registers, and stands in again if that one unmounts. Both are
// state, so a trigger arriving while the panel is open re-anchors it.
const anchorRef = useMemo<React.MutableRefObject<HTMLElement | null>>(
() => ({ current: trigger ?? root }),
[root, trigger],
);
// The panel is a `role="dialog"` and goes inert the moment it closes, so
// focus cannot be left sitting inside it: a dismissal hands it back to the
// trigger, the way the ARIA dialog pattern asks. A pointer dismissal takes
// the focus onward itself when it lands on something focusable — this only
// catches the case where it would otherwise be stranded. When no trigger has
// registered, the root anchor stands in only if it can actually hold focus;
// there is nowhere better than where the keyboard already is, so leave it.
const close = useCallback(() => {
setOpen(false);
const focused = document.activeElement;
const inPanel =
focused instanceof HTMLElement && contentRef.current?.contains(focused);
if (!inPanel) return;
const restore = trigger ?? (root && root.tabIndex >= 0 ? root : null);
restore?.focus();
}, [root, setOpen, trigger]);
// Inside is the root anchor and the portaled panel. Until the root mounts
// there is nothing to measure "outside" against, so nothing dismisses.
const insidePopover = useCallback(
(target: Element) =>
!root || root.contains(target) || Boolean(contentRef.current?.contains(target)),
[root],
);
useDismiss(open, close, null, { ignore: insidePopover });
const ctx = useMemo<MorphContextValue>(
() => ({
open,
setOpen,
toggle,
triggerId: `${baseId}-trigger`,
contentId: `${baseId}-content`,
triggerRef: anchorRef,
registerTrigger: setTrigger,
contentRef,
armFocusOnOpen,
takeFocusOnOpen,
}),
[open, setOpen, toggle, baseId, anchorRef, armFocusOnOpen, takeFocusOnOpen],
);
return (
<MorphContext.Provider value={ctx}>
<div ref={setRoot} className={cn("relative inline-flex", className)}>
{children}
</div>
</MorphContext.Provider>
);
}
export interface MorphPopoverTriggerProps {
children: ReactElement;
}
/** Wraps a single element, toggling the popover on click. */
export function MorphPopoverTrigger({ children }: MorphPopoverTriggerProps) {
const ctx = useMorphContext("MorphPopoverTrigger");
const child = children as ReactElement<Record<string, unknown>>;
const childOnClick = child?.props?.onClick as
| ((e: unknown) => void)
| undefined;
const childOnKeyDown = child?.props?.onKeyDown as
| ((e: unknown) => void)
| undefined;
const childOnPointerDown = child?.props?.onPointerDown as
| ((e: unknown) => void)
| undefined;
// Set by an Enter or Space keydown on the trigger, cleared by a pointer
// press, read by the click that follows.
const keyboardRef = useRef(false);
const childRef = (child?.props as { ref?: Ref<HTMLElement> } | undefined)
?.ref;
// Register once per actual ref change, not once per open-state render.
const mergedRef = useMemo(
() => mergeRefs(childRef, ctx.registerTrigger),
[childRef, ctx.registerTrigger],
);
if (!isValidElement(children)) return children;
return cloneElement(child, {
id: ctx.triggerId,
ref: mergedRef,
onKeyDown: (e: unknown) => {
childOnKeyDown?.(e);
const key = (e as { key?: string } | undefined)?.key;
keyboardRef.current = key === "Enter" || key === " ";
},
onPointerDown: (e: unknown) => {
childOnPointerDown?.(e);
keyboardRef.current = false;
},
onClick: (e: unknown) => {
childOnClick?.(e);
// Enter and Space reach here as a click with `detail` 0 after their
// keydown on this element. A pointer click counts at least 1, and a
// scripted click() has no keydown before it. Only a keyboard open
// moves focus into the panel.
const keyboard =
keyboardRef.current &&
(e as { detail?: number } | undefined)?.detail === 0;
keyboardRef.current = false;
ctx.armFocusOnOpen(!ctx.open && keyboard);
ctx.toggle();
},
"aria-haspopup": "dialog",
"aria-expanded": ctx.open,
"aria-controls": ctx.open ? ctx.contentId : undefined,
});
}
// Full-distance clip travel needs a shorter curve than SPRING_PANEL's slow
// overdamped tail. A non-bouncing spring reaches its rest within 260 ms.
const MORPH_ENTER = { type: "spring", duration: 0.26, bounce: 0 } as const;
const MORPH_EXIT = { duration: 0.2, ease: EASE_OUT } as const;
// Keep the panel and content at their final size. An inset clip reveals the
// nearest corner without scaling borders, shadows or keyboard-focus geometry.
// A full-size clip keeps content at its final coordinates without box-to-box
// scale correction. One progress value keeps clip and opacity synchronized;
// clip-path and the shadow may paint, so this is not a compositor-only morph.
function clipAt(side: Side, align: Align, radius: number, inset: number) {
return `inset(${side === "top" ? inset : 0}% ${align === "start" ? inset : 0}% ${side === "bottom" ? inset : 0}% ${align === "end" ? inset : 0}% round ${radius}px)`;
}
export interface MorphPopoverContentProps {
children: ReactNode;
/** Preferred side of the trigger. Flips when there is no room. Default: "bottom" */
side?: Side;
/** Lines the panel up with the trigger's start or end edge. Default: "end" */
align?: Align;
/** Gap between trigger and panel, in px. Default 8. */
sideOffset?: number;
/** Panel corner radius, in px. Default 16 (rounded-2xl), like every floating panel. */
radius?: number;
/** Draw the surface shadow. Default true. */
shadow?: boolean;
/**
* Runs after the portalled surface is positioned and visible. Passing it
* hands focus to the caller: the panel then moves no focus on its own.
*/
onOpenAutoFocus?: (content: HTMLDivElement) => void;
/**
* Element to focus when the trigger opens the panel by keyboard. Defaults
* to the first focusable element in the panel, or the panel itself. A
* pointer open does not move focus. Ignored with `onOpenAutoFocus`.
*/
initialFocus?: RefObject<HTMLElement | null>;
/** Classes merged onto the panel surface. */
className?: string;
}
export function MorphPopoverContent(props: MorphPopoverContentProps) {
const ctx = useMorphContext("MorphPopoverContent");
const [portalReady, setPortalReady] = useState(false);
useEffect(() => setPortalReady(true), []);
if (!portalReady) return null;
return createPortal(
<AnimatePresence>
{ctx.open && <MorphPopoverSurface {...props} />}
</AnimatePresence>,
document.body,
);
}
// Measurement belongs to the mounted portal session: reopening must not start
// an entrance at the previous session's coordinates before measuring this one.
function MorphPopoverSurface({
children,
side = "bottom",
align = "end",
sideOffset = 8,
radius = 16,
shadow = true,
onOpenAutoFocus,
initialFocus,
className,
}: MorphPopoverContentProps) {
const ctx = useMorphContext("MorphPopoverContent");
const reduce = useReducedMotion() ?? false;
const [isPresent, safeToRemove] = usePresence();
const layout = usePopoverPortalPosition(
ctx.triggerRef,
ctx.contentRef,
isPresent,
);
const preferredLeft = layout
? align === "end"
? layout.trigger.left + layout.trigger.width - layout.content.width
: layout.trigger.left
: 0;
// Keep larger compositions, such as calendars, inside the viewport. Prefer
// the requested side, then use the roomier side when it cannot fit there.
const gutter = 12;
const below = layout
? Math.max(
0,
window.innerHeight -
layout.trigger.top -
layout.trigger.height -
sideOffset -
gutter,
)
: 0;
const above = layout
? Math.max(0, layout.trigger.top - sideOffset - gutter)
: 0;
const requestedSpace = side === "bottom" ? below : above;
const otherSpace = side === "bottom" ? above : below;
const resolvedSide =
layout &&
layout.content.height > requestedSpace &&
otherSpace > requestedSpace
? side === "bottom"
? "top"
: "bottom"
: side;
const availableHeight = resolvedSide === "bottom" ? below : above;
const left = layout
? Math.max(
gutter,
Math.min(
preferredLeft,
window.innerWidth - layout.content.width - gutter,
),
)
: 0;
const top = layout
? resolvedSide === "bottom"
? layout.trigger.top + layout.trigger.height + sideOffset
: Math.max(
gutter,
layout.trigger.top - layout.content.height - sideOffset,
)
: 0;
const progress = useMotionValue(0);
const clipPath = useTransform(progress, (p) =>
clipAt(resolvedSide, align, radius, 92 * (1 - p)),
);
const surfaceOpacity = useTransform(progress, [0, 0.15], [0, 1]);
// Reduced motion has no travel, so a short fade carries the whole entrance
// and exit on its own.
const fade = useMotionValue(reduce ? 0 : 1);
const ready = layout !== null;
const focusedOnOpen = useRef(false);
useEffect(() => {
if (
!ready ||
!isPresent ||
focusedOnOpen.current ||
!ctx.contentRef.current
)
return;
focusedOnOpen.current = true;
onOpenAutoFocus?.(ctx.contentRef.current);
}, [ready, isPresent, ctx.contentRef, onOpenAutoFocus]);
// `safeToRemove` is a new function on every render: AnimatePresence
// rebuilds its context each time its parent renders. Read it through a ref
// so a render during the exit (a consumer's state change, a list streaming
// in) does not restart the exit from where it got to — restarted every
// render, it would close in ever smaller steps and never report completion,
// leaving an inert, invisible panel mounted for good.
const safeToRemoveRef = useRef(safeToRemove);
useLayoutEffect(() => {
safeToRemoveRef.current = safeToRemove;
});
useEffect(() => {
if (!ready) {
if (!isPresent) safeToRemoveRef.current?.();
return;
}
const settle = () => {
if (!isPresent) safeToRemoveRef.current?.();
};
if (reduce) {
progress.jump(1);
const animation = animate(fade, isPresent ? 1 : 0, {
duration: 0.12,
onComplete: settle,
});
return () => animation.stop();
}
const animation = animate(progress, isPresent ? 1 : 0, {
...(isPresent ? MORPH_ENTER : MORPH_EXIT),
onComplete: settle,
});
return () => animation.stop();
}, [fade, progress, ready, isPresent, reduce]);
// The wrapper stays `visibility: hidden` until the first measurement, and
// focus() inside a hidden subtree is silently ignored. So move focus in the
// commit that makes the panel visible, not when it mounts. A CSS transition
// on `visibility` can still hold the controls hidden for a moment after
// that commit (a reduced-motion reset that gives every element a short
// transition-duration does), so while focus rests on the panel or has not
// moved, each such transition that ends tries the candidates again, until
// the user presses a key or pointer. The effect runs once per open, so it
// reads the caller's props through refs: a new ref or callback passed
// mid-open must not tear down a pending retry.
const initialFocusRef = useRef(initialFocus);
const callerFocusesRef = useRef(onOpenAutoFocus !== undefined);
useLayoutEffect(() => {
initialFocusRef.current = initialFocus;
callerFocusesRef.current = onOpenAutoFocus !== undefined;
});
const { contentRef, takeFocusOnOpen } = ctx;
useLayoutEffect(() => {
if (!ready || !isPresent) return;
if (!takeFocusOnOpen() || callerFocusesRef.current) return;
const panel = contentRef.current;
const wrapper = panel?.parentElement;
if (!panel || !wrapper) return;
const from = document.activeElement;
const unmoved = () =>
document.activeElement === from || document.activeElement === panel;
// The selector also matches elements focus() refuses: a hidden input, a
// disabled button that carries a tabindex, anything under display: none.
// Keep the first candidate that takes focus, else hold it on the panel.
const focusFirst = () => {
const candidates = [
initialFocusRef.current?.current,
...panel.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
];
for (const candidate of candidates) {
if (!candidate) continue;
candidate.focus({ preventScroll: true });
if (unmoved()) continue;
// preventScroll keeps the page still, but it also stops the panel's
// own scroll area from bringing a row below the fold into view.
candidate.scrollIntoView?.({ block: "nearest" });
return true;
}
panel.focus({ preventScroll: true });
return false;
};
if (focusFirst()) return;
const retry = (event: TransitionEvent) => {
if (event.propertyName !== "visibility") return;
if (!unmoved() || focusFirst()) stop();
};
const stop = () => {
wrapper.removeEventListener("transitionend", retry);
document.removeEventListener("keydown", stop, true);
document.removeEventListener("pointerdown", stop, true);
};
wrapper.addEventListener("transitionend", retry);
document.addEventListener("keydown", stop, true);
document.addEventListener("pointerdown", stop, true);
return stop;
}, [ready, isPresent, contentRef, takeFocusOnOpen]);
return (
<motion.div
data-morph-popover-portal=""
inert={!isPresent}
style={{
left,
top,
opacity: reduce ? fade : surfaceOpacity,
pointerEvents: isPresent ? "auto" : "none",
visibility: layout ? "visible" : "hidden",
}}
// A drop-shadow follows the clipped surface; box-shadow would be cut
// off by its own clip. Caller surface classes retain their old target.
className={cn(
"fixed z-[9999]",
shadow && "[filter:drop-shadow(0_10px_18px_rgba(0,0,0,0.14))]",
)}
>
<motion.div
ref={ctx.contentRef}
id={ctx.contentId}
role="dialog"
aria-labelledby={ctx.triggerId}
tabIndex={-1}
style={{
clipPath: reduce ? undefined : clipPath,
borderRadius: radius,
maxHeight: layout ? availableHeight : undefined,
overflowX: "hidden",
overflowY: "auto",
}}
className={cn(
// The panel holds focus when nothing inside it can. An inset ring
// stays inside the clip that would cut off an outline.
"border border-border bg-background outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
className,
)}
>
{children}
</motion.div>
</motion.div>
);
}
"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;
}
open?booleanControlled open state.
—defaultOpen?booleanUncontrolled initial open state.
falseonOpenChange?((open: boolean) => void)Called with the new open state when the panel opens or closes.
—className?stringClasses merged onto the wrapper around the trigger.
—side?"top" | "bottom"Preferred side of the trigger. Flips when there is no room. Default: "bottom"
—align?"end" | "start"Lines the panel up with the trigger's start or end edge. Default: "end"
—sideOffset?numberGap between trigger and panel, in px. Default 8.
—radius?numberPanel corner radius, in px. Default 16 (rounded-2xl), like every floating panel.
—shadow?booleanDraw the surface shadow. Default true.
—onOpenAutoFocus?((content: HTMLDivElement) => void)Runs after the portalled surface is positioned and visible. Passing it hands focus to the caller: the panel then moves no focus on its own.
—initialFocus?RefObject<HTMLElement | null>Element to focus when the trigger opens the panel by keyboard. Defaults to the first focusable element in the panel, or the panel itself. A pointer open does not move focus. Ignored with `onOpenAutoFocus`.
—className?stringClasses merged onto the panel surface.
—Morphing Modal
Family-app-style modal. A single panel that morphs its height as you navigate between inner views, with blur cross-fade on content.
Drawer
Side panel that slides in from the left or right with a spring, backdrop blur, body scroll lock and esc-to-close.
Tooltip
Composable hover, focus and tap tooltip with a subtle scale and fade, collision-aware side and alignment, an optional arrow, a pointer corridor onto hoverable content, one label at a time, keyboard-only focus reveal and optional cursor tracking.
Updated