Tracing

Composable primitives for distributed-trace views built on the shared design system

import { Trace } from 'ui-patterns/Trace'

Trace.Root indexes a list of OpenTelemetry-style spans and shares the result with every part inside it. The other parts are small primitives you compose into the view you need.

Composition

Loading...
import { Trace, type Span, type TraceData } from 'ui-patterns/Trace'
 
function span(
  id: string,
  parentId: string | null,
  name: string,
  startMs: number,
  endMs: number | null,
  extra: Partial<Pick<Span, 'status' | 'attributes' | 'events'>> = {}
): Span {
  return {
    id,
    parentId,
    traceId: 'demo',
    name,
    startMs,
    endMs,
    status: 'ok',
    attributes: {},
    events: [],
    ...extra,
  }
}
 
const finished: TraceData = {
  spans: [
    span('root', null, 'GET /rest/v1/orders', 0, 480, {
      attributes: {
        'http.method': 'GET',
        'http.route': '/rest/v1/orders',
        'http.status_code': 200,
        'client.address': '203.0.113.42',
      },
    }),
    span('auth', 'root', 'auth.verify_jwt', 8, 140, {
      attributes: { 'enduser.id': 'usr_42', 'auth.method': 'jwt' },
      events: [
        { timeMs: 30, name: 'jwt.decoded' },
        { timeMs: 95, name: 'jwks.cache_miss' },
      ],
    }),
    span('db', 'root', 'postgrest.query', 70, 410, {
      attributes: { 'db.system': 'postgresql', 'db.schema': 'public', 'db.table': 'orders' },
    }),
    span('plan', 'db', 'db.plan', 72, 90, {
      attributes: { 'db.plan.rows_estimate': 1200, 'db.plan.cost': 48.2 },
    }),
    span('exec', 'db', 'db.execute', 95, 400, {
      attributes: { 'db.rows_affected': 24, 'db.cache_hit': true },
    }),
    span('rls', 'root', 'rls.policy_check', 420, 470, {
      status: 'error',
      attributes: { 'rls.policy': 'orders_select_own', 'error.message': 'permission denied' },
    }),
  ],
}
 
export function TraceWaterfallDemo() {
  return (
    <div className="flex w-full flex-col gap-3">
      <Trace.Root trace={finished} defaultCollapsed={new Set(['db'])}>
        <Trace.Header>
          <Trace.Title />
          <Trace.Status />
        </Trace.Header>
        <Trace.Summary>
          <Trace.SummaryItem label="Duration">
            <Trace.TotalDuration />
          </Trace.SummaryItem>
          <Trace.SummaryItem label="Depth">
            <Trace.Depth />
          </Trace.SummaryItem>
          <Trace.SummaryItem label="Total Spans">
            <Trace.SpanCount />
          </Trace.SummaryItem>
        </Trace.Summary>
        <Trace.Waterfall treeWidth={220} className="h-64" minimap={<Trace.Minimap />}>
          <Trace.Ruler>
            <Trace.CollapseAll />
            <Trace.ResetZoom />
          </Trace.Ruler>
          <Trace.Grid />
          <Trace.Cursor />
          <Trace.Scrubber />
          <Trace.Rows>
            <Trace.Cell />
            <Trace.Lane>
              <Trace.Bar />
              <Trace.Timing />
              <Trace.CollapsedChildren />
              <Trace.Markers />
            </Trace.Lane>
          </Trace.Rows>
        </Trace.Waterfall>
        <Trace.Inspector />
      </Trace.Root>
    </div>
  )
}
<Trace.Root trace={trace}>
  <Trace.Header>
    <Trace.Title />
    <Trace.Status />
  </Trace.Header>
  <Trace.Summary>
    <Trace.SummaryItem label="Duration">
      <Trace.TotalDuration />
    </Trace.SummaryItem>
    <Trace.SummaryItem label="Depth">
      <Trace.Depth />
    </Trace.SummaryItem>
    <Trace.SummaryItem label="Total Spans">
      <Trace.SpanCount />
    </Trace.SummaryItem>
  </Trace.Summary>
  <Trace.Waterfall minimap={<Trace.Minimap />}>
    <Trace.Ruler>
      <Trace.CollapseAll />
      <Trace.ResetZoom />
    </Trace.Ruler>
    <Trace.Grid />
    <Trace.Cursor />
    <Trace.Scrubber />
    <Trace.Rows>
      <Trace.Cell />
      <Trace.Lane>
        <Trace.Bar />
        <Trace.Timing />
        <Trace.CollapsedChildren />
        <Trace.Markers />
      </Trace.Lane>
    </Trace.Rows>
  </Trace.Waterfall>
  <Trace.Inspector />
