About
A popover that grows out of its trigger for rich details, like how full the context window is and a button to compact it.
Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Popover to your project and fits it to your theme.
Code
How Popover is used: the demo's code. The component's own source comes with a free account.
Usage.tsx
"use client"
import * as React from "react"
import { forwardRef, createElement, type SVGAttributes, type ForwardRefExoticComponent, type RefAttributes } from "react"
import { cn } from "@/lib/utils"
import { createPortal } from "react-dom"
import { Popover, PopoverClose, PopoverContent, PopoverDescription, PopoverTitle, PopoverTrigger } from "@/components/ui/popover"
interface GhostState {
x: number
y: number
shown: boolean
down: boolean
}
/**
* A pointer that walks a demo through its clicks, so a preview shows what each control does.
* `stage` is the positioned box the pointer moves in; targets are found inside it. Sizes come
* from layout boxes, so a scaled FitFrame never throws the aim off.
*/
function useGhost(stage: React.RefObject<HTMLElement | null>) {
const [ghost, setGhost] = React.useState<GhostState>({ x: 0, y: 0, shown: false, down: false })
const find = React.useCallback(
(target: string | HTMLElement) =>
typeof target === "string"
? stage.current?.querySelector<HTMLElement>(target) ?? null
: target,
[stage],
)
const moveTo = React.useCallback(
(target: string | HTMLElement, dx = 0.5, dy = 0.6) => {
const root = stage.current
const el = find(target)
if (!root || !el) return null
const rr = root.getBoundingClientRect()
const scale = root.offsetWidth ? rr.width / root.offsetWidth : 1
const er = el.getBoundingClientRect()
const x = (er.left - rr.left + er.width * dx) / scale
const y = (er.top - rr.top + er.height * dy) / scale
// A hidden pointer fades in a short way off its first target instead of flying in from
// wherever it was last.
setGhost((g) => (g.shown ? { x, y, shown: true, down: false } : { x: x + 70, y: y + 46, shown: false, down: false }))
window.requestAnimationFrame(() =>
window.requestAnimationFrame(() => setGhost({ x, y, shown: true, down: false })),
)
return el
},
[stage, find],
)
const press = React.useCallback((down: boolean) => setGhost((g) => ({ ...g, down })), [])
const hide = React.useCallback(() => setGhost((g) => ({ ...g, shown: false, down: false })), [])
return { ghost, moveTo, press, hide, find }
}
const FULL = 124_000
/**
* When the preview is themed by a `.dark` wrapper rather than the root element, carry the theme
* to the root so portalled menus match.
*/
function useRootTheme(stage: React.RefObject<HTMLElement | null>) {
React.useEffect(() => {
const html = document.documentElement
if (!stage.current?.closest(".dark") || html.classList.contains("dark")) return
html.classList.add("dark")
return () => html.classList.remove("dark")
}, [stage])
}
/**
* Menus render in a portal on the body, outside the scaled frame. A tour that opens one only
* runs when the frame shows the demo at full size; smaller frames (the phone, profile cards)
* show the still scene.
*/
const smallFrame = () => window.innerHeight < 400 || window.innerWidth < 640
const reducedMotion = () =>
typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches
const STOP = Symbol("stop")
/**
* Runs `script` in a loop with a `wait(ms)` that stops cleanly on unmount or once `active` turns
* false. Reduced motion never starts it.
*/
function useLoop(
script: (wait: (ms: number) => Promise<void>) => Promise<void>,
active = true,
) {
const ref = React.useRef(script)
ref.current = script
React.useEffect(() => {
if (!active || reducedMotion()) return
let alive = true
const timers = new Set<number>()
const wait = (ms: number) =>
new Promise<void>((resolve, reject) => {
const id = window.setTimeout(() => {
timers.delete(id)
if (alive) resolve()
else reject(STOP)
}, ms)
timers.add(id)
})
;(async () => {
try {
while (alive) await ref.current(wait)
} catch (error) {
if (error !== STOP) throw error
}
})()
return () => {
alive = false
for (const id of timers) window.clearTimeout(id)
}
}, [active])
}
/** A click the tour makes, through the same events a pointer sends. */
async function pointerClick(
g: ReturnType<typeof useGhost>,
el: HTMLElement | null,
wait: (ms: number) => Promise<void>,
scripted: React.RefObject<boolean>,
travel = 700,
) {
if (!el) return false
g.moveTo(el)
await wait(travel)
g.press(true)
await wait(130)
scripted.current = true
for (const type of ["pointerdown", "mousedown", "pointerup", "mouseup"]) {
const Ctor = type.startsWith("pointer") ? PointerEvent : MouseEvent
el.dispatchEvent(new Ctor(type, { bubbles: true, cancelable: true, button: 0 }))
}
el.click()
scripted.current = false
g.press(false)
return true
}
const COMPACTED = 36_000
const LIMIT = 200_000
const FIT_CSS = "html,body{overflow:hidden}[data-fit-small] [data-fit-hide]{display:none!important}"
/**
* 21st shows a demo in a small frame: about 674 by 421 on a component page, 358 by 224 on a
* phone and 245 by 139 on a profile card. A demo taller than its frame gets scrollbars, which
* render white on dark pages. FitFrame fills the frame exactly instead.
*
* - "scale": the content shrinks until it fits, centered. For visuals such as orbs.
* - "crop": the content stays at full size from the top and fades out at the bottom. For text
* that streams in, where a changing scale would make the page breathe.
*
* `minWidth` lays out a wide demo (a table, a two column panel) at that width and scales it down
* to the frame, instead of letting it collapse to a narrow layout. The frame centers it, so it
* shrinks evenly on both sides.
*
* Anything marked `data-fit-hide` (state buttons, the chatcn.dev line) drops out in frames
* shorter than `hideBelow`, so a profile card shows the visual alone.
*/
function FitFrame({
children,
mode = "scale",
hideBelow = 360,
minWidth,
}: {
children: React.ReactNode
mode?: "scale" | "crop"
hideBelow?: number
minWidth?: string
}) {
const content = React.useRef<HTMLDivElement>(null)
const [cropped, setCropped] = React.useState(false)
React.useLayoutEffect(() => {
const el = content.current
if (!el) return
const measure = () => {
const vw = window.innerWidth
const vh = window.innerHeight
el.toggleAttribute("data-fit-small", vh < hideBelow)
// Layout sizes ignore the transform, so measuring never feeds back.
const w = Math.max(el.offsetWidth, el.scrollWidth)
const h = Math.max(el.offsetHeight, el.scrollHeight)
const scale = mode === "scale" ? Math.min(1, vw / w, vh / h) : 1
el.style.transform = scale < 1 ? `scale(${scale})` : ""
setCropped(mode === "crop" && h > vh + 1)
}
measure()
const observer = new ResizeObserver(measure)
observer.observe(el)
// Content that changes inside a fixed width box (a headline that cycles words) never resizes
// the box itself, so changes below it measure again on the next frame.
let frame = 0
const mutations = new MutationObserver(() => {
cancelAnimationFrame(frame)
frame = requestAnimationFrame(measure)
})
mutations.observe(el, { subtree: true, childList: true, characterData: true })
window.addEventListener("resize", measure)
return () => {
observer.disconnect()
mutations.disconnect()
cancelAnimationFrame(frame)
window.removeEventListener("resize", measure)
}
}, [mode, hideBelow])
const fade = "linear-gradient(to bottom, #000 calc(100% - 40px), transparent)"
return (
<div
className="flex w-full justify-center overflow-hidden"
style={{
height: "100dvh",
alignItems: mode === "crop" ? "flex-start" : "center",
maskImage: cropped ? fade : undefined,
WebkitMaskImage: cropped ? fade : undefined,
}}
>
<style>{FIT_CSS}</style>
<div
ref={content}
className="w-full shrink-0"
style={{ transformOrigin: mode === "crop" ? "top center" : "center", minWidth }}
>
{children}
</div>
</div>
)
}
type ButtonVariant = "solid" | "outline" | "ghost" | "subtle"
type ButtonSize = "xs" | "sm" | "md" | "lg" | "icon-xs" | "icon-sm" | "icon-md" | "icon-lg"
interface ButtonProps extends React.ComponentProps<"button"> {
variant?: ButtonVariant
size?: ButtonSize
}
const base = cn(
"chatcn-focus inline-flex shrink-0 items-center justify-center gap-1.5 font-medium whitespace-nowrap select-none",
"ease-(--chatcn-ease-standard) transition-[background-color,color,box-shadow,scale] duration-150",
"active:scale-(--chatcn-press-scale) active:duration-100 disabled:pointer-events-none disabled:opacity-50",
"[&_svg]:pointer-events-none [&_svg]:shrink-0",
)
const variants: Record<ButtonVariant, string> = {
solid: "bg-(color:--chatcn-primary) text-(color:--chatcn-primary-fg) hover:bg-(color:--chatcn-primary-hover)",
outline: "bg-(color:--chatcn-card) text-(color:--chatcn-fg) shadow-(--chatcn-shadow-xs) hover:bg-(color:--chatcn-fill-hover)",
ghost: "text-(color:--chatcn-fg-muted) hover:bg-(color:--chatcn-fill-hover) hover:text-(color:--chatcn-fg)",
subtle: "bg-(color:--chatcn-fill) text-(color:--chatcn-fg) hover:bg-(color:--chatcn-fill-hover)",
}
// Heights follow the control scale: 24, 28, 32, 36. Radii stay concentric inside 12 px surfaces.
const sizes: Record<ButtonSize, string> = {
xs: "h-6 rounded-(--chatcn-radius-sm) px-2 text-[0.75rem]/[1rem] [&_svg]:size-3.5",
sm: "h-7 rounded-(--chatcn-radius-sm) px-2.5 text-[0.8125rem]/[1.25rem] [&_svg]:size-3.5",
md: "h-8 rounded-(--chatcn-radius-md) px-3 text-[0.875rem]/[1.25rem] tracking-[-0.003em] [&_svg]:size-4",
lg: "h-9 rounded-(--chatcn-radius-md) px-3.5 text-[0.875rem]/[1.25rem] tracking-[-0.003em] [&_svg]:size-4",
"icon-xs": "size-6 rounded-(--chatcn-radius-sm) active:scale-(--chatcn-press-scale-icon) [&_svg]:size-3.5",
"icon-sm": "size-7 rounded-(--chatcn-radius-sm) active:scale-(--chatcn-press-scale-icon) [&_svg]:size-3.5",
"icon-md": "size-8 rounded-(--chatcn-radius-md) active:scale-(--chatcn-press-scale-icon) [&_svg]:size-4",
"icon-lg": "size-9 rounded-(--chatcn-radius-md) active:scale-(--chatcn-press-scale-icon) [&_svg]:size-4",
}
/** Class names for anything that should look like a button, such as a link. */
function buttonVariants({
variant = "ghost",
size = "md",
}: {
variant?: ButtonVariant
size?: ButtonSize
} = {}) {
return cn(base, variants[variant], sizes[size])
}
function Button({
variant = "ghost",
size = "md",
type = "button",
className,
...props
}: ButtonProps) {
return (
<button
type={type}
data-slot="button"
data-variant={variant}
className={cn(buttonVariants({ variant, size }), className)}
{...props}
/>
)
}
interface IconProps extends SVGAttributes<SVGSVGElement> {
/** Width and height. Number means px. Default 24. */
size?: number | string
/** Stroke width in viewBox units (24 grid). Default 1.5. */
strokeWidth?: number | string
/** Keep the rendered stroke at `strokeWidth` px at any size. */
absoluteStrokeWidth?: boolean
/** Stroke color. Default currentColor. */
color?: string
/** Accessible name. Renders <title> and sets role="img"; without it the icon is aria-hidden. */
title?: string
}
type Icon = ForwardRefExoticComponent<IconProps & RefAttributes<SVGSVGElement>>
/** Shape elements an icon may contain. */
type IconElement = "path" | "circle" | "rect" | "ellipse" | "line" | "polyline" | "polygon"
/** An icon's drawing: a flat list of [element, attributes] pairs, lucide compatible. */
type IconNode = ReadonlyArray<readonly [IconElement, Readonly<Record<string, string>>]>
const toPascal = (name: string): string =>
name
.split("-")
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join("")
/**
* Builds a React icon component from an icon node.
* `name` is the kebab-case icon name, used for the class `chatcn-icon-<name>` and displayName.
*/
function createIcon(name: string, iconNode: IconNode): Icon {
// biome-ignore lint/correctness/noComponentHookFactories: runs once per icon at module load
const Component = forwardRef<SVGSVGElement, IconProps>(function ChatcnIcon(
{
size = 24,
strokeWidth = 1.5,
absoluteStrokeWidth = false,
color = "currentColor",
title,
className,
children,
...rest
},
ref,
) {
const stroke = absoluteStrokeWidth
? (Number(strokeWidth) * 24) / Number.parseFloat(String(size))
: strokeWidth
const labelled = Boolean(title || rest["aria-label"] || rest["aria-labelledby"])
return createElement(
"svg",
{
ref,
xmlns: "http://www.w3.org/2000/svg",
width: size,
height: size,
viewBox: "0 0 24 24",
fill: "none",
stroke: color,
strokeWidth: stroke,
strokeLinecap: "round",
strokeLinejoin: "round",
"data-slot": "icon",
className: className
? `chatcn-icon chatcn-icon-${name} ${className}`
: `chatcn-icon chatcn-icon-${name}`,
...(labelled ? { role: "img" } : { "aria-hidden": true }),
...rest,
},
title ? createElement("title", null, title) : null,
...iconNode.map(([tag, attrs], i) => createElement(tag, { key: i, ...attrs })),
children,
)
})
Component.displayName = `${toPascal(name)}Icon`
return Component
}
const iconNode: IconNode = [
["path", {"d":"m14.81 7.92-6.36 6.36a1.75 1.75 0 0 0 0 2.47 1.75 1.75 0 0 0 2.47 0l7.07-7.07a3.5 3.5 0 0 0 0-4.95 3.5 3.5 0 0 0-4.95 0L5.97 11.8a5.25 5.25 0 0 0 0 7.43 5.25 5.25 0 0 0 7.43 0l4.95-4.95"}],
]
const PaperclipIcon: Icon = /* @__PURE__ */ createIcon("paperclip", iconNode)
const iconNode2: IconNode = [
["path", {"d":"M7 4.5H6a3 3 0 0 0-3 3v9a3 3 0 0 0 3 3h1"}],
["path", {"d":"M17 4.5h1a3 3 0 0 1 3 3v9a3 3 0 0 1-3 3h-1"}],
["path", {"d":"M8 9h8"}],
["path", {"d":"M8 12h8"}],
["path", {"d":"M8 15h4.5"}],
]
const ContextWindowIcon: Icon = /* @__PURE__ */ createIcon("context-window", iconNode2)
const fmt = (n: number) => n.toLocaleString("en-US")
const iconNode3: IconNode = [
["path", {"d":"m18.5 11.5-4.73-4.73a2.5 2.5 0 0 0-3.54 0L5.5 11.5"}],
["path", {"d":"M12 19v-9"}],
]
const ArrowUpIcon: Icon = /* @__PURE__ */ createIcon("arrow-up", iconNode3)
/** The line under each 21st demo that points back to the kit. */
function MoreOn({ slug, children }: { slug: string; children: React.ReactNode }) {
return (
<p data-fit-hide className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-faint) text-center text-balance">
{children}{" "}
<a
href={`https://chatcn.dev/docs/components/${slug}`}
target="_blank"
rel="noopener"
className="text-(color:--chatcn-fg-subtle) hover:text-(color:--chatcn-fg) underline underline-offset-2"
>
chatcn.dev
</a>
</p>
)
}
/** The pointer itself. Put it last inside the stage, which must be `relative`. */
function Ghost({ ghost }: { ghost: GhostState }) {
return (
<div
aria-hidden
className="pointer-events-none absolute top-0 left-0 z-20"
style={{
transform: `translate(${ghost.x}px, ${ghost.y}px)`,
opacity: ghost.shown ? 1 : 0,
// Hidden, it jumps; shown, it glides.
transition: ghost.shown
? "transform 620ms cubic-bezier(0.4, 0, 0.2, 1), opacity 220ms ease-out"
: "opacity 220ms ease-out",
}}
>
<svg
width="18"
height="20"
viewBox="0 0 18 20"
className="drop-shadow-[0_1px_2px_rgb(0_0_0/0.25)]"
style={{
transform: ghost.down ? "scale(0.86)" : "scale(1)",
transformOrigin: "2px 2px",
transition: "transform 120ms ease-out",
}}
>
<path
d="M2 1.5 L2 16 L5.9 12.4 L8.6 18.3 L11.2 17.1 L8.6 11.3 L13.9 11.1 Z"
className="fill-[oklch(0.2_0_0)] stroke-white dark:fill-white dark:stroke-[oklch(0.2_0_0)]"
strokeWidth="1.3"
strokeLinejoin="round"
/>
</svg>
</div>
)
}
/** The pointer drawn above portalled menus, lined up with the stage on the page. */
function PortalGhost({
stage,
ghost,
}: {
stage: React.RefObject<HTMLElement | null>
ghost: ReturnType<typeof useGhost>["ghost"]
}) {
const [, rerender] = React.useState(0)
React.useEffect(() => {
rerender(1)
const on = () => rerender((n) => n + 1)
window.addEventListener("resize", on)
return () => window.removeEventListener("resize", on)
}, [])
const rect = stage.current?.getBoundingClientRect()
if (!rect || !stage.current) return null
const scale = stage.current.offsetWidth ? rect.width / stage.current.offsetWidth : 1
return createPortal(
<div
className="pointer-events-none fixed z-[60] origin-top-left"
style={{
left: rect.left,
top: rect.top,
width: stage.current.offsetWidth,
height: stage.current.offsetHeight,
transform: scale !== 1 ? `scale(${scale})` : undefined,
}}
>
<Ghost ghost={ghost} />
</div>,
document.body,
)
}
/**
* A long coding thread with the context popover in the composer. The pointer opens it, reads
* how full the window is, presses Compact now, and the meter drains as older tool output is
* summarized. The popover closes and the thread carries on. Loops. Click anything to stop the
* tour and try it yourself.
*/
export default function PopoverPreview() {
const stage = React.useRef<HTMLDivElement>(null)
const g = useGhost(stage)
const scripted = React.useRef(false)
const [touring, setTouring] = React.useState(true)
const [open, setOpen] = React.useState(false)
const [used, setUsed] = React.useState(FULL)
const [compacted, setCompacted] = React.useState(false)
useRootTheme(stage)
React.useEffect(() => {
if (smallFrame()) setTouring(false)
}, [])
useLoop(async (wait) => {
setUsed(FULL)
setCompacted(false)
await wait(1400)
await pointerClick(g, stage.current?.querySelector('[data-slot="popover-trigger"]') ?? null, wait, scripted)
await wait(1700)
const compact = document.querySelector<HTMLElement>('[data-slot="popover-content"] [data-demo="compact"]')
await pointerClick(g, compact, wait, scripted, 620)
// Older tool output folds into a summary; the meter drains as it goes.
for (let n = FULL; n > COMPACTED; n -= 4_000) {
setUsed(n)
await wait(28)
}
setUsed(COMPACTED)
setCompacted(true)
await wait(1800)
setOpen(false)
g.hide()
await wait(3600)
}, touring)
const pct = Math.round((used / LIMIT) * 100)
return (
<FitFrame minWidth="38rem">
<div className="flex w-full flex-col items-center justify-center gap-4 px-6 pt-5 pb-5">
<div
ref={stage}
className="relative flex h-[20.5rem] w-full max-w-xl flex-col justify-end gap-4"
onPointerDownCapture={() => {
if (scripted.current || !touring) return
setTouring(false)
g.hide()
}}
>
<div className="text-[0.9375rem]/[1.5rem] tracking-[-0.006em] text-(color:--chatcn-fg) flex flex-col gap-4">
<div className="flex justify-end">
<p className="bg-(color:--chatcn-fill) rounded-(--chatcn-radius-xl) px-4 py-2.5">Now port the retry logic to the webhook worker.</p>
</div>
<p className="text-pretty">
{compacted
? "Context compacted: the 31 earlier file reads and test runs are now a short summary. Porting the retry logic next."
: "On it. I have read 31 files and run the tests 9 times in this thread, so the context window is filling up."}
</p>
</div>
<div className="rounded-(--chatcn-radius-xl) bg-(color:--chatcn-card) shadow-(--chatcn-shadow-sm) flex flex-col gap-2 p-3">
<p className="text-[0.9375rem]/[1.5rem] tracking-[-0.006em] text-(color:--chatcn-fg-faint) px-1 pt-0.5">Ask a follow up</p>
<div className="flex items-center justify-between">
<div className="flex items-center gap-1">
<Button variant="ghost" size="icon-sm" aria-label="Attach">
<PaperclipIcon />
</Button>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger render={<Button variant="ghost" size="sm" />}>
<ContextWindowIcon />
Context
<span className="text-(color:--chatcn-fg-subtle) tabular-nums">{pct}%</span>
</PopoverTrigger>
<PopoverContent side="top" align="start" className="flex w-80 flex-col gap-3 p-3.5" initialFocus={false} finalFocus={false}>
<div className="flex flex-col gap-1">
<PopoverTitle>Context window</PopoverTitle>
<PopoverDescription>
{compacted
? `Compacted. ${fmt(used)} of ${fmt(LIMIT)} tokens used, with a summary of the earlier work kept in.`
: `${fmt(used)} of ${fmt(LIMIT)} tokens used. Older tool output is summarized first when the window fills.`}
</PopoverDescription>
</div>
<div className="bg-(color:--chatcn-fill) h-1.5 overflow-hidden rounded-full">
<div className="bg-(color:--chatcn-fg) h-full rounded-full" style={{ width: `${pct}%` }} />
</div>
<div className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle) flex justify-between tabular-nums">
<span>{pct}% used</span>
<span>{fmt(LIMIT - used)} left</span>
</div>
<div className="flex justify-end gap-1.5">
<PopoverClose render={<Button size="sm" variant="ghost" />}>Close</PopoverClose>
<Button size="sm" variant="solid" data-demo="compact" disabled={compacted} onClick={() => {
if (scripted.current) return
setUsed(COMPACTED)
setCompacted(true)
}}>
{compacted ? "Compacted" : "Compact now"}
</Button>
</div>
</PopoverContent>
</Popover>
</div>
<Button variant="solid" size="icon-sm" aria-label="Send" disabled>
<ArrowUpIcon />
</Button>
</div>
</div>
</div>
<MoreOn slug="popover">Popovers that grow out of their trigger, for rich details. On</MoreOn>
{touring ? <PortalGhost stage={stage} ghost={g.ghost} /> : null}
</div>
</FitFrame>
)
}
















