Citations

An answer with the sites it was taken from at its foot, as their own marks that open into a list.

'use client';

import { useEffect, useState } from 'react';
import { AtlassianLogo, GitHubLogo, GitLogo } from '@/components/site-logos';
import { Citations, type CitationSource } from '@/components/panelui/citations';
import type { ThinkingOrbsState } from '@/components/panelui/thinking-orbs';

const SOURCES: CitationSource[] = [
  {
    id: 'git',
    site: 'Git',
    title: 'Pro Git: Rebasing',
    url: 'https://git-scm.com/book/en/v2/Git-Branching-Rebasing',
    icon: <GitLogo />,
    kind: 'Summary',
    quote: (
      <>
        The result is the same either way, but a rebased branch <mark>reads as a linear history</mark>.
      </>
    ),
  },
  {
    id: 'atlassian',
    site: 'Atlassian',
    title: 'Merging vs. rebasing',
    url: 'https://www.atlassian.com/git/tutorials/merging-vs-rebasing',
    icon: <AtlassianLogo />,
    kind: 'Summary',
    quote: (
      <>
        A merge is <mark>non-destructive</mark>: the existing branches are left as they are.
      </>
    ),
  },
  {
    id: 'github',
    site: 'GitHub Docs',
    title: 'About Git rebase',
    url: 'https://docs.github.com/en/get-started/using-git/about-git-rebase',
    icon: <GitHubLogo />,
    kind: 'Summary',
    quote: (
      <>
        Rebasing commits you have <mark>already pushed</mark> makes things difficult for everyone else using them.
      </>
    ),
  },
];

/** What is done before there is an answer, and for how long. */
const RUN: { state: ThinkingOrbsState; says: string; lasts: number }[] = [
  { state: 'searching', says: 'Searching the web', lasts: 1700 },
  { state: 'reading', says: 'Reading 3 pages', lasts: 1600 },
];

/** The step being done, and whether the answer has started. */
function useRun() {
  const [at, setAt] = useState(0);
  useEffect(() => {
    if (at >= RUN.length) return;
    const timer = window.setTimeout(() => setAt(at + 1), RUN[at]!.lasts);
    return () => window.clearTimeout(timer);
  }, [at]);
  return { step: RUN[Math.min(at, RUN.length - 1)]!, answering: at >= RUN.length };
}

export default function CitationsOverview() {
  const { step, answering } = useRun();
  return (
    <Citations sources={SOURCES} className="max-w-lg">
      <Citations.Status state={step.state} open={!answering}>
        {step.says}
      </Citations.Status>
      {answering ? (
        <Citations.Bubble>
          <Citations.Content stream>
            <p>
              <Citations.Cite source="git">Rebase to keep a branch&apos;s history in one straight line.</Citations.Cite>{' '}
              <Citations.Cite source="atlassian">
                Merge when other people share the branch, because a merge changes nothing that is already there.
              </Citations.Cite>{' '}
              <Citations.Cite source={['github', 'git']}>
                Once commits are pushed and somebody may have built on them, leave them as they are.
              </Citations.Cite>
            </p>
          </Citations.Content>
          <Citations.Tray>Taken from</Citations.Tray>
        </Citations.Bubble>
      ) : null}
    </Citations>
  );
}

Use it for an assistant's answer that was taken from somewhere, so a reader can see who is being quoted and go and check. The sites' own marks sit at the foot of the bubble, and open into the list of pages.

stream on Citations.Content brings the answer in a word at a time. Citations.Status says what is being done until then, and folds away when it starts.

Give each source an id and wrap the sentences taken from it in Citations.Cite. Pointing at a source lights its sentences, and the row counts how many it backs.

For an answer with no sources, use Message. Message.Cite, Message.Citation and Message.Sources are still there for a conversation that already uses them.

The component draws no logos. Give each source an icon, an <img> or an <svg> that fills a circle; without one it shows the site's first letter. The marks on this page are the sites' own, and an app needs the right to show them.

Installation

npx shadcn@latest add https://panelui.dev/r/web/citations.json

The source is copied into components/panelui/, where you can edit it.

Usage

