# Animated Trace for UI SDK (/docs/components/trace)

Steps rise in one after another, a running title has a light passing through it, a finished step's tick pops in and draws itself, and a row opens to its real height with its detail cascading in.

<ComponentPreview slug="trace" source="{&#x22;code&#x22;:&#x22;\&#x22;use client\&#x22;\n\nimport * as React from \&#x22;react\&#x22;\n\nimport {\n  Trace,\n  TraceCollapsible,\n  TraceCollapsibleContent,\n  TraceCollapsibleTrigger,\n  TraceDescription,\n  TraceIcon,\n  TraceLine,\n  TraceTitle,\n  type TraceStatus,\n} from \&#x22;@/components/keyframery/trace\&#x22;\n\ntype Step = {\n  id: string\n  /** The title while it runs, and once it is done. */\n  running: string\n  done: string\n  failed?: boolean\n  took: string\n  icon: React.ReactNode\n  detail?: React.ReactNode\n}\n\nconst svg = (d: React.ReactNode) => (\n  <svg viewBox=\&#x22;0 0 16 16\&#x22; fill=\&#x22;none\&#x22; stroke=\&#x22;currentColor\&#x22; strokeWidth=\&#x22;1.5\&#x22; strokeLinecap=\&#x22;round\&#x22; strokeLinejoin=\&#x22;round\&#x22;>\n    {d}\n  </svg>\n)\n\nconst steps: Step[] = [\n  {\n    id: \&#x22;places\&#x22;,\n    running: \&#x22;Reading your saved places in Lisbon\&#x22;,\n    done: \&#x22;Read 14 saved places in Lisbon\&#x22;,\n    took: \&#x22;1.2s\&#x22;,\n    icon: svg(<path d=\&#x22;M8 14s4.5-3.9 4.5-7.5a4.5 4.5 0 0 0-9 0C3.5 10.1 8 14 8 14Z M8 8.25a1.75 1.75 0 1 0 0-3.5 1.75 1.75 0 0 0 0 3.5Z\&#x22; />),\n    detail: (\n      <>\n        <p>Time Out Market, LX Factory and Miradouro da Senhora do Monte are close together, so they go on Saturday.</p>\n        <p>Pastéis de Belém is the only one west of the river bend: Sunday morning.</p>\n      </>\n    ),\n  },\n  {\n    id: \&#x22;flights\&#x22;,\n    running: \&#x22;Checking flights from Manchester\&#x22;,\n    done: \&#x22;Found the 07:05 on Friday, back Monday 19:40\&#x22;,\n    took: \&#x22;2.4s\&#x22;,\n    icon: svg(<path d=\&#x22;M2.5 9.5 6 8.75 9.25 13l1.5-.5L9.5 8l3.25-.75a1.25 1.25 0 0 0-.5-2.45L9 5.5 5.5 2 4 2.5l2 3.75-3.25.75Z\&#x22; />),\n  },\n  {\n    id: \&#x22;ramiro\&#x22;,\n    running: \&#x22;Booking Cervejaria Ramiro for Saturday\&#x22;,\n    done: \&#x22;Couldn't book Cervejaria Ramiro for Saturday\&#x22;,\n    failed: true,\n    took: \&#x22;3.1s\&#x22;,\n    icon: svg(<path d=\&#x22;M4 2.5v4.25a2 2 0 0 0 4 0V2.5M6 2.5v11M11.5 13.5V2.5c-1.5 0-2.5 1.75-2.5 4.5s1 3 2.5 3\&#x22; />),\n    detail: (\n      <>\n        <p>Fully booked from 19:00 to 22:30. They hold the bar for walk-ins; the queue is usually about 40 minutes.</p>\n        <p>Put on the waitlist for 19:30 instead.</p>\n      </>\n    ),\n  },\n  {\n    id: \&#x22;hotels\&#x22;,\n    running: \&#x22;Comparing 6 hotels in Alfama\&#x22;,\n    done: \&#x22;Picked Memmo Alfama, €212 a night\&#x22;,\n    took: \&#x22;4.0s\&#x22;,\n    icon: svg(<path d=\&#x22;M2.5 13.5v-9h7v9M9.5 7.5h4v6M1.5 13.5h13M5 7h2M5 9.5h2\&#x22; />),\n  },\n  {\n    id: \&#x22;plan\&#x22;,\n    running: \&#x22;Writing the day-by-day plan\&#x22;,\n    done: \&#x22;Wrote a plan for 4 days\&#x22;,\n    took: \&#x22;2.2s\&#x22;,\n    icon: svg(<path d=\&#x22;M4 2.5h8M4 6h8M4 9.5h5M4 13h3\&#x22; />),\n  },\n]\n\n/* Where the trace stands when the demo first shows: three done, one running, one waiting. */\nconst START = 3\n\nexport default function TraceDemo({\n  icons = \&#x22;status\&#x22;,\n  durations = true,\n  openFailed = false,\n  themeInk = \&#x22;\&#x22;,\n  themeError = \&#x22;\&#x22;,\n  themeFont = 13,\n  themeDetailFont = 12.5,\n  themeGap = 10,\n  themeIconSize = 16,\n  themeIndent = 16,\n}: {\n  icons?: \&#x22;status\&#x22; | \&#x22;action\&#x22;\n  durations?: boolean\n  openFailed?: boolean\n  themeInk?: string\n  themeError?: string\n  themeFont?: number\n  themeDetailFont?: number\n  themeGap?: number\n  themeIconSize?: number\n  themeIndent?: number\n}) {\n  const [run, setRun] = React.useState(0)\n  const [at, setAt] = React.useState(START)\n  const timers = React.useRef<ReturnType<typeof setTimeout>[]>([])\n  React.useEffect(() => () => timers.current.forEach(clearTimeout), [])\n\n  /* Plan again: the list comes back in, then each step runs for a moment and finishes. */\n  const replan = (e: React.MouseEvent<HTMLButtonElement>) => {\n    const speed = parseFloat(getComputedStyle(e.currentTarget).getPropertyValue(\&#x22;--kf-speed\&#x22;)) || 1\n    timers.current.forEach(clearTimeout)\n    setRun((r) => r + 1)\n    setAt(0)\n    timers.current = steps.map((_, i) => setTimeout(() => setAt(i + 1), (700 + i * 900) * speed))\n  }\n\n  const statusOf = (i: number): TraceStatus | undefined =>\n    i < at ? (steps[i].failed ? \&#x22;error\&#x22; : undefined) : i === at ? \&#x22;running\&#x22; : \&#x22;pending\&#x22;\n\n  /* Leave defaults unset so each part keeps its own theme and size fallback. */\n  const theme = {\n    ...(themeInk ? { \&#x22;--trace-ink\&#x22;: themeInk } : null),\n    ...(themeError ? { \&#x22;--trace-error\&#x22;: themeError } : null),\n    ...(themeFont !== 13 ? { \&#x22;--trace-font\&#x22;: `${themeFont}px` } : null),\n    ...(themeDetailFont !== 12.5 ? { \&#x22;--trace-detail-font\&#x22;: `${themeDetailFont}px` } : null),\n    ...(themeGap !== 10 ? { \&#x22;--trace-gap\&#x22;: `${themeGap}px` } : null),\n    ...(themeIconSize !== 16 ? { \&#x22;--trace-icon-size\&#x22;: `${themeIconSize}px` } : null),\n    ...(themeIndent !== 16 ? { \&#x22;--trace-indent\&#x22;: `${themeIndent}px` } : null),\n  } as React.CSSProperties\n\n  return (\n    <div style={theme} className=\&#x22;@container w-full max-w-[460px]\&#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          Plan a long weekend in Lisbon, 14 to 17 March. Two of us, flying from Manchester.\n        </div>\n      </div>\n\n      <div className=\&#x22;mt-5 flex items-center justify-between gap-3\&#x22;>\n        <div className=\&#x22;text-[12px] font-medium text-muted-foreground\&#x22;>{at >= steps.length ? \&#x22;Done\&#x22; : \&#x22;Working on it\&#x22;}</div>\n        <button\n          type=\&#x22;button\&#x22;\n          data-action=\&#x22;replan\&#x22;\n          onClick={replan}\n          className=\&#x22;inline-flex h-7 items-center rounded-[8px] px-2.5 text-[12px] leading-none font-medium text-muted-foreground outline-none transition-[scale,color,background-color] duration-[calc(200ms*var(--kf-speed,1))] ease-pop hover:bg-foreground/[0.045] hover:text-foreground active:scale-[0.96] focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none\&#x22;\n        >\n          Plan again\n        </button>\n      </div>\n\n      <Trace key={run} className=\&#x22;mt-3\&#x22; aria-label=\&#x22;What the assistant did\&#x22;>\n        {steps.map((step, i) => {\n          const status = statusOf(i)\n          const line = (\n            <TraceLine status={status}>\n              <TraceIcon>{icons === \&#x22;action\&#x22; && status !== \&#x22;running\&#x22; ? step.icon : undefined}</TraceIcon>\n              <TraceTitle>{i < at ? step.done : step.running}</TraceTitle>\n              {durations && i < at && <TraceDescription className=\&#x22;@max-[26rem]:hidden\&#x22;>{step.took}</TraceDescription>}\n            </TraceLine>\n          )\n          /* A row with detail is a collapsible from the start, and can't open until its step is done. */\n          return step.detail ? (\n            <TraceCollapsible key={`${step.id}-${openFailed}`} data-step={step.id} disabled={i >= at} defaultOpen={step.failed ? openFailed : false}>\n              <TraceCollapsibleTrigger>{line}</TraceCollapsibleTrigger>\n              <TraceCollapsibleContent>{step.detail}</TraceCollapsibleContent>\n            </TraceCollapsible>\n          ) : (\n            <div key={step.id} data-step={step.id} className=\&#x22;w-fit max-w-full\&#x22;>\n              {line}\n            </div>\n          )\n        })}\n      </Trace>\n    </div>\n  )\n}&#x22;,&#x22;bindings&#x22;:{&#x22;icons&#x22;:[2556,2564],&#x22;durations&#x22;:[2580,2584],&#x22;openFailed&#x22;:[2601,2606],&#x22;themeInk&#x22;:[2621,2623],&#x22;themeError&#x22;:[2640,2642],&#x22;themeFont&#x22;:[2658,2660],&#x22;themeDetailFont&#x22;:[2682,2686],&#x22;themeGap&#x22;:[2701,2703],&#x22;themeIconSize&#x22;:[2723,2725],&#x22;themeIndent&#x22;:[2743,2745]},&#x22;root&#x22;:[4456,6755],&#x22;importOffset&#x22;:256}" />

