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

OptionTypeDefaultDescription
useWorkerbooleanfalseEnable Web Worker for large datasets
workerThresholdnumber50000Minimum rows to trigger worker usage
forceWorkerbooleanfalseForce worker usage regardless of data size
customAggregatorsRecord<string, Aggregator>{}Custom aggregator definitions
enableHistorybooleanfalseEnable undo/redo history tracking
historyOptionsConfigHistoryOptions-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

PropertyTypeDescription
dataDataRecord[]Current dataset
configPivotConfigCurrent pivot configuration
pivotDataPivotDataInterface | nullComputed pivot result (worker or main thread)
isLoadingbooleanWhether a pivot computation is in progress
errorstring | nullLast error message, if any
rowKeysstring[][]All row keys from the pivot result
colKeysstring[][]All column keys from the pivot result
attributesstring[]All attribute names detected in the data
numericAttributesstring[]Attributes detected as numeric
workerEnabledbooleanWhether Web Worker mode was requested
canUndobooleanWhether undo is available (requires enableHistory)
canRedobooleanWhether redo is available (requires enableHistory)

Methods

MethodSignatureDescription
setDatasetData(DataRecord[]): Promise<void>Replace the entire dataset (re-initializes worker if enabled)
setConfigsetConfig(PartialPivotConfig): voidMerge partial config into the current configuration
setRowssetRows(string[]): voidSet row fields
setColssetCols(string[]): voidSet column fields
setValssetVals(ValField[]): voidSet value fields (string or ValConfig)
setAggregatorsetAggregator(string): voidSet the default aggregator name
resetreset(): voidReset config to defaults and clear history
addInclusionaddInclusion(attr, value): voidAdd an inclusion filter value for an attribute
removeInclusionremoveInclusion(attr, value): voidRemove an inclusion filter value
addExclusionaddExclusion(attr, value): voidAdd an exclusion filter value for an attribute
removeExclusionremoveExclusion(attr, value): voidRemove an exclusion filter value
clearFiltersclearFilters(): voidClear all inclusion, exclusion, value, and rule filters
updateFilterRulesupdateFilterRules(attr, FilterRule[]): voidSet filter rules for a specific attribute
clearFilterRulesclearFilterRules(attr?): voidClear filter rules for one or all attributes
getAttributeValuesgetAttributeValues(attr): string[]Get distinct values for an attribute
getAggregatorgetAggregator(rowKey, colKey): AggregatorResultGet the aggregator result for a specific cell
getRecordsForCellgetRecordsForCell(rowKey, colKey): DataRecord[]Get raw records contributing to a cell (drill-down)
undoundo(): booleanUndo last config change (returns false if nothing to undo)
redoredo(): booleanRedo last undone change (returns false if nothing to redo)
addDateGroupingaddDateGrouping(sourceField, DateGroupingLevel[]): voidAuto-group a date field by year, quarter, month, week, or day
removeDateGroupingremoveDateGrouping(sourceField): voidRemove date grouping for a field
addBinningaddBinning(BinningConfig): voidAdd numeric binning for a field
removeBinningremoveBinning(sourceField): voidRemove binning for a field
exportConfigexportConfig(name, options?): SavedPivotConfigExport current config as a saveable object
importConfigimportConfig(saved): voidImport a saved config or partial config
applyDeltaapplyDelta(DataDelta): voidApply incremental data changes (inserts, updates, deletes)
destroyWorkerdestroyWorker(): 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 />
PropTypeDefaultDescription
storePivotStorerequiredPivot store instance created by createPivotStore()
layout'compact' | 'tabular' | 'flat''compact'Table layout mode
showRowTotalsbooleantrueShow row total column
showColTotalsbooleantrueShow column total row
showGrandTotalbooleantrueShow grand total cell
zebrabooleanfalseAlternate row background colors
localeLocale'en'Locale for i18n (affects labels, number formatting, RTL)
enableHoverbooleanfalseEnable row/column hover highlight
enableTooltipsbooleanfalseShow tooltips on cell hover
enableResizebooleanfalseEnable column resizing via drag handles
enableContextMenubooleanfalseEnable right-click context menu
enableDrillDownbooleanfalseEnable cell click drill-down modal
enableExportbooleanfalseEnable export from context menu
enableKeyboardNavigationbooleanfalseEnable arrow-key cell navigation
enablePrintbooleanfalseEnable print mode
enableRangeSelectionbooleanfalseEnable cell range selection (click + drag)
enableRowDragDropbooleanfalseEnable row drag-and-drop reordering
cellStyleConditionalStyle-Callback function returning per-cell CSS styles
formattingRulesFormattingRule[]-Conditional formatting rules (heatmap, data bar, icon set)
hideZeroRowsbooleanfalseHide rows where all values are zero
topNTopNConfig-Top/Bottom N row filtering
subtotalsPosition'top' | 'bottom' | 'none''top'Position of subtotal rows in grouped layouts
sparklineSparklineConfig-Inline sparkline charts in cells
masterDetailMasterDetailConfig-Master/detail expandable row panels
cellFlashCellFlashConfig-Cell flash animation on value changes
statusBarStatusBarConfig | boolean-Status bar with row counts and selection stats
cellRendererCellRendererCallback-Custom cell renderer returning HTML string or null
pinnedTopRowsstring[][]-Row keys pinned to the top of the table
pinnedBottomRowsstring[][]-Row keys pinned to the bottom of the table
pinnedLeftColumnsstring[][]-Column keys pinned to the left
pinnedRightColumnsstring[][]-Column keys pinned to the right
virtualThresholdnumber5000Cell count threshold to auto-switch to virtual mode
forceVirtualbooleanfalseForce virtual scrolling regardless of cell count
rowHeightnumber36Row 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 />
PropTypeDefaultDescription
storePivotStorerequiredPivot store instance
showExportbooleantrueShow the export dropdown button
showLayoutbooleantrueShow the layout switcher (compact/tabular/flat)
showRefreshbooleantrueShow the refresh button
showFieldChooserbooleantrueShow the field chooser toggle button
showFullscreenbooleantrueShow the fullscreen toggle button
showCalculatedFieldbooleanfalseShow the calculated field button
showChartbooleanfalseShow the chart view toggle and type selector
showHideZeroRowsbooleanfalseShow the hide-zero-rows toggle
showTopNbooleantrueShow the Top N filter control
showFiltersbooleanfalseShow the filter panel toggle
showUndoRedobooleanfalseShow undo/redo buttons
showPrintbooleanfalseShow 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)
chartTypeChartType'bar'Current chart type (bindable with bind:chartType)
hideZeroRowsbooleanfalseCurrent hide-zero-rows state (bindable)
topNTopNConfig{ 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} />
PropTypeDefaultDescription
storePivotStorerequiredPivot store instance
classstring''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} />
PropTypeDefaultDescription
storePivotStorerequiredPivot store instance
type'bar' | 'horizontalBar' | 'line' | 'pie' | 'doughnut' | 'area' | 'stacked''bar'Chart type
titlestring''Chart title
showLegendbooleantrueShow chart legend
showValuesbooleanfalseShow data values on chart elements
colorScheme'default' | 'pastel' | 'vivid' | 'monochrome''default'Color scheme for chart series
heightnumber400Chart height in pixels
classstring''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 },
  ]}