import { Citations } from "@/components/panelui/citations"
const sources = [
  { id: 'git', site: 'Git', title: 'Pro Git: Rebasing', url: 'https://git-scm.com/book/en/v2/Git-Branching-Rebasing', icon: <GitLogo /> },
  { id: 'mdn', site: 'MDN', title: 'View Transition API', url: 'https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API', icon: <MdnLogo /> },
]

<Citations sources={sources}>
  <Citations.Bubble>
    <Citations.Content stream>
      <p>
        <Citations.Cite source="git">A rebased branch reads as one line.</Citations.Cite>
      </p>
    </Citations.Content>
    <Citations.Tray>Taken from</Citations.Tray>
  </Citations.Bubble>
</Citations>

Composition

<Citations>
  <Citations.Status />
  <Citations.Bubble>
    <Citations.Content>
      <Citations.Cite />
      <Citations.Citation />
    </Citations.Content>
    <Citations.Tray />
  </Citations.Bubble>
  <Citations.Dock />
</Citations>

<Citations>
  <Citations.Flip>
    <Citations.Content />
  </Citations.Flip>
</Citations>

<Citations>
  <Citations.Margin>
    <Citations.Content />
  </Citations.Margin>
</Citations>
  • Citations.Status — What is being done before there is an answer, as a Thinking Orb and a line. state is the orb's: searching, reading. Turn open off when the answer starts, and it folds away.
  • Citations.Bubble — The surface the answer is on.
  • Citations.Content — The answer, set as prose, so rendered Markdown can go straight in. stream brings it in a word at a time, and the tray, dock, flip and notes wait for the last one.
  • Citations.Cite — A sentence taken from a source. source is the source's id, or several. It is lit while its source is pointed at.
  • Citations.Citation — A chip after a sentence, with the site's mark and domain. Pointing at it or focusing it opens a card with the passage, and the card pages when source names several.
  • Citations.Tray — A strip at the bubble's foot with the marks piled at its end. Pressed, it rises to the height of the answer, each mark travels to its own row, and the rows scroll when there are more than fit. early shows it while the answer is still arriving.
  • Citations.Dock — The marks in a pill on the bubble's lower edge, after the Citations.Bubble. They fan out when the pointer or focus comes to them, and each opens the passage it backs.
  • Citations.Flip — A bubble with the answer on one side and the sources on the other, which scrolls when there are more than fit. It stands in for Citations.Bubble.
  • Citations.Margin — The answer with a note beside each sentence that has a source, joined to it by a hairline. It stands in for Citations.Bubble, and needs 560 pixels; with less, the notes go under the answer.

Examples

Chips in the text

Follow a sentence with a Citations.Citation naming its source. Point at a chip to light the sentence and read the passage. A chip with two sources pages between them.

'use client';

import { useEffect, useState } from 'react';
import { ChromeLogo, MdnLogo } from '@/components/site-logos';
import { Citations, type CitationSource } from '@/components/panelui/citations';
import type { ThinkingOrbsState } from '@/components/panelui/thinking-orbs';

const SOURCES: CitationSource[] = [
  {
    id: 'mdn',
    site: 'MDN',
    title: 'View Transition API',
    url: 'https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API',
    icon: <MdnLogo />,
    kind: 'Summary',
    quote: (
      <>
        <mark>document.startViewTransition()</mark> starts a transition within one page and returns an object that
        stands for it.
      </>
    ),
  },
  {
    id: 'chrome',
    site: 'Chrome for Developers',
    title: 'Smooth transitions with the View Transition API',
    url: 'https://developer.chrome.com/docs/web-platform/view-transitions',
    icon: <ChromeLogo />,
    kind: 'Summary',
    quote: (
      <>
        Transitions within one document are supported <mark>from Chrome 111</mark>, and are driven by CSS animations.
      </>
    ),
  },
];

/** What is done before there is an answer, and for how long. */
const RUN: { state: ThinkingOrbsState; says: string; lasts: number }[] = [
  { state: 'thinking', says: 'Working out the question', lasts: 1300 },
  { state: 'searching', says: 'Searching the docs', lasts: 1600 },
];

/** The step being done, and whether the answer has started. */
function useRun() {
  const [at, setAt] = useState(0);
  useEffect(() => {
    if (at >= RUN.length) return;
    const timer = window.setTimeout(() => setAt(at + 1), RUN[at]!.lasts);
    return () => window.clearTimeout(timer);
  }, [at]);
  return { step: RUN[Math.min(at, RUN.length - 1)]!, answering: at >= RUN.length };
}