## Installation [#installation]

**CLI**

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

This adds `components/keyframery/trace.tsx` and its primitive to your project, and installs UI SDK, along with [agent-content](/docs/components/agent-content), [collapsible](/docs/components/collapsible), 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.9 @ui-sdk/react@0.1.0-beta.9 clsx tailwind-merge
```

**Add the motion tokens**

Copy the [motion tokens](/docs/installation#what-the-cli-adds-to-your-css) 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 = "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: `"springy"` (the default), `"calm"`, `"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 [agent-content](/docs/components/agent-content), [collapsible](/docs/components/collapsible) the same way first.

**Copy the component**

**components/keyframery/trace.tsx**

```tsx
"use client"

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

/* Theming variables (set on a part or ancestor; absent values preserve the theme):
   --trace-ink: Step text; default: text-muted-foreground.
   --trace-error: Failed step; default: text-destructive.
   --trace-font: Step size; default: text-[13px].
   --trace-detail-font: Detail size; default: text-[12.5px].
   --trace-gap: Step spacing; default: gap-2.5.
   --trace-icon-size: Status icon size; default: size-4.
   --trace-indent: Detail indent; default: ps-4.
*/

/* Styled trace: the animated primitive plus the Keyframery look. Quiet muted lines that wake on
   hover; a running title shimmers, a failed one turns destructive, a pending one waits at half ink.
   Rows that expand are Keyframery's collapsible: their detail hangs off a hairline under the icon. */

import * as React from "react"

import {
  Trace as TraceRoot,
  TraceCollapsibleTrigger as TraceCollapsibleTriggerPrimitive,
  TraceDescription as TraceDescriptionPrimitive,
  TraceIcon as TraceIconPrimitive,
  TraceLine as TraceLinePrimitive,
  TraceTitle as TraceTitlePrimitive,
} from "@/components/keyframery/primitives/trace"
import { Collapsible, CollapsiblePanel } from "@/components/keyframery/collapsible"
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)
}

/* Also styles any link or button that wraps a line directly, as the trigger is styled. */
function Trace({ speed, className, ...props }: React.ComponentProps<typeof TraceRoot> & SpeedProps) {
  return (
    <Speed speed={speed}>
      <TraceRoot
        className={withClass(
          cn(
            "flex w-full min-w-0 flex-col gap-[var(--trace-gap,0.625rem)] text-[length:var(--trace-font,13px)]",
            "*:has-[>[data-slot=trace-line]]:w-fit *:has-[>[data-slot=trace-line]]:max-w-full *:has-[>[data-slot=trace-line]]:rounded-[6px] *:has-[>[data-slot=trace-line]]:outline-none",
            "*:has-[>[data-slot=trace-line]]:focus-visible:ring-2 *:has-[>[data-slot=trace-line]]:focus-visible:ring-ring *:has-[>[data-slot=trace-line]]:focus-visible:ring-offset-2 *:has-[>[data-slot=trace-line]]:focus-visible:ring-offset-background",
          ),
          className,
        )}
        {...props}
      />
    </Speed>
  )
}

function TraceLine({ className, ...props }: React.ComponentProps<typeof TraceLinePrimitive>) {
  return (
    <TraceLinePrimitive
      className={withClass(
        cn(
          "flex w-fit max-w-full min-w-0 items-center gap-2 leading-[1.35] text-[color:var(--trace-ink,var(--muted-foreground))]",
          "transition-[color,opacity] duration-[calc(150ms*var(--kf-speed,1))] ease-house motion-reduce:transition-none",
          "in-[a:hover,button:hover]:text-foreground in-[a,button]:cursor-pointer",
          "data-[status=running]:text-foreground",
          "data-[status=error]:text-[color:var(--trace-error,var(--destructive))] in-[a:hover,button:hover]:data-[status=error]:text-[color:var(--trace-error,var(--destructive))]",
          "data-[status=pending]:opacity-55",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* 16px. Before the title it names the action; with no children it shows the line's status. Done
   steps take the payoff green. */
function TraceIcon({ className, ...props }: React.ComponentProps<typeof TraceIconPrimitive>) {
  return (
    <TraceIconPrimitive
      className={withClass(
        cn(
          "grid size-[var(--trace-icon-size,1rem)] shrink-0 place-items-center [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-[var(--trace-icon-size,1rem)]",
          "[&_[data-mark=done]]:text-[oklch(0.62_0.16_150)]",
        ),
        className,
      )}
      {...props}
    />
  )
}

function TraceTitle({ className, ...props }: React.ComponentProps<typeof TraceTitlePrimitive>) {
  return <TraceTitlePrimitive className={withClass("min-w-0 truncate", className)} {...props} />
}

/* A count or a duration after the title. It never truncates. */
function TraceDescription({ className, ...props }: React.ComponentProps<typeof TraceDescriptionPrimitive>) {
  return (
    <TraceDescriptionPrimitive
      className={withClass("shrink-0 text-[12px] text-muted-foreground/70 tabular-nums", className)}
      {...props}
    />
  )
}

/* A row that expands. It takes the props of Collapsible. */
function TraceCollapsible({ className, ...props }: React.ComponentProps<typeof Collapsible>) {
  return <Collapsible data-trace="" className={withClass("w-full min-w-0", className)} {...props} />
}

function TraceCollapsibleTrigger({ className, ...props }: React.ComponentProps<typeof TraceCollapsibleTriggerPrimitive>) {
  return (
    <TraceCollapsibleTriggerPrimitive
      className={withClass(
        cn(
          "flex w-fit max-w-full min-w-0 cursor-pointer items-center gap-1.5 rounded-[6px] text-start text-[color:var(--trace-ink,var(--muted-foreground))] outline-none",
          "hover:text-foreground data-open:text-foreground",
          "has-[[data-status=error]]:text-[color:var(--trace-error,var(--destructive))]",
          "*:data-[slot=trace-chevron]:text-muted-foreground/70 data-disabled:cursor-default data-disabled:*:data-[slot=trace-chevron]:opacity-0",
          "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* The detail hangs off a hairline under the line's icon. Its children rise in one after another, so
   pass rows or blocks straight inside. */
function TraceCollapsibleContent({ className, ...props }: React.ComponentProps<typeof CollapsiblePanel>) {
  return (
    <CollapsiblePanel
      className={withClass(
        cn(
          "ms-[7.5px] min-w-0 border-s border-border ps-[var(--trace-indent,1rem)] text-[length:var(--trace-detail-font,12.5px)] leading-relaxed text-[color:var(--trace-ink,var(--muted-foreground))]",
          "flex flex-col gap-2 *:first:mt-2.5 *:last:mb-1",
        ),
        className,
      )}
      {...props}
    />
  )
}

export {
  Trace,
  TraceCollapsible,
  TraceCollapsibleContent,
  TraceCollapsibleTrigger,
  TraceDescription,
  TraceIcon,
  TraceLine,
  TraceTitle,
}
export type { TraceStatus } from "@/components/keyframery/primitives/trace"
```

