@molecule/app-trace-waterfall-angular

Feature · trace-waterfall · App (browser) · v1.1.2 · Apache-2.0

Distributed-trace span waterfall view (Datadog/Jaeger-style).

npm install @molecule/app-trace-waterfall-angular

npm · Source on GitHub

How it works

@molecule/app-trace-waterfall-angular is a ready-made trace-waterfall feature for the app (browser) side. It composes the core interfaces it needs, so it works with whichever providers your app has bonded.

import { Component } from '@angular/core'
import { TraceWaterfall } from '@molecule/app-trace-waterfall-angular'

@Component({
  selector: 'app-trace',
  standalone: true,
  imports: [TraceWaterfall],
  template: ` <mol-trace-waterfall [spans]="spans" [onSpanClick]="select"></mol-trace-waterfall> `,
})
export class Trace {
  readonly spans = [
    {
      id: 'root',
      name: 'GET /checkout',
      service: 'api-gw',
      startTime: 0,
      duration: 320,
      status: 'ok',
    },
    {
      id: 'auth',
      parentId: 'root',
      name: 'verifyToken',
      service: 'auth-svc',
      startTime: 5,
      duration: 40,
      status: 'ok',
    },
    {
      id: 'db',
      parentId: 'root',
      name: 'db.query',
      service: 'postgres',
      startTime: 50,
      duration: 210,
      status: 'ok',
    },
    {
      id: 'cache',
      parentId: 'root',
      name: 'cache.get',
      service: 'redis',
      startTime: 45,
      duration: 8,
      status: 'error',
    },
  ]
  readonly select = (span: { id: string }): void => console.log('selected', span.id)
}

Works with: @molecule/app-angular, @molecule/app-ui, @molecule/app-ui-angular

Reference

Angular distributed-trace span waterfall visualization — the counterpart of @molecule/app-trace-waterfall-react, with the same props (React names) and the same DOM for the same input.

Exports <TraceWaterfall>, the Span / SpanStatus / SpanRow / SpanLayout types, and the pure layoutSpans() / serviceColor() / formatDurationLabel() helpers used to position rows.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

import { Component } from '@angular/core'
import { TraceWaterfall } from '@molecule/app-trace-waterfall-angular'

@Component({
  selector: 'app-trace',
  standalone: true,
  imports: [TraceWaterfall],
  template: ` <mol-trace-waterfall [spans]="spans" [onSpanClick]="select"></mol-trace-waterfall> `,
})
export class Trace {
  readonly spans = [
    {
      id: 'root',
      name: 'GET /checkout',
      service: 'api-gw',
      startTime: 0,
      duration: 320,
      status: 'ok',
    },
    {
      id: 'auth',
      parentId: 'root',
      name: 'verifyToken',
      service: 'auth-svc',
      startTime: 5,
      duration: 40,
      status: 'ok',
    },
    {
      id: 'db',
      parentId: 'root',
      name: 'db.query',
      service: 'postgres',
      startTime: 50,
      duration: 210,
      status: 'ok',
    },
    {
      id: 'cache',
      parentId: 'root',
      name: 'cache.get',
      service: 'redis',
      startTime: 45,
      duration: 8,
      status: 'error',
    },
  ]
  readonly select = (span: { id: string }): void => console.log('selected', span.id)
}

Type

feature

Installation

npm install @molecule/app-trace-waterfall-angular @angular/common @angular/core @angular/platform-browser @molecule/app-angular @molecule/app-ui @molecule/app-ui-angular

API

Interfaces

DurationParts

A duration split for translation: which unit its label names, and the number.

interface DurationParts {
  /** The unit the label names. */
  unit: DurationUnit
  /**
   * The duration rounded to the unit, as an `Intl.NumberFormat` string in
   * `locale` (no grouping, up to two decimals — exactly the digits the
   * English labels carry).
   */
  value: string
}

Span

