Skip to content
Molecules

Popover

A panel that opens from its trigger and flips.

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 popover

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

  2. Or install the package

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

    $ pnpm add asta-ui
    import { Popover } from "asta-ui/popover";
  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,
      useEffect,
      useId,
      useLayoutEffect,
      useRef,
      useState,
      type KeyboardEvent,
      type MouseEvent,
      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-popover-in { from { opacity: 0; transform: translate(var(--asta-pop-x, 0), var(--asta-pop-y, 0)) scale(.94) } }
    @keyframes asta-popover-out { to { opacity: 0; transform: scale(.97) } }`;
    
    export type PopoverSide = "top" | "right" | "bottom" | "left";
    export type PopoverAlign = "start" | "center" | "end";
    
    /** Props to spread on your own trigger when you pass `trigger` as a function. */
    export interface PopoverTriggerProps {
      ref: (el: HTMLElement | null) => void;
      onClick: (e: MouseEvent<HTMLElement>) => void;
      "aria-haspopup": "dialog";
      "aria-expanded": boolean;
      "aria-controls": string | undefined;
      "data-state": "open" | "closed";
    }
    
    export interface PopoverProps {
      /** A focusable element (it gets the props merged in), or a function that receives the props to spread. */
      trigger: ReactElement | ((props: PopoverTriggerProps, open: boolean) => ReactNode);
      /** Panel content, or a function that gets `close`. */
      children: ReactNode | ((api: { close: () => void }) => ReactNode);
      open?: boolean;
      defaultOpen?: boolean;
      onOpenChange?: (open: boolean) => void;
      side?: PopoverSide;
      align?: PopoverAlign;
      /** Gap between trigger and panel, in px. */
      offset?: number;
      /** Draw a small arrow pointing at the trigger. */
      arrow?: boolean;
      /** Accessible name for the panel. */
      label?: string;
      /** Extra classes for the panel (padding, width). */
      className?: string;
    }
    
    const PAD = 8;
    
    // Keeps a ref the trigger already had working after we add ours.
    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;
    }
    const OPPOSITE: Record<PopoverSide, PopoverSide> = { top: "bottom", bottom: "top", left: "right", right: "left" };
    const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';
    
    /**
     * A click-to-open panel anchored to its trigger. Pick a side and an alignment; it flips when there is no
     * room and slides to stay on screen. It grows out of the trigger, closes on an outside click, Escape or
     * when focus leaves, and hands focus back to the trigger.
     */
    export function Popover({ trigger, children, open, defaultOpen = false, onOpenChange, side = "bottom", align = "center", offset = 8, arrow, label, className }: PopoverProps) {
      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 panel = useRef<HTMLDivElement>(null);
      const arrowEl = useRef<SVGSVGElement>(null);
    
      // Stay mounted while the close animation plays.
      if (isOpen && !present) setPresent(true);
    
      const setOpen = (next: boolean) => {
        if (next === isOpen) return;
        if (open === undefined) setInner(next);
        onOpenChange?.(next);
      };
      const close = (refocus = true) => {
        setOpen(false);
        if (refocus) anchor?.focus();
      };
    
      // Position: measure, pick the side (flip if needed), clamp to the viewport, write straight to the DOM.
      useLayoutEffect(() => {
        if (!present || !anchor) return;
        const place = () => {
          const el = panel.current;
          if (!el) return;
          const a = anchor.getBoundingClientRect();
          const w = el.offsetWidth;
          const h = el.offsetHeight;
          const vw = window.innerWidth;
          const vh = window.innerHeight;
          const room: Record<PopoverSide, number> = { top: a.top, bottom: vh - a.bottom, left: a.left, right: vw - a.right };
          const need = side === "top" || side === "bottom" ? h : w;
          let s = side;
          if (room[s] < need + offset + PAD && room[OPPOSITE[s]] > room[s]) s = OPPOSITE[s];
          const vertical = s === "top" || s === "bottom";
    
          let x: number;
          let y: number;
          if (vertical) {
            x = align === "start" ? a.left : align === "end" ? a.right - w : a.left + a.width / 2 - w / 2;
            y = s === "bottom" ? a.bottom + offset : a.top - offset - h;
            x = Math.min(Math.max(PAD, x), vw - w - PAD);
          } else {
            y = align === "start" ? a.top : align === "end" ? a.bottom - h : a.top + a.height / 2 - h / 2;
            x = s === "right" ? a.right + offset : a.left - offset - w;
            y = Math.min(Math.max(PAD, y), vh - h - PAD);
          }
    
          // Where the trigger's centre lands on the panel edge: the arrow points there and the panel grows from it.
          const along = vertical ? Math.min(Math.max(14, a.left + a.width / 2 - x), w - 14) : Math.min(Math.max(14, a.top + a.height / 2 - y), h - 14);
          const origin = vertical ? `${along}px ${s === "bottom" ? "0" : "100%"}` : `${s === "right" ? "0" : "100%"} ${along}px`;
          const nudge = { top: ["0", "4px"], bottom: ["0", "-4px"], left: ["4px", "0"], right: ["-4px", "0"] }[s];
    
          el.style.left = `${Math.round(x)}px`;
          el.style.top = `${Math.round(y)}px`;
          el.style.transformOrigin = origin;
          el.style.setProperty("--asta-pop-x", nudge[0]);
          el.style.setProperty("--asta-pop-y", nudge[1]);
          el.dataset.side = s;
    
          const ar = arrowEl.current;
          if (ar) {
            const rot = { bottom: 0, top: 180, left: 90, right: -90 }[s];
            ar.style.transform = `rotate(${rot}deg)`;
            // The arrow box is 14×7. Its base overlaps the panel edge by 1px to hide the ring under it.
            ar.style.left = vertical ? `${along - 7}px` : s === "right" ? "-9.5px" : `${w - 4.5}px`;
            ar.style.top = vertical ? (s === "bottom" ? "-6px" : `${h - 1}px`) : `${along - 3.5}px`;
          }
        };
        place();
        // Scroll and resize fire many times a frame: coalesce them into one place() per frame.
        let frame = 0;
        const schedule = () => {
          if (!frame)
            frame = requestAnimationFrame(() => {
              frame = 0;
              place();
            });
        };
        const ro = new ResizeObserver(schedule);
        ro.observe(panel.current!);
        window.addEventListener("resize", schedule);
        window.addEventListener("scroll", schedule, { capture: true, passive: true });
        return () => {
          cancelAnimationFrame(frame);
          ro.disconnect();
          window.removeEventListener("resize", schedule);
          window.removeEventListener("scroll", schedule, true);
        };
      }, [present, anchor, side, align, offset]);
    
      // Move focus in on open.
      useEffect(() => {
        if (!isOpen) return;
        const el = panel.current;
        if (!el) return;
        const first = el.querySelector<HTMLElement>("[data-autofocus]") ?? el.querySelector<HTMLElement>(FOCUSABLE);
        (first ?? el).focus({ preventScroll: true });
      }, [isOpen]);
    
      // Outside press closes. Focus stays where the press put it.
      useEffect(() => {
        if (!isOpen) return;
        const onDown = (e: PointerEvent) => {
          const t = e.target as Node;
          if (panel.current?.contains(t) || anchor?.contains(t)) return;
          if (open === undefined) setInner(false);
          onOpenChange?.(false);
        };
        document.addEventListener("pointerdown", onDown);
        return () => document.removeEventListener("pointerdown", onDown);
      }, [isOpen, anchor, open, onOpenChange]);
    
      const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
        if (e.key === "Escape") {
          e.stopPropagation();
          close();
          return;
        }
        if (e.key !== "Tab") return;
        // Not modal: tabbing past either end closes and goes back to the trigger.
        const items = [...panel.current!.querySelectorAll<HTMLElement>(FOCUSABLE)];
        const first = items[0];
        const last = items[items.length - 1];
        const at = document.activeElement;
        if (!items.length || (e.shiftKey && (at === first || at === panel.current)) || (!e.shiftKey && at === last)) {
          e.preventDefault();
          close();
        }
      };
    
      const triggerProps: PopoverTriggerProps = {
        ref: setAnchor,
        onClick: () => setOpen(!isOpen),
        "aria-haspopup": "dialog",
        "aria-expanded": isOpen,
        "aria-controls": present ? id : undefined,
        "data-state": isOpen ? "open" : "closed",
      };
    
      let triggerNode: ReactNode;
      if (typeof trigger === "function") triggerNode = trigger(triggerProps, isOpen);
      else if (isValidElement<{ onClick?: (e: MouseEvent<HTMLElement>) => void; ref?: Ref<HTMLElement> }>(trigger)) {
        const own = trigger.props;
        triggerNode = cloneElement(trigger, {
          ...triggerProps,
          ref: (el: HTMLElement | null) => {
            setAnchor(el);
            assignRef(own.ref, el);
          },
          onClick: (e: MouseEvent<HTMLElement>) => {
            own.onClick?.(e);
            if (!e.defaultPrevented) setOpen(!isOpen);
          },
        });
      }
    
      return (
        <>
          {triggerNode}
          {present &&
            typeof document !== "undefined" &&
            createPortal(
              <div
                ref={panel}
                id={id}
                role="dialog"
                aria-label={label}
                tabIndex={-1}
                data-state={isOpen ? "open" : "closed"}
                onKeyDown={onKey}
                onAnimationEnd={(e) => {
                  if (e.target === e.currentTarget && !isOpen) setPresent(false);
                }}
                className={cx(
                  "fixed left-0 top-0 z-50 w-max max-w-[calc(100vw-16px)] rounded-xl bg-paper p-3 text-ink outline-none",
                  "shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_10%,transparent),0_14px_36px_-14px_rgb(0_0_0/0.3),0_4px_10px_-6px_rgb(0_0_0/0.12)]",
                  "animate-[asta-popover-in_.24s_cubic-bezier(.16,1,.3,1)_both] data-[state=closed]:animate-[asta-popover-out_.12s_cubic-bezier(.16,1,.3,1)_both]",
                  "motion-reduce:![animation-duration:1ms]",
                  className,
                )}
              >
                <style href="asta-popover" precedence="asta">{KEYFRAMES}</style>
                {arrow && (
                  <svg ref={arrowEl} width="14" height="7" viewBox="0 0 14 7" aria-hidden className="pointer-events-none absolute" style={{ transformOrigin: "50% 50%" }}>
                    <path d="M0 7 7 .8 14 7z" className="fill-paper" />
                    <path d="M0 7 7 .8 14 7" fill="none" strokeWidth="1" style={{ stroke: "color-mix(in srgb, var(--color-ink) 12%, transparent)" }} />
                  </svg>
                )}
                {typeof children === "function" ? children({ close: () => close() }) : children}
              </div>,
              document.body,
            )}
        </>
      );
    }
    
    export default Popover;
    
  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 Popover component to my project.
    
    A panel that opens from its trigger and flips.
    It includes: placement, flip, arrow, outside click, focus return, render prop.
    
    Install it:
    ```sh
    pnpm dlx asta-ui@latest add popover --radix
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/popover.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 { Popover } from "@/components/astabyte/popover";
    ```
    
    Usage example and props: https://ui.astabyte.com/popover
    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.

    <!-- Opens with the native popovertarget attribute; asta.js positions it next to the trigger and places the arrow. -->
    <div style="display:flex;flex-wrap:wrap;gap:12px;align-items:center">
      <button class="asta-btn asta-btn-outline" popovertarget="ex-pop-one" aria-haspopup="dialog"><span class="asta-btn-label">Set reminder</span></button>
      <div id="ex-pop-one" popover="auto" role="dialog" tabindex="-1" data-asta-popover data-side="bottom" data-align="center" aria-label="Reminder" class="asta-float asta-popover" style="width:16rem">
        <svg class="asta-popover-arrow" data-asta-arrow width="14" height="7" viewBox="0 0 14 7" aria-hidden="true"><path d="M0 7 7 .8 14 7z"/><path d="M0 7 7 .8 14 7" stroke-width="1"/></svg>
        <p style="font-size:13px;font-weight:500">Remind me</p>
        <label class="asta-input asta-input-sm" style="margin-top:8px"><input class="asta-input-control" type="time" name="time" value="09:00"></label>
        <button class="asta-btn asta-btn-accent asta-btn-sm" style="margin-top:12px;width:100%" popovertarget="ex-pop-one" popovertargetaction="hide"><span class="asta-btn-label">Save</span></button>
      </div>
      <button class="asta-btn asta-btn-outline" popovertarget="ex-pop-two" aria-haspopup="dialog"><span class="asta-btn-label">Right side</span></button>
      <div id="ex-pop-two" popover="auto" role="dialog" tabindex="-1" data-asta-popover data-side="right" data-align="center" aria-label="Info" class="asta-float asta-popover">
        <svg class="asta-popover-arrow" data-asta-arrow width="14" height="7" viewBox="0 0 14 7" aria-hidden="true"><path d="M0 7 7 .8 14 7z"/><path d="M0 7 7 .8 14 7" stroke-width="1"/></svg>
        <p style="max-width:200px;font-size:13px;color:var(--ink-2)">Popovers flip when there is no room.</p>
      </div>
    </div>

Usage

The demo above, as code.

"use client";

import { useEffect, useRef, useState } from "react";
import { Popover } from "@/components/astabyte/popover";

const LINK = "https://docs.astabyte.com/q4-launch-plan";

const PEOPLE = [
  { name: "Ana Lindqvist", initials: "AL", role: "Product lead", team: "Launch team", docs: 42, since: "2023" },
  { name: "Kenji Moto", initials: "KM", role: "Designer", team: "Brand", docs: 18, since: "2024" },
];

const triggerBtn =
  "inline-flex h-9 items-center gap-1.5 rounded-lg px-3 text-[13px] font-medium outline-none transition-[background-color,transform] duration-200 active:scale-[0.97] focus-visible:ring-2 focus-visible:ring-brand/50";

function CopyField() {
  const [copied, setCopied] = useState(false);
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
  useEffect(() => () => clearTimeout(timer.current), []);

  const copy = () => {
    navigator.clipboard?.writeText(LINK).catch(() => {});
    setCopied(true);
    clearTimeout(timer.current);
    timer.current = setTimeout(() => setCopied(false), 1600);
  };

  return (
    <div className="flex h-9 items-center gap-1 rounded-lg bg-paper-2 pl-3 pr-1">
      <input readOnly value={LINK} aria-label="Share link" onFocus={(e) => e.currentTarget.select()} className="h-full min-w-0 flex-1 truncate bg-transparent text-[16px] sm:text-[12.5px] text-ink-2 outline-none" />
      <button
        type="button"
        data-autofocus
        onClick={copy}
        className="relative inline-flex h-7 w-[72px] items-center justify-center overflow-hidden rounded-md bg-paper text-[12.5px] font-medium text-ink outline-none shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_12%,transparent)] transition-transform duration-200 active:scale-95 focus-visible:ring-2 focus-visible:ring-brand/50"
      >
        <span className={`transition-[transform,opacity] duration-300 ease-[cubic-bezier(.16,1,.3,1)] ${copied ? "-translate-y-3 opacity-0" : ""}`}>Copy</span>
        <span className={`absolute inset-0 flex items-center justify-center gap-1 text-brand transition-[transform,opacity] duration-300 ease-[cubic-bezier(.16,1,.3,1)] ${copied ? "" : "translate-y-3 opacity-0"}`} aria-hidden={!copied}>
          <svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
            <path d="m5 12.5 4.5 4.5L19 7.5" />
          </svg>
          Copied
        </span>
      </button>
    </div>
  );
}

export default function PopoverDemo() {
  const [access, setAccess] = useState<"view" | "edit">("view");

  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-8">
        <div className="rounded-xl bg-paper-2 p-4 pl-5">
          <div className="flex items-center justify-between gap-3">
            <div className="min-w-0">
              <p className="truncate text-[14px] font-medium tracking-[-0.01em] text-ink">Q4 launch plan</p>
              <p className="mt-0.5 text-[12.5px] text-mute">Edited 4 minutes ago</p>
            </div>
            <Popover
              align="end"
              label="Share Q4 launch plan"
              className="w-[320px] p-4"
              trigger={
                <button type="button" className={`${triggerBtn} bg-ink text-paper hover:bg-[color-mix(in_srgb,var(--color-ink)_84%,var(--color-paper))] data-[state=open]:bg-[color-mix(in_srgb,var(--color-ink)_84%,var(--color-paper))]`}>
                  <svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="none" stroke="currentColor" strokeWidth="2.55" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
                    <path d="M8 9.5H6.5A1.5 1.5 0 0 0 5 11v8a1.5 1.5 0 0 0 1.5 1.5h11A1.5 1.5 0 0 0 19 19v-8a1.5 1.5 0 0 0-1.5-1.5H16" />
                    <path d="M12 14V3.5" />
                    <path d="M8.5 7 12 3.5 15.5 7" />
                  </svg>
                  Share
                </button>
              }
            >
              {({ close }) => (
                <div className="flex flex-col gap-3">
                  <div>
                    <p className="text-[14px] font-medium tracking-[-0.01em] text-ink">Share this doc</p>
                    <p className="mt-0.5 text-[12.5px] text-mute">Anyone with the link can {access}.</p>
                  </div>
                  <CopyField />
                  <div role="radiogroup" aria-label="Link access" className="grid grid-cols-2 gap-1 rounded-lg bg-paper-2 p-1">
                    {(["view", "edit"] as const).map((a) => (
                      <button
                        key={a}
                        type="button"
                        role="radio"
                        aria-checked={access === a}
                        onClick={() => setAccess(a)}
                        className={`h-7 rounded-md text-[12.5px] font-medium capitalize outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-brand/50 ${access === a ? "bg-paper text-ink shadow-[0_1px_2px_rgb(0_0_0/0.08)]" : "text-mute hover:text-ink"}`}
                      >
                        Can {a}
                      </button>
                    ))}
                  </div>
                  <button type="button" onClick={close} className="h-8 self-end rounded-md px-3 text-[12.5px] font-medium text-ink-2 outline-none transition-colors hover:bg-paper-2 hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50">
                    Done
                  </button>
                </div>
              )}
            </Popover>
          </div>
        </div>

        <div className="flex items-center justify-between gap-4 px-1">
          <p className="text-[14px] text-ink-2">Editors</p>
          <div className="flex items-center gap-1.5">
            {PEOPLE.map((p) => (
              <Popover
                key={p.name}
                side="top"
                arrow
                label={p.name}
                className="w-[248px] p-4"
                trigger={(props, open) => (
                  <button
                    {...props}
                    type="button"
                    aria-label={p.name}
                    className={`grid h-9 w-9 place-items-center rounded-full text-[12px] font-medium outline-none transition-[transform,background-color] duration-200 hover:scale-105 focus-visible:ring-2 focus-visible:ring-brand/50 focus-visible:ring-offset-2 focus-visible:ring-offset-paper ${open ? "bg-brand text-on-brand" : "bg-paper-2 text-ink"}`}
                  >
                    {p.initials}
                  </button>
                )}
              >
                <div className="flex items-center gap-3">
                  <span className="grid h-10 w-10 shrink-0 place-items-center rounded-full bg-brand text-[13px] font-medium text-on-brand">{p.initials}</span>
                  <div className="min-w-0">
                    <p className="truncate text-[14px] font-medium tracking-[-0.01em] text-ink">{p.name}</p>
                    <p className="truncate text-[12.5px] text-mute">
                      {p.role} · {p.team}
                    </p>
                  </div>
                </div>
                <div className="mt-3 grid grid-cols-2 gap-2 text-[12px]">
                  <div className="rounded-lg bg-paper-2 px-2.5 py-2">
                    <p className="text-mute">Docs</p>
                    <p className="mt-0.5 text-[14px] font-medium tabular-nums text-ink">{p.docs}</p>
                  </div>
                  <div className="rounded-lg bg-paper-2 px-2.5 py-2">
                    <p className="text-mute">Member since</p>
                    <p className="mt-0.5 text-[14px] font-medium tabular-nums text-ink">{p.since}</p>
                  </div>
                </div>
                <button type="button" className={`${triggerBtn} mt-3 h-8 w-full justify-center bg-ink text-paper hover:bg-[color-mix(in_srgb,var(--color-ink)_84%,var(--color-paper))]`}>
                  Message
                </button>
              </Popover>
            ))}
          </div>
        </div>

        <p className="text-center text-[12.5px] text-mute">Click Share or an avatar. Esc or a click outside closes it.</p>
      </div>
    </div>
  );
}