@ackplus/react-tanstack-data-table 1.1.16 → 1.1.18
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.
- package/README.md +0 -8
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -1
- package/dist/lib/components/data-table-view.d.ts +7 -0
- package/dist/lib/components/data-table-view.d.ts.map +1 -0
- package/dist/lib/components/data-table-view.js +151 -0
- package/dist/lib/components/toolbar/column-filter-control.d.ts +3 -2
- package/dist/lib/components/toolbar/column-filter-control.d.ts.map +1 -1
- package/dist/lib/components/toolbar/column-filter-control.js +91 -92
- package/dist/lib/components/toolbar/data-table-toolbar.d.ts.map +1 -1
- package/dist/lib/components/toolbar/data-table-toolbar.js +14 -1
- package/dist/lib/components/toolbar/table-export-control.d.ts.map +1 -1
- package/dist/lib/components/toolbar/table-export-control.js +0 -2
- package/dist/lib/components/toolbar/table-refresh-control.d.ts.map +1 -1
- package/dist/lib/components/toolbar/table-refresh-control.js +3 -1
- package/dist/lib/data-table.d.ts +0 -3
- package/dist/lib/data-table.d.ts.map +1 -1
- package/dist/lib/data-table.js +9 -1638
- package/dist/lib/features/column-filter.feature.d.ts +2 -1
- package/dist/lib/features/column-filter.feature.d.ts.map +1 -1
- package/dist/lib/features/column-filter.feature.js +14 -0
- package/dist/lib/hooks/index.d.ts +3 -0
- package/dist/lib/hooks/index.d.ts.map +1 -0
- package/dist/lib/hooks/index.js +5 -0
- package/dist/lib/hooks/use-data-table-engine.d.ts +104 -0
- package/dist/lib/hooks/use-data-table-engine.d.ts.map +1 -0
- package/dist/lib/hooks/use-data-table-engine.js +964 -0
- package/dist/lib/types/data-table.types.d.ts +0 -1
- package/dist/lib/types/data-table.types.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +4 -0
- package/src/lib/components/data-table-view.tsx +386 -0
- package/src/lib/components/toolbar/column-filter-control.tsx +270 -212
- package/src/lib/components/toolbar/data-table-toolbar.tsx +15 -1
- package/src/lib/components/toolbar/table-export-control.tsx +0 -2
- package/src/lib/components/toolbar/table-refresh-control.tsx +11 -7
- package/src/lib/data-table.tsx +17 -2183
- package/src/lib/features/column-filter.feature.ts +15 -1
- package/src/lib/hooks/index.ts +2 -0
- package/src/lib/hooks/use-data-table-engine.ts +1285 -0
- package/src/lib/types/data-table.types.ts +0 -1
|
@@ -0,0 +1,1285 @@
|
|
|
1
|
+
import {
|
|
2
|
+
getCoreRowModel,
|
|
3
|
+
getPaginationRowModel,
|
|
4
|
+
getSortedRowModel,
|
|
5
|
+
PaginationState,
|
|
6
|
+
useReactTable,
|
|
7
|
+
type ColumnOrderState,
|
|
8
|
+
type ColumnPinningState,
|
|
9
|
+
type SortingState,
|
|
10
|
+
type Updater,
|
|
11
|
+
} from "@tanstack/react-table";
|
|
12
|
+
import { useVirtualizer } from "@tanstack/react-virtual";
|
|
13
|
+
import { useTheme } from "@mui/material/styles";
|
|
14
|
+
import { useMemo, useReducer, useState, useRef, useCallback, useEffect, RefObject, CSSProperties } from "react";
|
|
15
|
+
|
|
16
|
+
// your types
|
|
17
|
+
import type {
|
|
18
|
+
ColumnFilterState,
|
|
19
|
+
DataFetchMeta,
|
|
20
|
+
DataRefreshOptions,
|
|
21
|
+
DataTableProps,
|
|
22
|
+
ExportPhase,
|
|
23
|
+
ExportProgressPayload,
|
|
24
|
+
ExportStateChange,
|
|
25
|
+
TableFiltersForFetch,
|
|
26
|
+
TableState,
|
|
27
|
+
} from "../types";
|
|
28
|
+
import type { DataTableApi, DataTableExportApiOptions } from "../types/data-table-api";
|
|
29
|
+
|
|
30
|
+
// your features / utils
|
|
31
|
+
import { ColumnFilterFeature, getCombinedFilteredRowModel } from "../features/column-filter.feature";
|
|
32
|
+
import { SelectionFeature, SelectionState } from "../features";
|
|
33
|
+
import { createExpandingColumn, createSelectionColumn } from "../utils/special-columns.utils";
|
|
34
|
+
import {
|
|
35
|
+
exportClientData,
|
|
36
|
+
exportServerData,
|
|
37
|
+
generateRowId,
|
|
38
|
+
withIdsDeep,
|
|
39
|
+
type DataTableSize,
|
|
40
|
+
} from "../utils";
|
|
41
|
+
import { useDebouncedFetch } from "../utils/debounced-fetch.utils";
|
|
42
|
+
|
|
43
|
+
const DEFAULT_INITIAL_STATE = {
|
|
44
|
+
sorting: [] as SortingState,
|
|
45
|
+
pagination: { pageIndex: 0, pageSize: 10 },
|
|
46
|
+
selectionState: { ids: [], type: "include" } as SelectionState,
|
|
47
|
+
globalFilter: "",
|
|
48
|
+
expanded: {} as Record<string, boolean>,
|
|
49
|
+
columnOrder: [] as ColumnOrderState,
|
|
50
|
+
columnPinning: { left: [], right: [] } as ColumnPinningState,
|
|
51
|
+
columnVisibility: {} as Record<string, boolean>,
|
|
52
|
+
columnSizing: {} as Record<string, number>,
|
|
53
|
+
columnFilter: {
|
|
54
|
+
filters: [],
|
|
55
|
+
logic: "AND",
|
|
56
|
+
pendingFilters: [],
|
|
57
|
+
pendingLogic: "AND",
|
|
58
|
+
} as ColumnFilterState,
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
type EngineUIState = {
|
|
62
|
+
sorting: SortingState;
|
|
63
|
+
pagination: { pageIndex: number; pageSize: number };
|
|
64
|
+
globalFilter: string;
|
|
65
|
+
selectionState: SelectionState;
|
|
66
|
+
columnFilter: ColumnFilterState;
|
|
67
|
+
expanded: Record<string, boolean>;
|
|
68
|
+
tableSize: DataTableSize;
|
|
69
|
+
columnOrder: ColumnOrderState;
|
|
70
|
+
columnPinning: ColumnPinningState;
|
|
71
|
+
columnVisibility: Record<string, boolean>;
|
|
72
|
+
columnSizing: Record<string, number>;
|
|
73
|
+
};
|
|
74
|
+
type EngineAction =
|
|
75
|
+
| { type: "SET_SORTING_RESET_PAGE"; payload: SortingState }
|
|
76
|
+
| { type: "SET_PAGINATION"; payload: { pageIndex: number; pageSize: number } }
|
|
77
|
+
| { type: "SET_GLOBAL_FILTER_RESET_PAGE"; payload: string }
|
|
78
|
+
| { type: "SET_SELECTION"; payload: SelectionState }
|
|
79
|
+
| { type: "SET_COLUMN_FILTER"; payload: ColumnFilterState }
|
|
80
|
+
| { type: "SET_COLUMN_FILTER_RESET_PAGE"; payload: ColumnFilterState }
|
|
81
|
+
| { type: "SET_EXPANDED"; payload: Record<string, boolean> }
|
|
82
|
+
| { type: "SET_TABLE_SIZE"; payload: DataTableSize }
|
|
83
|
+
| { type: "SET_COLUMN_ORDER"; payload: ColumnOrderState }
|
|
84
|
+
| { type: "SET_COLUMN_PINNING"; payload: ColumnPinningState }
|
|
85
|
+
| { type: "SET_COLUMN_VISIBILITY"; payload: Record<string, boolean> }
|
|
86
|
+
| { type: "SET_COLUMN_SIZING"; payload: Record<string, number> }
|
|
87
|
+
| { type: "RESET_ALL"; payload: Partial<EngineUIState> } // payload = computed reset state
|
|
88
|
+
| { type: "RESTORE_LAYOUT"; payload: Partial<EngineUIState> };
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
function uiReducer(state: EngineUIState, action: EngineAction): EngineUIState {
|
|
92
|
+
switch (action.type) {
|
|
93
|
+
case "SET_SORTING_RESET_PAGE":
|
|
94
|
+
return { ...state, sorting: action.payload, pagination: { pageIndex: 0, pageSize: state.pagination.pageSize } };
|
|
95
|
+
case "SET_PAGINATION":
|
|
96
|
+
return { ...state, pagination: action.payload };
|
|
97
|
+
case "SET_GLOBAL_FILTER_RESET_PAGE":
|
|
98
|
+
return { ...state, globalFilter: action.payload, pagination: { pageIndex: 0, pageSize: state.pagination.pageSize } };
|
|
99
|
+
case "SET_SELECTION":
|
|
100
|
+
return { ...state, selectionState: action.payload };
|
|
101
|
+
case "SET_COLUMN_FILTER":
|
|
102
|
+
return { ...state, columnFilter: action.payload };
|
|
103
|
+
case "SET_COLUMN_FILTER_RESET_PAGE":
|
|
104
|
+
return { ...state, columnFilter: action.payload, pagination: { pageIndex: 0, pageSize: state.pagination.pageSize } };
|
|
105
|
+
case "SET_EXPANDED":
|
|
106
|
+
return { ...state, expanded: action.payload };
|
|
107
|
+
case "SET_TABLE_SIZE":
|
|
108
|
+
return { ...state, tableSize: action.payload };
|
|
109
|
+
case "SET_COLUMN_ORDER":
|
|
110
|
+
return { ...state, columnOrder: action.payload };
|
|
111
|
+
case "SET_COLUMN_PINNING":
|
|
112
|
+
return { ...state, columnPinning: action.payload };
|
|
113
|
+
case "SET_COLUMN_VISIBILITY":
|
|
114
|
+
return { ...state, columnVisibility: action.payload };
|
|
115
|
+
case "SET_COLUMN_SIZING":
|
|
116
|
+
return { ...state, columnSizing: action.payload };
|
|
117
|
+
case "RESTORE_LAYOUT":
|
|
118
|
+
return { ...state, ...action.payload };
|
|
119
|
+
case "RESET_ALL":
|
|
120
|
+
return { ...state, ...action.payload };
|
|
121
|
+
default:
|
|
122
|
+
return state;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function useLatestRef<T>(value: T) {
|
|
127
|
+
const ref = useRef(value);
|
|
128
|
+
useEffect(() => {
|
|
129
|
+
ref.current = value;
|
|
130
|
+
}, [value]);
|
|
131
|
+
return ref;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function useEvent<T extends (...args: any[]) => any>(fn: T): T {
|
|
135
|
+
const fnRef = useLatestRef(fn);
|
|
136
|
+
return useCallback(((...args: any[]) => fnRef.current(...args)) as T, [fnRef]) as T;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
export interface EngineResult<T = any> {
|
|
141
|
+
table: ReturnType<typeof useReactTable<T>>;
|
|
142
|
+
refs: {
|
|
143
|
+
tableContainerRef: RefObject<HTMLDivElement>;
|
|
144
|
+
apiRef: RefObject<DataTableApi<T> | null>;
|
|
145
|
+
exportControllerRef: RefObject<AbortController | null>;
|
|
146
|
+
};
|
|
147
|
+
derived: {
|
|
148
|
+
isServerMode: boolean;
|
|
149
|
+
isServerPagination: boolean;
|
|
150
|
+
isServerFiltering: boolean;
|
|
151
|
+
isServerSorting: boolean;
|
|
152
|
+
tableData: T[];
|
|
153
|
+
tableTotalRow: number;
|
|
154
|
+
tableLoading: boolean;
|
|
155
|
+
rows: ReturnType<ReturnType<typeof useReactTable<T>>["getRowModel"]>["rows"];
|
|
156
|
+
visibleLeafColumns: ReturnType<typeof useReactTable<T>>["getVisibleLeafColumns"];
|
|
157
|
+
useFixedLayout: boolean;
|
|
158
|
+
tableStyle: CSSProperties;
|
|
159
|
+
isExporting: boolean;
|
|
160
|
+
exportPhase: ExportPhase | null;
|
|
161
|
+
exportProgress: ExportProgressPayload;
|
|
162
|
+
isSomeRowsSelected: boolean;
|
|
163
|
+
selectedRowCount: number;
|
|
164
|
+
};
|
|
165
|
+
state: EngineUIState;
|
|
166
|
+
actions: {
|
|
167
|
+
fetchData: (overrides?: Partial<TableState>, options?: { delay?: number; meta?: DataFetchMeta }) => Promise<any>;
|
|
168
|
+
handleSortingChange: (updaterOrValue: any) => void;
|
|
169
|
+
handlePaginationChange: (updater: any) => void;
|
|
170
|
+
handleGlobalFilterChange: (updaterOrValue: any) => void;
|
|
171
|
+
handleColumnFilterChangeHandler: (updater: any, isApply?: boolean) => void;
|
|
172
|
+
handleColumnOrderChange: (updatedColumnOrder: Updater<ColumnOrderState>) => void;
|
|
173
|
+
handleColumnPinningChange: (updater: Updater<ColumnPinningState>) => void;
|
|
174
|
+
handleColumnVisibilityChange: (updater: any) => void;
|
|
175
|
+
handleColumnSizingChange: (updater: any) => void;
|
|
176
|
+
handleColumnReorder: (draggedColumnId: string, targetColumnId: string) => void;
|
|
177
|
+
resetAllAndReload: () => void;
|
|
178
|
+
triggerRefresh: (options?: boolean | DataRefreshOptions, fallbackReason?: string) => Promise<void>;
|
|
179
|
+
setTableSize: (size: DataTableSize) => void;
|
|
180
|
+
handleCancelExport: () => void;
|
|
181
|
+
renderRowModel: { rowVirtualizer: ReturnType<typeof useVirtualizer> };
|
|
182
|
+
};
|
|
183
|
+
api: DataTableApi<T>;
|
|
184
|
+
providerProps: {
|
|
185
|
+
table: ReturnType<typeof useReactTable<T>>;
|
|
186
|
+
apiRef: RefObject<DataTableApi<T> | null>;
|
|
187
|
+
dataMode: "client" | "server";
|
|
188
|
+
tableSize: DataTableSize;
|
|
189
|
+
onTableSizeChange: (size: DataTableSize) => void;
|
|
190
|
+
columnFilter: ColumnFilterState;
|
|
191
|
+
onChangeColumnFilter: (filter: ColumnFilterState) => void;
|
|
192
|
+
slots: Record<string, any>;
|
|
193
|
+
slotProps: Record<string, any>;
|
|
194
|
+
isExporting: boolean;
|
|
195
|
+
exportController: AbortController | null;
|
|
196
|
+
exportPhase: ExportPhase | null;
|
|
197
|
+
exportProgress: ExportProgressPayload;
|
|
198
|
+
onCancelExport: () => void;
|
|
199
|
+
exportFilename: string;
|
|
200
|
+
onExportProgress?: (progress: ExportProgressPayload) => void;
|
|
201
|
+
onExportComplete?: (result: { success: boolean; filename: string; totalRows: number }) => void;
|
|
202
|
+
onExportError?: (error: { message: string; code: string }) => void;
|
|
203
|
+
onServerExport?: (filters?: Partial<any>, selection?: SelectionState, signal?: AbortSignal) => Promise<any>;
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export function useDataTableEngine<T extends Record<string, any>>(
|
|
208
|
+
props: DataTableProps<T>
|
|
209
|
+
): EngineResult<T> {
|
|
210
|
+
const {
|
|
211
|
+
initialState,
|
|
212
|
+
columns,
|
|
213
|
+
data = [],
|
|
214
|
+
totalRow = 0,
|
|
215
|
+
idKey = "id" as keyof T,
|
|
216
|
+
|
|
217
|
+
dataMode = "client",
|
|
218
|
+
initialLoadData = true,
|
|
219
|
+
onFetchData,
|
|
220
|
+
onFetchStateChange,
|
|
221
|
+
onDataStateChange,
|
|
222
|
+
|
|
223
|
+
enableRowSelection = false,
|
|
224
|
+
enableMultiRowSelection = true,
|
|
225
|
+
selectMode = "page",
|
|
226
|
+
isRowSelectable,
|
|
227
|
+
onSelectionChange,
|
|
228
|
+
enableBulkActions = false,
|
|
229
|
+
|
|
230
|
+
enableColumnResizing = false,
|
|
231
|
+
columnResizeMode = "onChange",
|
|
232
|
+
onColumnSizingChange,
|
|
233
|
+
|
|
234
|
+
enableColumnDragging = false,
|
|
235
|
+
onColumnDragEnd,
|
|
236
|
+
|
|
237
|
+
enableColumnPinning = false,
|
|
238
|
+
onColumnPinningChange,
|
|
239
|
+
|
|
240
|
+
onColumnVisibilityChange,
|
|
241
|
+
enableColumnVisibility = true,
|
|
242
|
+
|
|
243
|
+
enableExpanding = false,
|
|
244
|
+
getRowCanExpand,
|
|
245
|
+
|
|
246
|
+
enablePagination = false,
|
|
247
|
+
paginationMode = "client",
|
|
248
|
+
|
|
249
|
+
enableGlobalFilter = true,
|
|
250
|
+
|
|
251
|
+
enableColumnFilter = false,
|
|
252
|
+
filterMode = "client",
|
|
253
|
+
|
|
254
|
+
enableSorting = true,
|
|
255
|
+
sortingMode = "client",
|
|
256
|
+
onSortingChange,
|
|
257
|
+
|
|
258
|
+
exportFilename = "export",
|
|
259
|
+
exportConcurrency = "cancelAndRestart",
|
|
260
|
+
exportChunkSize = 1000,
|
|
261
|
+
exportStrictTotalCheck = false,
|
|
262
|
+
exportSanitizeCSV = true,
|
|
263
|
+
onExportProgress,
|
|
264
|
+
onExportComplete,
|
|
265
|
+
onExportError,
|
|
266
|
+
onServerExport,
|
|
267
|
+
onExportCancel,
|
|
268
|
+
onExportStateChange,
|
|
269
|
+
|
|
270
|
+
fitToScreen = true,
|
|
271
|
+
tableSize: initialTableSize = "medium",
|
|
272
|
+
enableVirtualization = false,
|
|
273
|
+
estimateRowHeight = 52,
|
|
274
|
+
|
|
275
|
+
loading = false,
|
|
276
|
+
|
|
277
|
+
onColumnFiltersChange,
|
|
278
|
+
onPaginationChange,
|
|
279
|
+
onGlobalFilterChange,
|
|
280
|
+
|
|
281
|
+
slots = {},
|
|
282
|
+
slotProps = {},
|
|
283
|
+
} = props;
|
|
284
|
+
|
|
285
|
+
const theme = useTheme();
|
|
286
|
+
|
|
287
|
+
const isServerMode = dataMode === "server";
|
|
288
|
+
const isServerPagination = paginationMode === "server" || isServerMode;
|
|
289
|
+
const isServerFiltering = filterMode === "server" || isServerMode;
|
|
290
|
+
const isServerSorting = sortingMode === "server" || isServerMode;
|
|
291
|
+
|
|
292
|
+
// --- initial config (memo)
|
|
293
|
+
const initialStateConfig = useMemo(() => {
|
|
294
|
+
const config = { ...DEFAULT_INITIAL_STATE, ...initialState };
|
|
295
|
+
return config;
|
|
296
|
+
}, [initialState]);
|
|
297
|
+
|
|
298
|
+
const initialUIState: EngineUIState = useMemo(
|
|
299
|
+
() => ({
|
|
300
|
+
sorting: initialStateConfig.sorting ?? DEFAULT_INITIAL_STATE.sorting,
|
|
301
|
+
pagination: initialStateConfig.pagination ?? DEFAULT_INITIAL_STATE.pagination,
|
|
302
|
+
globalFilter: initialStateConfig.globalFilter ?? DEFAULT_INITIAL_STATE.globalFilter,
|
|
303
|
+
selectionState: initialStateConfig.selectionState ?? DEFAULT_INITIAL_STATE.selectionState,
|
|
304
|
+
columnFilter: initialStateConfig.columnFilter ?? DEFAULT_INITIAL_STATE.columnFilter,
|
|
305
|
+
expanded: initialStateConfig.expanded ?? {},
|
|
306
|
+
tableSize: (initialTableSize || "medium") as DataTableSize,
|
|
307
|
+
columnOrder: initialStateConfig.columnOrder ?? DEFAULT_INITIAL_STATE.columnOrder,
|
|
308
|
+
columnPinning: initialStateConfig.columnPinning ?? DEFAULT_INITIAL_STATE.columnPinning,
|
|
309
|
+
columnVisibility: initialStateConfig.columnVisibility ?? DEFAULT_INITIAL_STATE.columnVisibility,
|
|
310
|
+
columnSizing: initialStateConfig.columnSizing ?? DEFAULT_INITIAL_STATE.columnSizing,
|
|
311
|
+
}),
|
|
312
|
+
[initialStateConfig, initialTableSize]
|
|
313
|
+
);
|
|
314
|
+
|
|
315
|
+
// --- UI state (reducer)
|
|
316
|
+
const [ui, dispatch] = useReducer(uiReducer, initialUIState);
|
|
317
|
+
|
|
318
|
+
// --- server data state (UI-affecting)
|
|
319
|
+
const [serverData, setServerData] = useState<T[] | null>(null);
|
|
320
|
+
const [serverTotal, setServerTotal] = useState<number>(0);
|
|
321
|
+
|
|
322
|
+
// --- export UI state
|
|
323
|
+
const [exportPhase, setExportPhase] = useState<ExportPhase | null>(null);
|
|
324
|
+
const [exportProgress, setExportProgress] = useState<ExportProgressPayload>({});
|
|
325
|
+
const [exportController, setExportController] = useState<AbortController | null>(null);
|
|
326
|
+
const [queuedExportCount, setQueuedExportCount] = useState(0);
|
|
327
|
+
|
|
328
|
+
// --- refs (no-render control)
|
|
329
|
+
const tableContainerRef = useRef<HTMLDivElement>(null);
|
|
330
|
+
const apiRef = useRef<DataTableApi<T> | null>(null);
|
|
331
|
+
const exportControllerRef = useRef<AbortController | null>(null);
|
|
332
|
+
const exportQueueRef = useRef<Promise<void>>(Promise.resolve());
|
|
333
|
+
const lastSentRef = useRef<string>("");
|
|
334
|
+
|
|
335
|
+
// --- latest refs (prevent stale closures in stable API)
|
|
336
|
+
const uiRef = useLatestRef(ui);
|
|
337
|
+
const dataRef = useLatestRef(data);;
|
|
338
|
+
const serverDataRef = useLatestRef(serverData);
|
|
339
|
+
const nextFetchDelayRef = useRef<number>(0);
|
|
340
|
+
|
|
341
|
+
// callbacks refs (super important)
|
|
342
|
+
const onFetchDataRef = useLatestRef(onFetchData);
|
|
343
|
+
const onFetchStateChangeRef = useLatestRef(onFetchStateChange);
|
|
344
|
+
const onDataStateChangeRef = useLatestRef(onDataStateChange);
|
|
345
|
+
|
|
346
|
+
const onSortingChangeRef = useLatestRef(onSortingChange);
|
|
347
|
+
const onPaginationChangeRef = useLatestRef(onPaginationChange);
|
|
348
|
+
const onGlobalFilterChangeRef = useLatestRef(onGlobalFilterChange);
|
|
349
|
+
const onColumnFiltersChangeRef = useLatestRef(onColumnFiltersChange);
|
|
350
|
+
|
|
351
|
+
const onColumnDragEndRef = useLatestRef(onColumnDragEnd);
|
|
352
|
+
const onColumnPinningChangeRef = useLatestRef(onColumnPinningChange);
|
|
353
|
+
const onColumnVisibilityChangeRef = useLatestRef(onColumnVisibilityChange);
|
|
354
|
+
const onColumnSizingChangeRef = useLatestRef(onColumnSizingChange);
|
|
355
|
+
const onSelectionChangeRef = useLatestRef(onSelectionChange);
|
|
356
|
+
|
|
357
|
+
const onExportProgressRef = useLatestRef(onExportProgress);
|
|
358
|
+
const onExportCompleteRef = useLatestRef(onExportComplete);
|
|
359
|
+
const onExportErrorRef = useLatestRef(onExportError);
|
|
360
|
+
const onExportCancelRef = useLatestRef(onExportCancel);
|
|
361
|
+
const onExportStateChangeRef = useLatestRef(onExportStateChange);
|
|
362
|
+
const onServerExportRef = useLatestRef(onServerExport);
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
// --- debounced fetch helper (can stay as-is)
|
|
366
|
+
const fetchHandler = useEvent((filters: any, opts: any) => onFetchDataRef.current?.(filters, opts));
|
|
367
|
+
const { debouncedFetch, isLoading: fetchLoading } = useDebouncedFetch(fetchHandler);
|
|
368
|
+
|
|
369
|
+
const tableData = useMemo(() => {
|
|
370
|
+
return serverData !== null ? serverData : data;
|
|
371
|
+
}, [serverData, data]);
|
|
372
|
+
|
|
373
|
+
const tableTotalRow = useMemo(() => {
|
|
374
|
+
return serverData !== null ? serverTotal : totalRow || data.length;
|
|
375
|
+
}, [serverData, serverTotal, totalRow, data]);
|
|
376
|
+
|
|
377
|
+
const tableLoading = useMemo(() => {
|
|
378
|
+
return onFetchData ? loading || fetchLoading : loading;
|
|
379
|
+
}, [onFetchData, loading, fetchLoading]);
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
// --- columns enhancement
|
|
383
|
+
const enhancedColumns = useMemo(() => {
|
|
384
|
+
let cols = [...columns];
|
|
385
|
+
if (enableExpanding) {
|
|
386
|
+
cols = [
|
|
387
|
+
createExpandingColumn<T>({
|
|
388
|
+
...(slotProps?.expandColumn && typeof slotProps.expandColumn === "object"
|
|
389
|
+
? slotProps.expandColumn
|
|
390
|
+
: {}),
|
|
391
|
+
}),
|
|
392
|
+
...cols,
|
|
393
|
+
];
|
|
394
|
+
}
|
|
395
|
+
if (enableRowSelection) {
|
|
396
|
+
cols = [
|
|
397
|
+
createSelectionColumn<T>({
|
|
398
|
+
...(slotProps?.selectionColumn && typeof slotProps.selectionColumn === "object"
|
|
399
|
+
? slotProps.selectionColumn
|
|
400
|
+
: {}),
|
|
401
|
+
multiSelect: enableMultiRowSelection,
|
|
402
|
+
}),
|
|
403
|
+
...cols,
|
|
404
|
+
];
|
|
405
|
+
}
|
|
406
|
+
return withIdsDeep(cols);
|
|
407
|
+
}, [
|
|
408
|
+
columns,
|
|
409
|
+
enableExpanding,
|
|
410
|
+
enableRowSelection,
|
|
411
|
+
enableMultiRowSelection,
|
|
412
|
+
slotProps?.expandColumn,
|
|
413
|
+
slotProps?.selectionColumn,
|
|
414
|
+
]);
|
|
415
|
+
|
|
416
|
+
// --- fetchData: useEvent so it's stable but reads latest state refs
|
|
417
|
+
const fetchData = useEvent(async (overrides: Partial<TableState> = {}, options?: { delay?: number; meta?: DataFetchMeta }) => {
|
|
418
|
+
const s = uiRef.current;
|
|
419
|
+
|
|
420
|
+
const filters: Partial<TableFiltersForFetch> = {
|
|
421
|
+
globalFilter: s.globalFilter,
|
|
422
|
+
pagination: s.pagination,
|
|
423
|
+
columnFilter: s.columnFilter,
|
|
424
|
+
sorting: s.sorting,
|
|
425
|
+
...overrides,
|
|
426
|
+
};
|
|
427
|
+
|
|
428
|
+
onFetchStateChangeRef.current?.(filters, options?.meta);
|
|
429
|
+
|
|
430
|
+
const handler = onFetchDataRef.current;
|
|
431
|
+
if (!handler) return;
|
|
432
|
+
|
|
433
|
+
const delay = options?.delay ?? 0;
|
|
434
|
+
const result = await debouncedFetch(filters, { debounceDelay: delay, meta: options?.meta });
|
|
435
|
+
|
|
436
|
+
if (result && Array.isArray(result.data) && result.total !== undefined) {
|
|
437
|
+
setServerData(result.data);
|
|
438
|
+
setServerTotal(result.total);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
return result;
|
|
442
|
+
});
|
|
443
|
+
|
|
444
|
+
// --- derived selection counts
|
|
445
|
+
const isSomeRowsSelected = useMemo(() => {
|
|
446
|
+
if (!enableBulkActions || !enableRowSelection) return false;
|
|
447
|
+
if (ui.selectionState.type === "exclude") return ui.selectionState.ids.length < tableTotalRow;
|
|
448
|
+
return ui.selectionState.ids.length > 0;
|
|
449
|
+
}, [enableBulkActions, enableRowSelection, ui.selectionState, tableTotalRow]);
|
|
450
|
+
|
|
451
|
+
const selectedRowCount = useMemo(() => {
|
|
452
|
+
if (!enableBulkActions || !enableRowSelection) return 0;
|
|
453
|
+
if (ui.selectionState.type === "exclude") return tableTotalRow - ui.selectionState.ids.length;
|
|
454
|
+
return ui.selectionState.ids.length;
|
|
455
|
+
}, [enableBulkActions, enableRowSelection, ui.selectionState, tableTotalRow]);
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
// --- TanStack Table
|
|
460
|
+
const table = useReactTable({
|
|
461
|
+
_features: [ColumnFilterFeature, SelectionFeature],
|
|
462
|
+
data: tableData,
|
|
463
|
+
columns: enhancedColumns,
|
|
464
|
+
initialState: initialStateConfig,
|
|
465
|
+
state: {
|
|
466
|
+
...(enableSorting ? { sorting: ui.sorting } : {}),
|
|
467
|
+
...(enablePagination ? { pagination: ui.pagination } : {}),
|
|
468
|
+
...(enableGlobalFilter ? { globalFilter: ui.globalFilter } : {}),
|
|
469
|
+
...(enableExpanding ? { expanded: ui.expanded } : {}),
|
|
470
|
+
...(enableColumnDragging ? { columnOrder: ui.columnOrder } : {}),
|
|
471
|
+
...(enableColumnPinning ? { columnPinning: ui.columnPinning } : {}),
|
|
472
|
+
...(enableColumnVisibility ? { columnVisibility: ui.columnVisibility } : {}),
|
|
473
|
+
...(enableColumnResizing ? { columnSizing: ui.columnSizing } : {}),
|
|
474
|
+
...(enableColumnFilter ? { columnFilter: ui.columnFilter } : {}),
|
|
475
|
+
...(enableRowSelection ? { selectionState: ui.selectionState } : {}),
|
|
476
|
+
},
|
|
477
|
+
|
|
478
|
+
selectMode,
|
|
479
|
+
enableAdvanceSelection: !!enableRowSelection,
|
|
480
|
+
isRowSelectable: isRowSelectable as any,
|
|
481
|
+
|
|
482
|
+
...(enableRowSelection
|
|
483
|
+
? {
|
|
484
|
+
onSelectionStateChange: (updaterOrValue: any) => {
|
|
485
|
+
dispatch({
|
|
486
|
+
type: "SET_SELECTION",
|
|
487
|
+
payload:
|
|
488
|
+
typeof updaterOrValue === "function"
|
|
489
|
+
? updaterOrValue(uiRef.current.selectionState)
|
|
490
|
+
: updaterOrValue,
|
|
491
|
+
});
|
|
492
|
+
},
|
|
493
|
+
}
|
|
494
|
+
: {}),
|
|
495
|
+
|
|
496
|
+
enableAdvanceColumnFilter: enableColumnFilter,
|
|
497
|
+
onColumnFilterChange: (updater: any) => {
|
|
498
|
+
const next = typeof updater === "function" ? updater(uiRef.current.columnFilter) : updater;
|
|
499
|
+
dispatch({ type: "SET_COLUMN_FILTER", payload: next });
|
|
500
|
+
},
|
|
501
|
+
onColumnFilterApply: (state: ColumnFilterState) => {
|
|
502
|
+
dispatch({ type: "SET_COLUMN_FILTER_RESET_PAGE", payload: state });
|
|
503
|
+
},
|
|
504
|
+
|
|
505
|
+
...(enableSorting
|
|
506
|
+
? {
|
|
507
|
+
onSortingChange: (updaterOrValue: any) => {
|
|
508
|
+
const prev = uiRef.current.sorting;
|
|
509
|
+
const next = typeof updaterOrValue === "function" ? updaterOrValue(prev) : updaterOrValue;
|
|
510
|
+
const cleaned = (next || []).filter((s: any) => s?.id);
|
|
511
|
+
onSortingChangeRef.current?.(cleaned);
|
|
512
|
+
dispatch({ type: "SET_SORTING_RESET_PAGE", payload: cleaned });
|
|
513
|
+
},
|
|
514
|
+
}
|
|
515
|
+
: {}),
|
|
516
|
+
|
|
517
|
+
...(enablePagination
|
|
518
|
+
? {
|
|
519
|
+
onPaginationChange: (updater: any) => {
|
|
520
|
+
const prev = uiRef.current.pagination;
|
|
521
|
+
const next = typeof updater === "function" ? updater(prev) : updater;
|
|
522
|
+
onPaginationChangeRef.current?.(next);
|
|
523
|
+
dispatch({ type: "SET_PAGINATION", payload: next });
|
|
524
|
+
},
|
|
525
|
+
}
|
|
526
|
+
: {}),
|
|
527
|
+
|
|
528
|
+
...(enableGlobalFilter
|
|
529
|
+
? {
|
|
530
|
+
onGlobalFilterChange: (updaterOrValue: any) => {
|
|
531
|
+
const prev = uiRef.current.globalFilter;
|
|
532
|
+
const next = typeof updaterOrValue === "function" ? updaterOrValue(prev) : updaterOrValue;
|
|
533
|
+
onGlobalFilterChangeRef.current?.(next);
|
|
534
|
+
nextFetchDelayRef.current = 400;
|
|
535
|
+
dispatch({ type: "SET_GLOBAL_FILTER_RESET_PAGE", payload: next });
|
|
536
|
+
},
|
|
537
|
+
}
|
|
538
|
+
: {}),
|
|
539
|
+
|
|
540
|
+
...(enableExpanding ? { onExpandedChange: (u: any) => dispatch({ type: "SET_EXPANDED", payload: typeof u === "function" ? u(uiRef.current.expanded) : u }) } : {}),
|
|
541
|
+
...(enableColumnDragging ? { onColumnOrderChange: (u: any) => dispatch({ type: "SET_COLUMN_ORDER", payload: typeof u === "function" ? u(uiRef.current.columnOrder) : u }) } : {}),
|
|
542
|
+
...(enableColumnPinning ? { onColumnPinningChange: (u: any) => dispatch({ type: "SET_COLUMN_PINNING", payload: typeof u === "function" ? u(uiRef.current.columnPinning) : u }) } : {}),
|
|
543
|
+
...(enableColumnVisibility ? { onColumnVisibilityChange: (u: any) => dispatch({ type: "SET_COLUMN_VISIBILITY", payload: typeof u === "function" ? u(uiRef.current.columnVisibility) : u }) } : {}),
|
|
544
|
+
...(enableColumnResizing ? { onColumnSizingChange: (u: any) => dispatch({ type: "SET_COLUMN_SIZING", payload: typeof u === "function" ? u(uiRef.current.columnSizing) : u }) } : {}),
|
|
545
|
+
|
|
546
|
+
getCoreRowModel: getCoreRowModel(),
|
|
547
|
+
...(enableSorting ? { getSortedRowModel: getSortedRowModel() } : {}),
|
|
548
|
+
...(enableColumnFilter || enableGlobalFilter ? { getFilteredRowModel: getCombinedFilteredRowModel<T>() } : {}),
|
|
549
|
+
...(enablePagination && !isServerPagination ? { getPaginationRowModel: getPaginationRowModel() } : {}),
|
|
550
|
+
|
|
551
|
+
enableSorting,
|
|
552
|
+
manualSorting: isServerSorting,
|
|
553
|
+
manualFiltering: isServerFiltering,
|
|
554
|
+
|
|
555
|
+
enableColumnResizing,
|
|
556
|
+
columnResizeMode,
|
|
557
|
+
columnResizeDirection: theme.direction,
|
|
558
|
+
|
|
559
|
+
enableColumnPinning,
|
|
560
|
+
...(enableExpanding ? { getRowCanExpand: getRowCanExpand as any } : {}),
|
|
561
|
+
|
|
562
|
+
manualPagination: isServerPagination,
|
|
563
|
+
autoResetPageIndex: false,
|
|
564
|
+
|
|
565
|
+
rowCount: enablePagination ? (tableTotalRow ?? tableData.length) : tableData.length,
|
|
566
|
+
getRowId: (row: any, index: number) => generateRowId(row, index, idKey),
|
|
567
|
+
});
|
|
568
|
+
|
|
569
|
+
// --- layout sizing
|
|
570
|
+
const allLeafColumns = table.getAllLeafColumns();
|
|
571
|
+
const hasExplicitSizing = allLeafColumns.some((col) => {
|
|
572
|
+
const { size, minSize, maxSize } = col.columnDef;
|
|
573
|
+
return size !== undefined || minSize !== undefined || maxSize !== undefined;
|
|
574
|
+
});
|
|
575
|
+
const useFixedLayout = fitToScreen || enableColumnResizing || hasExplicitSizing;
|
|
576
|
+
const tableTotalSize = table.getTotalSize();
|
|
577
|
+
const tableWidth = fitToScreen ? "100%" : useFixedLayout ? tableTotalSize : "100%";
|
|
578
|
+
|
|
579
|
+
const tableStyle: CSSProperties = {
|
|
580
|
+
width: tableWidth,
|
|
581
|
+
minWidth: fitToScreen ? tableTotalSize : undefined,
|
|
582
|
+
tableLayout: useFixedLayout ? "fixed" : "auto",
|
|
583
|
+
};
|
|
584
|
+
|
|
585
|
+
// --- virtualization
|
|
586
|
+
const rows = table.getRowModel().rows;
|
|
587
|
+
const rowVirtualizer = useVirtualizer({
|
|
588
|
+
count: rows.length,
|
|
589
|
+
getScrollElement: () => tableContainerRef.current,
|
|
590
|
+
estimateSize: () => estimateRowHeight,
|
|
591
|
+
overscan: 10,
|
|
592
|
+
enabled: enableVirtualization && !enablePagination && rows.length > 0,
|
|
593
|
+
});
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
const serverKey = useMemo(() => {
|
|
597
|
+
if (!(isServerMode || isServerPagination || isServerFiltering || isServerSorting)) return null;
|
|
598
|
+
|
|
599
|
+
return JSON.stringify({
|
|
600
|
+
sorting: ui.sorting,
|
|
601
|
+
pagination: ui.pagination,
|
|
602
|
+
globalFilter: ui.globalFilter,
|
|
603
|
+
columnFilter: { filters: ui.columnFilter.filters, logic: ui.columnFilter.logic }, // only applied
|
|
604
|
+
});
|
|
605
|
+
}, [isServerMode, isServerPagination, isServerFiltering, isServerSorting, ui.sorting, ui.pagination, ui.globalFilter, ui.columnFilter]);
|
|
606
|
+
const serverKeyRef = useLatestRef(serverKey);
|
|
607
|
+
const lastServerKeyRef = useRef<string | null>(null);
|
|
608
|
+
|
|
609
|
+
// --- initial fetch
|
|
610
|
+
useEffect(() => {
|
|
611
|
+
if (!initialLoadData) return;
|
|
612
|
+
// If we're in server mode, mark current serverKey as already handled
|
|
613
|
+
// so the serverKey effect doesn't immediately fetch again.
|
|
614
|
+
if (serverKeyRef.current) {
|
|
615
|
+
lastServerKeyRef.current = serverKeyRef.current;
|
|
616
|
+
}
|
|
617
|
+
if (onFetchData || onFetchStateChange) {
|
|
618
|
+
void fetchData({}, { delay: 0, meta: { reason: "initial" } });
|
|
619
|
+
}
|
|
620
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
621
|
+
}, []);
|
|
622
|
+
|
|
623
|
+
useEffect(() => {
|
|
624
|
+
if (!serverKey) return;
|
|
625
|
+
if (serverKey === lastServerKeyRef.current) return;
|
|
626
|
+
lastServerKeyRef.current = serverKey;
|
|
627
|
+
|
|
628
|
+
const delay = nextFetchDelayRef.current ?? 0;
|
|
629
|
+
nextFetchDelayRef.current = 0; // reset after using
|
|
630
|
+
|
|
631
|
+
const timeoutId = setTimeout(() => {
|
|
632
|
+
void fetchData({}, { delay, meta: { reason: "stateChange" } });
|
|
633
|
+
}, 0);
|
|
634
|
+
return () => clearTimeout(timeoutId);
|
|
635
|
+
}, [serverKey, fetchData]);
|
|
636
|
+
|
|
637
|
+
// columnFilter apply handler stays explicit (button), but you can also auto-fetch on change if needed
|
|
638
|
+
const handleColumnFilterChangeHandler = useCallback(
|
|
639
|
+
(updater: any, isApply = false) => {
|
|
640
|
+
const prev = uiRef.current.columnFilter;
|
|
641
|
+
const next = typeof updater === "function" ? updater(prev) : updater;
|
|
642
|
+
if (isApply) {
|
|
643
|
+
nextFetchDelayRef.current = 0;
|
|
644
|
+
dispatch({ type: "SET_COLUMN_FILTER_RESET_PAGE", payload: next });
|
|
645
|
+
} else {
|
|
646
|
+
dispatch({ type: "SET_COLUMN_FILTER", payload: next });
|
|
647
|
+
}
|
|
648
|
+
onColumnFiltersChangeRef.current?.(next, isApply);
|
|
649
|
+
},
|
|
650
|
+
[onColumnFiltersChangeRef, uiRef]
|
|
651
|
+
);
|
|
652
|
+
|
|
653
|
+
// --- emit table state (dedupe)
|
|
654
|
+
useEffect(() => {
|
|
655
|
+
const cb = onDataStateChangeRef.current;
|
|
656
|
+
if (!cb) return;
|
|
657
|
+
|
|
658
|
+
const live = table.getState();
|
|
659
|
+
const payload = {
|
|
660
|
+
sorting: live.sorting,
|
|
661
|
+
pagination: live.pagination,
|
|
662
|
+
globalFilter: live.globalFilter,
|
|
663
|
+
columnFilter: live.columnFilter,
|
|
664
|
+
columnVisibility: live.columnVisibility,
|
|
665
|
+
columnSizing: live.columnSizing,
|
|
666
|
+
columnOrder: live.columnOrder,
|
|
667
|
+
columnPinning: live.columnPinning,
|
|
668
|
+
};
|
|
669
|
+
const key = JSON.stringify(payload);
|
|
670
|
+
if (key === lastSentRef.current) return;
|
|
671
|
+
lastSentRef.current = key;
|
|
672
|
+
cb(payload);
|
|
673
|
+
}, [table, ui.sorting, ui.pagination, ui.globalFilter, ui.columnFilter, ui.columnVisibility, ui.columnSizing, ui.columnOrder, ui.columnPinning, onDataStateChangeRef]);
|
|
674
|
+
|
|
675
|
+
// --- helpers
|
|
676
|
+
const resetPageToFirst = useCallback(() => {
|
|
677
|
+
return { pageIndex: 0, pageSize: uiRef.current.pagination.pageSize };
|
|
678
|
+
}, [uiRef]);
|
|
679
|
+
|
|
680
|
+
const normalizeRefreshOptions = useCallback(
|
|
681
|
+
(options?: boolean | DataRefreshOptions, fallbackReason: string = "refresh") => {
|
|
682
|
+
if (typeof options === "boolean") return { resetPagination: options, force: false, reason: fallbackReason };
|
|
683
|
+
return {
|
|
684
|
+
resetPagination: options?.resetPagination ?? false,
|
|
685
|
+
force: options?.force ?? false,
|
|
686
|
+
reason: options?.reason ?? fallbackReason,
|
|
687
|
+
};
|
|
688
|
+
},
|
|
689
|
+
[]
|
|
690
|
+
);
|
|
691
|
+
|
|
692
|
+
const triggerRefresh = useCallback(
|
|
693
|
+
async (options?: boolean | DataRefreshOptions, fallbackReason: string = "refresh") => {
|
|
694
|
+
const n = normalizeRefreshOptions(options, fallbackReason);
|
|
695
|
+
const current = uiRef.current.pagination;
|
|
696
|
+
const nextPagination = enablePagination
|
|
697
|
+
? { pageIndex: n.resetPagination ? 0 : current.pageIndex, pageSize: current.pageSize }
|
|
698
|
+
: undefined;
|
|
699
|
+
|
|
700
|
+
if (nextPagination) {
|
|
701
|
+
nextFetchDelayRef.current = 0;
|
|
702
|
+
dispatch({ type: "SET_PAGINATION", payload: nextPagination });
|
|
703
|
+
onPaginationChangeRef.current?.(nextPagination);
|
|
704
|
+
}
|
|
705
|
+
const paginationChanged = !!nextPagination &&
|
|
706
|
+
(nextPagination.pageIndex !== current.pageIndex || nextPagination.pageSize !== current.pageSize);
|
|
707
|
+
|
|
708
|
+
if (!paginationChanged) {
|
|
709
|
+
await fetchData({}, { delay: 0, meta: { reason: n.reason, force: n.force } });
|
|
710
|
+
}
|
|
711
|
+
},
|
|
712
|
+
[enablePagination, fetchData, normalizeRefreshOptions, onPaginationChangeRef, uiRef]
|
|
713
|
+
);
|
|
714
|
+
|
|
715
|
+
const getResetPayload = useCallback((): Partial<EngineUIState> => {
|
|
716
|
+
const resetSorting = initialStateConfig.sorting || [];
|
|
717
|
+
const resetGlobalFilter = initialStateConfig.globalFilter ?? "";
|
|
718
|
+
const resetColumnFilter = (initialStateConfig.columnFilter ?? DEFAULT_INITIAL_STATE.columnFilter) as ColumnFilterState;
|
|
719
|
+
|
|
720
|
+
const resetPagination = enablePagination
|
|
721
|
+
? (initialStateConfig.pagination || { pageIndex: 0, pageSize: 10 })
|
|
722
|
+
: uiRef.current.pagination;
|
|
723
|
+
|
|
724
|
+
return {
|
|
725
|
+
sorting: resetSorting,
|
|
726
|
+
globalFilter: resetGlobalFilter,
|
|
727
|
+
columnFilter: resetColumnFilter,
|
|
728
|
+
...(enablePagination ? { pagination: resetPagination } : {}),
|
|
729
|
+
selectionState: initialStateConfig.selectionState ?? DEFAULT_INITIAL_STATE.selectionState,
|
|
730
|
+
expanded: {},
|
|
731
|
+
columnVisibility: initialStateConfig.columnVisibility || {},
|
|
732
|
+
columnSizing: initialStateConfig.columnSizing || {},
|
|
733
|
+
columnOrder: initialStateConfig.columnOrder || [],
|
|
734
|
+
columnPinning: initialStateConfig.columnPinning || { left: [], right: [] },
|
|
735
|
+
};
|
|
736
|
+
}, [enablePagination, initialStateConfig]);
|
|
737
|
+
|
|
738
|
+
const resetAllAndReload = useCallback(() => {
|
|
739
|
+
const payload = getResetPayload();
|
|
740
|
+
dispatch({ type: "RESET_ALL", payload });
|
|
741
|
+
void fetchData(
|
|
742
|
+
{
|
|
743
|
+
sorting: payload.sorting as any,
|
|
744
|
+
globalFilter: payload.globalFilter as any,
|
|
745
|
+
columnFilter: payload.columnFilter as any,
|
|
746
|
+
...(enablePagination ? { pagination: payload.pagination as any } : {}),
|
|
747
|
+
},
|
|
748
|
+
{ delay: 0, meta: { reason: "reset", force: true } }
|
|
749
|
+
);
|
|
750
|
+
}, [enablePagination, fetchData, getResetPayload]);
|
|
751
|
+
|
|
752
|
+
// --- export (refs + small UI state)
|
|
753
|
+
const setExportControllerSafely = useCallback(
|
|
754
|
+
(value: AbortController | null | ((current: AbortController | null) => AbortController | null)) => {
|
|
755
|
+
setExportController((current) => {
|
|
756
|
+
const next = typeof value === "function" ? (value as any)(current) : value;
|
|
757
|
+
exportControllerRef.current = next;
|
|
758
|
+
return next;
|
|
759
|
+
});
|
|
760
|
+
},
|
|
761
|
+
[]
|
|
762
|
+
);
|
|
763
|
+
|
|
764
|
+
const handleExportProgressInternal = useCallback((p: ExportProgressPayload) => {
|
|
765
|
+
setExportProgress(p || {});
|
|
766
|
+
onExportProgressRef.current?.(p);
|
|
767
|
+
}, []);
|
|
768
|
+
|
|
769
|
+
const handleExportStateChangeInternal = useCallback((s: ExportStateChange) => {
|
|
770
|
+
setExportPhase(s.phase);
|
|
771
|
+
if (s.processedRows !== undefined || s.totalRows !== undefined || s.percentage !== undefined) {
|
|
772
|
+
setExportProgress({
|
|
773
|
+
processedRows: s.processedRows,
|
|
774
|
+
totalRows: s.totalRows,
|
|
775
|
+
percentage: s.percentage,
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
onExportStateChangeRef.current?.(s);
|
|
779
|
+
}, []);
|
|
780
|
+
|
|
781
|
+
const runExportWithPolicy = useCallback(
|
|
782
|
+
async (options: { format: "csv" | "excel"; filename: string; mode: "client" | "server"; execute: (controller: AbortController) => Promise<void> }) => {
|
|
783
|
+
const { format, filename, mode, execute } = options;
|
|
784
|
+
|
|
785
|
+
const startExecution = async () => {
|
|
786
|
+
const controller = new AbortController();
|
|
787
|
+
setExportProgress({});
|
|
788
|
+
setExportControllerSafely(controller);
|
|
789
|
+
try {
|
|
790
|
+
await execute(controller);
|
|
791
|
+
} finally {
|
|
792
|
+
setExportControllerSafely((cur) => (cur === controller ? null : cur));
|
|
793
|
+
}
|
|
794
|
+
};
|
|
795
|
+
|
|
796
|
+
if (exportConcurrency === "queue") {
|
|
797
|
+
setQueuedExportCount((p) => p + 1);
|
|
798
|
+
const runQueued = async () => {
|
|
799
|
+
setQueuedExportCount((p) => Math.max(0, p - 1));
|
|
800
|
+
await startExecution();
|
|
801
|
+
};
|
|
802
|
+
const queuedPromise = exportQueueRef.current.catch(() => undefined).then(runQueued);
|
|
803
|
+
exportQueueRef.current = queuedPromise;
|
|
804
|
+
return queuedPromise;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
const active = exportControllerRef.current;
|
|
808
|
+
if (active) {
|
|
809
|
+
if (exportConcurrency === "ignoreIfRunning") {
|
|
810
|
+
handleExportStateChangeInternal({
|
|
811
|
+
phase: "error",
|
|
812
|
+
mode,
|
|
813
|
+
format,
|
|
814
|
+
filename,
|
|
815
|
+
message: "An export is already running",
|
|
816
|
+
code: "EXPORT_IN_PROGRESS",
|
|
817
|
+
endedAt: Date.now(),
|
|
818
|
+
} as any);
|
|
819
|
+
onExportErrorRef.current?.({ message: "An export is already running", code: "EXPORT_IN_PROGRESS" });
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
if (exportConcurrency === "cancelAndRestart") active.abort();
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
await startExecution();
|
|
826
|
+
},
|
|
827
|
+
[exportConcurrency, handleExportStateChangeInternal, onExportErrorRef, setExportControllerSafely]
|
|
828
|
+
);
|
|
829
|
+
|
|
830
|
+
const handleCancelExport = useCallback(() => {
|
|
831
|
+
const active = exportControllerRef.current;
|
|
832
|
+
if (!active) return;
|
|
833
|
+
active.abort();
|
|
834
|
+
setExportControllerSafely((cur) => (cur === active ? null : cur));
|
|
835
|
+
onExportCancelRef.current?.();
|
|
836
|
+
}, [onExportCancelRef, setExportControllerSafely]);
|
|
837
|
+
|
|
838
|
+
const isExporting = exportController !== null;
|
|
839
|
+
|
|
840
|
+
// --- stable API (created once)
|
|
841
|
+
if (!apiRef.current) {
|
|
842
|
+
apiRef.current = {} as DataTableApi<T>;
|
|
843
|
+
|
|
844
|
+
// IMPORTANT: do NOT capture `table/ui/data` here. Always read from refs inside methods.
|
|
845
|
+
(apiRef.current as any).table = { getTable: () => table }; // will be updated below via tableRef
|
|
846
|
+
// We'll overwrite getTable below with a ref-backed function.
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
// table ref so API always returns latest table instance
|
|
850
|
+
const tableRef = useLatestRef(table);
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
useEffect(() => {
|
|
854
|
+
const api = apiRef.current!;
|
|
855
|
+
api.table = { getTable: () => tableRef.current } as any;
|
|
856
|
+
|
|
857
|
+
// --- state getters
|
|
858
|
+
api.state = {
|
|
859
|
+
getTableState: () => tableRef.current.getState(),
|
|
860
|
+
getCurrentFilters: () => tableRef.current.getState().columnFilter,
|
|
861
|
+
getCurrentSorting: () => tableRef.current.getState().sorting,
|
|
862
|
+
getCurrentPagination: () => tableRef.current.getState().pagination,
|
|
863
|
+
getCurrentSelection: () => uiRef.current.selectionState,
|
|
864
|
+
getGlobalFilter: () => tableRef.current.getState().globalFilter,
|
|
865
|
+
};
|
|
866
|
+
|
|
867
|
+
// --- data
|
|
868
|
+
api.data = {
|
|
869
|
+
refresh: (options?: boolean | DataRefreshOptions) => void triggerRefresh(options, "refresh"),
|
|
870
|
+
reload: (options: DataRefreshOptions = {}) => void triggerRefresh({ ...options, reason: options.reason ?? "reload" }, "reload"),
|
|
871
|
+
resetAll: () => resetAllAndReload(),
|
|
872
|
+
|
|
873
|
+
getAllData: () => {
|
|
874
|
+
const sData = serverDataRef.current;
|
|
875
|
+
const base = sData !== null ? sData : dataRef.current;
|
|
876
|
+
return [...base];
|
|
877
|
+
},
|
|
878
|
+
getDataCount: () => {
|
|
879
|
+
const sData = serverDataRef.current;
|
|
880
|
+
const base = sData !== null ? sData : dataRef.current;
|
|
881
|
+
return base.length;
|
|
882
|
+
},
|
|
883
|
+
getFilteredDataCount: () => tableRef.current.getFilteredRowModel().rows.length,
|
|
884
|
+
} as any;
|
|
885
|
+
|
|
886
|
+
// --- sorting/pagination/filtering - dispatch + callbacks + server fetch policies
|
|
887
|
+
api.sorting = {
|
|
888
|
+
setSorting: (next: SortingState) => {
|
|
889
|
+
const cleaned = (next || []).filter((s: any) => s?.id);
|
|
890
|
+
onSortingChangeRef.current?.(cleaned);
|
|
891
|
+
nextFetchDelayRef.current = 0;
|
|
892
|
+
dispatch({ type: "SET_SORTING_RESET_PAGE", payload: cleaned });
|
|
893
|
+
},
|
|
894
|
+
clearSorting: () => {
|
|
895
|
+
onSortingChangeRef.current?.([]);
|
|
896
|
+
nextFetchDelayRef.current = 0;
|
|
897
|
+
dispatch({ type: "SET_SORTING_RESET_PAGE", payload: [] });
|
|
898
|
+
},
|
|
899
|
+
resetSorting: () => {
|
|
900
|
+
const next = (initialStateConfig.sorting || []) as SortingState;
|
|
901
|
+
onSortingChangeRef.current?.(next);
|
|
902
|
+
nextFetchDelayRef.current = 0;
|
|
903
|
+
dispatch({ type: "SET_SORTING_RESET_PAGE", payload: next });
|
|
904
|
+
},
|
|
905
|
+
} as any;
|
|
906
|
+
|
|
907
|
+
api.pagination = {
|
|
908
|
+
goToPage: (pageIndex: number) => {
|
|
909
|
+
const prev = uiRef.current.pagination;
|
|
910
|
+
const next = { ...prev, pageIndex };
|
|
911
|
+
onPaginationChangeRef.current?.(next);
|
|
912
|
+
nextFetchDelayRef.current = 0;
|
|
913
|
+
dispatch({ type: "SET_PAGINATION", payload: next });
|
|
914
|
+
},
|
|
915
|
+
setPageSize: (pageSize: number) => {
|
|
916
|
+
const next = { pageIndex: 0, pageSize };
|
|
917
|
+
onPaginationChangeRef.current?.(next);
|
|
918
|
+
nextFetchDelayRef.current = 0;
|
|
919
|
+
dispatch({ type: "SET_PAGINATION", payload: next });
|
|
920
|
+
},
|
|
921
|
+
resetPagination: () => {
|
|
922
|
+
const next = (initialStateConfig.pagination || { pageIndex: 0, pageSize: 10 }) as any;
|
|
923
|
+
onPaginationChangeRef.current?.(next);
|
|
924
|
+
nextFetchDelayRef.current = 0;
|
|
925
|
+
dispatch({ type: "SET_PAGINATION", payload: next });
|
|
926
|
+
},
|
|
927
|
+
} as any;
|
|
928
|
+
|
|
929
|
+
api.filtering = {
|
|
930
|
+
setGlobalFilter: (filter: string) => {
|
|
931
|
+
onGlobalFilterChangeRef.current?.(filter);
|
|
932
|
+
nextFetchDelayRef.current = 400;
|
|
933
|
+
dispatch({ type: "SET_GLOBAL_FILTER_RESET_PAGE", payload: filter });
|
|
934
|
+
},
|
|
935
|
+
clearGlobalFilter: () => {
|
|
936
|
+
onGlobalFilterChangeRef.current?.("");
|
|
937
|
+
nextFetchDelayRef.current = 400;
|
|
938
|
+
dispatch({ type: "SET_GLOBAL_FILTER_RESET_PAGE", payload: "" });
|
|
939
|
+
},
|
|
940
|
+
setColumnFilters: (filters: ColumnFilterState, isApply = false) => handleColumnFilterChangeHandler(filters, isApply),
|
|
941
|
+
} as any;
|
|
942
|
+
|
|
943
|
+
api.columnVisibility = {
|
|
944
|
+
showColumn: (id: string) => dispatch({ type: "SET_COLUMN_VISIBILITY", payload: { ...uiRef.current.columnVisibility, [id]: true } }),
|
|
945
|
+
hideColumn: (id: string) => dispatch({ type: "SET_COLUMN_VISIBILITY", payload: { ...uiRef.current.columnVisibility, [id]: false } }),
|
|
946
|
+
resetColumnVisibility: () => dispatch({ type: "SET_COLUMN_VISIBILITY", payload: initialStateConfig.columnVisibility || {} }),
|
|
947
|
+
} as any;
|
|
948
|
+
|
|
949
|
+
api.columnOrdering = {
|
|
950
|
+
setColumnOrder: (next: ColumnOrderState) => {
|
|
951
|
+
dispatch({ type: "SET_COLUMN_ORDER", payload: next });
|
|
952
|
+
onColumnDragEndRef.current?.(next);
|
|
953
|
+
},
|
|
954
|
+
resetColumnOrder: () => dispatch({ type: "SET_COLUMN_ORDER", payload: initialStateConfig.columnOrder || [] }),
|
|
955
|
+
} as any;
|
|
956
|
+
|
|
957
|
+
api.columnPinning = {
|
|
958
|
+
setPinning: (next: ColumnPinningState) => {
|
|
959
|
+
dispatch({ type: "SET_COLUMN_PINNING", payload: next });
|
|
960
|
+
onColumnPinningChangeRef.current?.(next);
|
|
961
|
+
},
|
|
962
|
+
resetColumnPinning: () => dispatch({ type: "SET_COLUMN_PINNING", payload: initialStateConfig.columnPinning || { left: [], right: [] } }),
|
|
963
|
+
} as any;
|
|
964
|
+
|
|
965
|
+
api.columnResizing = {
|
|
966
|
+
resetColumnSizing: () => dispatch({ type: "SET_COLUMN_SIZING", payload: initialStateConfig.columnSizing || {} }),
|
|
967
|
+
} as any;
|
|
968
|
+
|
|
969
|
+
api.selection = {
|
|
970
|
+
getSelectionState: () => tableRef.current.getSelectionState?.() || ({ ids: [], type: "include" } as const),
|
|
971
|
+
getSelectedRows: () => tableRef.current.getSelectedRows(),
|
|
972
|
+
getSelectedCount: () => tableRef.current.getSelectedCount(),
|
|
973
|
+
isRowSelected: (rowId: string) => tableRef.current.getIsRowSelected(rowId) || false,
|
|
974
|
+
// keep using your table extension methods if you have them:
|
|
975
|
+
selectAll: () => tableRef.current.selectAll?.(),
|
|
976
|
+
deselectAll: () => tableRef.current.deselectAll?.(),
|
|
977
|
+
} as any;
|
|
978
|
+
|
|
979
|
+
// --- export API (use your existing exportClientData/exportServerData)
|
|
980
|
+
api.export = {
|
|
981
|
+
exportCSV: async (options: DataTableExportApiOptions = {}) => {
|
|
982
|
+
const fn = options.filename ?? exportFilename;
|
|
983
|
+
const chunkSize = options.chunkSize ?? exportChunkSize;
|
|
984
|
+
const strictTotalCheck = options.strictTotalCheck ?? exportStrictTotalCheck;
|
|
985
|
+
const sanitizeCSV = options.sanitizeCSV ?? exportSanitizeCSV;
|
|
986
|
+
|
|
987
|
+
const mode: "client" | "server" = dataMode === "server" && !!onServerExportRef.current ? "server" : "client";
|
|
988
|
+
|
|
989
|
+
await runExportWithPolicy({
|
|
990
|
+
format: "csv",
|
|
991
|
+
filename: fn,
|
|
992
|
+
mode,
|
|
993
|
+
execute: async (controller) => {
|
|
994
|
+
// TODO: keep your state-change event mapping (starting/progress/completed/cancel/error)
|
|
995
|
+
if (mode === "server" && onServerExportRef.current) {
|
|
996
|
+
await exportServerData(tableRef.current, {
|
|
997
|
+
format: "csv",
|
|
998
|
+
filename: fn,
|
|
999
|
+
fetchData: (filters: any, selection: any, signal?: AbortSignal) =>
|
|
1000
|
+
onServerExportRef.current?.(filters, selection, signal),
|
|
1001
|
+
currentFilters: {
|
|
1002
|
+
globalFilter: tableRef.current.getState().globalFilter,
|
|
1003
|
+
columnFilter: tableRef.current.getState().columnFilter,
|
|
1004
|
+
sorting: tableRef.current.getState().sorting,
|
|
1005
|
+
pagination: tableRef.current.getState().pagination,
|
|
1006
|
+
},
|
|
1007
|
+
selection: tableRef.current.getSelectionState?.(),
|
|
1008
|
+
onProgress: handleExportProgressInternal,
|
|
1009
|
+
onComplete: onExportCompleteRef.current,
|
|
1010
|
+
onError: onExportErrorRef.current,
|
|
1011
|
+
onStateChange: (s: any) => handleExportStateChangeInternal({ ...s, mode, format: "csv", filename: fn, queueLength: queuedExportCount } as any),
|
|
1012
|
+
signal: controller.signal,
|
|
1013
|
+
chunkSize,
|
|
1014
|
+
strictTotalCheck,
|
|
1015
|
+
sanitizeCSV,
|
|
1016
|
+
});
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
await exportClientData(tableRef.current, {
|
|
1021
|
+
format: "csv",
|
|
1022
|
+
filename: fn,
|
|
1023
|
+
onProgress: handleExportProgressInternal,
|
|
1024
|
+
onComplete: onExportCompleteRef.current,
|
|
1025
|
+
onError: onExportErrorRef.current,
|
|
1026
|
+
onStateChange: (s: any) => handleExportStateChangeInternal({ ...s, mode, format: "csv", filename: fn, queueLength: queuedExportCount } as any),
|
|
1027
|
+
signal: controller.signal,
|
|
1028
|
+
sanitizeCSV,
|
|
1029
|
+
});
|
|
1030
|
+
},
|
|
1031
|
+
});
|
|
1032
|
+
},
|
|
1033
|
+
|
|
1034
|
+
exportExcel: async (options: DataTableExportApiOptions = {}) => {
|
|
1035
|
+
const fn = options.filename ?? exportFilename;
|
|
1036
|
+
const chunkSize = options.chunkSize ?? exportChunkSize;
|
|
1037
|
+
const strictTotalCheck = options.strictTotalCheck ?? exportStrictTotalCheck;
|
|
1038
|
+
const sanitizeCSV = options.sanitizeCSV ?? exportSanitizeCSV;
|
|
1039
|
+
|
|
1040
|
+
const mode: "client" | "server" = dataMode === "server" && !!onServerExportRef.current ? "server" : "client";
|
|
1041
|
+
|
|
1042
|
+
await runExportWithPolicy({
|
|
1043
|
+
format: "excel",
|
|
1044
|
+
filename: fn,
|
|
1045
|
+
mode,
|
|
1046
|
+
execute: async (controller) => {
|
|
1047
|
+
// TODO: keep your state-change event mapping (starting/progress/completed/cancel/error)
|
|
1048
|
+
if (mode === "server" && onServerExportRef.current) {
|
|
1049
|
+
await exportServerData(tableRef.current, {
|
|
1050
|
+
format: "excel",
|
|
1051
|
+
filename: fn,
|
|
1052
|
+
fetchData: (filters: any, selection: any, signal?: AbortSignal) =>
|
|
1053
|
+
onServerExportRef.current?.(filters, selection, signal),
|
|
1054
|
+
currentFilters: {
|
|
1055
|
+
globalFilter: tableRef.current.getState().globalFilter,
|
|
1056
|
+
columnFilter: tableRef.current.getState().columnFilter,
|
|
1057
|
+
sorting: tableRef.current.getState().sorting,
|
|
1058
|
+
pagination: tableRef.current.getState().pagination,
|
|
1059
|
+
},
|
|
1060
|
+
selection: tableRef.current.getSelectionState?.(),
|
|
1061
|
+
onProgress: handleExportProgressInternal,
|
|
1062
|
+
onComplete: onExportCompleteRef.current,
|
|
1063
|
+
onError: onExportErrorRef.current,
|
|
1064
|
+
onStateChange: (s: any) => handleExportStateChangeInternal({ ...s, mode, format: "csv", filename: fn, queueLength: queuedExportCount } as any),
|
|
1065
|
+
signal: controller.signal,
|
|
1066
|
+
chunkSize,
|
|
1067
|
+
strictTotalCheck,
|
|
1068
|
+
sanitizeCSV,
|
|
1069
|
+
});
|
|
1070
|
+
return;
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
await exportClientData(tableRef.current, {
|
|
1074
|
+
format: "excel",
|
|
1075
|
+
filename: fn,
|
|
1076
|
+
onProgress: handleExportProgressInternal,
|
|
1077
|
+
onComplete: onExportCompleteRef.current,
|
|
1078
|
+
onError: onExportErrorRef.current,
|
|
1079
|
+
onStateChange: (s: any) => handleExportStateChangeInternal({ ...s, mode, format: "csv", filename: fn, queueLength: queuedExportCount } as any),
|
|
1080
|
+
signal: controller.signal,
|
|
1081
|
+
sanitizeCSV,
|
|
1082
|
+
});
|
|
1083
|
+
},
|
|
1084
|
+
});
|
|
1085
|
+
},
|
|
1086
|
+
|
|
1087
|
+
isExporting: () => exportControllerRef.current != null,
|
|
1088
|
+
cancelExport: () => handleCancelExport(),
|
|
1089
|
+
} as any;
|
|
1090
|
+
}, [dataMode, exportChunkSize, exportFilename, exportSanitizeCSV, exportStrictTotalCheck, fetchData, handleCancelExport, handleColumnFilterChangeHandler, handleExportProgressInternal, handleExportStateChangeInternal, initialStateConfig, isServerMode, isServerPagination, isServerSorting, resetAllAndReload, resetPageToFirst, runExportWithPolicy, triggerRefresh, queuedExportCount, tableRef, uiRef, serverDataRef, dataRef, onSortingChangeRef, onPaginationChangeRef, onGlobalFilterChangeRef, onColumnDragEndRef, onColumnPinningChangeRef, onServerExportRef, onExportCompleteRef, onExportErrorRef]);
|
|
1091
|
+
|
|
1092
|
+
// --- imperative handlers (used by TanStack callbacks above or view)
|
|
1093
|
+
const handleSortingChange = useCallback(
|
|
1094
|
+
(updaterOrValue: Updater<SortingState>) => {
|
|
1095
|
+
const prev = uiRef.current.sorting;
|
|
1096
|
+
const next = typeof updaterOrValue === "function" ? updaterOrValue(prev) : updaterOrValue;
|
|
1097
|
+
const cleaned = (next || []).filter((s: any) => s?.id);
|
|
1098
|
+
onSortingChangeRef.current?.(cleaned);
|
|
1099
|
+
nextFetchDelayRef.current = 0;
|
|
1100
|
+
dispatch({ type: "SET_SORTING_RESET_PAGE", payload: cleaned });
|
|
1101
|
+
},
|
|
1102
|
+
[onSortingChangeRef, uiRef]
|
|
1103
|
+
);
|
|
1104
|
+
|
|
1105
|
+
const handlePaginationChange = useCallback(
|
|
1106
|
+
(updater: Updater<PaginationState>) => {
|
|
1107
|
+
const prev = uiRef.current.pagination;
|
|
1108
|
+
const next = typeof updater === "function" ? updater(prev) : updater;
|
|
1109
|
+
onPaginationChangeRef.current?.(next);
|
|
1110
|
+
nextFetchDelayRef.current = 0;
|
|
1111
|
+
dispatch({ type: "SET_PAGINATION", payload: next });
|
|
1112
|
+
},
|
|
1113
|
+
[onPaginationChangeRef, uiRef]
|
|
1114
|
+
);
|
|
1115
|
+
|
|
1116
|
+
const handleGlobalFilterChange = useCallback(
|
|
1117
|
+
(updaterOrValue: Updater<string>) => {
|
|
1118
|
+
const prev = uiRef.current.globalFilter;
|
|
1119
|
+
const next = typeof updaterOrValue === "function" ? updaterOrValue(prev) : updaterOrValue;
|
|
1120
|
+
onGlobalFilterChangeRef.current?.(next);
|
|
1121
|
+
nextFetchDelayRef.current = 400;
|
|
1122
|
+
dispatch({ type: "SET_GLOBAL_FILTER_RESET_PAGE", payload: next });
|
|
1123
|
+
},
|
|
1124
|
+
[onGlobalFilterChangeRef, uiRef]
|
|
1125
|
+
);
|
|
1126
|
+
|
|
1127
|
+
const handleColumnOrderChange = useCallback(
|
|
1128
|
+
(updated: Updater<ColumnOrderState>) => {
|
|
1129
|
+
const prev = uiRef.current.columnOrder;
|
|
1130
|
+
const next = typeof updated === "function" ? updated(prev) : updated;
|
|
1131
|
+
dispatch({ type: "SET_COLUMN_ORDER", payload: next });
|
|
1132
|
+
onColumnDragEndRef.current?.(next);
|
|
1133
|
+
},
|
|
1134
|
+
[onColumnDragEndRef, uiRef]
|
|
1135
|
+
);
|
|
1136
|
+
|
|
1137
|
+
const handleColumnPinningChange = useCallback(
|
|
1138
|
+
(updated: Updater<ColumnPinningState>) => {
|
|
1139
|
+
const prev = uiRef.current.columnPinning;
|
|
1140
|
+
const next = typeof updated === "function" ? updated(prev) : updated;
|
|
1141
|
+
dispatch({ type: "SET_COLUMN_PINNING", payload: next });
|
|
1142
|
+
onColumnPinningChangeRef.current?.(next);
|
|
1143
|
+
},
|
|
1144
|
+
[onColumnPinningChangeRef, uiRef]
|
|
1145
|
+
);
|
|
1146
|
+
|
|
1147
|
+
const handleColumnVisibilityChange = useCallback(
|
|
1148
|
+
(updated: any) => {
|
|
1149
|
+
const prev = uiRef.current.columnVisibility;
|
|
1150
|
+
const next = typeof updated === "function" ? updated(prev) : updated;
|
|
1151
|
+
dispatch({ type: "SET_COLUMN_VISIBILITY", payload: next });
|
|
1152
|
+
onColumnVisibilityChangeRef.current?.(next);
|
|
1153
|
+
},
|
|
1154
|
+
[onColumnVisibilityChangeRef, uiRef]
|
|
1155
|
+
);
|
|
1156
|
+
|
|
1157
|
+
const handleColumnSizingChange = useCallback(
|
|
1158
|
+
(updated: any) => {
|
|
1159
|
+
const prev = uiRef.current.columnSizing;
|
|
1160
|
+
const next = typeof updated === "function" ? updated(prev) : updated;
|
|
1161
|
+
dispatch({ type: "SET_COLUMN_SIZING", payload: next });
|
|
1162
|
+
onColumnSizingChangeRef.current?.(next);
|
|
1163
|
+
},
|
|
1164
|
+
[onColumnSizingChangeRef, uiRef]
|
|
1165
|
+
);
|
|
1166
|
+
|
|
1167
|
+
const handleColumnReorder = useCallback(
|
|
1168
|
+
(draggedId: string, targetId: string) => {
|
|
1169
|
+
const currentOrder =
|
|
1170
|
+
uiRef.current.columnOrder.length > 0
|
|
1171
|
+
? uiRef.current.columnOrder
|
|
1172
|
+
: enhancedColumns.map((c: any, idx: number) => c.id ?? c.accessorKey ?? `column_${idx}`);
|
|
1173
|
+
|
|
1174
|
+
const from = currentOrder.indexOf(draggedId);
|
|
1175
|
+
const to = currentOrder.indexOf(targetId);
|
|
1176
|
+
if (from === -1 || to === -1) return;
|
|
1177
|
+
|
|
1178
|
+
const next = [...currentOrder];
|
|
1179
|
+
next.splice(from, 1);
|
|
1180
|
+
next.splice(to, 0, draggedId);
|
|
1181
|
+
|
|
1182
|
+
handleColumnOrderChange(next);
|
|
1183
|
+
},
|
|
1184
|
+
[enhancedColumns, handleColumnOrderChange, uiRef]
|
|
1185
|
+
);
|
|
1186
|
+
|
|
1187
|
+
// optional: selection callback
|
|
1188
|
+
useEffect(() => {
|
|
1189
|
+
onSelectionChangeRef.current?.(ui.selectionState);
|
|
1190
|
+
}, [onSelectionChangeRef, ui.selectionState]);
|
|
1191
|
+
|
|
1192
|
+
|
|
1193
|
+
|
|
1194
|
+
// --- provider props
|
|
1195
|
+
const providerProps = useMemo(
|
|
1196
|
+
() => ({
|
|
1197
|
+
table,
|
|
1198
|
+
apiRef,
|
|
1199
|
+
dataMode,
|
|
1200
|
+
tableSize: ui.tableSize,
|
|
1201
|
+
onTableSizeChange: (size: DataTableSize) => dispatch({ type: "SET_TABLE_SIZE", payload: size }),
|
|
1202
|
+
columnFilter: ui.columnFilter,
|
|
1203
|
+
onChangeColumnFilter: (f: ColumnFilterState) => handleColumnFilterChangeHandler(f, false),
|
|
1204
|
+
slots,
|
|
1205
|
+
slotProps,
|
|
1206
|
+
isExporting,
|
|
1207
|
+
exportController,
|
|
1208
|
+
exportPhase,
|
|
1209
|
+
exportProgress,
|
|
1210
|
+
onCancelExport: handleCancelExport,
|
|
1211
|
+
exportFilename,
|
|
1212
|
+
onExportProgress,
|
|
1213
|
+
onExportComplete,
|
|
1214
|
+
onExportError,
|
|
1215
|
+
onServerExport,
|
|
1216
|
+
}),
|
|
1217
|
+
[
|
|
1218
|
+
table,
|
|
1219
|
+
dataMode,
|
|
1220
|
+
ui.tableSize,
|
|
1221
|
+
ui.columnFilter,
|
|
1222
|
+
slots,
|
|
1223
|
+
slotProps,
|
|
1224
|
+
isExporting,
|
|
1225
|
+
exportController,
|
|
1226
|
+
exportPhase,
|
|
1227
|
+
exportProgress,
|
|
1228
|
+
handleCancelExport,
|
|
1229
|
+
exportFilename,
|
|
1230
|
+
onExportProgress,
|
|
1231
|
+
onExportComplete,
|
|
1232
|
+
onExportError,
|
|
1233
|
+
onServerExport,
|
|
1234
|
+
handleColumnFilterChangeHandler,
|
|
1235
|
+
]
|
|
1236
|
+
);
|
|
1237
|
+
|
|
1238
|
+
|
|
1239
|
+
return {
|
|
1240
|
+
table,
|
|
1241
|
+
refs: {
|
|
1242
|
+
tableContainerRef,
|
|
1243
|
+
apiRef,
|
|
1244
|
+
exportControllerRef,
|
|
1245
|
+
},
|
|
1246
|
+
derived: {
|
|
1247
|
+
isServerMode,
|
|
1248
|
+
isServerPagination,
|
|
1249
|
+
isServerFiltering,
|
|
1250
|
+
isServerSorting,
|
|
1251
|
+
tableData,
|
|
1252
|
+
tableTotalRow,
|
|
1253
|
+
tableLoading,
|
|
1254
|
+
rows,
|
|
1255
|
+
visibleLeafColumns: table.getVisibleLeafColumns,
|
|
1256
|
+
useFixedLayout,
|
|
1257
|
+
tableStyle,
|
|
1258
|
+
isExporting,
|
|
1259
|
+
exportPhase,
|
|
1260
|
+
exportProgress,
|
|
1261
|
+
isSomeRowsSelected,
|
|
1262
|
+
selectedRowCount,
|
|
1263
|
+
},
|
|
1264
|
+
state: ui,
|
|
1265
|
+
actions: {
|
|
1266
|
+
fetchData,
|
|
1267
|
+
handleSortingChange,
|
|
1268
|
+
handlePaginationChange,
|
|
1269
|
+
handleGlobalFilterChange,
|
|
1270
|
+
handleColumnFilterChangeHandler,
|
|
1271
|
+
handleColumnOrderChange,
|
|
1272
|
+
handleColumnPinningChange,
|
|
1273
|
+
handleColumnVisibilityChange,
|
|
1274
|
+
handleColumnSizingChange,
|
|
1275
|
+
handleColumnReorder,
|
|
1276
|
+
resetAllAndReload,
|
|
1277
|
+
triggerRefresh,
|
|
1278
|
+
setTableSize: (size: DataTableSize) => dispatch({ type: "SET_TABLE_SIZE", payload: size }),
|
|
1279
|
+
handleCancelExport,
|
|
1280
|
+
renderRowModel: { rowVirtualizer },
|
|
1281
|
+
},
|
|
1282
|
+
api: apiRef.current!,
|
|
1283
|
+
providerProps,
|
|
1284
|
+
};
|
|
1285
|
+
}
|