# Animated Reasoning for UI SDK (/docs/components/reasoning)

The thinking behind an AI answer, behind a disclosure: "Thinking…" has a light passing through it while the model works, the thinking opens on its own and closes into "Thought for 12s" when it ends, and it streams in as muted markdown.

<ComponentPreview slug="reasoning" source="{&#x22;code&#x22;:&#x22;\&#x22;use client\&#x22;\n\nimport * as React from \&#x22;react\&#x22;;\n\nimport { Markdown } from \&#x22;@/components/keyframery/markdown\&#x22;;\nimport {\n  Reasoning,\n  ReasoningContent,\n  ReasoningTrigger,\n} from \&#x22;@/components/keyframery/reasoning\&#x22;;\n\nconst question =\n  \&#x22;Alfama flat at €148 a night (4th floor, no lift) or Príncipe Real at €171 (ground floor)? Mum is coming with us.\&#x22;;\n\nconst thinking = `**Weighing the stairs against the price.** Alfama is €23 a night cheaper, so €69 over three nights.\n\nIt is a fourth floor with no lift, though, and the streets around it are steep cobbles. With Mum along, that counts every time they go out.\n\nPríncipe Real:\n- ground floor, no stairs at all\n- flatter streets, five minutes from the Rato metro\n- the extra €69 split four ways is about €17 each\n\nThat is an easy trade. Recommend Príncipe Real, and keep Alfama only as the budget option.`;\n\nconst answer = `Book **Príncipe Real**. It costs about **€17 more each** for the three nights, but it is on the ground floor and the streets around it are flat, which Mum will thank you for by day two.\n\nAlfama only wins if the budget is tight.`;\n\nconst words = (text: string) => text.match(/\\s*\\S+/g) ?? [];\n\ntype Phase = \&#x22;done\&#x22; | \&#x22;thinking\&#x22; | \&#x22;answering\&#x22;;\n\nexport default function ReasoningDemo({\n  autoClose = true,\n  defaultOpen = false,\n  timing = \&#x22;measured\&#x22;,\n  thinkingLabel = \&#x22;Thinking…\&#x22;,\n  doneLabel = \&#x22;Thought for {s}s\&#x22;,\n  themeInk = \&#x22;\&#x22;,\n  themeText = \&#x22;\&#x22;,\n  themeRule = \&#x22;\&#x22;,\n  themeFont = 13,\n  themeIndent = 14,\n  themeMaxHeight = 288,\n}: {\n  autoClose?: boolean;\n  defaultOpen?: boolean;\n  timing?: \&#x22;measured\&#x22; | \&#x22;given\&#x22;;\n  thinkingLabel?: string;\n  doneLabel?: string;\n  themeInk?: string;\n  themeText?: string;\n  themeRule?: string;\n  themeFont?: number;\n  themeIndent?: number;\n  themeMaxHeight?: number;\n}) {\n  const [phase, setPhase] = React.useState<Phase>(\&#x22;done\&#x22;);\n  const [thought, setThought] = React.useState(thinking);\n  const [said, setSaid] = React.useState(answer);\n  const [runs, setRuns] = React.useState(0);\n  const timer = React.useRef<ReturnType<typeof setTimeout>>(undefined);\n  React.useEffect(() => () => clearTimeout(timer.current), []);\n\n  /* Stream a text a few words at a time, then call `done`. */\n  const stream = (\n    text: string,\n    set: (s: string) => void,\n    speed: number,\n    done: () => void,\n  ) => {\n    const all = words(text);\n    let at = 0;\n    const tick = () => {\n      at = Math.min(all.length, at + 1 + (at % 4 === 0 ? 1 : 0));\n      set(all.slice(0, at).join(\&#x22;\&#x22;));\n      if (at >= all.length) {\n        done();\n        return;\n      }\n      timer.current = setTimeout(tick, (42 + (at % 5) * 9) * speed);\n    };\n    tick();\n  };\n\n  const ask = (e: React.MouseEvent<HTMLButtonElement>) => {\n    const speed =\n      parseFloat(\n        getComputedStyle(e.currentTarget).getPropertyValue(\&#x22;--kf-speed\&#x22;),\n      ) || 1;\n    clearTimeout(timer.current);\n    setRuns((r) => r + 1);\n    setThought(\&#x22;\&#x22;);\n    setSaid(\&#x22;\&#x22;);\n    setPhase(\&#x22;thinking\&#x22;);\n    timer.current = setTimeout(\n      () =>\n        stream(thinking, setThought, speed * 1.6, () => {\n          timer.current = setTimeout(() => {\n            setPhase(\&#x22;answering\&#x22;);\n            timer.current = setTimeout(\n              () => stream(answer, setSaid, speed, () => setPhase(\&#x22;done\&#x22;)),\n              420 * speed,\n            );\n          }, 300 * speed);\n        }),\n      500 * speed,\n    );\n  };\n\n  /* Leave defaults unset so each part keeps its own theme and size fallback. */\n  const theme = {\n    ...(themeInk ? { \&#x22;--reasoning-ink\&#x22;: themeInk } : null),\n    ...(themeText ? { \&#x22;--reasoning-text\&#x22;: themeText } : null),\n    ...(themeRule ? { \&#x22;--reasoning-rule\&#x22;: themeRule } : null),\n    ...(themeFont !== 13 ? { \&#x22;--reasoning-font\&#x22;: `${themeFont}px` } : null),\n    ...(themeIndent !== 14\n      ? { \&#x22;--reasoning-indent\&#x22;: `${themeIndent}px` }\n      : null),\n    ...(themeMaxHeight !== 288\n      ? { \&#x22;--reasoning-max-height\&#x22;: `${themeMaxHeight}px` }\n      : null),\n  } as React.CSSProperties;\n\n  /* Before the first run there is nothing measured yet, so the demo starts from a known time. */\n  const duration = timing === \&#x22;given\&#x22; ? 12 : runs === 0 ? 5 : undefined;\n\n  return (\n    <div\n      style={theme}\n      className=\&#x22;@container flex h-[440px] w-full max-w-[480px] flex-col\&#x22;\n    >\n      <div className=\&#x22;min-h-0 flex-1 overflow-y-auto overscroll-contain [scrollbar-width:none] [mask-image:linear-gradient(to_bottom,black_calc(100%-24px),transparent)]\&#x22;>\n        <div className=\&#x22;flex justify-end\&#x22;>\n          <div className=\&#x22;max-w-[85%] rounded-[16px] rounded-br-[6px] bg-muted px-3.5 py-2.5 text-[13px] leading-snug\&#x22;>\n            {question}\n          </div>\n        </div>\n\n        <Reasoning\n          key={`${defaultOpen}`}\n          className=\&#x22;mt-5\&#x22;\n          streaming={phase === \&#x22;thinking\&#x22;}\n          duration={duration}\n          autoClose={autoClose}\n          defaultOpen={defaultOpen}\n        >\n          <ReasoningTrigger\n            thinkingLabel={thinkingLabel}\n            doneLabel={(seconds) =>\n              seconds === undefined\n                ? \&#x22;Thought for a few seconds\&#x22;\n                : doneLabel.replace(\&#x22;{s}\&#x22;, String(seconds))\n            }\n          />\n          <ReasoningContent>{thought}</ReasoningContent>\n        </Reasoning>\n\n        <Markdown\n          className=\&#x22;mt-3\&#x22;\n          streaming={phase === \&#x22;answering\&#x22;}\n          aria-label=\&#x22;Answer\&#x22;\n        >\n          {said}\n        </Markdown>\n      </div>\n\n      <div className=\&#x22;flex shrink-0 items-center justify-end pt-3\&#x22;>\n        <button\n          type=\&#x22;button\&#x22;\n          data-play=\&#x22;ask\&#x22;\n          onClick={ask}\n          disabled={phase !== \&#x22;done\&#x22;}\n          className=\&#x22;inline-flex h-7 items-center gap-1.5 rounded-[8px] px-2.5 text-[12px] leading-none font-medium text-muted-foreground outline-none transition-[scale,color,background-color,opacity] duration-[calc(150ms*var(--kf-speed,1))] ease-house hover:bg-foreground/[0.045] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring active:scale-[calc(1-0.04*var(--kf-flourish,1))] disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none\&#x22;\n        >\n          <svg\n            viewBox=\&#x22;0 0 16 16\&#x22;\n            fill=\&#x22;none\&#x22;\n            stroke=\&#x22;currentColor\&#x22;\n            strokeWidth=\&#x22;1.5\&#x22;\n            strokeLinecap=\&#x22;round\&#x22;\n            strokeLinejoin=\&#x22;round\&#x22;\n            aria-hidden\n            className=\&#x22;size-3.5\&#x22;\n          >\n            <path d=\&#x22;M13.25 8a5.25 5.25 0 1 1-1.54-3.71M13.25 2.75v2.5h-2.5\&#x22; />\n          </svg>\n          Ask again\n        </button>\n      </div>\n    </div>\n  );\n}&#x22;,&#x22;bindings&#x22;:{&#x22;autoClose&#x22;:[1268,1272],&#x22;defaultOpen&#x22;:[1290,1295],&#x22;timing&#x22;:[1308,1318],&#x22;thinkingLabel&#x22;:[1338,1349],&#x22;doneLabel&#x22;:[1365,1383],&#x22;themeInk&#x22;:[1398,1400],&#x22;themeText&#x22;:[1416,1418],&#x22;themeRule&#x22;:[1434,1436],&#x22;themeFont&#x22;:[1452,1454],&#x22;themeIndent&#x22;:[1472,1474],&#x22;themeMaxHeight&#x22;:[1495,1498]},&#x22;root&#x22;:[4135,6518],&#x22;importOffset&#x22;:213}" />