/>
PropTypeDefaultDescription
storePivotStorerequiredPivot store instance
slicersSlicerConfig[]autoSlicer configurations (auto-generated from attributes if omitted)
layout'horizontal' | 'vertical' | 'grid''vertical'Panel layout direction
showClearAllbooleantrueShow "Clear All" button
showActiveFiltersbooleantrueShow active filter summary badges
compactbooleanfalseUse compact display mode

SlicerConfig

PropertyTypeDefaultDescription
attributestringrequiredData attribute to filter on
labelstringattribute nameDisplay label for the slicer
style'buttons' | 'checkboxes' | 'pills''buttons'Visual style of filter options
multiSelectbooleantrueAllow multiple selections
showCountsbooleantrueShow record count badges
maxVisiblenumber-Max visible items before "Show more"
searchablebooleanauto at 20+Show search input for filtering values
hierarchicalbooleanfalseEnable hierarchical tree view
cascadeFromstring-Parent slicer attribute for cascade filtering
virtualScrollbooleanauto 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>
PropTypeDefaultDescription
mode'light' | 'dark' | 'system''light'Theme mode ('system' tracks OS preference)
customThemePartial<PivotBlitzTheme>{}Custom theme overrides (colors, fonts, radii, etc.)
childrenSnippetrequiredChild 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';
FunctionSignatureDescription
setLocalesetLocale(locale: Locale): voidSet the active locale globally
getLocalegetLocale(): LocaleGet the current active locale
tt(key: TranslationKey, locale?: Locale): stringTranslate a key using current or specified locale
getSupportedLocalesgetSupportedLocales(): string[]Get list of all supported locale codes
formatLocalizedNumberformatLocalizedNumber(value: number, locale?: Locale, options?: Intl.NumberFormatOptions): stringFormat a number using locale conventions
formatLocalizedCurrencyformatLocalizedCurrency(value: number, locale?: Locale, currency?: string): stringFormat a currency value using locale conventions
isRTLisRTL(locale?: Locale): booleanCheck if a locale uses right-to-left text direction
getDirectiongetDirection(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 value
CEIL(x) Round up to integer
FLOOR(x) Round down to integer
ROUND(x, decimals?) Round to decimals
TRUNC(x) Truncate to integer
SQRT(x) Square root
POWER(base, exp) Exponentiation
EXP(x) e raised to power x
LOG(x, base?) Logarithm (natural if no base)
LOG10(x) Base-10 logarithm
LOG2(x) Base-2 logarithm
MOD(x, y) Modulo (remainder)
SIGN(x) Sign of number (-1, 0, 1)
PI() Value of pi
RAND() Random number 0-1
RANDBETWEEN(min, max) Random integer in range

Trigonometry

SIN(x) Sine
COS(x) Cosine
TAN(x) Tangent
ASIN(x) Arc sine
ACOS(x) Arc cosine
ATAN(x) Arc tangent
ATAN2(y, x) Two-argument arc tangent

Aggregation

SUM(...values) Sum of values
AVG(...values) Average of values
MIN(...values) Minimum value
MAX(...values) Maximum value
COUNT(...values) Count non-null values
COUNTA(...values) Count non-empty values
MEDIAN(...values) Median value
STDEV(...values) Standard deviation
VARIANCE(...values) Variance

String

CONCAT(...strings) Concatenate strings
UPPER(s) Convert to uppercase
LOWER(s) Convert to lowercase
PROPER(s) Title case
TRIM(s) Remove leading/trailing spaces
LEN(s) String length
LEFT(s, n) First n characters
RIGHT(s, n) Last n characters
MID(s, start, len) Substring from position
FIND(search, s) Find position (case-sensitive)
SEARCH(search, s) Find position (case-insensitive)
REPLACE(s, old, new) Replace all occurrences
SUBSTITUTE(s, old, new, n?) Replace nth occurrence
TEXT(value, format?) Format value as text
VALUE(s) Parse string to number
CONTAINS(s, search) Check if string contains substring

Date

NOW() Current date and time
TODAY() Current date (midnight)
YEAR(date) Extract year
MONTH(date) Extract month (1-12)
DAY(date) Extract day of month
HOUR(date) Extract hour
WEEKDAY(date) Day of week (0-6)
QUARTER(date) Quarter of year (1-4)
DATE(y, m, d) Create date from parts
DATEADD(date, n, unit) Add time to date
DATEDIFF(d1, d2, unit?) Difference between dates
FORMATDATE(date, fmt?) Format date as string
EOMONTH(date, months?) End of month
WORKDAY(date, days) Add business days

Logical

IF(cond, then, else) Conditional expression
AND(...booleans) Logical AND
OR(...booleans) Logical OR
NOT(x) Logical NOT
XOR(a, b) Exclusive OR
ISNULL(x) Check if null/undefined
ISBLANK(x) Check if null or empty
ISNUMBER(x) Check if numeric
IFNULL(x, default) Default value if null
COALESCE(...values) First non-null value
SWITCH(expr, ...cases) Switch/case matching
IFS(...conditions) Multiple if-conditions