Aadi

Artifact Versions

Component

About

A version switcher for artifacts an assistant revises, with relative times and added and removed line counts.

Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Artifact Versions to your project and fits it to your theme.

Code

How Artifact Versions 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 { ArtifactVersion, ArtifactVersions } from "@/components/ui/artifact-versions"

const reducedMotion = () =>
  typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches

/** How long a choice holds a tour before it carries on. */
const RESUME_MS = 1800

/**
 * Steps through `values` on a timer, so a 21st preview (and its cover video) shows every option
 * without a click. Picking a value holds it, and the tour carries on from there after
 * `RESUME_MS`, so a click never leaves the preview still. Reduced motion never starts it.
 */
function useCycle<T>(values: readonly T[], ms: number) {
  const [index, setIndex] = React.useState(0)
  const [heldAt, setHeldAt] = React.useState(0)
  React.useEffect(() => {
    if (reducedMotion()) return
    let id = 0
    const start = () => {
      id = window.setInterval(() => setIndex((n) => (n + 1) % values.length), ms)
    }
    const wait = window.setTimeout(start, heldAt ? RESUME_MS : 0)
    return () => {
      window.clearTimeout(wait)
      window.clearInterval(id)
    }
  }, [heldAt, values.length, ms])
  const pick = React.useCallback(
    (value: T) => {
      setHeldAt(Date.now())
      setIndex(Math.max(0, values.indexOf(value)))
    },
    [values],
  )
  return [values[index] as T, pick] as const
}

/** The tour opens on the latest version and holds it, then walks the history from v1. */
const TOUR = ["v4", "v4", "v1", "v2", "v3"]

const minutes = (n: number) => Date.now() - n * 60_000

const VERSIONS: ArtifactVersion[] = [
  { id: "v1", createdAt: minutes(42), summary: "First draft of the runs table", additions: 48, deletions: 0 },
  { id: "v2", createdAt: minutes(31), summary: "Added status filters", additions: 22, deletions: 6 },
  { id: "v3", createdAt: minutes(12), summary: "Paginated to 20 rows", additions: 9, deletions: 14 },
  { id: "v4", createdAt: minutes(2), summary: "Duration bars, so slow runs stand out", additions: 17, deletions: 3 },
]

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>
  )
}

const IDS = VERSIONS.map((v) => v.id)

type Status = "passed" | "running"

const RUNS: { name: string; status: Status; time: string; s: number }[] = [
  { name: "nightly-evals", status: "passed", time: "4 m 12 s", s: 252 },
  { name: "deploy-preview", status: "running", time: "1 m 03 s", s: 63 },
  { name: "migrate-billing", status: "passed", time: "38 s", s: 38 },
  { name: "reindex-search", status: "passed", time: "9 m 40 s", s: 580 },
  { name: "export-invoices", status: "passed", time: "2 m 18 s", s: 138 },
]

const DOT: Record<Status, string> = {
  passed: "bg-(color:--chatcn-green)",
  running: "bg-(color:--chatcn-amber)",
}

const SLOWEST = Math.max(...RUNS.map((r) => r.s))

