Skip to content
Star

Citation hover card

Hover a citation to see the exact passage it came from. Free and MIT licensed, as HTML, a typed React component or an Astro component, in three styles with light and dark mode.

$npx designme add citation-hover-card
$npx shadcn@latest add https://designme.dev/r/shadcn/citation-hover-card.json

Need this designed into your product? Book a call

Teams that show the annual price first see higher paid conversion, and the effect is stronger when the monthly price stays visible beside it. Your own data shows the same pattern since the September update.

01

Install

Add it to your project with the CLI.

HTML, CSS and JS

$npx designme add citation-hover-card

React

$npx designme add citation-hover-card --react

Astro

$npx designme add citation-hover-card --astro

shadcn, React

$npx shadcn@latest add https://designme.dev/r/shadcn/citation-hover-card.json

shadcn, Astro

$npx shadcn@latest add https://designme.dev/r/shadcn/astro/citation-hover-card.json

The CLI copies the source into your project, so you own it and can change anything. Where each version lands, what it needs and the shadcn theme bridge: Installation.

02

About

What it is for and what it does.

Citation hover card renders an agent's answer with numbered citations in the text. Hover, focus or tap a number and a small card opens under it, or above it when there is no room below, with the source's site, title and the exact passage the claim relies on, with the key words highlighted.

  • When an agent answers from web pages or your own files and people should be able to check each claim.
  • When you want the evidence one hover away instead of in a list at the bottom.
  • When the important part of a long source is a single sentence you can highlight.
  • When citations need to work with a mouse, a keyboard and a touch screen.
03

Usage

Import it in React and drive it from your own state, or place it in an Astro page.

React

import { CitationHoverCard } from '@/components/designme/citation-hover-card/CitationHoverCard';

React example

The demo above as a React component, 30 lines you can copy.

'use client';
// The preview from designme.dev, rebuilt from the React component. Hover, focus or tap a citation to see its source.
import { useState } from 'react';
import { CitationHoverCard, type CitationHoverCardSource } from './CitationHoverCard';
import { useScript } from '../lib/useScript';

const SOURCES: CitationHoverCardSource[] = [
  { mark: 'B', color: 'var(--dm-av-b)', site: 'baymard.com', title: 'Pricing page UX benchmark', meta: 'Read 4 days ago',
    quote: <>Of 64 SaaS sites tested, those leading with the annual plan saw <mark>a 12 to 20% higher trial to paid rate</mark> than monthly first layouts.</> },
  { mark: 'C', color: 'var(--dm-av-r)', site: 'cxl.com', title: 'Price anchoring in plan selection', meta: 'Read 4 days ago',
    quote: <>When the monthly price stayed visible with a strike through, <mark>annual selection rose by a further 9 points</mark> in the anchored group.</> },
  { mark: 'C', color: 'var(--dm-av-l)', site: 'Drive', title: 'Q3 conversion export.csv', meta: 'Your file',
    quote: <>Rows 412 to 480: <mark>trial to paid moves from 18.6% to 26.3%</mark> between Sep 18 and Oct 17.</> }
];

export default function CitationHoverCardDemo() {
  // shows the first card once on its own, then puts it away, unless you are already pointing at a citation
  const [open, setOpen] = useState<number | null>();
  useScript(async ({ wait }) => {
    await wait(1400); setOpen(o => o === undefined ? 0 : o);
    await wait(2800); setOpen(o => o === 0 ? null : o);
  });
  return (
    <div style={{ width: '100%' }}>
      <CitationHoverCard sources={SOURCES} open={open} onOpenChange={setOpen}
        text="Teams that show the annual price first see higher paid conversion[1], and the effect is stronger when the monthly price stays visible beside it[2]. Your own data shows the same pattern since the September update[3]." />
    </div>
  );
}

Astro

In a page in src/pages. It plays the demo above; change its citation-hover-card.js to show your own data. Attributes like class go on its root element.

---
import CitationHoverCard from '../components/designme/citation-hover-card/CitationHoverCard.astro';
---
<CitationHoverCard />
<CitationHoverCard data-style="soft" class="my-class" />
04

Props

Everything CitationHoverCard takes.