export default function CitationsInline() {
  const { step, answering } = useRun();
  return (
    <Citations sources={SOURCES} className="max-w-lg">
      <Citations.Status state={step.state} open={!answering}>
        {step.says}
      </Citations.Status>
      {answering ? (
        <Citations.Bubble>
          <Citations.Content stream>
            <p>
              <Citations.Cite source="mdn">
                Call <code>document.startViewTransition()</code> with a function that changes the page
              </Citations.Cite>
              <Citations.Citation source="mdn" />, and the browser animates between the two states.{' '}
              <Citations.Cite source="chrome">
                The motion is CSS, and it works in Chrome from version 111
              </Citations.Cite>
              <Citations.Citation source={['chrome', 'mdn']} />.
            </p>
          </Citations.Content>
        </Citations.Bubble>
      ) : null}
    </Citations>
  );
}

A dock of marks

Citations.Dock hangs the marks on the bubble's edge, piled. Bring the pointer to it and they fan out; the one under the pointer lifts, its sentence lights and its passage opens above. On a touch screen the first press fans them out and the next opens one.

'use client';

import { useEffect, useState } from 'react';
import { ArxivLogo, GitHubLogo, WikipediaLogo } from '@/components/site-logos';
import { Citations, type CitationSource } from '@/components/panelui/citations';
import type { ThinkingOrbsState } from '@/components/panelui/thinking-orbs';

const SOURCES: CitationSource[] = [
  {
    id: 'arxiv',
    site: 'arXiv',
    title: 'Attention Is All You Need',
    url: 'https://arxiv.org/abs/1706.03762',
    icon: <ArxivLogo />,
    kind: 'Summary',
    quote: (
      <>
        The Transformer is built on attention alone, <mark>without recurrence or convolutions</mark>, and trains in far
        less time.
      </>
    ),
  },
  {
    id: 'wikipedia',
    site: 'Wikipedia',
    title: 'Transformer (deep learning)',
    url: 'https://en.wikipedia.org/wiki/Transformer_(deep_learning)',
    icon: <WikipediaLogo />,
    kind: 'Summary',
    quote: (
      <>
        Because tokens are not processed one at a time, training can be <mark>parallelised across the sequence</mark>.
      </>
    ),
  },
  {
    id: 'github',
    site: 'GitHub',
    title: 'tensorflow/tensor2tensor',
    url: 'https://github.com/tensorflow/tensor2tensor',
    icon: <GitHubLogo />,
    kind: 'Summary',
    quote: (
      <>
        The library is <mark>now deprecated</mark>, and points its users to its successor, Trax.
      </>
    ),
  },
];

/** What is done before there is an answer, and for how long. */
const RUN: { state: ThinkingOrbsState; says: string; lasts: number }[] = [
  { state: 'searching', says: 'Looking for the paper', lasts: 1700 },
  { state: 'reading', says: 'Reading the abstract', lasts: 1500 },
];

/** The step being done, and whether the answer has started. */
function useRun() {
  const [at, setAt] = useState(0);
  useEffect(() => {
    if (at >= RUN.length) return;
    const timer = window.setTimeout(() => setAt(at + 1), RUN[at]!.lasts);
    return () => window.clearTimeout(timer);
  }, [at]);
  return { step: RUN[Math.min(at, RUN.length - 1)]!, answering: at >= RUN.length };
}

export default function CitationsDock() {
  const { step, answering } = useRun();
  return (
    <Citations sources={SOURCES} className="max-w-lg">
      <Citations.Status state={step.state} open={!answering}>
        {step.says}
      </Citations.Status>
      {answering ? (
        <div>
          <Citations.Bubble>
            <Citations.Content stream className="pb-8">
              <p>
                <Citations.Cite source="arxiv">
                  The 2017 paper dropped recurrence and kept only attention.
                </Citations.Cite>{' '}
                <Citations.Cite source="wikipedia">
                  That is what lets training run across a whole sequence at once.
                </Citations.Cite>{' '}
                <Citations.Cite source="github">
                  Its first library is still online, but is deprecated in favour of Trax.
                </Citations.Cite>
              </p>
            </Citations.Content>
          </Citations.Bubble>
          <Citations.Dock />
        </div>
      ) : null}
    </Citations>
  );
}

