# Charts (/ui/components/react/charts)

Charts in Appica UI are recipes. [Recharts](https://recharts.github.io) draws the chart, and 1 file you copy into your project, the chart layer, gives it the library's colors, tooltip, legend and motion. You still write `AreaChart`, `Bar` and `XAxis` yourself, so every Recharts prop still works.

This page sets up the chart layer and explains its parts. Each chart type has its own page of examples to copy: [Area](/ui/components/react/area-chart), [Line](/ui/components/react/line-chart), [Bar](/ui/components/react/bar-chart), [Pie](/ui/components/react/pie-chart), [Radial](/ui/components/react/radial-chart), [Radar](/ui/components/react/radar-chart), [Scatter](/ui/components/react/scatter-chart), [Funnel](/ui/components/react/funnel-chart), [Sankey](/ui/components/react/sankey-chart), [Treemap](/ui/components/react/treemap) and [Heatmap](/ui/components/react/heatmap). A small trend in a tile or a table row is a [`Sparkline`](/ui/components/react/sparkline) and a quota is a [`Meter`](/ui/components/react/meter). Neither needs Recharts.

## Installation [#installation]

Recharts 3.11 or later is the only extra dependency. It needs `react-is` at the same version as `react`, so install both:

```bash
pnpm add recharts react-is   # or: npm install recharts react-is / yarn add recharts react-is / bun add recharts react-is
```

Then save [the chart layer](#the-chart-layer) as `components/chart.tsx`. Every example imports it as `@/components/chart`.

## The chart layer [#the-chart-layer]

The layer is this 1 file. It imports `recharts` and Appica UI, and nothing else from your project.

`components/chart.tsx`:

```tsx
'use client'

/*
 * The chart layer: the 1 file that fits Recharts 3 to Appica UI. `Chart` themes and sizes the
 * Recharts chart inside it, `ChartTooltip` and `ChartLegend` stand in for Recharts' own, and
 * `useChartMotion` times every series. Save it as `components/chart.tsx`.
 */

import * as React from 'react'
import {
  RechartsThemeProvider,
  type AnimationInterpolateFn,
  type BarRectangleItem,
  type CartesianLayout,
  type DefaultLegendContentProps,
  type RechartsTheme,
  type TooltipContentProps,
} from 'recharts'
import { useDirection } from '@appica/ui-react/hooks/use-direction'
import { useReducedMotion } from '@appica/ui-react/hooks/use-reduced-motion'

/**
 * The series colors in their fixed order: the library's `--chart-1` to `--chart-5` tokens. Pass one
 * as a `stroke` or `fill`, so a series keeps its color when another one is hidden. The order keeps
 * neighbors apart for color-blind readers: take the slots in order, never skip or cycle them, and
 * stop at 5 series. The second variable is the stand-in `Chart` sets for a library version without the tokens.
 */
export const chartColors = [
  'var(--chart-1, var(--chart-fallback-1))',
  'var(--chart-2, var(--chart-fallback-2))',
  'var(--chart-3, var(--chart-fallback-3))',
  'var(--chart-4, var(--chart-fallback-4))',
  'var(--chart-5, var(--chart-fallback-5))',
] as const

/** The durations, in milliseconds, and the curves of every series. `useChartMotion` hands them to Recharts. */
export const chartMotion = {
  /** The wipe of a line or an area, and the sweep of a donut or a radial bar, once on mount. */
  reveal: 600,
  /** 1 bar growing from the baseline on mount. */
  grow: 450,
  /** The delay from 1 bar to the next on mount. The gaps shrink along the row. */
  stagger: 30,
  /** The cap on the delay of the last bar, however many there are. */
  staggerMax: 300,
  /** A series moving to new data. */
  morph: 300,
  /** The curve of a reveal. */
  easeOut: 'cubic-bezier(0.23,1,0.32,1)',
  /** The curve of a mark that moves while it stays on screen. */
  easeInOut: 'cubic-bezier(0.77,0,0.175,1)',
} as const

/** The sizes of the marks. Recharts takes them as numbers, so they are px and cannot follow the radius scale. */
export const chartMarks = {
  /** The outer corners of a bar. */
  barRadius: 4,
  /** The `activeDot` of a `Line` or an `Area`: Sparkline's indicator, a dot with a ring in the surface color. */
  activeDot: { r: 5, stroke: 'var(--background)', strokeWidth: 2 },
} as const

// Recharts writes these values into the DOM as they are, so `.dark` switches a chart with no render.
const theme: RechartsTheme = {
  typography: { fontSize: '0.75rem', color: 'var(--foreground-muted)' },
  graphicalItems: chartColors.map((color) => ({ fill: color, stroke: color, strokeWidth: 2 })),
  grid: { stroke: 'var(--border)', fill: 'none' },
  // Tick labels take the axis stroke, so it is a text token, and recipes draw no axis or tick lines.
  axis: { stroke: 'var(--foreground-muted)' },
  reference: { stroke: 'var(--foreground-subtle)', fill: 'var(--background-muted)' },
  cursor: { stroke: 'var(--border-strong)', fill: 'var(--background-muted)' },
  barBackground: { fill: 'var(--background-muted)' },
  pageBackground: 'var(--background)',
  chart: { width: '100%', height: '100%' },
}

// What Recharts draws itself is styled from here. Every transition is Tailwind's default 150 ms, as Sparkline's
// indicator, and the ones that follow the pointer wait for `:hover`, so an arrow key moves the tooltip at once.
const frame = [
  // Stand-ins for the `--chart-*` tokens, with the same values: `-strong` in light mode, `-emphasis` in dark mode.
  '[--chart-fallback-1:var(--secondary-strong)] [--chart-fallback-2:var(--success-strong)] [--chart-fallback-3:var(--warning-strong)]',
  '[--chart-fallback-4:var(--info-strong)] [--chart-fallback-5:var(--error-strong)]',
  'dark:[--chart-fallback-1:var(--secondary-emphasis)] dark:[--chart-fallback-2:var(--success-emphasis)]',
  'dark:[--chart-fallback-3:var(--warning-emphasis)] dark:[--chart-fallback-4:var(--info-emphasis)]',
  'dark:[--chart-fallback-5:var(--error-emphasis)]',
  // Zero specificity, so a size or a radius class from outside wins without tailwind-merge.
  '[:where(&)]:h-64 [:where(&)]:w-full [:where(&)]:rounded-xs',
  // The focus ring of the chart, drawn on the frame: a radius on the SVG itself would clip its corners.
  'outline-ring has-[.recharts-surface:focus-visible]:outline-3 [&_.recharts-surface]:outline-none',
  // The tooltip is placed with no transition, and eases after the pointer once its own enter is over.
  '[&_.recharts-tooltip-wrapper]:z-10 [&_.recharts-tooltip-wrapper]:transition-none!',
  'motion-safe:[&:hover_.recharts-tooltip-wrapper:has([data-following])]:transition-[transform]!',
  // The cursor and the active dot fade in, then slide to the next point. The cursor slides only where the browser
  // can ease the `d` of a path. Safari cannot, so the dot steps there too and never leaves its guide line.
  '[&_.recharts-rectangle.recharts-tooltip-cursor]:stroke-none',
  'motion-safe:[&:hover_.recharts-tooltip-cursor]:transition-[opacity,d] [&_.recharts-tooltip-cursor]:starting:opacity-0',
  '[&_.recharts-active-dot]:origin-center [&_.recharts-active-dot]:[transform-box:fill-box]',
  'motion-safe:[&:hover_.recharts-active-dot]:transition-[opacity,scale]',
  '[&_.recharts-active-dot]:starting:scale-50 [&_.recharts-active-dot]:starting:opacity-0',
  'motion-safe:supports-[d:none]:[&:hover_.recharts-active-dot_circle]:transition-[cx,cy]',
  // Recharts draws a label that sits on a fill in the page color. On a series color the families' own text token reads better.
  "[&_.recharts-label[fill='var(--background)']]:fill-secondary-foreground!",
  // Pointing at 1 series dims the others.
  'motion-safe:[&_:is(.recharts-bar,.recharts-area,.recharts-line,.recharts-radar,.recharts-scatter,.recharts-pie-sector)]:transition-opacity',
  '[@media(hover:hover)]:[&:has(:is(.recharts-bar,.recharts-area,.recharts-line,.recharts-radar,.recharts-scatter,.recharts-pie-sector):hover)_:is(.recharts-bar,.recharts-area,.recharts-line,.recharts-radar,.recharts-scatter,.recharts-pie-sector):not(:hover)]:opacity-30',
].join(' ')

/**
 * The frame of a chart. It supplies the theme, the size and the direction, so the Recharts chart
 * inside takes `responsive` and no width, height or `ResponsiveContainer`.
 */
export function Chart({ className, ...props }: React.ComponentProps<'div'>) {
  return (
    <RechartsThemeProvider value={theme}>
      {/* A chart is not mirrored in right-to-left, where SVG text anchors flip and push every tick into the plot. */}
      <div data-slot="chart" dir="ltr" className={className ? `${frame} ${className}` : frame} {...props} />
    </RechartsThemeProvider>
  )
}

const easeOutQuint = (t: number) => 1 - (1 - t) ** 5

// Recharts grows every bar at once. This gives each one its own delay, with gaps that shrink along the row.
const staggerBars: AnimationInterpolateFn<BarRectangleItem, CartesianLayout> = (items, elapsed, layout) => {
  if (items == null) return []
  const last = Math.max(items.length - 1, 1)
  const spread = Math.min(chartMotion.stagger * last, chartMotion.staggerMax)
  const total = chartMotion.grow + chartMotion.staggerMax
  return items.flatMap((item, index) => {
    if (item.status === 'removed') return []
    const { next } = item
    if (elapsed >= 1 || next.stackedBarStart == null) return [next]
    const delay = spread * (1 - (1 - index / last) ** 2)
    const t = easeOutQuint(Math.min(Math.max((elapsed * total - delay) / chartMotion.grow, 0), 1))
    const from = next.stackedBarStart
    return layout === 'horizontal'
      ? [{ ...next, y: from + (next.y - from) * t, height: next.height * t }]
      : [{ ...next, x: from + (next.x - from) * t, width: next.width * t }]
  })
}

/**
 * The animation props of a series: a reveal on mount, a morph when the data changes, and nothing
 * under reduced motion. Spread `bars` on a `Bar`, and `series` on anything else that animates.
 */
export function useChartMotion() {
  const reduced = useReducedMotion()
  const [revealed, setRevealed] = React.useState(false)
  return React.useMemo(() => {
    const base = {
      isAnimationActive: reduced ? false : ('auto' as const),
      // `Pie` and `Funnel` wait 400 ms by default.
      animationBegin: 0,
      onAnimationEnd: () => setRevealed(true),
    }
    const morph = { ...base, animationDuration: chartMotion.morph, animationEasing: chartMotion.easeInOut }
    if (revealed) return { series: morph, bars: morph }
    return {
      series: { ...base, animationDuration: chartMotion.reveal, animationEasing: chartMotion.easeOut },
      bars: {
        ...base,
        animationDuration: chartMotion.grow + chartMotion.staggerMax,
        animationEasing: 'linear' as const,
        animationInterpolateFn: staggerBars,
      },
    }
  }, [reduced, revealed])
}

type TooltipVariant = 'solid' | 'glass' | 'inverse'
type TooltipIndicator = 'dot' | 'line' | 'dashed'

// To keep 1 look, delete the other 2 entries.
const tooltipVariants: Record<TooltipVariant, string> = {
  solid: 'border-border-overlay bg-background text-foreground-intense rounded-xs border px-3 py-2 shadow-md',
  glass:
    'border-foreground/10 bg-background/70 text-foreground-intense rounded-xs border px-3 py-2 shadow-md backdrop-blur-md',
  inverse:
    'bg-background-inverse text-foreground-inverse rounded-xs px-3 py-2 **:data-[slot=chart-tooltip-name]:text-foreground-subtle',
}

const tooltipIndicators: Record<TooltipIndicator, string> = {
  dot: 'rounded-4xs size-2.5 bg-(--series)',
  line: 'w-1 self-stretch rounded-full bg-(--series)',
  dashed: 'self-stretch border-s-2 border-dashed border-(--series)',
}

// The enter and exit of the library's `TooltipContent`: `starting:` and `not-data-open:` stand in for Base UI's
// `data-starting-style` and `data-ending-style`, and the origin is the corner nearest the pointer.
const tooltipMotion = [
  'origin-top-left in-[.recharts-tooltip-wrapper-left]:origin-top-right in-[.recharts-tooltip-wrapper-top]:origin-bottom-left',
  'in-[.recharts-tooltip-wrapper-left.recharts-tooltip-wrapper-top]:origin-bottom-right',
  'motion-safe:ease-spring motion-safe:transition-[opacity,scale,display] motion-safe:transition-discrete motion-safe:duration-200',
  'starting:motion-safe:scale-90 starting:motion-safe:opacity-0',
  'not-data-open:hidden not-data-open:motion-safe:scale-95 not-data-open:motion-safe:opacity-0 not-data-open:motion-safe:duration-100 not-data-open:motion-safe:ease-out',
].join(' ')

interface ChartTooltipProps extends Partial<TooltipContentProps> {
  /**
   * The surface: `solid` is a bordered card, `glass` a translucent, blurred one, `inverse` the pill of `Tooltip`.
   * @default 'solid'
   */
  variant?: TooltipVariant
  /**
   * The shape of the swatch beside each series name.
   * @default 'dot'
   */
  indicator?: TooltipIndicator
  /** Hide the heading, the category under the pointer. */
  hideLabel?: boolean
  /** Hide the swatches. */
  hideIndicator?: boolean
  /** Formats each value. Use `Intl`, so money, percent and counts read as they do in the rest of the app. */
  formatValue?: (value: number, name: string) => string
  /** Formats the heading. */
  formatLabel?: (label: string | number) => string
}

/**
 * The content of a Recharts `Tooltip`: `<Tooltip content={<ChartTooltip />} />`. Recharts supplies
 * `active`, `payload` and `label`.
 */
export function ChartTooltip({
  active,
  payload,
  label,
  variant = 'solid',
  indicator = 'dot',
  hideLabel,
  hideIndicator,
  formatValue,
  formatLabel,
}: ChartTooltipProps) {
  const direction = useDirection()
  const open = Boolean(active && payload?.length)

  // Recharts empties the payload the moment the pointer leaves, so the last rows stay for the exit.
  const [last, setLast] = React.useState({ label, payload })
  if (open && (last.payload !== payload || last.label !== label)) setLast({ label, payload })
  const shown = open ? { label, payload } : last

  // Set once the enter is over, so the first placement never travels. See the frame classes of `Chart`.
  const [following, setFollowing] = React.useState(false)
  if (!open && following) setFollowing(false)

  // A range, such as a forecast band, arrives as a pair.
  const format = (value: unknown, name: string): string =>
    Array.isArray(value)
      ? value.map((part) => format(part, name)).join(' - ')
      : typeof value === 'number' && formatValue
        ? formatValue(value, name)
        : String(value)

  return (
    <div
      data-slot="chart-tooltip"
      data-open={open ? '' : undefined}
      data-following={following ? '' : undefined}
      dir={direction}
      onTransitionEnd={(event) => open && event.target === event.currentTarget && setFollowing(true)}
      // `visible` keeps the exit on screen: Recharts hides its wrapper as soon as the tooltip closes.
      className={`visible grid w-max min-w-32 gap-1.5 text-xs ${tooltipMotion} ${tooltipVariants[variant]}`}
    >
      {!hideLabel && shown.label != null && <p className="font-medium">{formatLabel?.(shown.label) ?? shown.label}</p>}
      <ul className="grid gap-1">
        {shown.payload?.map((item, index) => (
          // A scatter point lists several values of 1 series, so the series id alone is not a key.
          <li key={`${item.graphicalItemId}-${index}`} className="flex items-center gap-2">
            {!hideIndicator && (
              <span
                className={`shrink-0 ${tooltipIndicators[indicator]}`}
                style={{ '--series': item.color } as React.CSSProperties}
              />
            )}
            <span data-slot="chart-tooltip-name" className="text-foreground-muted">
              {item.name}
            </span>
            <span className="ms-auto ps-4 font-medium tabular-nums">{format(item.value, String(item.name))}</span>
          </li>
        ))}
      </ul>
    </div>
  )
}

/**
 * The content of a Recharts `Legend`: `<Legend content={<ChartLegend />} />`. With an `onClick` on
 * the `Legend`, every item is a toggle button, pressed while its series shows.
 */
export function ChartLegend({ payload, onClick }: DefaultLegendContentProps) {
  const direction = useDirection()
  return (
    <ul
      dir={direction}
      // Recharts opens the tooltip on the first point when the chart takes focus, and a legend button is inside it.
      onFocus={(event) => event.stopPropagation()}
      className="text-foreground flex flex-wrap items-center justify-center gap-x-4 gap-y-1 pt-3 text-xs"
    >
      {payload?.map((entry, index) => {
        const swatch = (
          <span
            className="rounded-4xs size-2.5 shrink-0 border-2 border-(--series) bg-(--series) group-aria-[pressed=false]:bg-transparent motion-safe:transition-colors"
            style={{ '--series': entry.color } as React.CSSProperties}
          />
        )
        return (
          <li key={`${entry.value}-${index}`} className="*:flex *:items-center *:gap-1.5">
            {onClick ? (
              <button
                type="button"
                aria-pressed={!entry.inactive}
                onClick={(event) => onClick(entry, index, event)}
                className="group outline-ring aria-[pressed=false]:text-foreground-subtle cursor-pointer rounded-xs motion-safe:transition-[color,scale] motion-safe:active:scale-97"
              >
                {swatch}
                {entry.value}
              </button>
            ) : (
              <span>
                {swatch}
                {entry.value}
              </span>
            )}
          </li>
        )
      })}
    </ul>
  )
}
```

A chart built with it looks like this:

```tsx
'use client'

import { CartesianGrid, Line, LineChart, Tooltip, XAxis, YAxis } from 'recharts'
import { Chart, ChartTooltip, chartColors, chartMarks, useChartMotion } from '@/components/chart'

export function OrdersChart({ data }: { data: { day: string; orders: number }[] }) {
  const motion = useChartMotion()

  return (
    <Chart>
      <LineChart responsive data={data} aria-label="Orders per day">
        <CartesianGrid vertical={false} />
        <XAxis dataKey="day" tickLine={false} axisLine={false} minTickGap={32} interval="equidistantPreserveEnd" />
        <YAxis tickLine={false} axisLine={false} width="auto" niceTicks="snap125" />
        <Tooltip content={<ChartTooltip />} />
        <Line
          name="Orders"
          dataKey="orders"
          stroke={chartColors[0]}
          dot={false}
          activeDot={chartMarks.activeDot}
          {...motion.series}
        />
      </LineChart>
    </Chart>
  )
}
```

### Chart [#chart]

The frame around a Recharts chart. It provides the theme (colors, type, grid, cursor), sizes the chart to itself, and keeps the plot left-to-right. The chart inside takes `responsive`, and no `width`, `height` or `ResponsiveContainer`. Renders a `<div>` and forwards its remaining props to it.

| Prop        | Type     | Default | Description                                                                         |
| ----------- | -------- | ------- | ----------------------------------------------------------------------------------- |
| `className` | `string` | -       | Classes on the frame. A height or a width class replaces the default `h-64 w-full`. |

### ChartTooltip [#charttooltip]

The content of a Recharts `Tooltip`. Pass it as an element, with its own props on it, and Recharts supplies the active point:

```tsx
<Tooltip content={<ChartTooltip variant="glass" formatValue={(value) => money.format(value)} />} />
```

| Prop            | Type         | Default   | Description                                   |
| --------------- | --------------------------------------------------- | --------- | ------------------------------------------------------------------------------------ |
| `variant`       | `'solid' \| 'glass' \| 'inverse'`                   | `'solid'` | The surface. See [Variants](#variants).                                              |
| `indicator`     | `'dot' \| 'line' \| 'dashed'`                       | `'dot'`   | The shape of the swatch beside each series name.                                     |
| `hideLabel`     | `boolean`                                           | `false`   | Hide the heading, the category under the pointer.                                    |
| `hideIndicator` | `boolean`                                           | `false`   | Hide the swatches.                                                                   |
| `formatValue`   | `(value: number, name: string) => string` | -         | Formats each value. Use `Intl`, so money, percent and counts read as in the rest of the app. |
| `formatLabel`   | `(label: string \| number) => string` | -         | Formats the heading.                                                                 |

### ChartLegend [#chartlegend]

The content of a Recharts `Legend`. It takes no props of its own:

```tsx
<Legend itemSorter={null} content={<ChartLegend />} />
```

`itemSorter={null}` keeps the items in the order of the series, where Recharts would sort them by name. Give the `Legend` an `onClick` and every item becomes a toggle button, as in the [interactive line chart](/ui/components/react/line-chart#interactive).

### useChartMotion [#usechartmotion]

A hook that returns the animation props of a series. They reveal the series once on mount, morph it when the data changes, and turn animation off under reduced motion.

| Key      | Spread on                                 | Description                                                    |
| -------- | ----------------------------------------- | -------------------------------------------------------------- |
| `series` | `Line`, `Area`, `Pie`, `RadialBar`, `Radar`, `Scatter`, `Funnel`, `Treemap` | A wipe or a sweep on mount, then a morph. |
| `bars`   | `Bar`                                     | Bars growing from the baseline one after another, then a morph. |

### Constants [#constants]

| Name          | Description                                                                                                      |
| ------------- | ---------------------------------------------------------------------------------------------------------------- |
| `chartColors` | The 5 series colors in their fixed order, as `var()` strings. See [Colors](#colors). |
| `chartMarks`  | Mark sizes that Recharts takes as numbers: `barRadius` for a bar's outer corners, and `activeDot` for the hovered point of a line or an area. |
| `chartMotion` | The durations and curves that `useChartMotion` hands to Recharts. See [Motion](#motion).                         |

## Examples [#examples]

### In a card [#in-a-card]

A chart usually sits in a [`Card`](/ui/components/react/card), under a value and a period control. The card has the heading, so the chart needs none. Pick another period: the area morphs to the new data and the reveal does not play again.

```tsx
'use client'

import { useId, useState } from 'react'
import { Area, AreaChart, CartesianGrid, Tooltip, XAxis, YAxis } from 'recharts'
import { Badge } from '@appica/ui-react/badge'
import { Card, CardDescription, CardHeader, CardTitle } from '@appica/ui-react/card'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@appica/ui-react/select'
import { Chart, ChartTooltip, chartColors, chartMarks, useChartMotion } from '@/components/chart'

const periods = {
  week: {
    label: 'Last 7 days',
    change: 0.084,
    data: [
      { label: 'Mon', revenue: 4120 },
      { label: 'Tue', revenue: 4680 },
      { label: 'Wed', revenue: 4390 },
      { label: 'Thu', revenue: 5240 },
      { label: 'Fri', revenue: 6130 },
      { label: 'Sat', revenue: 7460 },
      { label: 'Sun', revenue: 6870 },
    ],
  },
  month: {
    label: 'Last 4 weeks',
    change: 0.127,
    data: [
      { label: 'Week 1', revenue: 31200 },
      { label: 'Week 2', revenue: 34800 },
      { label: 'Week 3', revenue: 33100 },
      { label: 'Week 4', revenue: 38900 },
    ],
  },
  year: {
    label: 'Last 12 months',
    change: -0.031,
    data: [
      { label: 'Jan', revenue: 148000 },
      { label: 'Feb', revenue: 139000 },
      { label: 'Mar', revenue: 156000 },
      { label: 'Apr', revenue: 162000 },
      { label: 'May', revenue: 171000 },
      { label: 'Jun', revenue: 158000 },
      { label: 'Jul', revenue: 149000 },
      { label: 'Aug', revenue: 143000 },
      { label: 'Sep', revenue: 151000 },
      { label: 'Oct', revenue: 146000 },
      { label: 'Nov', revenue: 138000 },
      { label: 'Dec', revenue: 144000 },
    ],
  },
}

type Period = keyof typeof periods

const items = { week: periods.week.label, month: periods.month.label, year: periods.year.label }

const compact = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', notation: 'compact' })
const money = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 })
const percent = new Intl.NumberFormat('en-US', {
  style: 'percent',
  maximumFractionDigits: 1,
  signDisplay: 'exceptZero',
})

export default function ChartsInACard() {
  const motion = useChartMotion()
  const fill = useId()
  const [period, setPeriod] = useState<Period>('week')
  const { data, change } = periods[period]
  const total = data.reduce((sum, row) => sum + row.revenue, 0)

  return (
    <Card frame="solid" className="w-full max-w-lg">
      <CardHeader>
        <div className="flex flex-wrap items-start justify-between gap-x-4 gap-y-3">
          <div className="flex flex-col gap-1.5">
            <CardDescription>Revenue</CardDescription>
            <CardTitle className="flex items-center gap-2 text-2xl tabular-nums">
              {money.format(total)}
              <Badge variant={change < 0 ? 'error' : 'success'}>{percent.format(change)}</Badge>
            </CardTitle>
          </div>
          <Select
            size="sm"
            variant="soft"
            items={items}
            value={period}
            onValueChange={(value) => setPeriod(value as Period)}
          >
            <SelectTrigger aria-label="Period" className="w-36">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {Object.entries(items).map(([value, label]) => (
                <SelectItem key={value} value={value}>
                  {label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <Chart className="mt-4 h-48">
          <AreaChart responsive data={data} aria-label={`Revenue, ${periods[period].label.toLowerCase()}`}>
            <defs>
              <linearGradient id={fill} x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="var(--secondary-soft)" />
                <stop offset="100%" stopColor="var(--secondary-soft)" stopOpacity={0} />
              </linearGradient>
            </defs>
            <CartesianGrid vertical={false} />
            <XAxis
              dataKey="label"
              tickLine={false}
              axisLine={false}
              minTickGap={24}
              interval="equidistantPreserveEnd"
            />
            <YAxis
              tickFormatter={(value) => compact.format(value)}
              tickLine={false}
              axisLine={false}
              width="auto"
              niceTicks="snap125"
            />
            <Tooltip content={<ChartTooltip formatValue={(value) => money.format(value)} />} />
            <Area
              name="Revenue"
              dataKey="revenue"
              type="monotone"
              stroke={chartColors[0]}
              fill={`url(#${fill})`}
              activeDot={chartMarks.activeDot}
              {...motion.series}
            />
          </AreaChart>
        </Chart>
      </CardHeader>
    </Card>
  )
}
```

### Loading and empty states [#loading-and-empty-states]

A chart keeps its height in every state, so the layout around it doesn't jump. While the data loads, show a [`Skeleton`](/ui/components/react/skeleton) of the chart's height. With no rows, keep the frame and say there is no data.

```tsx
'use client'

import { Skeleton } from '@appica/ui-react/skeleton'
import { Chart } from '@/components/chart'

export default function ChartsStates() {
  return (
    <div className="grid w-full max-w-2xl gap-8 sm:grid-cols-2">
      <figure>
        <Skeleton className="h-56 w-full rounded-xl" />
        <figcaption className="text-foreground-muted mt-2 text-center text-xs">Loading</figcaption>
      </figure>
      <figure>
        <Chart className="text-foreground-muted flex h-56 items-center justify-center rounded-xl border border-dashed text-sm">
          No data for this date range
        </Chart>
        <figcaption className="text-foreground-muted mt-2 text-center text-xs">Empty</figcaption>
      </figure>
    </div>
  )
}
```

## Colors [#colors]

A series takes its color from `chartColors`: the library's `--chart-1` to `--chart-5` tokens, 5 accent families in a fixed order. Each one is the `-strong` step of its family in light mode and the fuller `-emphasis` step in dark mode. They point at the family tokens, so a theme that recolors `secondary` recolors series 1 with it. Recharts writes the `var()` strings into the DOM as they are, and `.dark` switches a chart with no render.

```tsx
'use client'

import { Bar, BarChart, BarStack, CartesianGrid, Legend, Tooltip, XAxis, YAxis } from 'recharts'
import { Chart, ChartLegend, ChartTooltip, chartColors, chartMarks, useChartMotion } from '@/components/chart'

const data = [
  { quarter: 'Q1', search: 4200, social: 3100, email: 2400, referral: 1800, paid: 1200 },
  { quarter: 'Q2', search: 4800, social: 3600, email: 2700, referral: 2100, paid: 1500 },
  { quarter: 'Q3', search: 5300, social: 4400, email: 2900, referral: 2300, paid: 1400 },
  { quarter: 'Q4', search: 6100, social: 5200, email: 3300, referral: 2600, paid: 1900 },
]

const slots = [
  { key: 'search', name: 'Search', family: 'secondary' },
  { key: 'social', name: 'Social', family: 'success' },
  { key: 'email', name: 'Email', family: 'warning' },
  { key: 'referral', name: 'Referral', family: 'info' },
  { key: 'paid', name: 'Paid', family: 'error' },
]

const compact = new Intl.NumberFormat('en-US', { notation: 'compact' })
const count = new Intl.NumberFormat('en-US')

export default function ChartsColors() {
  const motion = useChartMotion()

  return (
    <div className="flex w-full max-w-2xl flex-col gap-8">
      <Chart className="h-72">
        <BarChart responsive data={data} aria-label="Visits by channel, stacked by quarter, in all 5 series colors">
          <CartesianGrid vertical={false} />
          <XAxis dataKey="quarter" tickLine={false} axisLine={false} />
          <YAxis
            tickFormatter={(value) => compact.format(value)}
            tickLine={false}
            axisLine={false}
            width="auto"
            niceTicks="snap125"
          />
          <Tooltip content={<ChartTooltip formatValue={(value) => count.format(value)} />} />
          <Legend itemSorter={null} content={<ChartLegend />} />
          <BarStack radius={[chartMarks.barRadius, chartMarks.barRadius, 0, 0]}>
            {slots.map((slot, index) => (
              <Bar
                key={slot.key}
                name={slot.name}
                dataKey={slot.key}
                fill={chartColors[index] ?? 'var(--foreground-subtle)'}
                stroke="var(--background)"
                maxBarSize={56}
                {...motion.bars}
              />
            ))}
          </BarStack>
        </BarChart>
      </Chart>

      <table className="w-full text-xs">
        <thead>
          <tr className="text-foreground-muted *:pb-2 *:font-medium">
            <th className="text-start">Slot</th>
            <th className="text-start">Family</th>
            <th>-strong</th>
            <th>-emphasis</th>
            <th>-soft</th>
            <th>-subtle</th>
          </tr>
        </thead>
        <tbody>
          {slots.map((slot, index) => (
            <tr key={slot.key} className="*:py-1">
              <td className="text-foreground-muted tabular-nums">{index + 1}</td>
              <td className="font-mono">{slot.family}</td>
              {['strong', 'emphasis', 'soft', 'subtle'].map((step) => (
                <td key={step}>
                  <span
                    className="rounded-3xs mx-auto block h-5 w-full max-w-16"
                    style={{ backgroundColor: `var(--${slot.family}-${step})` }}
                  />
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}
```

- The order is fixed. It keeps neighboring colors apart for color-blind readers, so take the slots in order and never skip or cycle them. Orange never ends up beside red this way, nor blue beside sky: those are the 2 pairs that are hardest to tell apart.
- Use 5 series at most. Group a sixth as "Other" in `var(--foreground-subtle)`. On a scatter chart, where any 2 points can touch, use the first 3 slots only.
- A single series takes slot 1. A comparison period is the same color, dashed, at 60% stroke opacity. A neutral series, such as a target or a baseline, is `var(--foreground-subtle)`.
- When the data is a status, meaning comes before order: succeeded is the success color (`chartColors[1]`), pending the warning color (`chartColors[2]`) and failed the error color (`chartColors[4]`).
- Tints are the translucent steps of the same family, and they are the same in both modes: `-soft` (20%) for the top of an area fill, a band or a bubble, and `-subtle` (10%) for a bar's track or a hover wash. An area fill is a vertical gradient from `-soft` to transparent.
- Text never takes a series color. Ticks, legend labels and values use the foreground tokens, and the swatch beside them carries the identity. None of the 5 light-mode colors reaches 3:1 contrast on white, so every chart with 2 or more series has a legend, and every chart has a tooltip.

Always pass the color to the series as `stroke` or `fill`. Without one, the theme assigns colors by the sorted names of the `dataKey`s, not by the order you wrote the series in.

Where the library defines the tokens, the same colors work outside a chart as `var(--chart-1)` or `bg-chart-1`. On a version of the library without them, `Chart` supplies the same values inside its frame.

## Tooltip [#tooltip]

### Variants [#variants]

`variant` picks the surface. `solid` is Sparkline's tooltip, a bordered card with a shadow. `glass` is the same card made translucent, with a backdrop blur and a hairline border, in the surface color of the current mode. `inverse` is the surface of the library's [`Tooltip`](/ui/components/react/tooltip). All 3 live in 1 map of classes in the chart layer. If you only want 1 look, delete the other 2 entries.

```tsx
'use client'

import { Bar, BarChart, Tooltip, XAxis } from 'recharts'
import { Chart, ChartTooltip, chartColors, chartMarks, useChartMotion } from '@/components/chart'

const data = [
  { day: 'Mon', visits: 3200 },
  { day: 'Tue', visits: 4100 },
  { day: 'Wed', visits: 3800 },
  { day: 'Thu', visits: 5200 },
  { day: 'Fri', visits: 4700 },
]

const variants = ['solid', 'glass', 'inverse'] as const

const count = new Intl.NumberFormat('en-US')

export default function ChartsTooltipVariants() {
  const motion = useChartMotion()

  return (
    <div className="grid w-full max-w-2xl gap-8 sm:grid-cols-3">
      {variants.map((variant) => (
        <figure key={variant}>
          <Chart className="h-44">
            <BarChart responsive data={data} aria-label={`Visits by weekday, with the ${variant} tooltip`}>
              <XAxis dataKey="day" tickLine={false} axisLine={false} />
              <Tooltip
                defaultIndex={2}
                active
                cursor={false}
                content={<ChartTooltip variant={variant} formatValue={(value) => count.format(value)} />}
              />
              <Bar
                name="Visits"
                dataKey="visits"
                fill={chartColors[0]}
                radius={[chartMarks.barRadius, chartMarks.barRadius, 0, 0]}
                {...motion.bars}
              />
            </BarChart>
          </Chart>
          <figcaption className="text-foreground-muted mt-2 text-center font-mono text-xs">{variant}</figcaption>
        </figure>
      ))}
    </div>
  )
}
```

These 3 tooltips are pinned open with `defaultIndex` and `active` on the Recharts `Tooltip`. The same 2 props mark a point before anyone touches the chart.

### Indicators [#indicators]

`indicator` sets the swatch beside each name: a `dot`, a `line` or a `dashed` line. `hideIndicator` removes it and `hideLabel` removes the heading.

```tsx
'use client'

import { Line, LineChart, Tooltip, XAxis, YAxis } from 'recharts'
import { Chart, ChartTooltip, chartColors, chartMarks, useChartMotion } from '@/components/chart'

const data = [
  { day: 'Mon', desktop: 2100, mobile: 1100 },
  { day: 'Tue', desktop: 2600, mobile: 1500 },
  { day: 'Wed', desktop: 2300, mobile: 1500 },
  { day: 'Thu', desktop: 3100, mobile: 2100 },
  { day: 'Fri', desktop: 2700, mobile: 2000 },
]

const indicators = ['dot', 'line', 'dashed'] as const

const count = new Intl.NumberFormat('en-US')

export default function ChartsTooltipIndicators() {
  const motion = useChartMotion()

  return (
    <div className="grid w-full max-w-2xl gap-8 sm:grid-cols-3">
      {indicators.map((indicator) => (
        <figure key={indicator}>
          <Chart className="h-48">
            <LineChart
              responsive
              data={data}
              margin={{ top: 8, right: 12, left: 12 }}
              aria-label={`Visits by weekday and device, with the ${indicator} indicator`}
            >
              <XAxis dataKey="day" tickLine={false} axisLine={false} />
              <YAxis hide domain={[0, 6000]} />
              <Tooltip
                defaultIndex={1}
                active
                content={<ChartTooltip indicator={indicator} formatValue={(value) => count.format(value)} />}
              />
              <Line
                name="Desktop"
                dataKey="desktop"
                type="monotone"
                stroke={chartColors[0]}
                dot={false}
                activeDot={chartMarks.activeDot}
                {...motion.series}
              />
              <Line
                name="Mobile"
                dataKey="mobile"
                type="monotone"
                stroke={chartColors[1]}
                dot={false}
                activeDot={chartMarks.activeDot}
                {...motion.series}
              />
            </LineChart>
          </Chart>
          <figcaption className="text-foreground-muted mt-2 text-center font-mono text-xs">{indicator}</figcaption>
        </figure>
      ))}
    </div>
  )
}
```

## Motion [#motion]

All chart motion is timed in the chart layer. `useChartMotion` passes the series timings to Recharts, and the frame handles the rest with Tailwind classes.

| What                   | Motion                                                                                      |
| ---------------------- | ------------------------------------------------------------------------------------------- |
| Line and area reveal   | 1 wipe from the start edge, 600 ms, ease-out. Once, on mount.                               |
| Bar reveal             | Each bar grows from the baseline in 450 ms, 30 ms after the one before, 300 ms of delay at most. |
| Data change            | A 300 ms ease-in-out morph. The reveal doesn't replay.                                      |
| Tooltip enter and exit | The classes of the library's `Tooltip`: a 200 ms spring from 90% scale in, 100 ms out.     |
| Tooltip follow         | Placed with no travel, then eases after the pointer in 150 ms. An arrow key moves it at once. |
| Cursor and active dot  | Fade in over 150 ms, then slide to the next point in 150 ms. In Safari, which cannot animate the cursor, both step from point to point. |
| Hover                  | The series under the pointer stays, and the others dim to 30% in 150 ms.                    |
| Legend toggle          | The swatch and the label change in 150 ms, and a series that comes back draws in 300 ms.    |

None of it runs under reduced motion. Recharts follows the OS setting on its own, and `useChartMotion` also reads [`useReducedMotion`](/ui/docs/react/use-reduced-motion), so a [`ReducedMotionProvider`](/ui/docs/react/reduced-motion-provider) turns charts off with everything else.

## Server Components [#server-components]

Recharts draws in the browser. On the server a chart is only an empty box of its size. So make the chart a Client Component that takes its data as props, and read the data in the Server Component around it, inside `Suspense`, with a fallback of the chart's height.

```tsx
import { Suspense } from 'react'
import { Skeleton } from '@appica/ui-react/skeleton'
import { OrdersChart } from './orders-chart'

async function OrdersChartData() {
  const data = await getOrders()
  if (data.length === 0) {
    return <p className="text-foreground-muted flex h-64 items-center justify-center text-sm">No data for this date range</p>
  }
  return <OrdersChart data={data} />
}

export default function OverviewPage() {
  return (
    <Suspense fallback={<Skeleton className="h-64 w-full" />}>
      <OrdersChartData />
    </Suspense>
  )
}
```

The frame gets its height from a class (`h-64` by default) and never from the chart. That is why the box is the same size before and after the chart draws.

## RTL [#rtl]

A chart is not mirrored in a right-to-left layout. Time and numbers still run left to right there, so the plot keeps its direction, which is also what Material's bidirectionality guidance recommends. `Chart` sets `dir="ltr"` on its frame, which also keeps the tick labels in place, and `ChartTooltip` and `ChartLegend` read the direction from [`DirectionProvider`](/ui/docs/react/direction-provider), so their text follows the page.


Add no `rtl:` variant and no `reversed` axis. Format numbers and dates with `Intl` and the page's locale, as the examples do.

## Accessibility [#accessibility]

- Give every chart an `aria-label` that says what it shows. Recharts passes it to the SVG as its accessible name. Its own `title` prop names the chart too, but browsers also show it as a native tooltip beside yours.
- A chart takes keyboard focus, and the arrow keys move the tooltip from point to point. This is Recharts' `accessibilityLayer`, on by default: leave it on.
- Color is never the only cue. A chart with 2 or more series has a legend, every chart has a tooltip that names each series, and text keeps the foreground tokens.
- A legend item that toggles a series is a real `<button>` with `aria-pressed`.
- Charts honor reduced motion, from the OS setting and from `ReducedMotionProvider`.
- A chart shows the shape of the data. When readers need the exact numbers, put them in a [`Table`](/ui/components/react/table) beside it.
