# Sparkline

> Tiny line, area, column and win-loss charts from @salmonui/charts/sparkline, server-rendered as static SVG and cheap enough for hundreds of Data Grid cells.

Canonical: https://salmonui.dev/docs/data-visualization/sparkline

`Sparkline` draws a word-sized chart. It lives in `@salmonui/charts/sparkline`
with its own stylesheet and never loads the axis, legend, tooltip-layer or
canvas code of the larger charts: the entry is under 4 KB gzip.

```tsx
import { Sparkline } from '@salmonui/charts/sparkline';
import '@salmonui/charts/sparkline/styles.css';

<Sparkline data={[3, 5, 4, 9, 6, 8]} highlights={{ high: true, low: true }} />
```

### Live demo: Sparklines

Live demo: https://salmonui.dev/demos/data-visualization/sparkline-basic

Line, area, column and win-loss sparklines with highlighted high and low points, a range band and a keyboard-accessible tooltip.

`Demo.tsx`:

```tsx
'use client';

import { Sparkline } from '@salmonui/charts/sparkline';

const visits = [32, 41, 38, 52, 49, 61, 58, 66, 72, 69, 80, 77];
const margin = [4, -2, 6, 3, -5, 8, -1, 2, 7, -3, 5, 9];
// Labels in one column, sparklines in the next, so every sparkline starts at the same edge.
const rows = { display: 'grid', gridTemplateColumns: 'max-content max-content', alignItems: 'center', gap: '12px 16px' } as const;

/** Four sparkline types beside their labels; the first one has a tooltip. */
export default function SparklineBasicDemo() {
  return (
    <div style={rows}>
      <span>Visits</span>
      <Sparkline data={visits} highlights={{ high: true, low: true, last: true }} bands={[{ from: 40, to: 60 }]} tooltip width={120} height={28} />
      <span>Area</span>
      <Sparkline type="area" data={visits} width={120} height={28} />
      <span>Margin</span>
      <Sparkline type="column" data={margin} highlights={{ negative: true }} width={120} height={28} />
      <span>Results</span>
      <Sparkline type="winLoss" data={[1, 1, -1, 1, 0, -1, 1, 1]} width={120} height={28} />
    </div>
  );
}
```

## Types and data

`type` is `'line'` (default), `'area'`, `'column'` or `'winLoss'` (positive,
negative and tie bars; `tieColor` colors ties). `data` is a number array or
records read through `yField` and `xField` (nested paths such as
`'price.close'` work). Without `xField` points are evenly spaced;
`scale="time"` places them by their x value (numbers or `Date` instances,
epoch ms), `scale="category"` keeps them evenly spaced in data order.

`width` and `height` (default 100 x 24) are the drawing size in px; the SVG
scales to its CSS box through `viewBox`, so there is no `onResize`.
`renderer="canvas"` (or `'auto'`, from 20,000 points) draws the marks on a
canvas when `canvasRenderer={sparklineCanvas}` from
`@salmonui/charts/sparkline/canvas` is passed; without it the marks stay SVG.
`animated` (default `true`) plays the entrance after hydration with
the opt-in `@salmonui/charts/viz-animations.css`.

## Highlights, markers, labels and bands

| Prop | Meaning |
| --- | --- |
| `highlights` | `{ high, low, first, last, negative }`: `true` uses the success, danger and primary seeds, a hex string is a data color |
| `markers` | `'all'` or a list of point kinds that get a dot |
| `labels` | the same selector for value labels, formatted with `format` (`Intl.NumberFormatOptions` or a function) and `locale` |
| `bands` | `[{ from, to, color }]` range bands behind the line |
| `domain` | `{ x: [min, max], y: [min, max] }` fixes the extents |
| `baseline` | draws the axis line at a value (columns and areas grow from it) |
| `padding` | `'none'`, `'normal'` (default) or `'additional'` space around the extent |
| `color`, `palette` | the series data color, and data colors per bar |
| `getPointStyle(point)` | per-point `{ color, hidden }` |

Stroke widths and marker sizes are system-owned.

## Tooltip and events

`tooltip` (`true` or `{ format, render, trackLine }`) makes the sparkline
one focusable image: the tooltip chunk loads on the first pointer enter or
focus, then hover, arrow keys, Home and End move between points and Escape
hides it. `onPointClick` and `onPointHover` receive `{ point, source,
nativeEvent }`; Enter clicks the focused point. Without these props the SVG
has no listener and no state at all.

