Aadi

Source Document

AI chats

About

Inline citations that point to the page of a document they quote, with a card that shows the cited passage.

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

Code

How Source Document 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 { cn } from "@/lib/utils"
import { DocumentSource, SourceDocument } from "@/components/ui/source-document"

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 passages the answer cites, in the order the tour lights them up. */
const CITES = [
  {
    page: 4,
    quote:
      "Readers in layout B answered yes to “Did this answer your question?” 9 percent more often than readers in layout A.",
  },
  {
    page: 8,
    quote:
      "Cap help article body text at 70 characters per line, using max-width: 68ch on the article column, and keep line height at 1.6.",
  },
] as const

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

/* -------------------------------------------------------------------------------------------------
 * Types and context
 * -----------------------------------------------------------------------------------------------*/

type MessageRole = "user" | "assistant" | "system"

type MessageLayout = "auto" | "bubble" | "flat" | "compact"

type MessageState = "streaming" | "done" | "edited" | "error" | "stopped" | "queued"

/* -------------------------------------------------------------------------------------------------
 * Message
 * -----------------------------------------------------------------------------------------------*/

interface MessageProps extends React.ComponentProps<"div"> {
  /** Who wrote it. Named `from` so the ARIA `role` attribute stays free. */
  from: MessageRole
  /**
   * `auto` gives users a subtle bubble and assistants a flat, document-style block. `compact`
   * is the dense log style for agent traces and side panels. Defaults to `auto`.
   */
  layout?: MessageLayout
  /** Lifecycle state. Defaults to `done`. */
  state?: MessageState
  /** Follows a message from the same author: tightens the gap and hides the avatar. */
  grouped?: boolean
  /** The newest message. Keeps its actions visible instead of revealing them on hover. */
  latest?: boolean
  /**
   * Enter animation. Defaults to animating only messages that arrive after the conversation
   * mounted, so restored history appears at once.
   */
  animate?: boolean
  /** Announce the text to screen readers when streaming finishes. Defaults to true. */
  announce?: boolean
}

/** Scroll behavior for imperative calls. `smooth` falls back to instant under reduced motion. */
type ChatcnScrollBehavior = "smooth" | "instant"

/* -------------------------------------------------------------------------------------------------
 * Context
 * -----------------------------------------------------------------------------------------------*/

interface ConversationContextValue {
  scrollRef: (element: HTMLElement | null) => void
  contentRef: (element: HTMLElement | null) => void
  spacerRef: (element: HTMLElement | null) => void
  /** Within the threshold of the bottom. */
  isAtBottom: boolean
  /** Following new content. */
  isSticky: boolean
  /** More than one viewport from the bottom. */
  isFar: boolean
  /** Messages that arrived below while the reader was scrolled up. */
  unread: number
  scrollToBottom: (options?: { behavior?: ChatcnScrollBehavior }) => void
  scrollToTurn: (element: HTMLElement, options?: { behavior?: ChatcnScrollBehavior }) => void
  /** Read text to screen readers through the conversation's polite live region. */
  announce: (text: string) => void
  /** False during the first render, so restored history does not animate in. */
  ready: boolean
}

const ConversationContext = React.createContext<ConversationContextValue | null>(null)

/** Scroll state and controls of the nearest `Conversation`. Returns null outside one. */
function useConversation() {
  return React.useContext(ConversationContext)
}

interface MessageContextValue {
  from: MessageRole
  /** Resolved layout: `auto` becomes `bubble` for users and `flat` for everyone else. */
  layout: Exclude<MessageLayout, "auto">
  state: MessageState
  /** The newest message: its actions stay visible. */
  latest: boolean
}

const MessageContext = React.createContext<MessageContextValue | null>(null)

/**
 * One turn in the conversation. Compose `MessageAvatar`, `MessageContent`, `MessageMeta`,
 * `MessageStatus` and `MessageActions` inside it.
 */