Turning it over

Citations.Flip keeps the answer on one side and the list on the other. Use it where the answer is short and the sources are worth a look of their own. Escape turns it back.

'use client';

import { useEffect, useState } from 'react';
import { NodeLogo, TypeScriptLogo } from '@/components/site-logos';
import { Citations, type CitationSource } from '@/components/panelui/citations';
import type { ThinkingOrbsState } from '@/components/panelui/thinking-orbs';

const SOURCES: CitationSource[] = [
  {
    id: 'node',
    site: 'Node.js',
    title: 'Modules: TypeScript',
    url: 'https://nodejs.org/api/typescript.html',
    icon: <NodeLogo />,
  },
  {
    id: 'typescript',
    site: 'TypeScript',
    title: 'TypeScript 5.8 release notes',
    url: 'https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-8.html',
    icon: <TypeScriptLogo />,
  },
];

/** What is done before there is an answer, and for how long. */
const RUN: { state: ThinkingOrbsState; says: string; lasts: number }[] = [
  { state: 'thinking', says: 'Thinking', lasts: 1200 },
  { state: 'reading', says: 'Reading the release notes', lasts: 1700 },
];

/** The step being done, and whether the answer has started. */
function useRun() {
  const [at, setAt] = useState(0);
  useEffect(() => {
    if (at >= RUN.length) return;
    const timer = window.setTimeout(() => setAt(at + 1), RUN[at]!.lasts);
    return () => window.clearTimeout(timer);
  }, [at]);
  return { step: RUN[Math.min(at, RUN.length - 1)]!, answering: at >= RUN.length };
}

export default function CitationsFlip() {
  const { step, answering } = useRun();
  return (
    <Citations sources={SOURCES} className="max-w-md">
      <Citations.Status state={step.state} open={!answering}>
        {step.says}
      </Citations.Status>
      {answering ? (
        <Citations.Flip>
          <Citations.Content stream>
            <p>
              <Citations.Cite source="node">
                Node runs a TypeScript file by putting spaces where its types were. It does not check them.
              </Citations.Cite>{' '}
              <Citations.Cite source="typescript">
                Turn on erasableSyntaxOnly and the compiler reports what Node cannot run, such as enums.
              </Citations.Cite>
            </p>
          </Citations.Content>
        </Citations.Flip>
      ) : null}
    </Citations>
  );
}

Notes in the margin

Citations.Margin sets each source's quote beside the sentence it backs. Point at either and both light. Use it where the answer will be checked line by line. With less than 560 pixels the notes go under it.

'use client';

import { useEffect, useState } from 'react';
import { MdnLogo, ReactLogo } from '@/components/site-logos';
import { Citations, type CitationSource } from '@/components/panelui/citations';
import type { ThinkingOrbsState } from '@/components/panelui/thinking-orbs';

const SOURCES: CitationSource[] = [
  {
    id: 'need',
    site: 'React',
    title: 'You Might Not Need an Effect',
    url: 'https://react.dev/learn/you-might-not-need-an-effect',
    icon: <ReactLogo />,
    quote: (
      <>
        What can be worked out from props or state is <mark>calculated during rendering</mark>.
      </>
    ),
  },
  {
    id: 'effect',
    site: 'React reference',
    title: 'useEffect',
    url: 'https://react.dev/reference/react/useEffect',
    icon: <ReactLogo />,
    quote: (
      <>
        After a change, React runs <mark>the cleanup with the old values</mark> first.
      </>
    ),
  },
  {
    id: 'abort',
    site: 'MDN',
    title: 'AbortController',
    url: 'https://developer.mozilla.org/en-US/docs/Web/API/AbortController',
    icon: <MdnLogo />,
    quote: (
      <>
        <mark>abort()</mark> stops a fetch before it has finished.
      </>
    ),
  },
];

/** What is done before there is an answer, and for how long. */
const RUN: { state: ThinkingOrbsState; says: string; lasts: number }[] = [
  { state: 'searching', says: 'Looking through the docs', lasts: 1600 },
  { state: 'reading', says: 'Reading 3 pages', lasts: 1500 },
];