The root is `<svg role="img">` with an automatic summary as its name
("Sparkline, 12 points, minimum 3, maximum 9, first 4, last 8, trending
up"); pass `label` to replace it. `ref` receives the `<svg>`. The sparkline has
no controlled state; it is a tab stop only when `tooltip` is set.

### Live demo: Sparkline axis, labels and events

Live demo: https://salmonui.dev/demos/data-visualization/sparkline-axis-events

Three monthly temperature sparklines on a shared y domain with a 0 °C baseline, padding modes, high and low labels, per-point colors and point hover and click events.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';
import { Sparkline, type SparklinePointEvent } from '@salmonui/charts/sparkline';

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const regions = [
  { name: 'North', temps: [-4, -2, 3, 9, 15, 19, 22, 21, 16, 9, 3, -2] },
  { name: 'Central', temps: [2, 4, 8, 13, 18, 23, 26, 25, 20, 14, 7, 3] },
  { name: 'South', temps: [12, 13, 16, 19, 23, 27, 30, 30, 27, 22, 17, 13] },
];

type Padding = 'none' | 'normal' | 'additional';

// Region names in one column, sparklines in the next, so the three sparklines line up.
const rows = { display: 'grid', gridTemplateColumns: 'max-content max-content', alignItems: 'center', gap: '8px 16px' } as const;

/** Monthly temperatures on one shared y domain with a 0 °C baseline, labels and point events. */
export default function SparklineAxisEventsDemo() {
  const [shared, setShared] = useState(true);
  const [padding, setPadding] = useState<Padding>('normal');
  const [hovered, setHovered] = useState('none');
  const [clicked, setClicked] = useState('none');
  const describe = (region: string, e: SparklinePointEvent) => `${region} ${months[e.point.index] ?? ''}: ${e.point.y} °C (${e.source})`;
  return (
    <div className="demo-stack">
      <div className="demo-toolbar" role="group" aria-label="Sparkline axis options">
        <Checkbox checked={shared} onCheckedChange={(checked) => setShared(checked)}>Shared y domain (−10 to 35 °C)</Checkbox>
        <label>
          Padding
          <Select aria-label="Padding" data={[{ value: 'none', label: 'None' }, { value: 'normal', label: 'Normal' }, { value: 'additional', label: 'Additional' }]} value={padding} onValueChange={(value) => value != null && setPadding(value as Padding)} />
        </label>
      </div>
      <div style={rows}>
        {regions.map((r) => [
          <span key={`${r.name}-label`}>{r.name}</span>,
          <Sparkline
            key={r.name}
            label={`${r.name} monthly temperature`}
            data={r.temps}
            width={260}
            height={56}
            domain={shared ? { y: [-10, 35] } : undefined}
            baseline={0}
            padding={padding}
            markers="all"
            labels={['high', 'low']}
            format={(v) => `${v}°`}
            getPointStyle={(p) => (p.y < 0 ? { color: '#2563eb' } : p.y >= 25 ? { color: '#dc2626' } : undefined)}
            tooltip={{ format: (p) => `${months[p.index] ?? ''}: ${p.y} °C` }}
            onPointHover={(e) => setHovered(e ? describe(r.name, e) : 'none')}
            onPointClick={(e) => setClicked(describe(r.name, e))}
          />,
        ])}
      </div>
      <p className="demo-status" aria-live="polite">
        Hover: <code>{hovered}</code> · Click: <code>{clicked}</code>
      </p>
    </div>
  );
}
```

## Server rendering

The server markup is the final SVG: no effect, store or observer runs, and
the tooltip chunk and the animation attribute are added on the client only,
so hydration never differs.

## In Data Grid cells

Render a sparkline from a column's `renderCell`. The grid virtualizes rows
and every sparkline is final static markup, so 500 sparklines scrolled at
2,000 px/s keep the Data Grid scroll budgets (a `bench` core path).

### Live demo: Sparklines in Data Grid cells

Live demo: https://salmonui.dev/demos/data-visualization/sparkline-grid

A Data Grid with a Sparkline cell template on every row; the sparklines render as static SVG, so scrolling keeps the grid scroll budgets.

`Demo.tsx`:

```tsx
'use client';

import { DataGrid, type DataGridColumn } from '@salmonui/data-grid';
import { Sparkline } from '@salmonui/charts/sparkline';

interface Product {
  id: string;
  name: string;
  trend: number[];
}

const products: Product[] = Array.from({ length: 200 }, (_, i) => ({
  id: `p${i + 1}`,
  name: `Product ${i + 1}`,
  trend: Array.from({ length: 16 }, (_, k) => Math.round(50 + 30 * Math.sin(k / 2.5 + i) + ((k * 7 + i * 3) % 9))),
}));

const columns: DataGridColumn<Product>[] = [
  { field: 'id', header: 'Id', primaryKey: true, width: 90 },
  { field: 'name', header: 'Product', width: 160 },
  { field: 'trend', header: 'Last 16 weeks', type: 'string', sortable: false, width: 170, renderCell: ({ row }) => <Sparkline data={row.trend} width={140} height={24} highlights={{ high: true, low: true }} /> },
  { field: 'trend', id: 'weekly', header: 'Weekly', type: 'string', sortable: false, width: 170, renderCell: ({ row }) => <Sparkline data={row.trend.slice(-8)} type="column" width={140} height={24} color="#0f766e" /> },
];

export default function SparklineGridDemo() {
  return <DataGrid<Product> aria-label="Products with sparklines" data={products} columns={columns} height={360} />;
}
```

## Pie sparklines

`Sparkline` has no pie type: a pie layout with labels would grow
the `Sparkline` bundle, which must stay small for grid cells. For a pie in
a cell, use `<PieChart size="small" data={...} valueField="..." />` from
[`@salmonui/charts/pie-chart`](https://salmonui.dev/docs/data-visualization/pie-chart): no
legend, no labels, no title, static until hovered. Stroke widths, marker
sizes and the container area styling are system-owned, not props; see [Rendering and colors](https://salmonui.dev/docs/data-visualization/rendering-and-colors).
Every prop is listed in the [API reference](https://salmonui.dev/docs/reference/charts/sparkline).
