# Pivot Studio API & events

> Every option, method and event of Pivot Studio, the plugin interface, and the exported helpers.

Everything here is exported from `@birchui/pivot-studio`, except the chart helpers, which come from `@birchui/pivot-studio/charts`. The tables are generated from the package's TypeScript source; the [package reference](https://docs.birchui.com/api/pivot-studio.md) lists every exported type.

## createPivotStudio

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

const studio: PivotStudioApi<Sale> = createPivotStudio<Sale>(container, options);
```

`createPivotStudio<TRecord>(container, options?)` creates the widget inside `container` and returns its API. The generic parameter types the records returned by `getRecords()` and `drillThrough()` and carried by the `drillThrough` event. It throws a `TypeError` only when `container` is not a DOM element; problems with data or reports are reported through warnings and the `error` event.

## Options

**`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` |  |

See the [options table](https://docs.birchui.com/pivot-studio/overview.md#options) for defaults.

## PivotStudioApi

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

```ts
interface PivotStudioApi<TRecord = PivotRecord> extends Widget< PivotStudioOptions<TRecord>, PivotStudioEvents<TRecord> >
```

| Property | Type | Description |
| --- | --- | --- |
| `setData` | `(data: readonly TRecord[] \| string, options?: SetDataOptions) => void` |  |
| `getRecords` | `() => readonly TRecord[]` |  |
| `getFields` | `() => PivotField[]` |  |
| `getMembers` | `(field: string) => PivotMember[]` |  |
| `setReport` | `(report: PivotReport) => void` |  |
| `getReport` | `() => PivotReport` |  |
| `addField` | `(zone: PivotZone, field: string, index?: number) => void` |  |
| `removeField` | `(field: string, zone?: PivotZone) => void` |  |
| `moveField` | `(field: string, zone: Exclude<PivotZone, 'values'>, index?: number) => void` |  |
| `setAggregation` | `(measure: string, aggregation: AggregationName) => void` |  |
| `setShowValuesAs` | `(measure: string, showAs: ShowValuesAs, along?: PivotAxis) => void` |  |
| `setFilter` | `(field: string, filter: FieldFilter \| null) => void` |  |
| `setSort` | `(field: string, sort: SortDirection \| MeasureSort) => void` |  |
| `swapAxes` | `() => void` |  |
| `expandAll` | `(axis?: PivotAxis) => void` |  |
| `collapseAll` | `(axis?: PivotAxis) => void` |  |
| `setExpanded` | `(axis: PivotAxis, path: readonly string[], expanded: boolean) => void` |  |
| `drillThrough` | `(rowPath: readonly string[], colPath?: readonly string[]) => TRecord[]` |  |
| `getView` | `() => PivotView \| null` |  |
| `getPivotMatrix` | `(options?: PivotMatrixOptions) => PivotMatrixCell[][]` |  |
| `exportCsv` | `(options?: CsvExportOptions) => string` |  |
| `exportExcel` | `(options?: ExcelExportOptions) => Promise<Uint8Array>` |  |
| `refresh` | `() => Promise<void>` |  |
| `readonly element` | `HTMLElement` | Inherited from Widget. |
| `update` | `(options: Partial<PivotStudioOptions<TRecord>>) => void` | Inherited from Widget. |
| `on` | `<K extends keyof TEvents & string>(event: K, listener: Listener<TEvents[K]>) => () => void` | Inherited from Widget. |
| `destroy` | `() => void` | Inherited from Widget. |

### Data

| Method | Description |
| --- | --- |
| `setData(data, options?)` | Load records, CSV or JSON. `options`: `format`, `delimiter`, `fields`. |
| `getRecords()` | The loaded records |
| `getFields()` | Every field, including derived date parts |
| `getMembers(field)` | The distinct members of a field, with `key`, `label` and `isBlank` |
| `refresh()` | Re-read the records after changing them in place; resolves when the table is updated |

### Report

| Method | Description |
| --- | --- |
| `getReport()`, `setReport(report)` | Read or replace the report JSON |
| `addField(zone, field, index?)` | Add a field to `'rows'`, `'columns'`, `'values'` or `'filters'` |
| `removeField(field, zone?)` | Remove a field from one zone or every zone |
| `moveField(field, zone, index?)` | Move a field to another position or to `'rows'`, `'columns'` or `'filters'` |
| `setAggregation(measure, aggregation)` | Change a measure's aggregation |
| `setShowValuesAs(measure, showAs, along?)` | Show a measure as a calculation |
| `setFilter(field, filter)` | Set a field's filter, or clear it with `null` |
| `setSort(field, sort)` | `'asc'`, `'desc'` or `{ measure, dir, path? }` |

### Layout

| Method | Description |
| --- | --- |
| `swapAxes()` | Exchange row and column fields |
| `expandAll(axis?)`, `collapseAll(axis?)` | Expand or collapse every member, on `'rows'`, `'columns'` or both |
| `setExpanded(axis, path, expanded)` | Expand or collapse one member by its path of member keys |

### Results and export

| Method | Description |
| --- | --- |
| `getView()` | The computed `PivotView`, or `null` before the first computation |
| `getPivotMatrix(options?)` | The pivot as a 2-D array: `formatted`, `headers: 'stacked' \| 'flat'` |
| `drillThrough(rowPath, colPath?)` | The records behind a cell |
| `exportCsv(options?)` | CSV text; `download: true` also saves a file |
| `exportExcel(options?)` | A `Promise<Uint8Array>` with the `.xlsx` bytes; downloads unless `download: false` |

### Widget

| Member | Description |
| --- | --- |
| `element` | The root element |
| `update(partial)` | Apply option changes; `plugins` can only be set at creation |
| `on(event, listener)` | Subscribe; returns an unsubscribe function |
| `destroy()` | Remove the widget and release listeners, the worker, plugins and the license check |

## Events

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

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

| Property | Type | Description |
| --- | --- | --- |
| `ready` | `{ api: PivotStudioApi<TRecord> }` |  |
| `reportChange` | `{ report: PivotReport }` |  |
| `cellClick` | `CellClickEvent` |  |
| `drillThrough` | `DrillThroughEvent<TRecord>` |  |
| `dataLoaded` | `{ rowCount: number; fields: PivotField[] }` |  |
| `pivotUpdated` | `{ rowCount: number; columnCount: number; recordCount: number; durationMs: number }` |  |
| `error` | `{ message: string; error?: unknown }` |  |

| Event | Payload | Fires |
| --- | --- | --- |
| `dataLoaded` | `{ rowCount, fields }` | After the initial data and every `setData()` |
| `pivotUpdated` | `{ rowCount, columnCount, recordCount, durationMs }` | After every computation of the table |
| `ready` | `{ api }` | Once, after the first computation |
| `reportChange` | `{ report }` | After every change to the report, from users or code, including `setReport()` |
| `cellClick` | `{ rowPath, colPath, measure, value, rowKind, columnKind }` | When a table cell is clicked |
| `drillThrough` | `{ records, rowPath, colPath, measure }` | When users open drill-through on a value |
| `error` | `{ message, error? }` | When data, a report file, a computation or an export fails |

After creation the first events arrive in this order: `dataLoaded`, `pivotUpdated`, `ready`. They fire after `createPivotStudio()` returns, so listeners attached right away receive them. `recordCount` in `pivotUpdated` is the number of records after filters; `durationMs` is the time the update took.

```ts
studio.on('ready', ({ api }) => api.expandAll('rows'));

