# Grid integration

> Turn a range selected in Grid Pro into a chart with chartFromRange, and draw sparklines inside Birch UI Grid cells with sparklineSVG.

Charts and grids usually sit side by side in analytical screens. Birch UI Charts has two helpers for that: `chartFromRange()` turns a rectangle of cells into chart options, and `sparklineSVG()` draws a tiny chart as an SVG string for a grid cell. Neither depends on the grid package, so they work with any table data.

## Charts from a range of cells

`chartFromRange(values, headers, options?)` takes a 2-D array of cell values and the column headers, and returns `ChartOptions` ready for `createChart()`:

```ts title="range-chart.ts"
import { chartFromRange, createChart } from '@birchui/charts';

const options = chartFromRange(
  [
    ['North America', 1_265_000, 1_511_000],
    ['Europe', 865_000, 1_005_000],
    ['Asia Pacific', 731_000, 802_000],
  ],
  ['Region', 'Q1', 'Q2'],
  { type: 'column', stacked: true, title: 'Revenue by quarter' },
);

createChart(document.querySelector<HTMLElement>('#selection-chart')!, options);
```

How the range is read:

- **Numeric columns become series.** A column counts as numeric when at least 60% of its non-empty cells are numbers or numeric text. Formatted text such as `$1,265,000`, `€865,000`, `12.5%` and accounting negatives like `(2,500)` is parsed; the same parser is exported as `parseCellNumber()`.
- **The first non-numeric column becomes the category axis.** Set `categoryColumn` to pick another column by index. If every column is numeric, the first column is used as the x values (for scatter and bubble charts, or when there is more than one numeric column); if there is a single numeric column, rows are labelled "Row 1", "Row 2" and so on.
- **The chart type is chosen for you** unless you pass `type`: a line chart when the categories are dates or there are more than 24 rows, a bar chart otherwise.
- **Pie and donut charts** use only the first numeric column.
- **Headers** become series names and data keys. Empty headers become "Column 1", "Column 2", and duplicates get a suffix.

The options object also accepts `stacked`, `horizontal`, and every other `ChartOptions` property (`title`, `subtitle`, `axes`, `theme`, `licenseKey` and so on), which are passed through to the result.

