# Trend chart

> One metric over time, the way an analytics screen needs it: the period before as a dashed line, an unfinished day drawn dashed, a readout that glides with the pointer, and drag to zoom.

The chart at the top of every analytics page is usually a chart library, a tooltip plugin and a zoom plugin that don't know about each other, and it jumps every time the filter or the range changes. This is one line that knows what changed. Same days with new numbers (a filter) and the line morphs into place while the scale rolls to its new top; new days (a range, a zoom) and the old line stretches to where its days sit on the new axis while the new one fades in over it, so zooming in looks like zooming in. Turn on the period before and a dashed line draws itself in from the left. Point at it and a hairline and a dot follow you, with one readout card gliding beside them: the date morphs, the figures roll, and an optional note line says what was behind that day. Drag across it and Time brush snaps to whole buckets and hands you the span. A last bucket that isn't over yet is drawn dashed, so a dip at the end isn't news.

## Install

```bash
npx shadcn@latest add @hairline/trend-chart
```

Needs React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

- npm: none
- Hairline UI components it needs (the CLI installs them too): `number-roll`, `text-morph`
- Docs and live preview: https://hairlineui.com/ui/trend-chart
- Registry item (source): https://hairlineui.com/r/trend-chart.json

## Usage

```tsx
import { TrendChart } from "@/components/trend-chart";

<TrendChart
  label="Visitors by day"
  buckets={days}          // bucket starts, epoch ms
  values={visitors}
  previous={visitorsBefore}
  unit="visitors"
  onZoom={({ start, end }) => setRange({ start, end })}
/>
```

## In an analytics overview

Keep the range in state and fetch buckets for it; the chart works out whether the change is a morph or a zoom. Zoom sets the range, Back clears it. The note line can say anything you know about a bucket, here its top source.

