Skip to content
Browse documentation

A long rich-markdown AI response built for phones and side panels: folds with hidden section jump pills, inline reasoning, a sources drawer and a sticky Collapse pill.

Used forMobile AI chat appsSide-panel copilotsResearch & citation answersSupport & help-desk threads

Part of AI chat components for React, the parts of a chat in the order they appear.

Install with the shadcn CLI

$ npx shadcn@latest add @hairline/expandable-answer

Older shadcn CLI, or a network that blocks ui.shadcn.com? Install by URL: shadcn add https://hairlineui.com/r/expandable-answer.json. More

Templates

Need the whole page?

65 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 8 are free.

Where it’s used

  • Mobile AI chat apps

    Keep 500-word answers scannable on 375px screens with section jump chips and a sticky Collapse pill.

  • Side-panel copilots

    Fit rich tables, code blocks, reasoning traces and verified sources inside a 360px workspace drawer.

  • Research & citation answers

    Let readers tap inline [1] markers on touchscreens to inspect source quotes inside the same card.

  • Support & help-desk threads

    Show the opening verdict immediately while tucking step-by-step guides and follow-ups cleanly beneath the fold.

What it handles for you

A long AI response on a phone needs more than line-clamp. It has to fold rich Markdown without clipping tables, tell the reader what is hidden, keep Collapse within thumb reach, and restore scroll position when folded back.

Instead of wiring upa collapsible markdown response cardread more / show less height animationhidden heading jump chipsa sticky mobile collapse baran inline reasoning trace headera sources drawer and follow-up list
  1. Auto-folds only long answers

    Measures your rendered Markdown with ResizeObserver and skips the veil and Expand bar whenever a short answer already fits.

  2. Hidden headings become jump chips

    Scans h1–h4 headings below the fold automatically (or reads your sections prop) so tapping one unfolds straight to that section.

  3. Interruptible spring unfold

    Drives height with createSpring so tapping Expand and Collapse mid-flight reverses smoothly without snapping, then releases to auto height once open.

  4. Sticky mobile Collapse pill

    While scrolled deep inside an expanded reply, a hairline Collapse + Sources pill stays in reach and ducks away as soon as the footer enters view.

  5. Touch-friendly inline citations

    Drop AnswerCite inside any Markdown renderer: tapping [1] opens the card’s Sources drawer in place and spotlights that source.

  6. Reasoning, actions and follow-ups in one card

    Live rolling thinking timer, Copy with a drawn check, thumbs feedback, streaming/error recovery and follow-ups share one hairline frame.

Overview

Long AI answers break mobile chat threads and narrow sidebars: either a 600-word reply takes over four screens, or a naive "Read more" clamp cuts off tables mid-row and hides what is inside. Expandable answer wraps your own Markdown renderer in one hairline surface. When an answer overflows, it holds at a calm preview height behind an optical fade veil and surfaces the hidden headings right above the fold edge as clickable jump chips, beside a rolling section or word count. Tap any section chip and a spring unfolds the response straight to that heading; tap Expand and the full reply opens in place. While reading deep inside an expanded reply, a compact Collapse and Sources pill floats at the bottom edge of the viewport and ducks away the moment the real footer enters view. Collapsing from halfway down gently keeps the card header in view so you never lose your place in the thread.

States

folded
When the rendered body exceeds collapsedHeight + collapseThreshold, it clips behind a card-matched optical fade veil with clickable hidden section chips and a rolling +N sections/words count.
expanding / expanded
A spring (stiffness 250, damping 28) unfolds the body cleanly, dissolves the veil and folds away the dock, then releases to height: auto and overflow: visible so sticky Collapse works natively.
sticky return pill
When expanded and scrolled so the bottom footer is off screen, a compact hairline Collapse + Sources pill rises at the bottom edge (220ms) and hides before overlapping the footer.
reasoning
While status is "running", a sheen sweeps across "Thinking" with rolling elapsed seconds; when done it morphs to "Thought for Xs" and folds cleanly after 750ms.
sources
Clicking the stacked dot pill or any inline AnswerCite unfolds a responsive 1-to-2 column source drawer inside the card (420ms) and highlights the chosen citation.
streaming / error
Shows a live Writing indicator and hairline scan line while streaming, folds follow-ups until done, and offers an inline Retry bar on interruption.

Usage

usage.tsx
import { ExpandableAnswer, AnswerProse, AnswerCite } from "@/components/expandable-answer";<ExpandableAnswer  reasoning={{ steps: [{ label: "Checked 12-month retention math" }], durationMs: 4000 }}  sources={[{ title: "PostgreSQL Partitioning", url: "https://www.postgresql.org/docs/current/ddl-partitioning.html", snippet: "Range partitioning keeps active indexes warm." }]}  followUps={["Estimate ClickHouse cost at 200M rows"]}  copyText={rawMarkdown}  onFollowUp={ask}>  <AnswerProse>    <p>Move high-volume analytics to ClickHouse <AnswerCite index={1} />.</p>    <h2>Benchmarks</h2>    <p>Detailed comparison…</p>  </AnswerProse></ExpandableAnswer>

Depends on lucide-react, installed for you by the CLI along with the keyframes it needs.

Works with

With Vercel AI SDK and react-markdown

Pass any Markdown renderer as children. Map reasoning parts, source URLs and suggested follow-ups directly from your message.