PropTypeWhat it does
textrequiredstringThe answer. [n] cites source n; a blank line starts a new paragraph
sourcesrequiredCitationHoverCardSource[]
openLabelstringThe link in the card's corner
onOpenSource(source: CitationHoverCardSource, index: number) => voidCalled when the card's link is clicked, with the source and its index
opennumber | nullOpens a source's card from outside (0 is the first source), or closes it with null. Hover, focus and taps still work
onOpenChange(index: number | null) => voidCalled when a card opens or closes, with the source's index, or null
classNamestring
05

Code

The full source, as the CLI installs it.

CitationHoverCard.tsxReact · 161 lines
'use client';
import { Fragment, useEffect, useLayoutEffect, useRef, useState, type MouseEvent, type ReactNode } from 'react';
import { cx } from '../lib/cx';
import { Icon } from '../lib/icons';
import { avatarInk, mxIn, mxT } from '../lib/motion';
import '../designme.css';
import './citation-hover-card.css';

export interface CitationHoverCardSource {
  /** One or two letters on the source's coloured mark, like "B" */
  mark: string;
  /** The mark's fill: a colour dark enough for white letters, like '#2f4f9f', or an avatar colour like 'var(--dm-av-b)', which
      brings its own ink */
  color: string;
  /** Where it comes from, like "baymard.com" or "Drive" */
  site: string;
  title: string;
  /** The passage the answer relies on. Wrap the part that matters in <mark> */
  quote: ReactNode;
  /** The quiet line in the corner, like "Read 4 days ago" */
  meta?: string;
  /** Opens in a new tab from the card's link */
  href?: string;
}

export interface CitationHoverCardProps {
  /** The answer. [n] cites source n; a blank line starts a new paragraph */
  text: string;
  sources: CitationHoverCardSource[];
  /** The link in the card's corner */
  openLabel?: string;
  /** Called when the card's link is clicked, with the source and its index */
  onOpenSource?: (source: CitationHoverCardSource, index: number) => void;
  /** Opens a source's card from outside (0 is the first source), or closes it with null. Hover, focus and taps still work */
  open?: number | null;
  /** Called when a card opens or closes, with the source's index, or null */
  onOpenChange?: (index: number | null) => void;
  className?: string;
}

/** the open card: its source, its left edge, the top, bottom and middle of its citation (in the answer's box, and the top and
    bottom on screen), and a count of the times it was shown */
interface Shown { i: number; x: number; top: number; bottom: number; mid: number; vTop: number; vBottom: number; n: number }

/** An answer with numbered citations. Hovering, focusing or tapping one shows its source in a small card, under the citation
    when it fits there and above it when it doesn't, so the page never cuts it off. */
