# Chart parts

The shared frame (with its data table), legend and tooltip the charts are built from, plus the CHART_COLORS series palette, for a custom chart.

- Family: charts
- Import: `import { ChartFrame, ChartLegend, ChartTooltip, ChartAnimation } from "@senvenli/react/charts";`
- Page: https://design.senvenli.com/docs/components/chart-parts
- JSON: https://design.senvenli.com/docs/components/chart-parts.json

## Example: A custom chart

A dumbbell chart drawn by hand inside the shared frame, with the shared legend, tooltip and data table.

```tsx
import { useState } from "react";
import { ChartFrame, ChartLegend, ChartTooltip, chartSeries, useChartSeries } from "@senvenli/react/charts";

const ROWS = [
  { id: "north", region: "North", before: 4.2, after: 2.9 },
  { id: "south", region: "South", before: 5.1, after: 3.4 },
  { id: "east", region: "East", before: 3.6, after: 3.1 },
  { id: "west", region: "West", before: 4.8, after: 2.6 },
];
// chartSeries() gives each series its token color: the comparison is neutral, the current one the brand color.
const SERIES = [
  { key: "before", label: "2025", ...chartSeries(0, { isComparison: true }) },
  { key: "after", label: "2026", ...chartSeries(0) },
] as const;
const SCALE_MAX = 6;
const position = (value: number) => `${(value / SCALE_MAX) * 100}%`;
const days = new Intl.NumberFormat("en", { style: "unit", unit: "day", unitDisplay: "long" });

export default function Example() {
  const { hidden, toggle, isHidden } = useChartSeries();
  const [active, setActive] = useState<string | null>(null);
  const shown = SERIES.filter((series) => !isHidden(series.key));
  return (
    <ChartFrame
      height={176}
      legend={<ChartLegend items={SERIES} hidden={hidden} onToggle={toggle} />}
      // The same figures as a table: what screen readers get, and what the "Show as table" button shows.
      dataTable={{
        caption: "Average delivery time by region",
        rows: ROWS,
        columns: [
          { key: "region", header: "Region", isRowHeader: true },
          { key: "before", header: "2025", align: "end", render: (row) => days.format(row.before) },
          { key: "after", header: "2026", align: "end", render: (row) => days.format(row.after) },
        ],
      }}
    >
      <div className="flex h-full flex-col justify-around">
        {ROWS.map((row) => (
          <div key={row.id} className="relative flex items-center gap-ds-200" onPointerEnter={() => setActive(row.id)} onPointerLeave={() => setActive(null)}>
            <span className="w-12 shrink-0 text-body-small text-ds-text-subtle">{row.region}</span>
            <div className="relative h-4 flex-1">
              {shown.length === 2 && (
                <span
                  className="absolute top-1/2 h-0.5 -translate-y-1/2 bg-ds-border-bold"
                  style={{ insetInlineStart: position(Math.min(row.before, row.after)), width: position(Math.abs(row.before - row.after)) }}
                />
              )}
              {shown.map((series) => (
                <span
                  key={series.key}
                  className="absolute top-1/2 size-3 -translate-x-1/2 -translate-y-1/2 rounded-ds-full rtl:translate-x-1/2"
                  style={{ insetInlineStart: position(row[series.key]), background: series.color }}
                />
              ))}
            </div>
            {active === row.id && (
              <div className="pointer-events-none absolute end-0 top-full z-10">
                <ChartTooltip
                  active
                  label={row.region}
                  payload={shown.map((series) => ({ dataKey: series.key, name: series.label, value: row[series.key], color: series.color }))}
                  valueFormatter={days.format}
                />
              </div>
            )}
          </div>
        ))}
      </div>
    </ChartFrame>
  );
}
```

## Examples

### Nothing to draw

The frame keeps the chart's height and says why it is empty.