function Message({
  from,
  layout: layoutProp = "auto",
  state = "done",
  grouped = false,
  latest = false,
  animate,
  announce = true,
  className,
  children,
  ...props
}: MessageProps) {
  const conversation = useConversation()
  const layout: MessageContextValue["layout"] =
    layoutProp === "auto" ? (from === "user" ? "bubble" : "flat") : layoutProp
  const [enter] = React.useState(() => animate ?? conversation?.ready ?? false)
  const ref = React.useRef<HTMLDivElement>(null)

  // Screen readers hear the finished reply once, never token by token.
  const previous = React.useRef(state)
  React.useEffect(() => {
    const was = previous.current
    previous.current = state
    if (!announce || was !== "streaming" || state === "streaming") return
    const text = ref.current?.querySelector('[data-slot="message-content"]')?.textContent?.trim()
    if (text) conversation?.announce(text)
  }, [state, announce, conversation])

  const value = React.useMemo(
    () => ({ from, layout, state, latest }),
    [from, layout, state, latest],
  )

  return (
    <MessageContext.Provider value={value}>
      <div
        ref={ref}
        data-slot="message"
        data-role={from}
        data-layout={layout}
        data-message-state={state}
        data-grouped={grouped ? "" : undefined}
        data-latest={latest ? "" : undefined}
        aria-busy={state === "streaming" || undefined}
        className={cn(
          "group/message relative flex min-w-0 flex-col",
          layout === "compact" ? "gap-1" : "gap-2",
          layout === "bubble" ? "items-end" : "items-start",
          from === "system" && layout !== "compact" && "items-center text-center",
          grouped && (layout === "compact" ? "-mt-2" : "-mt-4"),
          // An avatar sits in the start gutter (the end gutter for bubbles).
          layout === "bubble"
            ? "has-[>[data-slot=message-avatar]]:pe-9"
            : "has-[>[data-slot=message-avatar]]:ps-9",
          enter &&
            (from === "user"
              ? "ease-(--chatcn-ease-out-soft) transition-[opacity,translate] duration-200 starting:translate-y-2 starting:opacity-0 motion-reduce:starting:translate-y-0"
              : "ease-(--chatcn-ease-out-soft) transition-opacity duration-150 starting:opacity-0"),
          className,
        )}
        {...props}
      >
        {children}
      </div>
    </MessageContext.Provider>
  )
}

/** Role, layout and state of the nearest `Message`. Returns null outside one. */
function useMessage() {
  return React.useContext(MessageContext)
}

/* -------------------------------------------------------------------------------------------------
 * MessageContent
 * -----------------------------------------------------------------------------------------------*/

/**
 * The text of a message, capped at a 68ch measure. Plain text keeps its line breaks. Markdown
 * renderers drop in as children and inherit the 15/24 prose size.
 */
function MessageContent({ className, children, ...props }: React.ComponentProps<"div">) {
  const ctx = useMessage()
  const layout = ctx?.layout ?? "flat"
  const from = ctx?.from ?? "assistant"
  const state = ctx?.state ?? "done"
  const plain = typeof children === "string"

  return (
    <div
      data-slot="message-content"
      className={cn(
        "text-(color:--chatcn-fg) min-w-0 [overflow-wrap:anywhere]",
        // Bubbles fill their lines: pretty wrapping would leave a wide, half-empty bubble.
        layout !== "bubble" && "text-pretty",
        plain && "whitespace-pre-wrap",
        layout === "bubble" &&
          "text-[0.9375rem]/[1.5rem] tracking-[-0.006em] rounded-(--chatcn-radius-xl) bg-(color:--chatcn-fill) max-w-[80%] px-4 py-2.5 text-start",
        layout === "flat" && "text-[0.9375rem]/[1.5rem] tracking-[-0.006em] w-full max-w-[68ch]",
        layout === "compact" &&
          (from === "user"
            ? "text-[0.875rem]/[1.25rem] tracking-[-0.003em] rounded-(--chatcn-radius-md) bg-(color:--chatcn-fill) max-w-full px-3 py-1.5"
            : "text-[0.875rem]/[1.25rem] tracking-[-0.003em] w-full max-w-[68ch]"),
        from === "system" && "text-[0.8125rem]/[1.25rem] text-(color:--chatcn-fg-muted) max-w-[60ch]",
        // Queued turns are not sent yet: an outline instead of a fill says "pending".
        state === "queued" &&
          from === "user" &&
          "text-(color:--chatcn-fg-muted) border-(color:--chatcn-border-strong) border border-dashed bg-transparent",
        state === "error" && from === "user" && "text-(color:--chatcn-fg-muted)",
        className,
      )}
      {...props}
    >
      {children}
    </div>
  )
}

