Hover Card
Hover card that springs out of its trigger after an open delay and stays open while the pointer travels into it; also opens on keyboard focus, closes on Escape or blur, and flips and aligns on any side to stay in the viewport, while touch taps simply follow the link.
Preview
Install
Add it with the shadcn CLI, or copy the source manually.
shadcn init? You are set. Theme setupInstall dependencies
npm i clsx lucide-react motion tailwind-mergeAdd util files
// Shared motion tokens. Easing curves mirror the CSS custom properties in
// globals.css; springs are the canonical physics used across components.
// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
export const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;
export const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;
/** CSS string form of EASE_OUT for inline style transitions. */
export const EASE_OUT_CSS = "cubic-bezier(0.16, 1, 0.3, 1)";
/** Press feedback on buttons and other tappable surfaces. */
export const SPRING_PRESS = {
type: "spring",
stiffness: 500,
damping: 30,
mass: 0.6,
} as const;
/** Content swaps — label/icon slots trading places inside a control. */
export const SPRING_SWAP = {
type: "spring",
stiffness: 460,
damping: 30,
mass: 0.55,
} as const;
/** Overlay panel entrances — modals and sheets summoned by pointer. */
export const SPRING_PANEL = {
type: "spring",
stiffness: 420,
damping: 40,
mass: 0.5,
} as const;
/** Shared-layout glides — pills, indicators and panels morphing between positions. */
export const SPRING_LAYOUT = {
type: "spring",
stiffness: 360,
damping: 32,
mass: 0.6,
} as const;
/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */
export const SPRING_MOUSE = {
stiffness: 200,
damping: 15,
mass: 0.3,
} as const;
/** Dragged handles and fills (sliders) — critically damped `useSpring` config,
* so the value follows the pointer butterily and never rebounds off an end. */
export const SPRING_GLIDE = {
stiffness: 700,
damping: 50,
mass: 0.5,
} as const;
"use client";
import { 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";
},
}),
[],
);
}
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
// Shared touch primitives. iOS and iPadOS run their own gestures on top of the
// page — the long-press selection callout and the selection it drags in with
// it — and they win: once the platform claims a touch it cancels ours
// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own
// their gesture have to opt out.
//
// What the two classes below cover, precisely:
// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:
// it is not a property other engines have, so it is inert everywhere else.
// - `user-select: none` stops the long-press selection on every engine,
// Android included, and stops a drag from painting a selection under the
// cursor. It is inherited, so it reaches every descendant — which is why the
// two classes differ only in whether they apply it unconditionally.
// What neither covers:
// - Chrome for Android's long-press menu on a link or an image. No CSS
// suppresses it; a gesture surface that wraps one needs its own
// `onContextMenu` with `preventDefault()`.
// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is
// not inherited and plain divs and buttons are not drag sources, so setting
// it on the surface does nothing — the child itself needs `draggable={false}`.
/**
* Classes for a surface that *is* the control: a thumb, a drum, a stage, a
* handle, a hold button. Selection is suppressed on every input, because a
* drag that highlights the control's own label is wrong on a mouse too.
* Compose with `touch-none` when the surface also owns the scroll axis — leave
* it off when the page must still scroll from there.
*/
export const TOUCH_GESTURE_CLASS = "select-none [-webkit-touch-callout:none]";
/**
* The same opt-out for a gesture surface that wraps content the consumer owns:
* a scroller, a context-menu trigger, a sheet header, a list row. Selection is
* suppressed only where the platform runs its own press gestures — a coarse
* pointer — so a mouse user can still select and copy that content. If the
* gesture itself would paint a selection under the cursor, add `select-none`
* for the duration of the gesture rather than reaching for
* `TOUCH_GESTURE_CLASS`.
*
* `pointer: coarse` describes the *primary* pointer and nothing else, so a
* hybrid machine reads it wrong in both directions: a tablet with a mouse
* plugged in keeps touch as primary and loses mouse selection, and a laptop
* with a touchscreen keeps the mouse as primary and leaves selection live
* under a finger. No media query can answer per interaction — the query is
* about the device, and the question is about the gesture in progress. The
* default stays here because it is right on the machines that are one thing or
* the other, and losing a selection is a nuisance; where the miss costs a
* *gesture* instead, the surface pairs it with `holdSelection` on the press.
*/
export const TOUCH_GESTURE_CONTENT_CLASS =
"[-webkit-touch-callout:none] pointer-coarse:select-none";
/**
* Grow a small control's *hit area* to at least 44×44px (WCAG 2.5.5, Apple
* HIG) on a coarse pointer, without changing what it looks like or the space
* it takes in layout. An invisible `::after` box, centered on the control and
* `max(100%, 2.75rem)` on each axis, catches the taps: a 32px icon button
* reaches 6px past each edge, a wide 40px button only grows vertically, and a
* control already 44px or larger is left as it is. Hit-testing a pseudo
* element lands on its owner, so handlers, focus and `:active` all behave.
*
* Mouse and trackpad rendering is untouched — nothing here applies outside
* `pointer: coarse`. Requirements on the element it goes on:
* - It must be the containing block: add `relative` (and keep it mergeable, so
* a consumer's `absolute` still wins through `cn`).
* - It must not clip itself (`overflow-hidden`), or the overhang is clipped
* away along with its hit area.
* - It must render children: `<input>` and other void elements have no
* `::after`. Put it on the wrapper or label instead.
* - It must not already use `::after` for something visible.
*
* Centered 44px means two 32px buttons with a 4px gap overlap by 8px; the
* later one wins that strip, which still ends well short of the earlier
* button's visual center. Below a ~32px pitch the later neighbour starts
* eating into that center — use `TOUCH_TARGET_Y_CLASS` for such dense rows.
*
* The overhang is real geometry: inside a scroll container it counts as
* scrollable overflow, so a control flush against a scroller's edge can add a
* few pixels of scroll on touch screens. Give such a scroller a little padding
* on that side.
*/
export const TOUCH_TARGET_CLASS =
"pointer-coarse:after:absolute pointer-coarse:after:top-1/2 pointer-coarse:after:left-1/2 pointer-coarse:after:size-[max(100%,2.75rem)] pointer-coarse:after:-translate-x-1/2 pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']";
/**
* `TOUCH_TARGET_CLASS` on the vertical axis only, for controls packed tighter
* than ~32px apart in a row (pagination dots, dense swatches), where growing
* sideways would hand most of each control to its neighbour. Same rules.
*/
export const TOUCH_TARGET_Y_CLASS =
"pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:top-1/2 pointer-coarse:after:h-[max(100%,2.75rem)] pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']";
/**
* Suppress selection on `element` for as long as a gesture is running on it,
* whatever the primary pointer of the machine happens to be. Returns the
* release. Inline, so it wins over the class above and is gone again the
* moment the gesture ends.
*
* For the press gestures a native selection would otherwise steal — a
* long-press that opens a menu. Elsewhere prefer the classes: a surface that
* takes selection away for the whole session is a surface whose text nobody
* can copy.
*/
export function holdSelection(element: HTMLElement) {
element.style.setProperty("user-select", "none");
element.style.setProperty("-webkit-user-select", "none");
return () => {
element.style.removeProperty("user-select");
element.style.removeProperty("-webkit-user-select");
};
}
/**
* Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer
* is already gone by the time the handler runs — routine on iOS, where the
* system can claim the touch first — and an uncaught throw takes the rest of
* the handler, the gesture included, down with it. Touch pointers carry
* implicit capture anyway, so losing it is never fatal.
*/
export function capturePointer(element: Element, pointerId: number) {
try {
element.setPointerCapture(pointerId);
} catch {
// Pointer is no longer active — implicit capture still applies on touch.
}
}
/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */
export function releasePointer(element: Element, pointerId: number) {
try {
if (element.hasPointerCapture(pointerId)) {
element.releasePointerCapture(pointerId);
}
} catch {
// Capture was already dropped by the browser.
}
}
/**
* Whether this event came from a pointer that is *hovering*: not a touch, and
* not currently pressed. Which input the user is holding right now is not
* something a device capability can answer — a touchscreen laptop hovers and
* taps, and iPadOS reports a fine hovering pointer for a finger — so both
* paths stay live and each handler branches on the event it was given.
*
* A pen resting on the glass is making contact, not hovering: `buttons` is the
* tell, and it sends a pen tap down the same route a finger takes.
*
* This answers what an *enter* asks. A leave is the other half of a pair and
* has to be read against the enter that started it — `useHoverGesture` in
* `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it
* rather than asking this question twice.
*/
export const isHoveringPointer = (event: {
pointerType: string;
buttons: number;
}) => event.pointerType !== "touch" && event.buttons === 0;
Copy the source code
"use client";
// karaui.kamisama-v0.my.id/components/motion/hover-card
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
cloneElement,
createContext,
isValidElement,
type MutableRefObject,
type ReactElement,
type FocusEvent as ReactFocusEvent,
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_PANEL } from "@/lib/ease";
import { useHoverGesture } from "@/lib/hooks/use-hover-gesture";
import { cn } from "@/lib/utils";
interface HoverCardContextValue {
open: boolean;
contentId: string;
triggerRef: MutableRefObject<HTMLElement | null>;
contentRef: MutableRefObject<HTMLDivElement | null>;
/** Open after `openDelay` (or at once when `immediate`). */
scheduleOpen: (immediate?: boolean) => void;
/** Close after `closeDelay` — cancelled if the pointer comes back. */
scheduleClose: () => void;
cancel: () => void;
close: () => void;
reduce: boolean;
}
const HoverCardContext = createContext<HoverCardContextValue | null>(null);
function useHoverCardContext(component: string) {
const ctx = useContext(HoverCardContext);
if (!ctx) throw new Error(`${component} must be used within <HoverCard>`);
return ctx;
}
export interface HoverCardProps {
children: ReactNode;
/** Controlled open state. */
open?: boolean;
/** Uncontrolled initial open state. */
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
/** Hover time before the card opens, in ms. Default 500. */
openDelay?: number;
/** Time after the pointer leaves before the card closes, in ms. Default 300. */
closeDelay?: number;
className?: string;
}
/**
* A rich preview shown while the pointer rests on a trigger (usually a link).
*
* - Opens after `openDelay`, closes `closeDelay` after the pointer leaves both
* the trigger and the card, so the pointer can travel into the card.
* - Opens when the trigger receives keyboard focus; closes on Escape or blur.
* - Touch has no hover: a tap is just a tap and the trigger behaves as the
* link it is. The card is supplementary — never put the only path to an
* action inside it.
*/
export function HoverCard({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
openDelay = 500,
closeDelay = 300,
className,
}: HoverCardProps) {
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const controlled = controlledOpen !== undefined;
const open = controlled ? controlledOpen : internalOpen;
const triggerRef = useRef<HTMLElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const contentId = useId();
const reduce = useReducedMotion() ?? false;
const setOpen = useCallback(
(next: boolean) => {
if (!controlled) setInternalOpen(next);
onOpenChange?.(next);
},
[controlled, onOpenChange],
);
const cancel = useCallback(() => {
if (timer.current) clearTimeout(timer.current);
timer.current = null;
}, []);
const scheduleOpen = useCallback(
(immediate = false) => {
cancel();
if (open) return;
if (immediate) {
setOpen(true);
return;
}
timer.current = setTimeout(() => {
timer.current = null;
setOpen(true);
}, openDelay);
},
[cancel, open, openDelay, setOpen],
);
const scheduleClose = useCallback(() => {
cancel();
if (!open) return;
timer.current = setTimeout(() => {
timer.current = null;
setOpen(false);
}, closeDelay);
}, [cancel, closeDelay, open, setOpen]);
const close = useCallback(() => {
cancel();
setOpen(false);
}, [cancel, setOpen]);
useEffect(() => cancel, [cancel]);
useEffect(() => {
if (!open) return;
const onKey = (event: KeyboardEvent) => {
if (event.key === "Escape") close();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [open, close]);
const ctx = useMemo<HoverCardContextValue>(
() => ({
open,
contentId,
triggerRef,
contentRef,
scheduleOpen,
scheduleClose,
cancel,
close,
reduce,
}),
[open, contentId, scheduleOpen, scheduleClose, cancel, close, reduce],
);
return (
<HoverCardContext.Provider value={ctx}>
<span className={cn("inline-flex", className)}>{children}</span>
</HoverCardContext.Provider>
);
}
type TriggerChildProps = React.HTMLAttributes<HTMLElement> & {
ref?: Ref<HTMLElement>;
[key: `data-${string}`]: string | undefined;
};
export interface HoverCardTriggerProps {
/** A single focusable element, usually an `<a>`. Its own handlers still run. */
children: ReactElement<TriggerChildProps>;
className?: string;
}
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;
}
export function HoverCardTrigger({ children, className }: HoverCardTriggerProps) {
const ctx = useHoverCardContext("HoverCardTrigger");
const hover = useHoverGesture();
if (!isValidElement(children)) {
throw new Error("<HoverCardTrigger> requires a single React element");
}
const childProps = children.props;
const childRef = childProps.ref;
return cloneElement(children, {
ref: (node: HTMLElement | null) => {
ctx.triggerRef.current = node;
assignRef(childRef, node);
},
"data-state": ctx.open ? "open" : "closed",
className: cn(childProps.className, className),
// Pointer events, filtered through useHoverGesture: a finger never rests,
// so touch never schedules an open and the tap reaches the link intact.
onPointerEnter: (event: ReactPointerEvent<HTMLElement>) => {
childProps.onPointerEnter?.(event);
if (hover.enter(event)) ctx.scheduleOpen();
},
onPointerLeave: (event: ReactPointerEvent<HTMLElement>) => {
childProps.onPointerLeave?.(event);
if (hover.leave(event)) ctx.scheduleClose();
},
onFocus: (event: ReactFocusEvent<HTMLElement>) => {
childProps.onFocus?.(event);
// Only keyboard focus opens it; a click's focus is already a hover.
if (event.currentTarget.matches(":focus-visible")) ctx.scheduleOpen();
},
onBlur: (event: ReactFocusEvent<HTMLElement>) => {
childProps.onBlur?.(event);
const next = event.relatedTarget as Node | null;
if (next && ctx.contentRef.current?.contains(next)) return;
ctx.close();
},
});
}
export interface HoverCardContentProps {
children: ReactNode;
/** Preferred side; flips when the viewport lacks room. Default "bottom". */
side?: PlacementSide;
/** Default "center". */
align?: PlacementAlign;
/** Gap between trigger and card, in px. Default 8. */
sideOffset?: number;
alignOffset?: number;
className?: string;
}
// Distance the card travels in from the trigger side on entrance.
const ENTER_SHIFT = 6;
function shiftFor(side: PlacementSide) {
if (side === "bottom") return { x: 0, y: -ENTER_SHIFT };
if (side === "top") return { x: 0, y: ENTER_SHIFT };
if (side === "right") return { x: -ENTER_SHIFT, y: 0 };
return { x: ENTER_SHIFT, y: 0 };
}
export function HoverCardContent({
children,
side = "bottom",
align = "center",
sideOffset = 8,
alignOffset = 0,
className,
}: HoverCardContentProps) {
const ctx = useHoverCardContext("HoverCardContent");
const hover = useHoverGesture();
const [portalReady, setPortalReady] = useState(false);
const layout = usePopoverPortalPosition(
ctx.triggerRef,
ctx.contentRef,
portalReady && ctx.open,
);
useEffect(() => setPortalReady(true), []);
if (!portalReady) return null;
const placement = layout
? resolvePlacement(layout, { side, align, sideOffset, alignOffset })
: null;
// The requested side seeds the entrance offset: the first frame mounts
// before measurement, and a flip is the rare case.
const shift = shiftFor(side);
return createPortal(
<AnimatePresence>
{ctx.open ? (
<motion.div
ref={ctx.contentRef}
id={ctx.contentId}
data-side={placement?.side ?? side}
initial={
ctx.reduce
? { opacity: 0 }
: { opacity: 0, scale: 0.92, x: shift.x, y: shift.y }
}
animate={{ opacity: 1, scale: 1, x: 0, y: 0 }}
exit={
ctx.reduce
? { opacity: 0, transition: { duration: 0.1 } }
: {
opacity: 0,
scale: 0.96,
transition: { duration: 0.14, ease: EASE_OUT },
}
}
transition={
ctx.reduce
? { duration: 0.14, ease: EASE_OUT }
: { ...SPRING_PANEL, opacity: { duration: 0.18, ease: EASE_OUT } }
}
style={{
left: placement?.left ?? 0,
top: placement?.top ?? 0,
transformOrigin: placement?.origin ?? "50% 0%",
visibility: placement ? "visible" : "hidden",
}}
onPointerEnter={(event) => {
if (hover.enter(event)) ctx.cancel();
}}
onPointerLeave={(event) => {
if (hover.leave(event)) ctx.scheduleClose();
}}
onBlur={(event) => {
const next = event.relatedTarget as Node | null;
if (
next &&
(event.currentTarget.contains(next) ||
ctx.triggerRef.current?.contains(next))
)
return;
ctx.close();
}}
className={cn(
"fixed z-[100] w-72 rounded-2xl border border-border bg-card p-4 text-card-foreground shadow-[0_20px_44px_-14px_rgba(0,0,0,0.3)]",
className,
)}
>
{children}
</motion.div>
) : null}
</AnimatePresence>,
document.body,
);
}
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;
}
@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
HoverCard
open?booleanControlled open state.
—defaultOpen?booleanUncontrolled initial open state.
falseonOpenChange?((open: boolean) => void)—openDelay?numberHover time before the card opens, in ms. Default 500.
500closeDelay?numberTime after the pointer leaves before the card closes, in ms. Default 300.
300className?string—HoverCardTrigger
childrenReactElement<TriggerChildProps, string | JSXElementConstructor<any>>A single focusable element, usually an `<a>`. Its own handlers still run.
—className?string—HoverCardContent
side?"bottom" | "left" | "right" | "top"Preferred side; flips when the viewport lacks room. Default "bottom".
bottomalign?"end" | "start" | "center"Default "center".
centersideOffset?numberGap between trigger and card, in px. Default 8.
8alignOffset?number0className?string—Updated