</Trace.Root>

Trace.Header is a layout container for the controls above the waterfall. Trace.Title shows the name of the trace's first root span. Trace.Status shows Live while any span is still running, Failed when the root span has an error status, and Done otherwise. It also announces changes to screen readers.

Trace.CollapseAll and Trace.ResetZoom are icon buttons with tooltips that go at the right end of the ruler's tree cell, as children of Trace.Ruler. Trace.CollapseAll collapses every span that has children, and expands them all again when they are already collapsed. Trace.ResetZoom restores the full window and is disabled until you zoom.

Summary

Trace.Summary is a divided strip of facts about the whole trace, meant to sit between the header and the waterfall. Each fact is a Trace.SummaryItem with a label, and its children are the value. Trace.TotalDuration, Trace.SpanCount and Trace.Depth read the trace and render the total duration, the number of spans, and how many levels deep the tree goes. Anything else can be a value too, so you can mix in facts the primitives don't cover.

Waterfall and ruler

Trace.Waterfall is the layout container. It measures its width so time can be mapped to pixels, and has two columns: the tree and the timeline. treeWidth sets the tree's starting width and minTreeWidth its lower bound. Drag the divider between the columns to resize the tree; it is a focusable separator, so the left and right arrow keys nudge it and Home and End jump to its bounds. The timeline column always keeps a minimum width, so the tree can never be dragged over it.

Pass the minimap to the minimap prop rather than as a child, so it sits above the ruler and outside the area that handles pointer gestures.

Trace.Ruler draws the time axis, adapts its ticks to the visible range, and renders its children at the right end of its tree cell, next to the "Span" label. Trace.Grid draws a vertical gridline at every tick below it. While a trace is live, Trace.Cursor draws a line at nowMs from the top of the ruler to the bottom of the waterfall. Pass nowMs on the trace to pin it, and minRangeMs to keep a minimum visible duration while live. Trace.Scrubber follows the pointer across the timeline with a line and a label reading the offset from the trace start. Place Trace.Grid, Trace.Cursor and Trace.Scrubber directly after the ruler.

Rows and bars

Trace.Rows is a virtualized, scrollable list with one row per visible span. Its children are the row template and render once per row. Trace.Cell is the tree column: indent by depth, an expand and collapse toggle, the span name, and a spinner while the span is running. Trace.Lane is the timeline column, a positioned container for the primitives below. Compose the primitives in this order so markers draw over the bar:

  • Trace.Bar draws the span from its start to its end, tinted by status. A running span extends to nowMs.
  • Trace.Timing shows the span's duration just after the bar, or inside the bar's end when there is no room after it.
  • Trace.CollapsedChildren draws a tick at each direct child's midpoint when a span is collapsed.
  • Trace.Markers places a marker at each of the span's event timestamps.

Rows follow the tree pattern. Use the arrow keys to move between rows, Right and Left to expand and collapse (Left on a collapsed row moves to its parent), and Enter or Space to select. Read the selection and collapse state with useView().

Panning and zooming

Drag anywhere across the timeline to pan the window, and use the wheel over it to zoom around the pointer. Panning starts only once the pointer has moved a few pixels, so a drag that ends on a row never selects it.

Trace.Minimap compresses the whole trace into a full-width strip above the ruler, with one row per depth level, colored by span status. Pass it to the waterfall's minimap prop. The brush shows the visible window. Drag the brush to pan and drag either edge to resize it. Outside the brush, drag to select a new window, or click to recenter the current one. With the brush focused, the left and right arrow keys pan, and Shift with an arrow key moves the end edge.

Until the window is changed, it follows the trace as it grows. Once it is zoomed it stays fixed, and ruler labels still read as offsets from the trace start. Use Trace.ResetZoom to follow the trace again, or read and control the window yourself with useView(): window, setWindow(start, end) and resetWindow().

Inspector

Place <Trace.Inspector /> once inside Trace.Root. When a span is selected, it opens a popover next to the span's bar with its name, status, start offset, duration, attributes and events. Arrow keys keep moving between rows while it is open, and clicking another row moves it to that span. Press Escape or click outside the waterfall to close it and clear the selection. If the selected row scrolls out of view, the popover hides and comes back when the row does.

Live traces

Spans without an end are running. Update the trace and nowMs as time passes and the running bars grow, the ruler follows, and Trace.Status changes from Live to Done when the last span finishes. Press Play to run this example.

Loading...
import { Pause, Play } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { Button } from 'ui'
import { Trace, type Span } from 'ui-patterns/Trace'
 
