@ackplus/react-tanstack-data-table 1.1.15 → 1.1.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +0 -8
  2. package/dist/index.d.ts +4 -0
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +5 -1
  5. package/dist/lib/components/data-table-view.d.ts +7 -0
  6. package/dist/lib/components/data-table-view.d.ts.map +1 -0
  7. package/dist/lib/components/data-table-view.js +151 -0
  8. package/dist/lib/components/toolbar/data-table-toolbar.d.ts.map +1 -1
  9. package/dist/lib/components/toolbar/data-table-toolbar.js +14 -1
  10. package/dist/lib/components/toolbar/table-export-control.d.ts.map +1 -1
  11. package/dist/lib/components/toolbar/table-export-control.js +0 -2
  12. package/dist/lib/data-table.d.ts +0 -3
  13. package/dist/lib/data-table.d.ts.map +1 -1
  14. package/dist/lib/data-table.js +9 -1646
  15. package/dist/lib/features/selection.feature.d.ts.map +1 -1
  16. package/dist/lib/features/selection.feature.js +1 -2
  17. package/dist/lib/hooks/index.d.ts +3 -0
  18. package/dist/lib/hooks/index.d.ts.map +1 -0
  19. package/dist/lib/hooks/index.js +5 -0
  20. package/dist/lib/hooks/use-data-table-engine.d.ts +104 -0
  21. package/dist/lib/hooks/use-data-table-engine.d.ts.map +1 -0
  22. package/dist/lib/hooks/use-data-table-engine.js +961 -0
  23. package/dist/lib/types/data-table-api.d.ts +1 -1
  24. package/dist/lib/types/data-table-api.d.ts.map +1 -1
  25. package/dist/lib/types/data-table.types.d.ts +1 -2
  26. package/dist/lib/types/data-table.types.d.ts.map +1 -1
  27. package/package.json +1 -1
  28. package/src/index.ts +4 -0
  29. package/src/lib/components/data-table-view.tsx +386 -0
  30. package/src/lib/components/toolbar/data-table-toolbar.tsx +15 -1
  31. package/src/lib/components/toolbar/table-export-control.tsx +0 -2
  32. package/src/lib/data-table.tsx +17 -2201
  33. package/src/lib/features/selection.feature.ts +1 -3
  34. package/src/lib/hooks/index.ts +2 -0
  35. package/src/lib/hooks/use-data-table-engine.ts +1282 -0
  36. package/src/lib/types/data-table-api.ts +1 -1
  37. package/src/lib/types/data-table.types.ts +1 -2
@@ -36,1654 +36,17 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.DataTable = void 0;
37
37
  const jsx_runtime_1 = require("react/jsx-runtime");
38
38
  /**
39
- * Main DataTable Component
39
+ * Main DataTable Component (thin wrapper)
40
40
  *
41
- * A comprehensive, highly customizable data table component built with:
42
- * - Material-UI (MUI) for styling
43
- * - TanStack Table for table logic
44
- * - TypeScript for type safety
41
+ * Composes useDataTableEngine + DataTableProvider + DataTableView.
42
+ * Preserves forwardRef API and DataTableApi surface.
45
43
  */
46
- const material_1 = require("@mui/material");
47
- const react_table_1 = require("@tanstack/react-table");
48
- // Import custom features
49
- const column_filter_feature_1 = require("./features/column-filter.feature");
50
- const features_1 = require("./features");
51
- const react_virtual_1 = require("@tanstack/react-virtual");
52
44
  const react_1 = __importStar(require("react"));
53
- // Import from new organized structure
54
45
  const data_table_context_1 = require("./contexts/data-table-context");
