Birch UI v0.1
Pricing

Build a chart dashboard from a gridCharts

Drive several charts from the rows a Birch UI Grid shows, so filtering the grid updates the dashboard, and chart a selected range with chartFromRange.

Open .md

An operations dashboard usually starts as a table: one row per work order. This recipe puts three charts above a Birch UI Grid and keeps them in step with it. When the user filters or searches the grid, the charts show only the rows that are left. With Grid Pro, a fourth chart shows whatever range of cells the user selects.

Steps#

  1. Create the grid and the charts once.
  2. On the grid's modelUpdated event, collect the data rows from getAllDisplayRows().
  3. Aggregate them into small arrays and pass each to a chart with setData().
  4. Optionally, chart a selected range with chartFromRange().

The grid#

work-order-grid.ts
import { createGrid, type ColumnDef } from '@birchui/core';

export interface WorkOrder {
  id: string;
  depot: string;
  technician: string;
  jobType: string;
  completed: string;
  hours: number;
  revenue: number;
  firstTimeFix: boolean;
}

const gbp = new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'GBP', maximumFractionDigits: 0 });

const columns: ColumnDef<WorkOrder>[] = [
  { field: 'id', header: 'Work order', width: 120 },
  { field: 'depot', header: 'Depot', filter: true },
  { field: 'technician', header: 'Technician', filter: true },
  { field: 'jobType', header: 'Job type', filter: true },
  { field: 'completed', header: 'Completed', type: 'date' },
  { field: 'hours', header: 'Hours', type: 'number' },
  { field: 'revenue', header: 'Revenue', type: 'number', format: (v) => gbp.format(Number(v)) },
  { field: 'firstTimeFix', header: 'First-time fix', type: 'boolean' },
];

export const grid = createGrid<WorkOrder>(document.querySelector<HTMLElement>('#work-orders')!, {
  columns,
  rows: workOrders,
  getRowId: (row) => row.id,
});

The charts#

dashboard-charts.ts
import { createChart } from '@birchui/charts';

export const revenueByDepot = createChart(document.querySelector<HTMLElement>('#revenue-by-depot')!, {
  title: 'Revenue by depot',
  data: [],
  series: [{ type: 'column', xKey: 'depot', yKey: 'revenue', name: 'Revenue' }],
  height: 260,
});

export const jobMix = createChart(document.querySelector<HTMLElement>('#job-mix')!, {
  title: 'Jobs by type',
  data: [],
  series: [{ type: 'donut', xKey: 'jobType', yKey: 'jobs', name: 'Jobs' }],
  height: 260,
});

export const weeklyHours = createChart(document.querySelector<HTMLElement>('#weekly-hours')!, {
  title: 'Hours per week',
  data: [],
  series: [{ type: 'line', xKey: 'week', yKey: 'hours', name: 'Hours', markers: true }],
  height: 260,
});

Keep them in step#

dashboard.ts
import { grid, type WorkOrder } from './work-order-grid';
import { jobMix, revenueByDepot, weeklyHours } from './dashboard-charts';

function totals(rows: WorkOrder[], key: (row: WorkOrder) => string, value: (row: WorkOrder) => number) {
  const result = new Map<string, number>();
  for (const row of rows) result.set(key(row), (result.get(key(row)) ?? 0) + value(row));
  return [...result];
}

function weekStart(isoDate: string): string {
  const date = new Date(`${isoDate}T00:00:00Z`);
  date.setUTCDate(date.getUTCDate() - ((date.getUTCDay() + 6) % 7));
  return date.toISOString().slice(0, 10);
}

let pending = 0;

function refreshCharts() {
  const rows = grid
    .getAllDisplayRows()
    .filter((row) => row.kind === 'data' && row.data)
    .map((row) => row.data as WorkOrder);

  revenueByDepot.setData(
    totals(rows, (r) => r.depot, (r) => r.revenue)
      .map(([depot, revenue]) => ({ depot, revenue }))
      .sort((x, y) => y.revenue - x.revenue),
  );
  jobMix.setData(totals(rows, (r) => r.jobType, () => 1).map(([jobType, jobs]) => ({ jobType, jobs })));
  weeklyHours.setData(
    totals(rows, (r) => weekStart(r.completed), (r) => r.hours)
      .map(([week, hours]) => ({ week, hours: Math.round(hours * 10) / 10 }))
      .sort((x, y) => x.week.localeCompare(y.week)),
  );
}

grid.on('modelUpdated', () => {
  window.clearTimeout(pending);
  pending = window.setTimeout(refreshCharts, 100);
});
refreshCharts();

modelUpdated fires after every run of the grid's row pipeline: new rows, transactions, sorting, filtering, paging and grouping. The short debounce turns a burst of filter keystrokes into one redraw.

Chart a selected range#

With Grid Pro's range selection, chartFromRange() builds chart options from the selected cells. Numeric columns become series and the first text column becomes the category axis:

selection-chart.ts
import { RangeSelectionModule } from '@birchui/grid-pro';
import { chartFromRange, createChart, type ChartApi } from '@birchui/charts';

let selectionChart: ChartApi | null = null;

function chartSelection() {
  const values = grid.getRangeValues?.() ?? [];
  const range = grid.getCellRanges?.().at(-1);
  if (!range || values.length === 0) return;
  const display = grid.getDisplayColumns();
  const from = display.findIndex((column) => column.id === range.startCol);
  const to = display.findIndex((column) => column.id === range.endCol);
  const headers = display.slice(Math.min(from, to), Math.max(from, to) + 1).map((column) => column.header);
  const options = chartFromRange(values, headers, { title: 'Selected work orders' });
  if (selectionChart) selectionChart.update(options);
  else selectionChart = createChart(document.querySelector<HTMLElement>('#selection-chart')!, options);
}

Create the grid with modules: [RangeSelectionModule] and rangeSelection: true for these methods to exist. Grid integration covers utility columns and live updates.

How it works#

  • getAllDisplayRows() returns the rows after filtering and sorting, across all pages, so the charts match what the grid would show. getRows() would return every source row, ignoring filters.
  • Group and total rows have kind other than 'data' and no row object of their own; filtering on kind === 'data' skips them.
  • setData() replaces a chart's data and keeps its series, axes and theme, so the charts are created once.

Pitfalls#

  • Aggregate before charting. Passing thousands of raw rows to a column chart draws thousands of bars. Group them first, as above.
  • Formatted values. Read raw values from the row objects, not getFormattedValue(), so numbers reach the chart as numbers.
  • Grouped grids. With row grouping, the rows of a collapsed group are not display rows. Read the top-level group rows' group.leaves instead, which hold every row in the group.
  • Clean up. Call destroy() on every chart and the grid when the dashboard is removed.

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