**`RangeChartOptions`** (interface from `@birchui/charts`, full reference: https://docs.birchui.com/api/charts.md)

```ts
interface RangeChartOptions extends Partial<Omit<ChartOptions, 'data' | 'series'>>
```

| Property | Type | Description |
| --- | --- | --- |
| `type?` | `SeriesType` |  |
| `stacked?` | `StackMode` |  |
| `categoryColumn?` | `number` |  |
| `horizontal?` | `boolean` |  |
| `sparkline?` | `boolean \| undefined` | Inherited from ChartOptions. |
| `theme?` | `ThemeName \| undefined` | Inherited from ChartOptions. |
| `licenseKey?` | `string \| undefined` | Inherited from ChartOptions. |
| `localeText?` | `LocaleTextInput \| undefined` | Inherited from ChartOptions. |
| `rtl?` | `boolean \| undefined` | Inherited from ChartOptions. |
| `injectStyles?` | `boolean \| undefined` | Inherited from ChartOptions. |
| `locale?` | `string \| undefined` | Inherited from ChartOptions. |
| `height?` | `string \| number \| undefined` | Inherited from ChartOptions. |
| `title?` | `string \| undefined` | Inherited from ChartOptions. |
| `subtitle?` | `string \| undefined` | Inherited from ChartOptions. |
| `axes?` | `AxesOptions \| undefined` | Inherited from ChartOptions. |
| `legend?` | `boolean \| LegendOptions \| undefined` | Inherited from ChartOptions. |
| `tooltip?` | `boolean \| TooltipOptions<ChartDatum> \| undefined` | Inherited from ChartOptions. |
| `zoom?` | `boolean \| ZoomOptions \| undefined` | Inherited from ChartOptions. |
| `padding?` | `Padding \| undefined` | Inherited from ChartOptions. |
| `animation?` | `boolean \| AnimationOptions \| undefined` | Inherited from ChartOptions. |
| `palette?` | `readonly string[] \| undefined` | Inherited from ChartOptions. |
| `accessibility?` | `AccessibilityOptions \| undefined` | Inherited from ChartOptions. |
| `renderer?` | `RendererOption \| undefined` | Inherited from ChartOptions. |
| `pixelRatio?` | `number \| undefined` | Inherited from ChartOptions. |

## From a Grid Pro range selection

> **Note**
>
> Range selection is a [Grid Pro](https://docs.birchui.com/grid-pro/range-selection.md) feature. Install `RangeSelectionModule` and set `rangeSelection: true` on the grid. The methods below are optional members of `GridApi` that exist only when the module is installed, so call them with optional chaining.

Grid Pro exposes the selected ranges and their values:

| Method | Returns |
| --- | --- |
| `getCellRanges?.()` | The selected ranges as `{ startRow, endRow, startCol, endCol }`, with display row indexes and column IDs |
| `getRangeValues?.(rangeIndex?)` | The raw values of one range (the last one by default) as rows of cells |
| `onRangeChanged?.(listener)` | Subscribes to selection changes; returns an unsubscribe function |

`getRangeValues()` skips utility columns, such as the selection checkbox column and the master/detail toggle, and full-width rows. The headers are not included, so read them from the grid's display columns:

```ts title="chart-selection.ts"
import { createGrid, type ColumnDef, type GridApi } from '@birchui/core';
import { RangeSelectionModule } from '@birchui/grid-pro';
import { chartFromRange, createChart, type ChartApi } from '@birchui/charts';

interface RegionSales {
  region: string;
  q1: number;
  q2: number;
  q3: number;
  q4: number;
}

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

const money = (v: unknown) => usd.format(Number(v));

const columns: ColumnDef<RegionSales>[] = [
  { field: 'region', header: 'Region', width: 180 },
  { field: 'q1', header: 'Q1', type: 'number', format: money },
  { field: 'q2', header: 'Q2', type: 'number', format: money },
  { field: 'q3', header: 'Q3', type: 'number', format: money },
  { field: 'q4', header: 'Q4', type: 'number', format: money },
];

const grid = createGrid<RegionSales>(document.querySelector('#sales-grid')!, {
  columns,
  rows: regionSales,
  getRowId: (row) => row.region,
  modules: [RangeSelectionModule],
  rangeSelection: true,
});

const UTILITY_COLUMNS = new Set(['__select', '__detail']);

function rangeHeaders(api: GridApi<RegionSales>): string[] {
  const range = api.getCellRanges?.().at(-1);
  if (!range) return [];
  const display = api.getDisplayColumns().filter((column) => !UTILITY_COLUMNS.has(column.id));
  const from = display.findIndex((column) => column.id === range.startCol);
  const to = display.findIndex((column) => column.id === range.endCol);
  if (from < 0 || to < 0) return [];
  return display.slice(Math.min(from, to), Math.max(from, to) + 1).map((column) => column.header);
}

let chart: ChartApi | null = null;
const chartHost = document.querySelector<HTMLElement>('#selection-chart')!;

function chartSelection() {
  const values = grid.getRangeValues?.() ?? [];
  if (values.length === 0) return;
  const options = chartFromRange(values, rangeHeaders(grid), {
    title: 'Selected revenue',
    axes: { y: { labelFormatter: (v) => usd.format(Number(v)) } },
  });
  if (chart) chart.update(options);
  else chart = createChart(chartHost, options);
}

document.querySelector('#chart-selection')!.addEventListener('click', chartSelection);
```

Select **Region** through **Q2** for three regions and click the button: the region names become the category axis and Q1 and Q2 become two column series. Because `getRangeValues()` returns raw values, numbers reach the chart as numbers, not as the formatted currency strings shown in the cells.

### Keeping the chart in sync

To redraw the chart while the user changes the selection, subscribe to range changes. Debounce it so a drag does not rebuild the chart on every cell:

```ts
let pending = 0;
const unsubscribe = grid.onRangeChanged?.(({ ranges }) => {
  window.clearTimeout(pending);
  if (ranges.length === 0) return;
  pending = window.setTimeout(chartSelection, 150);
});
```

Call `unsubscribe?.()` and `chart?.destroy()` when the panel closes.

## Sparklines in grid cells

`sparklineSVG(values, options?)` returns a small, self-contained SVG document as a string: no axes, no legend, no title, and no chart instance to manage. It suits trend columns in a grid, where hundreds of cells each show a tiny chart.

```ts
import { sparklineSVG } from '@birchui/charts';

const svg = sparklineSVG([412, 398, 455, 471, 502, 488, 530], { type: 'area', width: 96, height: 24, color: '#1a7f37' });
```

| Option | Values | Default |
| --- | --- | --- |
| `type` | `'line'`, `'area'`, `'bar'` | `'line'` |
| `width`, `height` | Pixels (at least 8) | `120` × `28` |
| `color` | Any CSS color | First palette color |
| `theme` | `'light'`, `'dark'` | `'light'` |
| `lineWidth` | Stroke width in pixels | theme default |
| `label` | Series name used in the generated accessible summary, which becomes the SVG's `<title>` | `'Value'` |

`null` and `undefined` values leave gaps. All text in the SVG is escaped.

**`SparklineOptions`** (interface from `@birchui/charts`, full reference: https://docs.birchui.com/api/charts.md)

```ts
interface SparklineOptions
```

| Property | Type | Description |
| --- | --- | --- |
| `type?` | `'line' \| 'area' \| 'bar'` |  |
| `width?` | `number` |  |
| `height?` | `number` |  |
| `color?` | `string` |  |
| `theme?` | `'light' \| 'dark'` |  |
| `lineWidth?` | `number` |  |
| `label?` | `string` |  |
| `localeText?` | `LocaleTextInput` |  |

### In a Birch UI Grid column

Birch UI Grid inserts strings returned from a `cell` renderer as text, never as HTML, so convert the SVG string to a DOM node before returning it. Cells are re-rendered while scrolling, so cache the markup per row instead of rebuilding it on every render:

```ts title="trend-column.ts"
import { createGrid, type CellContext, type ColumnDef } from '@birchui/core';
import { sparklineSVG } from '@birchui/charts';

interface ProductSales {
  sku: string;
  product: string;
  weeklyUnits: number[];
  revenue: number;
}

const sparklineCache = new WeakMap<ProductSales, string>();

function trendCell({ row }: CellContext<ProductSales>): Node | null {
  if (!row) return null;
  let markup = sparklineCache.get(row);
  if (!markup) {
    const rising = row.weeklyUnits.at(-1)! >= row.weeklyUnits[0];
    markup = sparklineSVG(row.weeklyUnits, {
      width: 110,
      height: 24,
      color: rising ? '#1a7f37' : '#cf222e',
      label: `${row.product}, weekly units over ${row.weeklyUnits.length} weeks`,
    });
    sparklineCache.set(row, markup);
  }
  const template = document.createElement('template');
  template.innerHTML = markup;
  return template.content.firstElementChild;
}

const columns: ColumnDef<ProductSales>[] = [
  { field: 'sku', header: 'SKU', width: 110 },
  { field: 'product', flex: 1 },
  { id: 'trend', header: '12-week trend', width: 130, sortable: false, cell: trendCell },
  { field: 'revenue', type: 'number' },
];

createGrid<ProductSales>(document.querySelector('#products')!, {
  columns,
  rows: products,
  getRowId: (p) => p.sku,
});
```

Parsing the string with a `<template>` element is safe here because `sparklineSVG()` escapes every text and attribute value it writes. Keep that property in mind if you post-process the markup: do not concatenate unescaped data into it.

The cache is keyed by the row object, so a row replaced through `applyTransaction({ update })` gets a fresh sparkline automatically.

For a dark grid, pass `theme: 'dark'` so the default color and contrast match. For a full interactive chart in a small space, such as a dashboard tile with a tooltip, use `createChart()` with `sparkline: true` instead: it hides axes, legend and title, turns off zoom, defaults to a height of 32 pixels, and keeps tooltips and keyboard access.