**components/keyframery/primitives/trace.tsx**

```tsx
"use client"

/* Animated trace, on UI SDK's core. UI SDK ships no trace, so its lines are defined in
   `@/components/core/trace` with `definePrimitive` and rendered here; a line that expands is UI SDK's
   collapsible (through Keyframery's animated collapsible primitive). This file adds motion only.
   Colours, radii and spacing stay yours (style `data-status`).

   - Cascade: lines rise in one after another as they arrive.
   - Shimmer: a running line's title has a light passing through it; it stops for reduced motion.
   - Draw and Pop: with no icon given, the mark follows the status: a spinner while running, and a
     tick that pops in and draws itself when the step is done.
   - Height and Cascade: a row opens to its real height and its detail rises in; the chevron turns
     on a spring. */

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 { trace } from "@/components/keyframery/core/trace-core"
import { cn } from "@/lib/utils"

const parts = createParts(trace, { root: "div", line: "span", icon: "span", title: "span", description: "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-trace-row{from{opacity:0;translate:0 8px;filter:blur(4px)}}",
  "@keyframes kf-trace-shimmer{from{background-position:100% 0}to{background-position:0% 0}}",
  "@keyframes kf-trace-tick{from{stroke-dashoffset:1}}",
  "@keyframes kf-trace-pop{from{scale:0.4;opacity:0}}",
].join("")

/* Each direct child (a line, a link, a row that expands) rises in a beat after the one above it. */
function Trace({ className, ...props }: React.ComponentProps<typeof parts.Root>) {
  return (
    <>
      <style href="kf-trace" precedence="default">
        {keyframes}
      </style>
      <parts.Root
        className={withClass(
          cn(
            "*:animate-[kf-trace-row_calc(460ms*var(--kf-speed,1))_var(--ease-spring)_backwards]",
            "*:[animation-delay:calc((min(sibling-index(),10)-1)*calc(55ms*var(--kf-speed,1)))]",
            "motion-reduce:*:animate-none!",
          ),
          className,
        )}
        {...props}
      />
    </>
  )
}

function TraceLine({ className, ...props }: React.ComponentProps<typeof parts.Line>) {
  return <parts.Line className={withClass("group/trace-line", className)} {...props} />
}

/* The light runs across the text of a running title. Its colour is the text's own, so it works on
   any theme. */
function TraceTitle({ className, ...props }: React.ComponentProps<typeof parts.Title>) {
  return (
    <parts.Title
      className={withClass(
        cn(
          "group-data-[status=running]/trace-line:bg-[linear-gradient(90deg,currentColor_0%,currentColor_38%,color-mix(in_oklch,currentColor_25%,transparent)_50%,currentColor_62%,currentColor_100%)]",
          "group-data-[status=running]/trace-line:bg-[length:250%_100%] group-data-[status=running]/trace-line:bg-clip-text group-data-[status=running]/trace-line:[-webkit-text-fill-color:transparent]",
          "group-data-[status=running]/trace-line:animate-[kf-trace-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}
    />
  )
}

const TraceDescription = parts.Description

/* The mark for each status, when the icon is given no children. All four are there; the line's
   `data-status` shows one. A mark that starts showing replays its animation, so the tick pops in and
   draws itself the moment a step finishes. */
const pop = "animate-[kf-trace-pop_calc(380ms*var(--kf-speed,1))_var(--ease-pop)_backwards] motion-reduce:animate-none"

function StatusMarks() {
  return (
    <>
      <svg data-mark="running" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className="hidden animate-spin [animation-duration:calc(800ms*var(--kf-speed,1))] group-data-[status=running]/trace-line:block motion-reduce:[animation-duration:calc(2400ms*var(--kf-speed,1))]">
        <circle cx="8" cy="8" r="5.75" opacity="0.25" />
        <path d="M8 2.25A5.75 5.75 0 0 1 13.75 8" />
      </svg>
      <svg data-mark="pending" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeDasharray="2 2.2" className="hidden group-data-[status=pending]/trace-line:block">
        <circle cx="8" cy="8" r="5.25" />
      </svg>
      <svg data-mark="error" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className={cn("hidden group-data-[status=error]/trace-line:block", pop)}>
        <circle cx="8" cy="8" r="5.75" />
        <path d="M8 5v3.25M8 10.75v.01" />
      </svg>
      <svg data-mark="done" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className={cn("hidden group-data-done/trace-line:block", pop)}>
        <circle cx="8" cy="8" r="5.75" />
        <path
          d="M5.5 8.25 7.25 10l3.25-3.75"
          pathLength={1}
          className="[stroke-dasharray:1] animate-[kf-trace-tick_calc(320ms*var(--kf-speed,1))_var(--ease-house)_calc(120ms*var(--kf-speed,1))_backwards] motion-reduce:animate-none"
        />
      </svg>
    </>
  )
}

/* Decorative. With no children it shows its line's status; pass your own icon to name the action. */
function TraceIcon({ children, ...props }: React.ComponentProps<typeof parts.Icon>) {
  return <parts.Icon {...props}>{children ?? <StatusMarks />}</parts.Icon>
}

/* A row that expands: UI SDK's collapsible. */
const TraceCollapsible = CollapsibleRoot

/* The button around a line. It adds a chevron after the line that turns down on a spring as the row opens. */
function TraceCollapsibleTrigger({
  className,
  children,
  ...props
}: React.ComponentProps<typeof CollapsibleTriggerPart>) {
  return (
    <CollapsibleTriggerPart
      className={withClass("group/trace-trigger transition-[scale] duration-[calc(220ms*var(--kf-speed,1))] ease-pop active:scale-[0.98] motion-reduce:transition-none!", className)}
      {...props}
    >
      {(state) => (
        <>
          {typeof children === "function" ? children(state) : children}
          <span
            data-slot="trace-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/trace-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 detail: opens to its real height, and its children rise in one after another (from the
   collapsible primitive). */
const TraceCollapsibleContent = CollapsiblePanelPart

export {
  Trace,
  TraceCollapsible,
  TraceCollapsibleContent,
  TraceCollapsibleTrigger,
  TraceDescription,
  TraceIcon,
  TraceLine,
  TraceTitle,
}
export type { TraceStatus } from "@/components/keyframery/core/trace-core"
```

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