## Installation [#installation]

**React**

**CLI**

```bash
npx shadcn@latest add @keyframery/reasoning
```

This adds `components/keyframery/reasoning.tsx` and its primitive to your project, and installs UI SDK, along with `agent-content`, [collapsible](/docs/components/collapsible), [markdown](/docs/components/markdown), which it builds on. The motion tokens are added to your global CSS the first time you install a component.

**Manual**

**Install the dependencies**

```bash
npm install @ui-sdk/core@0.1.0-beta.17 @ui-sdk/react@0.1.0-beta.17 clsx tailwind-merge
```

**Add the motion tokens**

Copy the [motion tokens](/docs/installation/manual#add-the-motion-tokens) into your global CSS, and this file into `lib/keyframery.tsx`. Every component shares them.

**lib/keyframery.tsx**

```tsx
"use client"

/* Speed for Keyframery components, as a prop.

   Every duration in the components is written as calc(Nms * var(--kf-speed, 1)). These helpers set
   that variable for you, so nobody has to know it exists:

     <Tabs speed="fast">                      one component
     <KeyframeryProvider speed="slow">        the whole app

   Parts that render in a portal (popups, menus, dialogs) are not inside the component in the page,
   so they pick the speed up through React context instead of the CSS cascade. */

import * as React from "react"

/** `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or any multiplier: `0.8` is 20% quicker. */
export type Speed = "fast" | "normal" | "slow" | number

export type SpeedProps = {
  /** How fast the component moves. `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or a multiplier like `0.8`. Popups follow it too. */
  speed?: Speed
}

export type MotionStyleName = "subtle" | "springy" | "calm" | "snappy" | "playful"

const presets = { fast: 0.6, normal: 1, slow: 1.4 } as const

export function speedValue(speed: Speed | undefined): number | undefined {
  if (speed === undefined) return undefined
  return typeof speed === "number" ? speed : presets[speed]
}

const SpeedContext = React.createContext<number | undefined>(undefined)

type SpeedStyle = React.CSSProperties & { "--kf-speed"?: number }

/* Wraps a component's parts. Without `speed` it adds nothing to the page. With it, a
   `display: contents` element carries the variable to the parts in place, and context carries it
   to the parts in a portal. */
export function Speed({ speed, children }: SpeedProps & { children?: React.ReactNode }) {
  const value = speedValue(speed)
  if (value === undefined) return children
  const style: SpeedStyle = { display: "contents", "--kf-speed": value }
  return (
    <SpeedContext value={value}>
      <span data-slot="speed" style={style}>
        {children}
      </span>
    </SpeedContext>
  )
}

/* For parts that render in a portal: adds the speed of the component they belong to. `style` can
   be an object or UI SDK's function of the part's state. */
export function useSpeedStyle<S>(style: S): S {
  return withSpeed(style, React.useContext(SpeedContext))
}

/* Adds a speed to a part's own `style`, for a part that takes `speed` and renders in a portal. */
export function withSpeed<S>(style: S, speed: Speed | undefined): S {
  const value = speedValue(speed)
  if (value === undefined) return style
  if (typeof style === "function")
    return ((state: unknown) => ({ "--kf-speed": value, ...(style as (s: unknown) => React.CSSProperties)(state) })) as S
  return { "--kf-speed": value, ...(style as React.CSSProperties | undefined) } as S
}

/* UI SDK parts take `children` as content or as a function of the part's state. A styled part
   that adds elements of its own (a chevron, a moving key) wraps either form with this, so the
   function form keeps working. */
export function mapChildren<State>(
  children: React.ReactNode | ((state: State) => React.ReactNode),
  wrap: (content: React.ReactNode) => React.ReactNode,
): React.ReactNode | ((state: State) => React.ReactNode) {
  return typeof children === "function" ? (state: State) => wrap(children(state)) : wrap(children)
}

/* Sets speed and motion style for the whole app, popups included. A component's own `speed` prop
   still wins inside that component. Server-rendered pages can put `data-motion` on <html> directly
   to avoid a change after hydration. */
export function KeyframeryProvider({
  speed,
  motion,
  children,
}: SpeedProps & {
  /** The motion style for the whole app: `"subtle"` (the default), `"calm"`, `"springy"`, `"snappy"` or `"playful"`. */
  motion?: MotionStyleName
  children?: React.ReactNode
}) {
  const value = speedValue(speed)
  React.useLayoutEffect(() => {
    const html = document.documentElement
    if (motion) html.setAttribute("data-motion", motion)
    if (value !== undefined) html.style.setProperty("--kf-speed", String(value))
    return () => {
      if (motion) html.removeAttribute("data-motion")
      if (value !== undefined) html.style.removeProperty("--kf-speed")
    }
  }, [motion, value])
  return children
}
```

**Add what it builds on**

Install [collapsible](/docs/components/collapsible), [markdown](/docs/components/markdown) the same way first. Add `agent-content` with the CLI: `npx shadcn@latest add @keyframery/agent-content`.

**Copy the component**

**components/keyframery/reasoning.tsx**

```tsx
"use client"

export * from "@/components/keyframery/primitives/reasoning"

/* Theming variables (set on a part or ancestor; absent values preserve the theme):
   --reasoning-ink: Trigger text; default: text-muted-foreground.
   --reasoning-text: Thinking text; default: text-muted-foreground.
   --reasoning-font: Thinking size; default: text-[13px].
   --reasoning-rule: Rule beside the thinking; default: border-border.
   --reasoning-indent: Thinking indent; default: ps-3.5.
   --reasoning-max-height: Tallest the thinking gets before it scrolls; default: max-h-72.
*/

/* Styled reasoning: the animated primitive plus the Keyframery look. A quiet muted trigger that wakes
   on hover; the thinking hangs off a hairline in smaller muted text, rendered with Keyframery's
   markdown, and scrolls once it gets long. */

import * as React from "react"

import { Markdown } from "@/components/keyframery/markdown"
import {
  Reasoning as ReasoningRoot,
  ReasoningContent as ReasoningContentPrimitive,
  ReasoningContext,
  ReasoningLabel,
  ReasoningTrigger as ReasoningTriggerPrimitive,
  type ReasoningProps,
} from "@/components/keyframery/primitives/reasoning"
import { Speed, type SpeedProps } from "@/lib/keyframery"
import { cn } from "@/lib/utils"

/* UI SDK accepts a class name or a function of state; keep both working. */
function withClass<S>(base: string, className: string | ((state: S) => string | undefined) | undefined) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

function Reasoning({ speed, className, ...props }: ReasoningProps & SpeedProps) {
  return (
    <Speed speed={speed}>
      <ReasoningRoot className={withClass("flex w-full min-w-0 flex-col", className)} {...props} />
    </Speed>
  )
}

function ReasoningTrigger({ className, ...props }: React.ComponentProps<typeof ReasoningTriggerPrimitive>) {
  return (
    <ReasoningTriggerPrimitive
      className={withClass(
        cn(
          "-mx-1.5 flex h-7 w-fit max-w-full min-w-0 cursor-pointer items-center gap-1 rounded-[7px] px-1.5 text-start text-[13px] leading-none font-medium outline-none select-none",
          "text-[color:var(--reasoning-ink,var(--muted-foreground))] transition-[color,background-color] duration-[calc(150ms*var(--kf-speed,1))] ease-house motion-reduce:transition-none",
          "hover:text-foreground data-open:text-foreground in-data-streaming:text-foreground",
          "*:data-[slot=reasoning-chevron]:text-muted-foreground/70",
          "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
          "*:data-[slot=reasoning-label]:truncate *:data-[slot=reasoning-label]:py-px",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* Pass the thinking as a markdown string (it streams with the trigger's `streaming`), or your own content. */
function ReasoningContent({ className, children, ...props }: React.ComponentProps<typeof ReasoningContentPrimitive>) {
  const { streaming } = React.useContext(ReasoningContext)
  return (
    <ReasoningContentPrimitive
      className={withClass(
        cn(
          "ms-[3px] min-w-0 border-s border-[color:var(--reasoning-rule,var(--border))]",
          "*:data-[slot=reasoning-scroll]:mt-2 *:data-[slot=reasoning-scroll]:mb-1 *:data-[slot=reasoning-scroll]:max-h-[var(--reasoning-max-height,18rem)] *:data-[slot=reasoning-scroll]:overflow-y-auto *:data-[slot=reasoning-scroll]:overscroll-contain *:data-[slot=reasoning-scroll]:[scrollbar-width:thin]",
          "*:data-[slot=reasoning-scroll]:ps-[var(--reasoning-indent,0.875rem)] *:data-[slot=reasoning-scroll]:text-[length:var(--reasoning-font,13px)] *:data-[slot=reasoning-scroll]:leading-relaxed",
          "*:data-[slot=reasoning-scroll]:text-[color:var(--reasoning-text,var(--muted-foreground))]",
        ),
        className,
      )}
      {...props}
    >
      {typeof children === "string" ? (
        <Markdown
          streaming={streaming}
          caret={false}
          className="[--markdown-font:var(--reasoning-font,13px)] [--markdown-gap:0.5rem] [--markdown-ink:var(--reasoning-text,var(--muted-foreground))] [&_[data-slot=markdown-heading]]:text-[1em]! [&_[data-slot=markdown-strong]]:font-medium [&_[data-slot=markdown-strong]]:text-foreground/80"
        >
          {children}
        </Markdown>
      ) : (
        children
      )}
    </ReasoningContentPrimitive>
  )
}

export { Reasoning, ReasoningContent, ReasoningContext, ReasoningLabel, ReasoningTrigger }
export type { ReasoningProps } from "@/components/keyframery/primitives/reasoning"
```

**components/keyframery/primitives/reasoning.tsx**

```tsx
"use client"

/* Animated reasoning, on UI SDK's core. UI SDK ships none, so its timing is defined in
   `@/components/core/reasoning` with `definePrimitive` and rendered here; opening and closing is UI
   SDK's collapsible (through Keyframery's animated collapsible primitive), and the thinking itself is
   Keyframery's streaming markdown. This file adds motion only. Colours, type and spacing stay yours
   (style `data-streaming` and the `data-slot` of each part).

   - Shimmer: while it thinks, a light passes through "Thinking…"; it stops for reduced motion.
   - Height and Cascade: the thinking opens to its real height on its own when streaming starts and
     closes when it ends (unless the reader toggled it); the chevron turns on a spring.
   - Follow: while it streams, the thinking keeps its newest line in view.
   The shimmer says "working" and always runs; the cascade and the press depth scale with
   --kf-flourish, and the height always animates. */

import { createParts } from "@ui-sdk/react/primitive"
import * as React from "react"

import {
  Collapsible as CollapsibleRoot,
  CollapsiblePanel as CollapsiblePanelPart,
  CollapsibleTrigger as CollapsibleTriggerPart,
} from "@/components/keyframery/primitives/collapsible"
import { Markdown } from "@/components/keyframery/primitives/markdown"
import { reasoning } from "@/components/keyframery/core/reasoning-core"
import { cn } from "@/lib/utils"

const parts = createParts(reasoning, { root: "div", label: "span" })

type ClassName<S> = string | ((state: S) => string | undefined) | undefined
function withClass<S>(base: string, className: ClassName<S>) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

const keyframes = "@keyframes kf-reasoning-shimmer{from{background-position:100% 0}to{background-position:0% 0}}"

const ReasoningContext = React.createContext<{ streaming: boolean }>({ streaming: false })

type CollapsibleProps = React.ComponentProps<typeof CollapsibleRoot>
type OpenChangeDetails = Parameters<NonNullable<CollapsibleProps["onOpenChange"]>>[1]

type ReasoningProps = Omit<React.ComponentProps<typeof parts.Root>, "children"> & {
  /** True while the model is still thinking: the trigger shimmers and the thinking shows. */
  streaming?: boolean
  /** How long it thought, in seconds. Without it, the time between `streaming` turning on and off. */
  duration?: number
  /** Close on its own when the thinking ends, unless the reader toggled it. Default true. */
  autoClose?: boolean
  /** Open at first, when not streaming. */
  defaultOpen?: boolean
  /** Controlled open state. Streaming starting and ending still asks for a change through `onOpenChange`. */
  open?: boolean
  /** Called with the new open state, from the reader or from streaming starting and ending (no details then). */
  onOpenChange?: (open: boolean, details?: OpenChangeDetails) => void
  children?: React.ReactNode
}

/* Opens on its own while streaming, closes when it ends; a reader's toggle wins until the next stream. */
function Reasoning({
  streaming = false,
  duration,
  autoClose = true,
  defaultOpen = false,
  open: controlled,
  onOpenChange,
  className,
  children,
  ...props
}: ReasoningProps) {
  const [auto, setAuto] = React.useState(streaming || defaultOpen)
  const [chosen, setChosen] = React.useState<boolean | undefined>(undefined)
  const [was, setWas] = React.useState(streaming)
  if (was !== streaming) {
    setWas(streaming)
    if (streaming) {
      setChosen(undefined)
      setAuto(true)
    } else if (autoClose && chosen === undefined) setAuto(false)
  }

  /* A controlled owner hears about the automatic changes too. */
  const report = React.useRef(onOpenChange)
  report.current = onOpenChange
  const first = React.useRef(true)
  React.useEffect(() => {
    if (first.current) {
      first.current = false
      return
    }
    report.current?.(auto)
  }, [auto])

  const open = controlled ?? chosen ?? auto
  const context = React.useMemo(() => ({ streaming }), [streaming])

  return (
    <ReasoningContext value={context}>
      <style href="kf-reasoning" precedence="default">
        {keyframes}
      </style>
      <parts.Root streaming={streaming} duration={duration} className={className} {...props}>
        <CollapsibleRoot
          open={open}
          onOpenChange={(next, details) => {
            setChosen(next)
            onOpenChange?.(next, details)
          }}
        >
          {children}
        </CollapsibleRoot>
      </parts.Root>
    </ReasoningContext>
  )
}

/* "Thinking…" with a light passing through it while it streams, "Thought for 12s" after. */
function ReasoningLabel({
  thinkingLabel = "Thinking…",
  doneLabel = (seconds) => (seconds === undefined ? "Thought for a few seconds" : `Thought for ${seconds}s`),
  className,
  ...props
}: Omit<React.ComponentProps<typeof parts.Label>, "children"> & {
  thinkingLabel?: React.ReactNode
  doneLabel?: (seconds: number | undefined) => React.ReactNode
}) {
  return (
    <parts.Label
      className={withClass(
        cn(
          "data-streaming:bg-[linear-gradient(90deg,currentColor_0%,currentColor_38%,color-mix(in_oklch,currentColor_25%,transparent)_50%,currentColor_62%,currentColor_100%)]",
          "data-streaming:bg-[length:250%_100%] data-streaming:bg-clip-text data-streaming:[-webkit-text-fill-color:transparent]",
          "data-streaming:animate-[kf-reasoning-shimmer_calc(1800ms*var(--kf-speed,1))_var(--ease-house)_infinite]",
          "motion-reduce:animate-none! motion-reduce:bg-none! motion-reduce:[-webkit-text-fill-color:currentColor]!",
        ),
        className,
      )}
      {...props}
    >
      {(state) => (state.streaming ? thinkingLabel : doneLabel(state.seconds))}
    </parts.Label>
  )
}

/* The button. With no children it shows the label, then a chevron that turns down as it opens. */
function ReasoningTrigger({
  className,
  children,
  thinkingLabel,
  doneLabel,
  ...props
}: React.ComponentProps<typeof CollapsibleTriggerPart> & Pick<React.ComponentProps<typeof ReasoningLabel>, "thinkingLabel" | "doneLabel">) {
  return (
    <CollapsibleTriggerPart
      className={withClass(
        "group/reasoning-trigger transition-[scale] duration-[calc(220ms*var(--kf-speed,1))] ease-pop active:scale-[calc(1-0.02*var(--kf-flourish,1))] motion-reduce:transition-none!",
        className,
      )}
      {...props}
    >
      {(state) => (
        <>
          {children === undefined ? (
            <ReasoningLabel thinkingLabel={thinkingLabel} doneLabel={doneLabel} />
          ) : typeof children === "function" ? (
            children(state)
          ) : (
            children
          )}
          <span
            data-slot="reasoning-chevron"
            aria-hidden
            className="inline-grid shrink-0 place-items-center transition-[rotate] duration-[calc(460ms*var(--kf-speed,1))] ease-spring group-data-open/reasoning-trigger:rotate-90 rtl:-scale-x-100 motion-reduce:transition-none!"
          >
            <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="size-3.5">
              <path d="m6 4 4 4-4 4" />
            </svg>
          </span>
        </>
      )}
    </CollapsibleTriggerPart>
  )
}

/* The thinking: opens to its real height and its content rises in (from the collapsible primitive).
   A string is rendered as streaming markdown; while it streams, the newest line stays in view. */
function ReasoningContent({
  className,
  children,
  ...props
}: Omit<React.ComponentProps<typeof CollapsiblePanelPart>, "children"> & { children?: React.ReactNode }) {
  const { streaming } = React.useContext(ReasoningContext)
  const scroller = React.useRef<HTMLDivElement>(null)
  React.useLayoutEffect(() => {
    const el = scroller.current
    if (el && streaming) el.scrollTop = el.scrollHeight
  })
  return (
    <CollapsiblePanelPart className={className} {...props}>
      <div ref={scroller} data-slot="reasoning-scroll">
        {typeof children === "string" ? <Markdown streaming={streaming} caret={false}>{children}</Markdown> : children}
      </div>
    </CollapsiblePanelPart>
  )
}

export { Reasoning, ReasoningContent, ReasoningContext, ReasoningLabel, ReasoningTrigger }
export type { ReasoningProps }
```

**components/keyframery/core/reasoning-core.ts**

```ts
/* Reasoning: the "thinking" a model did before it answered, behind a disclosure, as a UI SDK
   primitive. UI SDK ships none, so it is defined with its core: the same definition renders in React,
   Vue, Svelte, Solid and web components.

   It keeps time: while `streaming` is true it notes when the thinking started, and when it stops
   it keeps the seconds it took (unless a `duration` is given) and tells screen readers "Thought for
   12 seconds" once. Opening and closing is UI SDK's collapsible, composed in the renderer: this
   primitive adds no open state of its own. The renderer opens it while streaming and closes it when
   the thinking ends (`autoClose`), unless the reader toggled it in the meantime. */

import { announce, definePrimitive } from "@ui-sdk/core"

import { bindAgentContent } from "@/components/keyframery/core/agent-content-core"

type ReasoningOptions = {
  /** True while the model is still thinking. */
  streaming?: boolean
  /** How long it thought, in seconds. Without it, the time is measured from `streaming`. */
  duration?: number
}

type ReasoningState = {
  streaming: boolean
  duration: number | undefined
  /** Seconds measured between `streaming` turning on and off. */
  measured: number | undefined
  content: string
}

const now = () => (typeof performance === "undefined" ? Date.now() : performance.now())

/** The seconds to show: the given duration, else the measured one, at least 1. */
const secondsOf = (state: Pick<ReasoningState, "duration" | "measured">) => {
  const seconds = state.duration ?? state.measured
  return seconds === undefined ? undefined : Math.max(1, Math.round(seconds))
}

const reasoning = definePrimitive({
  name: "reasoning",
  options: { streaming: "boolean", duration: "number" },
  state: (options: ReasoningOptions): ReasoningState => ({
    streaming: options.streaming ?? false,
    duration: options.duration,
    measured: undefined,
    content: "",
  }),
  sync: (options) => ({ streaming: options.streaming ?? false, duration: options.duration }),
  controlled: ["content"],
  api: (context) => {
    let started = context.options().streaming ? now() : undefined
    let streaming = Boolean(context.options().streaming)
    context.onOptions((options) => {
      const next = Boolean(options.streaming)
      if (next === streaming) return
      streaming = next
      if (next) {
        started = now()
        context.store.set({ measured: undefined })
        return
      }
      const measured = started === undefined ? undefined : (now() - started) / 1000
      started = undefined
      context.store.set({ measured })
      const seconds = secondsOf({ duration: options.duration, measured })
      announce(seconds === undefined ? "Finished thinking" : `Thought for ${seconds} second${seconds === 1 ? "" : "s"}`)
    })
    return {
      /** The seconds to show once it has finished, or undefined when they are unknown. */
      seconds: (state: ReasoningState) => secondsOf(state),
    }
  },
  slots: (slot) => ({
    root: slot<{}, { streaming: boolean; seconds: number | undefined }>({
      state: (state, part) => ({ streaming: state.streaming, seconds: part.api.seconds(state) }),
      attrs: (state) => ({ "data-streaming": state.streaming ? "" : undefined }),
      /* An agent reads the label, and the thinking while it is open. */
      bind: (el, part) => bindAgentContent(el, (content) => part.store.set({ content })),
    }),
    /* The trigger's words: "Thinking…" or "Thought for 12s". */
    label: slot<{}, { streaming: boolean; seconds: number | undefined }>({
      state: (state, part) => ({ streaming: state.streaming, seconds: part.api.seconds(state) }),
      attrs: (state) => ({ "data-streaming": state.streaming ? "" : undefined }),
    }),
  }),
  agent: { actions: [] },
})

export { reasoning, type ReasoningOptions, type ReasoningState }
```

**Check the import paths**

The files import from `@/components/keyframery/…` and `@/lib/…`. Change those if your project's aliases differ.

**Vue**

```bash
npx shadcn-vue@latest add https://keyframery.com/r/vue/reasoning.json
```

This adds `components/keyframery/reasoning/` (one file per part, with the same part names as React) to your Vue or Nuxt project, installs UI SDK for Vue and adds the motion tokens to your global CSS. See [Install for Vue](/docs/installation/vue).

## Usage [#usage]

**React**

```tsx
import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/components/keyframery/reasoning"

export default function Usage() {
  return (
    <Reasoning duration={4}>
      <ReasoningTrigger />
      <ReasoningContent>{"The 07:05 lands at 10:20, early enough to drop bags before lunch."}</ReasoningContent>
    </Reasoning>
  )
}
```

**Vue**

```vue
<script setup lang="ts">
import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/components/keyframery/reasoning"
</script>

<template>
  <Reasoning :duration="4">
    <ReasoningTrigger />
    <ReasoningContent>The 07:05 lands at 10:20, early enough to drop bags before lunch.</ReasoningContent>
  </Reasoning>
</template>
```

### Anatomy [#anatomy]

How the parts fit together:

```text
Reasoning
├── ReasoningTrigger
└── ReasoningContent
```

## Examples [#examples]

### While it thinks [#while-it-thinks]

Set `streaming` while the model thinks: the trigger reads "Thinking…" with a light passing through it, and the thinking opens on its own. When `streaming` ends it closes and reads "Thought for 6s", timed for you unless you pass `duration`. A reader who toggles it keeps their choice.

<ExamplePreview name="reasoning/streaming">
**React**

  ```tsx
  import * as React from "react"

  import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/components/keyframery/reasoning"

  const thinking = `The parcel left **Leeds on Tuesday** and has had no scan since.

  - Royal Mail treats 10 working days as lost
  - it has been 7, so a resend is quicker than a claim`

  const words = thinking.match(/\s*\S+/g) ?? []

  export default function ReasoningStreaming() {
    const [at, setAt] = React.useState(0)
    React.useEffect(() => {
      const timer = setInterval(() => setAt((n) => (n >= words.length + 40 ? 0 : n + 1)), 90)
      return () => clearInterval(timer)
    }, [])
    return (
      <Reasoning className="max-w-[380px]" streaming={at < words.length}>
        <ReasoningTrigger />
        <ReasoningContent>{words.slice(0, at).join("")}</ReasoningContent>
      </Reasoning>
    )
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { onBeforeUnmount, ref } from "vue"

  import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/components/keyframery/reasoning"

  const thinking = `The parcel left **Leeds on Tuesday** and has had no scan since.

  - Royal Mail treats 10 working days as lost
  - it has been 7, so a resend is quicker than a claim`

  const words = thinking.match(/\s*\S+/g) ?? []

  const at = ref(0)
  const timer = setInterval(() => (at.value = at.value >= words.length + 40 ? 0 : at.value + 1), 90)
  onBeforeUnmount(() => clearInterval(timer))
  </script>

  <template>
    <Reasoning class="max-w-[380px]" :streaming="at < words.length">
      <ReasoningTrigger />
      <ReasoningContent>{{ words.slice(0, at).join("") }}</ReasoningContent>
    </Reasoning>
  </template>
  ```
</ExamplePreview>

### Your own labels [#your-own-labels]

`thinkingLabel` and `doneLabel` on the trigger change its words; `doneLabel` gets the seconds. Set `autoClose={false}` to leave the thinking open once it ends.

<ExamplePreview name="reasoning/labels">
**React**

  ```tsx
  import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/components/keyframery/reasoning"

  export default function ReasoningLabels() {
    return (
      <Reasoning className="max-w-[380px]" duration={14} defaultOpen autoClose={false}>
        <ReasoningTrigger thinkingLabel="Checking the menu…" doneLabel={(seconds) => `Checked the menu in ${seconds} seconds`} />
        <ReasoningContent>{"Two of the six mains are vegetarian, and the risotto can be made without butter. That covers *both* of your guests."}</ReasoningContent>
      </Reasoning>
    )
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/components/keyframery/reasoning"
  </script>

  <template>
    <Reasoning class="max-w-[380px]" :duration="14" default-open :auto-close="false">
      <ReasoningTrigger
        thinking-label="Checking the menu…"
        :done-label="(seconds) => `Checked the menu in ${seconds} seconds`"
      />
      <ReasoningContent>Two of the six mains are vegetarian, and the risotto can be made without butter. That covers *both* of your guests.</ReasoningContent>
    </Reasoning>
  </template>
  ```
</ExamplePreview>

### Controlled [#controlled]

Pass `open` and `onOpenChange` to own the state. Streaming starting and ending still asks for a change through `onOpenChange`, so the automatic open and close keep working.

<ExamplePreview name="reasoning/controlled">
**React**

  ```tsx
  import * as React from "react"

  import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/components/keyframery/reasoning"

  export default function ReasoningControlled() {
    const [open, setOpen] = React.useState(false)
    return (
      <div className="flex max-w-[380px] flex-col gap-3">
        <Reasoning duration={9} open={open} onOpenChange={setOpen}>
          <ReasoningTrigger />
          <ReasoningContent>{"Friday is the only day with seats on both legs, and it is €40 cheaper than Thursday."}</ReasoningContent>
        </Reasoning>
        <p className="text-[12px] text-muted-foreground">The thinking is {open ? "showing" : "hidden"}.</p>
      </div>
    )
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { ref } from "vue"

  import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/components/keyframery/reasoning"

  const open = ref(false)
  </script>

  <template>
    <div class="flex max-w-[380px] flex-col gap-3">
      <Reasoning v-model:open="open" :duration="9">
        <ReasoningTrigger />
        <ReasoningContent>Friday is the only day with seats on both legs, and it is €40 cheaper than Thursday.</ReasoningContent>
      </Reasoning>
      <p class="text-[12px] text-muted-foreground">The thinking is {{ open ? 'showing' : 'hidden' }}.</p>
    </div>
  </template>
  ```
</ExamplePreview>

## Motion [#motion]

| Move        | What you see                                                                                                                  |
| ----------- | ----------------------------------------------------------------------------------------------------------------------------- |
| **Fade**    | While it thinks, a soft light passes through "Thinking…"; it stops for reduced motion.                                        |
| **Height**  | The thinking opens to its real height on its own when streaming starts, and closes when it ends unless the reader toggled it. |
| **Cascade** | The thinking rises in as it opens.                                                                                            |
| **Rise**    | Each new paragraph or list of the thinking rises in as it streams, and the newest line stays in view.                         |
| **Spring**  | The chevron turns down on a spring.                                                                                           |

Timing and springiness follow the [motion style](/docs/motion-styles) you set. To change how fast this reasoning moves, pass `speed`:

```tsx
<Reasoning speed="fast">
  …
</Reasoning>
```

`"fast"` is 0.6×, `"slow"` 1.4×, and a number sets the multiplier. With reduced motion turned on, nothing moves: changes happen at once or with a short fade.

## Theming [#theming]

Set these CSS variables on the component or a parent. Leave them unset to follow the light and dark theme. The open Customize panel below the preview lets you try these settings.

| Variable                 | What it changes                             | Default               |
| ------------------------ | ------------------------------------------- | --------------------- |
| `--reasoning-ink`        | Trigger text                                | text-muted-foreground |
| `--reasoning-text`       | Thinking text                               | text-muted-foreground |
| `--reasoning-font`       | Thinking size                               | text-\[13px]          |
| `--reasoning-rule`       | Rule beside the thinking                    | border-border         |
| `--reasoning-indent`     | Thinking indent                             | ps-3.5                |
| `--reasoning-max-height` | Tallest the thinking gets before it scrolls | max-h-72              |

## API reference [#api-reference]

Every part takes `className` and `children`, along with the props of the element it renders. The parts are rendered by UI SDK, so they also take `render`, to draw your own element, and a function of their state for `className` and `style`.

### Reasoning [#reasoning]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;speed&#x22;,&#x22;type&#x22;:&#x22;\&#x22;fast\&#x22; | \&#x22;normal\&#x22; | \&#x22;slow\&#x22; | number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;How fast the component moves. `\&#x22;fast\&#x22;` (0.6×), `\&#x22;normal\&#x22;` (1×), `\&#x22;slow\&#x22;` (1.4×), or a multiplier like `0.8`. Popups follow it too.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;streaming&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;True while the model is still thinking: the trigger shimmers and the thinking shows.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;duration&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;How long it thought, in seconds. Without it, the time between `streaming` turning on and off is measured.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;autoClose&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Close on its own when the thinking ends, unless the reader toggled it. Default true.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultOpen&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Open at first, when not streaming.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;open&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Controlled open state. Streaming starting and ending still asks for a change through `onOpenChange`.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onOpenChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(open: boolean, details?: ChangeDetails<CollapsibleOpenChangeReason>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Called with the new open state, from the reader or from streaming starting and ending (no details then).&#x22;,&#x22;required&#x22;:false}]" />

### ReasoningTrigger [#reasoningtrigger]

Renders a `<button>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;thinkingLabel&#x22;,&#x22;type&#x22;:&#x22;ReactNode&#x22;,&#x22;full&#x22;:&#x22;ReactNode&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The words while it thinks. Default \&#x22;Thinking…\&#x22;.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;doneLabel&#x22;,&#x22;type&#x22;:&#x22;(seconds: number) => React.ReactNode&#x22;,&#x22;full&#x22;:&#x22;(seconds: number) => React.ReactNode&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;A function of the seconds that returns the words once it has finished. Default \&#x22;Thought for 12s\&#x22;.&#x22;,&#x22;required&#x22;:false}]" />

### ReasoningContent [#reasoningcontent]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;keepMounted&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:&#x22;false&#x22;,&#x22;description&#x22;:&#x22;Whether the panel stays in the page, hidden, while closed.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;hiddenUntilFound&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:&#x22;false&#x22;,&#x22;description&#x22;:&#x22;Keeps the closed panel in the page as `hidden=\&#x22;until-found\&#x22;`, so the browser's find in page can match its text and open it.&#x22;,&#x22;required&#x22;:false}]" />

### ReasoningLabel [#reasoninglabel]

Renders a `<span>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;thinkingLabel&#x22;,&#x22;type&#x22;:&#x22;ReactNode&#x22;,&#x22;full&#x22;:&#x22;ReactNode&#x22;,&#x22;default&#x22;:&#x22;\&#x22;Thinking…\&#x22;&#x22;,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;doneLabel&#x22;,&#x22;type&#x22;:&#x22;(seconds: number) => React.ReactNode&#x22;,&#x22;full&#x22;:&#x22;(seconds: number) => React.ReactNode&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false}]" />

### Other parts [#other-parts]

These take the props of the element they render, and nothing else:

* `ReasoningContext`

## Keyboard [#keyboard]

| Key                       | What it does                 |
| ------------------------- | ---------------------------- |
| <kbd>Tab</kbd>            | Moves focus to the trigger.  |
| <kbd>Enter or Space</kbd> | Shows or hides the thinking. |

## Accessibility [#accessibility]

Roles, keyboard and focus are declared on the component's UI SDK primitive, and state is announced through the matching ARIA attributes. More in [Accessibility](/docs/accessibility).

## Built on UI SDK's core [#built-on-ui-sdks-core]

UI SDK doesn't ship a reasoning, so this one is defined with its core: one `definePrimitive` in `components/keyframery/core/reasoning-core.ts`, with no React in it. UI SDK's adapters can render that same definition in Vue, Svelte, Solid and web components. To keep your own styling and take only the motion, import from `@/components/keyframery/primitives/reasoning`.

## Questions

### How does the animated Reasoning for UI SDK move?

Fade: While it thinks, a soft light passes through "Thinking…"; it stops for reduced motion. Height: The thinking opens to its real height on its own when streaming starts, and closes when it ends unless the reader toggled it. Cascade: The thinking rises in as it opens. Rise: Each new paragraph or list of the thinking rises in as it streams, and the newest line stays in view. Spring: The chevron turns down on a spring.

### Do I need Motion or Framer Motion for the animated Reasoning?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### UI SDK has no reasoning. How is this one built on UI SDK?

Its behaviour is one definition written with UI SDK's core (`definePrimitive`), in `components/keyframery/core/reasoning-core.ts`. Its parts are rendered by UI SDK's adapter, so they take `render`, state-based class names and `data-slot`, like every UI SDK component.

### What happens to the Reasoning when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
