Aadi

Code Block

Component

About

Syntax highlighted code that streams in as an agent writes it, with a caret, file tabs, highlighted lines, wrap and copy. Here a route, its query and its test arrive one tab at a time.

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

Code

How Code Block 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 { CodeBlockTabs } from "@/components/ui/code-block"

/** Opens partway into the first file, so the first frame already shows code landing. */
const START_MS = 600

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

/** True until `RESUME_MS` after the last `hold()`, for tours with their own state. */
function useHold() {
  const [held, setHeld] = React.useState(false)
  const timer = React.useRef(0)
  React.useEffect(() => () => window.clearTimeout(timer.current), [])
  const hold = React.useCallback(() => {
    setHeld(true)
    window.clearTimeout(timer.current)
    timer.current = window.setTimeout(() => setHeld(false), RESUME_MS)
  }, [])
  return [held, hold] as const
}

/** An agent writing a small API route, its query and its test, one file after another. */
const FILES = [
  {
    name: "route.ts",
    language: "ts",
    highlight: "4",
    code: `import { getRuns } from "@/lib/runs"

export async function GET(request: Request) {
  const limit = Number(new URL(request.url).searchParams.get("limit") ?? 20)
  const runs = await getRuns({ limit: Math.min(limit, 100) })
  return Response.json({ runs })
}`,
  },
  {
    name: "runs.ts",
    language: "ts",
    highlight: "5-8",
    code: `import { db } from "@/lib/db"

export function getRuns({ limit = 20 }: { limit?: number } = {}) {
  return db.run.findMany({
    take: limit,
    orderBy: { createdAt: "desc" },
    select: { id: true, status: true, createdAt: true },
  })
}`,
  },
  {
    name: "runs.test.ts",
    language: "ts",
    highlight: "6",
    code: `import { expect, test } from "vitest"
import { GET } from "./route"

test("caps the limit at 100", async () => {
  const res = await GET(new Request("http://localhost/api/runs?limit=500"))
  const { runs } = await res.json()
  expect(runs.length).toBeLessThanOrEqual(100)
})`,
  },
]

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

/** Each file streams for WRITE_MS, rests with its highlight for REST_MS, then the next tab opens. */
const WRITE_MS = 1500

const REST_MS = 1100

const FILE_MS = WRITE_MS + REST_MS

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 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 agent writes an API route, its query and its test: each file streams into its own tab with
 * a caret and syntax colors, the changed lines light up, then the next tab opens. Loops. Pick a
 * tab yourself and the tour waits a moment on it.
 */
export default function CodeBlockPreview() {
  const [clock, setClock] = React.useState(START_MS)
  const [held, hold] = useHold()
  const [mine, setMine] = React.useState(FILES[0]!.name)

  React.useEffect(() => {
    if (reducedMotion()) {
      setClock(WRITE_MS)
      return
    }
    if (held) return
    const began = performance.now() - clock
    const id = window.setInterval(() => setClock(performance.now() - began), 40)
    return () => window.clearInterval(id)
    // biome-ignore lint/correctness/useExhaustiveDependencies: resumes from the clock it held at.
  }, [held])

  const index = Math.floor(clock / FILE_MS) % FILES.length
  const local = clock % FILE_MS
  const reveal = reducedMotion() ? 1 : Math.min(1, local / WRITE_MS)
  const active = held ? mine : FILES[index]!.name

  const files = FILES.map((file, i) => {
    if (held || i !== index) return { name: file.name, language: file.language, code: file.code, highlightLines: file.highlight }
    const streaming = reveal < 1
    return {
      name: file.name,
      language: file.language,
      code: file.code.slice(0, Math.ceil(file.code.length * reveal)),
      streaming,
      highlightLines: streaming ? undefined : file.highlight,
    }
  })

  return (
    <FitFrame minWidth="44rem">
      <div className="flex w-full flex-col items-center justify-center gap-4 p-6">
        <div className="w-full max-w-2xl [--chatcn-code-sticky-top:-100rem]">
          <CodeBlockTabs
            className="h-[18.5rem] w-full"
            files={files}
            value={active}
            onValueChange={(name) => {
              hold()
              setMine(name)
            }}
          />
        </div>
        <MoreOn slug="code-block">Streaming code with tabs, highlights, wrap and copy. On</MoreOn>
      </div>
    </FitFrame>
  )
}

Dependencies

More by Aadi

View all
  • Dither Orb

    Dither Orb

    12
  • Audio Visualizer

    Audio Visualizer

    10
  • Voice Orb

    Voice Orb

    8
  • Agent Lanes

    Agent Lanes

    6
  • Waveform

    Waveform

    4
  • Computer View

    Computer View

    3
  • Chat Search

    Chat Search

    2
  • Reasoning

    Reasoning

    2

Explore more

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