```ts
/* A trace: the steps an assistant or a job went through, one line each, 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.

   A line has a status (running, error, pending, or done when it has none) and a title. When a line
   stops running, screen readers hear its new title once, so "Searching flights" becoming "Found
   12 flights" is announced without a live region on the whole list. Lines that expand are UI SDK's
   collapsible, composed in the renderer: this primitive adds no open state of its own. */

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

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

/** A line's state. Leave it out for a step that finished. */
type TraceStatus = "running" | "error" | "pending"

const statusAttr = (status: string | undefined) => (status === "running" || status === "error" || status === "pending" ? status : undefined)

const trace = definePrimitive({
  name: "trace",
  options: {},
  state: () => ({ content: "" }),
  controlled: ["content"],
  api: () => ({}),
  slots: (slot) => ({
    root: slot({
      state: () => ({}),
      bind: (el, part) => bindAgentContent(el, (content) => part.store.set({ content })),
    }),
    line: slot<{ status?: TraceStatus }, { status: TraceStatus | undefined }>({
      props: { status: "string" },
      state: (_state, part) => ({ status: statusAttr(part.props.status) as TraceStatus | undefined }),
      attrs: (_state, part) => ({
        "data-status": statusAttr(part.props.status),
        "data-done": statusAttr(part.props.status) ? undefined : "",
      }),
      /* Reads the title out once when the step stops running or fails. */
      bind: (el) => {
        let was = el.getAttribute("data-status")
        const observer = new MutationObserver(() => {
          const now = el.getAttribute("data-status")
          if (now === was) return
          const ended = was === "running" && now !== "running"
          was = now
          if (!ended) return
          const title = el.querySelector("[data-slot=trace-title]")?.textContent?.trim()
          if (title) announce(title, { priority: now === "error" ? "assertive" : "polite" })
        })
        observer.observe(el, { attributes: true, attributeFilter: ["data-status"] })
        return () => observer.disconnect()
      },
    }),
    /* Decorative: the title is the line's name. */
    icon: slot({
      attrs: () => ({ "aria-hidden": "true" }),
    }),
    title: slot({}),
    description: slot({}),
  }),
  /* Expose the trace's titles and descriptions; expanding rows are separate collapsibles. */
  agent: { actions: [] },
})

export { trace, type TraceStatus }
```

