Birch UI v0.1
Pricing

InteractionCharts

Tooltips and custom tooltip formatters, legend toggling, drag and wheel zoom, panning, resetting, and controlling the zoom from code.

Open .md

Charts are interactive by default: a tooltip follows the pointer, legend entries toggle series, and the x axis can be zoomed and panned with the mouse, touch or keyboard. Each part can be configured or turned off.

Revenue by region and category

Loading demo…

View source

Sample data and small UI helpers are imported from the docs' demos/_shared.ts and demos/_scheduler-data.ts files.

demos/chart-bar-pie.ts
import { createChart } from '@birchui/charts';
import { currency, docsTheme, layout, onDocsThemeChange } from './_shared';

export const meta = { title: 'Revenue by region and category', height: 440 };

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

interface CategoryShare {
  category: string;
  revenue: number;
}

const regions: RegionRevenue[] = [
  { region: 'North America', q1: 1_910_000, q2: 1_987_000, q3: 2_048_000, q4: 2_212_000 },
  { region: 'Europe', q1: 2_716_000, q2: 2_624_000, q3: 2_703_000, q4: 2_890_000 },
  { region: 'Asia Pacific', q1: 1_869_000, q2: 1_967_000, q3: 2_201_000, q4: 2_334_000 },
  { region: 'Latin America', q1: 1_257_000, q2: 1_211_000, q3: 1_386_000, q4: 1_402_000 },
];

const categories: CategoryShare[] = [
  { category: 'Furniture', revenue: 12_480_000 },
  { category: 'Electronics', revenue: 15_930_000 },
  { category: 'Accessories', revenue: 4_310_000 },
];

const short = (value: unknown) => (typeof value === 'number' ? `$${(value / 1_000_000).toFixed(1)}M` : String(value));

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  body.style.display = 'grid';
  body.style.gridTemplateColumns = 'minmax(0, 3fr) minmax(0, 2fr)';
  const left = document.createElement('div');
  const right = document.createElement('div');
  left.style.minHeight = right.style.minHeight = '0';
  body.append(left, right);
  toolbar.append('Click a legend entry to hide a series. Click a bar or slice for its value.');

  const columns = createChart<RegionRevenue>(left, {
    title: 'Revenue by region, 2026',
    data: regions,
    series: (['q1', 'q2', 'q3', 'q4'] as const).map((quarter) => ({
      type: 'column' as const,
      xKey: 'region' as const,
      yKey: quarter,
      name: quarter.toUpperCase(),
    })),
    axes: { x: { type: 'category' }, y: { labelFormatter: short } },
    theme: docsTheme(),
    height: '100%',
  });
  const donut = createChart<CategoryShare>(right, {
    title: 'Share by category',
    data: categories,
    series: [{ type: 'donut', xKey: 'category', yKey: 'revenue', innerRadius: 0.55, labels: true }],
    theme: docsTheme(),
    height: '100%',
  });

  const offs = [
    columns.on('pointClick', ({ point }) => {
      status.textContent = `${String(point.x)}, ${point.seriesName}: ${currency.format(Number(point.y))}`;
    }),
    donut.on('pointClick', ({ point }) => {
      status.textContent = `${String(point.x)}: ${currency.format(Number(point.y))}`;
    }),
    columns.on('legendToggle', ({ name, visible }) => {
      status.textContent = `${name} ${visible ? 'shown' : 'hidden'}`;
    }),
  ];
  status.textContent = 'Values appear here.';
  const stopTheme = onDocsThemeChange((theme) => {
    columns.update({ theme });
    donut.update({ theme });
  });
  return () => {
    for (const off of offs) off();
    stopTheme();
    columns.destroy();
    donut.destroy();
  };
}

Tooltip#

Cartesian charts show a shared tooltip: a crosshair snaps to the nearest x value and the tooltip lists every visible series at that position. Pie, donut and heatmap charts show the hovered slice or cell. The nearest point is found by binary search over the sorted x values, and scatter plots use a spatial index, so tooltips stay instant on large datasets.

TypeScript
createChart(container, {
  data,
  series,
  tooltip: { shared: false },
});
Option Meaning Default
tooltip false turns tooltips off; an object configures them on
tooltip.shared true lists every series at the hovered x value; false shows only the nearest point true
tooltip.formatter Builds the tooltip content yourself built-in layout
TooltipOptionsinterface@birchui/chartsFull reference
PropertyTypeDescription
enabledoptionalboolean—
sharedoptionalboolean—
formatteroptional(context: TooltipContext<TDatum>) => string | null | undefined—

Custom tooltips#

formatter(context) receives the tooltip title (the formatted x value) and one entry per point, each with the series name and color, the raw x and y, their formatted labels, and the original datum. It returns:

  • a string, which becomes the tooltip's content,
  • null, to hide the tooltip for this position,
  • undefined, to fall back to the built-in tooltip.

If the formatter throws, the error is reported with console.error and the built-in tooltip is shown.

orders-tooltip.ts
import { createChart, escapeHtml, type TooltipContext } from '@birchui/charts';

interface DailyOrders {
  date: string;
  orders: number;
  topCustomer: string;
}

