oakoss/ui
Components

Chart

Bar, line, area and other charts on TanStack Charts, with a visible title and description.

Source
Visitors by monthDesktop and mobile visitors from January to June.
Desktop and mobile visitors from January to June.

Installation

npx shadcn@latest add @oakoss/chart

Usage

import { barY, defineChart } from '@tanstack/charts';
import { scaleBand } from '@tanstack/charts/scales/band';
import { scaleLinear } from '@tanstack/charts/scales/linear';
import { tooltip } from '@tanstack/charts/tooltip';

import { ChartContainer, ChartPlot } from '#/components/ui/data/chart';
import type { ChartConfig } from '#/hooks/use-chart';
import { chartColor } from '#/lib/chart-series';

const config = {
  desktop: { color: 'var(--color-chart-1)', label: 'Desktop' },
  mobile: { color: 'var(--color-chart-2)', label: 'Mobile' },
} satisfies ChartConfig;

const definition = defineChart({
  color: chartColor(config),
  marks: [barY(visitors, { color: 'device', x: 'month', y: 'visitors' })],
  scales: {
    x: { scale: scaleBand },
    y: { grid: true, nice: true, scale: scaleLinear },
  },
  tooltip,
});

<ChartContainer
  config={config}
  description="Desktop and mobile visitors from January to June."
  title="Visitors by month"
>
  <ChartPlot definition={definition} />
</ChartContainer>;

The chart itself is a TanStack Charts definition: marks, scales, focus and the tooltip all live in it. ChartContainer is the figure, with your title and description as its caption, and ChartPlot renders the definition inside it, named by that caption. Content you place in the container, such as a summary, sits in the figure with the chart. Build the definition outside the component, or memoize it on the values it captures: a new definition rebuilds the chart.

config names each series and category, and an entry with a color is a series. Marks name a row's series with their color channel, and chartColor(config) turns the config into TanStack's color scale, so the marks, tooltip and legend share one mapping. Charts with several series take one row per value, so focus can group a month's values into one tooltip:

const visitors = [
  { device: 'desktop', month: 'January', visitors: 186 },
  { device: 'mobile', month: 'January', visitors: 80 },
];

A mark with no series takes the theme's --color-chart-1 to --color-chart-5 in turn, and a sixth takes TanStack's own color. When color means something else, such as a status, the series comes from z instead: the legend can then highlight it but not hide it.

Examples

Legend

ChartLegend lists the config's series. Given hidden and onHiddenChange, each item toggles its series: pass the same set to chartColor and rebuild the definition, and TanStack removes the series without moving the axes. Hovering or focusing an item dims the other series; give each mark chartSeriesStates for that. Without those props, the legend is a plain list.

const [hidden, setHidden] = useState(() => new Set<string>());
const definition = useMemo(
  () =>
    defineChart({
      color: chartColor(config, hidden),
      marks: [
        barY(visitors, {
          color: 'device',
          states: chartSeriesStates,
          x: 'month',
          y: 'visitors',
        }),
      ],
      // …
    }),
  [hidden],
);

<ChartContainer config={config} description="…" title="Visitors by month">
  <ChartPlot definition={definition} />
  <ChartLegend hidden={hidden} onHiddenChange={setHidden} />
</ChartContainer>;

The chart at the top of this page has one.

Data table

ChartTable shows the values each plot drew behind a "View as table" button: a row per category, headed by categoryLabel, and a column per series from the config. A series the legend hides leaves the table too. A chart without series, such as one bar per browser, takes a row per point and a valueLabel column; so does one where two marks draw the same series, with a seriesLabel column, so no value is dropped. The chart at the top of this page has one.

<ChartContainer config={config} description="…" title="Visitors by month">
  <ChartPlot definition={definition} />
  <ChartTable categoryLabel="Month" />
</ChartContainer>

The table is built from what the chart drew, so it appears once the chart renders in the browser. A pie slice's point carries its angle, not its value, so give a pie chart a table of your own.

Focus on bars

Focus marks a line's point with a ring. On bars, an outline marks the focused bar instead: give each bar mark chartBarStates, which also carries the legend's highlight, and set focusRing: false so the ring's dot doesn't sit on the bar's edge.

defineChart({
  focusRing: false,
  marks: [barY(visitors, { color: 'device', states: chartBarStates /* … */ })],
  // …
});

Loading, error and empty

status replaces the plot with a skeleton of its size ('loading'), an alert ('error') or a "No data" message ('empty'), so the layout holds when the data comes. fallback replaces what a status shows, for example with a retry button. A plot that draws no points keeps its axes and says "No data" over them, or "All series are hidden" when the legend hides every one. loadingLabel, errorLabel, emptyLabel and hiddenLabel change the text.

VisitorsVisitors from January to March.
Loading chart

Line and crosshair

focus: 'group-x' shows every series at the focused x value in one tooltip, and the crosshair mark draws a rule there. maxFocusDistance: Infinity snaps to the nearest month wherever the pointer is.

Visitor trendDesktop and mobile visitors from January to June, one line each.
Desktop and mobile visitors from January to June, one line each.

