{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"expandable-answer","type":"registry:component","title":"Expandable answer","description":"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.","author":"Hairline UI","dependencies":["lucide-react"],"registryDependencies":["https://hairlineui.com/r/number-roll.json?as=dependency","https://hairlineui.com/r/text-morph.json?as=dependency"],"files":[{"path":"registry/expandable-answer.tsx","type":"registry:component","content":"// Hairline UI · expandable-answer · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { AlertCircle, ChevronDown, ChevronUp } from \"lucide-react\";\nimport { NumberRoll } from \"./number-roll\";\nimport { TextMorph } from \"./text-morph\";\nimport {\n  createSpring,\n  EASE_OUT,\n  INTERACTION_FOCUS,\n  INTERACTION_PRESS,\n  useInteractionReducedMotion,\n  type Spring,\n} from \"./ui-interaction-motion\";\nimport {\n  AnswerFooterBar,\n  CHART_TONES,\n  FollowUpList,\n  ReasoningBand,\n  SHEEN,\n  SourceDotStack,\n  SourcesDrawer,\n  sourceColor,\n  type ExpandableAnswerStatus,\n  type ExpandableFeedback,\n  type ExpandableReasoning,\n  type ExpandableReasoningStatus,\n  type ExpandableReasoningStep,\n  type ExpandableReasoningStepStatus,\n  type ExpandableSection,\n  type ExpandableSource,\n} from \"./expandable-answer-parts\";\n\n/* ─────────────────────────────────────────────────────────\n * EXPANDABLE ANSWER: a long rich-markdown AI response built\n * for phones, side panels and dense threads\n *\n *   folded     long answers preview behind an optical fade\n *              veil; hidden headings surface as clickable\n *              jump chips right above the fold edge\n *   unfold     a velocity-preserving spring opens the body\n *              in place (tap a section chip to unfold and\n *              glide straight to that heading)\n *   reading    once expanded past the viewport, a hairline\n *              sticky pill floats at the bottom edge so you\n *              can collapse or jump to sources without\n *              scrolling back; it ducks away the moment the\n *              real footer enters view\n *   sources    inline [1] citations and the stacked dot pill\n *              open a responsive source verification drawer\n *              inside the same hairline surface\n * ───────────────────────────────────────────────────────── */\n\nexport type {\n  ExpandableAnswerStatus,\n  ExpandableFeedback,\n  ExpandableReasoning,\n  ExpandableReasoningStatus,\n  ExpandableReasoningStep,\n  ExpandableReasoningStepStatus,\n  ExpandableSection,\n  ExpandableSource,\n};\n\ninterface ExpandableAnswerContextValue {\n  sources: ExpandableSource[];\n  activeSourceIndex: number | null;\n  sourcesOpen: boolean;\n  expanded: boolean;\n  openSource: (index: number) => void;\n  setExpanded: (next: boolean) => void;\n}\n\nconst ExpandableAnswerContext = React.createContext<ExpandableAnswerContextValue | null>(null);\n\nexport function useExpandableAnswer() {\n  return React.useContext(ExpandableAnswerContext);\n}\n\nexport interface ExpandableAnswerLabels {\n  expand?: string;\n  expandShort?: string;\n  collapse?: string;\n  followUps?: string;\n  jumpTo?: string;\n}\n\nexport interface ExpandableAnswerProps extends Omit<React.HTMLAttributes<HTMLElement>, \"title\"> {\n  /** Any rich markdown renderer (<ReactMarkdown>…</ReactMarkdown>), MDX or JSX. */\n  children: React.ReactNode;\n  /** Optional collapsible reasoning trace docked cleanly in the header rail. */\n  reasoning?: ExpandableReasoning;\n  /** Verified sources displayed as a dot stack and inline expandable drawer. */\n  sources?: ExpandableSource[];\n  /** Suggested next questions shown once the response settles. */\n  followUps?: string[];\n  onFollowUp?: (question: string) => void;\n  /** Optional heading list for section jump chips; auto-detected from h1-h4 headings if omitted. */\n  sections?: ExpandableSection[];\n  /** Header label shown on the left when no reasoning is provided (e.g. model name). */\n  label?: string;\n  /** Right-hand header metadata (e.g. reading time or model badge). Auto-calculated reading time if omitted. */\n  meta?: React.ReactNode;\n  status?: ExpandableAnswerStatus;\n  onRetry?: () => void;\n  /** Plain text or markdown copied by the Copy button. Omit to hide Copy. */\n  copyText?: string;\n  onRegenerate?: () => void;\n  feedback?: ExpandableFeedback;\n  defaultFeedback?: ExpandableFeedback;\n  onFeedback?: (value: ExpandableFeedback) => void;\n  onSourceSelect?: (source: ExpandableSource, index: number) => void;\n  /** Visible preview height in px when collapsed. Short answers never fold. */\n  collapsedHeight?: number;\n  /** Minimum overflow (px) beyond collapsedHeight required before folding activates. */\n  collapseThreshold?: number;\n  expanded?: boolean;\n  defaultExpanded?: boolean;\n  onExpandedChange?: (expanded: boolean) => void;\n  reasoningOpen?: boolean;\n  defaultReasoningOpen?: boolean;\n  onReasoningOpenChange?: (open: boolean) => void;\n  sourcesOpen?: boolean;\n  defaultSourcesOpen?: boolean;\n  onSourcesOpenChange?: (open: boolean) => void;\n  /** Keep a compact floating Collapse pill pinned while reading deep inside a long expanded answer. */\n  stickyCollapse?: boolean;\n  labels?: ExpandableAnswerLabels;\n}\n\ninterface ScannedHeading {\n  id: string;\n  label: string;\n  hidden: boolean;\n  domIndex: number;\n}\n\ninterface ScanMeta {\n  fullHeight: number;\n  totalWords: number;\n  hiddenWords: number;\n  headings: ScannedHeading[];\n}\n\nconst EMPTY_SOURCES: ExpandableSource[] = [];\nconst EMPTY_FOLLOW_UPS: string[] = [];\nconst HEADING_SELECTOR = \"h1, h2, h3, h4, [data-answer-section]\";\nconst BODY_SPRING = { stiffness: 250, damping: 28, mass: 1 };\n\nfunction countWords(text: string): number {\n  const trimmed = text.trim();\n  return trimmed ? trimmed.split(/\\s+/).length : 0;\n}\n\nfunction sameScan(a: ScanMeta | null, b: ScanMeta): boolean {\n  if (!a) return false;\n  if (a.fullHeight !== b.fullHeight || a.totalWords !== b.totalWords || a.hiddenWords !== b.hiddenWords) return false;\n  if (a.headings.length !== b.headings.length) return false;\n  for (let i = 0; i < a.headings.length; i++) {\n    if (\n      a.headings[i].id !== b.headings[i].id ||\n      a.headings[i].label !== b.headings[i].label ||\n      a.headings[i].hidden !== b.headings[i].hidden ||\n      a.headings[i].domIndex !== b.headings[i].domIndex\n    ) {\n      return false;\n    }\n  }\n  return true;\n}\n\nfunction scanBody(container: HTMLElement, collapsedHeight: number): ScanMeta {\n  const fullHeight = Math.ceil(container.scrollHeight);\n  const baseRect = container.getBoundingClientRect();\n  const totalWords = countWords(container.textContent ?? \"\");\n\n  const nodes = Array.from(container.querySelectorAll<HTMLElement>(HEADING_SELECTOR));\n  const headings: ScannedHeading[] = [];\n  nodes.forEach((node, domIndex) => {\n    const label = (node.dataset.answerSection || node.textContent || \"\").trim();\n    if (!label) return;\n    const top = node.getBoundingClientRect().top - baseRect.top;\n    headings.push({\n      id: node.id || `section-${domIndex}`,\n      label,\n      hidden: top >= collapsedHeight - 36,\n      domIndex,\n    });\n  });\n\n  // Estimate hidden words from top-level prose blocks that sit past the fold line.\n  const proseRoot = container.firstElementChild instanceof HTMLElement ? container.firstElementChild : container;\n  let hiddenWords = 0;\n  for (const child of Array.from(proseRoot.children)) {\n    if (!(child instanceof HTMLElement)) continue;\n    const rect = child.getBoundingClientRect();\n    const relTop = rect.top - baseRect.top;\n    const relBottom = rect.bottom - baseRect.top;\n    if (relBottom <= collapsedHeight - 16) continue;\n    const w = countWords(child.textContent ?? \"\");\n    if (relTop >= collapsedHeight - 16) {\n      hiddenWords += w;\n    } else if (rect.height > 0) {\n      const hiddenFrac = Math.min(1, Math.max(0, (relBottom - (collapsedHeight - 16)) / rect.height));\n      hiddenWords += Math.round(w * hiddenFrac);\n    }\n  }\n\n  return { fullHeight, totalWords, hiddenWords, headings };\n}\n\nexport function ExpandableAnswer({\n  children,\n  reasoning,\n  sources = EMPTY_SOURCES,\n  followUps = EMPTY_FOLLOW_UPS,\n  onFollowUp,\n  sections,\n  label,\n  meta,\n  status = \"done\",\n  onRetry,\n  copyText,\n  onRegenerate,\n  feedback,\n  defaultFeedback = null,\n  onFeedback,\n  onSourceSelect,\n  collapsedHeight = 236,\n  collapseThreshold = 56,\n  expanded: controlledExpanded,\n  defaultExpanded = false,\n  onExpandedChange,\n  reasoningOpen: controlledReasoningOpen,\n  defaultReasoningOpen,\n  onReasoningOpenChange,\n  sourcesOpen: controlledSourcesOpen,\n  defaultSourcesOpen = false,\n  onSourcesOpenChange,\n  stickyCollapse = true,\n  labels,\n  className = \"\",\n  ...props\n}: ExpandableAnswerProps) {\n  const reduced = useInteractionReducedMotion();\n  const bodyId = React.useId();\n  const sourcesPanelId = React.useId();\n\n  const cardRef = React.useRef<HTMLElement>(null);\n  const bodyClipRef = React.useRef<HTMLDivElement>(null);\n  const bodyInnerRef = React.useRef<HTMLDivElement>(null);\n  const footerRef = React.useRef<HTMLDivElement>(null);\n\n  const [ownExpanded, setOwnExpanded] = React.useState(defaultExpanded);\n  const expanded = controlledExpanded ?? ownExpanded;\n\n  const reasoningRunning = reasoning?.status === \"running\";\n  const reasoningError = reasoning?.status === \"error\";\n  const [autoReasoningOpen, setAutoReasoningOpen] = React.useState(Boolean(reasoningRunning || reasoningError));\n  const [userReasoningOpen, setUserReasoningOpen] = React.useState<boolean | undefined>(defaultReasoningOpen);\n  const [seenReasoningTrigger, setSeenReasoningTrigger] = React.useState(Boolean(reasoningRunning || reasoningError));\n  if (Boolean(reasoningRunning || reasoningError) !== seenReasoningTrigger) {\n    const next = Boolean(reasoningRunning || reasoningError);\n    setSeenReasoningTrigger(next);\n    if (next) setAutoReasoningOpen(true);\n  }\n  React.useEffect(() => {\n    if (!reasoning || reasoningRunning || reasoningError) return;\n    const timer = window.setTimeout(() => setAutoReasoningOpen(false), 750);\n    return () => window.clearTimeout(timer);\n  }, [reasoning, reasoningRunning, reasoningError]);\n\n  const reasoningOpen = controlledReasoningOpen ?? userReasoningOpen ?? autoReasoningOpen;\n\n  const [ownSourcesOpen, setOwnSourcesOpen] = React.useState(defaultSourcesOpen);\n  const sourcesOpen = controlledSourcesOpen ?? ownSourcesOpen;\n  const [activeSourceIndex, setActiveSourceIndex] = React.useState<number | null>(null);\n  const [announcement, setAnnouncement] = React.useState(\"\");\n\n  const [scan, setScan] = React.useState<ScanMeta | null>(null);\n  const [bodyInView, setBodyInView] = React.useState(false);\n  const [footerInView, setFooterInView] = React.useState(true);\n\n  const canCollapse = scan !== null && scan.fullHeight > collapsedHeight + collapseThreshold;\n  const isFolded = canCollapse && !expanded;\n\n  // Measure the full rich markdown body and auto-detect hidden headings via ResizeObserver.\n  React.useLayoutEffect(() => {\n    const el = bodyInnerRef.current;\n    if (!el) return;\n    const measure = () => {\n      const next = scanBody(el, collapsedHeight);\n      setScan((prev) => (sameScan(prev, next) ? prev : next));\n    };\n    const observer = new ResizeObserver(measure);\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, [collapsedHeight]);\n\n  // Spring-driven height unfold/fold: interruptible mid-flight, releases to height:auto & overflow:visible once open.\n  const springRef = React.useRef<Spring | null>(null);\n  const expandedStateRef = React.useRef(expanded);\n  const hasMountedFoldRef = React.useRef(false);\n  const targetExpandedRef = React.useRef(expanded);\n\n  React.useLayoutEffect(() => {\n    const clip = bodyClipRef.current;\n    const inner = bodyInnerRef.current;\n    if (!clip || !inner) return;\n    targetExpandedRef.current = expanded;\n\n    if (!springRef.current) {\n      springRef.current = createSpring(\n        collapsedHeight,\n        BODY_SPRING,\n        () => {\n          const s = springRef.current;\n          const box = bodyClipRef.current;\n          if (!s || !box) return;\n          const v = Math.max(0, s.get());\n          const target = s.getTarget();\n          const settled = Math.abs(v - target) < 0.75 && Math.abs(s.getVelocity()) < 8;\n          if (settled && targetExpandedRef.current) {\n            box.style.height = \"\";\n            box.style.overflow = \"visible\";\n          } else {\n            box.style.height = `${v.toFixed(1)}px`;\n            box.style.overflow = \"clip\";\n          }\n        },\n        0.5,\n      );\n    }\n\n    const spring = springRef.current;\n\n    if (!canCollapse) {\n      spring.stop();\n      clip.style.height = \"\";\n      clip.style.overflow = \"visible\";\n      expandedStateRef.current = expanded;\n      return;\n    }\n\n    const changed = hasMountedFoldRef.current && expandedStateRef.current !== expanded;\n    expandedStateRef.current = expanded;\n\n    const currentHeight = clip.getBoundingClientRect().height;\n    const targetHeight = expanded ? Math.ceil(inner.scrollHeight) : collapsedHeight;\n\n    if (!hasMountedFoldRef.current) {\n      hasMountedFoldRef.current = true;\n      spring.stop();\n      if (expanded) {\n        clip.style.height = \"\";\n        clip.style.overflow = \"visible\";\n      } else if (!reduced && currentHeight > collapsedHeight + 8) {\n        clip.style.overflow = \"clip\";\n        clip.style.height = `${currentHeight.toFixed(1)}px`;\n        spring.jump(currentHeight);\n        spring.set(collapsedHeight);\n      } else {\n        clip.style.height = `${collapsedHeight}px`;\n        clip.style.overflow = \"clip\";\n      }\n      return;\n    }\n\n    if (!changed) {\n      if (expanded && clip.style.height !== \"\") {\n        // Content grew while the unfold spring is still mid-flight: chase the new target cleanly.\n        spring.set(Math.ceil(inner.scrollHeight));\n      } else if (!expanded && Math.abs(spring.getTarget() - collapsedHeight) > 0.5) {\n        clip.style.height = `${collapsedHeight}px`;\n        clip.style.overflow = \"clip\";\n      }\n      return;\n    }\n\n    if (reduced) {\n      spring.stop();\n      if (expanded) {\n        clip.style.height = \"\";\n        clip.style.overflow = \"visible\";\n      } else {\n        clip.style.height = `${collapsedHeight}px`;\n        clip.style.overflow = \"clip\";\n      }\n      return;\n    }\n\n    clip.style.overflow = \"clip\";\n    clip.style.height = `${currentHeight.toFixed(1)}px`;\n    spring.jump(currentHeight);\n    spring.set(targetHeight);\n  }, [expanded, canCollapse, collapsedHeight, scan?.fullHeight, reduced]);\n\n  React.useEffect(() => {\n    return () => {\n      springRef.current?.stop();\n    };\n  }, []);\n\n  // Track when the expanded body is on screen and its real bottom footer is still below the fold.\n  React.useEffect(() => {\n    if (!stickyCollapse || !expanded || !canCollapse) return;\n    const bodyEl = bodyInnerRef.current;\n    const footerEl = footerRef.current;\n    if (!bodyEl || !footerEl) return;\n\n    const bodyObs = new IntersectionObserver(\n      ([entry]) => setBodyInView(entry.isIntersecting),\n      { threshold: 0 },\n    );\n    const footerObs = new IntersectionObserver(\n      ([entry]) => setFooterInView(entry.isIntersecting),\n      { rootMargin: \"0px 0px -12px 0px\", threshold: 0 },\n    );\n    bodyObs.observe(bodyEl);\n    footerObs.observe(footerEl);\n    return () => {\n      bodyObs.disconnect();\n      footerObs.disconnect();\n    };\n  }, [stickyCollapse, expanded, canCollapse]);\n\n  const setExpandedValue = React.useCallback(\n    (next: boolean, keepHeaderInView = false) => {\n      if (!next && keepHeaderInView && cardRef.current) {\n        const top = cardRef.current.getBoundingClientRect().top;\n        if (top < 16) {\n          cardRef.current.scrollIntoView({ behavior: reduced ? \"auto\" : \"smooth\", block: \"nearest\" });\n        }\n      }\n      if (controlledExpanded === undefined) setOwnExpanded(next);\n      onExpandedChange?.(next);\n      setAnnouncement(next ? \"Answer expanded\" : \"Answer collapsed\");\n    },\n    [controlledExpanded, onExpandedChange, reduced],\n  );\n\n  const toggleReasoning = React.useCallback(() => {\n    const next = !reasoningOpen;\n    if (controlledReasoningOpen === undefined) setUserReasoningOpen(next);\n    onReasoningOpenChange?.(next);\n  }, [reasoningOpen, controlledReasoningOpen, onReasoningOpenChange]);\n\n  const setSourcesValue = React.useCallback(\n    (next: boolean) => {\n      if (controlledSourcesOpen === undefined) setOwnSourcesOpen(next);\n      onSourcesOpenChange?.(next);\n    },\n    [controlledSourcesOpen, onSourcesOpenChange],\n  );\n\n  const openSource = React.useCallback(\n    (index: number) => {\n      if (index < 0 || index >= sources.length) return;\n      setActiveSourceIndex(index);\n      if (!sourcesOpen) setSourcesValue(true);\n      setAnnouncement(`Showing source ${index + 1}: ${sources[index].title}`);\n    },\n    [sources, sourcesOpen, setSourcesValue],\n  );\n\n  const jumpTimerRef = React.useRef<number | undefined>(undefined);\n  React.useEffect(() => () => window.clearTimeout(jumpTimerRef.current), []);\n\n  const jumpToSection = React.useCallback(\n    (section: { id: string; domIndex?: number }) => {\n      if (!expanded) setExpandedValue(true);\n      window.clearTimeout(jumpTimerRef.current);\n      jumpTimerRef.current = window.setTimeout(() => {\n        const inner = bodyInnerRef.current;\n        if (!inner) return;\n        let target: HTMLElement | null = null;\n        if (section.id) {\n          target = Array.from(inner.querySelectorAll<HTMLElement>(\"[id]\")).find((node) => node.id === section.id) ?? null;\n        }\n        if (!target && section.domIndex !== undefined) {\n          target = inner.querySelectorAll<HTMLElement>(HEADING_SELECTOR)[section.domIndex] ?? null;\n        }\n        if (!target) return;\n        target.scrollIntoView({ behavior: reduced ? \"auto\" : \"smooth\", block: \"center\" });\n        if (!reduced) {\n          target.animate(\n            [\n              { backgroundColor: \"var(--accent)\", boxShadow: \"-6px 0 0 0 var(--accent), 6px 0 0 0 var(--accent)\", borderRadius: \"4px\" },\n              { backgroundColor: \"transparent\", boxShadow: \"-6px 0 0 0 transparent, 6px 0 0 0 transparent\", borderRadius: \"4px\" },\n            ],\n            { duration: 1150, easing: EASE_OUT },\n          );\n        }\n      }, reduced ? 0 : 180);\n    },\n    [expanded, setExpandedValue, reduced],\n  );\n\n  const jumpToSources = React.useCallback(() => {\n    if (!sourcesOpen) setSourcesValue(true);\n    window.setTimeout(() => {\n      footerRef.current?.scrollIntoView({ behavior: reduced ? \"auto\" : \"smooth\", block: \"center\" });\n    }, 80);\n  }, [sourcesOpen, setSourcesValue, reduced]);\n\n  const hiddenSections = React.useMemo(() => {\n    if (sections && sections.length > 0) {\n      return sections.filter((s) => s.hidden !== false).map((s) => ({ id: s.id, label: s.label, domIndex: undefined as number | undefined }));\n    }\n    return (scan?.headings ?? []).filter((h) => h.hidden);\n  }, [sections, scan]);\n\n  const totalReadMinutes = scan && scan.totalWords > 0 ? Math.max(1, Math.round(scan.totalWords / 220)) : null;\n  const hiddenMinutes = scan && scan.hiddenWords > 80 ? Math.max(1, Math.round(scan.hiddenWords / 220)) : null;\n  const showStickyPill = stickyCollapse && expanded && canCollapse && bodyInView && !footerInView;\n  const streaming = status === \"streaming\";\n  const ssrFold = !expanded && scan === null;\n\n  const textLabels = {\n    expand: labels?.expand ?? \"Expand full answer\",\n    expandShort: labels?.expandShort ?? \"Expand\",\n    collapse: labels?.collapse ?? \"Collapse\",\n    followUps: labels?.followUps ?? \"Follow-ups\",\n    jumpTo: labels?.jumpTo ?? \"Inside\",\n  };\n\n  const contextValue = React.useMemo<ExpandableAnswerContextValue>(\n    () => ({\n      sources,\n      activeSourceIndex,\n      sourcesOpen,\n      expanded,\n      openSource,\n      setExpanded: (next) => setExpandedValue(next),\n    }),\n    [sources, activeSourceIndex, sourcesOpen, expanded, openSource, setExpandedValue],\n  );\n\n  const headerMeta =\n    meta !== undefined ? (\n      meta\n    ) : streaming ? (\n      <span className=\"inline-flex items-center gap-1.5 text-[11.5px] font-medium\">\n        <span className=\"relative flex size-1.5\" aria-hidden=\"true\">\n          <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\" />\n          <span className=\"relative size-1.5 rounded-full bg-primary\" />\n        </span>\n        <span className={SHEEN}>Writing</span>\n      </span>\n    ) : totalReadMinutes && canCollapse ? (\n      <span className=\"tabular-nums text-muted-foreground\">{totalReadMinutes} min read</span>\n    ) : null;\n\n  return (\n    <ExpandableAnswerContext.Provider value={contextValue}>\n      <article\n        ref={cardRef}\n        className={`@container w-full overflow-x-clip rounded-[18px] border border-border bg-card text-card-foreground ${className}`}\n        {...props}\n      >\n        {reasoning ? (\n          <ReasoningBand reasoning={reasoning} open={reasoningOpen} onToggle={toggleReasoning} meta={headerMeta} reduced={reduced} />\n        ) : label || headerMeta ? (\n          <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\">\n            {label ? <span className=\"truncate text-[12.5px] font-medium text-foreground/85\">{label}</span> : <span />}\n            {headerMeta && <div className=\"shrink-0 text-[11.5px] text-muted-foreground\">{headerMeta}</div>}\n          </div>\n        ) : null}\n\n        {/* Subtle hairline scan along the top of the body while streaming */}\n        {streaming && (\n          <div aria-hidden=\"true\" className=\"relative h-[1.5px] w-full overflow-hidden bg-transparent\">\n            <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\" />\n          </div>\n        )}\n\n        {/* Rich markdown body with spring height fold + optical fade veil + sticky mobile collapse pill */}\n        <div className=\"relative\">\n          <div\n            ref={bodyClipRef}\n            id={bodyId}\n            aria-busy={streaming || undefined}\n            className={ssrFold ? \"max-h-[var(--ea-fold)] overflow-clip\" : undefined}\n            style={{ \"--ea-fold\": `${collapsedHeight}px` } as React.CSSProperties}\n          >\n            <div ref={bodyInnerRef} className=\"min-w-0 px-3.5 pt-4 pb-3.5 @[28rem]:px-5 @[28rem]:pt-4.5\">\n              {children}\n\n              {status === \"stopped\" && (\n                <p className=\"mt-3 text-[12px] text-muted-foreground animate-[ui-fade-in_260ms_ease-out_backwards] motion-reduce:animate-none\">\n                  Response stopped early.\n                </p>\n              )}\n\n              {status === \"error\" && (\n                <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\">\n                  <AlertCircle aria-hidden=\"true\" className=\"size-3.5 shrink-0 text-red-600 dark:text-red-400\" />\n                  <span className=\"min-w-0 flex-1\">The answer was interrupted before finishing.</span>\n                  {onRetry && (\n                    <button\n                      type=\"button\"\n                      onClick={onRetry}\n                      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}`}\n                    >\n                      Retry\n                    </button>\n                  )}\n                </div>\n              )}\n            </div>\n\n            {stickyCollapse && canCollapse && expanded && (\n              <div className=\"pointer-events-none sticky bottom-3 z-20 flex justify-center px-3 pb-2\">\n                <div\n                  inert={!showStickyPill}\n                  className={`inline-flex h-8.5 items-center rounded-full border border-border bg-background p-1 text-[12px] font-medium text-foreground ${\n                    showStickyPill ? \"pointer-events-auto\" : \"pointer-events-none\"\n                  }`}\n                  style={{\n                    opacity: showStickyPill ? 1 : 0,\n                    transform: showStickyPill ? \"none\" : \"translateY(8px) scale(0.95)\",\n                    transition: reduced ? \"none\" : `opacity 220ms ${EASE_OUT}, transform 320ms ${EASE_OUT}`,\n                  }}\n                >\n                  <button\n                    type=\"button\"\n                    onClick={() => setExpandedValue(false, true)}\n                    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}`}\n                  >\n                    <ChevronUp aria-hidden=\"true\" className=\"size-3.5 text-muted-foreground\" />\n                    <span>{textLabels.collapse}</span>\n                  </button>\n\n                  {sources.length > 0 && (\n                    <>\n                      <span aria-hidden=\"true\" className=\"mx-0.5 h-3.5 w-px bg-border\" />\n                      <button\n                        type=\"button\"\n                        onClick={jumpToSources}\n                        aria-label={`Jump to ${sources.length} ${sources.length === 1 ? \"source\" : \"sources\"}`}\n                        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}`}\n                      >\n                        <SourceDotStack sources={sources} ringClass=\"ring-background\" />\n                        <span className=\"tabular-nums text-[11.5px]\">{sources.length}</span>\n                      </button>\n                    </>\n                  )}\n                </div>\n              </div>\n            )}\n          </div>\n\n          {/* Optical fade veil anchored over the bottom of the folded viewport */}\n          <div\n            aria-hidden=\"true\"\n            className=\"pointer-events-none absolute inset-x-0 bottom-0 h-24\"\n            style={{\n              background: \"linear-gradient(to bottom, transparent 0%, color-mix(in oklab, var(--card) 78%, transparent) 58%, var(--card) 100%)\",\n              opacity: isFolded ? 1 : 0,\n              transition: reduced ? \"none\" : `opacity ${isFolded ? \"260ms\" : \"180ms\"} ${EASE_OUT}`,\n            }}\n          />\n        </div>\n\n        {/* Fold control dock: hidden section jump pills + expand trigger with remaining scope */}\n        <div\n          inert={!isFolded}\n          className=\"grid grid-cols-1\"\n          style={{\n            gridTemplateRows: isFolded ? \"1fr\" : \"0fr\",\n            opacity: isFolded ? 1 : 0,\n            transition: reduced ? \"none\" : `grid-template-rows 380ms ${EASE_OUT}, opacity ${isFolded ? \"280ms\" : \"160ms\"} ${EASE_OUT}`,\n          }}\n        >\n          <div className={`min-h-0 min-w-0 overflow-clip ${isFolded ? \"\" : \"pointer-events-none\"}`}>\n            <div className=\"flex flex-col gap-2 px-3.5 pb-3.5 pt-1 @[28rem]:px-5\">\n              {hiddenSections.length > 0 && (\n                <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\">\n                  <span className=\"shrink-0 text-[11px] font-medium text-muted-foreground\">{textLabels.jumpTo}</span>\n                  {hiddenSections.slice(0, 6).map((section, i) => (\n                    <button\n                      key={`${section.id}-${i}`}\n                      type=\"button\"\n                      onClick={() => jumpToSection(section)}\n                      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}`}\n                    >\n                      <span\n                        aria-hidden=\"true\"\n                        className=\"size-1.5 shrink-0 rounded-full\"\n                        style={{ backgroundColor: CHART_TONES[i % CHART_TONES.length] }}\n                      />\n                      <span className=\"max-w-[180px] truncate\">{section.label}</span>\n                    </button>\n                  ))}\n                </div>\n              )}\n\n              <button\n                type=\"button\"\n                aria-expanded={expanded}\n                aria-controls={bodyId}\n                onClick={() => setExpandedValue(true)}\n                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}`}\n              >\n                <span className=\"flex min-w-0 items-center gap-1.5\">\n                  <ChevronDown aria-hidden=\"true\" className=\"size-3.5 shrink-0 text-muted-foreground\" />\n                  <TextMorph>{textLabels.expand}</TextMorph>\n                </span>\n\n                <span className=\"flex shrink-0 items-baseline gap-1 text-[11.5px] font-normal text-muted-foreground tabular-nums\">\n                  {hiddenSections.length > 0 ? (\n                    <>\n                      <span className=\"inline-flex items-baseline\">\n                        +<NumberRoll value={hiddenSections.length} duration={480} />\n                        <span className=\"pl-[0.25em]\">{hiddenSections.length === 1 ? \"section\" : \"sections\"}</span>\n                      </span>\n                      {hiddenMinutes !== null && (\n                        <span className=\"hidden @[22rem]:inline\">· {hiddenMinutes} min</span>\n                      )}\n                    </>\n                  ) : scan && scan.hiddenWords > 15 ? (\n                    <span className=\"inline-flex items-baseline\">\n                      +<NumberRoll value={scan.hiddenWords} duration={480} />\n                      <span className=\"pl-[0.25em]\">words</span>\n                    </span>\n                  ) : null}\n                </span>\n              </button>\n            </div>\n          </div>\n        </div>\n\n        {/* Footer actions + sources trigger */}\n        <AnswerFooterBar\n          footerRef={footerRef}\n          copyText={copyText}\n          onRegenerate={onRegenerate}\n          feedback={feedback}\n          defaultFeedback={defaultFeedback}\n          onFeedback={onFeedback}\n          canCollapse={canCollapse}\n          expanded={expanded}\n          bodyId={bodyId}\n          onToggleExpand={() => setExpandedValue(!expanded, true)}\n          expandLabel={textLabels.expandShort}\n          collapseLabel={textLabels.collapse}\n          sources={sources}\n          sourcesOpen={sourcesOpen}\n          sourcesPanelId={sourcesPanelId}\n          onToggleSources={() => setSourcesValue(!sourcesOpen)}\n          disabled={streaming}\n          reduced={reduced}\n        />\n\n        {/* Inline sources verification drawer */}\n        <SourcesDrawer\n          id={sourcesPanelId}\n          sources={sources}\n          open={sourcesOpen}\n          activeIndex={activeSourceIndex}\n          onSelectSource={onSourceSelect}\n          reduced={reduced}\n        />\n\n        {/* Contextual follow-up questions */}\n        <FollowUpList\n          items={followUps}\n          label={textLabels.followUps}\n          show={followUps.length > 0 && !streaming}\n          onSelect={onFollowUp}\n          reduced={reduced}\n        />\n\n        <span role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n          {announcement}\n        </span>\n      </article>\n    </ExpandableAnswerContext.Provider>\n  );\n}\n\n/* ── AnswerCite ──────────────────────────────────────────── */\n\nexport interface AnswerCiteProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, \"children\"> {\n  /** 1-based citation number matching the `sources` array passed to ExpandableAnswer. */\n  index: number;\n  label?: string;\n}\n\n/** Inline numbered citation chip: opens the parent card's Sources drawer and spotlights that source. */\nexport function AnswerCite({ index, label, className = \"\", onClick, ...props }: AnswerCiteProps) {\n  const ctx = React.useContext(ExpandableAnswerContext);\n  const zeroIndex = index - 1;\n  const source = ctx?.sources[zeroIndex];\n  const active = Boolean(ctx?.sourcesOpen && ctx?.activeSourceIndex === zeroIndex);\n  const tone = sourceColor(source, zeroIndex);\n\n  return (\n    <button\n      type=\"button\"\n      onClick={(e) => {\n        ctx?.openSource(zeroIndex);\n        onClick?.(e);\n      }}\n      aria-label={`Inspect source ${index}${source ? `: ${source.title}` : \"\"}`}\n      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 ${\n        active ? \"bg-foreground text-background\" : \"bg-muted text-foreground/85 hover:bg-accent hover:text-foreground\"\n      } ${INTERACTION_FOCUS} ${className}`}\n      {...props}\n    >\n      <span aria-hidden=\"true\" className=\"size-1.5 shrink-0 rounded-full\" style={{ backgroundColor: active ? \"currentColor\" : tone }} />\n      <span>{label ?? index}</span>\n    </button>\n  );\n}\n\n/* ── AnswerProse ─────────────────────────────────────────── */\n\nexport interface AnswerProseProps extends React.HTMLAttributes<HTMLDivElement> {\n  children: React.ReactNode;\n}\n\n/** Hairline typography styling for rich Markdown or JSX inside ExpandableAnswer (no typography plugin needed). */\nexport function AnswerProse({ children, className = \"\", ...props }: AnswerProseProps) {\n  return (\n    <div\n      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}`}\n      {...props}\n    >\n      {children}\n    </div>\n  );\n}\n\nexport default ExpandableAnswer;\n"},{"path":"registry/expandable-answer-parts.tsx","type":"registry:component","content":"// Hairline UI · expandable-answer · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { AlertCircle, ArrowUpRight, ChevronDown, CircleSlash, Copy, CornerDownRight, Globe, RotateCcw, Sparkle, ThumbsDown, ThumbsUp, X } from \"lucide-react\";\nimport { NumberRoll } from \"./number-roll\";\nimport { TextMorph } from \"./text-morph\";\nimport { EASE_OUT, EASE_THROW, INTERACTION_FOCUS, INTERACTION_PRESS, interactionIcon } from \"./ui-interaction-motion\";\n\nexport type ExpandableAnswerStatus = \"streaming\" | \"done\" | \"stopped\" | \"error\";\nexport type ExpandableFeedback = \"up\" | \"down\" | null;\nexport type ExpandableReasoningStatus = \"running\" | \"done\" | \"error\" | \"cancelled\";\nexport type ExpandableReasoningStepStatus = \"pending\" | \"running\" | \"done\" | \"error\";\n\nexport interface ExpandableReasoningStep {\n  label: string;\n  detail?: string;\n  href?: string;\n  status?: ExpandableReasoningStepStatus;\n}\n\nexport interface ExpandableReasoning {\n  steps: ExpandableReasoningStep[];\n  status?: ExpandableReasoningStatus;\n  /** Header while running. Defaults to \"Thinking\". */\n  label?: string;\n  /** Header once settled. Defaults to \"Thought for Xs\" when timing is known. */\n  doneLabel?: string;\n  /** Start timestamp (ms) for a live rolling timer while running. */\n  startedAt?: number;\n  /** Fixed duration (ms) once settled. */\n  durationMs?: number;\n  onStepClick?: (step: ExpandableReasoningStep, index: number) => void;\n}\n\nexport interface ExpandableSource {\n  title: string;\n  url: string;\n  snippet?: string;\n  /** Optional favicon or mark, e.g. <img src=\"…\" alt=\"\" />. */\n  icon?: React.ReactNode;\n  /** Optional custom CSS colour for the source dot. Defaults to --chart-1..5. */\n  color?: string;\n}\n\nexport interface ExpandableSection {\n  id: string;\n  label: string;\n  /** Whether this heading currently starts below the collapsed fold. */\n  hidden?: boolean;\n}\n\nexport const CHART_TONES = [\n  \"var(--chart-1, var(--primary))\",\n  \"var(--chart-2, var(--primary))\",\n  \"var(--chart-3, var(--primary))\",\n  \"var(--chart-4, var(--primary))\",\n  \"var(--chart-5, var(--primary))\",\n] as const;\n\nexport const SHEEN =\n  \"text-foreground [mask-image:linear-gradient(90deg,rgb(0_0_0/0.42)_35%,#000_50%,rgb(0_0_0/0.42)_65%)] [mask-size:200%_100%] animate-[ui-sheen_1.4s_linear_infinite] motion-reduce:animate-none motion-reduce:[mask-image:none] motion-reduce:text-foreground/75\";\n\nconst TWO_DIGITS = { minimumIntegerDigits: 2 };\n\nexport function sourceColor(source: ExpandableSource | undefined, index: number): string {\n  return source?.color ?? CHART_TONES[index % CHART_TONES.length];\n}\n\nexport function hostnameOf(url: string): string {\n  try {\n    return new URL(url).hostname.replace(/^www\\./, \"\");\n  } catch {\n    return url;\n  }\n}\n\n/** Inline span that slides open horizontally without disturbing text baselines. */\nfunction InlineReveal({ show, reduced, className = \"\", children }: { show: boolean; reduced: boolean; className?: string; children: React.ReactNode }) {\n  return (\n    <span\n      aria-hidden={!show || undefined}\n      className={`grid ${className}`}\n      style={{\n        gridTemplateColumns: show ? \"1fr\" : \"0fr\",\n        opacity: show ? 1 : 0,\n        filter: show ? \"blur(0px)\" : \"blur(3px)\",\n        transition: reduced ? \"none\" : `grid-template-columns 380ms ${EASE_OUT}, opacity ${show ? \"260ms\" : \"150ms\"} ${EASE_OUT}, filter 260ms ${EASE_OUT}`,\n      }}\n    >\n      <span className=\"min-w-0 whitespace-nowrap [clip-path:inset(-4px_0)]\">{children}</span>\n    </span>\n  );\n}\n\nfunction ElapsedSeconds({ ms, reduced }: { ms: number; reduced: boolean }) {\n  const total = Math.max(0, Math.round(ms / 1000));\n  const minutes = Math.floor(total / 60);\n  return (\n    <span className=\"inline-flex items-baseline tabular-nums\">\n      <InlineReveal show={minutes > 0} reduced={reduced}>\n        <NumberRoll value={minutes} suffix=\"m\" duration={480} />\n        &nbsp;\n      </InlineReveal>\n      <NumberRoll value={minutes ? total % 60 : total} format={minutes ? TWO_DIGITS : undefined} suffix=\"s\" direction=\"up\" duration={480} />\n    </span>\n  );\n}\n\nfunction Spinner({ spinning = true }: { spinning?: boolean }) {\n  return (\n    <span\n      aria-hidden=\"true\"\n      className={`size-3 shrink-0 rounded-full border-[1.5px] border-border border-t-foreground/70 motion-reduce:animate-none ${spinning ? \"animate-spin\" : \"\"}`}\n    />\n  );\n}\n\nfunction DrawnCheck({ drawn, reduced, className = \"size-3.5\" }: { drawn: boolean; reduced: boolean; className?: string }) {\n  return (\n    <svg viewBox=\"0 0 16 16\" fill=\"none\" className={className}>\n      <path\n        d=\"M3.5 8.5 6.5 11.5 12.5 4.5\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.9\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        pathLength={1}\n        strokeDasharray={1}\n        style={{ strokeDashoffset: drawn ? 0 : 1, transition: drawn && !reduced ? `stroke-dashoffset 360ms ${EASE_OUT} 90ms` : \"none\" }}\n      />\n    </svg>\n  );\n}\n\n/* ── ReasoningBand ───────────────────────────────────────── */\n\nexport interface ReasoningBandProps {\n  reasoning: ExpandableReasoning;\n  open: boolean;\n  onToggle: () => void;\n  meta?: React.ReactNode;\n  reduced: boolean;\n}\n\nexport function ReasoningBand({ reasoning, open, onToggle, meta, reduced }: ReasoningBandProps) {\n  const status: ExpandableReasoningStatus = reasoning.status ?? \"done\";\n  const running = status === \"running\";\n  const panelId = React.useId();\n  const listRef = React.useRef<HTMLDivElement>(null);\n  const [listHeight, setListHeight] = React.useState<number | null>(null);\n  const [initialCount] = React.useState(reasoning.steps.length);\n\n  React.useLayoutEffect(() => {\n    const el = listRef.current;\n    if (!el) return;\n    const observer = new ResizeObserver(() => {\n      const next = el.offsetHeight;\n      setListHeight((prev) => (prev === next ? prev : next));\n    });\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n\n  const [now, setNow] = React.useState(reasoning.startedAt ?? 0);\n  const [endedAt, setEndedAt] = React.useState<number | undefined>(undefined);\n  const [seenRunning, setSeenRunning] = React.useState(running);\n  if (running !== seenRunning) {\n    setSeenRunning(running);\n    if (running && endedAt !== undefined) setEndedAt(undefined);\n  }\n\n  React.useEffect(() => {\n    if (!running) {\n      if (endedAt !== undefined || reasoning.startedAt === undefined) return;\n      const frame = requestAnimationFrame(() => setEndedAt(Date.now()));\n      return () => cancelAnimationFrame(frame);\n    }\n    if (reasoning.startedAt === undefined) return;\n    const first = window.setTimeout(() => setNow(Date.now()), 0);\n    const timer = window.setInterval(() => setNow(Date.now()), 1000);\n    return () => {\n      window.clearTimeout(first);\n      window.clearInterval(timer);\n    };\n  }, [running, reasoning.startedAt, endedAt]);\n\n  const took = reasoning.durationMs ?? (reasoning.startedAt !== undefined && endedAt !== undefined ? endedAt - reasoning.startedAt : undefined);\n  const timed = status === \"done\" && !reasoning.doneLabel && took !== undefined;\n  const settledLabel =\n    status === \"error\" ? \"Stopped with error\" : status === \"cancelled\" ? \"Stopped thinking\" : timed ? \"Thought for\" : \"Thought it through\";\n  const label = running ? (reasoning.label ?? \"Thinking\") : (reasoning.doneLabel ?? settledLabel);\n  const showTime = (running && reasoning.startedAt !== undefined) || timed;\n  const elapsedMs = running ? Math.max(0, now - (reasoning.startedAt ?? now)) : (took ?? 0);\n\n  const headerKey = status === \"error\" ? \"error\" : status === \"cancelled\" ? \"cancelled\" : \"sparkle\";\n\n  return (\n    <div className=\"rounded-t-[17px] border-b border-border bg-muted/25\">\n      <div className=\"flex min-h-10 items-center justify-between gap-2 px-3.5 py-2 @[28rem]:px-5\">\n        <button\n          type=\"button\"\n          aria-expanded={open}\n          aria-controls={panelId}\n          onClick={onToggle}\n          className={`cursor-pointer -ml-1.5 inline-flex min-w-0 max-w-full items-center gap-2 rounded-lg px-1.5 py-1 text-[12.5px] font-medium transition-colors duration-150 hover:bg-accent ${INTERACTION_FOCUS}`}\n        >\n          <span aria-hidden=\"true\" className={`relative flex size-3.5 shrink-0 items-center justify-center ${running ? \"text-foreground\" : \"text-muted-foreground\"}`}>\n            <span className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(headerKey === \"sparkle\", reduced)}>\n              <Sparkle className=\"size-3.5\" fill=\"currentColor\" strokeWidth={0} />\n            </span>\n            <span className=\"absolute inset-0 flex items-center justify-center text-red-600 dark:text-red-400\" style={interactionIcon(headerKey === \"error\", reduced)}>\n              <AlertCircle className=\"size-3.5\" />\n            </span>\n            <span className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(headerKey === \"cancelled\", reduced)}>\n              <CircleSlash className=\"size-3.5\" />\n            </span>\n          </span>\n\n          <span className=\"flex min-w-0 items-baseline\">\n            <span className={`min-w-0 truncate ${running ? SHEEN : \"text-foreground/85\"}`}>\n              <TextMorph>{label}</TextMorph>\n            </span>\n            {(reasoning.startedAt !== undefined || reasoning.durationMs !== undefined) && (\n              <InlineReveal show={showTime} reduced={reduced} className=\"shrink-0\">\n                <span className=\"pl-1 text-[12px] font-normal text-muted-foreground\">\n                  <ElapsedSeconds ms={elapsedMs} reduced={reduced} />\n                </span>\n              </InlineReveal>\n            )}\n            {reasoning.steps.length > 0 && (\n              <span className=\"hidden shrink-0 items-baseline pl-1.5 text-[11.5px] font-normal text-muted-foreground @[22rem]:inline-flex\">\n                <span aria-hidden=\"true\" className=\"pr-1.5 text-muted-foreground/50\">\n                  ·\n                </span>\n                <NumberRoll value={reasoning.steps.length} duration={480} />\n                <span className=\"pl-[0.3em]\">{reasoning.steps.length === 1 ? \"step\" : \"steps\"}</span>\n              </span>\n            )}\n          </span>\n\n          <ChevronDown\n            aria-hidden=\"true\"\n            className={`size-3.5 shrink-0 text-muted-foreground transition-transform duration-300 motion-reduce:transition-none ${open ? \"rotate-180\" : \"\"}`}\n            style={{ transitionTimingFunction: EASE_OUT }}\n          />\n        </button>\n\n        {meta && <div className=\"shrink-0 text-[11.5px] text-muted-foreground\">{meta}</div>}\n      </div>\n\n      <div\n        id={panelId}\n        inert={!open}\n        className=\"overflow-clip\"\n        style={{\n          height: open ? (listHeight ?? \"auto\") : 0,\n          opacity: open ? 1 : 0,\n          transition: reduced || listHeight === null ? \"none\" : `height 420ms ${EASE_OUT}, opacity 280ms ${EASE_OUT}`,\n        }}\n      >\n        <div ref={listRef} className=\"border-t border-border/70 px-3.5 py-2.5 @[28rem]:px-5\">\n          <div className=\"relative ml-[5px] pl-4\">\n            <span aria-hidden=\"true\" className=\"absolute bottom-2 left-[3px] top-1.5 w-px bg-border\" />\n            <ul className=\"flex flex-col gap-0.5\">\n              {reasoning.steps.map((step, i) => {\n                const last = i === reasoning.steps.length - 1;\n                const stepStatus: ExpandableReasoningStepStatus =\n                  step.status ?? (last && running ? \"running\" : last && status === \"error\" ? \"error\" : \"done\");\n                const failed = stepStatus === \"error\";\n                const pending = stepStatus === \"pending\";\n                const delay = i < initialCount ? Math.min(i * 65, 260) : 0;\n\n                const rowInner = (\n                  <>\n                    <span aria-hidden=\"true\" className=\"relative mt-[3px] flex size-3.5 shrink-0 items-center justify-center\">\n                      <span className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(pending, reduced)}>\n                        <span className=\"size-2.5 rounded-full border-[1.5px] border-border\" />\n                      </span>\n                      <span className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(stepStatus === \"running\", reduced)}>\n                        <Spinner spinning={stepStatus === \"running\"} />\n                      </span>\n                      <span className=\"absolute inset-0 flex items-center justify-center text-muted-foreground\" style={interactionIcon(stepStatus === \"done\", reduced)}>\n                        <DrawnCheck drawn={stepStatus === \"done\"} reduced={reduced} className=\"size-3.5\" />\n                      </span>\n                      <span className=\"absolute inset-0 flex items-center justify-center text-red-600 dark:text-red-400\" style={interactionIcon(failed, reduced)}>\n                        <X className=\"size-3.5\" strokeWidth={2.3} />\n                      </span>\n                    </span>\n                    <span className=\"min-w-0 flex-1 text-[12.5px] leading-snug\">\n                      <span className={pending ? \"text-muted-foreground\" : \"text-foreground/90\"}>{step.label}</span>\n                      {step.detail && <span className=\"ml-1.5 inline-block whitespace-nowrap font-mono text-[11px] text-muted-foreground\">{step.detail}</span>}\n                    </span>\n                  </>\n                );\n\n                const rowClass = `flex w-full items-start gap-2 rounded-md px-1.5 py-1 text-left ${INTERACTION_FOCUS}`;\n\n                return (\n                  <li\n                    key={`${i}-${step.label}`}\n                    className=\"animate-[ui-fade-up_280ms_cubic-bezier(0.23,1,0.32,1)_backwards] motion-reduce:animate-none\"\n                    style={{ animationDelay: `${delay}ms` }}\n                  >\n                    {step.href ? (\n                      <a href={step.href} target=\"_blank\" rel=\"noreferrer\" className={`${rowClass} transition-colors hover:bg-accent`}>\n                        {rowInner}\n                      </a>\n                    ) : reasoning.onStepClick ? (\n                      <button type=\"button\" onClick={() => reasoning.onStepClick?.(step, i)} className={`${rowClass} cursor-pointer transition-colors hover:bg-accent`}>\n                        {rowInner}\n                      </button>\n                    ) : (\n                      <div className={rowClass}>{rowInner}</div>\n                    )}\n                  </li>\n                );\n              })}\n            </ul>\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n}\n\n/* ── SourceDotStack ──────────────────────────────────────── */\n\nexport function SourceDotStack({ sources, ringClass = \"ring-card\" }: { sources: ExpandableSource[]; ringClass?: string }) {\n  return (\n    <span className=\"flex items-center -space-x-1.5\" aria-hidden=\"true\">\n      {sources.slice(0, 4).map((source, i) =>\n        source.icon ? (\n          <span key={`${source.url}-${i}`} className={`flex size-3.5 items-center justify-center overflow-hidden rounded-full bg-background ring-2 ${ringClass}`}>\n            {source.icon}\n          </span>\n        ) : (\n          <span\n            key={`${source.url}-${i}`}\n            className={`size-3.5 rounded-full ring-2 ${ringClass}`}\n            style={{ backgroundColor: sourceColor(source, i) }}\n          />\n        ),\n      )}\n    </span>\n  );\n}\n\n/* ── SourcesDrawer ───────────────────────────────────────── */\n\nexport interface SourcesDrawerProps {\n  id: string;\n  sources: ExpandableSource[];\n  open: boolean;\n  activeIndex: number | null;\n  onSelectSource?: (source: ExpandableSource, index: number) => void;\n  reduced: boolean;\n}\n\nexport function SourcesDrawer({ id, sources, open, activeIndex, onSelectSource, reduced }: SourcesDrawerProps) {\n  const cardRefs = React.useRef<(HTMLAnchorElement | null)[]>([]);\n\n  React.useEffect(() => {\n    if (!open || activeIndex === null) return;\n    const el = cardRefs.current[activeIndex];\n    if (!el) return;\n    const timer = window.setTimeout(() => {\n      el.scrollIntoView({ behavior: reduced ? \"auto\" : \"smooth\", block: \"nearest\" });\n      if (!reduced) {\n        el.animate([{ transform: \"scale(0.985)\" }, { transform: \"none\" }], { duration: 340, easing: EASE_OUT });\n      }\n    }, 120);\n    return () => window.clearTimeout(timer);\n  }, [open, activeIndex, reduced]);\n\n  if (!sources.length) return null;\n\n  return (\n    <div\n      id={id}\n      inert={!open}\n      className=\"grid grid-cols-1\"\n      style={{\n        gridTemplateRows: open ? \"1fr\" : \"0fr\",\n        opacity: open ? 1 : 0,\n        transition: reduced ? \"none\" : `grid-template-rows 420ms ${EASE_OUT}, opacity ${open ? \"300ms\" : \"180ms\"} ${EASE_OUT}`,\n      }}\n    >\n      <div className={`min-h-0 min-w-0 overflow-clip ${open ? \"\" : \"pointer-events-none\"}`}>\n        <div className=\"border-t border-border bg-muted/20 px-3.5 py-3 @[28rem]:px-5 @[28rem]:py-3.5\">\n          <div className=\"mb-2.5 flex items-center justify-between gap-2\">\n            <p className=\"text-[11.5px] font-medium text-muted-foreground\">\n              Verified sources\n              <span className=\"ml-1.5 font-mono text-[11px] text-muted-foreground/70 tabular-nums\">({sources.length})</span>\n            </p>\n            {activeIndex !== null && sources[activeIndex] && (\n              <span className=\"truncate text-[11px] text-muted-foreground\">\n                Showing citation <span className=\"font-mono font-medium text-foreground\">[{activeIndex + 1}]</span>\n              </span>\n            )}\n          </div>\n\n          <div className=\"grid grid-cols-1 gap-2 @[28rem]:grid-cols-2\">\n            {sources.map((source, i) => {\n              const active = activeIndex === i;\n              const tone = sourceColor(source, i);\n              return (\n                <a\n                  key={`${source.url}-${i}`}\n                  ref={(node) => {\n                    cardRefs.current[i] = node;\n                  }}\n                  href={source.url}\n                  target=\"_blank\"\n                  rel=\"noreferrer\"\n                  onClick={() => onSelectSource?.(source, i)}\n                  className={`group flex min-w-0 flex-col gap-1.5 rounded-[12px] border border-border p-2.5 text-left transition-colors duration-150 ${\n                    active ? \"bg-muted\" : \"bg-card hover:bg-accent\"\n                  } ${INTERACTION_FOCUS}`}\n                >\n                  <div className=\"flex min-w-0 items-center justify-between gap-2\">\n                    <span className=\"flex min-w-0 items-center gap-1.5\">\n                      <span\n                        className={`inline-flex h-4 min-w-4 shrink-0 items-center justify-center rounded-[5px] px-1 font-mono text-[10px] font-medium leading-none transition-colors ${\n                          active ? \"bg-foreground text-background\" : \"bg-muted text-muted-foreground\"\n                        }`}\n                      >\n                        {i + 1}\n                      </span>\n                      <span aria-hidden=\"true\" className=\"flex size-3.5 shrink-0 items-center justify-center overflow-hidden rounded-full\">\n                        {source.icon ?? (\n                          <span className=\"flex size-3.5 items-center justify-center rounded-full\" style={{ backgroundColor: tone }}>\n                            <Globe className=\"size-2 text-white\" strokeWidth={2.4} />\n                          </span>\n                        )}\n                      </span>\n                      <span className=\"min-w-0 truncate text-[11.5px] text-muted-foreground\">{hostnameOf(source.url)}</span>\n                    </span>\n                    <ArrowUpRight\n                      aria-hidden=\"true\"\n                      className=\"size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-200 group-hover:translate-x-0.5 group-hover:-translate-y-0.5 group-hover:text-foreground motion-reduce:transition-none\"\n                    />\n                  </div>\n                  <p className=\"line-clamp-2 text-[12.5px] font-medium leading-snug text-foreground\">{source.title}</p>\n                  {source.snippet && <p className=\"line-clamp-2 text-[11.5px] leading-relaxed text-muted-foreground\">{source.snippet}</p>}\n                </a>\n              );\n            })}\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n}\n\n/* ── AnswerFooterBar ─────────────────────────────────────── */\n\nfunction ToolbarIconButton({\n  label,\n  pressed,\n  disabled,\n  onClick,\n  children,\n}: {\n  label: string;\n  pressed?: boolean;\n  disabled?: boolean;\n  onClick: () => void;\n  children: React.ReactNode;\n}) {\n  return (\n    <button\n      type=\"button\"\n      aria-label={label}\n      aria-pressed={pressed}\n      disabled={disabled}\n      onClick={onClick}\n      className={`cursor-pointer disabled:cursor-default relative flex size-7 items-center justify-center rounded-lg transition-colors duration-150 hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-40 ${\n        pressed ? \"bg-accent text-foreground\" : \"text-muted-foreground\"\n      } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n    >\n      {children}\n    </button>\n  );\n}\n\nfunction ThumbGlyph({ down, filled, reduced }: { down?: boolean; filled: boolean; reduced: boolean }) {\n  const ref = React.useRef<HTMLSpanElement>(null);\n  const first = React.useRef(true);\n  React.useEffect(() => {\n    if (first.current) {\n      first.current = false;\n      return;\n    }\n    if (!filled || reduced) return;\n    ref.current?.animate([{ transform: \"scale(0.78) rotate(-9deg)\" }, { transform: \"none\" }], { duration: 420, easing: EASE_THROW });\n  }, [filled, reduced]);\n  const Icon = down ? ThumbsDown : ThumbsUp;\n  return (\n    <span ref={ref} className=\"flex\">\n      <Icon className=\"size-3.5\" style={{ fill: filled ? \"currentColor\" : \"transparent\", transition: reduced ? \"none\" : `fill 220ms ${EASE_OUT}` }} />\n    </span>\n  );\n}\n\nexport interface AnswerFooterBarProps {\n  footerRef?: React.Ref<HTMLDivElement>;\n  copyText?: string;\n  onRegenerate?: () => void;\n  feedback?: ExpandableFeedback;\n  defaultFeedback?: ExpandableFeedback;\n  onFeedback?: (value: ExpandableFeedback) => void;\n  canCollapse: boolean;\n  expanded: boolean;\n  bodyId: string;\n  onToggleExpand: () => void;\n  expandLabel: string;\n  collapseLabel: string;\n  sources: ExpandableSource[];\n  sourcesOpen: boolean;\n  sourcesPanelId: string;\n  onToggleSources: () => void;\n  disabled?: boolean;\n  reduced: boolean;\n}\n\nexport function AnswerFooterBar({\n  footerRef,\n  copyText,\n  onRegenerate,\n  feedback,\n  defaultFeedback = null,\n  onFeedback,\n  canCollapse,\n  expanded,\n  bodyId,\n  onToggleExpand,\n  expandLabel,\n  collapseLabel,\n  sources,\n  sourcesOpen,\n  sourcesPanelId,\n  onToggleSources,\n  disabled,\n  reduced,\n}: AnswerFooterBarProps) {\n  const [copied, setCopied] = React.useState(false);\n  const [ownFeedback, setOwnFeedback] = React.useState<ExpandableFeedback>(defaultFeedback);\n  const currentFeedback = feedback !== undefined ? feedback : ownFeedback;\n\n  React.useEffect(() => {\n    if (!copied) return;\n    const timer = window.setTimeout(() => setCopied(false), 1600);\n    return () => window.clearTimeout(timer);\n  }, [copied]);\n\n  const copy = async () => {\n    if (!copyText) return;\n    try {\n      await navigator.clipboard.writeText(copyText);\n      setCopied(true);\n    } catch {\n      // Clipboard blocked by browser policy.\n    }\n  };\n\n  const rate = (value: \"up\" | \"down\") => {\n    const next = currentFeedback === value ? null : value;\n    if (feedback === undefined) setOwnFeedback(next);\n    onFeedback?.(next);\n  };\n\n  return (\n    <div ref={footerRef} className=\"flex flex-wrap items-center justify-between gap-2 border-t border-border px-3.5 py-2 @[28rem]:px-5\">\n      <div className=\"flex items-center gap-0.5\">\n        {copyText !== undefined && (\n          <ToolbarIconButton label=\"Copy answer\" disabled={disabled} onClick={copy}>\n            <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(!copied, reduced)}>\n              <Copy className=\"size-3.5\" />\n            </span>\n            <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center text-emerald-600 dark:text-emerald-400\" style={interactionIcon(copied, reduced)}>\n              <DrawnCheck drawn={copied} reduced={reduced} className=\"size-3.5\" />\n            </span>\n          </ToolbarIconButton>\n        )}\n        {onRegenerate && (\n          <ToolbarIconButton label=\"Regenerate answer\" disabled={disabled} onClick={onRegenerate}>\n            <RotateCcw className=\"size-3.5\" />\n          </ToolbarIconButton>\n        )}\n        <ToolbarIconButton label=\"Helpful\" pressed={currentFeedback === \"up\"} disabled={disabled} onClick={() => rate(\"up\")}>\n          <ThumbGlyph filled={currentFeedback === \"up\"} reduced={reduced} />\n        </ToolbarIconButton>\n        <ToolbarIconButton label=\"Not helpful\" pressed={currentFeedback === \"down\"} disabled={disabled} onClick={() => rate(\"down\")}>\n          <ThumbGlyph down filled={currentFeedback === \"down\"} reduced={reduced} />\n        </ToolbarIconButton>\n\n        <InlineReveal show={canCollapse && expanded} reduced={reduced}>\n          <span className=\"inline-flex items-center\">\n            <span aria-hidden=\"true\" className=\"mx-1 h-3.5 w-px bg-border\" />\n            <button\n              type=\"button\"\n              aria-expanded={expanded}\n              aria-controls={bodyId}\n              tabIndex={canCollapse && expanded ? 0 : -1}\n              onClick={onToggleExpand}\n              className={`cursor-pointer inline-flex h-7.5 items-center gap-1 rounded-lg px-2 text-[12px] font-medium text-muted-foreground transition-colors duration-150 hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n            >\n              <TextMorph>{expanded ? collapseLabel : expandLabel}</TextMorph>\n              <ChevronDown\n                aria-hidden=\"true\"\n                className={`size-3.5 transition-transform duration-300 motion-reduce:transition-none ${expanded ? \"rotate-180\" : \"\"}`}\n                style={{ transitionTimingFunction: EASE_OUT }}\n              />\n            </button>\n          </span>\n        </InlineReveal>\n      </div>\n\n      <span role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n        {copied ? \"Copied to clipboard\" : \"\"}\n      </span>\n\n      {sources.length > 0 && (\n        <button\n          type=\"button\"\n          aria-expanded={sourcesOpen}\n          aria-controls={sourcesPanelId}\n          aria-label={`${sources.length} ${sources.length === 1 ? \"source\" : \"sources\"}`}\n          onClick={onToggleSources}\n          className={`cursor-pointer inline-flex h-7 items-center gap-1.5 rounded-full px-2 text-[12px] font-medium transition-colors duration-150 ${\n            sourcesOpen ? \"bg-muted text-foreground\" : \"text-muted-foreground hover:bg-accent hover:text-foreground\"\n          } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n        >\n          <SourceDotStack sources={sources} ringClass={sourcesOpen ? \"ring-muted\" : \"ring-card\"} />\n          <span className=\"inline-flex items-baseline gap-[0.3em] tabular-nums\">\n            <NumberRoll value={sources.length} duration={540} />\n            <span className=\"hidden @[20rem]:inline\">{sources.length === 1 ? \"source\" : \"sources\"}</span>\n          </span>\n          <ChevronDown\n            aria-hidden=\"true\"\n            className={`size-3 text-muted-foreground transition-transform duration-300 motion-reduce:transition-none ${sourcesOpen ? \"rotate-180\" : \"\"}`}\n            style={{ transitionTimingFunction: EASE_OUT }}\n          />\n        </button>\n      )}\n    </div>\n  );\n}\n\n/* ── FollowUpList ────────────────────────────────────────── */\n\nexport interface FollowUpListProps {\n  items: string[];\n  label: string;\n  show: boolean;\n  onSelect?: (question: string) => void;\n  reduced: boolean;\n}\n\nexport function FollowUpList({ items, label, show, onSelect, reduced }: FollowUpListProps) {\n  if (!items.length) return null;\n\n  return (\n    <div\n      inert={!show}\n      className=\"grid grid-cols-1\"\n      style={{\n        gridTemplateRows: show ? \"1fr\" : \"0fr\",\n        opacity: show ? 1 : 0,\n        transition: reduced ? \"none\" : `grid-template-rows 420ms ${EASE_OUT}, opacity 280ms ${EASE_OUT}`,\n      }}\n    >\n      <div className={`min-h-0 min-w-0 overflow-clip ${show ? \"\" : \"pointer-events-none\"}`}>\n        <div className=\"rounded-b-[17px] border-t border-border px-3.5 py-2.5 @[28rem]:px-5 @[28rem]:py-3\">\n          <p className=\"mb-1.5 text-[11.5px] font-medium text-muted-foreground\">{label}</p>\n          <ul className=\"flex flex-col gap-0.5\">\n            {items.map((item) => (\n              <li key={item}>\n                <button\n                  type=\"button\"\n                  onClick={() => onSelect?.(item)}\n                  className={`group cursor-pointer -mx-1.5 flex w-[calc(100%_+_0.75rem)] items-start gap-2 rounded-lg px-2 py-1.5 text-left text-[13px] leading-snug text-foreground transition-colors duration-150 hover:bg-accent ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n                >\n                  <CornerDownRight\n                    aria-hidden=\"true\"\n                    className=\"mt-[2px] size-3.5 shrink-0 text-muted-foreground transition-transform duration-200 group-hover:translate-x-0.5 group-hover:text-foreground motion-reduce:transition-none\"\n                  />\n                  <span className=\"min-w-0 flex-1\">{item}</span>\n                </button>\n              </li>\n            ))}\n          </ul>\n        </div>\n      </div>\n    </div>\n  );\n}\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · expandable-answer · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n'use client';\n\nimport * as React from 'react';\n\nexport const EASE_OUT = 'cubic-bezier(0.16, 1, 0.3, 1)';\nexport const EASE_SETTLE = 'cubic-bezier(0.22, 1.18, 0.36, 1)';\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = 'cubic-bezier(0.34, 1.36, 0.64, 1)';\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  'transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100';\nexport const INTERACTION_FOCUS ='focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst query = '(prefers-reduced-motion: reduce)';\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener('change', notify);\n  return () => media.removeEventListener('change', notify);\n};\nexport const useInteractionReducedMotion = () => React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility(); document.addEventListener('visibilitychange', visibility);\n    return () => { observer.disconnect(); document.removeEventListener('visibilitychange', visibility); };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(on: boolean, reduced: boolean): React.CSSProperties {\n  return { opacity: on ? 1 : 0, transform: on ? 'none' : 'scale(0.6)', filter: on ? 'blur(0px)' : 'blur(3px)', transition: reduced ? 'none' : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}` };\n}\n\n/** A raised object: one tight contact shadow, one short ambient, a hairline of light on its top edge. */\nexport const MATERIAL_LIFT =\n  'shadow-[0_1px_1.5px_rgb(0_0_0/0.07),0_3px_8px_-2px_rgb(0_0_0/0.1),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.5),0_4px_10px_-2px_rgb(0_0_0/0.35),inset_0_0.5px_0_rgb(255_255_255/0.1)]';\n/** A trough something sits in, shaded from above, lit along its bottom edge. */\nexport const MATERIAL_RECESS =\n  'shadow-[inset_0_1px_2.5px_rgb(0_0_0/0.09),inset_0_-0.5px_0_rgb(255_255_255/0.7)] dark:shadow-[inset_0_1px_3px_rgb(0_0_0/0.45),inset_0_-0.5px_0_rgb(255_255_255/0.07)]';\n\nexport type SpringConfig = { stiffness: number; damping: number; mass?: number };\nexport interface Spring {\n  get(): number;\n  getVelocity(): number;\n  getTarget(): number;\n  /** Aim somewhere new from wherever it is now, keeping its speed. */\n  set(target: number): void;\n  /** Add speed (units per second), on top of what it already has. */\n  push(velocity: number): void;\n  /** Be there now, at rest. */\n  jump(value: number): void;\n  configure(config: SpringConfig): void;\n  stop(): void;\n}\n\n// Every moving spring on the page shares one frame loop, which sleeps when the last one rests. Each spring's onFrame runs\n// once per frame after all of them have stepped, so several springs that draw one shape paint it once.\nconst SPRING_STEP = 1 / 240;\ntype Running = { step: () => void };\nconst runningSprings = new Set<Running>();\nconst springPainters = new Set<() => void>();\nlet springFrame = 0;\nlet springLast = 0;\nlet springSpare = 0;\n\nfunction springTick(now: number) {\n  // A hidden tab stops the frames, so the first one back must not count the whole gap as time passed.\n  springSpare += Math.min((now - springLast) / 1000, 0.05);\n  springLast = now;\n  while (springSpare >= SPRING_STEP) {\n    runningSprings.forEach((spring) => spring.step());\n    springSpare -= SPRING_STEP;\n  }\n  const painters = [...springPainters];\n  springPainters.clear();\n  painters.forEach((paint) => paint());\n  springFrame = runningSprings.size ? requestAnimationFrame(springTick) : 0;\n}\n\nfunction wakeSprings(spring: Running) {\n  runningSprings.add(spring);\n  if (springFrame) return;\n  springSpare = 0;\n  springFrame = requestAnimationFrame((now) => {\n    springLast = now - 1000 / 60;\n    springTick(now);\n  });\n}\n\n/**\n * A spring that carries its speed: re-aim it mid-flight and it curves on from where it is, push it while it swings and the\n * push adds to the swing. Use it for anything that can be interrupted; a curve restarts from a standstill every time.\n * `onFrame` should write straight to the DOM. `precision` is how close counts as there, in the value's own units.\n */\nexport function createSpring(initial: number, config: SpringConfig, onFrame: () => void, precision = 0.01): Spring {\n  let value = initial;\n  let velocity = 0;\n  let target = initial;\n  let { stiffness, damping, mass = 1 } = config;\n  const running: Running = {\n    step() {\n      velocity += ((-stiffness * (value - target) - damping * velocity) / mass) * SPRING_STEP;\n      value += velocity * SPRING_STEP;\n      if (Math.abs(value - target) < precision && Math.abs(velocity) < precision * 10) {\n        value = target;\n        velocity = 0;\n        runningSprings.delete(running);\n      }\n      springPainters.add(onFrame);\n    },\n  };\n  return {\n    get: () => value,\n    getVelocity: () => velocity,\n    getTarget: () => target,\n    set(next) {\n      if (next === target && !runningSprings.has(running)) return;\n      target = next;\n      wakeSprings(running);\n    },\n    push(speed) {\n      velocity += speed;\n      wakeSprings(running);\n    },\n    jump(next) {\n      value = next;\n      target = next;\n      velocity = 0;\n      runningSprings.delete(running);\n      onFrame();\n    },\n    configure(next) {\n      ({ stiffness, damping, mass = 1 } = next);\n    },\n    stop() {\n      runningSprings.delete(running);\n    },\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(samples: PointerSample[], x: number, time: number) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100) return 0;\n  const first = samples[0], last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(overshoot: number, dimension = 320, constant = 0.55): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(distance: number, velocity: number, time = 0.12): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(velocity: number, distanceToTarget: number, factor = 10): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient = (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value = to + Math.exp(-damping * omega * t) * (displacement * Math.cos(damped * t) + coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n\n"}],"css":{"@keyframes ui-sheen":{"from":{"mask-position":"150% 0"},"to":{"mask-position":"-50% 0"}},"@keyframes ui-scan":{"from":{"transform":"translateX(-100%)"},"to":{"transform":"translateX(250%)"}},"@keyframes ui-fade-up":{"from":{"opacity":"0","transform":"translateY(4px)"},"to":{"opacity":"1","transform":"none"}},"@keyframes ui-fade-in":{"from":{"opacity":"0"},"to":{"opacity":"1"}},"@keyframes ui-ping":{"from":{"transform":"scale(1)","opacity":"0.55"},"to":{"transform":"scale(2.6)","opacity":"0"}}},"docs":"Docs and live preview: https://hairlineui.com/ui/expandable-answer. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}