# Pivot Studio overview

> A pivot-first report builder for embedding analytics in your product, with a field list, subtotals, drill-through, conditional formatting, saved reports and Excel export.

Birch UI Pivot Studio is a report builder that end users drive themselves. They drag fields into rows, columns, values and filters and get an interactive pivot table with subtotals, drill-through to the underlying records, conditional formatting, saved reports and styled Excel export. It runs entirely in the browser, needs no server or OLAP cube, and pivots a million records in well under a second.

**Live demo: Retail sales report** (runs on the HTML version of this page). Source of `demos/pivot-studio-retail.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createPivotStudio, type PivotReport } from '@birchui/pivot-studio';
import { docsTheme, layout, onDocsThemeChange, seededRandom } from './_shared';

export const meta = { title: 'Retail sales report', height: 600 };

interface SaleRecord {
  region: string;
  store: string;
  category: string;
  month: string;
  quarter: string;
  revenue: number;
  units: number;
  margin: number;
}

const STORES: [string, string][] = [
  ['North', 'Leeds Trinity'],
  ['North', 'Manchester Arndale'],
  ['North', 'Newcastle Eldon Square'],
  ['South', 'Brighton Churchill Square'],
  ['South', 'Southampton West Quay'],
  ['London', 'Covent Garden'],
  ['London', 'Westfield Stratford'],
  ['Scotland', 'Edinburgh St James'],
  ['Scotland', 'Glasgow Buchanan'],
];

const CATEGORIES: [string, number, number][] = [
  ['Outerwear', 89, 0.46],
  ['Footwear', 74, 0.41],
  ['Knitwear', 52, 0.52],
  ['Accessories', 24, 0.61],
  ['Denim', 58, 0.48],
];

function makeSales(): SaleRecord[] {
  const random = seededRandom(31);
  const records: SaleRecord[] = [];
  for (let m = 0; m < 12; m++) {
    const month = `2026-${String(m + 1).padStart(2, '0')}`;
    const quarter = `Q${Math.floor(m / 3) + 1}`;
    const season = m >= 9 || m <= 1 ? 1.35 : m >= 5 && m <= 7 ? 0.85 : 1;
    for (const [region, store] of STORES) {
      for (const [category, price, marginRate] of CATEGORIES) {
        const units = Math.round((40 + random() * 160) * season * (category === 'Outerwear' ? season : 1));
        const revenue = Math.round(units * price * (0.9 + random() * 0.2));
        records.push({
          region,
          store,
          category,
          month,
          quarter,
          revenue,
          units,
          margin: Math.round(revenue * marginRate),
        });
      }
    }
  }
  return records;
}

const report: PivotReport = {
  slice: {
    rows: [{ field: 'region' }, { field: 'store' }],
    columns: [{ field: 'quarter' }],
    values: [
      { field: 'revenue', aggregation: 'sum', caption: 'Revenue' },
      { field: 'margin', aggregation: 'sum', showAs: 'percentOfColumnTotal', caption: 'Margin share' },
    ],
  },
  formats: { revenue: { style: 'currency', currency: 'GBP', decimals: 0 } },
};

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  toolbar.append('Drag fields between Rows, Columns and Values, or click a cell to drill through to its records.');
  const studio = createPivotStudio<SaleRecord>(body, {
    data: makeSales(),
    report,
    theme: docsTheme(),
    height: '100%',
    fileName: 'retail-sales-2026',
    ariaLabel: 'Retail sales pivot report',
  });
  const offs = [
    studio.on('pivotUpdated', () => {
      const slice = studio.getReport().slice;
      const names = (list: { field: string }[] | undefined) => (list ?? []).map((f) => f.field).join(', ') || 'none';
      status.textContent = `Rows: ${names(slice.rows)}. Columns: ${names(slice.columns)}. Values: ${names(slice.values)}.`;
    }),
    studio.on('error', ({ message }) => {
      status.textContent = message;
    }),
  ];
  status.textContent = 'Loading 540 sales records…';
  const stopTheme = onDocsThemeChange((theme) => studio.update({ theme }));
  return () => {
    for (const off of offs) off();
    stopTheme();
    studio.destroy();
  };
}
```

