About
A side panel for code and documents an assistant writes: streaming code with a line count, a sandboxed live preview and versions.
Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Artifact Panel to your project and fits it to your theme.
Code
How Artifact Panel 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 { ArtifactPanel, ArtifactVersion } from "@/components/ui/artifact-panel"
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 }
}
/** Moves to a target, presses and clicks it. Returns the element, or null if it is gone. */
async function tap(
g: ReturnType<typeof useGhost>,
target: string | HTMLElement,
wait: (ms: number) => Promise<void>,
travel = 700,
) {
if (!g.moveTo(target)) return null
await wait(travel)
g.press(true)
await wait(130)
const el = g.find(target)
el?.click()
g.press(false)
return el
}
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])
}
const head = (scheme: string) => `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<style>
:root { color-scheme: ${scheme}; font-family: system-ui, sans-serif; }
body { margin: 0; background: Canvas; color: CanvasText; }
main { max-width: 460px; margin: 18px auto; padding: 0 24px; }
h1 { font-size: 18px; margin: 0 0 4px; letter-spacing: -0.01em; }
p { margin: 0; font-size: 13px; opacity: 0.6; }
ul { list-style: none; padding: 0; margin: 14px 0 0; }
li { padding: 8px 0; font-size: 14px; border-top: 1px solid color-mix(in oklab, CanvasText 12%, Canvas); }
.row { display: flex; justify-content: space-between; }
span { opacity: 0.6; font-variant-numeric: tabular-nums; }`
const page1 = (scheme: string) => `${head(scheme)}
</style>
</head>
<body>
<main>
<h1>All systems normal</h1>
<p>Checked a moment ago</p>
<ul>
<li class="row">API <span>99.98%</span></li>
<li class="row">Run queue <span>99.91%</span></li>
<li class="row">Dashboard <span>100%</span></li>
</ul>
</main>
</body>
</html>
`
const page2 = (scheme: string) => `${head(scheme)}
h1::before { content: ""; display: inline-block; width: 9px; height: 9px; margin: 0 8px 2px 0;
border-radius: 50%; background: #30a46c; }
.bars { display: flex; gap: 2px; margin-top: 6px; }
.bars i { flex: 1; height: 12px; border-radius: 2px; background: #30a46c; }
.bars i.slow { background: #e2a336; }
</style>
</head>
<body>
<main>
<h1>All systems normal</h1>
<p>Last 30 days, checked a moment ago</p>
<ul>
<li><div class="row">API <span>99.98%</span></div><div class="bars" data-slow="21"></div></li>
<li><div class="row">Run queue <span>99.91%</span></div><div class="bars" data-slow="8"></div></li>
<li><div class="row">Dashboard <span>100%</span></div><div class="bars"></div></li>
</ul>
</main>
<script>
for (const bars of document.querySelectorAll(".bars")) {
for (let day = 0; day < 30; day++) {
const bar = document.createElement("i")
if (bars.dataset.slow == day) bar.className = "slow"
bars.append(bar)
}
}
</script>
</body>
</html>
`
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>
)
}
/** 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 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>
)
}
/**
* An HTML artifact in the side panel: a status page an agent writes. The code streams in with
* a line count, then the panel flips to the live preview in a sandboxed frame. The pointer peeks
* at the code, then version 2 streams in with 30 day uptime bars and lands as its own version.
* Loops. Click anything to stop the tour and use the panel yourself.
*/
export default function ArtifactPanelPreview() {
const stage = React.useRef<HTMLDivElement>(null)
const g = useGhost(stage)
const [touring, setTouring] = React.useState(true)
const scripted = React.useRef(false)
// The page the agent writes matches the preview's theme, light or dark.
const scheme = () =>
stage.current?.closest(".dark") || document.documentElement.classList.contains("dark") ? "dark" : "light"
const [content, setContent] = React.useState("")
const [streaming, setStreaming] = React.useState(false)
const [versions, setVersions] = React.useState<ArtifactVersion[]>([])
const [version, setVersion] = React.useState<string>()
const [view, setView] = React.useState<"code" | "preview">("preview")
const stream = async (text: string, wait: (ms: number) => Promise<void>) => {
const lines = text.split("\n")
setStreaming(true)
setView("code")
for (let i = 1; i <= lines.length; i += 1) {
setContent(lines.slice(0, i).join("\n"))
await wait(52)
}
setContent(text)
setStreaming(false)
}
const click = async (selector: string, wait: (ms: number) => Promise<void>) => {
scripted.current = true
await tap(g, selector, wait)
scripted.current = false
}
useLoop(async (wait) => {
const V1 = page1(scheme())
const V2 = page2(scheme())
setVersions([])
setVersion(undefined)
setContent("")
await wait(500)
await stream(V1, wait)
const v1 = { id: "v1", label: "Status page", createdAt: Date.now() - 6 * 60_000, content: V1 }
setVersions([v1])
setVersion("v1")
setView("preview")
await wait(2200)
// Peek at the code, then back to the preview.
await click('[data-slot="artifact-view-toggle"] [role="tab"]:first-child', wait)
await wait(1600)
await click('[data-slot="artifact-view-toggle"] [role="tab"]:last-child', wait)
await wait(700)
g.hide()
await wait(900)
// Version 2: uptime bars.
await stream(V2, wait)
setVersions([v1, { id: "v2", label: "Uptime bars", createdAt: Date.now(), content: V2 }])
setVersion("v2")
setView("preview")
await wait(3600)
}, touring)
const current = versions.find((v) => v.id === version)
return (
<FitFrame minWidth="38rem">
<div className="flex w-full flex-col items-center justify-center gap-4 p-6">
<div
ref={stage}
className="rounded-(--chatcn-radius-xl) shadow-(--chatcn-shadow-border) relative h-[22.5rem] w-full max-w-xl overflow-hidden"
onPointerDownCapture={() => {
if (scripted.current || !touring) return
setTouring(false)
g.hide()
}}
>
<ArtifactPanel
title="Status page"
kind="html"
label="HTML"
language="html"
filename="status.html"
content={streaming || !current ? content : (current.content ?? content)}
streaming={streaming}
versions={versions.length ? versions : undefined}
version={version}
onVersionChange={setVersion}
view={view}
onViewChange={setView}
/>
<Ghost ghost={g.ghost} />
</div>
<MoreOn slug="artifact-panel">Code and documents an assistant writes, with a live preview. On</MoreOn>
</div>
</FitFrame>
)
}
