const formatTooltip = ({ title, points }: TooltipContext<DailyOrders>) => {
  if (points.length === 0) return null;
  const rows = points
    .map(
      (point) => `
        <div class="lq-chart-tooltip-row">
          <span class="lq-chart-tooltip-swatch" style="background:${escapeHtml(point.color)}"></span>
          <span class="lq-chart-tooltip-label">${escapeHtml(point.seriesName)}</span>
          <span class="lq-chart-tooltip-value">${escapeHtml(point.yLabel)}</span>
        </div>
        <div class="order-top-customer">Top customer: ${escapeHtml(point.datum.topCustomer)}</div>`,
    )
    .join('');
  return `<div class="lq-chart-tooltip-title">${escapeHtml(title)}</div>${rows}`;
};

createChart<DailyOrders>(document.querySelector<HTMLElement>('#orders')!, {
  data: dailyOrders,
  series: [{ type: 'column', xKey: 'date', yKey: 'orders', name: 'Orders' }],
  tooltip: { formatter: formatTooltip },
});

escapeHtml(text) replaces &, <, >, " and ' with HTML entities, which makes a value safe inside element content and inside quoted attributes. It does not make a value safe inside a <script> element, an unquoted attribute or a URL attribute such as href; never put untrusted data there.

The class names above (lq-chart-tooltip-title, lq-chart-tooltip-row, lq-chart-tooltip-swatch, lq-chart-tooltip-label, lq-chart-tooltip-value) are the ones the built-in tooltip uses, so a custom tooltip that reuses them inherits the theme's styling.

TooltipContextinterface@birchui/chartsFull reference
PropertyTypeDescription
titlestring—
pointsTooltipPoint<TDatum>[]—

Legend#

The legend lists one entry per series, or one per slice for pie and donut charts. By default (legend not set) cartesian charts show it when they have two or more series; pie and donut charts always show it.

TypeScript
createChart(container, { data, series, legend: { position: 'right' } });
createChart(container, { data, series, legend: false });
Option Values Default
legend true, false or { enabled, position } automatic
legend.position 'top', 'bottom', 'left', 'right' 'bottom'

Legend entries are buttons. Clicking one, or pressing Enter or Space on it, hides or shows that series or slice, and the value axes rescale to what is visible. Hovering or focusing an entry highlights its series in the plot.

Each toggle fires legendToggle:

TypeScript
chart.on('legendToggle', ({ seriesId, name, visible, sliceIndex }) => {
  analytics.track('chart_legend_toggle', { chart: 'revenue', series: name, visible });
});

For pie and donut slices, seriesId is the pie series and sliceIndex the slice's position. To toggle from code, call setSeriesVisible(id, visible) with a series ID, or with a slice label for pie charts.

Zoom and pan#

The x axis of cartesian charts can be zoomed and panned. The value axes rescale to the visible range.

Gesture Action
Drag across the plot Zoom to the dragged range
Ctrl or Cmd + scroll wheel, or pinch Zoom in or out around the pointer
Shift + drag, or horizontal scroll, or Shift + scroll (while zoomed) Pan
One-finger drag on touch screens (while zoomed) Pan
Double-click, or the Reset zoom button Reset to the full range
+ / - with the chart focused Zoom in or out around the focused point
0 with the chart focused Reset

A plain scroll wheel never zooms, so charts do not trap page scrolling. The Reset zoom button appears while the chart is zoomed.

Turn the whole feature off with zoom: false, or individual gestures with an object:

TypeScript
createChart(container, {
  data,
  series,
  zoom: { drag: true, wheel: false, pan: true },
});
ZoomOptionsinterface@birchui/chartsFull reference
PropertyTypeDescription
enabledoptionalboolean—
dragoptionalboolean—
wheeloptionalboolean—
panoptionalboolean—

Zooming is turned off for sparklines.

Zooming from code#

TypeScript
chart.setZoom([Date.parse('2026-03-01'), Date.parse('2026-03-31')]);
const range = chart.getZoom();
chart.resetZoom();

The range is [min, max] in x axis units: category indexes on category axes ([0, 11] for the first twelve categories), numbers on linear axes, and timestamps in milliseconds on time axes. getZoom() returns null when the chart shows the full range, and setZoom(null) resets it like resetZoom().

Every change fires zoomChange with the new range and its source, which makes it easy to keep several charts in sync:

TypeScript
const charts = [ordersChart, revenueChart, sessionsChart];

for (const chart of charts) {
  chart.on('zoomChange', ({ range, source }) => {
    if (source === 'api') return;
    for (const other of charts) if (other !== chart) other.setZoom(range);
  });
}

source is one of 'drag', 'wheel', 'pinch', 'pan', 'keyboard', 'api' and 'reset'. Checking for 'api' as above prevents charts from echoing each other's updates.

Clicking and hovering points#

TypeScript
chart.on('pointClick', ({ point, event }) => {
  router.navigate(`/orders?date=${encodeURIComponent(String(point.x))}`);
});

chart.on('seriesHover', ({ seriesId, point }) => {
  details.textContent = point ? `${point.seriesName}: ${String(point.y)}` : '';
});

pointClick fires for mouse clicks and for Enter or Space on a point focused with the keyboard, so event is a MouseEvent or a KeyboardEvent. seriesHover fires when the hovered point changes, with null when the pointer leaves the plot. See Accessibility for keyboard navigation and API & events for the payloads.

↑ ↓ to move, Enter to open, Esc to close