export function CitationHoverCard({ text, sources, openLabel = 'Open source', onOpenSource, open: openAt, onOpenChange, className }: CitationHoverCardProps) {
  const box = useRef<HTMLDivElement>(null);
  const card = useRef<HTMLDivElement>(null);
  // `at` is the open card; `last` keeps its content while it fades out
  const [at, setAt] = useState<Shown | null>(null);
  const [last, setLast] = useState(0);
  const cur = useRef<number | null>(null);
  const showT = useRef<ReturnType<typeof setTimeout>>(undefined), hideT = useRef<ReturnType<typeof setTimeout>>(undefined);
  // the first citation of each source, which a card opened from outside sits under
  const marks = useRef(new Map<number, HTMLButtonElement>());
  const told = useRef(onOpenChange);
  useEffect(() => { told.current = onOpenChange; });
  // the citation the card belongs to, whether the card should take the focus once it shows (Enter or Space), and whether a
  // focus coming back to the citation (from Escape) should leave the card shut
  const curEl = useRef<HTMLElement | null>(null), focusLink = useRef(false), back = useRef(false);

  const show = (i: number, el: HTMLElement) => {
    clearTimeout(hideT.current); if (cur.current === i) return;
    const b = box.current, c = card.current; if (!b || !c) return;
    const br = b.getBoundingClientRect(), cr = el.getBoundingClientRect();
    const x = Math.max(0, Math.min(cr.left - br.left, br.width - c.offsetWidth));
    cur.current = i; curEl.current = el; setLast(i); told.current?.(i);
    setAt(a => ({ i, x, top: cr.top - br.top, bottom: cr.bottom - br.top, mid: cr.left - br.left + cr.width / 2, vTop: cr.top, vBottom: cr.bottom, n: (a?.n ?? 0) + 1 }));
  };
  const hide = (now = false) => {
    clearTimeout(hideT.current); clearTimeout(showT.current);
    const go = () => { if (cur.current !== null) told.current?.(null); cur.current = null; setAt(a => a && { ...a, i: -1 }); };
    if (now) go(); else hideT.current = setTimeout(go, 140);
  };

  useEffect(() => {
    const down = (e: PointerEvent) => { const t = e.target as Element; if (!card.current?.contains(t) && !t.closest?.('.dm-chx-c')) hide(true); };
    const resize = () => hide(true);
    // Escape puts the card away while the focus or the pointer is on the answer, and leaves the focus where it was, or on
    // its citation when it was in the card
    const key = (e: KeyboardEvent) => { const b = box.current; if (e.key === 'Escape' && cur.current !== null && b && (b.contains(document.activeElement) || b.matches(':hover'))) {
      e.preventDefault(); const to = card.current?.contains(document.activeElement) ? curEl.current : null; hide(true); if (to) { back.current = true; to.focus({ preventScroll: true }); } } };
    document.addEventListener('pointerdown', down); document.addEventListener('keydown', key); addEventListener('resize', resize);
    return () => { document.removeEventListener('pointerdown', down); document.removeEventListener('keydown', key); removeEventListener('resize', resize); clearTimeout(hideT.current); clearTimeout(showT.current); };
  }, []);

  // once it has its content, it goes below its citation when it fits in the window there, and above it when it doesn't and
  // fits above (or has more room there). It grows out of its citation's middle and shrinks back into it (dm-mx-pop); moving on
  // to another citation while it shows, it glides there and eases to its new height as the new source fades in (motion pieces)
  const was = useRef<{ i: number; left: number; top: number; height: number } | null>(null), glide = useRef<Animation | null>(null);
  useLayoutEffect(() => {
    const c = card.current; if (!c || !at || at.i < 0) { was.current = null; return; }
    glide.current?.cancel();
    const h = c.offsetHeight, below = innerHeight - at.vBottom, above = at.vTop;
    const up = below < h + 12 && (above >= h + 12 || above > below), top = up ? at.top - h - 6 : at.bottom + 6;
    c.style.top = top + 'px';
    c.style.setProperty('--dm-origin', `${Math.round(at.mid - at.x)}px ${up ? '100%' : '0'}`);
    const prev = was.current; was.current = { i: at.i, left: at.x, top, height: h };
    if (!prev || prev.i === at.i || typeof c.animate !== 'function' || matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    const cs = getComputedStyle(c), pad = cs.boxSizing === 'border-box' ? 0 : parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom) + parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth);
    c.style.overflow = 'clip';
    const a = glide.current = c.animate([{ left: prev.left + 'px', top: prev.top + 'px', height: prev.height - pad + 'px' }, { left: at.x + 'px', top: top + 'px', height: h - pad + 'px' }],
      { duration: mxT(c, 't-in', 360), easing: mxT(c, 'ease-spring', 'ease') });
    a.onfinish = a.oncancel = () => { if (glide.current === a) { glide.current = null; c.style.overflow = ''; } };
    mxIn([c.querySelector('.dm-chx-in')], { y: 0, step: 0 });
  }, [at]);

  // opened with Enter or Space, the card takes the focus on its link once it shows
  useEffect(() => { if (focusLink.current && at && at.i >= 0) { focusLink.current = false; card.current?.querySelector<HTMLElement>('a')?.focus({ preventScroll: true }); } }, [at]);

  // a card opened or closed from outside
  useEffect(() => {
    if (openAt === undefined) return;
    if (openAt === null) { if (cur.current !== null) hide(true); return; }
    const el = marks.current.get(openAt); if (el && cur.current !== openAt) show(openAt, el);
  }, [openAt]); // eslint-disable-line react-hooks/exhaustive-deps

  const cite = (n: number, key: string) => {
    const i = n - 1;
    if (!sources[i]) return <Fragment key={key}>[{n}]</Fragment>;
    return (
      <button type="button" key={key} ref={el => { if (el && !marks.current.has(i)) marks.current.set(i, el); }} className={cx('dm-chx-c', at?.i === i && 'dm-on')} aria-label={`Source ${n}: ${sources[i].title}`}
        onPointerEnter={e => { if (e.pointerType === 'touch') return; const el = e.currentTarget; clearTimeout(showT.current); clearTimeout(hideT.current); showT.current = setTimeout(() => show(i, el), cur.current !== null ? 0 : 90); }}
        onPointerLeave={e => { if (e.pointerType === 'touch') return; clearTimeout(showT.current); hide(); }}
        onFocus={e => { if (back.current) { back.current = false; return; } show(i, e.currentTarget); }} onBlur={e => { if (!card.current?.contains(e.relatedTarget as Node)) hide(); }}
        // touch has no hover: a tap shows the card, the next tap anywhere else hides it. Enter or Space (a click with no
        // pointer) also puts the focus on the card's link, so the keyboard can reach it
        onClick={e => { const key = e.detail === 0; if (cur.current !== i) { focusLink.current = key; show(i, e.currentTarget); } else if (key) card.current?.querySelector<HTMLElement>('a')?.focus({ preventScroll: true }); }}>{n}</button>
    );
  };
  const paragraphs = text.split(/\n\s*\n/).map((p, k) => (
    <p key={k} className="dm-msg dm-chx-p">{p.split(/\[(\d+)\]/).map((part, j) => j % 2 ? cite(+part, k + '-' + j) : part)}</p>
  ));

  const s = sources[at && at.i >= 0 ? at.i : last];
  const open = !!at && at.i >= 0;
  const follow = (e: MouseEvent) => { if (!s?.href) e.preventDefault(); onOpenSource?.(s, sources.indexOf(s)); };
  return (
    <div data-dm="" ref={box} className={cx('dm-chx', className)}>
      {paragraphs}
      <div ref={card} className={cx('dm-chx-card dm-panel dm-mx-pop', open && 'dm-show')} role="dialog" aria-label="Source"
        style={at ? { left: at.x } : undefined}
        onPointerEnter={() => clearTimeout(hideT.current)} onPointerLeave={e => { if (e.pointerType !== 'touch') hide(); }}
        onBlur={e => { const t = e.relatedTarget as Node | null; if (cur.current !== null && !card.current?.contains(t) && t !== curEl.current) hide(); }}>
        {s && (
          <div className="dm-chx-in">
            <div className="dm-chx-sh"><span className="dm-fv" style={{ background: s.color, color: avatarInk(s.color) }}>{s.mark}</span><span>{s.site}</span></div>
            <div className="dm-chx-t">{s.title}</div>
            <div className="dm-chx-q">{s.quote}</div>
            <div className="dm-chx-f">
              <span>{s.meta}</span>
              <a href={s.href ?? '#'} target={s.href ? '_blank' : undefined} rel="noreferrer" onClick={follow}>{openLabel} <Icon name="ext" size="xs" /></a>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
citation-hover-card.cssReact · 37 lines
/* Generated from designme.dev by scripts/sync.mjs. Edit the site, then sync. */
/* ---------- Citation hover card ---------- */
/* an answer with numbered citations; pointing at one (or focusing or tapping it) shows its source in a card that opens over
   the stage from the citation, below it when there is room and above it when there isn't (placePop), so it is never cut off.
   No room is kept for the card under the answer (owner, 17 Nov): the answer sits centred on its own */
.dm-chx{position:relative;overflow:visible}
.dm-chx-p{line-height:1.8}
/* a citation is a small grey number; pointed at or open, it takes the accent tint with the accent's text (owner: highlights
   are the tint, never a solid accent fill) */
.dm-chx-c{display:inline-grid;place-items:center;min-width:18px;height:18px;padding:0 5px;margin:0 1px 0 3px;border-radius:calc(6px * var(--dm-rk-s,var(--dm-rk)));background:var(--dm-hover);color:var(--dm-fg2);font-size:11px;font-variant-numeric:tabular-nums;vertical-align:2px;transition:background .2s,color .2s}
.dm-chx-c.dm-on{background:var(--dm-accent-bg);color:var(--dm-accent-fg,var(--dm-accent))}
:root:not([data-style="soft"],[data-style="studio"]) .dm-chx-c.dm-on:not(:where([data-style="soft"],[data-style="soft"] *,[data-style="studio"],[data-style="studio"] *)){background:var(--dm-bp-pick)}
@media (hover:hover) and (pointer:fine){.dm-chx-c:hover{background:var(--dm-accent-bg);color:var(--dm-accent-fg,var(--dm-accent))}}
/* hidden as well as clear when put away, so Tab never lands on its link; it grows out of its citation's side */
/* (its motion, owner's trial of 26 Nov, is the core's .mx-pop: it grows out of its citation, the origin set on the citation's
   middle, from a short blur, and shrinks back into it quicker than it came. Moving on to another citation while it shows, it
   glides there and eases to its new height as the new source crossfades in) */
.dm-chx-card{position:absolute;left:0;top:0;width:min(290px,calc(100% - 8px));padding:var(--dm-s-4);pointer-events:none;z-index:4;box-shadow:var(--dm-shadow-pop)}
.dm-chx-card.dm-show{pointer-events:auto}
.dm-chx-sh{display:flex;align-items:center;gap:var(--dm-s-2);font-size:12px;color:var(--dm-muted)}
/* the source's mark is a vivid fill of its own with white letters (owner, 18 Nov), or an avatar colour with its own ink */
.dm-chx-sh .dm-fv{width:20px;height:20px;border-radius:calc(6px * var(--dm-rk-s,var(--dm-rk)));display:grid;place-items:center;font-size:9px;font-weight:500;color:#fff;flex:none}
.dm-chx-t{font-size:13px;font-weight:500;margin:var(--dm-s-2) 0 6px}
/* the passage, with a neutral rule down its left (lines are grey unless they mean something) and the part the answer relies
   on in the accent's tint */
.dm-chx-q{font-size:12.5px;line-height:1.55;color:var(--dm-fg2);padding-left:10px;box-shadow:inset 2px 0 0 var(--dm-faint)}
.dm-chx-q mark{background:var(--dm-sel);color:var(--dm-accent-fg,var(--dm-accent));border-radius:var(--dm-r-tiny,3px);padding:0 2px}
/* the source's foot sits under a hairline in Soft and Blueprint (owner, 21 Nov), 12px from it on each side */
.dm-chx-f{display:flex;align-items:center;justify-content:space-between;margin-top:var(--dm-s-3);padding-top:var(--dm-s-4);border-top:1px solid color-mix(in srgb,var(--dm-line) 50%,transparent);font-size:12px;color:var(--dm-muted)}
/* Studio: the source's foot is the card's off-white foot strip (owner, 21 Nov), its words 16px in */
:root[data-style="studio"] .dm-chx-f,:root [data-style="studio"] .dm-chx-f,:root [data-style="studio"].dm-chx-f{margin:var(--dm-s-3) -16px -16px;padding:calc(var(--dm-strip-y) + 5px) 16px;background:var(--dm-strip);border-top:1px solid var(--dm-line);border-radius:0 0 var(--dm-r-card) var(--dm-r-card);line-height:18px}
.dm-chx-f a{color:var(--dm-accent-fg,var(--dm-accent));display:inline-flex;align-items:center;gap:var(--dm-s-1);text-decoration:none}
@media (hover:hover) and (pointer:fine){.dm-chx-f a:hover{text-decoration:underline;text-underline-offset:2px}}
/* Studio (owner, 17 and 18 Nov): the card's content 16px from each edge; it scales and fades from its citation like Studio's
   menus, and the source's mark is Studio's neutral grey */
:root[data-style="studio"] .dm-chx-sh .dm-fv,:root [data-style="studio"] .dm-chx-sh .dm-fv,:root [data-style="studio"].dm-chx-sh .dm-fv{background:var(--dm-chip)!important;color:var(--dm-fg2)!important;box-shadow:inset 0 0 0 1px var(--dm-hair)}
CitationHoverCard.astroAstro · 27 lines
---
// Generated from designme.dev by scripts/sync.mjs. Edit the site, then sync.
// Citation hover card: Hover a citation to see the exact passage it came from.
// The markup, CSS and script are designme.dev's own, run by the shared core in ../core, which mounts the component when it scrolls
// into view and plays its demo. To show your own data, change citation-hover-card.js. The markup is kept exactly as it is (is:raw).
import type { HTMLAttributes } from 'astro/types';
import '../core/designme.css';
import './citation-hover-card.css';

export interface Props extends HTMLAttributes<'div'> {
  /** "soft" or "studio" draws it in that style. Leave it out for Blueprint, or for the style set on <html> (data-style="soft" or "studio") */
  'data-style'?: 'soft' | 'studio';
}
const { class: className, ...rest } = Astro.props;
---
<div class:list={['card', 'bare', className]} data-c="citation-hover" {...rest}>
  <div class="stage-in"><Fragment is:raw>
<div class="chx">
  <p class="msg chx-p">Teams that show the annual price first see higher paid conversion<button class="chx-c" data-i="0">1</button>, and the effect is stronger when the monthly price stays visible beside it<button class="chx-c" data-i="1">2</button>. Your own data shows the same pattern since the September update<button class="chx-c" data-i="2">3</button>.</p>
  <div class="chx-card panel keep mx-pop" role="dialog" aria-label="Source"><div class="chx-in"></div></div>
</div>
  </Fragment></div>
</div>
<script>
  import './citation-hover-card.js';
</script>
citation-hover-card.htmlHTML · 9 lines
<div class="card bare" data-c="citation-hover">
  <div class="stage-in">
    <div class="chx">
      <p class="msg chx-p">Teams that show the annual price first see higher paid conversion<button class="chx-c" data-i="0">1</button>, and the effect is stronger when the monthly price stays visible beside it<button class="chx-c" data-i="1">2</button>. Your own data shows the same pattern since the September update<button class="chx-c" data-i="2">3</button>.</p>
      <div class="chx-card panel keep mx-pop" role="dialog" aria-label="Source"><div class="chx-in"></div></div>
    </div>
  </div>
</div>
citation-hover-card.cssHTML · 36 lines
/* ---------- Citation hover card ---------- */
/* an answer with numbered citations; pointing at one (or focusing or tapping it) shows its source in a card that opens over
   the stage from the citation, below it when there is room and above it when there isn't (placePop), so it is never cut off.
   No room is kept for the card under the answer (owner, 17 Nov): the answer sits centred on its own */
.chx{position:relative;overflow:visible}
.chx-p{line-height:1.8}
/* a citation is a small grey number; pointed at or open, it takes the accent tint with the accent's text (owner: highlights
   are the tint, never a solid accent fill) */
.chx-c{display:inline-grid;place-items:center;min-width:18px;height:18px;padding:0 5px;margin:0 1px 0 3px;border-radius:calc(6px * var(--dm-rk-s,var(--dm-rk)));background:var(--dm-hover);color:var(--dm-fg2);font-size:11px;font-variant-numeric:tabular-nums;vertical-align:2px;transition:background .2s,color .2s}
.chx-c.on{background:var(--dm-accent-bg);color:var(--dm-accent-fg,var(--dm-accent))}
:root:not([data-style="soft"],[data-style="studio"]) .chx-c.on:not(:where([data-style="soft"],[data-style="soft"] *,[data-style="studio"],[data-style="studio"] *)){background:var(--dm-bp-pick)}
@media (hover:hover) and (pointer:fine){.chx-c:hover{background:var(--dm-accent-bg);color:var(--dm-accent-fg,var(--dm-accent))}}
/* hidden as well as clear when put away, so Tab never lands on its link; it grows out of its citation's side */
/* (its motion, owner's trial of 26 Nov, is the core's .mx-pop: it grows out of its citation, the origin set on the citation's
   middle, from a short blur, and shrinks back into it quicker than it came. Moving on to another citation while it shows, it
   glides there and eases to its new height as the new source crossfades in) */
.chx-card{position:absolute;left:0;top:0;width:min(290px,calc(100% - 8px));padding:var(--dm-s-4);pointer-events:none;z-index:4;box-shadow:var(--dm-shadow-pop)}
.chx-card.show{pointer-events:auto}
.chx-sh{display:flex;align-items:center;gap:var(--dm-s-2);font-size:12px;color:var(--dm-muted)}
/* the source's mark is a vivid fill of its own with white letters (owner, 18 Nov), or an avatar colour with its own ink */
.chx-sh .fv{width:20px;height:20px;border-radius:calc(6px * var(--dm-rk-s,var(--dm-rk)));display:grid;place-items:center;font-size:9px;font-weight:500;color:#fff;flex:none}
.chx-t{font-size:13px;font-weight:500;margin:var(--dm-s-2) 0 6px}
/* the passage, with a neutral rule down its left (lines are grey unless they mean something) and the part the answer relies
   on in the accent's tint */
.chx-q{font-size:12.5px;line-height:1.55;color:var(--dm-fg2);padding-left:10px;box-shadow:inset 2px 0 0 var(--dm-faint)}
.chx-q mark{background:var(--dm-sel);color:var(--dm-accent-fg,var(--dm-accent));border-radius:var(--dm-r-tiny,3px);padding:0 2px}
/* the source's foot sits under a hairline in Soft and Blueprint (owner, 21 Nov), 12px from it on each side */
.chx-f{display:flex;align-items:center;justify-content:space-between;margin-top:var(--dm-s-3);padding-top:var(--dm-s-4);border-top:1px solid color-mix(in srgb,var(--dm-line) 50%,transparent);font-size:12px;color:var(--dm-muted)}
/* Studio: the source's foot is the card's off-white foot strip (owner, 21 Nov), its words 16px in */
:root[data-style="studio"] .chx-f,:root [data-style="studio"] .chx-f,:root [data-style="studio"].chx-f{margin:var(--dm-s-3) -16px -16px;padding:calc(var(--dm-strip-y) + 5px) 16px;background:var(--dm-strip);border-top:1px solid var(--dm-line);border-radius:0 0 var(--dm-r-card) var(--dm-r-card);line-height:18px}
.chx-f a{color:var(--dm-accent-fg,var(--dm-accent));display:inline-flex;align-items:center;gap:var(--dm-s-1);text-decoration:none}
@media (hover:hover) and (pointer:fine){.chx-f a:hover{text-decoration:underline;text-underline-offset:2px}}
/* Studio (owner, 17 and 18 Nov): the card's content 16px from each edge; it scales and fades from its citation like Studio's
   menus, and the source's mark is Studio's neutral grey */
:root[data-style="studio"] .chx-sh .fv,:root [data-style="studio"] .chx-sh .fv,:root [data-style="studio"].chx-sh .fv{background:var(--dm-chip)!important;color:var(--dm-fg2)!important;box-shadow:inset 0 0 0 1px var(--dm-hair)}
citation-hover-card.jsHTML · 68 lines
DM.def('citation-hover', (r, c) => {
  const S = [
    ['B','var(--dm-av-b)','baymard.com','Pricing page UX benchmark','Of 64 SaaS sites tested, those leading with the annual plan saw <mark>a 12 to 20% higher trial to paid rate</mark> than monthly first layouts.','Read 4 days ago'],
    ['C','var(--dm-av-r)','cxl.com','Price anchoring in plan selection','When the monthly price stayed visible with a strike through, <mark>annual selection rose by a further 9 points</mark> in the anchored group.','Read 4 days ago'],
    ['CSV','var(--dm-av-l)','Drive','Q3 conversion export.csv','Rows 412 to 480: <mark>trial to paid moves from 18.6% to 26.3%</mark> between Sep 18 and Oct 17.','Your file']
  ];
  const card = $('.chx-card', r), inn = $('.chx-in', r), box = $('.chx', r), cites = $$('.chx-c', r);
  let cur = null, hideT, showT, back = false, glide = null;
  /* it opens below its citation when it fits there and above it when it doesn't (placePop), so the stage or the page never cuts
     it off, and it stays inside the answer's column; it grows out of the citation's middle (--origin) */
  function place(b){
    placePop(b, card);
    const x = Math.max(0, Math.min(parseFloat(card.style.left) || 0, box.clientWidth - card.offsetWidth)); card.style.left = x + 'px';
    const bb = b.getBoundingClientRect(), kb = box.getBoundingClientRect(), k = kb.width / box.offsetWidth || 1;
    card.style.setProperty('--dm-origin', `${Math.round((bb.left + bb.width / 2 - kb.left) / k - x)}px ${/^bottom/.test(card.style.getPropertyValue('--dm-origin')) ? '100%' : '0'}`);
  }
  /* the card exists only while a citation (or the card itself) is under the pointer */
  function show(b){
    clearTimeout(hideT); if (cur === b) return;
    const s = S[+b.dataset.i], moving = !!cur && card.classList.contains('show') && !REDUCE; cur = b;
    cites.forEach(x => x.classList.toggle('on', x === b));
    const fill = () => { inn.innerHTML = `<div class="chx-sh"><span class="fv" style="background:${s[1]};color:${s[1].replace(')', '-ink)')}">${s[0][0]}</span><span>${s[2]}</span></div><div class="chx-t">${s[3]}</div><div class="chx-q">${s[4]}</div><div class="chx-f"><span>${s[5]}</span><a href="#" onclick="return false">Open source ${I('ext','xs')}</a></div>`; };
    if (glide){ glide.cancel(); glide = null; }
    /* showing: it grows out of its citation where it will sit (.mx-pop). Already showing for another citation, it moves on
       there: the old source fades out, and the card glides to its new place and eases to its new height as the new one fades in
       (owner's trial, 26 Nov) */
    if (!moving){ (inn._mx || []).forEach(a => a.cancel()); fill(); place(b); card.classList.add('show'); return; }
    const was = { left:card.offsetLeft, top:card.offsetTop, height:card.offsetHeight };
    mxOut(inn, { ms:80, y:0 }).then(() => {
      if (cur !== b) return;
      fill(); place(b);
      const cs = getComputedStyle(card), pad = cs.boxSizing === 'border-box' ? 0 : parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom) + parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth);
      const to = { left:card.offsetLeft, top:card.offsetTop, height:card.offsetHeight }, px = o => ({ left:o.left + 'px', top:o.top + 'px', height:o.height - pad + 'px' });
      card.style.overflow = 'clip';
      const a = glide = card.animate([px(was), px(to)], { duration:mxT(card, '--dm-t-in', 360), easing:mxT(card, '--dm-ease-spring', 'ease') });
      a.onfinish = a.oncancel = () => { if (glide === a) glide = null; if (!glide) card.style.overflow = ''; };
      mxIn(inn, { y:0, step:0 });
    });
  }
  function hide(now){
    clearTimeout(hideT); clearTimeout(showT);
    const go = () => { if (glide){ glide.cancel(); glide = null; } card.classList.remove('show'); cur = null; cites.forEach(x => x.classList.remove('on')); };
    if (now) go(); else hideT = setTimeout(go, 140);
  }
  /* pointing at a citation shows its card, leaving it (and the card) hides it; focus shows it too, so the keyboard gets the
     same card. Touch has no hover: a tap shows the card, the next tap anywhere else hides it */
  const hover = e => e.pointerType !== 'touch';
  cites.forEach(b => {
    c.on(b, 'pointerenter', e => { if (!hover(e)) return; clearTimeout(showT); clearTimeout(hideT); showT = setTimeout(() => show(b), cur ? 0 : 90); });
    c.on(b, 'pointerleave', e => { if (!hover(e)) return; clearTimeout(showT); hide(); });
    c.on(b, 'focus', () => { if (back){ back = false; return; } show(b); }); c.on(b, 'blur', e => { if (!card.contains(e.relatedTarget)) hide(); });
    // Enter or Space opens the card with the focus on its link, so the keyboard can reach it; Escape brings the focus back
    c.on(b, 'click', e => { if (cur !== b) show(b); if (e.isTrusted && !e.detail){ const a = $('a', card); if (a) a.focus({ preventScroll:true }); } });
  });
  c.on(card, 'pointerenter', () => clearTimeout(hideT));
  c.on(card, 'pointerleave', e => { if (hover(e)) hide(); });
  c.on(card, 'focusout', e => { if (cur && !card.contains(e.relatedTarget) && e.relatedTarget !== cur) hide(); });
  /* Escape puts the card away while the focus or the pointer is on the answer, and leaves the focus where it was, or on its
     citation when it was in the card */
  c.on(document, 'keydown', e => { if (e.key === 'Escape' && cur && (box.contains(document.activeElement) || box.matches(':hover'))){ e.preventDefault(); const to = card.contains(document.activeElement) && cur; hide(true); if (to){ back = true; to.focus({ preventScroll:true }); } } });
  c.on(document, 'pointerdown', e => { if (!card.contains(e.target) && !e.target.closest('.chx-c')) hide(true); });
  c.on(window, 'resize', e => { if (e.isTrusted) hide(true); });
  c.offs.push(() => { clearTimeout(hideT); clearTimeout(showT); });
  // the preview shows one card on its own after the entrance, then puts it away, unless you are already pointing at a citation
  let mine = false; c.on(r, 'pointerover', e => { if (e.isTrusted) mine = true; }, true);
  c.run(async () => { await c.wait(1400); if (mine || cur) return; show(cites[0]); await c.wait(2800); if (!mine && cur === cites[0]) hide(); });
});
06

Questions

What people ask about it.

How do I mark which part of the source backs up the claim?
quote accepts React nodes, so wrap the passage that matters in a <mark> element. The card styles it as a highlight.
What happens if the text cites a number with no source?
A marker like [4] with no fourth source is left as plain text, so it never opens an empty card.
What if a source has no URL, like a private file?
Leave out href. The link then stays on the page and only calls onOpenSource, so you can open the file in your own viewer.
07

More in Sources and output

What the agent read, what it produced and where each answer came from.

Terminal streamShell commands the agent runs, with their output as it streams in.
Source stackEverything the agent read, folded into one quiet pill.