studio.on('error', ({ message }) => notifications.error(message));
```

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

```ts
interface CellClickEvent
```

| Property | Type | Description |
| --- | --- | --- |
| `rowPath` | `string[]` |  |
| `colPath` | `string[]` |  |
| `measure` | `string \| null` |  |
| `value` | `number \| null` |  |
| `rowKind` | `PivotRowKind` |  |
| `columnKind` | `PivotRowKind \| null` |  |

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

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

| Property | Type | Description |
| --- | --- | --- |
| `records` | `TRecord[]` |  |
| `rowPath` | `string[]` |  |
| `colPath` | `string[]` |  |
| `measure` | `string \| null` |  |

## Plugins

A plugin adds controls to the widget. The [pivot chart](https://docs.birchui.com/pivot-studio/charts.md) is one; you can write your own with the same interface:

```ts title="share-link-plugin.ts"
import type { PivotStudioPlugin } from '@birchui/pivot-studio';

export const shareLinkPlugin: PivotStudioPlugin = {
  name: 'shareLink',
  install(context) {
    const button = context.addToolbarButton({
      id: 'share',
      label: 'Copy link',
      title: 'Copy a link to this report',
      onClick: async () => {
        const report = btoa(encodeURIComponent(JSON.stringify(context.studio.getReport())));
        await navigator.clipboard.writeText(`${location.origin}/reports/store-sales?view=${report}`);
        context.announce('Link copied');
      },
    });
    return () => button.remove();
  },
};
```

`install(context)` receives:

| Member | Description |
| --- | --- |
| `studio` | The `PivotStudioApi` |
| `root` | The widget's root element |
| `licenseKey`, `theme` | The widget's options |
| `addToolbarButton(button)` | Add a button (`id`, `label`, `title?`, `toggle?`, `onClick`); returns a handle with `element`, `setPressed()` and `remove()` |
| `addPanel(position)` | Add an empty panel above (`'top'`) or below (`'bottom'`) the table; returns its element |
| `announce(message)` | Say something through the widget's live region |

Return a cleanup function; it runs on `destroy()`.

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

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

| Property | Type | Description |
| --- | --- | --- |
| `readonly studio` | `PivotStudioApi<TRecord>` |  |
| `readonly root` | `HTMLElement` |  |
| `readonly licenseKey` | `string \| undefined` |  |
| `readonly theme` | `'light' \| 'dark' \| 'auto'` |  |
| `addToolbarButton` | `(button: PivotToolbarButton) => PivotToolbarHandle` |  |
| `addPanel` | `(position: 'top' \| 'bottom') => HTMLElement` |  |
| `announce` | `(message: string) => void` |  |
| `translate` | `Translate` |  |

## Exported helpers

| Export | Description |
| --- | --- |
| `pivotStudioDefinition`, `PIVOT_STUDIO_EVENTS` | The widget definition (`birchui-pivot-studio`) and its event names |
| `createPivotEngine(options)` | The headless engine. See [Performance](https://docs.birchui.com/pivot-studio/performance.md#the-headless-engine). |
| `aggregateCube(input)` | The aggregation kernel |
| `buildPivotWorkbook(view, options?)`, `buildRecordsWorkbook(records, fields, options?)` | Excel workbooks of a pivot view or of records, for `writeXlsx()` |
| `pivotViewToMatrix(view, options?)` | A 2-D array from a view |
| `pivotChartData(view, options?)` | Categories and series for charting |
| `formatPivotValue(value, resolved, locale?, emptyText?)`, `excelNumberFormat(resolved)` | Number formatting as used in the table and in Excel; `resolved` is `{ kind, format }` with `kind` one of `'number'`, `'integer'`, `'percent'`, `'date'` and `format` a `PivotNumberFormat` |
| `parseCsv(text, options?)`, `sniffDelimiter(text)` | CSV parsing |
| `csvToRecords(text, options?)`, `parseJsonData(input)` | CSV and JSON to records |
| `detectFieldType(values)`, `inferFields(records, definitions?)`, `humanizeFieldName(name)` | Field detection |
| `parseDateValue(value)` | ISO date text, `Date` or timestamp to epoch milliseconds, read as UTC |
| `normalizeReport(report, warn?)` | Validate and clean a report |
| `DEFAULT_REPORT_OPTIONS`, `AGGREGATION_NAMES`, `SHOW_VALUES_AS` | Defaults and the lists of valid names |
| `pivotStudioStyles` | The widget's CSS as a string |

From `@birchui/pivot-studio/charts`: `pivotChartPlugin(options?)`, `createPivotChart(container, studio, options?)`, `pivotChartOptions(view, options?)` and `pivotChartData`. See [Pivot charts](https://docs.birchui.com/pivot-studio/charts.md).
