Data Display

Chart

Line, area, bar and donut charts built on TanStack Charts and styled with the theme tokens. Describe a chart with three props, data, index and categories, and get a legend, a tooltip, keyboard navigation and an SVG that is rendered on the server. When the props run out, pass a full TanStack Charts definition instead.

Installation

Add @tanstack/charts (version 1.5 or later) next to sv5ui. Nothing else is needed: the chart colors ship in sv5ui/theme.css.

Terminal
npm install sv5ui @tanstack/charts

Basic Usage

data is a list of rows, index names the key that labels the x axis, and categories lists the keys to plot, one series each. The chart fills the width of its container and is 300px tall.

  • desktop
  • mobile
<script lang="ts">
  import { Chart } from 'sv5ui/chart';

  const visitors = [
    { month: 'Jan', desktop: 186, mobile: 80 },
    { month: 'Feb', desktop: 305, mobile: 200 },
    { month: 'Mar', desktop: 237, mobile: 120 },
    { month: 'Apr', desktop: 73, mobile: 190 },
    { month: 'May', desktop: 209, mobile: 130 },
    { month: 'Jun', desktop: 214, mobile: 140 }
  ];
</script>

<Chart data={visitors} index="month" categories={['desktop', 'mobile']} />

Types

type picks the shape. Line, area and bar share the same props. A donut reads its rows differently: each row is a slice, index labels it, and the first entry of categories holds its value.

type="line"

  • Desktop
  • Mobile
  • Tablet

type="area"

  • Desktop
  • Mobile
  • Tablet

type="bar"

  • Desktop
  • Mobile
  • Tablet

type="donut"

  • Chrome
  • Safari
  • Firefox
  • Edge
  • Other
<Chart type="line" data={visitors} index="month" categories={categories} />
<Chart type="area" data={visitors} index="month" categories={categories} />
<Chart type="bar" data={visitors} index="month" categories={categories} />

<!-- One row per slice: index labels the slice, the first category holds its value -->
<Chart type="donut" data={browsers} index="browser" categories={['visitors']} />

Categories

A category is a row key, or an object with a label and a color. The label is what the legend, the tooltip and the accessible name show; without one they show the key. Series are drawn, colored and listed in the order you give.

With typed rows, index only accepts keys whose values are strings or numbers and categories only keys whose values are numbers, so a typo or a text column is a type error rather than an empty chart.

  • Desktop
  • Mobile
  • tablet
<script lang="ts">
  import { Chart } from 'sv5ui/chart';
</script>

<Chart
  data={visitors}
  index="month"
  categories={[
    { key: 'desktop', label: 'Desktop' },
    { key: 'mobile', label: 'Mobile', color: 'tertiary' },
    'tablet'
  ]}
/>

Missing and Repeated Values

Real data has holes and duplicates, and the chart handles both without preprocessing. A missing value leaves a gap rather than dropping to zero, and rows that share an index value are added together, so a list of raw records can be charted as is.

Gaps

Six orders, three bars

<script lang="ts">
  import { Chart } from 'sv5ui/chart';

  // null leaves a gap. Thu has no neighbour, so it keeps a dot.
  const sessions = [
    { day: 'Mon', sessions: 12 },
    { day: 'Tue', sessions: 18 },
    { day: 'Wed', sessions: null },
    { day: 'Thu', sessions: 15 },
    { day: 'Fri', sessions: null },
    { day: 'Sat', sessions: 9 },
    { day: 'Sun', sessions: 11 }
  ];

  // Raw records: rows that share a month are added together.
  const orders = [
    { month: 'Jan', amount: 120 },
    { month: 'Jan', amount: 80 },
    { month: 'Feb', amount: 150 },
    { month: 'Mar', amount: 90 },
    { month: 'Mar', amount: 60 },
    { month: 'Mar', amount: 45 }
  ];
</script>

<Chart data={sessions} index="day" categories={['sessions']} />
<Chart type="bar" data={orders} index="month" categories={['amount']} />

