# Expandable answer

> 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.

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.

## Install

```bash
npx shadcn@latest add @hairline/expandable-answer
```

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

- npm: `lucide-react`
- Hairline UI components it needs (the CLI installs them too): `number-roll`, `text-morph`
- Docs and live preview: https://hairlineui.com/ui/expandable-answer
- Registry item (source): https://hairlineui.com/r/expandable-answer.json

## 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>
```

## 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.

```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

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `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` | `number` | `236` | Preview height in pixels when folded. |
| `collapseThreshold` | `number` | `56` | Minimum overflow beyond collapsedHeight before folding activates, so short answers never show a veil. |
| `expanded / defaultExpanded / onExpandedChange` | `boolean / (open: boolean) => void` | `false` | Controlled or uncontrolled expanded state. |
| `reasoningOpen / defaultReasoningOpen / onReasoningOpenChange` | `boolean / (open: boolean) => void` | – | Controlled or uncontrolled reasoning disclosure state. |
| `sourcesOpen / defaultSourcesOpen / onSourcesOpenChange` | `boolean / (open: boolean) => void` | `false` | Controlled or uncontrolled sources drawer state. |
| `stickyCollapse` | `boolean` | `true` | Pins a compact Collapse + Sources pill at the bottom edge while reading deep inside a long expanded reply. |
| `status` | `"streaming" \| "done" \| "stopped" \| "error"` | `"done"` | 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` | `"up" \| "down" \| null` | `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. |

## 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.

## What it handles

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.

- **Auto-folds only long answers**: Measures your rendered Markdown with ResizeObserver and skips the veil and Expand bar whenever a short answer already fits.
- **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.
- **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.
- **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.
- **Touch-friendly inline citations**: Drop AnswerCite inside any Markdown renderer: tapping [1] opens the card’s Sources drawer in place and spotlights that source.
- **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.

## Replaces

a collapsible markdown response card, read more / show less height animation, hidden heading jump chips, a sticky mobile collapse bar, an inline reasoning trace header, a sources drawer and follow-up list

## Where it fits

- **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.

## Notes

- 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.

License: MIT (https://hairlineui.com/license#components)
