# Chart

> Source: https://design.nanatec.co.ke/components/chart/
> The frame around a chart: series colours from the theme, a legend, and the axes and tooltip in the Nana look. Bring the chart library you prefer.

Nana does not draw charts. It gives a chart its colours, its legend and its look,
and leaves the drawing to a chart library. The examples use
[LayerChart](https://layerchart.com), which reads the colours as CSS variables;
canvas and SVG libraries such as ApexCharts get the same colours as concrete
values. The chart is available for Svelte.

## Preview

## Installation

```bash
npx @nana-tec/ui add chart --framework svelte
```

Lands in `src/lib/components/ui/chart/` as `NanaChartContainer.svelte` and
`NanaChartLegend.svelte`. It installs no chart library, so add the one you use:

```bash
npm install layerchart
```

## The config

A chart starts from a config: one entry per series, keyed by the field that
holds its values, with the label people read.

```ts
import type { ChartConfig } from '$lib/components/ui/chart';

const config: ChartConfig = {
  premiums: { label: 'Premiums' },
  claims: { label: 'Claims paid' },
};
```

`NanaChartContainer` turns each entry into a CSS variable named after its key,
`--chart-premiums` and `--chart-claims`, set on the container. Anything inside
can use them: a chart library, an SVG you draw yourself, or a Tailwind class such
as `fill-(--chart-premiums)`.

## Colours

Series take the theme's chart colours in order, `--nana-chart-1` to
`--nana-chart-5`. Each set is checked for colour-blind separation on its own
surface, in light and in dark. A sixth series gets a quiet grey: more than five
series rarely read well, so fold the smallest into "Other" or split the chart.

Give a series its own colour in the config. Prefer a token, so the colour follows
the theme:

```ts
const config: ChartConfig = {
  premiums: { label: 'Premiums', color: 'var(--nana-chart-3)' },
  target: { label: 'Target', color: 'var(--nana-surface-text-subtle)' },
};
```

To change the palette everywhere, override the tokens in your theme:

```css
:root {
  --nana-chart-1: #2563eb;
}
```

## With LayerChart

The container's snippet receives `series`: each key with its label and its
colour variable, in the shape LayerChart's charts take.

```svelte
<script lang="ts">
  import { BarChart } from 'layerchart';
  import { NanaChartContainer, NanaChartLegend } from '$lib/components/ui/chart';
</script>

<NanaChartContainer {config} aria-label="Premiums and claims paid by month">
  {#snippet children({ series })}
    <BarChart {data} x="month" {series} seriesLayout="group" />
  {/snippet}
</NanaChartContainer>
<NanaChartLegend {config} />
```

The container styles LayerChart's axes, grid, highlight and tooltip with the
Nana tokens, and keeps the tooltip inside the chart so it shares the series
colours. `AreaChart`, `LineChart` and `PieChart` work the same way.

## With ApexCharts

Libraries that paint to a canvas or set SVG attributes cannot read `var()`. The
snippet also receives `colors`: each series key mapped to the colour it resolves
to right now. The container resolves them again when the theme changes, so a
Svelte action that updates the chart keeps it in step with dark mode.

```svelte
<script lang="ts">
  import ApexCharts from 'apexcharts';
  import { NanaChartContainer, type ChartConfig } from '$lib/components/ui/chart';

  const config: ChartConfig = {
    premiums: { label: 'Premiums' },
    claims: { label: 'Claims paid' },
  };

  function apex(node: HTMLElement, colors: Record<string, string>) {
    const chart = new ApexCharts(node, {
      chart: { type: 'bar', height: 280, toolbar: { show: false }, foreColor: 'currentColor' },
      series: [
        { name: 'Premiums', data: [186, 305, 237, 173] },
        { name: 'Claims paid', data: [80, 200, 120, 190] },
      ],
      xaxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr'] },
      colors: [colors.premiums, colors.claims],
    });
    chart.render();
    return {
      update: (next: Record<string, string>) =>
        chart.updateOptions({ colors: [next.premiums, next.claims] }),
      destroy: () => chart.destroy(),
    };
  }
</script>

<NanaChartContainer {config} class="aspect-auto">
  {#snippet children({ colors })}
    <div class="w-full" use:apex={colors}></div>
  {/snippet}
</NanaChartContainer>
```

The same values are available outside Svelte from `@nana-tec/ui-dom/chart`:
`resolveChartColors(element, config)` reads them, and `watchTheme(callback)`
reports a theme change and returns a function that stops watching.

## Examples

Ready-made layouts to copy. Each takes its colours from the config, so it follows
the theme and dark mode without changes.

### Area chart in a card

### Stacked bars

Stack parts of a whole with `seriesLayout="stack"`. Keep the stack to three or
four series, so each segment stays readable.

### Line chart

### Donut

A donut colours each slice by row, so map the config onto LayerChart's colour
scale with `cDomain` and `cRange`.

## Legend

`NanaChartLegend` lists the series with a swatch beside each name. Inside a
container it reads the container's config; outside one, pass `config`. To list
only some series, pass their `keys`.

```svelte
<NanaChartLegend {config} keys={['premiums']} />
```

Use the legend whenever a chart has two or more series, so a series is never
told apart by colour alone.

## Sizing

The container fills its width at a 16:9 ratio. Set a height or another ratio
with a class:

```svelte
<NanaChartContainer {config} class="aspect-auto h-72">
```

## Accessibility

- Name the chart with `aria-label` on the container, saying what it shows.
- A chart is hard to read with a screen reader. Put the same numbers in a table
  nearby, or a sentence with the main finding.
- The legend is a list, and its swatches are hidden from assistive technology.

## API

`config` is required on `NanaChartContainer`. `id` names the chart in
`data-chart`; one is generated when you leave it out. The `children` snippet
receives `series` and `colors`. On `NanaChartLegend`, `config` is needed only
outside a container, and `keys` limits the series it lists.
