Skip to content
Molecules

Hover card

A preview card on hover or focus.

Installation

  1. Run the CLI

    Run pnpm dlx asta-ui@latest init once, then this. The file lands in components/astabyte/, installs react-dom and the colour tokens go into your CSS.

    $ pnpm dlx asta-ui@latest add hover-card

    Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/hover-card.json

  2. Or install the package

    Don’t want the file? Import from asta-ui/hover-card and update with pnpm update asta-ui. Add the stylesheet once. More.

    $ pnpm add asta-ui
    import { HoverCard } from "asta-ui/hover-card";
  3. Or copy it by hand

    Install react-dom, then copy this file. Keep the paths, or fix the @/ imports. Then add the tokens from globals.css.

    "use client";
    
    import {
      cloneElement,
      isValidElement,
      useCallback,
      useEffect,
      useId,
      useLayoutEffect,
      useRef,
      useState,
      type KeyboardEvent,
      type ReactElement,
      type ReactNode,
      type Ref,
    } from "react";
    import { createPortal } from "react-dom";
    
    const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
    
    const KEYFRAMES = `@keyframes asta-hovercard-in { from { opacity: 0; transform: translateY(var(--asta-hc-y, 6px)) scale(.98) } }
    @keyframes asta-hovercard-out { to { opacity: 0; transform: translateY(calc(var(--asta-hc-y, 6px) / 2)) } }`;
    
    export type HoverCardSide = "top" | "bottom";
    export type HoverCardAlign = "start" | "center" | "end";
    
    export interface HoverCardProps {
      /** A focusable element, usually a link. It gets the hover and focus handlers merged in. */
      trigger: ReactElement;
      /** Card content. */
      children: ReactNode;
      open?: boolean;
      defaultOpen?: boolean;
      onOpenChange?: (open: boolean) => void;
      /** Wait this long on hover or focus before opening, in ms. */
      openDelay?: number;
      /** Wait this long after the pointer leaves before closing, in ms. */
      closeDelay?: number;
      side?: HoverCardSide;
      align?: HoverCardAlign;
      /** Gap between the trigger and the card, in px. */
      offset?: number;
      /** Accessible name for the card. */
      label?: string;
      /** Extra classes for the card (width, padding). */
      className?: string;
    }
    
    const PAD = 8;
    const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';
    
    function assignRef(r: Ref<HTMLElement> | undefined, el: HTMLElement | null) {
      if (typeof r === "function") r(el);
      else if (r) (r as { current: HTMLElement | null }).current = el;
    }
    
    
    /**
     * A preview card for a link, like a profile peek. It opens after a short hover or on keyboard focus, and
     * stays open while the pointer travels into it, so you can use what's inside. It fades and lifts in, flips
     * when there's no room, and closes on leave, blur or Escape. Touch taps just follow the link.
     */
    export function HoverCard({ trigger, children, open, defaultOpen = false, onOpenChange, openDelay = 500, closeDelay = 220, side = "bottom", align = "center", offset = 8, label, className }: HoverCardProps) {
      const id = useId();
      const [inner, setInner] = useState(defaultOpen);
      const isOpen = open ?? inner;
      const [present, setPresent] = useState(isOpen);
      const [anchor, setAnchor] = useState<HTMLElement | null>(null);
      const card = useRef<HTMLDivElement>(null);
      const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
    
      if (isOpen && !present) setPresent(true);
    
      // The latest open state for timers and handlers that fire before the next render.
      const cur = useRef(isOpen);
      useLayoutEffect(() => {
        cur.current = isOpen;
      });
    
      const setOpen = (next: boolean) => {
        clearTimeout(timer.current);
        if (next === cur.current) return;
        if (open === undefined) {
          cur.current = next;
          setInner(next);
        }
        onOpenChange?.(next);
      };
      const later = (next: boolean) => {
        clearTimeout(timer.current);
        if (next === cur.current) return;
        timer.current = setTimeout(() => setOpen(next), next ? openDelay : closeDelay);
      };
      const hold = () => clearTimeout(timer.current);
      useEffect(() => () => clearTimeout(timer.current), []);
    
      // Position before paint: flip top/bottom if needed, clamp sideways, follow scroll and resize.
      useLayoutEffect(() => {
        if (!present || !anchor) return;
        const place = () => {
          const el = card.current;
          if (!el) return;
          const a = anchor.getBoundingClientRect();
          const w = el.offsetWidth;
          const h = el.offsetHeight;
          const vw = window.innerWidth;
          const vh = window.innerHeight;
          let s = side;
          const room = { top: a.top, bottom: vh - a.bottom };
          const other = s === "top" ? "bottom" : "top";
          if (room[s] < h + offset + PAD && room[other] > room[s]) s = other;
          let x = align === "start" ? a.left : align === "end" ? a.right - w : a.left + a.width / 2 - w / 2;
          x = Math.min(Math.max(PAD, x), vw - w - PAD);
          const y = s === "bottom" ? a.bottom + offset : a.top - offset - h;
          const ox = Math.min(Math.max(16, a.left + a.width / 2 - x), w - 16);
          el.style.left = `${Math.round(x)}px`;
          el.style.top = `${Math.round(y)}px`;
          el.style.transformOrigin = `${ox}px ${s === "bottom" ? "0" : "100%"}`;
          el.style.setProperty("--asta-hc-y", s === "bottom" ? "6px" : "-6px");
          el.style.setProperty("--asta-hc-gap", `${offset + 2}px`);
          el.dataset.side = s;
        };
        place();
        const ro = new ResizeObserver(place);
        ro.observe(card.current!);
        window.addEventListener("resize", place);
        window.addEventListener("scroll", place, true);
        return () => {
          ro.disconnect();
          window.removeEventListener("resize", place);
          window.removeEventListener("scroll", place, true);
        };
      }, [present, anchor, side, align, offset]);
    
      const focusables = () => [...(card.current?.querySelectorAll<HTMLElement>(FOCUSABLE) ?? [])];
    
      // Focus leaving both the trigger and the card closes it.
      const onBlurOut = (to: EventTarget | null) => {
        if (to instanceof Node && (anchor?.contains(to) || card.current?.contains(to))) return;
        later(false);
      };
    
      // Trigger listeners go on the DOM node, so they always see the latest state and the trigger's own
      // handlers stay untouched.
      const handlers = {
        enter: (e: globalThis.PointerEvent) => e.pointerType === "mouse" && later(true),
        leave: (e: globalThis.PointerEvent) => e.pointerType === "mouse" && later(false),
        // Keyboard focus only: a mouse click shouldn't pop the card a second time.
        focus: (e: globalThis.FocusEvent) => (e.currentTarget as HTMLElement).matches(":focus-visible") && later(true),
        blur: (e: globalThis.FocusEvent) => onBlurOut(e.relatedTarget),
        key: (e: globalThis.KeyboardEvent) => {
          if (e.key === "Escape" && cur.current) {
            e.stopPropagation();
            setOpen(false);
          }
          // The card is portalled: Tab from the trigger steps into it when it has something to focus.
          if (e.key === "Tab" && !e.shiftKey && cur.current) {
            const first = focusables()[0];
            if (first) {
              e.preventDefault();
              hold();
              first.focus();
            }
          }
        },
      };
      const latest = useRef(handlers);
      useLayoutEffect(() => {
        latest.current = handlers;
      });
      useEffect(() => {
        if (!anchor) return;
        const on: [string, (e: never) => void][] = [
          ["pointerenter", (e: globalThis.PointerEvent) => latest.current.enter(e)],
          ["pointerleave", (e: globalThis.PointerEvent) => latest.current.leave(e)],
          ["focus", (e: globalThis.FocusEvent) => latest.current.focus(e)],
          ["blur", (e: globalThis.FocusEvent) => latest.current.blur(e)],
          ["keydown", (e: globalThis.KeyboardEvent) => latest.current.key(e)],
        ];
        for (const [t, f] of on) anchor.addEventListener(t, f as EventListener);
        return () => {
          for (const [t, f] of on) anchor.removeEventListener(t, f as EventListener);
        };
      }, [anchor]);
    
      // A stable ref callback: a new one each render would detach and re-attach the trigger every time.
      const triggerRef = isValidElement<{ ref?: Ref<HTMLElement> }>(trigger) ? trigger.props.ref : undefined;
      const setTriggerRef = useCallback(
        (el: HTMLElement | null) => {
          setAnchor(el);
          assignRef(triggerRef, el);
        },
        [triggerRef],
      );
      const triggerNode = isValidElement<{ ref?: Ref<HTMLElement> }>(trigger)
        ? cloneElement(trigger, {
            ref: setTriggerRef,
            "aria-describedby": isOpen ? id : undefined,
            "data-state": isOpen ? "open" : "closed",
          } as Record<string, unknown>)
        : trigger;
    
      const onCardKey = (e: KeyboardEvent<HTMLDivElement>) => {
        if (e.key === "Escape") {
          e.stopPropagation();
          setOpen(false);
          anchor?.focus({ preventScroll: true });
          return;
        }
        if (e.key !== "Tab") return;
        const items = focusables();
        const at = document.activeElement;
        if (e.shiftKey && at === items[0]) {
          e.preventDefault();
          anchor?.focus({ preventScroll: true });
        } else if (!e.shiftKey && at === items[items.length - 1]) {
          // Hand focus back to the trigger and let the browser's own Tab carry on to whatever follows it.
          setOpen(false);
          anchor?.focus({ preventScroll: true });
        }
      };
    
      return (
        <>
          {triggerNode}
          {present &&
            typeof document !== "undefined" &&
            createPortal(
              <div
                ref={card}
                id={id}
                role="dialog"
                aria-modal="false"
                aria-label={label}
                data-state={isOpen ? "open" : "closed"}
                onPointerEnter={(e) => {
                  if (e.pointerType === "mouse") hold();
                }}
                onPointerLeave={(e) => {
                  if (e.pointerType === "mouse") later(false);
                }}
                onFocus={hold}
                onBlur={(e) => onBlurOut(e.relatedTarget)}
                onKeyDown={onCardKey}
                onAnimationEnd={(e) => {
                  if (e.target === e.currentTarget && !isOpen) setPresent(false);
                }}
                className={cx(
                  "fixed left-0 top-0 z-50 w-[300px] max-w-[calc(100vw-16px)] rounded-xl bg-paper p-4 text-ink outline-none",
                  "shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_10%,transparent),0_18px_44px_-16px_rgb(0_0_0/0.32),0_4px_10px_-6px_rgb(0_0_0/0.12)]",
                  // An invisible bridge over the gap, so the pointer can cross from the link without the card closing.
                  "before:absolute before:inset-x-0 before:h-[var(--asta-hc-gap,10px)] before:content-[''] data-[side=bottom]:before:bottom-full data-[side=top]:before:top-full",
                  "animate-[asta-hovercard-in_.28s_cubic-bezier(.16,1,.3,1)_both] data-[state=closed]:animate-[asta-hovercard-out_.14s_cubic-bezier(.16,1,.3,1)_both]",
                  "data-[state=closed]:pointer-events-none motion-reduce:![animation-duration:1ms]",
                  className,
                )}
              >
                <style href="asta-hover-card" precedence="asta">
                  {KEYFRAMES}
                </style>
                {children}
              </div>,
              document.body,
            )}
        </>
      );
    }
    
    export default HoverCard;
    
  4. Or ask your AI agent

    Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.

    Add the Astabyte UI Hover card component to my project.
    
    A preview card on hover or focus.
    It includes: open/close delay, safe travel, keyboard focus, flip, Escape.
    
    Install it:
    ```sh
    pnpm dlx asta-ui@latest add hover-card --radix
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/hover-card.json
    ```
    If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4).
    
    Import it like this:
    ```tsx
    import { HoverCard } from "@/components/astabyte/hover-card";
    ```
    
    Usage example and props: https://ui.astabyte.com/hover-card
    Full catalogue for context: https://ui.astabyte.com/llms.txt
    
    Rules:
    - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS.
    - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback.
    - Keep keyboard, focus and ARIA behaviour.
    - Use fake data and fake brand names in examples.
    
    Use it to: [describe where it goes and what it should do]
  5. Or use plain HTML + CSS

    Not on React? Use it from Django, Rails, Laravel, Go html/template, htmx or a static page. Load asta.css and asta.js once (the head.html tab), then paste the markup. The ui.astabyte.com/cdn link is temporary: pin a version from jsDelivr for production. More in HTML + CSS.

    <!-- Needs asta.js: opens on hover/focus of the data-asta-hovercard-for link and positions the card. -->
    <div>
      <p style="font-size:14px;color:var(--ink-2)">Built by <a href="#hover-card" data-asta-hovercard-for="ex-hc-one" style="font-weight:500;color:var(--ink);text-decoration:underline;text-underline-offset:4px">@astabyte</a> in Jakarta.</p>
      <div id="ex-hc-one" popover="manual" role="dialog" aria-modal="false" data-asta-hovercard data-side="bottom" data-align="center" aria-label="Astabyte" class="asta-float asta-lift asta-hover-card">
        <div style="display:flex;gap:12px">
          <span class="asta-avatar" role="img" aria-label="Astabyte"><span class="asta-avatar-face">A</span></span>
          <div style="min-width:0"><p style="font-size:14px;font-weight:500">Astabyte</p><p style="font-size:12.5px;color:var(--mute)">@astabyte</p><p style="margin-top:8px;font-size:13px;color:var(--ink-2)">A small studio making web apps and the kit behind them.</p></div>
        </div>
      </div>
    </div>