const HELP_CENTER_STUDY: DocumentSource = {
  id: "doc-help-center-study",
  title: "Help center readability study",
  filename: "help-center-readability-study-2026.pdf",
  mediaType: "application/pdf",
  pageCount: 14,
  pages: [
    {
      number: 3,
      text: `Method

We rebuilt 40 of the most visited help articles in three layouts and split traffic evenly between them for six weeks. Layout A kept the current full-width column, which runs to about 110 characters per line on a 1440 px screen. Layout B capped the column at 75 characters. Layout C capped it at 60 characters and raised the line height from 1.5 to 1.6.

Each article ended with the existing “Did this answer your question?” prompt. We also logged scroll depth, time on page, and whether the reader opened a support ticket within 24 hours.

In total 212,480 sessions met the inclusion rules: desktop only, article loaded fully, at least 10 seconds on the page.`,
    },
    {
      number: 4,
      text: `Results

Readers in layout B answered yes to “Did this answer your question?” 9 percent more often than readers in layout A. Layout C was within one point of layout B. The difference between B and C was not significant.

Ticket rate fell from 4.1 percent in layout A to 3.4 percent in layout B and 3.5 percent in layout C. Time on page was slightly longer in the capped layouts, which we read as people finishing the article rather than abandoning it.

Scroll depth was the clearest signal. In layout A, half of readers stopped before the steps section. In layouts B and C, most readers reached the final step.`,
    },
    {
      number: 5,
      text: `Reading comments

We asked 18 participants to read two articles aloud while sharing their screen. Several lost their place when moving from the end of one line to the start of the next in layout A, and two reread the same line without noticing.

No participant commented on the narrower layouts. When asked afterwards, most said the capped articles felt "shorter", even though the text was identical.`,
    },
    {
      number: 8,
      text: `Recommendation

Cap help article body text at 70 characters per line, using max-width: 68ch on the article column, and keep line height at 1.6. Tables, code samples and screenshots may extend to the full content width.

Roll the change out to all articles in one release. The template change is small, and running two layouts side by side for longer would delay the ticket savings.

Revisit mobile separately. Phone screens already sit below 45 characters per line at our default size, so the cap has no effect there.`,
    },
  ],
}

/** 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 grounded in a PDF the user uploaded. Each claim cites its page, and the card below
 * quotes the passage of the citation that is lit. The tour steps through both. Click a chip to
 * pick one yourself.
 */
export default function SourceDocumentPreview() {
  const [cite, pick] = useCycle(CITES, 2400)
  return (
    <FitFrame minWidth="36rem">
      <div className="flex w-full flex-col items-center justify-center gap-5 p-6">
        <div className="text-[0.9375rem]/[1.5rem] tracking-[-0.006em] text-(color:--chatcn-fg) flex w-full max-w-xl flex-col gap-4">
          <Message from="user">
            <MessageContent>Should we narrow the help center column?</MessageContent>
          </Message>
          <p className="text-pretty">
            Yes. Your own study points that way. Capping articles at 75 characters raised yes
            answers to “Did this answer your question?” by 9 percent
            <SourceDocument
              document={HELP_CENTER_STUDY}
              page={4}
              quote={CITES[0].quote}
              viewer="none"
              active={cite.page === 4}
              onOpen={() => pick(CITES[0])}
            />{" "}
            and cut the ticket rate from 4.1 to 3.4 percent. It recommends a 68ch column with a 1.6
            line height
            <SourceDocument
              document={HELP_CENTER_STUDY}
              page={8}
              quote={CITES[1].quote}
              viewer="none"
              active={cite.page === 8}
              onOpen={() => pick(CITES[1])}
            />
            .
          </p>
          <SourceDocument
            variant="card"
            viewer="none"
            document={HELP_CENTER_STUDY}
            page={cite.page}
            quote={cite.quote}
          />
        </div>
        <MoreOn slug="source-document">Citations that open the page of a document they quote. On</MoreOn>
      </div>
    </FitFrame>
  )
}

Dependencies

More by Aadi

View all
  • Stat Card

    Stat Card

    46
  • Audio Visualizer

    Audio Visualizer

    32
  • Dither Orb

    Dither Orb

    24
  • Voice Orb

    Voice Orb

    20
  • Weather Card

    Weather Card

    17
  • Waveform

    Waveform

    15
  • Ticker Card

    Ticker Card

    15
  • Message Feedback

    Message Feedback

    13

More in AI chats

View all
  • AI Actions

    AI Actions

    351
  • Aquarium Prompt

    Aquarium Prompt

    113
  • Agent Chat

    Agent Chat

    21
  • Message With Header And Delivery Status

    Message With Header And Delivery Status

    60
  • Research Report

    Research Report

    7
  • Tool Web Fetch

    Tool Web Fetch

    4
  • Color Picker

    Color Picker

    201
  • Suggestions

    Suggestions

    40

Explore more

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