Aadi

Chart

AI chats

About

Charts an assistant can answer with: line, bar, stacked bar, area and proportion, streamed in point by point into reserved slots so nothing shifts, with a table view, value formats and an accessible summary.

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

Code

How Chart 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 { Chart, ChartProps } from "@/components/ui/chart"

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

/** Three charts an assistant might answer with, each streamed in point by point. */
const CHARTS: (ChartProps & { data: NonNullable<ChartProps["data"]> })[] = [
  {
    type: "line",
    title: "Failing tests per fix attempt",
    description: "The agent reruns the suite of 443 tests after each change",
    xKey: "run",
    data: [
      { run: "1", passed: 412, failed: 31 },
      { run: "2", passed: 418, failed: 25 },
      { run: "3", passed: 426, failed: 17 },
      { run: "4", passed: 431, failed: 12 },
      { run: "5", passed: 437, failed: 6 },
      { run: "6", passed: 440, failed: 3 },
      { run: "7", passed: 443, failed: 0 },
    ],
    series: [{ key: "failed", label: "Failing" }],
    domain: [0, 35],
  },
  {
    type: "bar",
    title: "Signups by channel",
    description: "Last six weeks, stacked",
    xKey: "week",
    stacked: true,
    data: [
      { week: "W1", search: 320, referral: 140, social: 90 },
      { week: "W2", search: 360, referral: 150, social: 120 },
      { week: "W3", search: 410, referral: 190, social: 110 },
      { week: "W4", search: 380, referral: 230, social: 160 },
      { week: "W5", search: 450, referral: 260, social: 180 },
      { week: "W6", search: 520, referral: 300, social: 210 },
    ],
    series: [
      { key: "search", label: "Search" },
      { key: "referral", label: "Referral" },
      { key: "social", label: "Social" },
    ],
    domain: [0, 1100],
  },
  {
    type: "area",
    title: "API latency, p95",
    description: "Before and after the cache rollout",
    xKey: "hour",
    unit: "ms",
    data: [
      { hour: "09:00", p95: 412 },
      { hour: "10:00", p95: 438 },
      { hour: "11:00", p95: 455 },
      { hour: "12:00", p95: 301 },
      { hour: "13:00", p95: 188 },
      { hour: "14:00", p95: 164 },
      { hour: "15:00", p95: 158 },
      { hour: "16:00", p95: 161 },
    ],
    series: [{ key: "p95", label: "p95" }],
    domain: [0, 500],
  },
]

const REST_MS = 1500

const POINT_MS = 260

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 assistant answers with charts: a line of failing tests per fix, stacked signups by channel
 * and p95 latency as an area, each streamed in point by point into reserved slots so nothing
 * shifts, then held a moment before the next. Loops. Switch any of them to its table.
 */
export default function ChartPreview() {
  const [step, setStep] = React.useState({ chart: 0, count: 4 })

  React.useEffect(() => {
    if (reducedMotion()) {
      setStep({ chart: 0, count: CHARTS[0]!.data.length })
      return
    }
    const total = CHARTS[step.chart]!.data.length
    const done = step.count >= total
    const id = window.setTimeout(
      () =>
        setStep((s) => (done ? { chart: (s.chart + 1) % CHARTS.length, count: 1 } : { ...s, count: s.count + 1 })),
      done ? REST_MS : POINT_MS,
    )
    return () => window.clearTimeout(id)
  }, [step])

  const chart = CHARTS[step.chart]!
  const done = step.count >= chart.data.length

  return (
    <FitFrame minWidth="36rem">
      <div className="flex w-full flex-col items-center justify-center gap-4 p-6">
        <div className="h-[20rem] w-full max-w-xl">
          <Chart
            key={step.chart}
            {...chart}
            data={chart.data.slice(0, step.count)}
            expectedCount={chart.data.length}
            streaming={!done}
            height={200}
          />
        </div>
        <MoreOn slug="chart">Line, bar, area and proportion charts that stream in. On</MoreOn>
      </div>
    </FitFrame>
  )
}

Dependencies

More by Aadi

View all
  • Dither Orb

    Dither Orb

    12
  • Audio Visualizer

    Audio Visualizer

    9
  • Voice Orb

    Voice Orb

    8
  • Agent Lanes

    Agent Lanes

    6
  • Computer View

    Computer View

    3
  • Waveform

    Waveform

    2
  • Reasoning

    Reasoning

    2
  • Voice Session

    Voice Session

    1

More in AI chats

View all
  • AI Actions

    AI Actions

    338
  • Illos Knowledge Sources

    Illos Knowledge Sources

    40
  • Aquarium Prompt

    Aquarium Prompt

    48
  • Attachments

    Attachments

    38
  • Chat Search

    Chat Search

    1
  • Color Picker

    Color Picker

    171
  • Commit

    Commit

    32
  • Chat Bubble

    Chat Bubble

    199