Usage

The demo above, as code.

"use client";

import { HoverCard } from "@/components/astabyte/hover-card";

const PEOPLE = {
  maya: { name: "Maya Lindqvist", handle: "maya", initials: "ML", bio: "Design systems at Astabyte. Writes about type, spacing and calm interfaces.", following: 182, followers: "4.1k" },
  jonah: { name: "Jonah Reyes", handle: "jonah", initials: "JR", bio: "Frontend engineer. Motion, accessibility and fast pages.", following: 96, followers: "1.8k" },
};

const link = "rounded-sm font-medium text-ink underline decoration-[color-mix(in_srgb,var(--color-ink)_30%,transparent)] underline-offset-4 outline-none transition-[text-decoration-color] duration-200 hover:decoration-brand focus-visible:ring-2 focus-visible:ring-brand/50 data-[state=open]:decoration-brand";

function Profile({ p }: { p: (typeof PEOPLE)["maya"] }) {
  return (
    <div className="flex flex-col gap-3">
      <div className="flex items-center gap-3">
        <span className="grid h-11 w-11 shrink-0 place-items-center rounded-full bg-brand text-[13px] font-medium text-on-brand">{p.initials}</span>
        <div className="min-w-0 flex-1">
          <p className="truncate text-[14px] font-medium tracking-[-0.01em] text-ink">{p.name}</p>
          <p className="truncate text-[12.5px] text-mute">@{p.handle}</p>
        </div>
        <button type="button" className="h-8 shrink-0 rounded-lg bg-ink px-3 text-[12.5px] font-medium text-paper outline-none transition-transform duration-200 active:scale-[0.97] focus-visible:ring-2 focus-visible:ring-brand/50">
          Follow
        </button>
      </div>
      <p className="text-[13px] leading-relaxed text-ink-2">{p.bio}</p>
      <p className="flex gap-4 text-[12.5px] text-mute">
        <span>
          <span className="font-medium tabular-nums text-ink">{p.following}</span> following
        </span>
        <span>
          <span className="font-medium tabular-nums text-ink">{p.followers}</span> followers
        </span>
      </p>
    </div>
  );
}

export default function HoverCardDemo() {
  return (
    <div className="flex min-h-[420px] w-full items-center justify-center p-6 sm:p-10">
      <div className="flex w-full max-w-md flex-col gap-6">
        <div className="rounded-xl bg-paper-2 p-5">
          <p className="text-[12px] text-mute">Changelog · v2.4</p>
          <p className="mt-2 text-[14.5px] leading-relaxed text-ink-2">
            New spacing scale and calmer focus rings, designed by{" "}
            <HoverCard label={PEOPLE.maya.name} trigger={<a href="#maya" onClick={(e) => e.preventDefault()} className={link}>@maya</a>}>
              <Profile p={PEOPLE.maya} />
            </HoverCard>{" "}
            and shipped by{" "}
            <HoverCard label={PEOPLE.jonah.name} side="top" trigger={<a href="#jonah" onClick={(e) => e.preventDefault()} className={link}>@jonah</a>}>
              <Profile p={PEOPLE.jonah} />
            </HoverCard>
            .
          </p>
        </div>
        <p className="text-center text-[12.5px] text-mute">Hover a name, or Tab to it. Move into the card to use it.</p>
      </div>
    </div>
  );
}