**Check the import paths**

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

## Usage [#usage]

```tsx
import { Trace, TraceIcon, TraceLine, TraceTitle } from "@/components/keyframery/trace"

export default function Usage() {
  return (
    <Trace>
      <TraceLine>
        <TraceIcon />
        <TraceTitle>Read the order history</TraceTitle>
      </TraceLine>
      <TraceLine status="running">
        <TraceIcon />
        <TraceTitle>Drafting the refund email</TraceTitle>
      </TraceLine>
    </Trace>
  )
}
```

### Anatomy [#anatomy]

How the parts fit together:

```text
Trace
└── TraceLine
    ├── TraceIcon
    └── TraceTitle
```

## Examples [#examples]

### Status [#status]

`status` on a line is "running", "error" or "pending"; leave it out once the step is done. With no children, the icon follows it: a spinner, a mark, a dashed ring, or a tick that draws itself.

<ExamplePreview name="trace/status">
  ```tsx
  import { Trace, TraceDescription, TraceIcon, TraceLine, TraceTitle } from "@/components/keyframery/trace"

  export default function TraceStatus() {
    return (
      <Trace className="max-w-[380px]">
        <TraceLine>
          <TraceIcon />
          <TraceTitle>Checked stock at the Leeds warehouse</TraceTitle>
          <TraceDescription>0.8s</TraceDescription>
        </TraceLine>
        <TraceLine status="error">
          <TraceIcon />
          <TraceTitle>Couldn't reach the courier's tracking page</TraceTitle>
        </TraceLine>
        <TraceLine status="running">
          <TraceIcon />
          <TraceTitle>Writing to the customer</TraceTitle>
        </TraceLine>
        <TraceLine status="pending">
          <TraceIcon />
          <TraceTitle>Issue the refund</TraceTitle>
        </TraceLine>
      </Trace>
    )
  }
  ```