A single distributed-trace span. Times are numeric milliseconds (labels assume ms; layout is unit-agnostic) — startTime and duration must share a unit. The tree is formed by parentId references; spans without a parentId (or whose parentId isn't present in the input array) are roots.

interface Span {
  /** Stable id for this span. */
  id: string
  /** Id of the parent span; omit (or set undefined) for a root span. */
  parentId?: string
  /** Operation name (e.g. `GET /users/:id`, `db.query`). */
  name: string
  /** Service / component label that emitted this span (e.g. `auth-api`). */
  service?: string
  /**
   * Start time relative to some shared origin. Any unit is fine as long as
   * it matches `duration`; the trace is auto-scaled to its own min/max.
   */
  startTime: number
  /** Duration in the same unit as `startTime`. Must be >= 0. */
  duration: number
  /** Optional status; controls the bar color. */
  status?: SpanStatus
  /** Optional structured attributes (tags, key/value pairs). */
  attributes?: Record<string, unknown>
}

SpanRow

Layout metadata computed for a single span row.

interface SpanRow {
  /** The original span. */
  span: Span
  /** Zero-based depth in the parent tree (root === 0). */
  depth: number
  /** Position of the bar's left edge as a fraction `[0, 1]` of the trace duration. */
  startFraction: number
  /** Width of the bar as a fraction `[0, 1]` of the trace duration. */
  widthFraction: number
}

SpanLayout

Output of layoutSpans: ordered rows + the trace's absolute time bounds.

interface SpanLayout {
  /** Rows in render order (depth-first, sorted by `startTime`). */
  rows: SpanRow[]
  /** Earliest `startTime` across all spans (the trace origin on the axis). */
  traceStart: number
  /** Latest end time (`startTime + duration`) across all spans. */
  traceEnd: number
  /** `traceEnd - traceStart`, clamped to a minimum of `1` to avoid divide-by-zero. */
  traceDuration: number
}

TraceWaterfallProps

Props accepted by the TraceWaterfall component — React's prop names.

interface TraceWaterfallProps {
  /** Flat list of spans; tree is derived from `parentId` references. */
  spans: Span[]
  /** Optional root span id to focus the view on a single subtree. */
  rootSpanId?: string
  /** Optional id of the currently selected span; sets `aria-selected` on that row. */
  selectedSpanId?: string
  /** Click handler invoked when a span row (label or bar) is selected. */
  onSpanClick?: (span: Span) => void
  /**
   * Optional content shown when `spans` is empty. Angular projects it as `[slot=emptyState]` content — pass it in the host template, not as an input.
   */
  emptyState?: unknown
  /** Extra classes merged onto the root via `cm.cn`. */
  className?: string
}

Types

DurationUnit

The unit a duration label names: microseconds (< 1), milliseconds (< 1000) or seconds.

type DurationUnit = 'us' | 'ms' | 's'

DurationLabelTranslator

The translation function the duration label helpers need — the shape of the t a framework binding's useTranslation() / useT() returns.

type DurationLabelTranslator = (
  key: string,
  values?: Record<string, string | number>,
  options?: { defaultValue?: string },
) => string

SpanStatus

Status indicator for a span. Mirrors common OTel-style status semantics.

type SpanStatus = 'ok' | 'error' | 'pending'

Classes

TraceWaterfall

TraceWaterfall component.

Datadog/Jaeger-style distributed-trace waterfall: each span renders as a horizontal bar positioned by startTime, scaled to the trace's total duration and indented by parent depth, under a time axis. Service name shows as a colored tag beside the operation name; bar color encodes status.

React's root is the <div role="region"> when there are rows, the bare emptyState node when the trace is empty and a node was given, and the <div role="status"> fallback otherwise — three different roots, so the rendered content stands in front of the host's place and the host itself leaves the page (placeContentBefore + setElementPresent). The empty state arrives as a node-valued input (emptyState, a TemplateRef).

Styling is fully ClassMap-driven for layout. Only color attributes (status colors, service-tag colors, bar fill) and pixel-perfect axis geometry use inline styles — properties ClassMap does not model.

@Component({
  selector: 'mol-trace-waterfall',
  standalone: true,
  imports: [NgTemplateOutlet],
  hostDirectives: [MolPlacement],
  inputs: ['spans', 'rootSpanId', 'selectedSpanId', 'onSpanClick', 'emptyState', 'className'],
  // prettier-ignore
  template: `@if (rows().length === 0) {@if (emptyTemplate(); as emptyTpl) {<ng-container [ngTemplateOutlet]="emptyTpl" />} @else {<div [class]="emptyClasses()" data-mol-id="trace-waterfall-empty" role="status">{{ emptyLabel() }}</div>}} @else {<div [class]="rootClasses()" role="region" [attr.aria-label]="ariaLabel()" data-mol-id="trace-waterfall"><div [class]="axisClasses()" data-mol-id="trace-waterfall-axis"><div [style]="totalStyle()">{{ totalLabel() }}</div><div [style]="tickBoxStyle()">@for (tick of ticks(); track $index) {<div [style]="tickStyle(tick)" data-mol-id="trace-waterfall-axis-tick">{{ tick.label }}</div>}</div></div><div role="tree" data-mol-id="trace-waterfall-rows">@for (row of rows(); track row.span.id) {<div [class]="rowClasses()" [style]="rowStyle()" role="treeitem" [attr.aria-level]="row.depth + 1" [attr.aria-selected]="selectedSpanId === row.span.id ? 'true' : 'false'" [attr.aria-label]="rowAriaLabel(row)" [attr.tabindex]="interactive() ? 0 : -1" (click)="rowClick(row)" (keydown)="rowKeydown(row, $event)" data-mol-id="trace-waterfall-row" [attr.data-span-id]="row.span.id"><div [class]="labelClasses()" [style]="labelStyle(row)">@if (row.span.service) {<span data-mol-id="trace-waterfall-service-tag" [style]="tagStyle(row)">{{ row.span.service }}</span>}<span [style]="nameStyle()" data-mol-id="trace-waterfall-name">{{ row.span.name }}</span></div><div [style]="barBoxStyle()"><div data-mol-id="trace-waterfall-bar" [style]="barStyle(row)"></div><div data-mol-id="trace-waterfall-duration" [style]="durationStyle(row)">{{ durationText(row) }}</div></div></div>}</div></div>}`,
})
export class TraceWaterfall {
  spans: Span[] = []

  rootSpanId?: string

  selectedSpanId?: string

  onSpanClick?: (span: Span) => void

  emptyState?: unknown

  className?: string

  private readonly i18n = useTranslation()

  private readonly activeLocale = useLocale()

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  constructor() {
    usePlacement(() => {
      placeContentBefore(this.host.nativeElement, this.host.nativeElement)
      setElementPresent(this.host.nativeElement, false)
    })
  }

  /** The current class map. */
  cm(): UIClassMap {
    return getClassMap()
  }

  layout(): SpanLayout {
    return layoutSpans(this.spans ?? [], this.rootSpanId)
  }

  /** The visible rows. */
  rows(): SpanRow[] {
    return this.layout().rows
  }

  emptyTemplate(): TemplateRef<unknown> | null {
    return this.emptyState instanceof TemplateRef ? this.emptyState : null
  }

  interactive(): boolean {
    return Boolean(this.onSpanClick)
  }

  rootClasses(): string {
    return this.cm().cn(this.cm().stack(1), this.className)
  }

  /** The fallback status line's class list. */
  emptyClasses(): string {
    return this.cm().cn(this.cm().sp('p', 3), this.cm().textSize('sm'), this.className)
  }

  /** The time axis's class list. */
  axisClasses(): string {
    return this.cm().cn(this.cm().flex({ align: 'center' }), this.cm().textSize('xs'))
  }

  /** A span row's class list. */
  rowClasses(): string {
    return this.cm().cn(this.cm().flex({ align: 'center' }))
  }

  /** The label column's class list. */
  labelClasses(): string {
    return this.cm().cn(this.cm().flex({ align: 'center', gap: 'sm' }), this.cm().textSize('xs'))
  }

  /** The translated empty-trace message. */
  emptyLabel(): string {
    return this.i18n.t('traceWaterfall.empty', undefined, {
      defaultValue: 'No spans to display.',
    })
  }

  /** The translated region label. */
  ariaLabel(): string {
    return this.i18n.t('traceWaterfall.aria.label', undefined, {
      defaultValue: 'Distributed trace waterfall',
    })
  }

  totalLabel(): string {
    return this.i18n.t(
      'traceWaterfall.totalDuration',
      {
        duration: translateDuration(this.layout().traceDuration, this.activeLocale(), this.i18n.t),
      },
      { defaultValue: 'Total: {{duration}}' },
    )
  }

  rowAriaLabel(row: SpanRow): string {
    return this.i18n.t(
      'traceWaterfall.row.aria',
      {
        name: row.span.name,
        service: row.span.service ?? '',
        duration: this.durationText(row),
      },
      { defaultValue: '{{service}} · {{name}} · {{duration}}' },
    )
  }

  durationText(row: SpanRow): string {
    return translateDuration(row.span.duration, this.activeLocale(), this.i18n.t)
  }

  ticks(): AxisTick[] {
    const traceDuration = this.layout().traceDuration
    const out: AxisTick[] = []
    for (let i = 0; i < AXIS_TICK_COUNT; i++) {
      const fraction = i / (AXIS_TICK_COUNT - 1)
      out.push({
        left: `${fraction * 100}%`,
        label: translateDuration(fraction * traceDuration, this.activeLocale(), this.i18n.t),
      })
    }
    return out
  }

  rowClick(row: SpanRow): void {
    this.onSpanClick?.(row.span)
  }

  rowKeydown(row: SpanRow, ev: KeyboardEvent): void {
    if (!this.onSpanClick) return
    if (ev.key === 'Enter' || ev.key === ' ') {
      ev.preventDefault()
      this.onSpanClick(row.span)
    }
  }

  totalStyle(): Record<string, string> {
    return { width: `${LABEL_COLUMN_PX}px`, 'flex-shrink': '0', opacity: '0.7' }
  }

  /** The tick container's inline style. */
  tickBoxStyle(): Record<string, string> {
    return { position: 'relative', flex: '1', height: '18px' }
  }

  /** A tick mark's inline style. */
  tickStyle(tick: AxisTick): Record<string, string> {
    return {
      position: 'absolute',
      left: tick.left,
      top: '0px',
      transform: 'translateX(-50%)',
      opacity: '0.7',
      'white-space': 'nowrap',
    }
  }

  rowStyle(): Record<string, string> {
    return { height: `${ROW_HEIGHT_PX}px` }
  }

  labelStyle(row: SpanRow): Record<string, string> {
    return {
      width: `${LABEL_COLUMN_PX}px`,
      'flex-shrink': '0',
      'padding-left': `${row.depth * DEPTH_INDENT_PX}px`,
      cursor: this.interactive() ? 'pointer' : 'default',
      overflow: 'hidden',
      'white-space': 'nowrap',
      'text-overflow': 'ellipsis',
    }
  }

  tagStyle(row: SpanRow): Record<string, string> {
    const service = row.span.service
    return {
      display: 'inline-block',
      padding: '0 6px',
      'border-radius': '4px',
      background: service ? serviceColor(service) : '',
      color: '#fff',
      'font-weight': '600',
      'font-size': '10px',
      'line-height': '14px',
      'flex-shrink': '0',
    }
  }

  /** The operation name's inline style. */
  nameStyle(): Record<string, string> {
    return { overflow: 'hidden', 'text-overflow': 'ellipsis' }
  }

  /** The bar container's inline style. */
  barBoxStyle(): Record<string, string> {
    return {
      position: 'relative',
      flex: '1',
      height: `${ROW_HEIGHT_PX}px`,
      cursor: this.interactive() ? 'pointer' : 'default',
    }
  }

  barStyle(row: SpanRow): Record<string, string> {
    const status = row.span.status
    return {
      position: 'absolute',
      top: `${(ROW_HEIGHT_PX - BAR_HEIGHT_PX) / 2}px`,
      left: `${row.startFraction * 100}%`,
      width: `${Math.max(row.widthFraction * 100, 0.5)}%`,
      height: `${BAR_HEIGHT_PX}px`,
      background: status ? STATUS_COLOR[status] : DEFAULT_BAR_COLOR,
      'border-radius': '2px',
    }
  }

  durationStyle(row: SpanRow): Record<string, string> {
    const width = Math.max(row.widthFraction * 100, 0.5)
    return {
      position: 'absolute',
      top: '0px',
      left: `calc(${row.startFraction * 100}% + ${width}% + 6px)`,
      height: `${ROW_HEIGHT_PX}px`,
      display: 'flex',
      'align-items': 'center',
      'font-size': '11px',
      opacity: '0.75',
      'white-space': 'nowrap',
      'pointer-events': 'none',
    }
  }
}

(Member comments are shortened to their first sentence, and the 29 longest are left out to fit; the full declaration is in node_modules/@molecule/app-trace-waterfall-angular/dist/trace-waterfall.component.d.ts.)

Functions

formatDurationLabel(value)

Format a duration value (in the same unit as Span.startTime) as a short, human-readable string: < 1 → microseconds, < 1000 → ms, otherwise seconds with one decimal.

function formatDurationLabel(value: number): string
  • value — The numeric value to format.

Returns: A short label string.

formatDurationParts(value, locale)

Split a duration value (in the same unit as Span.startTime) for translation: the unit its label names — < 1 → microseconds, < 1000 → ms, otherwise seconds — and the number in that unit, formatted in locale so it follows a locale switch. Pair the result with translateDuration, which renders it through t().

function formatDurationParts(value: number, locale: string): DurationParts
  • value — The numeric value to split.
  • locale — The locale to format the number in.

Returns: The unit and the formatted number.

translateDuration(value, locale, t)

A duration label for the axis ticks and the row badges: the unit and the number in the app's active locale go through t() as one string, so the label follows a locale switch (and the pseudo-locale check sees it). The keys are traceWaterfall.duration.us / .ms / .s in the @molecule/app-locales-trace-waterfall bond.

function translateDuration(value: number, locale: string, t: DurationLabelTranslator): string
  • value — The numeric value to label.
  • locale — The app's active locale.
  • t — The translation function.

Returns: The label in the active locale.

layoutSpans(spans, rootSpanId)

Build a hierarchical, time-positioned layout for a flat list of spans.

Behavior:

  • Spans are linked by parentId. A span whose parentId is missing from the input (or undefined) is treated as a root.
  • If rootSpanId is provided AND that id exists in the input, the layout is restricted to that span and its descendants. Otherwise every root contributes its own subtree.
  • Children are sorted by startTime ascending (stable for equal times).
  • traceStart / traceEnd are derived from the included spans only.
  • traceDuration is clamped to >= 1 so callers can safely divide.

The output is intentionally framework-agnostic: callers (such as <TraceWaterfall>) can render the rows however they like.

function layoutSpans(spans: Span[], rootSpanId?: string): SpanLayout
  • spans — Flat list of spans, in any order.
  • rootSpanId — Optional id to use as the visible root.

Returns: Layout rows, sorted depth-first, with normalized fractions.

serviceColor(service)

Deterministically derive a hex color from a service name. Used for the color tag next to each span row. Same input always yields the same color across renders so a service is visually stable.

function serviceColor(service: string): string
  • service — Service / component label.

Returns: A hex color string suitable for an inline style.background.

Injection Notes

Requirements

Peer dependencies:

  • @angular/common ^22.0.0
  • @angular/core ^22.0.0
  • @angular/platform-browser ^22.0.0
  • @molecule/app-angular ^3.13.0 || ^4.0.0
  • @molecule/app-ui ^1.0.1
  • @molecule/app-ui-angular ^1.1.0

Runtime Dependencies

  • @angular/common
  • @angular/core
  • @angular/platform-browser
  • @molecule/app-angular
  • @molecule/app-ui
  • @molecule/app-ui-angular

Duration labels assume time values are MILLISECONDS: formatDurationLabel renders values below 1 as microseconds and 1000+ as seconds, so seconds-unit spans get wrong axis/row labels even though bar layout itself is unit-agnostic — feed ms (or divide labels yourself). Bar status colors and the 12-hue service palette are hardcoded hex (theme-independent, legible in light + dark). The label column is fixed at 240px; long names ellipsize. Rows are keyboard-activatable when onSpanClick is set. The emptyState node is a node-valued input (a TemplateRef from an <ng-template>). Aria/empty-state strings come from the companion @molecule/app-locales-trace-waterfall bond.

Translations

Translation strings are provided by @molecule/app-locales-trace-waterfall.