const DURATION_MS = 6000
 
interface Step {
  id: string
  parentId: string | null
  name: string
  startMs: number
  endMs: number
  status?: 'error'
  events?: { timeMs: number; name: string }[]
}
 
const PLAN: Step[] = [
  {
    id: 'run',
    parentId: null,
    name: 'POST /functions/v1/process-order',
    startMs: 0,
    endMs: DURATION_MS,
    events: [{ timeMs: 450, name: 'order.validated' }],
  },
  { id: 'auth', parentId: 'run', name: 'auth.verify_jwt', startMs: 50, endMs: 400 },
  { id: 'select', parentId: 'run', name: 'postgrest.select', startMs: 450, endMs: 1800 },
  { id: 'query', parentId: 'select', name: 'db.query', startMs: 500, endMs: 1700 },
  { id: 'upload', parentId: 'run', name: 'storage.upload', startMs: 1900, endMs: 3600 },
  {
    id: 'write',
    parentId: 'upload',
    name: 'storage.write',
    startMs: 1950,
    endMs: 3500,
    events: [{ timeMs: 2500, name: 'invoice.rendered' }],
  },
  { id: 'broadcast', parentId: 'run', name: 'realtime.broadcast', startMs: 3700, endMs: 5900 },
  {
    id: 'webhook',
    parentId: 'run',
    name: 'webhook.deliver',
    startMs: 3900,
    endMs: 5200,
    status: 'error',
    events: [
      { timeMs: 4300, name: 'retry 1' },
      { timeMs: 4800, name: 'retry 2' },
    ],
  },
]
 
function buildSpans(elapsedMs: number): Span[] {
  return PLAN.filter((step) => elapsedMs >= step.startMs).map((step) => {
    const isDone = elapsedMs >= step.endMs
    return {
      id: step.id,
      parentId: step.parentId,
      traceId: 'live-demo',
      name: step.name,
      startMs: step.startMs,
      endMs: isDone ? step.endMs : null,
      status: isDone ? (step.status ?? 'ok') : 'unset',
      attributes: {},
      events: (step.events ?? []).filter((event) => event.timeMs <= elapsedMs),
    }
  })
}
 
export function TraceWaterfallLiveDemo() {
  const [elapsedMs, setElapsedMs] = useState(0)
  const [isPlaying, setIsPlaying] = useState(false)
  const baseMs = useRef(0)
  const sessionStart = useRef(0)
 
  useEffect(() => {
    if (!isPlaying) return
    sessionStart.current = performance.now()
    const interval = setInterval(() => {
      const elapsed = baseMs.current + (performance.now() - sessionStart.current)
      if (elapsed >= DURATION_MS) {
        baseMs.current = DURATION_MS
        setElapsedMs(DURATION_MS)
        setIsPlaying(false)
        return
      }
      setElapsedMs(elapsed)
    }, 100)
    return () => {
      clearInterval(interval)
      baseMs.current = Math.min(
        DURATION_MS,
        baseMs.current + (performance.now() - sessionStart.current)
      )
      setElapsedMs(baseMs.current)
    }
  }, [isPlaying])
 
  const trace = { spans: buildSpans(elapsedMs), nowMs: elapsedMs }
 
  return (
    <div className="flex w-full flex-col gap-3">
      <Trace.Root trace={trace} minRangeMs={3000}>
        <Trace.Header>
          <Trace.Title />
          <Trace.Status />
          <div className="ml-auto flex items-center gap-2">
            <Button
              variant="default"
              size="tiny"
              icon={isPlaying ? <Pause /> : <Play />}
              onClick={() => {
                if (!isPlaying && baseMs.current >= DURATION_MS) {
                  baseMs.current = 0
                  setElapsedMs(0)
                }
                setIsPlaying((playing) => !playing)
              }}
            >
              {isPlaying ? 'Pause' : 'Play'}
            </Button>
          </div>
        </Trace.Header>
        <Trace.Waterfall treeWidth={330} className="h-80" minimap={<Trace.Minimap />}>
          <Trace.Ruler>
            <Trace.CollapseAll />
            <Trace.ResetZoom />
          </Trace.Ruler>
          <Trace.Grid />
          <Trace.Cursor />
          <Trace.Scrubber />
          <Trace.Rows>
            <Trace.Cell />
            <Trace.Lane>
              <Trace.Bar />
              <Trace.Timing />
              <Trace.CollapsedChildren />
              <Trace.Markers />
            </Trace.Lane>
          </Trace.Rows>
        </Trace.Waterfall>
        <Trace.Inspector />
      </Trace.Root>
    </div>
  )
}