Birch UI v0.1
Pricing

PivotingPro

Turn flat records into a cross-tab report with row groups, pivot columns, aggregated values and totals.

Open .md

Pivot mode reshapes your rows into a cross-tab. Pick fields for the rows (for example region and country), fields whose values become columns (for example year and quarter) and the values to aggregate in each cell (for example sum of revenue). The grid generates the columns, computes every cell and keeps the result live as data and filters change.

Pivot: revenue by region and quarter

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/pivot.ts
import { createGrid, type ColumnDef, type PivotOptions } from '@birchui/core';
import { AggregationModule, PivotModule } from '@birchui/grid-pro';
import {
  docsTheme,
  field,
  formatCurrency,
  layout,
  makeOrders,
  onDocsThemeChange,
  revenueOf,
  type Order,
} from './_shared';

export const meta = { title: 'Pivot: revenue by region and quarter', height: 480 };

const columns: ColumnDef<Order>[] = [
  { field: 'region', header: 'Region' },
  { field: 'category', header: 'Category' },
  { field: 'quarter', header: 'Quarter' },
  { field: 'status', header: 'Status' },
  { field: 'quantity', header: 'Units', type: 'number' },
  { id: 'revenue', header: 'Revenue', type: 'number', valueGetter: revenueOf, format: formatCurrency },
];

const LAYOUTS: Record<string, PivotOptions> = {
  'Region by quarter': {
    enabled: true,
    rows: ['region'],
    columns: ['quarter'],
    values: [{ colId: 'revenue', aggFunc: 'sum' }],
    totals: true,
  },
  'Category by status': {
    enabled: true,
    rows: ['category'],
    columns: ['status'],
    values: [
      { colId: 'quantity', aggFunc: 'sum' },
      { colId: 'revenue', aggFunc: 'sum' },
    ],
    totals: true,
  },
  'Region and category by quarter': {
    enabled: true,
    rows: ['region', 'category'],
    columns: ['quarter'],
    values: [{ colId: 'revenue', aggFunc: 'sum' }],
    totals: true,
  },
  'Pivot off': { enabled: false },
};

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const choice = document.createElement('select');
  for (const name of Object.keys(LAYOUTS)) choice.add(new Option(name, name));
  toolbar.append(field('Layout', choice));
  const grid = createGrid<Order>(body, {
    columns,
    rows: makeOrders(8000, 5),
    getRowId: (order) => order.id,
    modules: [AggregationModule, PivotModule],
    pivot: LAYOUTS['Region by quarter'],
    groupDefaultExpanded: -1,
    theme: docsTheme(),
    ariaLabel: 'Revenue pivot table',
  });
  const describe = () => {
    status.textContent = `${grid.getDisplayColumns().length} columns generated from ${grid.getRows().length.toLocaleString()} orders.`;
  };
  const onChange = () => grid.update({ pivot: LAYOUTS[choice.value] });
  choice.addEventListener('change', onChange);
  const off = grid.on('modelUpdated', describe);
  describe();
  const stopTheme = onDocsThemeChange((theme) => grid.update({ theme }));
  return () => {
    choice.removeEventListener('change', onChange);
    off();
    stopTheme();
    grid.destroy();
  };
}

A first pivot#

revenue-pivot.ts
import { createGrid, type ColumnDef } from '@birchui/core';
import { PivotModule } from '@birchui/grid-pro';

interface Sale {
  id: string;
  region: string;
  country: string;
  category: 'Hardware' | 'Software' | 'Services';
  product: string;
  year: number;
  quarter: 'Q1' | 'Q2' | 'Q3' | 'Q4';
  units: number;
  revenue: number;
}

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

const columns: ColumnDef<Sale>[] = [
  { field: 'region', header: 'Region' },
  { field: 'country', header: 'Country' },
  { field: 'category', header: 'Category' },
  { field: 'year', header: 'Year', type: 'number', format: (v) => String(v ?? '') },
  { field: 'quarter', header: 'Quarter' },
  { field: 'units', header: 'Units', type: 'number' },
  { field: 'revenue', header: 'Revenue', type: 'number', format: (v) => (v == null ? '' : usd.format(Number(v))) },
];

const api = createGrid(container, {
  columns,
  rows: sales,
  getRowId: (row) => row.id,
  modules: [PivotModule],
  pivot: {
    enabled: true,
    rows: ['region', 'country'],
    columns: ['year', 'quarter'],
    values: [{ colId: 'revenue', aggFunc: 'sum' }],
    totals: true,
  },
});

The result has one row per region, expandable to its countries, and one column per year and quarter that occurs in the data, headed for example 2026 › Q1 › Revenue. With totals: true, a Total › Revenue column follows, and a grand total row closes the table.

In pivot mode your original columns are hidden. The grid shows a group column, headed with the row fields (Region › Country), followed by the generated columns.

The pivot options#

PivotOptionsinterface@birchui/coreFull reference
PropertyTypeDescription
enabledoptionalboolean—
rowsoptionalstring[]—
columnsoptionalstring[]—
valuesoptionalPivotValue[]—
totalsoptionalboolean—
Property What it does
enabled Turns pivot mode on. While it is false or missing, the grid shows your normal columns and the rest of the configuration is kept for later.
rows Column ids to group rows by, outermost first. Leave empty for a single summary row.
columns Column ids whose distinct values become generated columns. With two ids, every combination that occurs in the data becomes a column, nested under the first.
values The measures to show for each pivot column. Each entry names a column and an aggregation function.
totals Adds a total column per value, aggregated across all pivot columns, and a grand total row.

Each entry in values is a PivotValue:

