About
An export menu for a conversation: copy as Markdown, download Markdown or JSON with live file sizes, include reasoning, and a share link.
Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Export Menu to your project and fits it to your theme.
Code
How Export Menu 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 { createPortal } from "react-dom"
import { ChatcnMessage, ExportFormat, ExportMenu } from "@/components/ui/export-menu"
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 }
}
/**
* The menu renders in a portal on the body, outside the scaled frame, so the tour only runs in
* frames that show the demo at full size. Smaller frames (the phone, profile cards) stay still.
*/
const smallFrame = () => window.innerHeight < 400 || window.innerWidth < 640
const TITLE = "Fix the webhook retry storm"
const MESSAGE_ONE = "Webhook retries are flooding the billing service. Can you check the retry policy?"
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])
}
/** 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>
)
}
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>
)
}
/** A short debugging thread with reasoning, so Include reasoning changes what gets exported. */
const MESSAGES: ChatcnMessage[] = [
{
id: "m1",
role: "user",
parts: [{ type: "text", text: "Webhook retries are flooding the billing service. Can you check the retry policy?" }],
},
{
id: "m2",
role: "assistant",
parts: [
{
type: "reasoning",
text: "A constant delay would line every retry up at the same moment during an outage. Read the queue config before suggesting a change, then check how many attempts are allowed and what happens after the last one.",
},
{
type: "text",
text: "Retries wait a fixed 5 s, so every failed event fires again at the same moment. I switched them to exponential backoff with jitter, capped at 10 minutes, and events now move to the dead letter queue after 8 attempts.",
},
],
},
]
const LINK = "https://chat.quarry.dev/s/7f3k2q"
/** 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>
)
}
/**
* A chat header with Export. The pointer opens the menu, turns on Include reasoning (the file
* sizes recount), copies the thread as Markdown, then comes back for a share link. What each
* export wrote shows under the thread. Loops. Click anything to stop the tour and try it.
*/
export default function ExportMenuPreview() {
const stage = React.useRef<HTMLDivElement>(null)
const g = useGhost(stage)
// A still frame (the phone, profile cards) shows the result of a copy instead of the tour.
const [still] = React.useState(() => typeof window !== "undefined" && smallFrame())
const [touring, setTouring] = React.useState(!still)
const [mounted, setMounted] = React.useState(false)
const [last, setLast] = React.useState<{ format: ExportFormat; content: string } | undefined>(() =>
still ? { format: "copy-markdown", content: `# ${TITLE}\n**You**\n${MESSAGE_ONE}` } : undefined,
)
const [reasoning, setReasoning] = React.useState(still)
const [run, setRun] = React.useState(0)
const scripted = React.useRef(false)
React.useEffect(() => {
setMounted(true)
}, [])
// The menu lives in a portal. When the preview is themed by a `.dark` wrapper rather than the
// root element, carry the theme to the root so the menu matches.
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")
}, [])
// Embedded previews often block the clipboard. The tour's copies land in the panel below, so
// they never depend on it; a visitor's own clicks use the real clipboard.
React.useEffect(() => {
const clip = navigator.clipboard
if (!clip) {
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: { writeText: async () => {} },
})
return
}
const real = clip.writeText.bind(clip)
clip.writeText = async (text: string) => {
if (scripted.current || touringRef.current) return
return real(text)
}
return () => {
clip.writeText = real
}
}, [])
const touringRef = React.useRef(touring)
touringRef.current = touring
/** A click the tour makes, through the same events a pointer sends. */
const click = async (el: HTMLElement | null, wait: (ms: number) => Promise<void>) => {
if (!el) return
g.moveTo(el)
await wait(700)
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)
}
const item = (selector: string) => document.querySelector<HTMLElement>(`[data-slot="menu-content"] ${selector}`)
const trigger = () => stage.current?.querySelector<HTMLElement>("[data-export-trigger] button") ?? null
useLoop(async (wait) => {
setLast(undefined)
setReasoning(false)
setRun((n) => n + 1)
await wait(1400)
await click(trigger(), wait)
await wait(1000)
await click(item('[role="menuitemcheckbox"]'), wait)
await wait(1200)
await click(item('[data-export-format="copy-markdown"]'), wait)
await wait(1100)
;(document.activeElement as HTMLElement | null)?.blur()
g.hide()
await wait(2600)
await click(trigger(), wait)
await wait(900)
await click(item('[data-export-format="copy-link"]'), wait)
await wait(1900)
;(document.activeElement as HTMLElement | null)?.blur()
g.hide()
await wait(2800)
}, touring)
// The pointer sits above the portalled menu, lined up with the stage on the page.
const rect = mounted ? stage.current?.getBoundingClientRect() : undefined
const pointer = rect
? createPortal(
<div
className="pointer-events-none fixed z-[60]"
style={{ left: rect.left, top: rect.top, width: rect.width, height: rect.height }}
>
<Ghost ghost={g.ghost} />
</div>,
document.body,
)
: null
const preview =
last?.format === "copy-link"
? last.content
: last
? last.content.split("\n").filter(Boolean).slice(0, 3).join("\n")
: ""
return (
<FitFrame minWidth="36rem">
<div className="flex h-[26.25rem] w-full flex-col items-center justify-start gap-4 px-6 pt-5 pb-4">
<div
ref={stage}
className="relative flex w-full max-w-xl flex-1 flex-col gap-4"
onPointerDownCapture={() => {
if (scripted.current || !touring) return
setTouring(false)
g.hide()
}}
>
<div className="border-(color:--chatcn-border) flex h-12 items-center gap-3 border-b">
<h3 className="text-[0.9375rem]/[1.5rem] tracking-[-0.006em] text-(color:--chatcn-fg) min-w-0 flex-1 truncate font-medium">{TITLE}</h3>
<span data-export-trigger>
<ExportMenu
key={run}
messages={MESSAGES}
title={TITLE}
includeReasoning={reasoning}
onIncludeReasoningChange={setReasoning}
formats={["copy-markdown", "download-markdown", "download-json", "copy-link"]}
onCreateLink={() => new Promise<string>((resolve) => setTimeout(() => resolve(LINK), 900))}
onPrint={() => {}}
onExport={(format, content) => setLast({ format, content })}
/>
</span>
</div>
<div className="flex justify-end">
<p className="bg-(color:--chatcn-fill) rounded-(--chatcn-radius-xl) text-[0.875rem]/[1.25rem] tracking-[-0.003em] text-(color:--chatcn-fg) max-w-[26rem] px-4 py-2.5">
Webhook retries are flooding the billing service. Can you check the retry policy?
</p>
</div>
<p className="text-[0.875rem]/[1.25rem] tracking-[-0.003em] text-(color:--chatcn-fg)">
Retries wait a fixed 5 s, so every failed event fires again at the same moment. They now back off
with jitter up to 10 minutes and move to the dead letter queue after 8 attempts.
</p>
<div
className="border-(color:--chatcn-border) rounded-(--chatcn-radius-lg) bg-(color:--chatcn-card) mt-auto flex h-[6.75rem] flex-col gap-1.5 border px-3.5 py-2.5 transition-opacity duration-300"
style={{ opacity: last ? 1 : 0.55 }}
>
<p className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle)">
{last?.format === "copy-link"
? "Share link copied"
: last
? `Copied as Markdown${reasoning ? ", with reasoning" : ""}`
: "What an export writes shows here"}
</p>
<pre
key={last?.format ?? "none"}
className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-muted) font-mono min-h-0 flex-1 overflow-hidden leading-[1.45] whitespace-pre-wrap [mask-image:linear-gradient(to_bottom,black_65%,transparent)] transition-opacity duration-300 starting:opacity-0"
>
{preview}
</pre>
</div>
</div>
<MoreOn slug="export-menu">Copy, download or share a whole conversation, with sizes. On</MoreOn>
{pointer}
</div>
</FitFrame>
)
}
