</ExamplePreview>

### A row that expands [#a-row-that-expands]

Wrap a line in `TraceCollapsibleTrigger` inside `TraceCollapsible`. The detail opens to its real height and its paragraphs rise in one after another.

<ExamplePreview name="trace/collapsible">
  ```tsx
  import {
    Trace,
    TraceCollapsible,
    TraceCollapsibleContent,
    TraceCollapsibleTrigger,
    TraceIcon,
    TraceLine,
    TraceTitle,
  } from "@/components/keyframery/trace"

  export default function TraceCollapsibleExample() {
    return (
      <Trace className="max-w-[380px]">
        <TraceCollapsible defaultOpen>
          <TraceCollapsibleTrigger>
            <TraceLine>
              <TraceIcon />
              <TraceTitle>Thought for 6 seconds</TraceTitle>
            </TraceLine>
          </TraceCollapsibleTrigger>
          <TraceCollapsibleContent>
            <p>The parcel left Leeds on Tuesday but has no scan since. Royal Mail treats 10 working days as lost.</p>
            <p>It has been 7, so offer a resend now rather than a refund.</p>
          </TraceCollapsibleContent>
        </TraceCollapsible>
      </Trace>
    )
  }
  ```
</ExamplePreview>

### Your own icons [#your-own-icons]

