# Morphing chart

> Bars, line and area as one set of marks: bars condense into beads, a thread is strung through them, the fill pours down. Drag the switch to scrub it.

Resting bars are stacks of 2px hairlines over a faint column of the same lines. Switching a chart between bars and a line usually swaps one drawing for another with a fade. Here the marks are the same objects throughout. Choose Line and each bar condenses up into a bead on its value; a thread is strung through the beads from the left and each one melts into it as the thread passes. Back to Bars, the thread is pulled out to the right, each bead swells as the tail leaves it and drips a stick to the axis that lands and spreads into its bar. Area pours the fill down from the line, and from Bars the bars widen until they touch, fade to a wash and melt from steps into the curve. Every morph is a function of time rather than a fire-and-forget animation, so the switch's thumb can be dragged and the chart follows it frame by frame, and changing your mind mid-morph runs it back from where it is. New values ease into place one after another while the scale rolls, and pointing at the line slides a bead along the curve to the point.

## Install

```bash
npx shadcn@latest add @hairline/morphing-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/morphing-chart
- Registry item (source): https://hairlineui.com/r/morphing-chart.json

## Usage

```tsx
import { MorphingChart } from "@/components/morphing-chart";

<MorphingChart
  title="Revenue"
  caption="January to December 2025"
  labels={["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]}
  values={[6100, 5800, 7400, 9200, 11800, 14900, 17600, 16900, 12100, 9400, 7300, 8900]}
  format={{ style: "currency", currency: "USD", maximumFractionDigits: 0 }}
/>
```

## Remember the reader's shape

The shape is controlled or not. Here a dashboard keeps it per chart in a cookie, so the page renders the reader's choice on the server and the switch never jumps after load. The values come from your database, grouped by month.

```tsx
// app/dashboard/revenue-card.tsx
import { cookies } from "next/headers";
import { db } from "@/lib/db";
import { RevenueCard } from "./revenue-card.client";

export async function RevenueCardServer() {
  const rows = await db.revenueByMonth({ year: 2025 }); // [{ month: "2025-01", total: 6100 }, …]
  const shape = (await cookies()).get("revenue-shape")?.value ?? "bars";
  return <RevenueCard rows={rows} initialShape={shape as "bars" | "line" | "area"} />;
}

// app/dashboard/revenue-card.client.tsx
"use client";
import * as React from "react";
import { MorphingChart, type ChartShape } from "@/components/morphing-chart";

export function RevenueCard({ rows, initialShape }: { rows: { month: string; total: number }[]; initialShape: ChartShape }) {
  const [shape, setShape] = React.useState(initialShape);
  const months = rows.map((r) => new Date(r.month + "-01T12:00:00"));
  return (
    <MorphingChart
      title="Revenue"
      caption="January to December 2025"
      labels={months.map((d) => d.toLocaleDateString("en-GB", { month: "short" }))}
      titles={months.map((d) => d.toLocaleDateString("en-GB", { month: "long", year: "numeric" }))}
      values={rows.map((r) => r.total)}
      format={{ style: "currency", currency: "USD", maximumFractionDigits: 0 }}
      shape={shape}
      onShapeChange={(next) => {
        setShape(next);
        document.cookie = `revenue-shape=${next}; path=/; max-age=31536000`;
      }}
    />
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `labels` | `string[]` | – | Along the bottom, one per value. They thin out from the latest when there isn't room. |
| `values` | `number[]` | – | One per label. New values ease into place; negative values are drawn at zero. |
| `titles` | `string[]` | – | Longer names for the readout, e.g. "October 2025". Defaults to labels. |
| `shape / defaultShape` | `"bars" \| "line" \| "area"` | `"bars"` | Controlled or not. |
| `onShapeChange` | `(shape) => void` | – | Called when the reader picks a shape, or lets go of the thumb on one. |
| `title` | `string` | `"Revenue"` | Above the figure. It morphs when it changes. |
| `caption` | `string` | – | Under the figure, e.g. "Last 12 months". The point's name takes its place while one is read. |
| `format` | `Intl.NumberFormatOptions` | – | How the figure and the readout read. The scale uses the same options in compact notation. |
| `locales` | `string \| string[]` | – | For number formatting. |

## States

- **arrive**: The first time the card is on screen every mark rises from the axis (650ms, up to 40ms apart) and the total and the scale roll up from zero.
- **bars → line**: Each bar bulges a touch, pinches to a stick and retracts up into a 7px bead on its value, which hops 2px as it closes (460ms, staggered left to right). A thread then draws from the left through the beads (an exact cut of the curve, not a dash), and each bead shrinks to the thread's thickness under it as the tip passes. About 1.2s.
- **line → bars**: The thread's tail is pulled to the right. Each bead swells back just before the tail leaves it, then lifts, drips a stick to the axis and spreads a little past the bar's width as it lands before settling (540ms).
- **line ↔ area**: The fill pours down from the line to the axis, left to right (760ms), and drains back up into it on the way back (620ms). The wash fades from 22% at the top to 3% at the axis.
- **bars ↔ area**: The bars widen until they touch and their hairlines close into a solid fill that fades to the wash; the steps they make melt into the curve while the line draws along the top. The reverse sets the curve into steps and parts them into bars.
- **scrub**: Drag the thumb of the switch: the morph between neighbouring shapes is held at the frame under your finger. Let go and it runs on to the nearer shape, or the one you flung it toward; the thumb lands with a slight overshoot.
- **take it back**: Choose the shape you came from while a morph is running and it runs backward from that frame. A third shape waits for the morph to land, then goes on.
- **data**: New values ease to their heights one after another (650ms) while the scale's labels roll; on the line and the area the curve reshapes as they go.
- **hover**: Light falls off from the bar you're on over its neighbours, so reading along the year is a hand passing over it. On the line and the area a ringed bead slides along the curve to the point (it rides the line, never cutting across it) with a hairline under it. The figure rolls to the point and its name morphs into the caption.

## What it handles

Switching a chart between bars and a line usually swaps one drawing for another with a fade. Here the marks are the same objects throughout, so people see how the shapes relate.

- **One set of marks, three shapes**: Bars condense into beads, a thread is strung through them, and the fill pours down for the area.
- **Scrub the switch**: Drag the switch’s thumb and the chart follows frame by frame. Let go and it runs on to the nearer shape.
- **Change your mind mid-way**: Choose the shape you came from while it is moving and it runs back from where it is.
- **New values ease in**: Heights ease to new values one after another while the scale’s labels roll.
- **A readout on hover**: A bead rides the curve to the point, the figure rolls and its name morphs into the caption.
- **Remember the reader’s shape**: Control the shape and save it per chart. Arrow keys read each point, and every value is also in a hidden table.

## Replaces

a chart library, a chart type switch, a fade between charts, a hover readout, axis scale labels

## Where it fits

- **Analytics dashboards**: Let people switch a metric between bars, a line and an area.
- **Revenue and growth reports**: Show the same numbers in the shape that suits the question.
- **Investor and customer updates**: A chart that is worth watching when the shape changes.
- **Habit and finance trackers**: Spending, steps or sleep over months, with a shape to suit.

## Notes

- Grey in a new shadcn project? Its default theme sets --chart-1 to --chart-5 to greys. Set five colours, light and dark, as in Theming › Chart colours (/ui/theming#charts).
- The shape switch is a radio group (arrow keys move and choose). Dragging the thumb is a pointer extra on top of it; it only starts from the selected shape, and a short press is still a click.
- The plot is one tab stop: arrow keys, Home and End read each point, Escape lets go, and the reading is announced. Every value is also in a visually hidden table.
- One frame loop writes path data and two transforms straight to the DOM and sleeps when nothing moves; nothing re-renders through React during a morph, a scrub or a slide of the bead.
- The line is a monotone cubic, so it never overshoots a value between two points, and the bead and the area's edge are evaluated on the same curve.
- Colour comes from the theme's --chart-1 (falling back to --primary). Reduced motion changes shape, data and the bead in place, and turns the thumb's drag off.

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