Data Rules

How rows and values are read.

InputResult
One row per x valueEach row of data is one position on the x axis, or one slice of a donut
Rows that share an indexAdded together into one position. The tooltip and the axis show it once
A row without an indexSkipped. The index value must be a string or a finite number
null, undefined, NaN, InfinityLeave a gap in the series instead of being drawn as zero
A numeric string such as '12'Also a gap: values are not parsed. Typed rows reject such a column at compile time, and untyped rows log a console warning once per category. Convert with Number() first
A value with no neighbourKeeps a dot on line and area charts, so a single reading is never invisible
Donut slice of zero or lessDropped from the ring and the legend. A missing value is dropped as well

Stacked

stacked applies to area and bar charts, and a line chart ignores it. Series stack in categories order, positive values upwards from zero and negative values downwards. The tooltip still shows each series' own value, not the running total.

  • Desktop
  • Mobile
  • Tablet
  • Desktop
  • Mobile
  • Tablet
<Chart type="area" stacked curve="monotone" data={visitors} index="month" categories={categories} />
<Chart type="bar" stacked data={visitors} index="month" categories={categories} />

Curves & Points

For line and area charts, curve sets how values are joined: linear draws straight segments, monotone a smooth curve that never overshoots a value, and step changes level halfway between two values. points adds a dot at each value.

curve="linear"

curve="monotone"

curve="step"

<Chart data={visitors} index="month" categories={['desktop']} curve="linear" points />
<Chart data={visitors} index="month" categories={['desktop']} curve="monotone" points />
<Chart data={visitors} index="month" categories={['desktop']} curve="step" points />

Colors

Series take their colors from six theme tokens, --color-chart-1 to --color-chart-6, which have separate light and dark values. A seventh series and beyond reuse them as lighter tints, so no two series share a color.

--color-chart-1
--color-chart-2
--color-chart-3
--color-chart-4
--color-chart-5
--color-chart-6

To pick colors yourself, pass colors in categories order, or set color on a category, which wins. Both accept the theme colors primary, secondary, tertiary, success, warning, error and info; anything else is used as a CSS color, such as a hex value or a var().

  • desktop
  • mobile
  • tablet
  • desktop
  • mobile
  • Revenue
  • Costs
<!-- Default: --color-chart-1 to --color-chart-6 -->
<Chart type="bar" data={visitors} index="month" categories={['desktop', 'mobile', 'tablet']} />

<!-- colors: theme colors or any CSS color, in categories order -->
<Chart
  type="bar"
  data={visitors}
  index="month"
  categories={['desktop', 'mobile']}
  colors={['success', '#8b5cf6']}
/>

<!-- A category color wins over colors -->
<Chart
  data={revenue}
  index="quarter"
  categories={[
    { key: 'revenue', label: 'Revenue', color: 'success' },
    { key: 'costs', label: 'Costs', color: 'error' }
  ]}
  colors={['info', 'warning']}
/>

To change the palette for every chart, override the tokens after importing the theme, in both modes:

app.css
/* app.css, after importing sv5ui/theme.css */
:root {
  --color-chart-1: oklch(0.6 0.18 250);
  --color-chart-2: oklch(0.7 0.16 150);
}

.dark {
  --color-chart-1: oklch(0.68 0.16 250);
  --color-chart-2: oklch(0.72 0.14 150);
}

Axes, Labels & Formatting

xLabel and yLabel add axis titles. format turns a number into text for the y axis ticks and the tooltip values; the x axis shows the index values as they are.

  • Revenue
  • Costs
<script lang="ts">
  import { Chart } from 'sv5ui/chart';

  const usd = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    maximumFractionDigits: 0
  });
</script>

<Chart
  type="bar"
  data={revenue}
  index="quarter"
  categories={[
    { key: 'revenue', label: 'Revenue' },
    { key: 'costs', label: 'Costs' }
  ]}
  format={(value) => usd.format(value)}
  xLabel="Quarter"
  yLabel="Amount (USD)"
/>