```tsx
import { ChartFrame, ChartLegend, chartColor } from "@senvenli/react/charts";
import { EmptyState } from "@senvenli/react/feedback";

type Row = { id: string; region: string; days: number };
const ROWS: Row[] = [];

export default function Example() {
  return (
    <ChartFrame
      height={176}
      // The legend's row is kept (invisible) while empty or loading, so nothing jumps when data arrives.
      legend={<ChartLegend items={[{ key: "days", label: "Delivery time", color: chartColor(0) }]} />}
      emptyState={ROWS.length === 0 ? <EmptyState size="small" icon="chart-column" title="No deliveries in this period" description="Figures appear once the first order ships." /> : null}
      dataTable={{
        caption: "Average delivery time by region",
        rows: ROWS,
        columns: [
          { key: "region", header: "Region" },
          { key: "days", header: "Days", align: "end" },
        ],
      }}
    >
      {null}
    </ChartFrame>
  );
}
```

## Guidelines

### When to use it

- Building a chart the library does not have, so it looks and reads like the others.

### Use something else when

- [composed-chart](https://design.senvenli.com/docs/components/composed-chart.md): Bars and lines on one plot cover the need without custom parts.
- [bar-chart](https://design.senvenli.com/docs/components/bar-chart.md): A standard chart is enough.

## Accessibility

Built in:

- A "Show as table" button shows the same data as a table, which screen readers get by default.

You provide:

- A title that says what the figure is.

## API reference

### ChartFrame

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| height | `number` |  | yes | The chart's height in px: loading, empty and the plot all keep it. |
| isLoading | `boolean` |  | no |  |
| emptyState | `React.ReactNode` |  | no | Shown instead of the plot when there is nothing to draw (a compact EmptyState); `null` while there is data. |
| dataTable | `ChartDataTable<T>` |  | yes | The same data as a compact Table: always there for screen readers, shown on request. Cells are values: a `render` that returns text (a formatted figure) is used; anything else falls back to the raw value in the hidden table. |
| legend | `React.ReactNode` |  | no | The Legend: above the plot, or below it (LineChart). |
| legendPlacement | `"top" \| "bottom"` | `"top"` | no |  |
| children | `React.ReactNode` |  | yes | The Recharts chart (inside a ResponsiveContainer), named by the table's caption. Its keyboard layer (arrow keys move between data points, the tooltip follows) stays on; the table carries the data in full. |

### ChartLegend

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| items | `readonly ChartLegendItem[]` |  | yes |  |
| hidden | `ReadonlySet<string>` |  | no | From `useChartSeries()`: pressing a key hides or shows its series. Leave out for a static legend. |
| onToggle | `(key: string) => void` |  | no |  |

### ChartTooltip

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| active | `boolean` |  | no | Set by Recharts when used as `<Tooltip content={<ChartTooltip … />} />`. |
| payload | `readonly ChartTooltipEntry[]` |  | no |  |
| label | `{}` |  | no |  |
| valueFormatter | `ChartValueFormatter` | `String` | no | Shared with the chart: "€ 55,0k". |
| labelFormatter | `(label: unknown) => ReactNode` |  | no | The period title ("August 2026"); the category label by default. |
| labels | `Readonly<Record<string, string>>` |  | no | Series names by data key ("2026", "Website"). |
| change | `(payload: readonly ChartTooltipEntry[]) => { label: string; value: string; tone: "success" \| "danger" \| "neutral" } \| null` |  | no | An optional change row, colored by meaning ("Change +11.8%"). |

### ChartAnimation

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| isEnabled | `boolean` |  | yes |  |
| children | `React.ReactNode` |  | yes |  |

### Tokens it reads

`--ds-border-focused`, `--ds-chart-1`, `--ds-chart-2`, `--ds-chart-3`, `--ds-chart-4`, `--ds-chart-5`, `--ds-chart-neutral`, `--ds-link`, `--ds-radius-medium`, `--ds-radius-small`, `--ds-radius-xsmall`, `--ds-shadow-overlay`, `--ds-space-050`, `--ds-space-075`, `--ds-space-100`, `--ds-space-150`, `--ds-space-200`, `--ds-surface-overlay`, `--ds-text`, `--ds-text-danger`, `--ds-text-subtle`, `--ds-text-success`

## Related

- [area-chart](https://design.senvenli.com/docs/components/area-chart.md)
- [bar-chart](https://design.senvenli.com/docs/components/bar-chart.md)
