# Metrics dashboard

A SaaS overview for a fictional workspace: a range `Select` that switches every number on the page, four KPI `Card`s with a change `Badge` and a sparkline, a bar chart of daily signups with axis labels and a written summary, and a breakdown of signups by plan. `Stack`, `Heading`, `Text` and `Table` do the rest.

**Example: Fernhill overview** (`examples/recipes/metrics-dashboard.tsx`)

```tsx
'use client'

import {
  Badge,
  BodySmall,
  Card,
  Heading,
  Select,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableHeader,
  TableRow,
  Text,
} from '@blocks/design-system'
import { ChevronRight, TrendingDown, TrendingUp } from 'lucide-react'
import { useId, useState } from 'react'
import styles from './metrics-dashboard.module.css'

type Range = '7' | '30' | '90'

const ranges = [
  { value: '7', label: 'Last 7 days' },
  { value: '30', label: 'Last 30 days' },
  { value: '90', label: 'Last 90 days' },
]

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
const lastFullDay = Date.UTC(2026, 11, 1)

// Formats without Intl so the server and the browser render the same text.
function dayLabel(daysAgo: number) {
  const date = new Date(lastFullDay - daysAgo * 86_400_000)
  return `${months[date.getUTCMonth()]} ${date.getUTCDate()}`
}

// 180 days of signups, oldest first: a weekly rhythm on a slow climb. Integer
// arithmetic only, so every render produces the same numbers.
const weeklyRhythm = [6, 11, 13, 9, 4, -15, -19]
const signups = Array.from({ length: 180 }, (_, day) => 34 + Math.floor(day * 0.22) + (weeklyRhythm[day % 7] ?? 0) + ((day * 37) % 9))

interface Metric {
  label: string
  value: string
  change: number
  /** Churn falling is good news: the badge tone follows meaning, the arrow follows direction. */
  higherIsBetter: boolean
  trend: number[]
}

const sum = (values: number[]) => values.reduce((total, value) => total + value, 0)

function signupsFor(days: number) {
  const current = signups.slice(-days)
  const previous = signups.slice(-days * 2, -days)
  return { current, change: ((sum(current) - sum(previous)) / sum(previous)) * 100 }
}

const metricsByRange: Record<Range, Metric[]> = {
  '7': [
    { label: 'Revenue (MRR)', value: '$48.2k', change: 1.4, higherIsBetter: true, trend: [46.9, 47.1, 47.4, 47.3, 47.8, 48.0, 48.2] },
    { label: 'Active teams', value: '1,284', change: 2.3, higherIsBetter: true, trend: [1251, 1259, 1262, 1270, 1268, 1279, 1284] },
    { label: 'Churn', value: '1.9%', change: -0.4, higherIsBetter: false, trend: [2.0, 2.0, 1.9, 2.0, 1.9, 1.9, 1.9] },
  ],
  '30': [
    { label: 'Revenue (MRR)', value: '$48.2k', change: 6.8, higherIsBetter: true, trend: [44.1, 44.9, 45.6, 46.2, 46.4, 47.1, 47.7, 48.2] },
    { label: 'Active teams', value: '1,284', change: 8.9, higherIsBetter: true, trend: [1178, 1196, 1210, 1225, 1241, 1252, 1270, 1284] },
    { label: 'Churn', value: '2.1%', change: 0.3, higherIsBetter: false, trend: [1.8, 1.9, 1.9, 2.0, 2.2, 2.1, 2.1, 2.1] },
  ],
  '90': [
    { label: 'Revenue (MRR)', value: '$48.2k', change: 19.2, higherIsBetter: true, trend: [39.6, 40.8, 41.9, 43.0, 44.1, 45.6, 46.9, 48.2] },
    { label: 'Active teams', value: '1,284', change: 24.6, higherIsBetter: true, trend: [1030, 1072, 1101, 1149, 1178, 1210, 1252, 1284] },
    { label: 'Churn', value: '2.3%', change: -1.2, higherIsBetter: false, trend: [2.9, 2.7, 2.6, 2.6, 2.4, 2.3, 2.4, 2.3] },
  ],
}

const planShares: Record<Range, number[]> = {
  '7': [0.48, 0.31, 0.15],
  '30': [0.51, 0.29, 0.14],
  '90': [0.55, 0.27, 0.13],
}
const planNames = ['Starter', 'Team', 'Business', 'Enterprise']

export default function MetricsDashboard() {
  const [range, setRange] = useState<Range>('30')
  const [hovered, setHovered] = useState<number | null>(null)
  const chartTitleId = useId()

  const days = Number(range)
  const daily = signupsFor(days)
  const total = sum(daily.current)
  const peak = Math.max(...daily.current)
  const peakIndex = daily.current.indexOf(peak)
  // Round the scale up to a multiple of 20 so the gridline labels stay tidy.
  const scaleMax = Math.ceil(peak / 20) * 20

  const metrics: Metric[] = [
    ...metricsByRange[range].slice(0, 2),
    { label: 'Signups', value: total.toLocaleString('en-US'), change: daily.change, higherIsBetter: true, trend: daily.current },
    ...metricsByRange[range].slice(2),
  ]

  // The last plan takes the remainder, so the breakdown always adds up to the total.
  const planCounts = planShares[range].map((share) => Math.round(total * share))
  const plans = [...planCounts, total - sum(planCounts)].map((count, index) => ({ name: planNames[index], count }))

  const readout =
    hovered === null
      ? `Peak ${peak} on ${dayLabel(days - 1 - peakIndex)}`
      : `${dayLabel(days - 1 - hovered)} · ${daily.current[hovered]} signups`

  return (
    <Stack as="section" aria-labelledby={`${chartTitleId}-overview`} gap="lg" dangerouslySetClassName={styles.dashboard}>
      <Stack direction="row" justify="space-between" align="end" wrap="wrap" gap="md">
        <Stack gap="xxs">
          <Heading as="h2" id={`${chartTitleId}-overview`} fontSize="xl">
            Overview
          </Heading>
          <BodySmall color="text-muted" margin="none">
            Fernhill workspace · through {dayLabel(0)}, 2026
          </BodySmall>
        </Stack>
        <Stack gap="xxs">
          <Select items={ranges} value={range} onValueChange={(value) => value && setRange(value as Range)}>
            <Select.Label>Range</Select.Label>
            <Select.Trigger size="sm" />
            <Select.Content>
              {ranges.map((item) => (
                <Select.Item key={item.value} value={item.value}>
                  {item.label}
                </Select.Item>
              ))}
            </Select.Content>
          </Select>
        </Stack>
      </Stack>

      <ul className={styles.kpis} aria-label="Key metrics">
        {metrics.map((metric) => (
          <Card as="li" key={metric.label} padding="lg" dangerouslySetClassName={styles.kpi}>
            <Text fontSize="sm" color="text-muted">
              {metric.label}
            </Text>
            <Text fontSize="xl" fontWeight="semibold" dangerouslySetClassName={styles.numeric}>
              {metric.value}
            </Text>
            <Stack direction="row" justify="space-between" align="center" gap="sm">
              <Change value={metric.change} higherIsBetter={metric.higherIsBetter} />
              <Sparkline points={metric.trend} />
            </Stack>
          </Card>
        ))}
      </ul>

      <Card as="section" padding="lg" aria-labelledby={chartTitleId}>
        <Stack gap="md">
          <Stack direction="row" justify="space-between" align="baseline" wrap="wrap" gap="sm">
            <Heading as="h3" id={chartTitleId} fontSize="md">
              Daily signups
            </Heading>
            <Text fontSize="sm" color="text-muted" aria-hidden dangerouslySetClassName={styles.numeric}>
              {readout}
            </Text>
          </Stack>
          <div className={styles.plot}>
            <div className={styles.yAxis} aria-hidden>
              <span>{scaleMax}</span>
              <span>{scaleMax / 2}</span>
              <span>0</span>
            </div>
            <div
              className={styles.bars}
              role="img"
              aria-label={`Bar chart of daily signups, ${ranges.find((item) => item.value === range)?.label.toLowerCase()}`}
              aria-describedby={`${chartTitleId}-summary`}
              onPointerLeave={() => setHovered(null)}
            >
              {daily.current.map((count, index) => (
                <span
                  // biome-ignore lint/suspicious/noArrayIndexKey: one column per day, in a fixed order
                  key={index}
                  className={styles.column}
                  data-active={hovered === index || undefined}
                  onPointerEnter={() => setHovered(index)}
                >
                  <span className={styles.bar} style={{ height: `${(count / scaleMax) * 100}%` }} />
                </span>
              ))}
            </div>
          </div>
          <div className={styles.xAxis} aria-hidden>
            <span>{dayLabel(days - 1)}</span>
            <span>{dayLabel(Math.floor((days - 1) / 2))}</span>
            <span>{dayLabel(0)}</span>
          </div>
          <BodySmall id={`${chartTitleId}-summary`} color="text-muted" margin="none">
            {total.toLocaleString('en-US')} signups from {dayLabel(days - 1)} to {dayLabel(0)}, about {Math.round(total / days)} a day, peaking
            at {peak} on {dayLabel(days - 1 - peakIndex)}. Weekends run lower.
          </BodySmall>
          <details className={styles.details}>
            <summary>
              <ChevronRight aria-hidden size={14} className={styles.chevron} />
              View as a table
            </summary>
            <TableContainer tabIndex={0} role="region" aria-label="Daily signups table" dangerouslySetClassName={styles.tableScroll}>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead scope="col">Day</TableHead>
                    <TableHead scope="col" textAlign="right">
                      Signups
                    </TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {daily.current.map((count, index) => {
                    const label = dayLabel(days - 1 - index)
                    return (
                      <TableRow key={label}>
                        <TableHead scope="row">{label}</TableHead>
                        <TableCell textAlign="right" dangerouslySetClassName={styles.numeric}>
                          {count}
                        </TableCell>
                      </TableRow>
                    )
                  })}
                </TableBody>
              </Table>
            </TableContainer>
          </details>
        </Stack>
      </Card>

      <Card as="section" padding="lg" aria-labelledby={`${chartTitleId}-plans`}>
        <Stack gap="md">
          <Stack direction="row" justify="space-between" align="baseline">
            <Heading as="h3" id={`${chartTitleId}-plans`} fontSize="md">
              Top plans
            </Heading>
            <Text fontSize="sm" color="text-muted">
              Share of signups
            </Text>
          </Stack>
          <Stack as="ul" gap="md" margin="none" padding="none" dangerouslySetClassName={styles.plans}>
            {plans.map((plan) => {
              const share = Math.round((plan.count / total) * 100)
              return (
                <Stack as="li" key={plan.name} gap="xs">
                  <Stack direction="row" justify="space-between" gap="sm">
                    <Text fontSize="sm" fontWeight="medium">
                      {plan.name}
                    </Text>
                    <Text fontSize="sm" color="text-muted" dangerouslySetClassName={styles.numeric}>
                      {plan.count.toLocaleString('en-US')} · {share}%
                    </Text>
                  </Stack>
                  <span className={styles.track} aria-hidden>
                    <span className={styles.fill} style={{ width: `${share}%` }} />
                  </span>
                </Stack>
              )
            })}
          </Stack>
        </Stack>
      </Card>
    </Stack>
  )
}

// Direction is in the icon and the sign, not only the color.
function Change({ value, higherIsBetter }: { value: number; higherIsBetter: boolean }) {
  const up = value >= 0
  const Icon = up ? TrendingUp : TrendingDown
  return (
    <Badge tone={up === higherIsBetter ? 'success' : 'danger'}>
      <Icon aria-hidden />
      {up ? '+' : '−'}
      {Math.abs(value).toFixed(1)}%<span className="visually-hidden"> vs. the previous period</span>
    </Badge>
  )
}

// Decorative: the value and the change badge carry the meaning.
function Sparkline({ points }: { points: number[] }) {
  const min = Math.min(...points)
  const span = Math.max(...points) - min || 1
  const coordinates = points.map((point, index) => `${(index / (points.length - 1)) * 100},${22 - ((point - min) / span) * 20}`).join(' ')
  return (
    <svg className={styles.sparkline} viewBox="0 0 100 24" preserveAspectRatio="none" aria-hidden>
      <polyline points={coordinates} fill="none" stroke="currentColor" strokeWidth={1.5} vectorEffect="non-scaling-stroke" />
    </svg>
  )
}
```