/** The step being done, and whether the answer has started. */
function useRun() {
  const [at, setAt] = useState(0);
  useEffect(() => {
    if (at >= RUN.length) return;
    const timer = window.setTimeout(() => setAt(at + 1), RUN[at]!.lasts);
    return () => window.clearTimeout(timer);
  }, [at]);
  return { step: RUN[Math.min(at, RUN.length - 1)]!, answering: at >= RUN.length };
}

export default function CitationsMargin() {
  const { step, answering } = useRun();
  return (
    <Citations sources={SOURCES} className="max-w-2xl">
      <Citations.Status state={step.state} open={!answering}>
        {step.says}
      </Citations.Status>
      {answering ? (
        <Citations.Margin>
          <Citations.Content stream>
            <p>
              <Citations.Cite source="need">
                A value that follows from props needs no effect. Work it out as you render.
              </Citations.Cite>
            </p>
            <p>
              <Citations.Cite source="effect">
                When you do need one, return a cleanup: React runs it before the next.
              </Citations.Cite>
            </p>
            <p>
              <Citations.Cite source="abort">
                For a fetch, let that cleanup abort the request it started.
              </Citations.Cite>
            </p>
          </Citations.Content>
        </Citations.Margin>
      ) : null}
    </Citations>
  );
}

As sources are found

Add to sources as they arrive and each mark drops onto the pile. early on the tray shows it before there is an answer. Past four marks, the rest are a count, and opened over a short answer the rows scroll.

'use client';

import { useEffect, useState } from 'react';
import { AtlassianLogo, GitHubLogo, GitLogo, MdnLogo, ReactLogo } from '@/components/site-logos';
import { Citations, type CitationSource } from '@/components/panelui/citations';

const FOUND: CitationSource[] = [
  {
    id: 'effect',
    site: 'React',
    title: 'You might not need an effect',
    url: 'https://react.dev/learn/you-might-not-need-an-effect',
    icon: <ReactLogo />,
  },
  {
    id: 'git',
    site: 'Git',
    title: 'Pro Git: Rebasing',
    url: 'https://git-scm.com/book/en/v2/Git-Branching-Rebasing',
    icon: <GitLogo />,
  },
  {
    id: 'mdn',
    site: 'MDN',
    title: 'View Transition API',
    url: 'https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API',
    icon: <MdnLogo />,
  },
  {
    id: 'github',
    site: 'GitHub Docs',
    title: 'About Git rebase',
    url: 'https://docs.github.com/en/get-started/using-git/about-git-rebase',
    icon: <GitHubLogo />,
  },
  {
    id: 'atlassian',
    site: 'Atlassian',
    title: 'Merging vs. rebasing',
    url: 'https://www.atlassian.com/git/tutorials/merging-vs-rebasing',
    icon: <AtlassianLogo />,
  },
];

export default function CitationsStreaming() {
  // How many sources have been found. The answer starts when they all have.
  const [found, setFound] = useState(0);
  const searching = found < FOUND.length;

  useEffect(() => {
    if (!searching) return;
    const timer = window.setTimeout(() => setFound(found + 1), found === 0 ? 1300 : 750);
    return () => window.clearTimeout(timer);
  }, [searching, found]);

  return (
    <Citations sources={FOUND.slice(0, found)} className="max-w-lg">
      <Citations.Status open={searching}>{found === 0 ? 'Searching' : `Found ${found} of 5`}</Citations.Status>
      <Citations.Bubble>
        {searching ? null : (
          <Citations.Content stream>
            <p>
              Three things to read this week:{' '}
              <Citations.Cite source="effect">when an effect can be left out</Citations.Cite>,{' '}
              <Citations.Cite source={['git', 'github', 'atlassian']}>when a rebase is safe</Citations.Cite>, and{' '}
              <Citations.Cite source="mdn">how the browser can animate between two states of a page</Citations.Cite>.
            </p>
            <p>The first is the shortest, and the one most likely to change what you write tomorrow.</p>
          </Citations.Content>
        )}
        <Citations.Tray early>{searching ? 'Finding sources' : 'Taken from'}</Citations.Tray>
      </Citations.Bubble>
    </Citations>
  );
}

API Reference

Citations.Provider

PropTypeDefaultDescription
sourcesreadonly CitationSource[]—Every source, once each.