example.tsx
"use client";import ReactMarkdown from "react-markdown";import { useChat } from "@ai-sdk/react";import type { UIMessage } from "ai";import { ExpandableAnswer, AnswerProse } from "@/components/expandable-answer";export function ChatAnswer({ message, isLast }: { message: UIMessage; isLast: boolean }) {  const { status, sendMessage, regenerate } = useChat();  const text = message.parts.filter((p) => p.type === "text").map((p) => p.text).join("");  const reasoningParts = message.parts.filter((p) => p.type === "reasoning");  const sources = message.parts    .filter((p) => p.type === "source-url")    .map((s) => ({ title: s.title ?? s.url, url: s.url }));  const live = isLast && status === "streaming";  const answerStatus = live ? "streaming" : isLast && status === "error" ? "error" : "done";  return (    <ExpandableAnswer      status={answerStatus}      copyText={text}      onRegenerate={() => regenerate({ messageId: message.id })}      onRetry={() => regenerate({ messageId: message.id })}      onFollowUp={(question) => sendMessage({ text: question })}      sources={sources}      reasoning={        reasoningParts.length          ? {              status: live ? "running" : "done",              steps: reasoningParts                .flatMap((r) => r.text.split(/(?<=[.!?])\s+/))                .filter(Boolean)                .map((label) => ({ label })),            }          : undefined      }    >      <AnswerProse>        <ReactMarkdown          components={{            table: ({ children, ...tableProps }) => (              <div>                <table {...tableProps}>{children}</table>              </div>            ),          }}        >          {text}        </ReactMarkdown>      </AnswerProse>    </ExpandableAnswer>  );}

Props

children
ReactNode
Your rendered Markdown, MDX or JSX. Wrap in AnswerProse for built-in hairline headings, tables, code blocks and blockquotes.
reasoning
ExpandableReasoning
Optional collapsible reasoning header and steps: { steps, status?, label?, doneLabel?, startedAt?, durationMs?, onStepClick? }.
sources= []
ExpandableSource[]
Sources for the dot stack, inline AnswerCite pills and expandable source cards: { title, url, snippet?, icon?, color? }.
followUps= []
string[]
Suggested next questions shown beneath the answer once streaming finishes.
onFollowUp
(question: string) => void
Called when a follow-up question is tapped.
sections
ExpandableSection[]
Optional explicit jump chips ({ id, label, hidden? }). When omitted, headings (h1–h4) below the fold are detected automatically.
collapsedHeight= 236
number
Preview height in pixels when folded.
collapseThreshold= 56
number
Minimum overflow beyond collapsedHeight before folding activates, so short answers never show a veil.
expanded / defaultExpanded / onExpandedChange= false
boolean / (open: boolean) => void
Controlled or uncontrolled expanded state.
reasoningOpen / defaultReasoningOpen / onReasoningOpenChange
boolean / (open: boolean) => void
Controlled or uncontrolled reasoning disclosure state.
sourcesOpen / defaultSourcesOpen / onSourcesOpenChange= false
boolean / (open: boolean) => void
Controlled or uncontrolled sources drawer state.
stickyCollapse= true
boolean
Pins a compact Collapse + Sources pill at the bottom edge while reading deep inside a long expanded reply.
status= "done"
"streaming" | "done" | "stopped" | "error"
Current generation state; shows a live caret, stopped note or inline Retry bar.
copyText / onRegenerate / onRetry
string / () => void
Action callbacks for Copy, Regenerate and interrupted Retry.
feedback / defaultFeedback / onFeedback= null
"up" | "down" | null
Controlled or uncontrolled helpful / not helpful rating.
label / meta / labels
string / ReactNode / ExpandableAnswerLabels
Header label when no reasoning is passed, custom right-side metadata, and button label overrides.

Accessibility and motion

  • Uses container queries (@container) on the card root so narrow 320px–375px phone threads and sidebars stack cleanly regardless of screen width.
  • Folded reasoning steps, the fold dock, hidden sticky pill and closed sources drawer all carry the inert attribute so keyboard focus never enters hidden controls.
  • Collapsing from partway down an expanded reply checks whether the card header has scrolled out of view and gently brings it back, avoiding jarring scroll jumps.
  • AnswerCite connects to the nearest ExpandableAnswer via React context, making numbered [1] citations tap-friendly on touchscreens without hover tooltips.
  • Respects prefers-reduced-motion: disables spring height travel, sheen sweeps, heading highlight flashes and icon blur swaps while keeping every state change intact.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

The CLI also installs Number roll, Text morph.

Source