Tooltip

The tooltip is ChartTooltipContent, rendered through ChartPlot's renderTooltipBody. Render it yourself to change indicator (dot, line or dashed), hide the heading or indicators, or format the heading and values. The definition still needs TanStack's tooltip, which decides when it shows.

The heading is the value the focused points share, usually the x value, and each row shows the other axis; a bar or area reports its length, and a range its two ends. A pie slice's point carries its angle and radius, so pass labelFormatter and valueFormatter that read the slice's data from point.datum.

Total visitorsDesktop and mobile visitors from January to June, stacked.
Desktop and mobile visitors from January to June, stacked.

Axes and formatting

Axis titles are the axis label, and ticks.values picks which ticks show, here only the first and last month. The tooltip formats numbers and dates in the app's locale, from React Aria's I18nProvider; useChartFormatter gives axis ticks the same formatting; without it, numeric ticks take TanStack's default format.

RevenueMonthly revenue from January to June, rising from $42,000 to $97,000.
Monthly revenue from January to June, rising from $42,000 to $97,000.

Accessibility

The chart is a figure named by its title and described by its description, both visible in its caption, so the comparison it shows reads before the graphic. Inside, TanStack renders an SVG with role img, the same name and the description as its desc. Put the conclusion a reader should draw, or the values that matter, in the description.

TanStack makes the chart one tab stop and moves a virtual focus between its points, showing the tooltip for the focused one. The tooltip is a polite live region, and it speaks what it shows: the series named from the config, values in the app's locale. A chart without a tooltip announces the focused points through a status region of its own. ChartTable gives the exact values as a real table, for readers who need numbers rather than a picture.

Focus is marked on the point, not around the chart: a ring with the page's background inside and its foreground outside, or an outline on a bar, so it holds 3:1 on any series color. Hovering marks a point the same way. A chart with no points to mark keeps its outline. In forced colors the marker takes system colors, since SVG strokes keep their own colors there.

KeyAction
TabFocuses the chart, on its first point
Arrow keysMove to the next or previous point
Home / EndMove to the first or last point
Enter or SpacePins the tooltip open
EscapeHides the tooltip until focus moves, or closes a pinned one

An interactive legend is a toolbar named by its label ("Series"), one tab stop with arrow keys between its items. Each item is a toggle button named by its series alone, with aria-pressed set while the series shows; the WAI-ARIA button pattern keeps a toggle's name the same in both states. Focus highlights a series as hover does, and a hidden series doesn't highlight. A hidden item's swatch is hollow and its label struck through, so the state doesn't rest on color. Swatches keep their series colors in forced colors, as the tooltip's indicators do.

KeyAction
TabMoves into the legend, or on past it
Arrow Left / RightIn the legend, moves between items
Enter or SpaceOn a legend item, shows or hides its series

API

ChartContainer

A figure with a caption, which hands config, title and description to the parts inside it.

Props

Prop

Type

Also accepts figure props, except the ARIA naming ones: the caption names the figure.

Data attributes

AttributePresent when
data-slotAlways: chart, and chart-caption, chart-title and chart-description in its caption

ChartPlot

TanStack's Chart, named and described by the container's caption, with ChartTooltipContent as its tooltip body. It accepts TanStack Chart's props, except ariaLabel, ariaDescription and style; aspectRatio defaults to 16:9. Outside a ChartContainer it throws.

It sets the focus ring and the tooltip's spoken text unless the definition sets its own (focusRing, or the tooltip's content, format, formatGroup or items), and adds the legend's highlight control.

Props

Prop

Type

Data attributes

AttributePresent when
data-slotAlways: chart-plot, and chart-empty on the message over an empty plot
data-statusGiven status: loading, error or empty

ChartTable

The plotted values in a Table, behind a Collapsible.

Props

Prop

Type

Data attributes

AttributePresent when
data-slotAlways: chart-table

ChartTooltipContent

The tooltip body, a div of one row per focused point.

Props

Prop

Type

Also takes the context renderTooltipBody passes.

Data attributes

AttributePresent when
data-slotAlways: chart-tooltip, chart-tooltip-label, chart-tooltip-item and chart-tooltip-indicator

ChartLegend

The config's series: a React Aria ToggleButtonGroup of toggle buttons given hidden and onHiddenChange, otherwise a ul.

Props

Prop

Type

Data attributes

AttributePresent when
data-slotAlways: chart-legend, chart-legend-item on a toggle, chart-legend-swatch on each swatch
data-selectedOn a toggle whose series shows

chartColor, chartSeriesStates and chartBarStates

chartColor(config, hidden) returns a definition's color option: the config's series as the color domain, their colors as the range, and a legend that draws nothing and removes the hidden series after the scales resolve. chartSeriesStates goes in a mark's states and dims its series while the legend highlights another. chartBarStates adds an outline on the focused or hovered bar; use it on bar marks with focusRing: false.

useChartFormatter

Returns a function that formats a number or date in the app's locale, with optional number and date format options. Dates format in UTC by default. Keep the options outside the component or memoized, so the function, and a definition built on it, stays the same between renders.