Put an icon inside `TraceIcon` to name the action instead of showing the status. The title stays the line's name for screen readers.

<ExamplePreview name="trace/icons">
  ```tsx
  import { Trace, TraceIcon, TraceLine, TraceTitle } from "@/components/keyframery/trace"

  export default function TraceIcons() {
    return (
      <Trace className="max-w-[380px]">
        <a href="#receipt">
          <TraceLine>
            <TraceIcon>
              <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M4 2.5h8v11l-2-1.25-2 1.25-2-1.25-2 1.25Z M6 6h4M6 8.5h4" />
              </svg>
            </TraceIcon>
            <TraceTitle>Opened receipt #40817</TraceTitle>
          </TraceLine>
        </a>
      </Trace>
    )
  }
  ```
</ExamplePreview>

## Motion [#motion]

| Move        | What you see                                                                      |
| ----------- | --------------------------------------------------------------------------------- |
| **Cascade** | Lines rise in one after another as they arrive.                                   |
| **Fade**    | A running title has a soft light passing through it; it stops for reduced motion. |
| **Draw**    | When a step finishes, its tick pops in and draws itself.                          |
| **Height**  | A row that expands opens to its real height.                                      |
| **Cascade** | The detail's paragraphs rise in one after another as it opens.                    |
| **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 trace moves, pass `speed`:

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

