-
Notifications
You must be signed in to change notification settings - Fork 540
Expand file tree
/
Copy pathuseTableManager.tsx
More file actions
519 lines (451 loc) · 15.9 KB
/
useTableManager.tsx
File metadata and controls
519 lines (451 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
import type {Key, MouseEvent, ReactNode, RefObject} from "react"
import {useCallback, useEffect, useMemo, useRef, useState} from "react"
import {Grid, Input} from "antd"
import type {ColumnsType} from "antd/es/table"
import clsx from "clsx"
import {atom, useAtom} from "jotai"
import type {WritableAtom} from "jotai"
import type {InfiniteDatasetStore} from "../createInfiniteDatasetStore"
import type {
TableScopeConfig,
TableFeaturePagination,
InfiniteVirtualTableFeatureProps,
TableDeleteConfig,
TableExportConfig,
} from "../features/InfiniteVirtualTableFeatureShell"
import type {
InfiniteTableRowBase,
InfiniteVirtualTableProps,
InfiniteVirtualTableRowSelection,
} from "../types"
import useTableExport from "./useTableExport"
/** Stable no-op atom used when no external search atom is provided (hooks can't be conditional) */
const dummySearchAtom = atom("")
/**
* Default CSS selectors for interactive elements that should not trigger row navigation.
* Consolidated from all table implementations to ensure consistent click-through behavior.
*/
export const INTERACTIVE_ROW_SELECTORS = [
"button",
"a",
"input",
"textarea",
"select",
"[role='button']",
"[role='menuitem']",
"[role='checkbox']",
"[data-interactive]",
".ant-dropdown-trigger",
".ant-checkbox-wrapper",
".ant-checkbox",
".ant-checkbox-input",
".ant-checkbox-inner",
".ant-btn",
".ant-select",
].join(", ")
/**
* Helper to detect if a click event should be ignored for row navigation.
* Returns true if the click was on an interactive element (button, link, dropdown, etc.)
*/
export const shouldIgnoreRowClick = (event: MouseEvent<HTMLElement>): boolean => {
const target = event.target as HTMLElement
if (!target) return false
return Boolean(target.closest(INTERACTIVE_ROW_SELECTORS))
}
/** Configuration for built-in search. When provided, the hook manages search state internally. */
export interface TableSearchConfig {
/** Placeholder text (default: "Search") */
placeholder?: string
/** Custom className for the search input (default: "max-w-[320px]") */
className?: string
/** Whether search is disabled */
disabled?: boolean
/** External Jotai atom to sync search term with (for cross-component access) */
atom?: WritableAtom<string, [string], void>
}
export interface UseTableManagerConfig<T extends InfiniteTableRowBase> {
/** The dataset store for this table */
datasetStore: InfiniteDatasetStore<T, any, any>
/** Unique scope ID for this table instance */
scopeId: string
/** Number of items per page (default: 50) */
pageSize?: number
/** Row height in pixels (default: 48) */
rowHeight?: number
/** Callback when a row is clicked */
onRowClick?: (record: T) => void
/**
* Built-in search configuration. When provided, the hook manages search state
* and renders a search input in the filters slot of shellProps.
* Pass `true` for defaults, or an object for customization.
*/
search?: TableSearchConfig | boolean
/** Dependencies that should trigger pagination reset (e.g., search term) */
searchDeps?: any[]
/** Whether rows should be clickable (default: true) */
clickableRows?: boolean
/** Custom className for rows */
rowClassName?: string | ((record: T) => string)
/** Storage key for column visibility persistence */
columnVisibilityStorageKey?: string | null
/** Enable infinite scroll (default: true) */
enableInfiniteScroll?: boolean
/** Callback when bulk delete is triggered */
onBulkDelete?: (records: T[]) => void
/** Label for delete button (default: "Delete") */
deleteLabel?: string
/** Tooltip when delete is disabled (default: "Select items to delete") */
deleteDisabledTooltip?: string
/** Label for export button (default: "Export CSV") */
exportLabel?: string
/** Tooltip when export is disabled (default: "Select items to export") */
exportDisabledTooltip?: string
/** Filename for CSV export (default: "table-export.csv") */
exportFilename?: string
}
export interface UseTableManagerReturn<T extends InfiniteTableRowBase> {
/** Pagination state and controls */
pagination: ReturnType<InfiniteDatasetStore<T, any, any>["hooks"]["usePagination"]>
/** Current rows from pagination */
rows: T[]
/** Selected row keys */
selectedRowKeys: Key[]
/** Update selected row keys */
setSelectedRowKeys: (keys: Key[] | ((prev: Key[]) => Key[])) => void
/** Row selection configuration for the table */
rowSelection: InfiniteVirtualTableRowSelection<T>
/** Table props configuration */
tableProps: InfiniteVirtualTableProps<T>["tableProps"]
/** Table scope configuration */
tableScope: TableScopeConfig
/** Pagination configuration for FeatureShell */
tablePagination: TableFeaturePagination<T>
/** Get currently selected records */
getSelectedRecords: () => T[]
/** Clear selection */
clearSelection: () => void
/** Whether running on narrow screen (< lg breakpoint) */
isNarrowScreen: boolean
/** Delete action config for the shell */
deleteAction: TableDeleteConfig | undefined
/** Export action config for the shell */
exportAction: TableExportConfig | undefined
/** Handler to export a single row */
handleExportRow: (record: T) => Promise<void>
/** Whether a row is currently being exported */
rowExportingKey: string | null
/** Ref to store current columns for export */
columnsRef: RefObject<ColumnsType<T> | null>
/** Search term value (only meaningful when search config is provided) */
searchTerm: string
/** Search term setter (only meaningful when search config is provided) */
setSearchTerm: (value: string) => void
/** Spread these props directly to InfiniteVirtualTableFeatureShell */
shellProps: Pick<
InfiniteVirtualTableFeatureProps<T>,
| "datasetStore"
| "tableScope"
| "pagination"
| "rowSelection"
| "tableProps"
| "deleteAction"
| "exportAction"
| "useSettingsDropdown"
| "rowKey"
| "filters"
>
}
/**
* Hook to manage common table setup and reduce boilerplate.
*
* Consolidates:
* - Pagination setup and auto-reset
* - Row selection state and config
* - Row click handlers with smart ignore logic
* - Table props with sensible defaults
* - Scope and pagination configs
*
* @example
* ```tsx
* const table = useTableManager({
* datasetStore: testsetsDatasetStore,
* scopeId: "testsets-page",
* pageSize: 50,
* onRowClick: (record) => router.push(`/testsets/${record._id}`),
* searchDeps: [searchTerm],
* })
*
* return (
* <InfiniteVirtualTableFeatureShell
* tableScope={table.tableScope}
* pagination={table.tablePagination}
* rowSelection={table.rowSelection}
* tableProps={table.tableProps}
* // ... other props
* />
* )
* ```
*/
export function useTableManager<T extends InfiniteTableRowBase>({
datasetStore,
scopeId,
pageSize = 50,
rowHeight = 48,
onRowClick,
search,
searchDeps: externalSearchDeps = [],
clickableRows = true,
rowClassName,
columnVisibilityStorageKey,
enableInfiniteScroll = true,
onBulkDelete,
deleteLabel = "Delete",
deleteDisabledTooltip = "Select items to delete",
exportLabel = "Export CSV",
exportDisabledTooltip = "Select items to export",
exportFilename = "table-export.csv",
}: UseTableManagerConfig<T>): UseTableManagerReturn<T> {
// Responsive breakpoints
const screens = Grid.useBreakpoint()
const isNarrowScreen = !screens.lg
// Normalize search config
const searchConfig = search === true ? {} : search || undefined
const searchAtom = searchConfig?.atom
// Built-in search state (local or atom-backed)
const [localSearchTerm, setLocalSearchTerm] = useState("")
const [atomSearchTerm, setAtomSearchTerm] = useAtom(searchAtom || dummySearchAtom)
const searchTerm = searchConfig ? (searchAtom ? atomSearchTerm : localSearchTerm) : ""
const setSearchTerm = useCallback(
(value: string) => {
if (searchAtom) {
setAtomSearchTerm(value)
} else {
setLocalSearchTerm(value)
}
},
[searchAtom, setAtomSearchTerm],
)
// Merge built-in search deps with any external searchDeps
const searchDeps = searchConfig ? [searchTerm, ...externalSearchDeps] : externalSearchDeps
// Pagination
const pagination = datasetStore.hooks.usePagination({
scopeId,
pageSize,
resetOnScopeChange: false,
})
const {rows, loadNextPage, resetPages} = pagination
// Selection state
const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([])
// Export state
const [rowExportingKey, setRowExportingKey] = useState<string | null>(null)
const tableExport = useTableExport<T>()
const columnsRef = useRef<ColumnsType<T> | null>(null)
// Auto-reset pagination when search dependencies change (skip initial mount)
const searchDepsInitialized = useRef(false)
useEffect(() => {
if (!searchDepsInitialized.current) {
searchDepsInitialized.current = true
return
}
if (searchDeps.length > 0) {
resetPages()
}
}, [resetPages, ...searchDeps])
// Row selection config
const rowSelection = useMemo<InfiniteVirtualTableRowSelection<T>>(
() => ({
type: "checkbox" as const,
selectedRowKeys,
onChange: (keys: Key[]) => {
setSelectedRowKeys(keys)
},
getCheckboxProps: (record: T) => ({
disabled: Boolean(record.__isSkeleton),
}),
columnWidth: 48,
fixed: true,
}),
[selectedRowKeys],
)
// Row click handlers
const buildRowHandlers = useCallback(
(record: T) => {
const isNavigable = clickableRows && !record.__isSkeleton
const customClass =
typeof rowClassName === "function" ? rowClassName(record) : rowClassName
return {
onClick: (event: MouseEvent<HTMLTableRowElement>) => {
if (!isNavigable) return
if (shouldIgnoreRowClick(event)) return
onRowClick?.(record)
},
className: clsx(customClass, {
"opacity-60 animate-pulse": record.__isSkeleton,
}),
style: {
cursor: isNavigable ? "pointer" : "default",
height: rowHeight,
minHeight: rowHeight,
} as React.CSSProperties,
}
},
[clickableRows, onRowClick, rowClassName, rowHeight],
)
// Table props with defaults
const tableProps = useMemo(
() => ({
size: "small" as const,
sticky: true,
bordered: true,
virtual: true,
tableLayout: "fixed" as const,
onRow: buildRowHandlers,
}),
[buildRowHandlers],
)
// Table scope config
const tableScope = useMemo<TableScopeConfig>(
() => ({
scopeId,
pageSize,
enableInfiniteScroll,
columnVisibilityStorageKey: columnVisibilityStorageKey ?? undefined,
}),
[scopeId, pageSize, enableInfiniteScroll, columnVisibilityStorageKey],
)
// Pagination config for FeatureShell
const tablePagination = useMemo<TableFeaturePagination<T>>(
() => ({
rows,
loadNextPage,
resetPages,
}),
[rows, loadNextPage, resetPages],
)
// Helper to get selected records
const getSelectedRecords = useCallback(
() => rows.filter((record) => selectedRowKeys.includes(record.key)),
[rows, selectedRowKeys],
)
// Helper to clear selection
const clearSelection = useCallback(() => {
setSelectedRowKeys([])
}, [])
// Delete action config - shell handles button rendering and narrow screen behavior
const deleteAction = useMemo<TableDeleteConfig | undefined>(
() =>
onBulkDelete
? {
onDelete: () => onBulkDelete(getSelectedRecords()),
disabled: !selectedRowKeys.length,
disabledTooltip: deleteDisabledTooltip,
label: deleteLabel,
}
: undefined,
[
onBulkDelete,
selectedRowKeys.length,
getSelectedRecords,
deleteDisabledTooltip,
deleteLabel,
],
)
// Export action config - shell handles button rendering and narrow screen behavior
const exportAction = useMemo<TableExportConfig | undefined>(
() => ({
disabled: !selectedRowKeys.length,
disabledTooltip: exportDisabledTooltip,
label: exportLabel,
}),
[selectedRowKeys.length, exportDisabledTooltip, exportLabel],
)
// Handler to export a single row
const handleExportRow = useCallback(
async (record: T) => {
if (!record || record.__isSkeleton || !record.key) return
const snapshot = columnsRef.current
if (!snapshot?.length) {
console.warn("[useTableManager] Cannot export row without columns")
return
}
const sanitizedKey = String(record.key).replace(/[^a-zA-Z0-9-_]+/g, "-")
setRowExportingKey(String(record.key))
try {
await tableExport({
columns: snapshot,
rows: [record],
filename: exportFilename.replace(".csv", `-${sanitizedKey}.csv`),
})
} catch (error) {
console.error("[useTableManager] Failed to export row", error)
} finally {
setRowExportingKey((current) => (current === String(record.key) ? null : current))
}
},
[tableExport, exportFilename],
)
// Row key extractor
const rowKeyExtractor = useCallback((record: T) => record.key, [])
// Built-in search node
const searchNode = useMemo<ReactNode>(() => {
if (!searchConfig) return undefined
return (
<Input.Search
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
placeholder={searchConfig.placeholder ?? "Search"}
allowClear
disabled={searchConfig.disabled}
className={clsx("w-full", searchConfig.className ?? "max-w-[320px]")}
/>
)
}, [searchConfig, searchTerm, setSearchTerm])
// Shell props to spread directly to InfiniteVirtualTableFeatureShell
const shellProps = useMemo(
() => ({
datasetStore,
tableScope,
pagination: tablePagination,
rowSelection,
tableProps,
deleteAction,
exportAction,
useSettingsDropdown: isNarrowScreen,
rowKey: rowKeyExtractor,
filters: searchNode,
}),
[
datasetStore,
tableScope,
tablePagination,
rowSelection,
tableProps,
deleteAction,
exportAction,
isNarrowScreen,
rowKeyExtractor,
searchNode,
],
)
return {
pagination,
rows,
selectedRowKeys,
setSelectedRowKeys,
rowSelection,
tableProps,
tableScope,
tablePagination,
getSelectedRecords,
clearSelection,
isNarrowScreen,
deleteAction,
exportAction,
handleExportRow,
rowExportingKey,
columnsRef,
searchTerm,
setSearchTerm,
shellProps,
}
}