## Install

```bash
npm install @birchui/core @birchui/license @birchui/grid-pro @birchui/excel @birchui/pivot-studio
```

The table is rendered by Birch UI Grid (`@birchui/core`) and Excel files are written by the Excel Engine (`@birchui/excel`). `@birchui/grid-pro` is installed because Pivot Studio shares a few constants with it; Pivot Studio installs no Grid Pro modules and you do not need a Grid Pro license. Pivot Studio is about 41 KB minified and gzipped, styles included, not counting those packages.

## Quick start: a retail sales report

```ts title="sales-report.ts"
import { createPivotStudio, type PivotReport } from '@birchui/pivot-studio';

interface Sale {
  orderId: string;
  orderDate: string;
  region: string;
  store: string;
  category: string;
  product: string;
  channel: string;
  revenue: number;
  units: number;
  margin: number;
}

const sales: Sale[] = await fetch('/api/sales?year=2026').then((response) => response.json());

const report: PivotReport = {
  slice: {
    rows: [{ field: 'region', sortBy: { measure: 'sum(revenue)', dir: 'desc' } }, { field: 'store' }],
    columns: [{ field: 'orderDate.year' }, { field: 'orderDate.quarter' }],
    values: [
      { field: 'revenue', format: { style: 'currency', currency: 'GBP', decimals: 0 } },
      { field: 'units' },
      { field: 'margin', showAs: 'percentOfColumnTotal', caption: 'Margin share' },
    ],
    filters: [{ field: 'channel' }, { field: 'category' }],
  },
  filters: { channel: { exclude: ['Marketplace'] } },
  conditionalFormats: [{ type: 'dataBar', measure: 'sum(revenue)' }],
};

const studio = createPivotStudio<Sale>(document.querySelector<HTMLElement>('#sales-report')!, {
  data: sales,
  report,
  fileName: 'store-sales-2026',
  height: 640,
});

studio.on('reportChange', ({ report }) => localStorage.setItem('store-sales-report', JSON.stringify(report)));
studio.on('drillThrough', ({ records }) => console.info(`${records.length} orders behind this cell`));
```

The widget fills its container, so give the container a height or pass `height`. Styles are injected automatically; to load them yourself, pass `injectStyles: false` and import `@birchui/pivot-studio/styles.css` together with `@birchui/core/styles.css`.

Without a `report`, the field list is shown with every detected field and an empty table, ready for users to build their own report.

## What users can do

