-
Notifications
You must be signed in to change notification settings - Fork 540
Expand file tree
/
Copy pathEntityTable.tsx
More file actions
564 lines (525 loc) · 19.9 KB
/
EntityTable.tsx
File metadata and controls
564 lines (525 loc) · 19.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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
/**
* EntityTable - Generic Entity Table Component
*
* A reusable table component for displaying entity lists with optional selection,
* column grouping, and pagination. Uses an `EntityDataController` for data access
* and `InfiniteVirtualTableFeatureShell` for rendering.
*
* Entity-specific table components (like `TestcaseTable`) should be thin wrappers
* over this component, providing the appropriate data controller and configuration.
*
* @example
* ```typescript
* import { EntityTable } from '@agenta/entity-ui'
* import { testcaseDataController, type TestcaseDataConfig } from '@agenta/entities/testcase'
*
* // View-only mode
* <EntityTable
* controller={testcaseDataController}
* config={config}
* getRowData={(record) => record as Record<string, unknown>}
* />
*
* // With selection
* <EntityTable
* controller={testcaseDataController}
* config={config}
* getRowData={(record) => record as Record<string, unknown>}
* selectable
* onSelectionChange={(ids) => console.log('Selected:', ids)}
* />
* ```
*
* @module EntityTable
*/
import {useCallback, useEffect, useMemo, useState, type ReactNode} from "react"
import type {
EntityColumnDef,
EntityDataConfigBase,
EntityDataController,
EntityRowBase,
} from "@agenta/entities/shared"
import {SmartCellContent} from "@agenta/ui/cell-renderers"
import {
CollapsibleGroupHeader,
TableEmptyState,
TableLoadingState,
} from "@agenta/ui/components/presentational"
import {useSelectionState} from "@agenta/ui/hooks"
import {bgColors, cn} from "@agenta/ui/styles"
import {
buildEntityColumns,
InfiniteVirtualTableFeatureShell,
shouldIgnoreRowClick,
type BuildEntityColumnsOptions,
type RowHeightFeatureConfig,
type TableScopeConfig,
type TypeChipConfig,
} from "@agenta/ui/table"
import type {GroupColumnsOptions} from "@agenta/ui/utils"
import {Checkbox, Radio} from "antd"
import type {ColumnType, ColumnsType} from "antd/es/table"
import {useAtomValue, useSetAtom} from "jotai"
import {getDefaultStore} from "jotai/vanilla"
// ============================================================================
// TYPES
// ============================================================================
/**
* Props for the generic EntityTable component.
*
* @template TRow - Row data type (must have id and key)
* @template TConfig - Data controller config type (must have scopeId)
* @template TColumn - Column definition type
*/
export interface EntityTableProps<
TRow extends EntityRowBase,
TConfig extends EntityDataConfigBase,
TColumn extends EntityColumnDef = EntityColumnDef,
> {
/** Data controller for this entity type */
controller: EntityDataController<TRow, TConfig, TColumn>
/** Controller configuration (must be memoized by the consumer) */
config: TConfig
// Data resolution
/**
* Function to resolve full row data from a row record.
*
* Entity tables may store row data in molecules or other sources.
* This function maps a table row record to the data used for cell rendering.
*
* @default (record) => record as Record<string, unknown>
*/
getRowData?: (record: TRow) => Record<string, unknown> | null
/**
* Optional function to get a cell value directly.
*
* When provided, this function is called instead of using `getRowData` + path extraction.
* This allows for fine-grained cell-level data access (e.g., from reactive atoms).
*
* @param record - The table row record
* @param columnKey - The column key/path
* @returns The cell value
*/
getCellValue?: (record: TRow, columnKey: string) => unknown
// Selection
/** Enable row selection (default: false) */
selectable?: boolean
/** Externally controlled selection state */
selectedIds?: string[]
/** Callback when selection changes (only used when selectable=true) */
onSelectionChange?: (ids: string[]) => void
/** Whether to allow multiple selection (default: true) */
multiSelect?: boolean
/** Whether selection is disabled (grayed out but visible) */
selectionDisabled?: boolean
// Column customization
/**
* Enable collapsible column grouping.
*
* When true, uses the default grouping behavior with `CollapsibleGroupHeader`.
* When a `GroupColumnsOptions` object, uses the provided custom grouping config.
*
* @default false
*/
grouping?: boolean | GroupColumnsOptions<TRow, TColumn>
/** Extra columns prepended to the column list */
prependColumns?: ColumnsType<TRow>
/** Extra columns appended to the column list */
appendColumns?: ColumnsType<TRow>
/** Optional cell renderer override for entity-specific display rules. */
renderCell?: (
value: unknown,
rowData: Record<string, unknown> | null,
column: TColumn,
) => ReactNode
// Table features
/** Row height config */
rowHeightConfig?: RowHeightFeatureConfig
/** Show settings dropdown (default: true) */
showSettings?: boolean
/** Enable table export action (default: true) */
enableExport?: boolean
/**
* Type chip config. When omitted, a default config is built from
* `getCellValue`/`getRowData` so chip rendering doesn't depend on each
* caller wiring it up. Pass `null` to disable chips entirely.
*/
typeChips?: TypeChipConfig<TRow> | null
/** Jotai store for entity atom access (default: global store) */
store?: ReturnType<typeof getDefaultStore>
/** Page size for table scope (default: 100) */
pageSize?: number
/** Empty state message */
emptyMessage?: string
/** Number of skeleton rows in loading state */
loadingRows?: number
/** Enable auto height mode (default: true) */
autoHeight?: boolean
}
// ============================================================================
// CONSTANTS
// ============================================================================
/** Width for selection checkbox column */
const SELECTION_COLUMN_WIDTH = 48
/** Width for collapsed group column */
const COLLAPSED_GROUP_WIDTH = 200
/** Label suffix for collapsed groups */
const COLLAPSED_LABEL = "collapsed"
/** Default row height configuration */
const DEFAULT_ROW_HEIGHT_CONFIG: RowHeightFeatureConfig = {
storageKey: "agenta:entity-table:row-height",
defaultSize: "medium",
}
// ============================================================================
// DEFAULT ROW DATA RESOLVER
// ============================================================================
const defaultGetRowData = <TRow,>(record: TRow): Record<string, unknown> | null =>
record as Record<string, unknown>
// ============================================================================
// MAIN COMPONENT
// ============================================================================
/**
* Generic entity table with selection, grouping, and pagination support.
*
* Uses `EntityDataController` for unified data access and
* `InfiniteVirtualTableFeatureShell` for rendering.
*
* @template TRow - Row data type
* @template TConfig - Config type
* @template TColumn - Column type
*/
export function EntityTable<
TRow extends EntityRowBase,
TConfig extends EntityDataConfigBase,
TColumn extends EntityColumnDef = EntityColumnDef,
>({
controller,
config,
getRowData = defaultGetRowData,
getCellValue,
selectable = false,
selectedIds: externalSelectedIds,
onSelectionChange,
multiSelect = true,
selectionDisabled = false,
grouping = false,
prependColumns,
appendColumns,
renderCell,
rowHeightConfig = DEFAULT_ROW_HEIGHT_CONFIG,
showSettings = true,
enableExport = true,
typeChips,
store,
pageSize,
emptyMessage = "No data found",
loadingRows = 8,
autoHeight = true,
}: EntityTableProps<TRow, TConfig, TColumn>) {
// Determine if selection is externally controlled
const isExternallyControlled = externalSelectedIds !== undefined
// Collapsed groups state (only used when grouping is enabled)
const [collapsedGroups, setCollapsedGroups] = useState<Set<string>>(new Set())
const toggleGroupCollapse = useCallback((groupPath: string) => {
setCollapsedGroups((prev) => {
const next = new Set(prev)
if (next.has(groupPath)) {
next.delete(groupPath)
} else {
next.add(groupPath)
}
return next
})
}, [])
// Get the global Jotai store for entity atoms
const globalStore = useMemo(() => store ?? getDefaultStore(), [store])
// Use data controller selectors for data
const rows = useAtomValue(controller.selectors.rows(config))
const isLoading = useAtomValue(controller.selectors.isLoading(config))
const columns = useAtomValue(controller.selectors.columns(config))
const allRowIds = useAtomValue(controller.selectors.allRowIds(config))
// Selection state - either external or from controller
const internalSelectedIdsSet = useAtomValue(controller.selectors.selectedIds(config.scopeId))
// Compute selection state using shared hook
const {
selectedSet: selectedIdsSet,
isAllSelected,
isSomeSelected,
} = useSelectionState(
allRowIds,
isExternallyControlled ? externalSelectedIds : internalSelectedIdsSet,
)
const selectedIds = useMemo(() => [...selectedIdsSet], [selectedIdsSet])
// Internal controller actions
const setInternalSelection = useSetAtom(controller.actions.setSelection)
const toggleInternalSelection = useSetAtom(controller.actions.toggleSelection)
const selectAllInternal = useSetAtom(controller.actions.selectAll)
const clearInternalSelection = useSetAtom(controller.actions.clearSelection)
const resetSelection = useSetAtom(controller.actions.resetSelection)
// Cleanup selection state on unmount to prevent memory leaks
useEffect(() => {
return () => {
resetSelection(config.scopeId)
}
}, [config.scopeId, resetSelection])
// Table scope configuration
const resolvedPageSize =
pageSize ?? ((config as Record<string, unknown>).pageSize as number) ?? 100
const tableScope = useMemo<TableScopeConfig>(
() => ({
scopeId: config.scopeId,
pageSize: resolvedPageSize,
enableInfiniteScroll: false,
}),
[config.scopeId, resolvedPageSize],
)
// Build pagination object for IVT (no-op for now — paginated mode TBD)
const pagination = useMemo(
() => ({
rows,
loadNextPage: () => {},
resetPages: () => {},
}),
[rows],
)
// Handle row selection toggle
const handleRowSelect = useCallback(
(rowId: string, checked: boolean) => {
const newSelection = multiSelect
? checked
? [...selectedIds, rowId]
: selectedIds.filter((id) => id !== rowId)
: checked
? [rowId]
: []
if (isExternallyControlled) {
onSelectionChange?.(newSelection)
} else {
if (multiSelect) {
toggleInternalSelection(config.scopeId, rowId, true)
} else {
if (checked) {
setInternalSelection(config.scopeId, [rowId])
} else {
clearInternalSelection(config.scopeId)
}
}
onSelectionChange?.(newSelection)
}
},
[
config.scopeId,
multiSelect,
isExternallyControlled,
toggleInternalSelection,
setInternalSelection,
clearInternalSelection,
onSelectionChange,
selectedIds,
],
)
// Handle select all toggle
const handleSelectAll = useCallback(
(checked: boolean) => {
if (isExternallyControlled) {
onSelectionChange?.(checked ? allRowIds : [])
} else {
if (checked) {
selectAllInternal(config.scopeId, allRowIds)
} else {
clearInternalSelection(config.scopeId)
}
onSelectionChange?.(checked ? allRowIds : [])
}
},
[
config.scopeId,
allRowIds,
isExternallyControlled,
selectAllInternal,
clearInternalSelection,
onSelectionChange,
],
)
// Build grouping options
const groupingOptions = useMemo((): GroupColumnsOptions<TRow, TColumn> | undefined => {
if (!grouping) return undefined
if (typeof grouping === "object") return grouping
// Default grouping behavior
return {
collapsedGroups,
onGroupHeaderClick: toggleGroupCollapse,
maxDepth: 1,
renderGroupHeader: (groupPath, isCollapsed, childCount) => (
<CollapsibleGroupHeader
label={groupPath}
isCollapsed={isCollapsed}
count={childCount}
onClick={() => toggleGroupCollapse(groupPath)}
/>
),
createCollapsedColumnDef: (groupPath) => ({
key: `__collapsed_${groupPath}`,
title: (
<CollapsibleGroupHeader
label={groupPath}
isCollapsed={true}
count={COLLAPSED_LABEL}
onClick={() => toggleGroupCollapse(groupPath)}
/>
),
width: COLLAPSED_GROUP_WIDTH,
render: (_, record) => {
const dataSource = getRowData(record)
if (!dataSource) return null
const value = (dataSource as Record<string, unknown>)[groupPath]
return <SmartCellContent value={value} />
},
}),
} as GroupColumnsOptions<TRow, TColumn>
}, [grouping, collapsedGroups, toggleGroupCollapse, getRowData])
// Build table columns
const tableColumns: ColumnsType<TRow> = useMemo(() => {
// Selection column. Header is `Checkbox` (select-all) ONLY when the
// table is multi-select — single-select has no select-all concept.
// Row control mirrors that: `Checkbox` for multi-select, `Radio` for
// single-select. Without the radio, single-select callers (e.g. the
// chat playground testset picker) render visually identical
// checkboxes whose behaviour silently replaces the previous
// selection on every click — the "we do something else behind the
// curtains" UX wart Arda flagged on 2026-06-01.
const selectionColumn: ColumnType<TRow> = {
key: "__selection",
title: multiSelect ? (
<Checkbox
checked={isAllSelected}
indeterminate={isSomeSelected}
onChange={(e) => handleSelectAll(e.target.checked)}
disabled={selectionDisabled}
/>
) : null,
width: SELECTION_COLUMN_WIDTH,
fixed: "left",
render: (_, record) => {
const checked = selectedIdsSet.has(record.id)
if (multiSelect) {
return (
<Checkbox
checked={checked}
onChange={(e) => handleRowSelect(record.id, e.target.checked)}
disabled={selectionDisabled}
onClick={(e) => e.stopPropagation()}
/>
)
}
// Single-select: render a Radio. Clicking an unchecked radio
// selects (and replaces the previous selection via the
// `multiSelect ? … : [rowId]` branch in `handleRowSelect`).
// Clicking a checked radio is a no-op in antd by default —
// we don't try to "uncheck" because single-select tables
// are semantically "pick one"; the user can pick a
// different row instead.
return (
<Radio
checked={checked}
onChange={() => {
if (!checked) handleRowSelect(record.id, true)
}}
disabled={selectionDisabled}
onClick={(e) => e.stopPropagation()}
/>
)
},
}
// Build entity columns using the helper
const entityColumns = buildEntityColumns<TRow, TColumn>(columns, {
getRowData,
getCellValue,
grouping: groupingOptions,
renderCell,
} as BuildEntityColumnsOptions<TRow, TColumn>)
// Assemble final columns
const result: ColumnsType<TRow> = []
if (selectable) result.push(selectionColumn)
if (prependColumns) result.push(...prependColumns)
result.push(...entityColumns)
if (appendColumns) result.push(...appendColumns)
return result
}, [
columns,
selectable,
multiSelect,
isAllSelected,
isSomeSelected,
selectedIdsSet,
selectionDisabled,
groupingOptions,
handleSelectAll,
handleRowSelect,
getRowData,
getCellValue,
renderCell,
prependColumns,
appendColumns,
])
// Loading state
if (isLoading && rows.length === 0) {
return <TableLoadingState rows={loadingRows} />
}
// Empty state
if (!isLoading && rows.length === 0) {
return <TableEmptyState message={emptyMessage} />
}
// Default type chip wiring. Reuses existing data accessors so chips appear
// for every consumer (eg. testset preview modal in edit mode) without each
// caller having to opt in. Pass `typeChips={null}` to disable.
const defaultGetRowValue = useCallback(
(record: TRow, columnKey: string): unknown => {
if (getCellValue) return getCellValue(record, columnKey)
const data = getRowData(record)
return data ? data[columnKey] : undefined
},
[getCellValue, getRowData],
)
const effectiveTypeChips = useMemo<TypeChipConfig<TRow> | undefined>(() => {
if (typeChips === null) return undefined
if (typeChips) return typeChips
return {
defaultEnabled: true,
storageKey: "agenta:entity-table:type-chips-enabled",
getRowValue: defaultGetRowValue,
}
}, [typeChips, defaultGetRowValue])
return (
<div className="h-full">
<InfiniteVirtualTableFeatureShell<TRow>
columns={tableColumns}
pagination={pagination}
rowHeightConfig={rowHeightConfig}
tableScope={tableScope}
rowKey="id"
autoHeight={autoHeight}
useSettingsDropdown={showSettings}
enableExport={enableExport}
typeChips={effectiveTypeChips}
store={globalStore}
tableProps={{
size: "small",
bordered: true,
onRow: selectable
? (record) => ({
onClick: (event) => {
if (shouldIgnoreRowClick(event)) return
handleRowSelect(record.id, !selectedIdsSet.has(record.id))
},
className: cn(
"cursor-pointer",
selectedIdsSet.has(record.id) && bgColors.subtle,
),
})
: undefined,
}}
/>
</div>
)
}