/** The artifact itself, as each version left it. */
function RunsTable({ version }: { version: string }) {
  const n = IDS.indexOf(version) + 1
  const filters = n >= 2
  const paged = n >= 3
  const bars = n >= 4
  return (
    <div className="flex h-full flex-col gap-3">
      {filters ? (
        <div className="flex gap-1.5">
          {["All", "Passed", "Running"].map((f) => {
            const on = f === "All"
            return (
              <span
                key={f}
                className={
                  on
                    ? "bg-(color:--chatcn-fg) text-(color:--chatcn-bg) text-[0.75rem]/[1rem] rounded-full px-2.5 py-0.5 font-medium"
                    : "bg-(color:--chatcn-fill) text-(color:--chatcn-fg-muted) text-[0.75rem]/[1rem] rounded-full px-2.5 py-0.5"
                }
              >
                {f}
              </span>
            )
          })}
          <span className="text-(color:--chatcn-fg-subtle) text-[0.75rem]/[1rem] ms-auto self-center">Last 24 h</span>
        </div>
      ) : null}
      <div className="border-(color:--chatcn-border) rounded-(--chatcn-radius-md) flex flex-1 flex-col overflow-hidden border">
        <div className="bg-(color:--chatcn-bg-subtle) text-(color:--chatcn-fg-subtle) text-[0.75rem]/[1rem] border-(color:--chatcn-border) grid grid-cols-[1fr_6rem_9rem] border-b px-3 py-1.5">
          <span>Run</span>
          <span>Status</span>
          <span className="text-end">Duration</span>
        </div>
        {RUNS.map((r) => (
            <div
              key={r.name}
              className="border-(color:--chatcn-border) text-[0.8125rem]/[1.25rem] grid grid-cols-[1fr_6rem_9rem] items-center border-b px-3 py-1.5 last:border-b-0"
            >
              <span className="text-(color:--chatcn-fg) truncate font-mono text-[0.75rem]">{r.name}</span>
              <span className="text-(color:--chatcn-fg-muted) inline-flex items-center gap-1.5 capitalize">
                <span className={`size-1.5 rounded-full ${DOT[r.status]}`} />
                {r.status}
              </span>
              <span className="text-(color:--chatcn-fg-muted) flex items-center justify-end gap-2 tabular-nums">
                {bars ? (
                  <span className="bg-(color:--chatcn-fill) h-1.5 w-12 overflow-hidden rounded-full">
                    <span
                      className={`block h-full rounded-full ${r.s === SLOWEST ? "bg-(color:--chatcn-amber)" : "bg-(color:--chatcn-fg-subtle)"}`}
                      style={{ width: `${Math.max(8, (r.s / SLOWEST) * 100)}%` }}
                    />
                  </span>
                ) : null}
                {r.time}
              </span>
            </div>
          ))}
        {paged ? (
          <div className="text-(color:--chatcn-fg-subtle) text-[0.75rem]/[1rem] border-(color:--chatcn-border) mt-auto flex justify-between border-t px-3 py-1.5">
            <span>1 to 20 of 134</span>
            <span className="text-(color:--chatcn-fg)">Next page</span>
          </div>
        ) : null}
      </div>
    </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 artifact an assistant has revised four times. The tour steps through the versions with the
 * switcher in the header: each shows its summary, its added and removed line counts and the runs
 * table as that version left it. Step through yourself and the tour waits a moment.
 */
export default function ArtifactVersionsPreview() {
  const [version, pick] = useCycle(TOUR, 1800)
  const current = VERSIONS.find((v) => v.id === version)
  return (
    <FitFrame minWidth="34rem">
      <div className="flex w-full flex-col items-center justify-center gap-4 p-6">
        <div className="rounded-(--chatcn-radius-lg) bg-(color:--chatcn-card) shadow-(--chatcn-shadow-sm) @container flex w-full max-w-lg flex-col">
          <div className="border-(color:--chatcn-border) flex h-11 items-center justify-between gap-3 border-b ps-4 pe-2">
            <span className="text-[0.875rem]/[1.25rem] tracking-[-0.003em] text-(color:--chatcn-fg) min-w-0 truncate font-medium">Runs table</span>
            <ArtifactVersions
              versions={VERSIONS}
              value={version}
              onValueChange={pick}
              showMeta
              className="flex-row-reverse"
            />
          </div>
          <p className="text-[0.8125rem]/[1.25rem] text-(color:--chatcn-fg-muted) px-4 pt-3">{current?.summary}</p>
          <div className="h-[18.5rem] p-4 pt-3">
            <RunsTable version={version} />
          </div>
        </div>
        <MoreOn slug="artifact-versions">Every revision of an artifact, one click apart. On</MoreOn>
      </div>
    </FitFrame>
  )
}

Dependencies

More by Aadi

View all
  • Audio Visualizer

    Audio Visualizer

    29
  • Stat Card

    Stat Card

    24
  • Dither Orb

    Dither Orb

    23
  • Voice Orb

    Voice Orb

    17
  • Waveform

    Waveform

    13
  • Message Feedback

    Message Feedback

    12
  • Agent Lanes

    Agent Lanes

    11
  • Voice Controls

    Voice Controls

    10

Explore more

Part of chatcn — browse the full library on 21st.dev.