55
- const utils_1 = require("./utils");
56
- const debounced_fetch_utils_1 = require("./utils/debounced-fetch.utils");
57
- const slot_helpers_1 = require("./utils/slot-helpers");
58
- const headers_1 = require("./components/headers");
59
- const pagination_1 = require("./components/pagination");
60
- const rows_1 = require("./components/rows");
61
- const toolbar_1 = require("./components/toolbar");
62
- const special_columns_utils_1 = require("./utils/special-columns.utils");
63
- // Static default initial state - defined outside component
64
- const DEFAULT_INITIAL_STATE = {
65
- sorting: [],
66
- pagination: {
67
- pageIndex: 0,
68
- pageSize: 10,
69
- },
70
- selectionState: { ids: [], type: 'include' },
71
- globalFilter: '',
72
- expanded: {},
73
- columnOrder: [],
74
- columnPinning: {
75
- left: [],
76
- right: [],
77
- },
78
- columnVisibility: {},
79
- columnSizing: {},
80
- columnFilter: {
81
- filters: [],
82
- logic: 'AND',
83
- pendingFilters: [],
84
- pendingLogic: 'AND',
85
- },
86
- };
87
- /**
88
- * Main DataTable component with all features
89
- */
90
- exports.DataTable = (0, react_1.forwardRef)(function DataTable({ initialState, columns, data = [], totalRow = 0, idKey = 'id', extraFilter = null, footerFilter = null,
91
- // Data management mode (MUI DataGrid style)
92
- dataMode = 'client', initialLoadData = true, onFetchData, // callback to fetch data from the server need to with response { data: T[], total: number }
93
- onFetchStateChange, // callback to fetch data from the server no need to resonce , this for filter data
94
- onDataChange, // callback to change data
95
- onDataStateChange, // callback to change data state
96
- // Selection props
97
- enableRowSelection = false, enableMultiRowSelection = true, selectMode = 'page', isRowSelectable, onSelectionChange,
98
- // Row click props
99
- onRowClick, selectOnRowClick = false,
100
- // Bulk action props
101
- enableBulkActions = false, bulkActions,
102
- // Column resizing props
103
- enableColumnResizing = false, columnResizeMode = 'onChange', onColumnSizingChange,
104
- // Column ordering props
105
- enableColumnDragging = false, onColumnDragEnd,
106
- // Column pinning props
107
- enableColumnPinning = false, onColumnPinningChange,
108
- // Column visibility props
109
- onColumnVisibilityChange, enableColumnVisibility = true,
110
- // Expandable rows props
111
- enableExpanding = false, getRowCanExpand, renderSubComponent,
112
- // Pagination props
113
- enablePagination = false, paginationMode = 'client',
114
- // Filtering props
115
- enableGlobalFilter = true, enableColumnFilter = false, filterMode = 'client',
116
- // Sorting props
117
- enableSorting = true, sortingMode = 'client', onSortingChange,
118
- //export props
119
- exportFilename = 'export', exportConcurrency = 'cancelAndRestart', exportChunkSize = 1000, exportStrictTotalCheck = false, exportSanitizeCSV = true, onExportProgress, onExportComplete, onExportError, onServerExport, onExportCancel, onExportStateChange,
120
- // Styling props
121
- enableHover = true, enableStripes = false, tableProps = {}, fitToScreen = true, tableSize: initialTableSize = 'medium',
122
- // Sticky header/footer props
123
- enableStickyHeaderOrFooter = false, maxHeight = '400px',
124
- // Virtualization props
125
- enableVirtualization = false, estimateRowHeight = 52,
126
- // Toolbar props
127
- enableTableSizeControl = true, enableExport = false, enableReset = true, enableRefresh = false,
128
- // Loading and empty states
129
- loading = false, emptyMessage = 'No data available', skeletonRows = 5,
130
- // Column filters props
131
- onColumnFiltersChange, onPaginationChange, onGlobalFilterChange,
132
- // Slots
133
- slots = {}, slotProps = {},
134
- // Logging
135
- logging, }, ref) {
136
- // Convert mode-based props to boolean flags for internal use
137
- const isServerMode = dataMode === 'server';
138
- const isServerPagination = paginationMode === 'server' || isServerMode;
139
- const isServerFiltering = filterMode === 'server' || isServerMode;
140
- const isServerSorting = sortingMode === 'server' || isServerMode;
141
- const theme = (0, material_1.useTheme)();
142
- const logger = (0, react_1.useMemo)(() => (0, utils_1.createLogger)('DataTable', logging), [logging]);
143
- (0, react_1.useEffect)(() => {
144
- if (logger.isLevelEnabled('info')) {
145
- logger.info('mounted', {
146
- dataMode,
147
- paginationMode,
148
- filterMode,
149
- sortingMode,
150
- });
151
- }
152
- return () => {
153
- if (logger.isLevelEnabled('info')) {
154
- logger.info('unmounted');
155
- }
156
- };
157
- }, [logger, dataMode, paginationMode, filterMode, sortingMode]);
158
- // -------------------------------
159
- // Memoized values (grouped together)
160
- // -------------------------------
161
- const initialStateConfig = (0, react_1.useMemo)(() => {
162
- const config = {
163
- ...DEFAULT_INITIAL_STATE,
164
- ...initialState,
165
- };
166
- if (logger.isLevelEnabled('info')) {
167
- logger.info('initialStateConfig', { config });
168
- }
169
- return config;
170
- }, [initialState, logger]);
171
- const initialSelectionState = (0, react_1.useMemo)(() => {
172
- return initialStateConfig.selectionState || DEFAULT_INITIAL_STATE.selectionState;
173
- }, [initialStateConfig.selectionState]);
174
- // -------------------------------
175
- // State hooks (grouped together)
176
- // -------------------------------
177
- // const [fetchLoading, setFetchLoading] = useState(false);
178
- const [sorting, setSorting] = (0, react_1.useState)((initialState === null || initialState === void 0 ? void 0 : initialState.sorting) || DEFAULT_INITIAL_STATE.sorting);
179
- const [pagination, setPagination] = (0, react_1.useState)((initialState === null || initialState === void 0 ? void 0 : initialState.pagination) || DEFAULT_INITIAL_STATE.pagination);
180
- const [globalFilter, setGlobalFilter] = (0, react_1.useState)((initialState === null || initialState === void 0 ? void 0 : initialState.globalFilter) || DEFAULT_INITIAL_STATE.globalFilter);
181
- const [selectionState, setSelectionState] = (0, react_1.useState)((initialState === null || initialState === void 0 ? void 0 : initialState.selectionState) || DEFAULT_INITIAL_STATE.selectionState);
182
- const [columnFilter, setColumnFilter] = (0, react_1.useState)((initialState === null || initialState === void 0 ? void 0 : initialState.columnFilter) || DEFAULT_INITIAL_STATE.columnFilter);
183
- const [expanded, setExpanded] = (0, react_1.useState)({});
184
- const [tableSize, setTableSize] = (0, react_1.useState)(initialTableSize || 'medium');
185
- const [columnOrder, setColumnOrder] = (0, react_1.useState)((initialState === null || initialState === void 0 ? void 0 : initialState.columnOrder) || DEFAULT_INITIAL_STATE.columnOrder);
186
- const [columnPinning, setColumnPinning] = (0, react_1.useState)((initialState === null || initialState === void 0 ? void 0 : initialState.columnPinning) || DEFAULT_INITIAL_STATE.columnPinning);
187
- const [columnVisibility, setColumnVisibility] = (0, react_1.useState)((initialState === null || initialState === void 0 ? void 0 : initialState.columnVisibility) || DEFAULT_INITIAL_STATE.columnVisibility);
188
- const [columnSizing, setColumnSizing] = (0, react_1.useState)((initialState === null || initialState === void 0 ? void 0 : initialState.columnSizing) || DEFAULT_INITIAL_STATE.columnSizing);
189
- const [serverData, setServerData] = (0, react_1.useState)(null);
190
- const [serverTotal, setServerTotal] = (0, react_1.useState)(0);
191
- const [exportController, setExportController] = (0, react_1.useState)(null);
192
- const [exportProgress, setExportProgress] = (0, react_1.useState)({});
193
- const [exportPhase, setExportPhase] = (0, react_1.useState)(null);
194
- const [queuedExportCount, setQueuedExportCount] = (0, react_1.useState)(0);
195
- // -------------------------------
196
- // Ref hooks (grouped together)
197
- // -------------------------------
198
- const tableContainerRef = (0, react_1.useRef)(null);
199
- const internalApiRef = (0, react_1.useRef)(null);
200
- const exportControllerRef = (0, react_1.useRef)(null);
201
- const exportQueueRef = (0, react_1.useRef)(Promise.resolve());
202
- const isExternallyControlledData = (0, react_1.useMemo)(() => !onFetchData && (!!onDataChange || !!onFetchStateChange), [onFetchData, onDataChange, onFetchStateChange]);
203
- const { debouncedFetch, isLoading: fetchLoading } = (0, debounced_fetch_utils_1.useDebouncedFetch)(onFetchData);
204
- const tableData = (0, react_1.useMemo)(() => {
205
- if (isExternallyControlledData)
206
- return data;
207
- return serverData !== null ? serverData : data;
208
- }, [isExternallyControlledData, serverData, data]);
209
- const tableTotalRow = (0, react_1.useMemo)(() => (isExternallyControlledData ? (totalRow || data.length) : (serverData !== null ? serverTotal : totalRow || data.length)), [isExternallyControlledData, serverData, serverTotal, totalRow, data]);
210
- const tableLoading = (0, react_1.useMemo)(() => onFetchData ? (loading || fetchLoading) : loading, [onFetchData, loading, fetchLoading]);
211
- const enhancedColumns = (0, react_1.useMemo)(() => {
212
- let columnsMap = [...columns];
213
- if (enableExpanding) {
214
- const expandingColumnMap = (0, special_columns_utils_1.createExpandingColumn)({
215
- ...((slotProps === null || slotProps === void 0 ? void 0 : slotProps.expandColumn) && typeof slotProps.expandColumn === 'object' ? slotProps.expandColumn : {}),
216
- });
217
- columnsMap = [expandingColumnMap, ...columnsMap];
218
- }
219
- if (enableRowSelection) {
220
- const selectionColumnMap = (0, special_columns_utils_1.createSelectionColumn)({
221
- ...((slotProps === null || slotProps === void 0 ? void 0 : slotProps.selectionColumn) && typeof slotProps.selectionColumn === 'object' ? slotProps.selectionColumn : {}),
222
- multiSelect: enableMultiRowSelection,
223
- });
224
- columnsMap = [selectionColumnMap, ...columnsMap];
225
- }
226
- const enhancedColumns = (0, utils_1.withIdsDeep)(columnsMap);
227
- if (logger.isLevelEnabled('info')) {
228
- logger.info('enhancedColumns', { enhancedColumns });
229
- }
230
- return enhancedColumns;
231
- }, [columns, enableExpanding, enableRowSelection, logger, slotProps.expandColumn, slotProps.selectionColumn, enableMultiRowSelection]);
232
- const isExporting = (0, react_1.useMemo)(() => exportController !== null, [exportController]);
233
- const isSomeRowsSelected = (0, react_1.useMemo)(() => {
234
- if (!enableBulkActions || !enableRowSelection)
235
- return false;
236
- if (selectionState.type === 'exclude') {
237
- return selectionState.ids.length < tableTotalRow;
238
- }
239
- else {
240
- return selectionState.ids.length > 0;
241
- }
242
- }, [enableBulkActions, enableRowSelection, selectionState, tableTotalRow]);
243
- const selectedRowCount = (0, react_1.useMemo)(() => {
244
- if (!enableBulkActions || !enableRowSelection)
245
- return 0;
246
- if (selectionState.type === 'exclude') {
247
- return tableTotalRow - selectionState.ids.length;
248
- }
249
- else {
250
- return selectionState.ids.length;
251
- }
252
- }, [enableBulkActions, enableRowSelection, selectionState, tableTotalRow]);
253
- // -------------------------------
254
- // Callback hooks (grouped together)
255
- // -------------------------------
256
- const fetchData = (0, react_1.useCallback)(async (overrides = {}, options) => {
257
- var _a, _b, _c, _d, _e;
258
- const filters = {
259
- globalFilter,
260
- pagination,
261
- columnFilter,
262
- sorting,
263
- ...overrides,
264
- };
265
- if (onFetchStateChange) {
266
- onFetchStateChange(filters, options === null || options === void 0 ? void 0 : options.meta);
267
- }
268
- if (!onFetchData) {
269
- if (logger.isLevelEnabled('debug')) {
270
- logger.debug('onFetchData not provided, skipping fetch', { overrides, columnFilter, sorting, pagination });
271
- }
272
- return;
273
- }
274
- if (logger.isLevelEnabled('info')) {
275
- logger.info('Requesting data', {
276
- filters,
277
- reason: (_a = options === null || options === void 0 ? void 0 : options.meta) === null || _a === void 0 ? void 0 : _a.reason,
278
- force: (_b = options === null || options === void 0 ? void 0 : options.meta) === null || _b === void 0 ? void 0 : _b.force,
279
- });
280
- }
281
- try {
282
- const delay = (_c = options === null || options === void 0 ? void 0 : options.delay) !== null && _c !== void 0 ? _c : 300; // respects 0
283
- const result = await debouncedFetch(filters, {
284
- debounceDelay: delay,
285
- meta: options === null || options === void 0 ? void 0 : options.meta,
286
- });
287
- if (logger.isLevelEnabled('info')) {
288
- logger.info('Fetch resolved', {
289
- rows: (_e = (_d = result === null || result === void 0 ? void 0 : result.data) === null || _d === void 0 ? void 0 : _d.length) !== null && _e !== void 0 ? _e : 0,
290
- total: result === null || result === void 0 ? void 0 : result.total,
291
- });
292
- }
293
- if (result && Array.isArray(result.data) && result.total !== undefined) {
294
- setServerData(result.data);
295
- setServerTotal(result.total);
296
- }
297
- else if (logger.isLevelEnabled('warn')) {
298
- logger.warn('Fetch handler returned unexpected shape', result);
299
- }
300
- return result;
301
- }
302
- catch (error) {
303
- logger.error('Fetch failed', error);
304
- throw error;
305
- }
306
- }, [
307
- onFetchData,
308
- globalFilter,
309
- pagination,
310
- columnFilter,
311
- sorting,
312
- debouncedFetch,
313
- logger,
314
- onFetchStateChange,
315
- ]);
316
- const normalizeRefreshOptions = (0, react_1.useCallback)((options, fallbackReason = 'refresh') => {
317
- var _a, _b, _c;
318
- if (typeof options === 'boolean') {
319
- return {
320
- resetPagination: options,
321
- force: false,
322
- reason: fallbackReason,
323
- };
324
- }
325
- return {
326
- resetPagination: (_a = options === null || options === void 0 ? void 0 : options.resetPagination) !== null && _a !== void 0 ? _a : false,
327
- force: (_b = options === null || options === void 0 ? void 0 : options.force) !== null && _b !== void 0 ? _b : false,
328
- reason: (_c = options === null || options === void 0 ? void 0 : options.reason) !== null && _c !== void 0 ? _c : fallbackReason,
329
- };
330
- }, []);
331
- const handleSelectionStateChange = (0, react_1.useCallback)((updaterOrValue) => {
332
- setSelectionState((prevState) => {
333
- const next = typeof updaterOrValue === 'function' ? updaterOrValue(prevState) : updaterOrValue;
334
- onSelectionChange === null || onSelectionChange === void 0 ? void 0 : onSelectionChange(next);
335
- return next;
336
- });
337
- }, [onSelectionChange]);
338
- const handleColumnFilterStateChange = (0, react_1.useCallback)((filterState) => {
339
- if (!filterState || typeof filterState !== 'object')
340
- return;
341
- setColumnFilter(filterState);
342
- onColumnFiltersChange === null || onColumnFiltersChange === void 0 ? void 0 : onColumnFiltersChange(filterState);
343
- return filterState;
344
- }, [onColumnFiltersChange]);
345
- const resetPageToFirst = (0, react_1.useCallback)(() => {
346
- if (logger.isLevelEnabled('info')) {
347
- logger.info('Resetting to first page due to state change', {
348
- previousPageIndex: pagination.pageIndex,
349
- pageSize: pagination.pageSize,
350
- });
351
- }
352
- const newPagination = { pageIndex: 0, pageSize: pagination.pageSize };
353
- setPagination(newPagination);
354
- onPaginationChange === null || onPaginationChange === void 0 ? void 0 : onPaginationChange(newPagination);
355
- return newPagination;
356
- }, [pagination, logger, onPaginationChange]);
357
- const handleSortingChange = (0, react_1.useCallback)((updaterOrValue) => {
358
- setSorting((prev) => {
359
- const next = typeof updaterOrValue === 'function' ? updaterOrValue(prev) : updaterOrValue;
360
- const cleaned = next.filter((s) => s === null || s === void 0 ? void 0 : s.id);
361
- onSortingChange === null || onSortingChange === void 0 ? void 0 : onSortingChange(cleaned);
362
- const nextPagination = resetPageToFirst();
363
- if (isServerMode || isServerSorting) {
364
- fetchData({ sorting: cleaned, pagination: nextPagination }, { delay: 0 });
365
- }
366
- return cleaned;
367
- });
368
- }, [onSortingChange, isServerMode, isServerSorting, resetPageToFirst, fetchData]);
369
- const handleColumnOrderChange = (0, react_1.useCallback)((updatedColumnOrder) => {
370
- const newColumnOrder = typeof updatedColumnOrder === 'function'
371
- ? updatedColumnOrder(columnOrder)
372
- : updatedColumnOrder;
373
- setColumnOrder(newColumnOrder);
374
- if (onColumnDragEnd) {
375
- onColumnDragEnd(newColumnOrder);
376
- }
377
- }, [onColumnDragEnd, columnOrder]);
378
- const handleColumnPinningChange = (0, react_1.useCallback)((updater) => {
379
- setColumnPinning((prev) => {
380
- const next = typeof updater === "function" ? updater(prev) : updater;
381
- // keep direct callback here (optional)
382
- onColumnPinningChange === null || onColumnPinningChange === void 0 ? void 0 : onColumnPinningChange(next);
383
- return next;
384
- });
385
- }, [onColumnPinningChange]);
386
- // Column visibility change handler - same pattern as column order
387
- const handleColumnVisibilityChange = (0, react_1.useCallback)((updater) => {
388
- setColumnVisibility((prev) => {
389
- const next = typeof updater === 'function' ? updater(prev) : updater;
390
- onColumnVisibilityChange === null || onColumnVisibilityChange === void 0 ? void 0 : onColumnVisibilityChange(next);
391
- return next;
392
- });
393
- }, [onColumnVisibilityChange]);
394
- // Column sizing change handler - same pattern as column order
395
- const handleColumnSizingChange = (0, react_1.useCallback)((updater) => {
396
- setColumnSizing((prev) => {
397
- const next = typeof updater === 'function' ? updater(prev) : updater;
398
- onColumnSizingChange === null || onColumnSizingChange === void 0 ? void 0 : onColumnSizingChange(next);
399
- return next;
400
- });
401
- }, [onColumnSizingChange]);
402
- const handlePaginationChange = (0, react_1.useCallback)((updater) => {
403
- setPagination((prev) => {
404
- const next = typeof updater === 'function' ? updater(prev) : updater;
405
- onPaginationChange === null || onPaginationChange === void 0 ? void 0 : onPaginationChange(next);
406
- if (isServerMode || isServerPagination) {
407
- fetchData({ pagination: next }, { delay: 0 });
408
- }
409
- return next;
410
- });
411
- }, [isServerMode, isServerPagination, fetchData, onPaginationChange]);
412
- const handleGlobalFilterChange = (0, react_1.useCallback)((updaterOrValue) => {
413
- setGlobalFilter((prev) => {
414
- const next = typeof updaterOrValue === 'function' ? updaterOrValue(prev) : updaterOrValue;
415
- onGlobalFilterChange === null || onGlobalFilterChange === void 0 ? void 0 : onGlobalFilterChange(next);
416
- if (isServerMode || isServerFiltering) {
417
- const nextPagination = { pageIndex: 0, pageSize: pagination.pageSize };
418
- setPagination(nextPagination);
419
- fetchData({ globalFilter: next, pagination: nextPagination }, { delay: 0 });
420
- }
421
- return next;
422
- });
423
- }, [isServerMode, isServerFiltering, onGlobalFilterChange, fetchData, pagination.pageSize]);
424
- const onColumnFilterChangeHandler = (0, react_1.useCallback)((updater) => {
425
- const currentState = columnFilter;
426
- const newState = typeof updater === 'function'
427
- ? updater(currentState)
428
- : updater;
429
- const legacyFilterState = {
430
- filters: newState.filters,
431
- logic: newState.logic,
432
- pendingFilters: newState.pendingFilters,
433
- pendingLogic: newState.pendingLogic
434
- };
435
- handleColumnFilterStateChange(legacyFilterState);
436
- }, [columnFilter, handleColumnFilterStateChange]);
437
- const onColumnFilterApplyHandler = (0, react_1.useCallback)((appliedState) => {
438
- const pagination = resetPageToFirst();
439
- if (isServerFiltering) {
440
- fetchData({
441
- columnFilter: appliedState,
442
- pagination,
443
- });
444
- }
445
- onColumnFiltersChange === null || onColumnFiltersChange === void 0 ? void 0 : onColumnFiltersChange(appliedState);
446
- }, [resetPageToFirst, isServerFiltering, fetchData, onColumnFiltersChange]);
447
- // -------------------------------
448
- // Table creation (after callbacks/memo)
449
- // -------------------------------
450
- const table = (0, react_table_1.useReactTable)({
451
- _features: [column_filter_feature_1.ColumnFilterFeature, features_1.SelectionFeature],
452
- data: tableData,
453
- columns: enhancedColumns,
454
- // Use merged initial state so built-in reset helpers align with our controlled state defaults
455
- initialState: initialStateConfig,
456
- state: {
457
- ...(enableSorting ? { sorting } : {}),
458
- ...(enablePagination ? { pagination } : {}),
459
- ...(enableGlobalFilter ? { globalFilter } : {}),
460
- ...(enableExpanding ? { expanded } : {}),
461
- ...(enableColumnDragging ? { columnOrder } : {}),
462
- ...(enableColumnPinning ? { columnPinning } : {}),
463
- ...(enableColumnVisibility ? { columnVisibility } : {}),
464
- ...(enableColumnResizing ? { columnSizing } : {}),
465
- ...(enableColumnFilter ? { columnFilter } : {}),
466
- ...(enableRowSelection ? { selectionState } : {}),
467
- },
468
- // Selection options (same pattern as column filter)
469
- // Add custom features
470
- selectMode: selectMode,
471
- enableAdvanceSelection: !!enableRowSelection,
472
- isRowSelectable: isRowSelectable,
473
- ...(enableRowSelection ? { onSelectionStateChange: handleSelectionStateChange } : {}),
474
- // Column filter
475
- enableAdvanceColumnFilter: enableColumnFilter,
476
- onColumnFilterChange: onColumnFilterChangeHandler, // Handle column filters change
477
- onColumnFilterApply: onColumnFilterApplyHandler, // Handle when filters are actually applied
478
- ...(enableSorting ? { onSortingChange: handleSortingChange } : {}),
479
- ...(enablePagination ? { onPaginationChange: handlePaginationChange } : {}),
480
- ...(enableGlobalFilter ? { onGlobalFilterChange: handleGlobalFilterChange } : {}),
481
- ...(enableExpanding ? { onExpandedChange: setExpanded } : {}),
482
- ...(enableColumnDragging ? { onColumnOrderChange: handleColumnOrderChange } : {}),
483
- ...(enableColumnPinning ? { onColumnPinningChange: handleColumnPinningChange } : {}),
484
- ...(enableColumnVisibility ? { onColumnVisibilityChange: handleColumnVisibilityChange } : {}),
485
- ...(enableColumnResizing ? { onColumnSizingChange: handleColumnSizingChange } : {}),
486
- // Row model
487
- getCoreRowModel: (0, react_table_1.getCoreRowModel)(),
488
- ...(enableSorting ? { getSortedRowModel: (0, react_table_1.getSortedRowModel)() } : {}),
489
- ...(enableColumnFilter || enableGlobalFilter ? { getFilteredRowModel: (0, column_filter_feature_1.getCombinedFilteredRowModel)() } : {}),
490
- // Only use getPaginationRowModel for client-side pagination
491
- ...(enablePagination && !isServerPagination ? { getPaginationRowModel: (0, react_table_1.getPaginationRowModel)() } : {}),
492
- // Sorting
493
- enableSorting: enableSorting,
494
- manualSorting: isServerSorting,
495
- // Filtering
496
- manualFiltering: isServerFiltering,
497
- // Column resizing
498
- enableColumnResizing: enableColumnResizing,
499
- columnResizeMode: columnResizeMode,
500
- columnResizeDirection: theme.direction,
501
- // Column pinning
502
- enableColumnPinning: enableColumnPinning,
503
- // Expanding
504
- ...(enableExpanding ? { getRowCanExpand: getRowCanExpand } : {}),
505
- // Pagination
506
- manualPagination: isServerPagination,
507
- autoResetPageIndex: false, // Prevent automatic page reset on state changes
508
- // pageCount: enablePagination ? Math.ceil(tableTotalRow / pagination.pageSize) : -1,
509
- rowCount: enablePagination ? (tableTotalRow !== null && tableTotalRow !== void 0 ? tableTotalRow : tableData.length) : tableData.length,
510
- // Row ID
511
- getRowId: (row, index) => (0, utils_1.generateRowId)(row, index, idKey),
512
- // Debug
513
- debugAll: false, // Disabled for production
514
- });
515
- // Compute width after table is created so column resizing is safe and reflects changes
516
- const allLeafColumns = table.getAllLeafColumns();
517
- const visibleLeafColumns = table.getVisibleLeafColumns();
518
- const hasExplicitSizing = allLeafColumns.some((column) => {
519
- const { size, minSize, maxSize } = column.columnDef;
520
- return size !== undefined || minSize !== undefined || maxSize !== undefined;
521
- });
522
- const useFixedLayout = fitToScreen || enableColumnResizing || hasExplicitSizing;
523
- const tableTotalSize = table.getTotalSize();
524
- const tableWidth = fitToScreen ? '100%' : (useFixedLayout ? tableTotalSize : '100%');
525
- const tableStyle = {
526
- width: tableWidth,
527
- minWidth: fitToScreen ? tableTotalSize : undefined,
528
- tableLayout: useFixedLayout ? 'fixed' : 'auto',
529
- };
530
- // -------------------------------
531
- // Virtualization and row memo
532
- // -------------------------------
533
- // Note: globalFilter is needed in dependencies to trigger recalculation when filter changes
534
- // The table object is stable, so we need to depend on the filter state directly
535
- const rows = table.getRowModel().rows;
536
- const rowVirtualizer = (0, react_virtual_1.useVirtualizer)({
537
- count: rows.length,
538
- getScrollElement: () => tableContainerRef.current,
539
- estimateSize: () => estimateRowHeight,
540
- overscan: 10,
541
- enabled: enableVirtualization && !enablePagination && rows.length > 0,
542
- });
543
- // -------------------------------
544
- // Callbacks (after table creation)
545
- // -------------------------------
546
- const handleColumnReorder = (0, react_1.useCallback)((draggedColumnId, targetColumnId) => {
547
- const currentOrder = columnOrder.length > 0 ? columnOrder : enhancedColumns.map((col, index) => {
548
- if (col.id)
549
- return col.id;
550
- const anyCol = col;
551
- if (anyCol.accessorKey && typeof anyCol.accessorKey === 'string') {
552
- return anyCol.accessorKey;
553
- }
554
- return `column_${index}`;
555
- });
556
- const draggedIndex = currentOrder.indexOf(draggedColumnId);
557
- const targetIndex = currentOrder.indexOf(targetColumnId);
558
- if (draggedIndex === -1 || targetIndex === -1)
559
- return;
560
- const newOrder = [...currentOrder];
561
- newOrder.splice(draggedIndex, 1);
562
- newOrder.splice(targetIndex, 0, draggedColumnId);
563
- handleColumnOrderChange(newOrder);
564
- }, [columnOrder, enhancedColumns, handleColumnOrderChange]);
565
- // -------------------------------
566
- // Effects (after callbacks)
567
- // -------------------------------
568
- (0, react_1.useEffect)(() => {
569
- if (!isExternallyControlledData || serverData === null)
570
- return;
571
- setServerData(null);
572
- setServerTotal(0);
573
- }, [isExternallyControlledData, serverData]);
574
- (0, react_1.useEffect)(() => {
575
- if (initialLoadData && (onFetchData || onFetchStateChange)) {
576
- if (logger.isLevelEnabled('info')) {
577
- logger.info('Initial data load triggered', { initialLoadData });
578
- }
579
- fetchData({}, {
580
- delay: 0,
581
- meta: { reason: 'initial' },
582
- });
583
- }
584
- else if (logger.isLevelEnabled('debug')) {
585
- logger.debug('Skipping initial data load', {
586
- initialLoadData,
587
- hasOnFetchData: !!onFetchData
588
- });
589
- }
590
- // eslint-disable-next-line react-hooks/exhaustive-deps
591
- }, []);
592
- (0, react_1.useEffect)(() => {
593
- if (enableColumnDragging && columnOrder.length === 0) {
594
- const initialOrder = enhancedColumns.map((col, index) => {
595
- if (col.id)
596
- return col.id;
597
- const anyCol = col;
598
- if (anyCol.accessorKey && typeof anyCol.accessorKey === 'string') {
599
- return anyCol.accessorKey;
600
- }
601
- return `column_${index}`;
602
- });
603
- setColumnOrder(initialOrder);
604
- }
605
- }, [enableColumnDragging, enhancedColumns, columnOrder.length]);
606
- const lastSentRef = (0, react_1.useRef)("");
607
- const emitTableState = (0, react_1.useCallback)(() => {
608
- if (!onDataStateChange)
609
- return;
610
- const live = table.getState();
611
- const liveColumnFilter = live.columnFilter;
612
- // only keep what you persist/store
613
- const payload = {
614
- sorting: live.sorting,
615
- pagination: live.pagination,
616
- globalFilter: live.globalFilter,
617
- columnFilter: liveColumnFilter,
618
- columnVisibility: live.columnVisibility,
619
- columnSizing: live.columnSizing,
620
- columnOrder: live.columnOrder,
621
- columnPinning: live.columnPinning,
622
- };
623
- const key = JSON.stringify(payload);
624
- if (key === lastSentRef.current)
625
- return;
626
- lastSentRef.current = key;
627
- onDataStateChange(payload);
628
- }, [onDataStateChange, table]);
629
- (0, react_1.useEffect)(() => {
630
- emitTableState();
631
- }, [
632
- emitTableState,
633
- sorting,
634
- pagination,
635
- globalFilter,
636
- columnFilter,
637
- columnVisibility,
638
- columnSizing,
639
- columnOrder,
640
- columnPinning,
641
- ]);
642
- const getResetState = (0, react_1.useCallback)(() => {
643
- var _a;
644
- const resetSorting = initialStateConfig.sorting || [];
645
- const resetGlobalFilter = (_a = initialStateConfig.globalFilter) !== null && _a !== void 0 ? _a : '';
646
- const resetColumnFilter = initialStateConfig.columnFilter;
647
- const resetPagination = enablePagination
648
- ? (initialStateConfig.pagination || { pageIndex: 0, pageSize: 10 })
649
- : undefined;
650
- return {
651
- sorting: resetSorting,
652
- globalFilter: resetGlobalFilter,
653
- columnFilter: resetColumnFilter,
654
- ...(resetPagination ? { pagination: resetPagination } : {}),
655
- };
656
- }, [initialStateConfig, enablePagination]);
657
- const applyDataMutation = (0, react_1.useCallback)((action, updater, details = {}) => {
658
- const previousData = [...tableData];
659
- const nextData = updater(previousData);
660
- if (nextData === previousData)
661
- return nextData;
662
- const nextTotal = Math.max(0, tableTotalRow + (nextData.length - previousData.length));
663
- if (!isExternallyControlledData) {
664
- setServerData(nextData);
665
- setServerTotal(nextTotal);
666
- }
667
- onDataChange === null || onDataChange === void 0 ? void 0 : onDataChange(nextData, {
668
- action,
669
- previousData,
670
- nextData,
671
- totalRow: nextTotal,
672
- ...details,
673
- });
674
- if (logger.isLevelEnabled('debug')) {
675
- logger.debug('Applied data mutation', {
676
- action,
677
- previousCount: previousData.length,
678
- nextCount: nextData.length,
679
- totalRow: nextTotal,
680
- });
681
- }
682
- return nextData;
683
- }, [isExternallyControlledData, logger, onDataChange, tableData, tableTotalRow]);
684
- const triggerRefresh = (0, react_1.useCallback)(async (options, fallbackReason = 'refresh') => {
685
- const normalizedOptions = normalizeRefreshOptions(options, fallbackReason);
686
- const nextPagination = enablePagination
687
- ? {
688
- pageIndex: normalizedOptions.resetPagination ? 0 : pagination.pageIndex,
689
- pageSize: pagination.pageSize,
690
- }
691
- : undefined;
692
- const shouldUpdatePagination = !!nextPagination
693
- && (nextPagination.pageIndex !== pagination.pageIndex || nextPagination.pageSize !== pagination.pageSize);
694
- if (nextPagination && shouldUpdatePagination) {
695
- setPagination(nextPagination);
696
- onPaginationChange === null || onPaginationChange === void 0 ? void 0 : onPaginationChange(nextPagination);
697
- }
698
- await fetchData(nextPagination ? { pagination: nextPagination } : {}, {
699
- delay: 0,
700
- meta: {
701
- reason: normalizedOptions.reason,
702
- force: normalizedOptions.force,
703
- },
704
- });
705
- return;
706
- }, [normalizeRefreshOptions, enablePagination, pagination, onPaginationChange, fetchData]);
707
- const resetAllAndReload = (0, react_1.useCallback)(() => {
708
- var _a;
709
- const resetState = getResetState();
710
- setSorting(resetState.sorting || []);
711
- setGlobalFilter((_a = resetState.globalFilter) !== null && _a !== void 0 ? _a : '');
712
- setColumnFilter(resetState.columnFilter);
713
- if (resetState.pagination) {
714
- setPagination(resetState.pagination);
715
- onPaginationChange === null || onPaginationChange === void 0 ? void 0 : onPaginationChange(resetState.pagination);
716
- }
717
- setSelectionState(initialSelectionState);
718
- setExpanded({});
719
- // layout state
720
- setColumnVisibility(initialStateConfig.columnVisibility || {});
721
- setColumnSizing(initialStateConfig.columnSizing || {});
722
- setColumnOrder(initialStateConfig.columnOrder || []);
723
- setColumnPinning(initialStateConfig.columnPinning || { left: [], right: [] });
724
- const resetOptions = normalizeRefreshOptions({
725
- resetPagination: true,
726
- force: true,
727
- reason: 'reset',
728
- }, 'reset');
729
- void fetchData(resetState, {
730
- delay: 0,
731
- meta: {
732
- reason: resetOptions.reason,
733
- force: resetOptions.force,
734
- },
735
- });
736
- }, [getResetState, initialSelectionState, initialStateConfig, onPaginationChange, normalizeRefreshOptions, fetchData]);
737
- const setExportControllerSafely = (0, react_1.useCallback)((value) => {
738
- setExportController((current) => {
739
- const next = typeof value === 'function' ? value(current) : value;
740
- exportControllerRef.current = next;
741
- return next;
742
- });
743
- }, []);
744
- const handleExportProgressInternal = (0, react_1.useCallback)((progress) => {
745
- setExportProgress(progress || {});
746
- onExportProgress === null || onExportProgress === void 0 ? void 0 : onExportProgress(progress);
747
- }, [onExportProgress]);
748
- const handleExportStateChangeInternal = (0, react_1.useCallback)((state) => {
749
- setExportPhase(state.phase);
750
- if (state.processedRows !== undefined
751
- || state.totalRows !== undefined
752
- || state.percentage !== undefined) {
753
- setExportProgress({
754
- processedRows: state.processedRows,
755
- totalRows: state.totalRows,
756
- percentage: state.percentage,
757
- });
758
- }
759
- onExportStateChange === null || onExportStateChange === void 0 ? void 0 : onExportStateChange(state);
760
- }, [onExportStateChange]);
761
- const runExportWithPolicy = (0, react_1.useCallback)(async (options) => {
762
- const { format, filename, mode, execute } = options;
763
- const startExecution = async () => {
764
- const controller = new AbortController();
765
- setExportProgress({});
766
- setExportControllerSafely(controller);
767
- try {
768
- await execute(controller);
769
- }
770
- finally {
771
- setExportControllerSafely((current) => (current === controller ? null : current));
772
- }
773
- };
774
- if (exportConcurrency === 'queue') {
775
- setQueuedExportCount((prev) => prev + 1);
776
- const runQueued = async () => {
777
- setQueuedExportCount((prev) => Math.max(0, prev - 1));
778
- await startExecution();
779
- };
780
- const queuedPromise = exportQueueRef.current
781
- .catch(() => undefined)
782
- .then(runQueued);
783
- exportQueueRef.current = queuedPromise;
784
- return queuedPromise;
785
- }
786
- const activeController = exportControllerRef.current;
787
- if (activeController) {
788
- if (exportConcurrency === 'ignoreIfRunning') {
789
- handleExportStateChangeInternal({
790
- phase: 'error',
791
- mode,
792
- format,
793
- filename,
794
- message: 'An export is already running',
795
- code: 'EXPORT_IN_PROGRESS',
796
- endedAt: Date.now(),
797
- });
798
- onExportError === null || onExportError === void 0 ? void 0 : onExportError({
799
- message: 'An export is already running',
800
- code: 'EXPORT_IN_PROGRESS',
801
- });
802
- return;
803
- }
804
- if (exportConcurrency === 'cancelAndRestart') {
805
- activeController.abort();
806
- }
807
- }
808
- await startExecution();
809
- }, [
810
- exportConcurrency,
811
- handleExportStateChangeInternal,
812
- onExportError,
813
- setExportControllerSafely,
814
- ]);
815
- const dataTableApi = (0, react_1.useMemo)(() => {
816
- // helpers (avoid repeating boilerplate)
817
- const buildInitialOrder = () => enhancedColumns.map((col, index) => {
818
- if (col.id)
819
- return col.id;
820
- const anyCol = col;
821
- if (anyCol.accessorKey && typeof anyCol.accessorKey === "string")
822
- return anyCol.accessorKey;
823
- return `column_${index}`;
824
- });
825
- const applyColumnOrder = (next) => {
826
- // handleColumnOrderChange supports both Updater<ColumnOrderState> and array in your impl
827
- handleColumnOrderChange(next);
828
- };
829
- const applyPinning = (next) => {
830
- handleColumnPinningChange(next);
831
- };
832
- const applyVisibility = (next) => {
833
- handleColumnVisibilityChange(next);
834
- };
835
- const applySizing = (next) => {
836
- handleColumnSizingChange(next);
837
- };
838
- const applyPagination = (next) => {
839
- handlePaginationChange(next);
840
- };
841
- const applySorting = (next) => {
842
- handleSortingChange(next);
843
- };
844
- const applyGlobalFilter = (next) => {
845
- handleGlobalFilterChange(next);
846
- };
847
- const getRowIndexById = (rowsToSearch, rowId) => rowsToSearch.findIndex((row, index) => String((0, utils_1.generateRowId)(row, index, idKey)) === rowId);
848
- const clampInsertIndex = (rowsToMutate, insertIndex) => {
849
- if (insertIndex === undefined)
850
- return rowsToMutate.length;
851
- return Math.max(0, Math.min(insertIndex, rowsToMutate.length));
852
- };
853
- return {
854
- table: {
855
- getTable: () => table,
856
- },
857
- // -------------------------------
858
- // Column Management
859
- // -------------------------------
860
- columnVisibility: {
861
- showColumn: (columnId) => {
862
- applyVisibility({ ...table.getState().columnVisibility, [columnId]: true });
863
- },
864
- hideColumn: (columnId) => {
865
- applyVisibility({ ...table.getState().columnVisibility, [columnId]: false });
866
- },
867
- toggleColumn: (columnId) => {
868
- var _a, _b;
869
- const curr = (_b = (_a = table.getState().columnVisibility) === null || _a === void 0 ? void 0 : _a[columnId]) !== null && _b !== void 0 ? _b : true;
870
- applyVisibility({ ...table.getState().columnVisibility, [columnId]: !curr });
871
- },
872
- showAllColumns: () => {
873
- // set all known columns true
874
- const all = {};
875
- table.getAllLeafColumns().forEach((c) => (all[c.id] = true));
876
- applyVisibility(all);
877
- },
878
- hideAllColumns: () => {
879
- const all = {};
880
- table.getAllLeafColumns().forEach((c) => (all[c.id] = false));
881
- applyVisibility(all);
882
- },
883
- resetColumnVisibility: () => {
884
- const initialVisibility = initialStateConfig.columnVisibility || {};
885
- applyVisibility(initialVisibility);
886
- },
887
- },
888
- // -------------------------------
889
- // Column Ordering
890
- // -------------------------------
891
- columnOrdering: {
892
- setColumnOrder: (nextOrder) => {
893
- applyColumnOrder(nextOrder);
894
- },
895
- moveColumn: (columnId, toIndex) => {
896
- var _a;
897
- const currentOrder = (((_a = table.getState().columnOrder) === null || _a === void 0 ? void 0 : _a.length) ? table.getState().columnOrder : buildInitialOrder()) || [];
898
- const fromIndex = currentOrder.indexOf(columnId);
899
- if (fromIndex === -1)
900
- return;
901
- const next = [...currentOrder];
902
- next.splice(fromIndex, 1);
903
- next.splice(toIndex, 0, columnId);
904
- applyColumnOrder(next);
905
- },
906
- resetColumnOrder: () => {
907
- applyColumnOrder(buildInitialOrder());
908
- },
909
- },
910
- // -------------------------------
911
- // Column Pinning
912
- // -------------------------------
913
- columnPinning: {
914
- pinColumnLeft: (columnId) => {
915
- const current = table.getState().columnPinning || { left: [], right: [] };
916
- const next = {
917
- left: [...(current.left || []).filter((id) => id !== columnId), columnId],
918
- right: (current.right || []).filter((id) => id !== columnId),
919
- };
920
- applyPinning(next);
921
- },
922
- pinColumnRight: (columnId) => {
923
- const current = table.getState().columnPinning || { left: [], right: [] };
924
- const next = {
925
- left: (current.left || []).filter((id) => id !== columnId),
926
- // keep your "prepend" behavior
927
- right: [columnId, ...(current.right || []).filter((id) => id !== columnId)],
928
- };
929
- applyPinning(next);
930
- },
931
- unpinColumn: (columnId) => {
932
- const current = table.getState().columnPinning || { left: [], right: [] };
933
- const next = {
934
- left: (current.left || []).filter((id) => id !== columnId),
935
- right: (current.right || []).filter((id) => id !== columnId),
936
- };
937
- applyPinning(next);
938
- },
939
- setPinning: (pinning) => {
940
- applyPinning(pinning);
941
- },
942
- resetColumnPinning: () => {
943
- const initialPinning = initialStateConfig.columnPinning || { left: [], right: [] };
944
- applyPinning(initialPinning);
945
- },
946
- },
947
- // -------------------------------
948
- // Column Resizing
949
- // -------------------------------
950
- columnResizing: {
951
- resizeColumn: (columnId, width) => {
952
- const currentSizing = table.getState().columnSizing || {};
953
- applySizing({ ...currentSizing, [columnId]: width });
954
- },
955
- autoSizeColumn: (columnId) => {
956
- // safe to call tanstack helper; it will feed into onColumnSizingChange if wired,
957
- // but since you're controlled, we still prefer to update through handler:
958
- const col = table.getColumn(columnId);
959
- if (!col)
960
- return;
961
- col.resetSize();
962
- // after resetSize, read state and emit via handler so controlled stays synced
963
- applySizing({ ...(table.getState().columnSizing || {}) });
964
- },
965
- autoSizeAllColumns: () => {
966
- const initialSizing = initialStateConfig.columnSizing || {};
967
- applySizing(initialSizing);
968
- },
969
- resetColumnSizing: () => {
970
- const initialSizing = initialStateConfig.columnSizing || {};
971
- applySizing(initialSizing);
972
- },
973
- },
974
- // -------------------------------
975
- // Filtering
976
- // -------------------------------
977
- filtering: {
978
- setGlobalFilter: (filter) => {
979
- applyGlobalFilter(filter);
980
- },
981
- clearGlobalFilter: () => {
982
- applyGlobalFilter("");
983
- },
984
- setColumnFilters: (filters) => {
985
- handleColumnFilterStateChange(filters);
986
- },
987
- addColumnFilter: (columnId, operator, value) => {
988
- const newFilter = {
989
- id: `filter_${Date.now()}`,
990
- columnId,
991
- operator,
992
- value,
993
- };
994
- const current = table.getState().columnFilter;
995
- const currentFilters = (current === null || current === void 0 ? void 0 : current.filters) || [];
996
- const nextFilters = [...currentFilters, newFilter];
997
- handleColumnFilterStateChange({
998
- filters: nextFilters,
999
- logic: current === null || current === void 0 ? void 0 : current.logic,
1000
- pendingFilters: (current === null || current === void 0 ? void 0 : current.pendingFilters) || [],
1001
- pendingLogic: (current === null || current === void 0 ? void 0 : current.pendingLogic) || "AND",
1002
- });
1003
- if (logger.isLevelEnabled("debug")) {
1004
- logger.debug(`Adding column filter ${columnId} ${operator} ${value}`, nextFilters);
1005
- }
1006
- },
1007
- removeColumnFilter: (filterId) => {
1008
- const current = table.getState().columnFilter;
1009
- const currentFilters = (current === null || current === void 0 ? void 0 : current.filters) || [];
1010
- const nextFilters = currentFilters.filter((f) => f.id !== filterId);
1011
- handleColumnFilterStateChange({
1012
- filters: nextFilters,
1013
- logic: current === null || current === void 0 ? void 0 : current.logic,
1014
- pendingFilters: (current === null || current === void 0 ? void 0 : current.pendingFilters) || [],
1015
- pendingLogic: (current === null || current === void 0 ? void 0 : current.pendingLogic) || "AND",
1016
- });
1017
- if (logger.isLevelEnabled("debug")) {
1018
- logger.debug(`Removing column filter ${filterId}`, nextFilters);
1019
- }
1020
- },
1021
- clearAllFilters: () => {
1022
- applyGlobalFilter("");
1023
- handleColumnFilterStateChange({
1024
- filters: [],
1025
- logic: "AND",
1026
- pendingFilters: [],
1027
- pendingLogic: "AND",
1028
- });
1029
- },
1030
- resetFilters: () => {
1031
- handleColumnFilterStateChange({
1032
- filters: [],
1033
- logic: "AND",
1034
- pendingFilters: [],
1035
- pendingLogic: "AND",
1036
- });
1037
- if (logger.isLevelEnabled("debug")) {
1038
- logger.debug("Resetting filters");
1039
- }
1040
- },
1041
- },
1042
- // -------------------------------
1043
- // Sorting
1044
- // -------------------------------
1045
- sorting: {
1046
- setSorting: (sortingState) => {
1047
- applySorting(sortingState);
1048
- if (logger.isLevelEnabled("debug"))
1049
- logger.debug("Setting sorting", sortingState);
1050
- },
1051
- // NOTE: toggleSorting is okay, but can become "one behind" in controlled server mode.
1052
- // So we implement deterministic sorting through handler.
1053
- sortColumn: (columnId, direction) => {
1054
- const current = table.getState().sorting || [];
1055
- const filtered = current.filter((s) => s.id !== columnId);
1056
- if (direction === false) {
1057
- applySorting(filtered);
1058
- return;
1059
- }
1060
- applySorting([{ id: columnId, desc: direction === "desc" }, ...filtered]);
1061
- },
1062
- clearSorting: () => {
1063
- applySorting([]);
1064
- },
1065
- resetSorting: () => {
1066
- const initialSorting = initialStateConfig.sorting || [];
1067
- applySorting(initialSorting);
1068
- },
1069
- },
1070
- // -------------------------------
1071
- // Pagination
1072
- // -------------------------------
1073
- pagination: {
1074
- goToPage: (pageIndex) => {
1075
- applyPagination((prev) => ({ ...prev, pageIndex }));
1076
- if (logger.isLevelEnabled("debug"))
1077
- logger.debug(`Going to page ${pageIndex}`);
1078
- },
1079
- nextPage: () => {
1080
- applyPagination((prev) => { var _a; return ({ ...prev, pageIndex: ((_a = prev === null || prev === void 0 ? void 0 : prev.pageIndex) !== null && _a !== void 0 ? _a : 0) + 1 }); });
1081
- if (logger.isLevelEnabled("debug"))
1082
- logger.debug("Next page");
1083
- },
1084
- previousPage: () => {
1085
- applyPagination((prev) => { var _a; return ({ ...prev, pageIndex: Math.max(0, ((_a = prev === null || prev === void 0 ? void 0 : prev.pageIndex) !== null && _a !== void 0 ? _a : 0) - 1) }); });
1086
- if (logger.isLevelEnabled("debug"))
1087
- logger.debug("Previous page");
1088
- },
1089
- setPageSize: (pageSize) => {
1090
- // usually want pageIndex reset
1091
- applyPagination(() => ({ pageIndex: 0, pageSize }));
1092
- if (logger.isLevelEnabled("debug"))
1093
- logger.debug(`Setting page size to ${pageSize}`);
1094
- },
1095
- goToFirstPage: () => {
1096
- applyPagination((prev) => ({ ...prev, pageIndex: 0 }));
1097
- if (logger.isLevelEnabled("debug"))
1098
- logger.debug("Going to first page");
1099
- },
1100
- goToLastPage: () => {
1101
- var _a, _b;
1102
- // pageCount can be derived; keep safe fallback
1103
- const pageCount = (_b = (_a = table.getPageCount) === null || _a === void 0 ? void 0 : _a.call(table)) !== null && _b !== void 0 ? _b : 0;
1104
- if (pageCount > 0) {
1105
- applyPagination((prev) => ({ ...prev, pageIndex: pageCount - 1 }));
1106
- if (logger.isLevelEnabled("debug"))
1107
- logger.debug(`Going to last page ${pageCount - 1}`);
1108
- }
1109
- },
1110
- resetPagination: () => {
1111
- const initialPagination = initialStateConfig.pagination || { pageIndex: 0, pageSize: 10 };
1112
- applyPagination(initialPagination);
1113
- },
1114
- },
1115
- // -------------------------------
1116
- // Selection
1117
- // -------------------------------
1118
- selection: {
1119
- selectRow: (rowId) => { var _a; return (_a = table.selectRow) === null || _a === void 0 ? void 0 : _a.call(table, rowId); },
1120
- deselectRow: (rowId) => { var _a; return (_a = table.deselectRow) === null || _a === void 0 ? void 0 : _a.call(table, rowId); },
1121
- toggleRowSelection: (rowId) => { var _a; return (_a = table.toggleRowSelected) === null || _a === void 0 ? void 0 : _a.call(table, rowId); },
1122
- selectAll: () => { var _a; return (_a = table.selectAll) === null || _a === void 0 ? void 0 : _a.call(table); },
1123
- deselectAll: () => { var _a; return (_a = table.deselectAll) === null || _a === void 0 ? void 0 : _a.call(table); },
1124
- toggleSelectAll: () => { var _a; return (_a = table.toggleAllRowsSelected) === null || _a === void 0 ? void 0 : _a.call(table); },
1125
- getSelectionState: () => { var _a; return ((_a = table.getSelectionState) === null || _a === void 0 ? void 0 : _a.call(table)) || { ids: [], type: "include" }; },
1126
- getSelectedRows: () => table.getSelectedRows(),
1127
- getSelectedCount: () => table.getSelectedCount(),
1128
- isRowSelected: (rowId) => table.getIsRowSelected(rowId) || false,
1129
- },
1130
- // -------------------------------
1131
- // Data Management (kept same, but ensure state changes go through handlers)
1132
- // -------------------------------
1133
- data: {
1134
- refresh: (options) => {
1135
- void triggerRefresh(options, 'refresh');
1136
- },
1137
- reload: (options = {}) => {
1138
- var _a, _b;
1139
- void triggerRefresh({
1140
- ...options,
1141
- resetPagination: (_a = options.resetPagination) !== null && _a !== void 0 ? _a : false,
1142
- reason: (_b = options.reason) !== null && _b !== void 0 ? _b : 'reload',
1143
- }, 'reload');
1144
- },
1145
- resetAll: () => resetAllAndReload(),
1146
- getAllData: () => [...tableData],
1147
- getRowData: (rowId) => {
1148
- const rowIndex = getRowIndexById(tableData, rowId);
1149
- return rowIndex === -1 ? undefined : tableData[rowIndex];
1150
- },
1151
- getRowByIndex: (index) => tableData[index],
1152
- updateRow: (rowId, updates) => {
1153
- applyDataMutation('updateRow', (rowsToMutate) => {
1154
- const rowIndex = getRowIndexById(rowsToMutate, rowId);
1155
- if (rowIndex === -1)
1156
- return rowsToMutate;
1157
- const nextData = [...rowsToMutate];
1158
- nextData[rowIndex] = { ...nextData[rowIndex], ...updates };
1159
- return nextData;
1160
- }, { rowId });
1161
- },
1162
- updateRowByIndex: (index, updates) => {
1163
- applyDataMutation('updateRowByIndex', (rowsToMutate) => {
1164
- if (!rowsToMutate[index])
1165
- return rowsToMutate;
1166
- const nextData = [...rowsToMutate];
1167
- nextData[index] = { ...nextData[index], ...updates };
1168
- return nextData;
1169
- }, { index });
1170
- },
1171
- insertRow: (newRow, index) => {
1172
- applyDataMutation('insertRow', (rowsToMutate) => {
1173
- const nextData = [...rowsToMutate];
1174
- nextData.splice(clampInsertIndex(nextData, index), 0, newRow);
1175
- return nextData;
1176
- }, { index });
1177
- },
1178
- deleteRow: (rowId) => {
1179
- applyDataMutation('deleteRow', (rowsToMutate) => {
1180
- const rowIndex = getRowIndexById(rowsToMutate, rowId);
1181
- if (rowIndex === -1)
1182
- return rowsToMutate;
1183
- const nextData = [...rowsToMutate];
1184
- nextData.splice(rowIndex, 1);
1185
- return nextData;
1186
- }, { rowId });
1187
- },
1188
- deleteRowByIndex: (index) => {
1189
- applyDataMutation('deleteRowByIndex', (rowsToMutate) => {
1190
- if (index < 0 || index >= rowsToMutate.length)
1191
- return rowsToMutate;
1192
- const nextData = [...rowsToMutate];
1193
- nextData.splice(index, 1);
1194
- return nextData;
1195
- }, { index });
1196
- },
1197
- deleteSelectedRows: () => {
1198
- var _a, _b, _c;
1199
- const currentSelection = ((_a = table.getSelectionState) === null || _a === void 0 ? void 0 : _a.call(table)) || selectionState;
1200
- const selectedIds = new Set((currentSelection.ids || []).map((id) => String(id)));
1201
- const loadedRowIds = tableData.map((row, index) => String((0, utils_1.generateRowId)(row, index, idKey)));
1202
- const deletableRowIds = currentSelection.type === 'exclude'
1203
- ? loadedRowIds.filter((rowId) => !selectedIds.has(rowId))
1204
- : loadedRowIds.filter((rowId) => selectedIds.has(rowId));
1205
- if (deletableRowIds.length === 0)
1206
- return;
1207
- if (currentSelection.type === 'exclude'
1208
- && table.getRowCount() > loadedRowIds.length
1209
- && logger.isLevelEnabled('info')) {
1210
- logger.info('deleteSelectedRows in exclude mode removed currently loaded rows only', {
1211
- removedRows: deletableRowIds.length,
1212
- totalSelected: (_b = table.getSelectedCount) === null || _b === void 0 ? void 0 : _b.call(table),
1213
- });
1214
- }
1215
- const deletableRowIdSet = new Set(deletableRowIds);
1216
- applyDataMutation('deleteSelectedRows', (rowsToMutate) => rowsToMutate.filter((row, index) => !deletableRowIdSet.has(String((0, utils_1.generateRowId)(row, index, idKey)))), { rowIds: deletableRowIds });
1217
- (_c = table.deselectAll) === null || _c === void 0 ? void 0 : _c.call(table);
1218
- },
1219
- replaceAllData: (newData) => {
1220
- applyDataMutation('replaceAllData', () => [...newData]);
1221
- },
1222
- updateMultipleRows: (updates) => {
1223
- const updateMap = new Map(updates.map((update) => [update.rowId, update.data]));
1224
- applyDataMutation('updateMultipleRows', (rowsToMutate) => rowsToMutate.map((row, index) => {
1225
- const currentRowId = String((0, utils_1.generateRowId)(row, index, idKey));
1226
- const updateData = updateMap.get(currentRowId);
1227
- return updateData ? { ...row, ...updateData } : row;
1228
- }));
1229
- },
1230
- insertMultipleRows: (newRows, startIndex) => {
1231
- applyDataMutation('insertMultipleRows', (rowsToMutate) => {
1232
- const nextData = [...rowsToMutate];
1233
- nextData.splice(clampInsertIndex(nextData, startIndex), 0, ...newRows);
1234
- return nextData;
1235
- }, { index: startIndex });
1236
- },
1237
- deleteMultipleRows: (rowIds) => {
1238
- const idsToDelete = new Set(rowIds);
1239
- applyDataMutation('deleteMultipleRows', (rowsToMutate) => rowsToMutate.filter((row, index) => !idsToDelete.has(String((0, utils_1.generateRowId)(row, index, idKey)))), { rowIds });
1240
- },
1241
- updateField: (rowId, fieldName, value) => {
1242
- applyDataMutation('updateField', (rowsToMutate) => {
1243
- const rowIndex = getRowIndexById(rowsToMutate, rowId);
1244
- if (rowIndex === -1)
1245
- return rowsToMutate;
1246
- const nextData = [...rowsToMutate];
1247
- nextData[rowIndex] = { ...nextData[rowIndex], [fieldName]: value };
1248
- return nextData;
1249
- }, { rowId });
1250
- },
1251
- updateFieldByIndex: (index, fieldName, value) => {
1252
- applyDataMutation('updateFieldByIndex', (rowsToMutate) => {
1253
- if (!rowsToMutate[index])
1254
- return rowsToMutate;
1255
- const nextData = [...rowsToMutate];
1256
- nextData[index] = { ...nextData[index], [fieldName]: value };
1257
- return nextData;
1258
- }, { index });
1259
- },
1260
- findRows: (predicate) => tableData.filter(predicate),
1261
- findRowIndex: (predicate) => tableData.findIndex(predicate),
1262
- getDataCount: () => tableData.length,
1263
- getFilteredDataCount: () => table.getFilteredRowModel().rows.length,
1264
- },
1265
- // -------------------------------
1266
- // Layout Management
1267
- // -------------------------------
1268
- layout: {
1269
- resetLayout: () => {
1270
- var _a;
1271
- // go through handlers so controlled state updates + emit works
1272
- applySizing(initialStateConfig.columnSizing || {});
1273
- applyVisibility(initialStateConfig.columnVisibility || {});
1274
- applySorting(initialStateConfig.sorting || []);
1275
- applyGlobalFilter((_a = initialStateConfig.globalFilter) !== null && _a !== void 0 ? _a : "");
1276
- },
1277
- resetAll: () => resetAllAndReload(),
1278
- saveLayout: () => ({
1279
- columnVisibility: table.getState().columnVisibility,
1280
- columnSizing: table.getState().columnSizing,
1281
- columnOrder: table.getState().columnOrder,
1282
- columnPinning: table.getState().columnPinning,
1283
- sorting: table.getState().sorting,
1284
- pagination: table.getState().pagination,
1285
- globalFilter: table.getState().globalFilter,
1286
- columnFilter: table.getState().columnFilter,
1287
- }),
1288
- restoreLayout: (layout) => {
1289
- if (layout.columnVisibility)
1290
- applyVisibility(layout.columnVisibility);
1291
- if (layout.columnSizing)
1292
- applySizing(layout.columnSizing);
1293
- if (layout.columnOrder)
1294
- applyColumnOrder(layout.columnOrder);
1295
- if (layout.columnPinning)
1296
- applyPinning(layout.columnPinning);
1297
- if (layout.sorting)
1298
- applySorting(layout.sorting);
1299
- if (layout.pagination && enablePagination)
1300
- applyPagination(layout.pagination);
1301
- if (layout.globalFilter !== undefined)
1302
- applyGlobalFilter(layout.globalFilter);
1303
- if (layout.columnFilter)
1304
- handleColumnFilterStateChange(layout.columnFilter);
1305
- },
1306
- },
1307
- // -------------------------------
1308
- // Table State
1309
- // -------------------------------
1310
- state: {
1311
- getTableState: () => table.getState(),
1312
- getCurrentFilters: () => table.getState().columnFilter,
1313
- getCurrentSorting: () => table.getState().sorting,
1314
- getCurrentPagination: () => table.getState().pagination,
1315
- getCurrentSelection: () => { var _a; return (_a = table.getSelectionState) === null || _a === void 0 ? void 0 : _a.call(table); },
1316
- },
1317
- // -------------------------------
1318
- // Export (unchanged mostly)
1319
- // -------------------------------
1320
- export: {
1321
- exportCSV: async (options = {}) => {
1322
- const { filename = exportFilename, chunkSize = exportChunkSize, strictTotalCheck = exportStrictTotalCheck, sanitizeCSV = exportSanitizeCSV, } = options;
1323
- const mode = dataMode === "server" && !!onServerExport ? 'server' : 'client';
1324
- await runExportWithPolicy({
1325
- format: 'csv',
1326
- filename,
1327
- mode,
1328
- execute: async (controller) => {
1329
- var _a;
1330
- const toStateChange = (state) => {
1331
- const isFinalPhase = state.phase === 'completed' || state.phase === 'cancelled' || state.phase === 'error';
1332
- handleExportStateChangeInternal({
1333
- phase: state.phase,
1334
- mode,
1335
- format: 'csv',
1336
- filename,
1337
- processedRows: state.processedRows,
1338
- totalRows: state.totalRows,
1339
- percentage: state.percentage,
1340
- message: state.message,
1341
- code: state.code,
1342
- startedAt: state.phase === 'starting' ? Date.now() : undefined,
1343
- endedAt: isFinalPhase ? Date.now() : undefined,
1344
- queueLength: queuedExportCount,
1345
- });
1346
- if (state.phase === 'cancelled') {
1347
- onExportCancel === null || onExportCancel === void 0 ? void 0 : onExportCancel();
1348
- }
1349
- };
1350
- if (mode === 'server' && onServerExport) {
1351
- const currentFilters = {
1352
- globalFilter: table.getState().globalFilter,
1353
- columnFilter: table.getState().columnFilter,
1354
- sorting: table.getState().sorting,
1355
- pagination: table.getState().pagination,
1356
- };
1357
- if (logger.isLevelEnabled("debug"))
1358
- logger.debug("Server export CSV", { currentFilters });
1359
- await (0, utils_1.exportServerData)(table, {
1360
- format: "csv",
1361
- filename,
1362
- fetchData: (filters, selection, signal) => onServerExport(filters, selection, signal),
1363
- currentFilters,
1364
- selection: (_a = table.getSelectionState) === null || _a === void 0 ? void 0 : _a.call(table),
1365
- onProgress: handleExportProgressInternal,
1366
- onComplete: onExportComplete,
1367
- onError: onExportError,
1368
- onStateChange: toStateChange,
1369
- signal: controller.signal,
1370
- chunkSize,
1371
- strictTotalCheck,
1372
- sanitizeCSV,
1373
- });
1374
- return;
1375
- }
1376
- await (0, utils_1.exportClientData)(table, {
1377
- format: "csv",
1378
- filename,
1379
- onProgress: handleExportProgressInternal,
1380
- onComplete: onExportComplete,
1381
- onError: onExportError,
1382
- onStateChange: toStateChange,
1383
- signal: controller.signal,
1384
- sanitizeCSV,
1385
- });
1386
- if (logger.isLevelEnabled("debug"))
1387
- logger.debug("Client export CSV", filename);
1388
- }
1389
- });
1390
- },
1391
- exportExcel: async (options = {}) => {
1392
- const { filename = exportFilename, chunkSize = exportChunkSize, strictTotalCheck = exportStrictTotalCheck, sanitizeCSV = exportSanitizeCSV, } = options;
1393
- const mode = dataMode === "server" && !!onServerExport ? 'server' : 'client';
1394
- await runExportWithPolicy({
1395
- format: 'excel',
1396
- filename,
1397
- mode,
1398
- execute: async (controller) => {
1399
- var _a;
1400
- const toStateChange = (state) => {
1401
- const isFinalPhase = state.phase === 'completed' || state.phase === 'cancelled' || state.phase === 'error';
1402
- handleExportStateChangeInternal({
1403
- phase: state.phase,
1404
- mode,
1405
- format: 'excel',
1406
- filename,
1407
- processedRows: state.processedRows,
1408
- totalRows: state.totalRows,
1409
- percentage: state.percentage,
1410
- message: state.message,
1411
- code: state.code,
1412
- startedAt: state.phase === 'starting' ? Date.now() : undefined,
1413
- endedAt: isFinalPhase ? Date.now() : undefined,
1414
- queueLength: queuedExportCount,
1415
- });
1416
- if (state.phase === 'cancelled') {
1417
- onExportCancel === null || onExportCancel === void 0 ? void 0 : onExportCancel();
1418
- }
1419
- };
1420
- if (mode === 'server' && onServerExport) {
1421
- const currentFilters = {
1422
- globalFilter: table.getState().globalFilter,
1423
- columnFilter: table.getState().columnFilter,
1424
- sorting: table.getState().sorting,
1425
- pagination: table.getState().pagination,
1426
- };
1427
- if (logger.isLevelEnabled("debug"))
1428
- logger.debug("Server export Excel", { currentFilters });
1429
- await (0, utils_1.exportServerData)(table, {
1430
- format: "excel",
1431
- filename,
1432
- fetchData: (filters, selection, signal) => onServerExport(filters, selection, signal),
1433
- currentFilters,
1434
- selection: (_a = table.getSelectionState) === null || _a === void 0 ? void 0 : _a.call(table),
1435
- onProgress: handleExportProgressInternal,
1436
- onComplete: onExportComplete,
1437
- onError: onExportError,
1438
- onStateChange: toStateChange,
1439
- signal: controller.signal,
1440
- chunkSize,
1441
- strictTotalCheck,
1442
- sanitizeCSV,
1443
- });
1444
- return;
1445
- }
1446
- await (0, utils_1.exportClientData)(table, {
1447
- format: "excel",
1448
- filename,
1449
- onProgress: handleExportProgressInternal,
1450
- onComplete: onExportComplete,
1451
- onError: onExportError,
1452
- onStateChange: toStateChange,
1453
- signal: controller.signal,
1454
- sanitizeCSV,
1455
- });
1456
- if (logger.isLevelEnabled("debug"))
1457
- logger.debug("Client export Excel", filename);
1458
- }
1459
- });
1460
- },
1461
- exportServerData: async (options) => {
1462
- const { format, filename = exportFilename, fetchData: fetchFn = onServerExport, chunkSize = exportChunkSize, strictTotalCheck = exportStrictTotalCheck, sanitizeCSV = exportSanitizeCSV, } = options;
1463
- if (!fetchFn) {
1464
- onExportError === null || onExportError === void 0 ? void 0 : onExportError({ message: "No server export function provided", code: "NO_SERVER_EXPORT" });
1465
- if (logger.isLevelEnabled("debug"))
1466
- logger.debug("Server export data failed", "No server export function provided");
1467
- return;
1468
- }
1469
- await runExportWithPolicy({
1470
- format,
1471
- filename,
1472
- mode: 'server',
1473
- execute: async (controller) => {
1474
- var _a;
1475
- const currentFilters = {
1476
- globalFilter: table.getState().globalFilter,
1477
- columnFilter: table.getState().columnFilter,
1478
- sorting: table.getState().sorting,
1479
- pagination: table.getState().pagination,
1480
- };
1481
- if (logger.isLevelEnabled("debug"))
1482
- logger.debug("Server export data", { currentFilters });
1483
- await (0, utils_1.exportServerData)(table, {
1484
- format,
1485
- filename,
1486
- fetchData: (filters, selection, signal) => fetchFn(filters, selection, signal),
1487
- currentFilters,
1488
- selection: (_a = table.getSelectionState) === null || _a === void 0 ? void 0 : _a.call(table),
1489
- onProgress: handleExportProgressInternal,
1490
- onComplete: onExportComplete,
1491
- onError: onExportError,
1492
- onStateChange: (state) => {
1493
- const isFinalPhase = state.phase === 'completed' || state.phase === 'cancelled' || state.phase === 'error';
1494
- handleExportStateChangeInternal({
1495
- phase: state.phase,
1496
- mode: 'server',
1497
- format,
1498
- filename,
1499
- processedRows: state.processedRows,
1500
- totalRows: state.totalRows,
1501
- percentage: state.percentage,
1502
- message: state.message,
1503
- code: state.code,
1504
- startedAt: state.phase === 'starting' ? Date.now() : undefined,
1505
- endedAt: isFinalPhase ? Date.now() : undefined,
1506
- queueLength: queuedExportCount,
1507
- });
1508
- if (state.phase === 'cancelled') {
1509
- onExportCancel === null || onExportCancel === void 0 ? void 0 : onExportCancel();
1510
- }
1511
- },
1512
- signal: controller.signal,
1513
- chunkSize,
1514
- strictTotalCheck,
1515
- sanitizeCSV,
1516
- });
1517
- }
1518
- });
1519
- },
1520
- isExporting: () => isExporting || false,
1521
- cancelExport: () => {
1522
- const activeController = exportControllerRef.current;
1523
- if (!activeController) {
1524
- return;
1525
- }
1526
- activeController.abort();
1527
- setExportControllerSafely((current) => (current === activeController ? null : current));
1528
- if (logger.isLevelEnabled("debug"))
1529
- logger.debug("Export cancelled");
1530
- },
1531
- },
1532
- };
1533
- // eslint-disable-next-line react-hooks/exhaustive-deps
1534
- }, [
1535
- table,
1536
- enhancedColumns,
1537
- handleColumnOrderChange,
1538
- handleColumnPinningChange,
1539
- handleColumnVisibilityChange,
1540
- handleColumnSizingChange,
1541
- handlePaginationChange,
1542
- handleSortingChange,
1543
- handleGlobalFilterChange,
1544
- handleColumnFilterStateChange,
1545
- initialStateConfig,
1546
- enablePagination,
1547
- idKey,
1548
- triggerRefresh,
1549
- applyDataMutation,
1550
- tableData,
1551
- selectionState,
1552
- // export
1553
- exportFilename,
1554
- exportChunkSize,
1555
- exportStrictTotalCheck,
1556
- exportSanitizeCSV,
1557
- onExportComplete,
1558
- onExportError,
1559
- onExportCancel,
1560
- onServerExport,
1561
- queuedExportCount,
1562
- isExporting,
1563
- dataMode,
1564
- handleExportProgressInternal,
1565
- handleExportStateChangeInternal,
1566
- runExportWithPolicy,
1567
- setExportControllerSafely,
1568
- logger,
1569
- resetAllAndReload,
1570
- ]);
1571
- internalApiRef.current = dataTableApi;
1572
- (0, react_1.useImperativeHandle)(ref, () => dataTableApi, [dataTableApi]);
1573
- // -------------------------------
1574
- // Render table rows with slot support (callback)
1575
- // -------------------------------
1576
- const renderTableRows = (0, react_1.useCallback)(() => {
1577
- var _a, _b, _c, _d;
1578
- if (tableLoading) {
1579
- const { component: LoadingRowComponent, props: loadingRowProps } = (0, slot_helpers_1.getSlotComponentWithProps)(slots, slotProps || {}, 'loadingRow', rows_1.LoadingRows, {});
1580
- return ((0, jsx_runtime_1.jsx)(LoadingRowComponent, { rowCount: enablePagination ? Math.min(pagination.pageSize, skeletonRows) : skeletonRows, colSpan: table.getAllColumns().length, slots: slots, slotProps: slotProps, ...loadingRowProps }));
1581
- }
1582
- if (rows.length === 0) {
1583
- const { component: EmptyRowComponent, props: emptyRowProps } = (0, slot_helpers_1.getSlotComponentWithProps)(slots, slotProps || {}, 'emptyRow', rows_1.EmptyDataRow, {});
1584
- return ((0, jsx_runtime_1.jsx)(EmptyRowComponent, { colSpan: table.getAllColumns().length, message: emptyMessage, slots: slots, slotProps: slotProps, ...emptyRowProps }));
1585
- }
1586
- if (enableVirtualization && !enablePagination && rows.length > 0) {
1587
- const virtualItems = rowVirtualizer.getVirtualItems();
1588
- return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [virtualItems.length > 0 && ((0, jsx_runtime_1.jsx)("tr", { children: (0, jsx_runtime_1.jsx)("td", { colSpan: table.getAllColumns().length, style: {
1589
- height: `${(_b = (_a = virtualItems[0]) === null || _a === void 0 ? void 0 : _a.start) !== null && _b !== void 0 ? _b : 0}px`,
1590
- padding: 0,
1591
- border: 0,
1592
- } }) })), virtualItems.map((virtualRow) => {
1593
- const row = rows[virtualRow.index];
1594
- if (!row)
1595
- return null;
1596
- return ((0, jsx_runtime_1.jsx)(rows_1.DataTableRow, { row: row, enableHover: enableHover, enableStripes: enableStripes, isOdd: virtualRow.index % 2 === 1, renderSubComponent: renderSubComponent, disableStickyHeader: enableStickyHeaderOrFooter, onRowClick: onRowClick, selectOnRowClick: selectOnRowClick, slots: slots, slotProps: slotProps }, row.id));
1597
- }), virtualItems.length > 0 && ((0, jsx_runtime_1.jsx)("tr", { children: (0, jsx_runtime_1.jsx)("td", { colSpan: table.getAllColumns().length, style: {
1598
- height: `${rowVirtualizer.getTotalSize() -
1599
- ((_d = (_c = virtualItems[virtualItems.length - 1]) === null || _c === void 0 ? void 0 : _c.end) !== null && _d !== void 0 ? _d : 0)}px`,
1600
- padding: 0,
1601
- border: 0,
1602
- } }) }))] }));
1603
- }
1604
- return rows.map((row, index) => ((0, jsx_runtime_1.jsx)(rows_1.DataTableRow, { row: row, enableHover: enableHover, enableStripes: enableStripes, isOdd: index % 2 === 1, renderSubComponent: renderSubComponent, disableStickyHeader: enableStickyHeaderOrFooter, onRowClick: onRowClick, selectOnRowClick: selectOnRowClick, slots: slots, slotProps: slotProps }, row.id)));
1605
- }, [
1606
- tableLoading,
1607
- rows,
1608
- enableVirtualization,
1609
- enablePagination,
1610
- pagination.pageSize,
1611
- skeletonRows,
1612
- table,
1613
- slotProps,
1614
- emptyMessage,
1615
- rowVirtualizer,
1616
- enableHover,
1617
- enableStripes,
1618
- renderSubComponent,
1619
- enableStickyHeaderOrFooter,
1620
- onRowClick,
1621
- selectOnRowClick,
1622
- slots,
1623
- ]);
1624
- // -------------------------------
1625
- // Export cancel callback
1626
- // -------------------------------
1627
- const handleCancelExport = (0, react_1.useCallback)(() => {
1628
- const activeController = exportControllerRef.current;
1629
- if (activeController) {
1630
- activeController.abort();
1631
- setExportControllerSafely((current) => (current === activeController ? null : current));
1632
- }
1633
- }, [setExportControllerSafely]);
1634
- // -------------------------------
1635
- // Slot components
1636
- // -------------------------------
1637
- const { component: RootComponent, props: rootSlotProps } = (0, slot_helpers_1.getSlotComponentWithProps)(slots, slotProps || {}, 'root', material_1.Box, {});
1638
- const { component: ToolbarComponent, props: toolbarSlotProps } = (0, slot_helpers_1.getSlotComponentWithProps)(slots, slotProps || {}, 'toolbar', toolbar_1.DataTableToolbar, {});
1639
- const { component: BulkActionsComponent, props: bulkActionsSlotProps } = (0, slot_helpers_1.getSlotComponentWithProps)(slots, slotProps || {}, 'bulkActionsToolbar', toolbar_1.BulkActionsToolbar, {});
1640
- const { component: TableContainerComponent, props: tableContainerSlotProps } = (0, slot_helpers_1.getSlotComponentWithProps)(slots, slotProps || {}, 'tableContainer', material_1.TableContainer, {});
1641
- const { component: TableComponent, props: tableComponentSlotProps } = (0, slot_helpers_1.getSlotComponentWithProps)(slots, slotProps || {}, 'table', material_1.Table, {});
1642
- const { component: BodyComponent, props: bodySlotProps } = (0, slot_helpers_1.getSlotComponentWithProps)(slots, slotProps || {}, 'body', material_1.TableBody, {});
1643
- const { component: FooterComponent, props: footerSlotProps } = (0, slot_helpers_1.getSlotComponentWithProps)(slots, slotProps || {}, 'footer', material_1.Box, {});
1644
- const { component: PaginationComponent, props: paginationSlotProps } = (0, slot_helpers_1.getSlotComponentWithProps)(slots, slotProps || {}, 'pagination', pagination_1.DataTablePagination, {});
1645
- // -------------------------------
1646
- // Render
1647
- // -------------------------------
1648
- return ((0, jsx_runtime_1.jsx)(data_table_context_1.DataTableProvider, { table: table, apiRef: internalApiRef, dataMode: dataMode, tableSize: tableSize, onTableSizeChange: (size) => {
1649
- setTableSize(size);
1650
- }, columnFilter: columnFilter, onChangeColumnFilter: handleColumnFilterStateChange, slots: slots, slotProps: slotProps, isExporting: isExporting, exportController: exportController, exportPhase: exportPhase, exportProgress: exportProgress, onCancelExport: handleCancelExport, exportFilename: exportFilename, onExportProgress: onExportProgress, onExportComplete: onExportComplete, onExportError: onExportError, onServerExport: onServerExport, children: (0, jsx_runtime_1.jsxs)(RootComponent, { ...rootSlotProps, children: [(enableGlobalFilter || extraFilter) ? ((0, jsx_runtime_1.jsx)(ToolbarComponent, { extraFilter: extraFilter, enableGlobalFilter: enableGlobalFilter, enableColumnVisibility: enableColumnVisibility, enableColumnFilter: enableColumnFilter, enableExport: enableExport, enableReset: enableReset, enableTableSizeControl: enableTableSizeControl, enableColumnPinning: enableColumnPinning, enableRefresh: enableRefresh, ...toolbarSlotProps, refreshButtonProps: {
1651
- loading: tableLoading, // disable while fetching
1652
- showSpinnerWhileLoading: false,
1653
- onRefresh: () => { var _a, _b, _c; return (_c = (_b = (_a = internalApiRef.current) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.refresh) === null || _c === void 0 ? void 0 : _c.call(_b, true); },
1654
- ...toolbarSlotProps.refreshButtonProps,
1655
- } })) : null, enableBulkActions && enableRowSelection && isSomeRowsSelected ? ((0, jsx_runtime_1.jsx)(BulkActionsComponent, { selectionState: selectionState, selectedRowCount: selectedRowCount, bulkActions: bulkActions, sx: {
1656
- position: 'relative',
1657
- zIndex: 2,
1658
- ...bulkActionsSlotProps.sx,
1659
- }, ...bulkActionsSlotProps })) : null, (0, jsx_runtime_1.jsx)(TableContainerComponent, { component: material_1.Paper, ref: tableContainerRef, sx: {
1660
- width: '100%',
1661
- overflowX: 'auto',
1662
- ...(enableStickyHeaderOrFooter && {
1663
- maxHeight: maxHeight,
1664
- overflowY: 'auto',
1665
- }),
1666
- ...(enableVirtualization && {
1667
- maxHeight: maxHeight,
1668
- overflowY: 'auto',
1669
- }),
1670
- ...tableContainerSlotProps === null || tableContainerSlotProps === void 0 ? void 0 : tableContainerSlotProps.sx,
1671
- }, ...tableContainerSlotProps, children: (0, jsx_runtime_1.jsxs)(TableComponent, { size: tableSize, stickyHeader: enableStickyHeaderOrFooter, style: {
1672
- ...tableStyle,
1673
- ...tableProps === null || tableProps === void 0 ? void 0 : tableProps.style,
1674
- }, ...(0, slot_helpers_1.mergeSlotProps)(tableProps || {}, tableComponentSlotProps), children: [useFixedLayout ? ((0, jsx_runtime_1.jsx)("colgroup", { children: visibleLeafColumns.map((column) => ((0, jsx_runtime_1.jsx)("col", { style: {
1675
- width: column.getSize(),
1676
- minWidth: column.columnDef.minSize,
1677
- maxWidth: column.columnDef.maxSize,
1678
- } }, column.id))) })) : null, (0, jsx_runtime_1.jsx)(headers_1.TableHeader, { draggable: enableColumnDragging, enableColumnResizing: enableColumnResizing, enableStickyHeader: enableStickyHeaderOrFooter, onColumnReorder: handleColumnReorder, slots: slots, slotProps: slotProps }), (0, jsx_runtime_1.jsx)(BodyComponent, { ...bodySlotProps, children: renderTableRows() })] }) }), enablePagination ? ((0, jsx_runtime_1.jsx)(FooterComponent, { sx: {
1679
- ...(enableStickyHeaderOrFooter && {
1680
- position: 'sticky',
1681
- bottom: 0,
1682
- backgroundColor: 'background.paper',
1683
- borderTop: '1px solid',
1684
- borderColor: 'divider',
1685
- zIndex: 1,
1686
- }),
1687
- ...footerSlotProps.sx,
1688
- }, ...footerSlotProps, children: (0, jsx_runtime_1.jsx)(PaginationComponent, { footerFilter: footerFilter, pagination: pagination, totalRow: tableTotalRow, ...paginationSlotProps }) })) : null] }) }));
46
+ const use_data_table_engine_1 = require("./hooks/use-data-table-engine");
47
+ const data_table_view_1 = require("./components/data-table-view");
48
+ exports.DataTable = (0, react_1.forwardRef)(function DataTable(props, ref) {
49
+ const engine = (0, use_data_table_engine_1.useDataTableEngine)(props);
50
+ (0, react_1.useImperativeHandle)(ref, () => engine.refs.apiRef.current, []);
51
+ return ((0, jsx_runtime_1.jsx)(data_table_context_1.DataTableProvider, { ...engine.providerProps, children: (0, jsx_runtime_1.jsx)(data_table_view_1.DataTableView, { engine: engine, ...props }) }));
1689
52
  });