## How it works

- **One source of truth.** The signups card, the chart, its summary, the table view and the plan breakdown all derive from the same daily series, so changing the range can never leave two numbers disagreeing. The data comes from fixed integer arithmetic, so the server and the browser render the same page.
- **Change badges carry meaning, not just color.** The arrow and sign show direction; the tone shows whether that direction is good. Churn falling is a green, downward badge. A visually hidden “vs. the previous period” completes the sentence for screen readers.
- **The chart is readable without seeing it.** The plot is a `role="img"` described by the summary sentence below it, and “View as a table” opens every value in a `TableContainer`. Hovering a bar highlights it and shows its day and count in the chart’s header; each column is full height, so short bars are as easy to hit as tall ones. Sparklines are decorative and hidden from assistive technology.
- **Layout follows the component’s width.** A container query puts the KPIs in four columns when the dashboard has room and two on a phone.

## App-owned CSS

The chart geometry, gridlines, sparklines and plan bars are app visuals drawn with tokens only, so they follow the light and dark themes.

`examples/recipes/metrics-dashboard.module.css`:

```css
/* The dashboard lays out by its own width, not the viewport's. */
.dashboard {
  container-type: inline-size;
}

.numeric {
  font-variant-numeric: tabular-nums;
}

.kpis {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: var(--ds-space-md);
  margin: 0;
  padding: 0;
  list-style: none;
}

@container (min-width: 34rem) {
  .kpis {
    grid-template-columns: repeat(4, minmax(0, 1fr));
  }
}

.kpi {
  display: flex;
  flex-direction: column;
  gap: var(--ds-space-sm);
  background-color: var(--ds-color-bg);
}

.sparkline {
  flex: 1;
  min-width: 0;
  max-width: 4rem;
  height: var(--ds-space-lg);
  color: var(--ds-color-text-muted);
}

/* Bar chart: y-axis labels beside a plot with two recessive gridlines. */
.plot {
  display: grid;
  grid-template-columns: auto 1fr;
  gap: var(--ds-space-md);
  height: 10rem;
}

.yAxis {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  margin-block: calc(var(--ds-font-size-xs) / -2);
  font-size: var(--ds-font-size-xs);
  color: var(--ds-color-text-muted);
  text-align: right;
  font-variant-numeric: tabular-nums;
}

.bars {
  display: flex;
  align-items: stretch;
  border-bottom: var(--ds-border-width-sm) solid var(--ds-color-border);
  background:
    linear-gradient(var(--ds-color-border-subtle), var(--ds-color-border-subtle)) top / 100% var(--ds-border-width-sm) no-repeat,
    linear-gradient(var(--ds-color-border-subtle), var(--ds-color-border-subtle)) center / 100% var(--ds-border-width-sm) no-repeat;
}

/* Each column is full height, so a short bar is as easy to hover as a tall one. */
.column {
  display: flex;
  flex: 1;
  align-items: flex-end;
  min-width: 0;
  padding-inline: min(var(--ds-space-xs), 12%);
}

.bar {
  width: 100%;
  border-radius: var(--ds-border-radius-sm) var(--ds-border-radius-sm) 0 0;
  background-color: var(--ds-color-accent);
  transition: opacity var(--ds-duration-fast) var(--ds-easing-standard);
}

.bars:hover .bar {
  opacity: 0.45;
}

.bars:hover .column[data-active] .bar {
  opacity: 1;
}

.xAxis {
  display: flex;
  justify-content: space-between;
  margin-top: calc(var(--ds-space-sm) * -1);
  padding-left: var(--ds-space-xl);
  font-size: var(--ds-font-size-xs);
  color: var(--ds-color-text-muted);
}

/* A chevron that turns when the table opens, in place of the browser's triangle. */
.details summary {
  display: inline-flex;
  align-items: center;
  gap: var(--ds-space-xs);
  font-size: var(--ds-font-size-sm);
  color: var(--ds-color-accent-text);
  list-style: none;
  cursor: pointer;

  &::-webkit-details-marker {
    display: none;
  }
}

.chevron {
  transition: transform var(--ds-duration-fast) var(--ds-easing-standard);

  .details[open] & {
    transform: rotate(90deg);
  }
}

.tableScroll {
  max-height: 16rem;
  margin-top: var(--ds-space-md);
  overflow-y: auto;
}

.plans {
  list-style: none;
}

.track {
  display: block;
  height: var(--ds-space-md);
  border-radius: var(--ds-border-radius-pill);
  background-color: var(--ds-color-surface);
}

.fill {
  display: block;
  height: 100%;
  border-radius: inherit;
  background-color: var(--ds-color-accent);
}

@media (prefers-reduced-motion: reduce) {
  .bar,
  .chevron {
    transition: none;
  }
}
```
