API Reference
Complete technical reference for all PivotBlitz stores, components, types, and utility functions.
1. createPivotStore()
Creates a reactive pivot store that manages data, configuration, and computed pivot results.
import { createPivotStore } from '@pivotblitz/svelte'; const store = createPivotStore( data: DataRecord[], config?: PartialPivotConfig, options?: PivotStoreOptions ): PivotStore;
PivotStoreOptions
| Option | Type | Default | Description |
|---|---|---|---|
useWorker | boolean | false | Enable Web Worker for large datasets |
workerThreshold | number | 50000 | Minimum rows to trigger worker usage |
forceWorker | boolean | false | Force worker usage regardless of data size |
customAggregators | Record<string, Aggregator> | {} | Custom aggregator definitions |
enableHistory | boolean | false | Enable undo/redo history tracking |
historyOptions | ConfigHistoryOptions | - | History configuration: { maxDepth: number } |
Example
const store = createPivotStore( salesData, { rows: ['region', 'product'], cols: ['quarter'], vals: [{ field: 'revenue', aggregator: 'Sum' }], aggregatorName: 'Sum', }, { enableHistory: true, historyOptions: { maxDepth: 50 }, } );
2. PivotStore
The object returned by createPivotStore(). All properties are reactive (Svelte 5 runes).
Reactive Properties
| Property | Type | Description |
|---|---|---|
data | DataRecord[] | Current dataset |
config | PivotConfig | Current pivot configuration |
pivotData | PivotDataInterface | null | Computed pivot result (worker or main thread) |
isLoading | boolean | Whether a pivot computation is in progress |
error | string | null | Last error message, if any |
rowKeys | string[][] | All row keys from the pivot result |
colKeys | string[][] | All column keys from the pivot result |
attributes | string[] | All attribute names detected in the data |
numericAttributes | string[] | Attributes detected as numeric |
workerEnabled | boolean | Whether Web Worker mode was requested |
canUndo | boolean | Whether undo is available (requires enableHistory) |
canRedo | boolean | Whether redo is available (requires enableHistory) |
Methods
| Method | Signature | Description |
|---|---|---|
setData | setData(DataRecord[]): Promise<void> | Replace the entire dataset (re-initializes worker if enabled) |
setConfig | setConfig(PartialPivotConfig): void | Merge partial config into the current configuration |
setRows | setRows(string[]): void | Set row fields |
setCols | setCols(string[]): void | Set column fields |
setVals | setVals(ValField[]): void | Set value fields (string or ValConfig) |
setAggregator | setAggregator(string): void | Set the default aggregator name |
reset | reset(): void | Reset config to defaults and clear history |
addInclusion | addInclusion(attr, value): void | Add an inclusion filter value for an attribute |
removeInclusion | removeInclusion(attr, value): void | Remove an inclusion filter value |
addExclusion | addExclusion(attr, value): void | Add an exclusion filter value for an attribute |
removeExclusion | removeExclusion(attr, value): void | Remove an exclusion filter value |
clearFilters | clearFilters(): void | Clear all inclusion, exclusion, value, and rule filters |
updateFilterRules | updateFilterRules(attr, FilterRule[]): void | Set filter rules for a specific attribute |
clearFilterRules | clearFilterRules(attr?): void | Clear filter rules for one or all attributes |
getAttributeValues | getAttributeValues(attr): string[] | Get distinct values for an attribute |
getAggregator | getAggregator(rowKey, colKey): AggregatorResult | Get the aggregator result for a specific cell |
getRecordsForCell | getRecordsForCell(rowKey, colKey): DataRecord[] | Get raw records contributing to a cell (drill-down) |
undo | undo(): boolean | Undo last config change (returns false if nothing to undo) |
redo | redo(): boolean | Redo last undone change (returns false if nothing to redo) |
addDateGrouping | addDateGrouping(sourceField, DateGroupingLevel[]): void | Auto-group a date field by year, quarter, month, week, or day |
removeDateGrouping | removeDateGrouping(sourceField): void | Remove date grouping for a field |
addBinning | addBinning(BinningConfig): void | Add numeric binning for a field |
removeBinning | removeBinning(sourceField): void | Remove binning for a field |
exportConfig | exportConfig(name, options?): SavedPivotConfig | Export current config as a saveable object |
importConfig | importConfig(saved): void | Import a saved config or partial config |
applyDelta | applyDelta(DataDelta): void | Apply incremental data changes (inserts, updates, deletes) |
destroyWorker | destroyWorker(): Promise<void> | Destroy the Web Worker and free resources |
3. PivotTable Props
The main pivot table visualization component. Supports compact, tabular, and flat layouts with automatic virtual scrolling for large datasets.
import { PivotTable } from '@pivotblitz/svelte'; <PivotTable store={store} layout="compact" enableDrillDown />
| Prop | Type | Default | Description |
|---|---|---|---|
store | PivotStore | required | Pivot store instance created by createPivotStore() |
layout | 'compact' | 'tabular' | 'flat' | 'compact' | Table layout mode |
showRowTotals | boolean | true | Show row total column |
showColTotals | boolean | true | Show column total row |
showGrandTotal | boolean | true | Show grand total cell |
zebra | boolean | false | Alternate row background colors |
locale | Locale | 'en' | Locale for i18n (affects labels, number formatting, RTL) |
enableHover | boolean | false | Enable row/column hover highlight |
enableTooltips | boolean | false | Show tooltips on cell hover |
enableResize | boolean | false | Enable column resizing via drag handles |
enableContextMenu | boolean | false | Enable right-click context menu |
enableDrillDown | boolean | false | Enable cell click drill-down modal |
enableExport | boolean | false | Enable export from context menu |
enableKeyboardNavigation | boolean | false | Enable arrow-key cell navigation |
enablePrint | boolean | false | Enable print mode |
enableRangeSelection | boolean | false | Enable cell range selection (click + drag) |
enableRowDragDrop | boolean | false | Enable row drag-and-drop reordering |
cellStyle | ConditionalStyle | - | Callback function returning per-cell CSS styles |
formattingRules | FormattingRule[] | - | Conditional formatting rules (heatmap, data bar, icon set) |
hideZeroRows | boolean | false | Hide rows where all values are zero |
topN | TopNConfig | - | Top/Bottom N row filtering |
subtotalsPosition | 'top' | 'bottom' | 'none' | 'top' | Position of subtotal rows in grouped layouts |
sparkline | SparklineConfig | - | Inline sparkline charts in cells |
masterDetail | MasterDetailConfig | - | Master/detail expandable row panels |
cellFlash | CellFlashConfig | - | Cell flash animation on value changes |
statusBar | StatusBarConfig | boolean | - | Status bar with row counts and selection stats |
cellRenderer | CellRendererCallback | - | Custom cell renderer returning HTML string or null |
pinnedTopRows | string[][] | - | Row keys pinned to the top of the table |
pinnedBottomRows | string[][] | - | Row keys pinned to the bottom of the table |
pinnedLeftColumns | string[][] | - | Column keys pinned to the left |
pinnedRightColumns | string[][] | - | Column keys pinned to the right |
virtualThreshold | number | 5000 | Cell count threshold to auto-switch to virtual mode |
forceVirtual | boolean | false | Force virtual scrolling regardless of cell count |
rowHeight | number | 36 | Row height in pixels (virtual mode) |
onCellClick | (rowKey, colKey, value) => void | - | Callback when a cell is clicked |
onCellDoubleClick | (rowKey, colKey, value) => void | - | Callback when a cell is double-clicked |
onRowReorder | (fromIndex, toIndex, rowKeys) => void | - | Callback when a row is drag-reordered |
4. PivotToolbar Props
Configurable toolbar with layout, export, chart, filter, and undo/redo controls.
import { PivotToolbar } from '@pivotblitz/svelte'; <PivotToolbar store={store} showUndoRedo showChart bind:layout />
| Prop | Type | Default | Description |
|---|---|---|---|
store | PivotStore | required | Pivot store instance |
showExport | boolean | true | Show the export dropdown button |
showLayout | boolean | true | Show the layout switcher (compact/tabular/flat) |
showRefresh | boolean | true | Show the refresh button |
showFieldChooser | boolean | true | Show the field chooser toggle button |
showFullscreen | boolean | true | Show the fullscreen toggle button |
showCalculatedField | boolean | false | Show the calculated field button |
showChart | boolean | false | Show the chart view toggle and type selector |
showHideZeroRows | boolean | false | Show the hide-zero-rows toggle |
showTopN | boolean | true | Show the Top N filter control |
showFilters | boolean | false | Show the filter panel toggle |
showUndoRedo | boolean | false | Show undo/redo buttons |
showPrint | boolean | false | Show the print button |
layout | 'compact' | 'tabular' | 'flat' | 'compact' | Current layout (bindable with bind:layout) |
viewMode | 'table' | 'chart' | 'split' | 'table' | Current view mode (bindable with bind:viewMode) |
chartType | ChartType | 'bar' | Current chart type (bindable with bind:chartType) |
hideZeroRows | boolean | false | Current hide-zero-rows state (bindable) |
topN | TopNConfig | { type: 'none', count: 10 } | Current Top N config (bindable) |
onExport | (format) => void | - | Callback when an export format is selected |
onToggleFieldChooser | () => void | - | Callback when field chooser is toggled |
onToggleFullscreen | () => void | - | Callback when fullscreen is toggled |
5. FieldChooser Props
Drag-and-drop interface for configuring pivot rows, columns, values, and aggregators.
import { FieldChooser } from '@pivotblitz/svelte'; <FieldChooser store={store} />
| Prop | Type | Default | Description |
|---|---|---|---|
store | PivotStore | required | Pivot store instance |
class | string | '' | Additional CSS classes |
6. PivotChart Props
Chart visualization component powered by Chart.js. Automatically derives data from the pivot store.
import { PivotChart } from '@pivotblitz/svelte'; <PivotChart store={store} type="bar" showLegend height={500} />
| Prop | Type | Default | Description |
|---|---|---|---|
store | PivotStore | required | Pivot store instance |
type | 'bar' | 'horizontalBar' | 'line' | 'pie' | 'doughnut' | 'area' | 'stacked' | 'bar' | Chart type |
title | string | '' | Chart title |
showLegend | boolean | true | Show chart legend |
showValues | boolean | false | Show data values on chart elements |
colorScheme | 'default' | 'pastel' | 'vivid' | 'monochrome' | 'default' | Color scheme for chart series |
height | number | 400 | Chart height in pixels |
class | string | '' | Additional CSS classes |
7. SlicerPanel Props
Visual filter panel with multiple slicer controls (Excel-style). Supports buttons, checkboxes, pills, hierarchical trees, cascade filtering, and virtual scrolling.
import { SlicerPanel } from '@pivotblitz/svelte'; <SlicerPanel store={store} slicers={[ { attribute: 'region', style: 'buttons', multiSelect: true }, { attribute: 'product', style: 'checkboxes', searchable: true }, ]} />
| Prop | Type | Default | Description |
|---|---|---|---|
store | PivotStore | required | Pivot store instance |
slicers | SlicerConfig[] | auto | Slicer configurations (auto-generated from attributes if omitted) |
layout | 'horizontal' | 'vertical' | 'grid' | 'vertical' | Panel layout direction |
showClearAll | boolean | true | Show "Clear All" button |
showActiveFilters | boolean | true | Show active filter summary badges |
compact | boolean | false | Use compact display mode |
SlicerConfig
| Property | Type | Default | Description |
|---|---|---|---|
attribute | string | required | Data attribute to filter on |
label | string | attribute name | Display label for the slicer |
style | 'buttons' | 'checkboxes' | 'pills' | 'buttons' | Visual style of filter options |
multiSelect | boolean | true | Allow multiple selections |
showCounts | boolean | true | Show record count badges |
maxVisible | number | - | Max visible items before "Show more" |
searchable | boolean | auto at 20+ | Show search input for filtering values |
hierarchical | boolean | false | Enable hierarchical tree view |
cascadeFrom | string | - | Parent slicer attribute for cascade filtering |
virtualScroll | boolean | auto at 100+ | Enable virtual scrolling for large value lists |
8. ThemeProvider Props
Wraps pivot components to provide dark/light mode and custom theme CSS variables.
import { ThemeProvider } from '@pivotblitz/svelte'; <ThemeProvider mode="dark" customTheme={{ accentPrimary: '#8b5cf6' }{'}' }> <PivotTable store={store} /> </ThemeProvider>
| Prop | Type | Default | Description |
|---|---|---|---|
mode | 'light' | 'dark' | 'system' | 'light' | Theme mode ('system' tracks OS preference) |
customTheme | Partial<PivotBlitzTheme> | {} | Custom theme overrides (colors, fonts, radii, etc.) |
children | Snippet | required | Child components (Svelte 5 snippet) |
9. Key Types
TypeScript interfaces and enums used across the API.
PivotConfig
interface PivotConfig { rows: string[]; cols: string[]; vals: ValField[]; aggregatorName: string; rendererName: string; rowOrder: 'key_a_to_z' | 'key_z_to_a' | 'value_a_to_z' | 'value_z_to_a'; colOrder: 'key_a_to_z' | 'key_z_to_a' | 'value_a_to_z' | 'value_z_to_a'; derivedAttributes: Record<string, (record: DataRecord) => unknown>; valueFilter: Record<string, (value: unknown) => boolean>; sorters: Record<string, (a: string, b: string) => number>; inclusionsInfo: Record<string, string[]>; exclusionsInfo: Record<string, string[]>; locale: string; hideZeroRows?: boolean; topN?: TopNConfig; filterRules?: Record<string, FilterRule[]>; dateGroupings?: DateGroupingConfig[]; binnings?: BinningConfig[]; }
ValConfig
interface ValConfig { field: string; aggregator?: string; displayMode?: SummaryDisplayMode; }
SummaryDisplayMode
type SummaryDisplayMode = | 'normal' // Raw aggregated value | 'pctOfGrandTotal' // % of grand total | 'pctOfRowTotal' // % of row total | 'pctOfColTotal' // % of column total | 'pctOfParentRow' // % of parent row | 'pctOfParentCol' // % of parent column | 'runningTotal' // Cumulative running total | 'difference' // Difference from previous | 'pctDifference' // % difference from previous | 'rank'; // Rank within group
TopNConfig
interface TopNConfig { type: 'none' | 'top' | 'bottom'; count: number; showOthers?: boolean; // Aggregate remaining items into "Others" }
SparklineConfig
interface SparklineConfig { type: 'line' | 'bar' | 'area'; height?: number; // Default: 20 color?: string; // Stroke/bar color showMinMax?: boolean; // Show min/max dots negativeColor?: string; // Color for negative bars fillOpacity?: number; // Area fill opacity (default: 0.2) }
MasterDetailConfig
interface MasterDetailConfig { enabled: boolean; renderer: 'records' | 'pivot' | 'custom'; getDetailData?: (rowKey: string[]) => Promise<Record<string, unknown>[]>; height?: number; // Default: 200 }
FormattingRule (union type)
type FormattingRule = | ConditionalRule | HeatmapRule | DataBarRule | IconSetRule; interface ConditionalRule { id: string; name?: string; applyTo?: string[]; operator: ComparisonOperator; // 'gt' | 'gte' | 'lt' | 'between' | 'top' | ... value?: number | string; value2?: number; style: CellStyle; priority?: number; stopIfTrue?: boolean; } interface HeatmapRule { id: string; type: 'heatmap'; applyTo?: string[]; minColor: string; midColor?: string; maxColor: string; usePercentile?: boolean; } interface DataBarRule { id: string; type: 'dataBar'; applyTo?: string[]; color: string; backgroundColor?: string; showValue?: boolean; minValue?: number; maxValue?: number; } interface IconSetRule { id: string; type: 'iconSet'; applyTo?: string[]; icons: IconDefinition[]; reverseOrder?: boolean; }
FilterRule
interface FilterRule { type: 'label' | 'value'; operator: LabelFilterOperator | ValueFilterOperator; compareTo?: string | number; compareToEnd?: string | number; // For 'between'/'dateBetween' measureField?: string; // For value filters relativeDatePreset?: RelativeDatePreset; }
StatusBarConfig
interface StatusBarConfig { enabled: boolean; panels?: StatusBarPanel[]; } interface StatusBarPanel { type: 'totalRowCount' | 'totalColumnCount' | 'filteredRowCount' | 'selectedRangeStats' | 'custom'; position?: 'left' | 'center' | 'right'; label?: string; value?: string; }
PrintConfig
interface PrintConfig { title?: string; subtitle?: string; pageSize?: 'a4' | 'a3' | 'letter' | 'legal'; orientation?: 'portrait' | 'landscape'; showTimestamp?: boolean; maxRows?: number; // Default: 10000 }
CellFlashConfig
interface CellFlashConfig { enabled?: boolean; // Default: false duration?: number; // Flash duration in ms (default: 500) upColor?: string; // Color for increased values downColor?: string; // Color for decreased values }
SavedPivotConfig
interface SavedPivotConfig { id: string; name: string; description?: string; config: PivotConfig; createdAt: string; updatedAt: string; userId?: string; tenantId?: string; }
DataDelta
interface DataDelta { inserts?: DataRecord[]; // New records to append updates?: DataRecord[]; // Records to replace (matched by ID) deletes?: string[]; // Record IDs to remove }
CellRendererContext
interface CellRendererContext { rowKey: string[]; colKey: string[]; value: AggregatorValue; formattedValue: string; rawValue: number | null; rowIndex: number; colIndex: number; valIndex: number; }
10. Export Functions
Utility functions for exporting pivot results to various formats. Imported from @pivotblitz/core.
exportToCSV
import { exportToCSV } from '@pivotblitz/core'; exportToCSV(pivotResult, options?: CSVExportOptions): void interface CSVExportOptions { filename?: string; // Default: 'pivot-export' delimiter?: string; // Default: ',' includeHeaders?: boolean; // Default: true encoding?: string; }
exportToJSON
import { exportToJSON } from '@pivotblitz/core'; exportToJSON(pivotResult, options?: JSONExportOptions): void interface JSONExportOptions { filename?: string; // Default: 'pivot-export' pretty?: boolean; // Default: true includeMetadata?: boolean; // Default: true }
exportToHTML
import { exportToHTML } from '@pivotblitz/core'; exportToHTML(pivotResult, options?: HTMLExportOptions): void interface HTMLExportOptions { filename?: string; // Default: 'pivot-export' title?: string; // Default: 'Pivot Table Export' includeStyles?: boolean; // Default: true theme?: 'light' | 'dark'; // Default: 'light' responsive?: boolean; // Default: true includeSparklines?: boolean; // Default: false sparklineConfig?: SparklineConfig; sparklineData?: Map<string, number[]>; }
11. i18n Functions
Internationalization utilities for locale management, translation, number formatting, and RTL support. Supports 10 locales: en, it, de, fr, es, pt, ja, zh, ar, he.
import { setLocale, getLocale, t, getSupportedLocales, formatLocalizedNumber, formatLocalizedCurrency, isRTL, getDirection, } from '@pivotblitz/core';
| Function | Signature | Description |
|---|---|---|
setLocale | setLocale(locale: Locale): void | Set the active locale globally |
getLocale | getLocale(): Locale | Get the current active locale |
t | t(key: TranslationKey, locale?: Locale): string | Translate a key using current or specified locale |
getSupportedLocales | getSupportedLocales(): string[] | Get list of all supported locale codes |
formatLocalizedNumber | formatLocalizedNumber(value: number, locale?: Locale, options?: Intl.NumberFormatOptions): string | Format a number using locale conventions |
formatLocalizedCurrency | formatLocalizedCurrency(value: number, locale?: Locale, currency?: string): string | Format a currency value using locale conventions |
isRTL | isRTL(locale?: Locale): boolean | Check if a locale uses right-to-left text direction |
getDirection | getDirection(locale?: Locale): 'ltr' | 'rtl' | Get the text direction for a locale |
Example
setLocale('de'); t('total'); // 'Gesamt' formatLocalizedNumber(1234.56); // '1.234,56' formatLocalizedCurrency(99.9); // '99,90 EUR' isRTL('ar'); // true getDirection('he'); // 'rtl'
12. Formula Functions
PivotBlitz includes 40+ built-in formula functions for calculated fields. Functions are organized by category and can be used in formula expressions like ROUND([revenue] / [quantity], 2).
import { createCalculatedField } from '@pivotblitz/core'; const profitMargin = createCalculatedField({ name: 'Profit Margin', formula: 'ROUND(([revenue] - [cost]) / [revenue] * 100, 1)', });
Math
ABS(x) Absolute valueCEIL(x) Round up to integerFLOOR(x) Round down to integerROUND(x, decimals?) Round to decimalsTRUNC(x) Truncate to integerSQRT(x) Square rootPOWER(base, exp) ExponentiationEXP(x) e raised to power xLOG(x, base?) Logarithm (natural if no base)LOG10(x) Base-10 logarithmLOG2(x) Base-2 logarithmMOD(x, y) Modulo (remainder)SIGN(x) Sign of number (-1, 0, 1)PI() Value of piRAND() Random number 0-1RANDBETWEEN(min, max) Random integer in rangeTrigonometry
SIN(x) SineCOS(x) CosineTAN(x) TangentASIN(x) Arc sineACOS(x) Arc cosineATAN(x) Arc tangentATAN2(y, x) Two-argument arc tangentAggregation
SUM(...values) Sum of valuesAVG(...values) Average of valuesMIN(...values) Minimum valueMAX(...values) Maximum valueCOUNT(...values) Count non-null valuesCOUNTA(...values) Count non-empty valuesMEDIAN(...values) Median valueSTDEV(...values) Standard deviationVARIANCE(...values) VarianceString
CONCAT(...strings) Concatenate stringsUPPER(s) Convert to uppercaseLOWER(s) Convert to lowercasePROPER(s) Title caseTRIM(s) Remove leading/trailing spacesLEN(s) String lengthLEFT(s, n) First n charactersRIGHT(s, n) Last n charactersMID(s, start, len) Substring from positionFIND(search, s) Find position (case-sensitive)SEARCH(search, s) Find position (case-insensitive)REPLACE(s, old, new) Replace all occurrencesSUBSTITUTE(s, old, new, n?) Replace nth occurrenceTEXT(value, format?) Format value as textVALUE(s) Parse string to numberCONTAINS(s, search) Check if string contains substringDate
NOW() Current date and timeTODAY() Current date (midnight)YEAR(date) Extract yearMONTH(date) Extract month (1-12)DAY(date) Extract day of monthHOUR(date) Extract hourWEEKDAY(date) Day of week (0-6)QUARTER(date) Quarter of year (1-4)DATE(y, m, d) Create date from partsDATEADD(date, n, unit) Add time to dateDATEDIFF(d1, d2, unit?) Difference between datesFORMATDATE(date, fmt?) Format date as stringEOMONTH(date, months?) End of monthWORKDAY(date, days) Add business daysLogical
IF(cond, then, else) Conditional expressionAND(...booleans) Logical ANDOR(...booleans) Logical ORNOT(x) Logical NOTXOR(a, b) Exclusive ORISNULL(x) Check if null/undefinedISBLANK(x) Check if null or emptyISNUMBER(x) Check if numericIFNULL(x, default) Default value if nullCOALESCE(...values) First non-null valueSWITCH(expr, ...cases) Switch/case matchingIFS(...conditions) Multiple if-conditions