Aadi

Citation

AI chats

About

Numbered inline sources that open a card with the title, site and the supporting passage highlighted.

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

Code

How Citation 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 { Citation, CitationSource } from "@/components/ui/citation"

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

/**
 * The cards are portaled to the body at full size, so a scaled down frame (the phone and profile
 * card previews) keeps them closed and shows the answer alone.
 */
const smallFrame = () => window.innerHeight < 360

/** The order the tour opens the cards in, by citation number. */
const ORDER = [1, 3, 2] as const

const OPEN_MS = 2600

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 NEXT: CitationSource = {
  url: "https://nextjs.org/docs/app/api-reference/file-conventions/loading",
  title: "loading.js file convention",
  snippet:
    "In the same folder, loading.js will be nested inside layout.js. It will automatically wrap the page.js file and any children below in a <Suspense> boundary.",
  quote: "loading.js will be nested inside layout.js",
}

const GITHUB: CitationSource = {
  url: "https://github.com/vercel/next.js/discussions/50120",
  title: "Why is my loading.tsx not showing?",
  snippet:
    "Data awaited in a layout blocks rendering before the loading boundary. Start the request in the layout, pass the promise down and wrap the reader in Suspense.",
  quote: "Data awaited in a layout blocks rendering",
}

const REACT: CitationSource = {
  url: "https://react.dev/reference/react/use",
  title: "use, React reference",
  snippet:
    "use is a React API that lets you read the value of a resource like a Promise or context. When called with a Promise, the component suspends until it resolves.",
  quote: "the component suspends until it resolves",
}

/** 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 answer with numbered sources. The tour opens each card in turn, with the supporting
 * passage highlighted. Hover or focus a number to take over; the tour carries on after you leave.
 */
export default function CitationPreview() {
  const [open, setOpen] = React.useState<number | null>(null)
  const [held, setHeld] = React.useState(false)
  const step = React.useRef(0)
  const root = React.useRef<HTMLDivElement>(null)

  // The cards render in a portal on the body. When the preview is themed by a `.dark` wrapper
  // rather than the root element, carry the theme to the root so the cards match.
  React.useEffect(() => {
    const html = document.documentElement
    if (!root.current?.closest(".dark") || html.classList.contains("dark")) return
    html.classList.add("dark")
    return () => html.classList.remove("dark")
  }, [])

  React.useEffect(() => {
    if (held || reducedMotion() || smallFrame()) return
    let id = 0
    const show = () => {
      setOpen(ORDER[step.current % ORDER.length]!)
      step.current += 1
      id = window.setTimeout(show, OPEN_MS)
    }
    id = window.setTimeout(show, 700)
    return () => window.clearTimeout(id)
  }, [held])

  const props = (index: number, source: CitationSource) => ({
    index,
    source,
    open: open === index,
    onOpenChange: (next: boolean) => {
      setHeld(next)
      setOpen(next ? index : null)
    },
  })

  return (
    <FitFrame>
      <div ref={root} className="flex w-full flex-col items-center justify-end gap-5 px-6 pt-48 pb-8">
        <div className="flex w-full max-w-xl flex-col gap-4">
          <p className="text-[1rem]/[1.5rem] tracking-[-0.01em] text-(color:--chatcn-fg) text-pretty">
            loading.tsx only wraps the page below its layout, so an await in the layout blocks the
            route before the fallback can show
            <Citation {...props(1, NEXT)} />
            <Citation {...props(3, GITHUB)} />. Pass the promise down instead and read it with use(),
            which suspends only the component that needs the data
            <Citation {...props(2, REACT)} />.
          </p>
        </div>
        <MoreOn slug="citation">Numbered sources with the passage that backs each claim. 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

More in AI chats

View all
  • AI Actions

    AI Actions

    349
  • Aquarium Prompt

    Aquarium Prompt

    95
  • Generation Stats

    Generation Stats

  • Chat Bubble

    Chat Bubble

    202
  • Commit

    Commit

    36
  • Color Picker

    Color Picker

    190
  • Environment Variables

    Environment Variables

    27
  • Message With Header And Delivery Status

    Message With Header And Delivery Status

    57

Explore more

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