Birch UI v0.1
Pricing

Pivot Studio API & eventsPivot Studio

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

Open .md

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 lists every exported type.

createPivotStudio#

TypeScript
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#

PivotStudioOptionsinterface@birchui/pivot-studioFull reference
PropertyTypeDescription
dataoptionalreadonly TRecord[] | string—
dataFormatoptionalDataFormat—
csvDelimiteroptionalstring—
dataLimitsoptionalPartial<DataLimits>—
fieldsoptionalFieldDefinition[]—
reportoptionalPivotReport—
licenseKeyoptionalstring—
themeoptional'light' | 'dark' | 'auto'—
densityoptional'compact' | 'normal' | 'comfortable'—
localeoptionalstring—
heightoptionalnumber | string—
fieldListoptionalboolean—
toolbaroptionalboolean—
workeroptionalboolean—
drillThroughoptionalboolean—
injectStylesoptionalboolean—
ariaLabeloptionalstring—
fileNameoptionalstring—
pluginsoptionalPivotStudioPlugin[]—
localeTextoptionalLocaleTextInput—
rtloptionalboolean—

See the options table for defaults.

PivotStudioApi#

PivotStudioApiinterface@birchui/pivot-studioFull reference
MemberTypeDescription
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>—
elementreadonlyHTMLElementInherited from Widget.
update()(options: Partial<PivotStudioOptions<TRecord>>) => voidInherited from Widget.
on()<K extends keyof TEvents & string>(event: K, listener: Listener<TEvents[K]>) => () => voidInherited from Widget.
destroy()() => voidInherited 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#

PivotStudioEventsinterface@birchui/pivot-studioFull reference
PropertyTypeDescription
ready{ api: PivotStudioApi<TRecord> }—
reportChange{ report: PivotReport }—
cellClickCellClickEvent—
drillThroughDrillThroughEvent<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.

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

studio.on('error', ({ message }) => notifications.error(message));
CellClickEventinterface@birchui/pivot-studioFull reference
PropertyTypeDescription
rowPathstring[]—
colPathstring[]—
measurestring | null—
valuenumber | null—
rowKindPivotRowKind—
columnKindPivotRowKind | null—
DrillThroughEventinterface@birchui/pivot-studioFull reference
PropertyTypeDescription
recordsTRecord[]—
rowPathstring[]—
colPathstring[]—
measurestring | null—

Plugins#

A plugin adds controls to the widget. The pivot chart is one; you can write your own with the same interface:

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().

PivotStudioPluginContextinterface@birchui/pivot-studioFull reference
PropertyTypeDescription
studioreadonlyPivotStudioApi<TRecord>—
rootreadonlyHTMLElement—
licenseKeyreadonlystring | undefined—
themereadonly'light' | 'dark' | 'auto'—
addToolbarButton()(button: PivotToolbarButton) => PivotToolbarHandle—
addPanel()(position: 'top' | 'bottom') => HTMLElement—
announce()(message: string) => void—
translateTranslate—

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.
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.

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