Grid, Axes & Legend

grid, xAxis and yAxis are on by default. Turn them off with a small height for a sparkline. The legend appears on its own when there is more than one series or slice; legend forces it on or off.

Desktop

214

Mobile

140

Tablet

93

<Card variant="outline">
  <span class="text-sm text-on-surface-variant">Desktop</span>
  <p class="text-2xl font-semibold tabular-nums">214</p>
  <Chart
    type="area"
    data={visitors}
    index="month"
    categories={[{ key: 'desktop', label: 'Desktop', color: 'primary' }]}
    curve="monotone"
    grid={false}
    xAxis={false}
    yAxis={false}
    tooltip={false}
    height={64}
    aria-label="Desktop visitors, last six months"
  />
</Card>

Donut

thickness sets the ring width in pixels; a value at or above the radius fills the circle and draws a pie. The center snippet places content in the middle and receives the total of every slice and the slice items. It does not catch the pointer, so hovering the ring still works.

Slices are colored in data order. A slice that is zero, negative or missing is left out, and the slices after it keep their colors.

thickness={16}

925 across 5 browsers
  • Chrome
  • Safari
  • Firefox
  • Edge
  • Other

thickness={32}

925 across 5 browsers

thickness={999}

<Chart
  type="donut"
  data={browsers}
  index="browser"
  categories={['visitors']}
  thickness={16}
  aria-label="Visitors by browser"