`"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               |
| --------------------- | ---------------- | --------------------- |
| `--trace-ink`         | Step text        | text-muted-foreground |
| `--trace-error`       | Failed step      | text-destructive      |
| `--trace-font`        | Step size        | text-\[13px]          |
| `--trace-detail-font` | Detail size      | text-\[12.5px]        |
| `--trace-gap`         | Step spacing     | gap-2.5               |
| `--trace-icon-size`   | Status icon size | size-4                |
| `--trace-indent`      | Detail indent    | ps-4                  |

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

### Trace [#trace]

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}]" />

### TraceLine [#traceline]

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

<PropsTable rows="[{&#x22;name&#x22;:&#x22;status&#x22;,&#x22;type&#x22;:&#x22;\&#x22;error\&#x22; | \&#x22;pending\&#x22; | \&#x22;running\&#x22;&#x22;,&#x22;full&#x22;:&#x22;TraceStatus&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;\&#x22;running\&#x22;, \&#x22;error\&#x22; or \&#x22;pending\&#x22;. Leave it out once the step is done.&#x22;,&#x22;required&#x22;:false}]" />

### TraceCollapsible [#tracecollapsible]

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;disabled&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:&#x22;false&#x22;,&#x22;description&#x22;:&#x22;Stops the trigger from opening or closing the panel. The trigger stays focusable.&#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;Whether the panel is open. Pass it to control the collapsible.&#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;Runs when the panel wants to open or close. `details.reason` says why, and `details.cancel()` stops it.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onOpenChangeComplete&#x22;,&#x22;type&#x22;:&#x22;(open: boolean) => void&#x22;,&#x22;full&#x22;:&#x22;(open: boolean) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Runs once the panel has finished opening or closing, after any animation.&#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;:&#x22;false&#x22;,&#x22;description&#x22;:&#x22;Whether the panel is open at first, when uncontrolled.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;controller&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;{ isOpen: () => boolean; setOpen: (open: boolean, options?: CollapsibleChangeOptions) => boolean; open: (options?: CollapsibleChangeOptions) => boolean; close: (options?: CollapsibleChangeOptions) => boolean; toggle: (options?: CollapsibleChangeOptions) => boolean; focus: () => void; }&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Opens and closes the panel from anywhere. Create one with `createCollapsibleController()`.&#x22;,&#x22;required&#x22;:false}]" />

### TraceCollapsibleContent [#tracecollapsiblecontent]

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}]" />

### Other parts [#other-parts]

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

* `TraceIcon`: a `<span>`
* `TraceTitle`: a `<span>`
* `TraceCollapsibleTrigger`: a `<button>`
* `TraceDescription`: a `<span>`

## Keyboard [#keyboard]

| Key                       | What it does                                 |
| ------------------------- | -------------------------------------------- |
| <kbd>Tab</kbd>            | Moves to the next row that expands, or link. |
| <kbd>Enter or Space</kbd> | Opens or closes the focused row.             |

## 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 trace, so this one is defined with its core: one `definePrimitive` in `components/keyframery/core/trace-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/trace`.

## Questions

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

Cascade: Lines rise in one after another as they arrive. Fade: A running title has a soft light passing through it; it stops for reduced motion. Draw: When a step finishes, its tick pops in and draws itself. Height: A row that expands opens to its real height. Cascade: The detail's paragraphs rise in one after another as it opens. Spring: The chevron turns down on a spring.

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

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

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

Its behaviour is one definition written with UI SDK's core (`definePrimitive`), in `components/keyframery/core/trace-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 Trace when someone turns on reduced motion?

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