| Area | Features |
| --- | --- |
| Data | Arrays of objects, CSV text or JSON, with field types detected and a year › quarter › month › day hierarchy for dates. See [Data](https://docs.birchui.com/pivot-studio/data.md). |
| Field list | A searchable list and four zones (Filters, Columns, Rows, Values), by drag and drop or entirely from the keyboard. See [Field list](https://docs.birchui.com/pivot-studio/field-list.md). |
| Values | Sum, count, average, min, max, distinct count and median, shown as is, as percentages of totals, as running totals or as differences. See [Calculations](https://docs.birchui.com/pivot-studio/calculations.md). |
| Filters and sorting | Member checklists, label, value and top-N filters; sorting by label or by any measure. See [Filtering & sorting](https://docs.birchui.com/pivot-studio/filtering-and-sorting.md). |
| Table | Compact, outline and tabular layouts, subtotals and grand totals, number formats, color scales, data bars and thresholds. See [Totals & formatting](https://docs.birchui.com/pivot-studio/totals-and-formatting.md). |
| Drill-through | The records behind any value, with CSV and Excel export. See [Drill-through & export](https://docs.birchui.com/pivot-studio/drill-through-and-export.md). |
| Reports | Save and open reports as JSON. See [Reports](https://docs.birchui.com/pivot-studio/saving-reports.md). |
| Charts | An optional pivot chart through `@birchui/pivot-studio/charts`. See [Pivot charts](https://docs.birchui.com/pivot-studio/charts.md). |

## The widget contract

`createPivotStudio(container, options)` returns a `PivotStudioApi`. Like every Birch UI widget it has:

| Member | Description |
| --- | --- |
| `element` | The widget's root element |
| `update(partial)` | Apply option changes without recreating the widget |
| `on(event, listener)` | Subscribe to an event; returns an unsubscribe function |
| `destroy()` | Remove the widget and release its listeners, worker and license check |

The API adds methods for data, reports, fields, filters, layout and export; see [API & events](https://docs.birchui.com/pivot-studio/api.md).

`pivotStudioDefinition` describes the widget for framework adapters and custom elements. Its name is `BirchPivotStudio`, its tag name `birchui-pivot-studio`, and its events are `ready`, `reportChange`, `cellClick`, `drillThrough`, `dataLoaded`, `pivotUpdated` and `error` (also exported as `PIVOT_STUDIO_EVENTS`).

After creation the events arrive in a fixed order: `dataLoaded`, then `pivotUpdated` for the first computation, then `ready`. All three fire after `createPivotStudio()` returns, so listeners attached right away receive them.

## Options

| Option | Default | Meaning |
| --- | --- | --- |
| `data` | none | Records, CSV text or JSON text. See [Data](https://docs.birchui.com/pivot-studio/data.md). |
| `dataFormat` | `'auto'` | `'auto'`, `'array'`, `'csv'` or `'json'` |
| `csvDelimiter` | sniffed | Field delimiter for CSV text |
| `fields` | detected | Captions, types, formats and date parts per field |
| `report` | empty | The initial report. See [Reports](https://docs.birchui.com/pivot-studio/saving-reports.md). |
| `theme` | `'light'` | `'light'`, `'dark'` or `'auto'` |
| `density` | `'normal'` | `'compact'`, `'normal'` or `'comfortable'` |
| `locale` | browser locale | Number, date and month formatting |
| `height` | container height | Pixels or any CSS length |
| `fieldList` | `true` | `false` hides the field list; users can still open it from the toolbar's Fields button |
| `toolbar` | `true` | `false` hides the toolbar |
| `drillThrough` | `true` | `false` turns off the drill-through dialog |
| `worker` | `false` | Aggregate in a Web Worker. See [Performance](https://docs.birchui.com/pivot-studio/performance.md). |
| `fileName` | `'pivot-report'` | Base name for exported and saved files |
| `ariaLabel` | `'Pivot report'` | Accessible name of the widget region |
| `plugins` | none | Plugins such as the [pivot chart](https://docs.birchui.com/pivot-studio/charts.md); set at creation only |
| `injectStyles` | `true` | `false` to load the CSS yourself |
| `licenseKey` | the key from `setLicenseKey()` | See [Licensing](#licensing) |

**`PivotStudioOptions`** (interface from `@birchui/pivot-studio`, full reference: https://docs.birchui.com/api/pivot-studio.md)

```ts
interface PivotStudioOptions<TRecord = PivotRecord>
```

| Property | Type | Description |
| --- | --- | --- |
| `data?` | `readonly TRecord[] \| string` |  |
| `dataFormat?` | `DataFormat` |  |
| `csvDelimiter?` | `string` |  |
| `dataLimits?` | `Partial<DataLimits>` |  |
| `fields?` | `FieldDefinition[]` |  |
| `report?` | `PivotReport` |  |
| `licenseKey?` | `string` |  |
| `theme?` | `'light' \| 'dark' \| 'auto'` |  |
| `density?` | `'compact' \| 'normal' \| 'comfortable'` |  |
| `locale?` | `string` |  |
| `height?` | `number \| string` |  |
| `fieldList?` | `boolean` |  |
| `toolbar?` | `boolean` |  |
| `worker?` | `boolean` |  |
| `drillThrough?` | `boolean` |  |
| `injectStyles?` | `boolean` |  |
| `ariaLabel?` | `string` |  |
| `fileName?` | `string` |  |
| `plugins?` | `PivotStudioPlugin[]` |  |
| `localeText?` | `LocaleTextInput` |  |
| `rtl?` | `boolean` |  |

## Licensing

> **Pivot Studio: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md**
>
> Birch UI Pivot Studio is a commercial product: **$349 per developer, paid once**, with free updates forever and unlimited apps and end users. Team licenses (up to 5 developers) are $1,299 and Company licenses (unlimited developers) are $3,499. Pivot Studio is also part of Birch UI Complete ($999), which includes every product.

Each widget checks its license when it is created by calling `checkLicense('pivot-studio', { key, host })` from `@birchui/license`, with the widget's root element as host. The check runs in the browser and never makes a network request.

- Pivot Studio checks only its own `pivot-studio` license. It never checks for Grid Pro, and a Pivot Studio key also covers the Excel export it performs.
- Pass the key with `licenseKey`, or call `setLicenseKey(key)` from `@birchui/license` once for the whole app.
- Without a valid key every feature keeps working. A small watermark appears on the widget and one console warning is printed, on non-local hosts only; on localhost you can develop without a key.
- Changing `licenseKey` with `update()` re-runs the check.

[Pivot charts](https://docs.birchui.com/pivot-studio/charts.md) are drawn by Birch UI Charts and need a Charts license or Birch UI Complete. See [Licensing & activation](https://docs.birchui.com/getting-started/licensing.md) and [Pricing](https://docs.birchui.com/getting-started/pricing.md).

## Using Pivot Studio in a framework

The framework adapters do not ship a Pivot Studio component, and there is no `/pivot-studio` subpath. Each adapter exports the generic factory it uses for its own components; pass it `pivotStudioDefinition` to get a component that creates the widget on mount, sends changed props to `update()` and forwards every event.

**JavaScript**

```ts
import { createPivotStudio } from '@birchui/pivot-studio';

const studio = createPivotStudio(document.getElementById('sales-report')!, { data: sales, report, height: 640 });
studio.on('reportChange', ({ report }) => saveReport(report));
```

**React**

```tsx
import { createReactComponent } from '@birchui/react';
import { pivotStudioDefinition } from '@birchui/pivot-studio';

export const BirchPivotStudio = createReactComponent(pivotStudioDefinition);

export function SalesReport({ sales, report }: { sales: Sale[]; report: PivotReport }) {
  return (
    <BirchPivotStudio
      data={sales}
      report={report}
      height={640}
      onReportChange={({ report }) => saveReport(report)}
    />
  );
}
```

**Vue**

```vue
<script setup lang="ts">
import { createVueComponent } from '@birchui/vue';
import { pivotStudioDefinition, type PivotReport, type PivotStudioEvents } from '@birchui/pivot-studio';

const BirchPivotStudio = createVueComponent(pivotStudioDefinition);

defineProps<{ sales: Sale[]; report: PivotReport }>();

function onReportChange({ report }: PivotStudioEvents['reportChange']) {
  saveReport(report);
}
</script>

<template>
  <BirchPivotStudio :data="sales" :report="report" :height="640" @report-change="onReportChange" />
</template>
```

**Angular**

```ts
import { ChangeDetectionStrategy, Component, input, output } from '@angular/core';
import { injectBirchWidget, withOverrides, type WidgetOutputs } from '@birchui/angular';
import {
  pivotStudioDefinition,
  type PivotStudioApi,
  type PivotStudioEvents,
  type PivotStudioOptions,
} from '@birchui/pivot-studio';

@Component({
  selector: 'app-pivot-studio',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: '',
  styles: ':host { display: block; height: 640px; }',
})
export class PivotStudioComponent implements WidgetOutputs<PivotStudioEvents> {
  readonly options = input<PivotStudioOptions>({});
  readonly data = input<PivotStudioOptions['data']>();
  readonly report = input<PivotStudioOptions['report']>();

  readonly ready = output<PivotStudioEvents['ready']>();
  readonly reportChange = output<PivotStudioEvents['reportChange']>();
  readonly cellClick = output<PivotStudioEvents['cellClick']>();
  readonly drillThrough = output<PivotStudioEvents['drillThrough']>();
  readonly dataLoaded = output<PivotStudioEvents['dataLoaded']>();
  readonly pivotUpdated = output<PivotStudioEvents['pivotUpdated']>();
  readonly error = output<PivotStudioEvents['error']>();

  private readonly widget = injectBirchWidget(pivotStudioDefinition, this, () =>
    withOverrides<PivotStudioOptions>(this.options(), { data: this.data(), report: this.report() }),
  );

  get api(): PivotStudioApi | undefined {
    return this.widget.instance;
  }
}
```

**Svelte**

```svelte
<script lang="ts">
  import { createSvelteAction } from '@birchui/svelte';
  import { pivotStudioDefinition, type PivotReport, type PivotStudioApi } from '@birchui/pivot-studio';

  const birchPivotStudio = createSvelteAction(pivotStudioDefinition);

  let { sales, report }: { sales: Sale[]; report: PivotReport } = $props();
  let api: PivotStudioApi | null = $state.raw(null);
</script>

<div
  style="height: 640px"
  use:birchPivotStudio={{
    data: sales,
    report,
    on: { reportChange: ({ report }) => saveReport(report) },
    onReady: (studio) => (api = studio),
  }}
></div>
```

**Solid**

```tsx
import { createSolidComponent } from '@birchui/solid';
import { pivotStudioDefinition } from '@birchui/pivot-studio';

export const BirchPivotStudio = createSolidComponent(pivotStudioDefinition);

export function SalesReport(props: { sales: Sale[]; report: PivotReport }) {
  return (
    <BirchPivotStudio
      data={props.sales}
      report={props.report}
      height={640}
      onReportChange={({ report }) => saveReport(report)}
    />
  );
}
```

**Web Component**

```html
<birchui-pivot-studio id="sales-report" theme="auto" style="display: block; height: 640px"></birchui-pivot-studio>

<script type="module">
  import { createElementClass } from '@birchui/element';
  import { pivotStudioDefinition } from '@birchui/pivot-studio';

  customElements.define(
    'birchui-pivot-studio',
    createElementClass(pivotStudioDefinition, {
      optionKeys: ['data', 'report', 'fields', 'plugins'],
      attributes: { theme: 'string', density: 'string', locale: 'string', 'license-key': 'string' },
      requiredOptions: [],
    }),
  );

  const studio = document.getElementById('sales-report');
  studio.data = sales;
  studio.report = report;
  studio.addEventListener('report-change', ({ detail: { report } }) => saveReport(report));
</script>
```

Notes per adapter:

- **React and Solid**: options are props, events are `on…` props (`onReportChange`, `onDrillThrough`), and `ref` gives you the `PivotStudioApi`.
- **Vue**: options are attributes (kebab-case is converted to camelCase) or an `options` object; events are kebab-case (`@report-change`, `@drill-through`).
- **Angular**: `injectBirchWidget` needs one output per event, which is why the wrapper declares all seven.
- **Svelte**: the action's parameter is the options plus `on` (handlers keyed by event name) and `onReady`.
- **Web Component**: `createElementClass` turns the definition into a custom element; events are kebab-case `CustomEvent`s with the payload in `detail`, and `element.api` is the `PivotStudioApi`. Define the element in the browser only. Set `plugins` before the element is connected, since plugins are read only when the widget is created.

A report usually changes because the user edited it, so avoid feeding the `reportChange` payload straight back into a bound `report` prop: it would reapply the same report on every edit. Keep the bound value for loading reports, and store the edited one separately.