Citations

PropTypeDefaultDescription
sourcesreadonly CitationSource[]—Every source the answer cites, once each, in the order they are listed.

Citations.Status

PropTypeDefaultDescription
stateThinkingOrbsState'searching'What is being done, as the orb's shape. Default searching.
sizenumber26The orb's size in pixels. Default 26.
openbooleantrueWhether it is there. Turn it off when the answer starts, and it folds away. Default true.

Citations.Bubble

PropTypeDefaultDescription
setTray(tray: { foot: number; open: boolean; least: number } | null) => void—The tray's, while there is one: the room it keeps at the bubble's foot, and the least the bubble can be.
coveredboolean—

Citations.Content

PropTypeDefaultDescription
streambooleanfalseBrings the answer in a word at a time. The tray, dock, flip and notes wait for it. Default false.
wordDelaynumber55About how long each word takes, in ms. Default 55.
onStreamEnd() => void—Called when the last word is in.

Citations.Cite

PropTypeDefaultDescription
sourcestring | readonly string[]—The id, or ids, of the sources this sentence comes from.

Citations.Citation

PropTypeDefaultDescription
sourcestring | readonly string[]—The id, or ids, of the sources for the sentence before it.
sourcesreadonly CitationSource[]—The sources themselves, where there is no Citations round it to find them by id.
delaynumber—How long the pointer rests on the chip before the card opens, in ms. Default 120.

Citations.Tray

PropTypeDefaultDescription
openboolean—Whether it has risen, when the caller holds it.
defaultOpenbooleanfalseWhether it starts risen, when the caller does not hold it. Default false.
onOpenChange(open: boolean) => void—Called when it is pressed, or Escape puts it down.
earlybooleanfalseShows it while the answer is still arriving, for marks that land as they are found. Default false.

Citations.Dock

PropTypeDefaultDescription
labelstring'Where this comes from'What a screen reader calls the row. Default "Sources".

Citations.Flip

PropTypeDefaultDescription
flippedboolean—Whether the sources are showing, when the caller holds it.
defaultFlippedbooleanfalseWhether they show to begin with, when the caller does not hold it. Default false.
onFlippedChange(flipped: boolean) => void—Called when the bubble is turned over.
labelReactNode'Where this comes from'The line beside the marks. Default "Where this comes from".
backLabelReactNode'Back to the answer'The line on the back's way back. Default "Back to the answer".

Citations.Margin

PropTypeDefaultDescription
besideboolean—
widthnumber—
heightnumber—
placesRecord<string, { top: number; from: { x: number; y: number }; to: number }>—
widthNOTE_WIDTH,—
toplayout.places[source.id]?.top ?? 0,—
visibilitylayout.places[source.id] ? undefined : 'hidden',—

Every part also takes the props of the element it renders, and a className.

Notes

Accessibility

The tray's button says how many sources there are and which sites they are from, and whether it is open. While it is open the answer under it is out of the tab order, and while it is closed its rows are. Escape closes it and puts focus back on the button. The marks are decoration, and every row is a link.

A chip is a link named "Source:" and the titles. Its card opens on focus as well as on hover.

Reduced motion

With reduced motion turned on, the tray, the marks and the flip change at once, and a streamed answer arrives whole.

Streaming

stream plays back an answer that is already whole. For one still coming from a model, leave it off and render the text as it arrives; the content grows with it.

The content is marked busy until the last word, so a screen reader reads it once.

Quoting

kind says what the passage is: "Exact quote" for the site's own words, "Summary" for yours. In quote, words inside <mark> are set in the text's colour and the rest muted, so the part the sentence relies on stands out.

Your own layout

useCitations returns the sources, which of them are lit and a function to light them, for a part of your own inside Citations. CitationsProvider is the lighting without the layout.

Server Components

Citations is a client component. In a file that starts with "use client", write its parts with a dot, as on this page. A Server Component cannot read Citations.Status off the import, so each part is also exported by name: CitationsStatus is Citations.Status, and so on for the others.

import { Citations, CitationsStatus, CitationsBubble, CitationsContent, CitationsCite, CitationsCitation, CitationsTray, CitationsDock, CitationsFlip, CitationsMargin } from "@/components/panelui/citations"

On this page