>
  {#snippet center({ total, items })}
    <span class="text-2xl font-semibold text-on-surface tabular-nums">{total}</span>
    <span class="text-xs">across {items.length} browsers</span>
  {/snippet}
</Chart>

Custom Tooltip

The tooltip lists every series at the hovered x value and highlights the one under the pointer. tooltip={false} turns it off. The tooltipSlot snippet replaces what is inside it and keeps the surface. Through points it can reach the original row and show fields that are not plotted, like the profit below.

A click, Enter or Space pins the tooltip so it stays open. Use pinned and dismiss to offer a close button; Escape closes it too.

  • Revenue
  • Costs
<script lang="ts">
  import { Chart } from 'sv5ui/chart';
  import { Badge, Button } from 'sv5ui';
</script>

<Chart
  data={revenue}
  index="quarter"
  categories={[
    { key: 'revenue', label: 'Revenue' },
    { key: 'costs', label: 'Costs' }
  ]}
  curve="monotone"
  points
>
  {#snippet tooltipSlot({ title, points, pinned, dismiss })}
    {@const row = points[0]?.datum.row}
    <div class="flex min-w-44 flex-col gap-1">
      <div class="flex items-center justify-between gap-2">
        <span class="font-medium text-on-surface">{title}</span>
        {#if pinned}
          <Button size="xs" variant="ghost" color="surface" icon="lucide:x" aria-label="Close" onclick={dismiss} />
        {/if}
      </div>
      {#if row}
        <span>Revenue <b class="text-on-surface">{usd.format(row.revenue)}</b></span>
        <span>Costs <b class="text-on-surface">{usd.format(row.costs)}</b></span>
        <Badge
          size="sm"
          variant="soft"
          color="success"
          label={`Profit ${usd.format(row.revenue - row.costs)}`}
          class="mt-1 self-start"
        />
      {/if}
    </div>
  {/snippet}
</Chart>

Size

A chart is as wide as its container and 300px tall. Set height for another fixed height, aspectRatio to let the height follow the width, or width to fix both.

  • Desktop
  • Mobile
  • Tablet
  • Desktop
  • Mobile
  • Tablet
  • Desktop
  • Mobile
  • Tablet
<!-- Fixed height, width follows the container (the default is 300px) -->
<Chart data={visitors} index="month" categories={categories} height={200} />

<!-- Height follows the width -->
<Chart data={visitors} index="month" categories={categories} aspectRatio={3} />

<!-- Fixed size -->
<Chart data={visitors} index="month" categories={categories} width={280} height={160} />

Events

onFocusChange follows the hovered or keyboard-focused point, onFocusGroupChange receives every point at that x value, and onSelect fires on a click, Enter or Space. Each point's datum is a ChartSeriesDatum that carries the series, the plotted value and the original row, so a drill-down needs no lookup.

  • Desktop
  • Mobile
  • Tablet
Focused: none (0 values in the group) Selected: none
<script lang="ts">
  import { Chart, type ChartSeriesDatum } from 'sv5ui/chart';

  type Visitors = (typeof visitors)[number];

  let focused = $state('');
  let group = $state(0);
  let selected = $state<ChartSeriesDatum<Visitors> | null>(null);
</script>

<Chart
  type="bar"
  data={visitors}
  index="month"
  categories={categories}
  onFocusChange={(point) => (focused = point ? `${point.datum.index} · ${point.datum.label}` : '')}
  onFocusGroupChange={(points) => (group = points.length)}
  onSelect={(point) => (selected = point?.datum ?? null)}
/>

<p>Focused: {focused || 'none'} ({group} values in the group)</p>
<p>Selected: {selected ? `${selected.index} · ${selected.label} = ${selected.value}` : 'none'}</p>

Custom Definition

For marks the props do not cover, such as a reference line, build a chart with TanStack Charts' defineChart and pass it as definition. It takes precedence over type, data, index and categories. Sizing, the tooltip surface, the ui slots and the chart palette still apply.

<script lang="ts">
  import { Chart } from 'sv5ui/chart';
  import { defineChart, lineY, ruleY } from '@tanstack/charts';
  import { scaleLinear } from '@tanstack/charts/scales/linear';
  import { scalePoint } from '@tanstack/charts/scales/point';
  import { tooltip } from '@tanstack/charts/tooltip';

  const target = 200;

  const definition = defineChart({
    marks: [
      ruleY([target], { stroke: 'var(--color-error)', strokeDasharray: '4 4' }),
      lineY(visitors, { x: 'month', y: 'desktop', stroke: 'var(--color-primary)', points: true })
    ],
    scales: {
      x: { scale: () => scalePoint<string>().padding(0.1) },
      y: { scale: scaleLinear, nice: true, grid: true, axis: { label: 'Desktop visitors' } }
    },
    tooltip
  });
</script>

<Chart {definition} aria-label="Desktop visitors against a target of 200" height={240} />

Accessibility

The chart is a single focusable image with the role description "chart". Its accessible name is built from the type and the series labels, such as "Bar chart: Revenue, Costs", or the slice labels of a donut. That names what is plotted but not what it means, so pass an aria-label that does, and an aria-description for the takeaway.

Once focused, the arrow keys move through the values and the tooltip follows, so every number a pointer can reach is reachable from the keyboard. Labels from your data are always rendered as text, never as markup, and the animations are skipped when the user prefers reduced motion.

<!-- Accessible name defaults to "Bar chart: Revenue, Costs" -->
<Chart type="bar" data={revenue} index="quarter" categories={categories} />

<!-- Name what the chart shows, and describe the takeaway -->
<Chart
  type="bar"
  data={revenue}
  index="quarter"
  categories={categories}
  aria-label="Revenue and costs by quarter, 2026"
  aria-description="Revenue grows every quarter while costs stay roughly flat."
/>

Global Configuration

Set the default type and slot classes for every chart with defineConfig under the chart key.

// src/routes/+layout.svelte (or any module that runs before the first chart)
import { defineConfig } from 'sv5ui';

defineConfig({
  chart: {
    defaultVariants: { type: 'bar' },
    slots: {
      legend: 'justify-start',
      tooltip: 'rounded-lg'
    }
  }
});

Keyboard Navigation

With the chart focused. Focus stops at the first and the last value rather than wrapping around.

KeyAction
TabMove focus to the chart. The first value is focused and its tooltip opens
ArrowRight / ArrowDownFocus the next x value, or the next slice of a donut in data order
ArrowLeft / ArrowUpFocus the previous x value, or the previous slice
Home / EndFocus the first or the last value
Enter / SpaceSelect the focused point (onSelect) and pin its tooltip
EscapeClose a pinned tooltip

ChartCategory

An entry of categories, when it is not a plain key.

FieldTypeDefault
keyChartValueKey<T>-
labelstringkey
colorstring-

ChartSeriesDatum

The datum behind every point, received by onSelect, onFocusChange, onFocusGroupChange and the tooltipSlot points as point.datum.

FieldType
indexstring | number
categorystring
labelstring
valuenumber | null
startnumber | null
endnumber | null
rowT
rowsT[]

tooltipSlot Context

FieldType
titlestring | undefined
rowsChartTooltipRow[]
pointsreadonly ChartPoint<D>[]
pinnedboolean
dismiss() => void

center Context

FieldType
totalnumber
itemsChartLegendItem[]

Types

Exported from sv5ui/chart.

TypeDescription
ChartProps<T, D>Props of the component. D is ChartSeriesDatum<T>, or the datum of definition
ChartType'line' | 'area' | 'bar' | 'donut'
ChartCurve'linear' | 'monotone' | 'step'
ChartCategory<T>A category object: key, label, color
ChartIndexKey<T>Row keys whose values are strings or numbers. Any key for loosely typed rows
ChartValueKey<T>Row keys whose values are number | null | undefined. Any key for loosely typed rows
ChartSeriesDatum<T>The datum behind every point, received by the callbacks as point.datum
ChartLegendItem{ key, label, color }
ChartTooltipRow{ label, value, color?, active }
ChartTooltipSlotProps<D>Context of the tooltipSlot snippet
ChartCenterSlotPropsContext of the center snippet
ChartDefinitionRe-exported from @tanstack/charts/svelte, for the definition prop
ChartPoint<TDatum>Re-exported from @tanstack/charts/svelte. Has datum, color, key, x, y and more

UI Slots

Use the `ui` prop to override classes on internal elements.

SlotDescription
rootOuter wrapper around the chart and the legend. Maps the palette tokens for TanStack Charts
baseWrapper around the SVG. Draws the focus ring
centerOverlay in the middle of a donut that holds the center snippet
legendLegend list under the chart
legendItemOne legend entry
legendIndicatorColor marker of an entry: a short line for line charts, a swatch otherwise
legendLabelText of an entry
tooltipTooltip surface. Also wraps the tooltipSlot snippet
tooltipTitleTooltip heading, the focused index value
tooltipRowOne row per series. Has data-active on the focused series
tooltipIndicatorColor marker of a row
tooltipLabelSeries label in a row
tooltipValueFormatted value in a row

Snippets

SnippetDescription
tooltipSlotReplaces the tooltip content. Receives ChartTooltipSlotProps
centerContent in the middle of a donut. Receives { total, items }. Ignored for other types and for definition

Props

Other HTML attributes are passed to the root element.

PropTypeDefault
type'line' | 'area' | 'bar' | 'donut''line'
datareadonly T[][]
indexChartIndexKey<T>-
categoriesreadonly (ChartValueKey<T> | ChartCategory<T>)[]-
colorsreadonly string[]chart palette
stackedbooleanfalse
curve'linear' | 'monotone' | 'step''linear'
pointsbooleanfalse
gridbooleantrue
xAxisbooleantrue
yAxisbooleantrue
xLabelstring-
yLabelstring-
legendbooleanauto
format(value: number) => string-
tooltipbooleantrue
transitionbooleantrue
thicknessnumber24
heightnumber300
widthnumber-
aspectRationumber-
initialWidthnumber640
definitionChartDefinition<D>-
aria-labelstringderived
aria-descriptionstring-
onSelect(point: ChartPoint<D> | null) => void-
onFocusChange(point: ChartPoint<D> | null) => void-
onFocusGroupChange(points: readonly ChartPoint<D>[]) => void-
refHTMLElement | nullnull
classClassNameValue-
uiPartial<Record<ChartSlots, ClassNameValue>>-