UNPKG

@mindfiredigital/pivothead

Version:

PivotHead is a powerful and flexible library for creating interactive pivot tables in JavaScript applications. It provides a core engine for data manipulation and, in the future, will be compatible with wrappers for React, Vue, Svelte, and Angular, making

483 lines 17.3 kB
import { AggregationType, Dimension, Group, GroupConfig, MeasureConfig, PivotTableConfig, PivotTableState, FilterConfig, PaginationConfig, DataHandlingMode, FormatOptions, AxisConfig, CellValue } from '../types/interfaces'; /** * Creates an instance of PivotEngine. * @param {PivotTableConfig<T>} config - The configuration for the pivot table. */ export declare class PivotEngine<T extends Record<string, unknown>> { setColumns(columns: AxisConfig[]): void; setRows(rows: AxisConfig[]): void; setData(augmentedData: T[]): void; private config; private state; private filterConfig; private paginationConfig; private autoAllColumnEnabled; private cache; constructor(config: PivotTableConfig<T>); private validateConfig; private initializeState; /** * Loads data from a file or URL. **/ private loadData; private ensureSyntheticAllColumn; setDataHandlingMode(mode: DataHandlingMode): void; getDataHandlingMode(): DataHandlingMode; setAutoAllColumn(enabled: boolean): void; /** * Updates the engine's data source and clears filters * This method allows external components to update the data with fresh filtering state * @param {T[]} newData - The new data to use as the source * @param {boolean} clearFilters - Whether to clear existing filters (default: true) * @public */ updateDataSource(newData: T[], clearFilters?: boolean): void; /** * Loads data from a file or URL. * @param {File | string} source - The file or URL to load data from. * @public * @returns {Promise<void>} A promise that resolves when the data is loaded. **/ private fetchRemoteData; /** * Process the data to be displayed in the table. * @param {T[]} data - The data to process. * @returns {ProcessedData} The processed data including headers, rows, and totals. * @private **/ private readFileData; /** * Initializes row sizes for the pivot table. * @param {T[]} data - The data to initialize row sizes for. * @returns {RowSize[]} An array of row sizes. * @private */ private initializeRowSizes; /** * Processes the data for the pivot table. * @param {T[]} data - The data to process. * @returns {ProcessedData} The processed data including headers, rows, and totals. * @private */ private generateProcessedDataForDisplay; /** * Generates headers for the pivot table. * @returns {string[]} An array of header strings. * @private */ private generateHeaders; /** * Generates rows for the pivot table. * @param {T[]} data - The data to generate rows from. * @returns {CellValue[][]} A 2D array representing the rows. * @private */ /** * Generates rows for the pivot table with enhanced formatting. * @param {T[]} data - The data to generate rows from. * @returns {CellValue[][]} A 2D array representing the rows. * @private */ private generateRows; /** * Calculates the value for a specific measure. * @param {T} item - The data item. * @param {MeasureConfig} measure - The measure configuration. * @returns {number} The calculated measure value. * @private */ private calculateMeasureValue; /** * Calculates totals for each measure in the pivot table. * @param {T[]} data - The data to calculate totals from. * @returns {Record<string, number>} An object with measure names as keys and their totals as values. * @private */ private calculateTotals; private listeners; /** * Subscribe to state changes. Returns an unsubscribe function. */ subscribe(fn: (state: PivotTableState<T>) => void): () => void; /** * Emit state changes to all subscribers. * CRITICAL FIX: Wrap each listener in try-catch to prevent one subscriber error from crashing others */ private _emit; /** * Sets the measures for the pivot table. * @param {MeasureConfig[]} measureFields - The measure configurations to set. * @public */ setMeasures(measureFields: MeasureConfig[]): void; /** * Sets the dimensions for the pivot table. * @param {Dimension[]} dimensionFields - The dimension configurations to set. * @public */ setDimensions(dimensionFields: Dimension[]): void; /** * Sets the aggregation type for the pivot table. * @param {AggregationType} type - The aggregation type to set. * @public */ setAggregation(type: AggregationType): void; /** * Sets the row groups for the pivot table. * @param {Group[]} rowGroups - The row groups to set. * @public */ setRowGroups(rowGroups: Group[]): void; /** * Sets the column groups for the pivot table. * @param {Group[]} columnGroups - The column groups to set. * @public */ setColumnGroups(columnGroups: Group[]): void; /** * Enhanced formatValue method with comprehensive formatting support * @param {CellValue} value - The value to format. * @param {string} field - The field name to use for formatting. * @returns {string} The formatted value as a string. * @public */ formatValue(value: CellValue, field: string): string; /** * Get formatting configuration for a field * @param {string} field - The field name * @returns {FormatOptions | null} The format configuration * @private */ private getFieldFormat; /** * Apply comprehensive formatting to a value * @param {CellValue} value - The value to format * @param {FormatOptions} format - The format configuration * @returns {string} The formatted value * @private */ private applyFormatting; /** * Format as currency * @param {number} num - The number to format * @param {FormatOptions} format - The format configuration * @param {number} decimals - Number of decimal places * @returns {string} The formatted currency value * @private */ private formatCurrency; /** * Format as percentage * @param {number} num - The number to format * @param {FormatOptions} format - The format configuration * @param {number} decimals - Number of decimal places * @returns {string} The formatted percentage value * @private */ private formatPercentage; /** * Format as number * @param {number} num - The number to format * @param {FormatOptions} format - The format configuration * @param {number} decimals - Number of decimal places * @returns {string} The formatted number value * @private */ private formatNumber; /** * Format as date * @param {CellValue} value - The date value to format * @param {FormatOptions} format - The format configuration * @returns {string} The formatted date value * @private */ private formatDate; /** * Apply custom thousand and decimal separators * @param {string} formattedValue - The pre-formatted value * @param {FormatOptions} format - The format configuration * @returns {string} The value with custom separators applied * @private */ private applyCustomSeparators; /** * Calculate aggregated value for a cell intersection * @param {string} rowValue - The row value * @param {string} columnValue - The column value * @param {MeasureConfig} measure - The measure configuration * @param {string} rowFieldName - The row field name * @param {string} columnFieldName - The column field name * @returns {number} The calculated aggregated value * @public */ calculateCellValue(rowValue: string, columnValue: string, measure: MeasureConfig, rowFieldName: string, columnFieldName: string): number; /** * Get text alignment for a field * @param {string} field - The field name * @returns {string} The text alignment ('left', 'right', 'center') * @public */ getFieldAlignment(field: string): string; /** * Update formatting configuration for a specific field * @param {string} field - The field name * @param {FormatOptions} format - The format configuration * @public */ updateFieldFormatting(field: string, format: FormatOptions): void; /** * Sorts the pivot table data based on the specified field and direction. * @param {string} field - The field to sort by. * @param {'asc' | 'desc'} direction - The sort direction. * @public */ sort(field: string, direction: 'asc' | 'desc'): void; private applySort; private sortData; private getFieldValue; private sortGroups; /** * Updates aggregates for all groups in the pivot table. * @private */ private updateAggregates; /** * Applies grouping to the pivot table data. * @private */ private applyGrouping; /** * Sets the group configuration for the pivot table. * @param {GroupConfig | null} groupConfig - The group configuration to set. * @public */ setGroupConfig(groupConfig: GroupConfig | null): void; /** * Returns the grouped data. * @returns {Group[]} An array of grouped data. * @public */ getGroupedData(): Group[]; /** * Returns the current state of the pivot table. * @returns {PivotTableState<T>} The current state of the pivot table. * @public */ getState(): PivotTableState<T>; /** * Resets the pivot table to its initial state. * @public */ reset(): void; /** * Resizes a specific row in the pivot table. * @param {number} index - The index of the row to resize. * @param {number} height - The new height for the row. * @public */ resizeRow(index: number, height: number): void; /** * Toggles the expansion state of a row. * @param {string} rowId - The ID of the row to toggle. * @public */ toggleRowExpansion(rowId: string): void; /** * Checks if a row is expanded. * @param {string} rowId - The ID of the row to check. * @returns {boolean} True if the row is expanded, false otherwise. * @public */ isRowExpanded(rowId: string): boolean; /** * Handles dragging a row to a new position. * This method now correctly operates on state.rowGroups. * @param {number} fromIndex - The original index of the row. * @param {number} toIndex - The new index for the row. * @public */ dragRow(fromIndex: number, toIndex: number): void; /** * Handles dragging a column to a new position. * This method now correctly operates on state.columnGroups. * @param {number} fromIndex - The original index of the column. * @param {number} toIndex - The new index for the column. * @public */ dragColumn(fromIndex: number, toIndex: number): void; private validateDragOperation; /** * Applies filters to the data * @param {FilterConfig[]} filters - Array of filter configurations * @public */ applyFilters(filters: FilterConfig[]): void; /** * Sets pagination configuration * @param {PaginationConfig} config - Pagination configuration * @public */ setPagination(config: PaginationConfig): void; /** * Returns the current pagination configuration * @returns {PaginationConfig} * @public */ getPagination(): PaginationConfig; /** * Refreshes data with current filters and pagination * @private */ private refreshData; /** * Gets the appropriate data source based on the current data handling mode * @private */ private getDataForCurrentMode; /** * Filters data based on filter configuration * @param {T[]} data - Data to filter * @private */ private filterData; /** * Paginates data based on pagination configuration * @param {T[]} data - Data to paginate * @private */ private paginateData; /** * Gets current pagination state * @returns {PaginationConfig} Current pagination configuration * @public */ getPaginationState(): PaginationConfig; /** * Gets current filter state * @returns {FilterConfig[]} Current filter configuration * @public */ getFilterState(): FilterConfig[]; /** * Exports the pivot table data to HTML and downloads the file. * @param {string} fileName - The name of the downloaded file (without extension). * @public */ exportToHTML(fileName?: string): void; /** * Exports the pivot table data to PDF and downloads the file. * @param {string} fileName - The name of the downloaded file (without extension). * @public */ exportToPDF(fileName?: string): void; /** * Exports the pivot table data to Excel and downloads the file. * @param {string} fileName - The name of the downloaded file (without extension). * @public */ exportToExcel(fileName?: string): void; /** * Opens a print dialog with the formatted pivot table. * @public */ openPrintDialog(): void; /** * Handles dragging a data row (product) to a new position * This method operates on the actual data items, not groups * @param {number} fromIndex - The original index of the product in unique products list * @param {number} toIndex - The new index for the product in unique products list * @public */ dragDataRow(fromIndex: number, toIndex: number): void; /** * Handles dragging a data column (region) to a new position * This method operates on the actual data structure, not groups * @param {number} fromIndex - The original index of the region * @param {number} toIndex - The new index for the region * @public */ dragDataColumn(fromIndex: number, toIndex: number): void; /** * Alternative method: Reorder products by their names directly * This is more direct for your UI implementation * @param {string} fromProduct - Name of the product being moved * @param {string} toProduct - Name of the product to move before/after * @param {'before' | 'after'} position - Whether to place before or after target * @public */ reorderProductsByName(fromProduct: string, toProduct: string, position?: 'before' | 'after'): void; getCustomRegionOrder(): string[] | null; /** * Generic method to swap data rows based on the configured row field * Works with any field name (product, country, customer, etc.) */ swapDataRows(fromIndex: number, toIndex: number): void; /** * Generic method to swap data columns based on the configured column field * Works with any field name (region, category, department, etc.) */ swapDataColumns(fromIndex: number, toIndex: number): void; /** * Generic method to get unique values for any field * Uses the original config data, not the paginated state data * Utility method for UI components */ getUniqueFieldValues(fieldName: string): string[]; /** * Get unique field values respecting any custom order that has been set */ getOrderedUniqueFieldValues(fieldName: string, isRowField?: boolean): string[]; /** * Generic method to get the configured row field name */ getRowFieldName(): string | null; /** * Generic method to get the configured column field name */ getColumnFieldName(): string | null; /** * Generic method to set custom field order * Can be used by UI to store custom arrangements */ setCustomFieldOrder(fieldName: string, order: string[], isRowField?: boolean): void; /** * Get ordered column values if custom order exists */ getOrderedColumnValues(): string[] | null; /** * Get ordered row values if custom order exists */ getOrderedRowValues(): string[] | null; /** * Method to swap raw data rows by index * This works directly with the raw data array regardless of pivot configuration */ swapRawDataRows(fromIndex: number, toIndex: number): void; /** * Checks if any of the current filters are for aggregated measures * @private */ private hasAggregatedFilters; /** * Filters processed data based on aggregated values * @private */ private filterProcessedData; /** * Sets the layout for the pivot table (rows, columns, measures) in one call. * @param {AxisConfig[]} rows - Row fields * @param {AxisConfig[]} columns - Column fields * @param {MeasureConfig[]} measures - Measure fields * @public */ setLayout(rows: AxisConfig[], columns: AxisConfig[], measures: MeasureConfig[]): void; /** * Set only rows and columns, keeping measures unchanged * @param {AxisConfig[]} rows * @param {AxisConfig[]} columns * @public */ setRowsAndColumns(rows: AxisConfig[], columns: AxisConfig[]): void; private normalizeMeasures; } //# sourceMappingURL=pivotEngine.d.ts.map