"use client";import * as React from "react";import { AlertCircle, ChevronDown, ChevronUp } from "lucide-react";import { NumberRoll } from "./number-roll";import { TextMorph } from "./text-morph";import {  createSpring,  EASE_OUT,  INTERACTION_FOCUS,  INTERACTION_PRESS,  useInteractionReducedMotion,  type Spring,} from "./ui-interaction-motion";import {  AnswerFooterBar,  CHART_TONES,  FollowUpList,  ReasoningBand,  SHEEN,  SourceDotStack,  SourcesDrawer,  sourceColor,  type ExpandableAnswerStatus,  type ExpandableFeedback,  type ExpandableReasoning,  type ExpandableReasoningStatus,  type ExpandableReasoningStep,  type ExpandableReasoningStepStatus,  type ExpandableSection,  type ExpandableSource,} from "./expandable-answer-parts";/* ───────────────────────────────────────────────────────── * EXPANDABLE ANSWER: a long rich-markdown AI response built * for phones, side panels and dense threads * *   folded     long answers preview behind an optical fade *              veil; hidden headings surface as clickable *              jump chips right above the fold edge *   unfold     a velocity-preserving spring opens the body *              in place (tap a section chip to unfold and *              glide straight to that heading) *   reading    once expanded past the viewport, a hairline *              sticky pill floats at the bottom edge so you *              can collapse or jump to sources without *              scrolling back; it ducks away the moment the *              real footer enters view *   sources    inline [1] citations and the stacked dot pill *              open a responsive source verification drawer *              inside the same hairline surface * ───────────────────────────────────────────────────────── */export type {  ExpandableAnswerStatus,  ExpandableFeedback,  ExpandableReasoning,  ExpandableReasoningStatus,  ExpandableReasoningStep,  ExpandableReasoningStepStatus,  ExpandableSection,  ExpandableSource,};interface ExpandableAnswerContextValue {  sources: ExpandableSource[];  activeSourceIndex: number | null;  sourcesOpen: boolean;  expanded: boolean;  openSource: (index: number) => void;  setExpanded: (next: boolean) => void;}const ExpandableAnswerContext = React.createContext<ExpandableAnswerContextValue | null>(null);export function useExpandableAnswer() {  return React.useContext(ExpandableAnswerContext);}export interface ExpandableAnswerLabels {  expand?: string;  expandShort?: string;  collapse?: string;  followUps?: string;  jumpTo?: string;}export interface ExpandableAnswerProps extends Omit<React.HTMLAttributes<HTMLElement>, "title"> {  /** Any rich markdown renderer (<ReactMarkdown>…</ReactMarkdown>), MDX or JSX. */  children: React.ReactNode;  /** Optional collapsible reasoning trace docked cleanly in the header rail. */  reasoning?: ExpandableReasoning;  /** Verified sources displayed as a dot stack and inline expandable drawer. */  sources?: ExpandableSource[];  /** Suggested next questions shown once the response settles. */  followUps?: string[];  onFollowUp?: (question: string) => void;  /** Optional heading list for section jump chips; auto-detected from h1-h4 headings if omitted. */  sections?: ExpandableSection[];  /** Header label shown on the left when no reasoning is provided (e.g. model name). */  label?: string;  /** Right-hand header metadata (e.g. reading time or model badge). Auto-calculated reading time if omitted. */  meta?: React.ReactNode;  status?: ExpandableAnswerStatus;  onRetry?: () => void;  /** Plain text or markdown copied by the Copy button. Omit to hide Copy. */  copyText?: string;  onRegenerate?: () => void;  feedback?: ExpandableFeedback;  defaultFeedback?: ExpandableFeedback;  onFeedback?: (value: ExpandableFeedback) => void;  onSourceSelect?: (source: ExpandableSource, index: number) => void;  /** Visible preview height in px when collapsed. Short answers never fold. */  collapsedHeight?: number;  /** Minimum overflow (px) beyond collapsedHeight required before folding activates. */  collapseThreshold?: number;  expanded?: boolean;  defaultExpanded?: boolean;  onExpandedChange?: (expanded: boolean) => void;  reasoningOpen?: boolean;  defaultReasoningOpen?: boolean;  onReasoningOpenChange?: (open: boolean) => void;  sourcesOpen?: boolean;  defaultSourcesOpen?: boolean;  onSourcesOpenChange?: (open: boolean) => void;  /** Keep a compact floating Collapse pill pinned while reading deep inside a long expanded answer. */  stickyCollapse?: boolean;  labels?: ExpandableAnswerLabels;}interface ScannedHeading {  id: string;  label: string;  hidden: boolean;  domIndex: number;}interface ScanMeta {  fullHeight: number;  totalWords: number;  hiddenWords: number;  headings: ScannedHeading[];}const EMPTY_SOURCES: ExpandableSource[] = [];const EMPTY_FOLLOW_UPS: string[] = [];const HEADING_SELECTOR = "h1, h2, h3, h4, [data-answer-section]";const BODY_SPRING = { stiffness: 250, damping: 28, mass: 1 };function countWords(text: string): number {  const trimmed = text.trim();  return trimmed ? trimmed.split(/\s+/).length : 0;}function sameScan(a: ScanMeta | null, b: ScanMeta): boolean {  if (!a) return false;  if (a.fullHeight !== b.fullHeight || a.totalWords !== b.totalWords || a.hiddenWords !== b.hiddenWords) return false;  if (a.headings.length !== b.headings.length) return false;  for (let i = 0; i < a.headings.length; i++) {    if (      a.headings[i].id !== b.headings[i].id ||      a.headings[i].label !== b.headings[i].label ||      a.headings[i].hidden !== b.headings[i].hidden ||      a.headings[i].domIndex !== b.headings[i].domIndex    ) {      return false;    }  }  return true;}function scanBody(container: HTMLElement, collapsedHeight: number): ScanMeta {  const fullHeight = Math.ceil(container.scrollHeight);  const baseRect = container.getBoundingClientRect();  const totalWords = countWords(container.textContent ?? "");  const nodes = Array.from(container.querySelectorAll<HTMLElement>(HEADING_SELECTOR));  const headings: ScannedHeading[] = [];  nodes.forEach((node, domIndex) => {    const label = (node.dataset.answerSection || node.textContent || "").trim();    if (!label) return;    const top = node.getBoundingClientRect().top - baseRect.top;    headings.push({      id: node.id || `section-${domIndex}`,      label,      hidden: top >= collapsedHeight - 36,      domIndex,    });  });  // Estimate hidden words from top-level prose blocks that sit past the fold line.  const proseRoot = container.firstElementChild instanceof HTMLElement ? container.firstElementChild : container;  let hiddenWords = 0;  for (const child of Array.from(proseRoot.children)) {    if (!(child instanceof HTMLElement)) continue;    const rect = child.getBoundingClientRect();    const relTop = rect.top - baseRect.top;    const relBottom = rect.bottom - baseRect.top;    if (relBottom <= collapsedHeight - 16) continue;    const w = countWords(child.textContent ?? "");    if (relTop >= collapsedHeight - 16) {      hiddenWords += w;    } else if (rect.height > 0) {      const hiddenFrac = Math.min(1, Math.max(0, (relBottom - (collapsedHeight - 16)) / rect.height));      hiddenWords += Math.round(w * hiddenFrac);    }  }  return { fullHeight, totalWords, hiddenWords, headings };}export function ExpandableAnswer({  children,  reasoning,  sources = EMPTY_SOURCES,  followUps = EMPTY_FOLLOW_UPS,  onFollowUp,  sections,  label,  meta,  status = "done",  onRetry,  copyText,  onRegenerate,  feedback,  defaultFeedback = null,  onFeedback,  onSourceSelect,  collapsedHeight = 236,  collapseThreshold = 56,  expanded: controlledExpanded,  defaultExpanded = false,  onExpandedChange,  reasoningOpen: controlledReasoningOpen,  defaultReasoningOpen,  onReasoningOpenChange,  sourcesOpen: controlledSourcesOpen,  defaultSourcesOpen = false,  onSourcesOpenChange,  stickyCollapse = true,  labels,  className = "",  ...props}: ExpandableAnswerProps) {  const reduced = useInteractionReducedMotion();  const bodyId = React.useId();  const sourcesPanelId = React.useId();  const cardRef = React.useRef<HTMLElement>(null);  const bodyClipRef = React.useRef<HTMLDivElement>(null);  const bodyInnerRef = React.useRef<HTMLDivElement>(null);  const footerRef = React.useRef<HTMLDivElement>(null);  const [ownExpanded, setOwnExpanded] = React.useState(defaultExpanded);  const expanded = controlledExpanded ?? ownExpanded;  const reasoningRunning = reasoning?.status === "running";  const reasoningError = reasoning?.status === "error";  const [autoReasoningOpen, setAutoReasoningOpen] = React.useState(Boolean(reasoningRunning || reasoningError));  const [userReasoningOpen, setUserReasoningOpen] = React.useState<boolean | undefined>(defaultReasoningOpen);  const [seenReasoningTrigger, setSeenReasoningTrigger] = React.useState(Boolean(reasoningRunning || reasoningError));  if (Boolean(reasoningRunning || reasoningError) !== seenReasoningTrigger) {    const next = Boolean(reasoningRunning || reasoningError);    setSeenReasoningTrigger(next);    if (next) setAutoReasoningOpen(true);  }  React.useEffect(() => {    if (!reasoning || reasoningRunning || reasoningError) return;    const timer = window.setTimeout(() => setAutoReasoningOpen(false), 750);    return () => window.clearTimeout(timer);  }, [reasoning, reasoningRunning, reasoningError]);  const reasoningOpen = controlledReasoningOpen ?? userReasoningOpen ?? autoReasoningOpen;  const [ownSourcesOpen, setOwnSourcesOpen] = React.useState(defaultSourcesOpen);  const sourcesOpen = controlledSourcesOpen ?? ownSourcesOpen;  const [activeSourceIndex, setActiveSourceIndex] = React.useState<number | null>(null);  const [announcement, setAnnouncement] = React.useState("");  const [scan, setScan] = React.useState<ScanMeta | null>(null);  const [bodyInView, setBodyInView] = React.useState(false);  const [footerInView, setFooterInView] = React.useState(true);  const canCollapse = scan !== null && scan.fullHeight > collapsedHeight + collapseThreshold;  const isFolded = canCollapse && !expanded;  // Measure the full rich markdown body and auto-detect hidden headings via ResizeObserver.  React.useLayoutEffect(() => {    const el = bodyInnerRef.current;    if (!el) return;    const measure = () => {      const next = scanBody(el, collapsedHeight);      setScan((prev) => (sameScan(prev, next) ? prev : next));    };    const observer = new ResizeObserver(measure);    observer.observe(el);    return () => observer.disconnect();  }, [collapsedHeight]);  // Spring-driven height unfold/fold: interruptible mid-flight, releases to height:auto & overflow:visible once open.  const springRef = React.useRef<Spring | null>(null);  const expandedStateRef = React.useRef(expanded);  const hasMountedFoldRef = React.useRef(false);  const targetExpandedRef = React.useRef(expanded);  React.useLayoutEffect(() => {    const clip = bodyClipRef.current;    const inner = bodyInnerRef.current;    if (!clip || !inner) return;    targetExpandedRef.current = expanded;    if (!springRef.current) {      springRef.current = createSpring(        collapsedHeight,        BODY_SPRING,        () => {          const s = springRef.current;          const box = bodyClipRef.current;          if (!s || !box) return;          const v = Math.max(0, s.get());          const target = s.getTarget();          const settled = Math.abs(v - target) < 0.75 && Math.abs(s.getVelocity()) < 8;          if (settled && targetExpandedRef.current) {            box.style.height = "";            box.style.overflow = "visible";          } else {            box.style.height = `${v.toFixed(1)}px`;            box.style.overflow = "clip";          }        },        0.5,      );    }    const spring = springRef.current;    if (!canCollapse) {      spring.stop();      clip.style.height = "";      clip.style.overflow = "visible";      expandedStateRef.current = expanded;      return;    }    const changed = hasMountedFoldRef.current && expandedStateRef.current !== expanded;    expandedStateRef.current = expanded;    const currentHeight = clip.getBoundingClientRect().height;    const targetHeight = expanded ? Math.ceil(inner.scrollHeight) : collapsedHeight;    if (!hasMountedFoldRef.current) {      hasMountedFoldRef.current = true;      spring.stop();      if (expanded) {        clip.style.height = "";        clip.style.overflow = "visible";      } else if (!reduced && currentHeight > collapsedHeight + 8) {        clip.style.overflow = "clip";        clip.style.height = `${currentHeight.toFixed(1)}px`;        spring.jump(currentHeight);        spring.set(collapsedHeight);      } else {        clip.style.height = `${collapsedHeight}px`;        clip.style.overflow = "clip";      }      return;    }    if (!changed) {      if (expanded && clip.style.height !== "") {        // Content grew while the unfold spring is still mid-flight: chase the new target cleanly.        spring.set(Math.ceil(inner.scrollHeight));      } else if (!expanded && Math.abs(spring.getTarget() - collapsedHeight) > 0.5) {        clip.style.height = `${collapsedHeight}px`;        clip.style.overflow = "clip";      }      return;    }    if (reduced) {      spring.stop();      if (expanded) {        clip.style.height = "";        clip.style.overflow = "visible";      } else {        clip.style.height = `${collapsedHeight}px`;        clip.style.overflow = "clip";      }      return;    }    clip.style.overflow = "clip";    clip.style.height = `${currentHeight.toFixed(1)}px`;    spring.jump(currentHeight);    spring.set(targetHeight);  }, [expanded, canCollapse, collapsedHeight, scan?.fullHeight, reduced]);  React.useEffect(() => {    return () => {      springRef.current?.stop();    };  }, []);  // Track when the expanded body is on screen and its real bottom footer is still below the fold.  React.useEffect(() => {    if (!stickyCollapse || !expanded || !canCollapse) return;    const bodyEl = bodyInnerRef.current;    const footerEl = footerRef.current;    if (!bodyEl || !footerEl) return;    const bodyObs = new IntersectionObserver(      ([entry]) => setBodyInView(entry.isIntersecting),      { threshold: 0 },    );    const footerObs = new IntersectionObserver(      ([entry]) => setFooterInView(entry.isIntersecting),      { rootMargin: "0px 0px -12px 0px", threshold: 0 },    );    bodyObs.observe(bodyEl);    footerObs.observe(footerEl);    return () => {      bodyObs.disconnect();      footerObs.disconnect();    };  }, [stickyCollapse, expanded, canCollapse]);  const setExpandedValue = React.useCallback(    (next: boolean, keepHeaderInView = false) => {      if (!next && keepHeaderInView && cardRef.current) {        const top = cardRef.current.getBoundingClientRect().top;        if (top < 16) {          cardRef.current.scrollIntoView({ behavior: reduced ? "auto" : "smooth", block: "nearest" });        }      }      if (controlledExpanded === undefined) setOwnExpanded(next);      onExpandedChange?.(next);      setAnnouncement(next ? "Answer expanded" : "Answer collapsed");    },    [controlledExpanded, onExpandedChange, reduced],  );  const toggleReasoning = React.useCallback(() => {    const next = !reasoningOpen;    if (controlledReasoningOpen === undefined) setUserReasoningOpen(next);    onReasoningOpenChange?.(next);  }, [reasoningOpen, controlledReasoningOpen, onReasoningOpenChange]);  const setSourcesValue = React.useCallback(    (next: boolean) => {      if (controlledSourcesOpen === undefined) setOwnSourcesOpen(next);      onSourcesOpenChange?.(next);    },    [controlledSourcesOpen, onSourcesOpenChange],  );  const openSource = React.useCallback(    (index: number) => {      if (index < 0 || index >= sources.length) return;      setActiveSourceIndex(index);      if (!sourcesOpen) setSourcesValue(true);      setAnnouncement(`Showing source ${index + 1}: ${sources[index].title}`);    },    [sources, sourcesOpen, setSourcesValue],  );  const jumpTimerRef = React.useRef<number | undefined>(undefined);  React.useEffect(() => () => window.clearTimeout(jumpTimerRef.current), []);  const jumpToSection = React.useCallback(    (section: { id: string; domIndex?: number }) => {      if (!expanded) setExpandedValue(true);      window.clearTimeout(jumpTimerRef.current);      jumpTimerRef.current = window.setTimeout(() => {        const inner = bodyInnerRef.current;        if (!inner) return;        let target: HTMLElement | null = null;        if (section.id) {          target = Array.from(inner.querySelectorAll<HTMLElement>("[id]")).find((node) => node.id === section.id) ?? null;        }        if (!target && section.domIndex !== undefined) {          target = inner.querySelectorAll<HTMLElement>(HEADING_SELECTOR)[section.domIndex] ?? null;        }        if (!target) return;        target.scrollIntoView({ behavior: reduced ? "auto" : "smooth", block: "center" });        if (!reduced) {          target.animate(            [              { backgroundColor: "var(--accent)", boxShadow: "-6px 0 0 0 var(--accent), 6px 0 0 0 var(--accent)", borderRadius: "4px" },              { backgroundColor: "transparent", boxShadow: "-6px 0 0 0 transparent, 6px 0 0 0 transparent", borderRadius: "4px" },            ],            { duration: 1150, easing: EASE_OUT },          );        }      }, reduced ? 0 : 180);    },    [expanded, setExpandedValue, reduced],  );  const jumpToSources = React.useCallback(() => {    if (!sourcesOpen) setSourcesValue(true);    window.setTimeout(() => {      footerRef.current?.scrollIntoView({ behavior: reduced ? "auto" : "smooth", block: "center" });    }, 80);  }, [sourcesOpen, setSourcesValue, reduced]);  const hiddenSections = React.useMemo(() => {    if (sections && sections.length > 0) {      return sections.filter((s) => s.hidden !== false).map((s) => ({ id: s.id, label: s.label, domIndex: undefined as number | undefined }));    }    return (scan?.headings ?? []).filter((h) => h.hidden);  }, [sections, scan]);  const totalReadMinutes = scan && scan.totalWords > 0 ? Math.max(1, Math.round(scan.totalWords / 220)) : null;  const hiddenMinutes = scan && scan.hiddenWords > 80 ? Math.max(1, Math.round(scan.hiddenWords / 220)) : null;  const showStickyPill = stickyCollapse && expanded && canCollapse && bodyInView && !footerInView;  const streaming = status === "streaming";  const ssrFold = !expanded && scan === null;  const textLabels = {    expand: labels?.expand ?? "Expand full answer",    expandShort: labels?.expandShort ?? "Expand",    collapse: labels?.collapse ?? "Collapse",    followUps: labels?.followUps ?? "Follow-ups",    jumpTo: labels?.jumpTo ?? "Inside",  };  const contextValue = React.useMemo<ExpandableAnswerContextValue>(    () => ({      sources,      activeSourceIndex,      sourcesOpen,      expanded,      openSource,      setExpanded: (next) => setExpandedValue(next),    }),    [sources, activeSourceIndex, sourcesOpen, expanded, openSource, setExpandedValue],  );  const headerMeta =    meta !== undefined ? (      meta    ) : streaming ? (      <span className="inline-flex items-center gap-1.5 text-[11.5px] font-medium">        <span className="relative flex size-1.5" aria-hidden="true">          <span className="absolute inset-0 rounded-full bg-primary animate-[ui-ping_1.4s_cubic-bezier(0,0,0.2,1)_infinite] motion-reduce:animate-none" />          <span className="relative size-1.5 rounded-full bg-primary" />        </span>        <span className={SHEEN}>Writing</span>      </span>    ) : totalReadMinutes && canCollapse ? (      <span className="tabular-nums text-muted-foreground">{totalReadMinutes} min read</span>    ) : null;  return (    <ExpandableAnswerContext.Provider value={contextValue}>      <article        ref={cardRef}        className={`@container w-full overflow-x-clip rounded-[18px] border border-border bg-card text-card-foreground ${className}`}        {...props}      >        {reasoning ? (          <ReasoningBand reasoning={reasoning} open={reasoningOpen} onToggle={toggleReasoning} meta={headerMeta} reduced={reduced} />        ) : label || headerMeta ? (          <div className="flex min-h-10 items-center justify-between gap-2 rounded-t-[17px] border-b border-border bg-muted/25 px-3.5 py-2 @[28rem]:px-5">            {label ? <span className="truncate text-[12.5px] font-medium text-foreground/85">{label}</span> : <span />}            {headerMeta && <div className="shrink-0 text-[11.5px] text-muted-foreground">{headerMeta}</div>}          </div>        ) : null}        {/* Subtle hairline scan along the top of the body while streaming */}        {streaming && (          <div aria-hidden="true" className="relative h-[1.5px] w-full overflow-hidden bg-transparent">            <span className="absolute inset-y-0 left-0 w-2/5 bg-primary/70 animate-[ui-scan_1.35s_cubic-bezier(0.4,0,0.2,1)_infinite] motion-reduce:animate-none" />          </div>        )}        {/* Rich markdown body with spring height fold + optical fade veil + sticky mobile collapse pill */}        <div className="relative">          <div            ref={bodyClipRef}            id={bodyId}            aria-busy={streaming || undefined}            className={ssrFold ? "max-h-[var(--ea-fold)] overflow-clip" : undefined}            style={{ "--ea-fold": `${collapsedHeight}px` } as React.CSSProperties}          >            <div ref={bodyInnerRef} className="min-w-0 px-3.5 pt-4 pb-3.5 @[28rem]:px-5 @[28rem]:pt-4.5">              {children}              {status === "stopped" && (                <p className="mt-3 text-[12px] text-muted-foreground animate-[ui-fade-in_260ms_ease-out_backwards] motion-reduce:animate-none">                  Response stopped early.                </p>              )}              {status === "error" && (                <div className="mt-3 flex flex-wrap items-center gap-2 rounded-[10px] border border-border bg-muted/40 px-3 py-2 text-[12.5px] text-muted-foreground animate-[ui-fade-in_260ms_ease-out_backwards] motion-reduce:animate-none">                  <AlertCircle aria-hidden="true" className="size-3.5 shrink-0 text-red-600 dark:text-red-400" />                  <span className="min-w-0 flex-1">The answer was interrupted before finishing.</span>                  {onRetry && (                    <button                      type="button"                      onClick={onRetry}                      className={`cursor-pointer rounded-md border border-border bg-background px-2.5 py-1 text-[12px] font-medium text-foreground transition-colors hover:bg-accent ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}                    >                      Retry                    </button>                  )}                </div>              )}            </div>            {stickyCollapse && canCollapse && expanded && (              <div className="pointer-events-none sticky bottom-3 z-20 flex justify-center px-3 pb-2">                <div                  inert={!showStickyPill}                  className={`inline-flex h-8.5 items-center rounded-full border border-border bg-background p-1 text-[12px] font-medium text-foreground ${                    showStickyPill ? "pointer-events-auto" : "pointer-events-none"                  }`}                  style={{                    opacity: showStickyPill ? 1 : 0,                    transform: showStickyPill ? "none" : "translateY(8px) scale(0.95)",                    transition: reduced ? "none" : `opacity 220ms ${EASE_OUT}, transform 320ms ${EASE_OUT}`,                  }}                >                  <button                    type="button"                    onClick={() => setExpandedValue(false, true)}                    className={`cursor-pointer inline-flex h-6.5 items-center gap-1 rounded-full px-2.5 transition-colors hover:bg-accent ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}                  >                    <ChevronUp aria-hidden="true" className="size-3.5 text-muted-foreground" />                    <span>{textLabels.collapse}</span>                  </button>                  {sources.length > 0 && (                    <>                      <span aria-hidden="true" className="mx-0.5 h-3.5 w-px bg-border" />                      <button                        type="button"                        onClick={jumpToSources}                        aria-label={`Jump to ${sources.length} ${sources.length === 1 ? "source" : "sources"}`}                        className={`cursor-pointer inline-flex h-6.5 items-center gap-1.5 rounded-full px-2 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}                      >                        <SourceDotStack sources={sources} ringClass="ring-background" />                        <span className="tabular-nums text-[11.5px]">{sources.length}</span>                      </button>                    </>                  )}                </div>              </div>            )}          </div>          {/* Optical fade veil anchored over the bottom of the folded viewport */}          <div            aria-hidden="true"            className="pointer-events-none absolute inset-x-0 bottom-0 h-24"            style={{              background: "linear-gradient(to bottom, transparent 0%, color-mix(in oklab, var(--card) 78%, transparent) 58%, var(--card) 100%)",              opacity: isFolded ? 1 : 0,              transition: reduced ? "none" : `opacity ${isFolded ? "260ms" : "180ms"} ${EASE_OUT}`,            }}          />        </div>        {/* Fold control dock: hidden section jump pills + expand trigger with remaining scope */}        <div          inert={!isFolded}          className="grid grid-cols-1"          style={{            gridTemplateRows: isFolded ? "1fr" : "0fr",            opacity: isFolded ? 1 : 0,            transition: reduced ? "none" : `grid-template-rows 380ms ${EASE_OUT}, opacity ${isFolded ? "280ms" : "160ms"} ${EASE_OUT}`,          }}        >          <div className={`min-h-0 min-w-0 overflow-clip ${isFolded ? "" : "pointer-events-none"}`}>            <div className="flex flex-col gap-2 px-3.5 pb-3.5 pt-1 @[28rem]:px-5">              {hiddenSections.length > 0 && (                <div className="flex items-center gap-1.5 overflow-x-auto pb-0.5 pr-4 [mask-image:linear-gradient(to_right,#000_0%,#000_93%,transparent_100%)] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">                  <span className="shrink-0 text-[11px] font-medium text-muted-foreground">{textLabels.jumpTo}</span>                  {hiddenSections.slice(0, 6).map((section, i) => (                    <button                      key={`${section.id}-${i}`}                      type="button"                      onClick={() => jumpToSection(section)}                      className={`cursor-pointer inline-flex h-7 shrink-0 items-center gap-1.5 rounded-full border border-border bg-background px-2.5 text-[11.5px] font-medium text-foreground transition-colors duration-150 hover:bg-accent ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}                    >                      <span                        aria-hidden="true"                        className="size-1.5 shrink-0 rounded-full"                        style={{ backgroundColor: CHART_TONES[i % CHART_TONES.length] }}                      />                      <span className="max-w-[180px] truncate">{section.label}</span>                    </button>                  ))}                </div>              )}              <button                type="button"                aria-expanded={expanded}                aria-controls={bodyId}                onClick={() => setExpandedValue(true)}                className={`cursor-pointer flex h-9 w-full items-center justify-between gap-3 rounded-[11px] border border-border bg-background px-3 text-[12.5px] font-medium text-foreground transition-colors duration-150 hover:bg-accent ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}              >                <span className="flex min-w-0 items-center gap-1.5">                  <ChevronDown aria-hidden="true" className="size-3.5 shrink-0 text-muted-foreground" />                  <TextMorph>{textLabels.expand}</TextMorph>                </span>                <span className="flex shrink-0 items-baseline gap-1 text-[11.5px] font-normal text-muted-foreground tabular-nums">                  {hiddenSections.length > 0 ? (                    <>                      <span className="inline-flex items-baseline">                        +<NumberRoll value={hiddenSections.length} duration={480} />                        <span className="pl-[0.25em]">{hiddenSections.length === 1 ? "section" : "sections"}</span>                      </span>                      {hiddenMinutes !== null && (                        <span className="hidden @[22rem]:inline">· {hiddenMinutes} min</span>                      )}                    </>                  ) : scan && scan.hiddenWords > 15 ? (                    <span className="inline-flex items-baseline">                      +<NumberRoll value={scan.hiddenWords} duration={480} />                      <span className="pl-[0.25em]">words</span>                    </span>                  ) : null}                </span>              </button>            </div>          </div>        </div>        {/* Footer actions + sources trigger */}        <AnswerFooterBar          footerRef={footerRef}          copyText={copyText}          onRegenerate={onRegenerate}          feedback={feedback}          defaultFeedback={defaultFeedback}          onFeedback={onFeedback}          canCollapse={canCollapse}          expanded={expanded}          bodyId={bodyId}          onToggleExpand={() => setExpandedValue(!expanded, true)}          expandLabel={textLabels.expandShort}          collapseLabel={textLabels.collapse}          sources={sources}          sourcesOpen={sourcesOpen}          sourcesPanelId={sourcesPanelId}          onToggleSources={() => setSourcesValue(!sourcesOpen)}          disabled={streaming}          reduced={reduced}        />        {/* Inline sources verification drawer */}        <SourcesDrawer          id={sourcesPanelId}          sources={sources}          open={sourcesOpen}          activeIndex={activeSourceIndex}          onSelectSource={onSourceSelect}          reduced={reduced}        />        {/* Contextual follow-up questions */}        <FollowUpList          items={followUps}          label={textLabels.followUps}          show={followUps.length > 0 && !streaming}          onSelect={onFollowUp}          reduced={reduced}        />        <span role="status" aria-live="polite" className="sr-only">          {announcement}        </span>      </article>    </ExpandableAnswerContext.Provider>  );}/* ── AnswerCite ──────────────────────────────────────────── */export interface AnswerCiteProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, "children"> {  /** 1-based citation number matching the `sources` array passed to ExpandableAnswer. */  index: number;  label?: string;}/** Inline numbered citation chip: opens the parent card's Sources drawer and spotlights that source. */export function AnswerCite({ index, label, className = "", onClick, ...props }: AnswerCiteProps) {  const ctx = React.useContext(ExpandableAnswerContext);  const zeroIndex = index - 1;  const source = ctx?.sources[zeroIndex];  const active = Boolean(ctx?.sourcesOpen && ctx?.activeSourceIndex === zeroIndex);  const tone = sourceColor(source, zeroIndex);  return (    <button      type="button"      onClick={(e) => {        ctx?.openSource(zeroIndex);        onClick?.(e);      }}      aria-label={`Inspect source ${index}${source ? `: ${source.title}` : ""}`}      className={`cursor-pointer mx-0.5 inline-flex h-[1.35em] min-w-[1.35em] -translate-y-[0.08em] items-center justify-center gap-1 rounded-[5px] border border-border px-1 align-baseline font-mono text-[10.5px] font-medium leading-none transition-colors duration-150 ${        active ? "bg-foreground text-background" : "bg-muted text-foreground/85 hover:bg-accent hover:text-foreground"      } ${INTERACTION_FOCUS} ${className}`}      {...props}    >      <span aria-hidden="true" className="size-1.5 shrink-0 rounded-full" style={{ backgroundColor: active ? "currentColor" : tone }} />      <span>{label ?? index}</span>    </button>  );}/* ── AnswerProse ─────────────────────────────────────────── */export interface AnswerProseProps extends React.HTMLAttributes<HTMLDivElement> {  children: React.ReactNode;}/** Hairline typography styling for rich Markdown or JSX inside ExpandableAnswer (no typography plugin needed). */export function AnswerProse({ children, className = "", ...props }: AnswerProseProps) {  return (    <div      className={`min-w-0 space-y-3 text-[13.5px] leading-[1.65] text-foreground @[28rem]:text-[14px] [&_h2]:mt-5 [&_h2]:mb-2 [&_h2]:text-[15px] [&_h2]:font-semibold [&_h2]:tracking-[-0.02em] [&_h2]:text-foreground [&_h3]:mt-4 [&_h3]:mb-1.5 [&_h3]:text-[13.5px] [&_h3]:font-semibold [&_h3]:tracking-[-0.015em] [&_h3]:text-foreground [&_h4]:mt-3.5 [&_h4]:mb-1 [&_h4]:text-[13px] [&_h4]:font-medium [&_h4]:text-foreground [&_p]:m-0 [&_strong]:font-semibold [&_strong]:text-foreground [&_ul]:list-disc [&_ul]:space-y-1.5 [&_ul]:pl-5 [&_ol]:list-decimal [&_ol]:space-y-1.5 [&_ol]:pl-5 [&_li]:pl-0.5 [&_li::marker]:text-muted-foreground [&_blockquote]:border-l-2 [&_blockquote]:border-border [&_blockquote]:pl-3.5 [&_blockquote]:text-[13px] [&_blockquote]:text-muted-foreground [&_hr]:border-t [&_hr]:border-border [&_a]:font-medium [&_a]:text-foreground [&_a]:underline [&_a]:decoration-border [&_a]:underline-offset-4 [&_a:hover]:decoration-foreground [&_:not(pre)>code]:rounded-[5px] [&_:not(pre)>code]:border [&_:not(pre)>code]:border-border [&_:not(pre)>code]:bg-muted/65 [&_:not(pre)>code]:px-1.5 [&_:not(pre)>code]:py-px [&_:not(pre)>code]:font-mono [&_:not(pre)>code]:text-[12px] [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_pre]:rounded-[12px] [&_pre]:border [&_pre]:border-border [&_pre]:bg-muted/40 [&_pre]:p-3 [&_pre]:font-mono [&_pre]:text-[12px] [&_pre]:leading-relaxed [&_div:has(>table)]:max-w-full [&_div:has(>table)]:overflow-x-auto [&_div:has(>table)]:rounded-[11px] [&_div:has(>table)]:border [&_div:has(>table)]:border-border [&>table]:block [&>table]:w-full [&>table]:overflow-x-auto [&>table]:rounded-[11px] [&>table]:border [&>table]:border-border [&_table]:w-full [&_table]:border-collapse [&_table]:text-left [&_table]:text-[12.5px] [&_table]:tabular-nums [&_thead]:bg-muted/50 [&_th]:whitespace-nowrap [&_th]:border-b [&_th]:border-border [&_th]:px-3 [&_th]:py-2 [&_th]:text-[11.5px] [&_th]:font-medium [&_th]:text-muted-foreground [&_td]:border-b [&_td]:border-border/70 [&_td]:px-3 [&_td]:py-2 [&_tr:last-child_td]:border-b-0 ${className}`}      {...props}    >      {children}    </div>  );}export default ExpandableAnswer;

Registry item: /r/expandable-answer.json