PivotValueinterface@birchui/coreFull reference
PropertyTypeDescription
colIdstring—
aggFuncoptionalAggFuncName | AggFunc—

aggFunc accepts the same built-in names and custom functions as column aggregation. When it is omitted, the column's own aggFunc is used, and when that is missing too, the value is summed.

Column ids that do not exist are skipped with one console warning each, as are unknown aggregation names.

Toggle pivot mode#

Because enabled is separate from the configuration, a "Pivot" switch in your toolbar is a one-line update:

TypeScript
const pivotToggle = document.querySelector<HTMLInputElement>('#pivot-mode')!;

pivotToggle.addEventListener('change', () => {
  const current = api.getOptions().pivot ?? {};
  api.update({ pivot: { ...current, enabled: pivotToggle.checked } });
});

Change the layout the same way, for example when a user picks a different measure:

TypeScript
api.update({
  pivot: {
    enabled: true,
    rows: ['category'],
    columns: ['region'],
    values: [
      { colId: 'revenue', aggFunc: 'sum' },
      { colId: 'units', aggFunc: 'avg' },
    ],
    totals: true,
  },
});

ColumnDef also declares pivot and pivotIndex properties. The pivot module takes its layout from the pivot grid option only, so put rows, columns and values there.

The pivot API#

PivotModule adds two methods to the grid API. They are optional members of GridApi, so call them with ?.:

Method Purpose
setPivot(options) Apply a pivot layout as a runtime override, for example from a field picker. enabled defaults to true. Pass null to return to the pivot option. A later update({ pivot }) replaces the override.
getPivotResult() The current pivot as a plain matrix, or null when pivot mode is off.
TypeScript
api.setPivot?.({ rows: ['country'], columns: ['quarter'], values: [{ colId: 'units' }] });

const matrix = api.getPivotResult?.();
if (matrix) {
  console.log(matrix.headers);
  console.table(matrix.rows);
}

The matrix has headers (one flat header per column), headerRows (the header split into levels, for multi-row headers), columnIds and rows. Each row starts with the row-field labels, followed by one value per generated column, with the grand total last. It is a convenient input for charts and custom reports.

Generated columns#

Pivot columns are created from the data, so their number changes when the data does. A few rules make them predictable:

  • Order. Pivot keys are sorted ascending. A pivot column's comparator is used when it has one; otherwise numbers sort numerically and text with a natural, case-insensitive collation, so Q2 comes before Q10.
  • Labels. Keys are shown through the pivot column's format function, so a date field can produce Mar 2026 headings.
  • Headers. A header is the path of key labels followed by the value column's header (or its id), joined with ›, for example 2026 › Q3 › Revenue. When the same column appears twice in values, the function name is added: Units (sum) and Units (avg).
  • Blanks. Rows with an empty pivot key are collected under a (Blanks) column.
  • Totals. With totals: true, the total columns come last and are headed Total › <value>.
  • Formatting. Generated columns are right-aligned, sortable and at least 150 pixels wide. They keep the value column's type and format, except for count and distinct, which are shown as plain numbers.

Generated column ids encode the pivot keys and the value, so they are stable for the same data, and you can pass them to setSort(). Read them from api.getDisplayColumns() rather than writing them by hand:

TypeScript
const totalColumn = api.getDisplayColumns().find((column) => column.header.startsWith('Total'));
if (totalColumn) api.setSort([{ colId: totalColumn.id, dir: 'desc' }]);

Rows, totals and filters#

  • Row groups in pivot mode are group rows: they expand and collapse, honour groupDefaultExpanded, and fire rowExpanded. The innermost level is not expandable, because pivot mode shows aggregates, not individual records.
  • With an empty rows list, the pivot is a single summary row.
  • Filters apply before pivoting. Filter by category to get a hardware-only report, even though category is not part of the layout. Your original columns, and their header filters, are hidden while pivot mode is on, so set column filters with setFilter() or before switching.
  • The quick filter searches every one of your columns, including the hidden ones, so a search box above the grid keeps narrowing the rows that feed the pivot. Generated pivot columns are not searched.
  • Pivot mode takes precedence over row grouping and tree data. Their options are kept and apply again when pivot mode is turned off.

Pivot with custom aggregation#

Any custom AggFunc works in a pivot cell. Here each cell shows the revenue share of the best-selling product:

TypeScript
import type { AggFunc } from '@birchui/core';

const topProductShare: AggFunc = (_values, rows: readonly Sale[]) => {
  const byProduct = new Map<string, number>();
  let total = 0;
  for (const sale of rows) {
    byProduct.set(sale.product, (byProduct.get(sale.product) ?? 0) + sale.revenue);
    total += sale.revenue;
  }
  return total ? Math.max(...byProduct.values()) / total : null;
};

api.update({
  pivot: {
    enabled: true,
    rows: ['region'],
    columns: ['quarter'],
    values: [{ colId: 'revenue', aggFunc: topProductShare }],
  },
});

Because the generated columns keep the value column's format, give such a measure its own column definition with a percentage formatter, for example a hidden revenueShare column whose valueGetter returns row.revenue.

Export a pivot#

Excel export writes the columns and rows the grid shows, so a pivot exports as a cross-tab with its generated headers, group labels and totals.

TypeScript
await api.exportExcel?.({ fileName: 'revenue-by-quarter.xlsx', sheetName: 'Pivot' });

Performance#

The pivot engine works on row indices and computes each cell with a streaming accumulator, without copying your rows. The column layout is cached and only rebuilt when the pivot configuration, the columns or the row array change, so filtering and sorting a 100,000-row pivot stays interactive. If the pivot columns produce thousands of combinations, column virtualization keeps rendering cheap, but consider coarser column fields for readability.

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