```tsx
"use client";
import { useEffect, useState } from "react";
import { TrendChart } from "@/components/trend-chart";

type Series = { buckets: number[]; values: number[]; previous: number[]; topSource: string[] };

export function VisitorsChart({ site, compare }: { site: string; compare: boolean }) {
  const [zoom, setZoom] = useState<{ start: number; end: number } | null>(null);
  const [data, setData] = useState<Series | null>(null);

  useEffect(() => {
    const range = zoom ?? { start: Date.now() - 30 * 86_400_000, end: Date.now() };
    const interval = range.end - range.start <= 2 * 86_400_000 ? "hour" : "day";
    const q = new URLSearchParams({ site, from: String(range.start), to: String(range.end), interval });
    fetch(`/api/stats/timeseries?${q}`).then((r) => r.json()).then(setData);
  }, [site, zoom]);

  if (!data) return null;
  return (
    <section>
      {zoom && <button onClick={() => setZoom(null)}>Back</button>}
      <TrendChart
        label="Visitors"
        buckets={data.buckets}
        values={data.values}
        previous={compare ? data.previous : null}
        interval={data.buckets.length > 1 && data.buckets[1] - data.buckets[0] < 86_400_000 ? "hour" : "day"}
        unit="visitors"
        onZoom={setZoom}
        note={(i) => (data.topSource[i] ? `Mostly from ${data.topSource[i]}` : null)}
      />
    </section>
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `buckets` | `number[]` | – | Bucket starts in epoch ms, oldest first. Same first bucket, count and interval as before means a morph; anything else is a zoom. |
| `values` | `number[]` | – | One value per bucket. |
| `previous` | `number[] \| null` | – | The period before, bucket for bucket. null hides the dashed line. |
| `interval` | `"hour" \| "day" \| "week" \| "month"` | `"day"` | How long one bucket is: sets the last bucket's end, the date words and the shortest span the brush takes. |
| `kind` | `"count" \| "percent" \| "duration"` | `"count"` | Counts (or money, with format); percentages from 0 to 100; or durations in seconds ("2m 41s", morphed rather than rolled). |
| `format` | `Intl.NumberFormatOptions` | `{ maximumFractionDigits: 0 }` | How counts are written in the readout and the table. The scale writes the same format compactly (1.2K, $4.5K). |
| `unit` | `string` | – | What one value is called, after the figure: "visitors". |
| `previousLabel` | `string` | `"the period before"` | How the readout names the dashed line. |
| `now` | `number` | `the clock at mount` | A last bucket that ends after this is unfinished and drawn dashed. |
| `onZoom` | `({ start, end }) => void` | – | Called with the span dragged across, in epoch ms, snapped to bucket edges. Without it the chart can't be brushed. |
| `note` | `(index) => string \| null` | – | A line under the figures in the readout for that bucket. |
| `onActiveChange` | `(index \| null) => void` | – | The bucket being read, to highlight the same bucket elsewhere. |
| `label` | `string` | – | Accessible name of the chart and caption of its table. |
| `locale` | `string` | – | For dates and numbers; the viewer's own by default. |
| `className` | `string` | – | On the root. The readout's figure has data-slot="figure" for your display font. |

## States

- **arrive**: The first time it has data, the line and its wash are revealed from left to right (a clip, 1100ms).
- **morph**: New values on the same buckets (a filter): every point tweens to its new height (640ms, ease-out) and the scale's figures roll to the new round top.
- **zoom**: New buckets (a range, a zoom, a new interval): the axis eases from the old span to the new one, so the old line stretches or shrinks to where its days sit while it fades out under the new one (640ms). The tick labels crossfade the same way. A change that lands mid-change starts from what is on screen.
- **compare**: previous turns on: the dashed line is drawn in from the left (900ms) and fades in; it morphs with the main line after that.
- **hover**: A hairline and a dot glide to the nearest bucket (240ms, slight overshoot); the readout card glides beside them and flips to the other side near the edge. Its date morphs letter by letter, the figure rolls, and the note line lifts the old sentence out through a blur as the new one rises in.
- **brush**: With onZoom, pressing and dragging draws Time brush's band, snapped to bucket edges, with its first and last day and its length on a tag. Release calls onZoom; spans under one bucket are ignored. Escape cancels.
- **unfinished**: When the last bucket ends after now, its segment is drawn dashed (3 5) in the line's colour.

## What it handles

A single-metric chart looks like the easy one, until it has to compare with last period, zoom, say what a point was, and not jump every time a filter changes. That is usually three chart-library plugins and a custom tooltip.

- **Changes without jumping**: New numbers on the same days morph in place; a new range stretches the old line under the new one.
- **The period before**: Pass previous and a dashed line draws itself in, with its figure in the readout.
- **Unfinished buckets**: A last day or hour that ends after now is drawn dashed, so a dip at the end isn’t read as a drop.
- **A readout that reads**: Date, value, the period before and your own note line in one card that glides beside the pointer.
- **Drag to zoom**: Drag across the chart and onZoom gets the span, snapped to whole buckets.
- **Keyboard and table**: One tab stop with arrow keys, Home and End, each point announced, and every value in a hidden table.

## Replaces

a chart library, a tooltip plugin, a zoom or brush plugin, a comparison series, axis and scale maths

## Where it fits

- **Analytics overviews**: Visitors, signups or revenue by day, with the period before beside it.
- **Product metrics**: Daily active users or API calls, zoomed into the week something changed.
- **Billing and revenue**: MRR or payments by week, formatted as money on the scale and in the readout.
- **Monitoring**: Requests or latency by hour, where the current hour isn’t over yet.

## Notes

- The plot is one focusable group: ←/→ move between buckets, Home and End jump to the ends, Escape lets go. Each step is announced in a polite region (date, value, the period before, the note); the pointer path isn't announced.
- Every value is also in a visually hidden table with the period before as a column.
- The line is a monotone cubic, so it never overshoots a point: a day with zero visitors never dips below the axis.
- Its height steps down in narrow containers (a container query), the tick labels thin out to fit, and labels near an edge hang inward instead of running off the card. On touch, pressing reads a bucket; the brush keeps vertical page scroll.
- Reduced motion: no reveal, morph, stretch or glide; the line, the readout and the scale change in place.

License: MIT (https://hairlineui.com/license#components)
