@xiaomingio/data-table 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +63 -2
  2. package/dist/components/CellEditorDialog.d.ts +20 -0
  3. package/dist/components/CellEditorDialog.d.ts.map +1 -0
  4. package/dist/components/CellEditorDialog.js +154 -0
  5. package/dist/components/CellEditorDialog.js.map +1 -0
  6. package/dist/components/ColumnFilterPopover.d.ts +17 -0
  7. package/dist/components/ColumnFilterPopover.d.ts.map +1 -0
  8. package/dist/components/ColumnFilterPopover.js +75 -0
  9. package/dist/components/ColumnFilterPopover.js.map +1 -0
  10. package/dist/components/ColumnManagerPopover.d.ts +15 -0
  11. package/dist/components/ColumnManagerPopover.d.ts.map +1 -0
  12. package/dist/components/ColumnManagerPopover.js +38 -0
  13. package/dist/components/ColumnManagerPopover.js.map +1 -0
  14. package/dist/components/DataTable.d.ts +8 -0
  15. package/dist/components/DataTable.d.ts.map +1 -0
  16. package/dist/components/DataTable.js +703 -0
  17. package/dist/components/DataTable.js.map +1 -0
  18. package/dist/components/DatabaseTableBrowser.d.ts +8 -0
  19. package/dist/components/DatabaseTableBrowser.d.ts.map +1 -0
  20. package/dist/components/DatabaseTableBrowser.js +241 -0
  21. package/dist/components/DatabaseTableBrowser.js.map +1 -0
  22. package/dist/components/Popover.d.ts +18 -0
  23. package/dist/components/Popover.d.ts.map +1 -0
  24. package/dist/components/Popover.js +104 -0
  25. package/dist/components/Popover.js.map +1 -0
  26. package/dist/core/index.d.ts +8 -0
  27. package/dist/core/index.d.ts.map +1 -0
  28. package/dist/core/index.js +8 -0
  29. package/dist/core/index.js.map +1 -0
  30. package/dist/core/types.d.ts +130 -0
  31. package/dist/core/types.d.ts.map +1 -0
  32. package/dist/core/types.js +7 -0
  33. package/dist/core/types.js.map +1 -0
  34. package/dist/core/values.d.ts +22 -0
  35. package/dist/core/values.d.ts.map +1 -0
  36. package/dist/core/values.js +381 -0
  37. package/dist/core/values.js.map +1 -0
  38. package/dist/index.d.ts +14 -0
  39. package/dist/index.d.ts.map +1 -0
  40. package/dist/index.js +14 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/styles/data-table.css +1194 -0
  43. package/dist/types.d.ts +146 -0
  44. package/dist/types.d.ts.map +1 -0
  45. package/dist/types.js +7 -0
  46. package/dist/types.js.map +1 -0
  47. package/dist/utils/measureWidth.d.ts +12 -0
  48. package/dist/utils/measureWidth.d.ts.map +1 -0
  49. package/dist/utils/measureWidth.js +72 -0
  50. package/dist/utils/measureWidth.js.map +1 -0
  51. package/package.json +51 -4
@@ -0,0 +1,703 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ /**
3
+ * 文件说明:
4
+ * 核心 React DataTable 组件,基于 TanStack Table v8 与 TanStack Virtual v3 构建。
5
+ * 支持客户端/服务端双模式查询、虚拟滚动、列宽拖拽与自适应、左侧固定列、行选择、简易编辑与扩展渲染钩子。
6
+ */
7
+ import { useCallback, useEffect, useMemo, useRef, useState, } from 'react';
8
+ import { flexRender, getCoreRowModel, useReactTable, } from '@tanstack/react-table';
9
+ import { useVirtualizer } from '@tanstack/react-virtual';
10
+ import { ArrowDown, ArrowUp, ArrowUpDown, Check, Columns3, Filter, Loader2, Minus, } from 'lucide-react';
11
+ import { applyClientFilters, applyClientSort, computeEnumOptionCounts, formatCellDisplayValue, inferColumnFilterType, inferColumnSortType, isColumnFilterActive, isMissingCellValue, readColumnRawValue, } from '../core/values.js';
12
+ import { computeInitialColumnWidth } from '../utils/measureWidth.js';
13
+ import { CellEditorDialog } from './CellEditorDialog.js';
14
+ import { ColumnFilterPopover } from './ColumnFilterPopover.js';
15
+ import { ColumnManagerPopover } from './ColumnManagerPopover.js';
16
+ import { Popover } from './Popover.js';
17
+ function resolveRowKey(row, index, rowKey) {
18
+ if (typeof rowKey === 'function')
19
+ return rowKey(row, index);
20
+ if (rowKey && row && typeof row === 'object') {
21
+ const val = row[rowKey];
22
+ if (val !== undefined && val !== null)
23
+ return String(val);
24
+ }
25
+ if (row && typeof row === 'object' && 'id' in row) {
26
+ const id = row.id;
27
+ if (id !== undefined && id !== null)
28
+ return String(id);
29
+ }
30
+ return String(index);
31
+ }
32
+ function normalizeVirtualConfig(virtual, density = 'comfortable') {
33
+ const defaultRowHeight = density === 'ultra' ? 26 : density === 'compact' ? 32 : 40;
34
+ if (virtual === false) {
35
+ return {
36
+ enabled: false,
37
+ rowHeight: defaultRowHeight,
38
+ overscan: 8,
39
+ dynamicHeight: false,
40
+ maxHeight: 560,
41
+ };
42
+ }
43
+ if (virtual === true || virtual === undefined) {
44
+ return {
45
+ enabled: true,
46
+ rowHeight: defaultRowHeight,
47
+ overscan: 8,
48
+ dynamicHeight: false,
49
+ maxHeight: 560,
50
+ };
51
+ }
52
+ return {
53
+ enabled: virtual.enabled ?? true,
54
+ rowHeight: virtual.rowHeight ?? defaultRowHeight,
55
+ overscan: virtual.overscan ?? 8,
56
+ dynamicHeight: virtual.dynamicHeight ?? false,
57
+ maxHeight: virtual.maxHeight ?? 560,
58
+ };
59
+ }
60
+ export function DataTable({ data, columns, rowKey, queryMode = 'client', sort: controlledSort, defaultSort = [], onSortChange, multiSort = false, filters: controlledFilters, defaultFilters = {}, onFiltersChange, serverEnumCounts, loading = false, emptyText = '暂无匹配数据', emptyNode, virtual, density = 'comfortable', headerWrap = false, columnManager = false, showSequenceColumn = false, sequenceLabel = '#', autoMeasureWidths = true, selection, editing, pagination, toolbar, footer, columnActions, headerExtras, renderRow, onFilteredRowsChange, onVisibleRowsChange, onRowClick, rowClassName, className = '', style, ariaLabel = '数据表格', }) {
61
+ const [internalSort, setInternalSort] = useState(defaultSort);
62
+ const [internalFilters, setInternalFilters] = useState(defaultFilters);
63
+ const [openFilterKey, setOpenFilterKey] = useState(null);
64
+ const [columnManagerOpen, setColumnManagerOpen] = useState(false);
65
+ const [hiddenColumnKeys, setHiddenColumnKeys] = useState(new Set());
66
+ const [locatedColumnKey, setLocatedColumnKey] = useState(null);
67
+ const [columnWidths, setColumnWidths] = useState({});
68
+ const [narrowContainer, setNarrowContainer] = useState(false);
69
+ const [editorTarget, setEditorTarget] = useState(null);
70
+ const [editingRow, setEditingRow] = useState(null);
71
+ const [editingCol, setEditingCol] = useState(null);
72
+ const filterAnchorRefs = useRef({});
73
+ const headerCellRefs = useRef({});
74
+ const columnManagerBtnRef = useRef(null);
75
+ const scrollContainerRef = useRef(null);
76
+ const activeSort = controlledSort ?? internalSort;
77
+ const activeFilters = controlledFilters ?? internalFilters;
78
+ const virtualConfig = useMemo(() => normalizeVirtualConfig(virtual, density), [virtual, density]);
79
+ const setSort = useCallback((next) => {
80
+ if (controlledSort === undefined)
81
+ setInternalSort(next);
82
+ onSortChange?.(next);
83
+ }, [controlledSort, onSortChange]);
84
+ const setFilters = useCallback((next) => {
85
+ if (controlledFilters === undefined)
86
+ setInternalFilters(next);
87
+ onFiltersChange?.(next);
88
+ }, [controlledFilters, onFiltersChange]);
89
+ // 推断每列的 sortType 和 filterType
90
+ const inferredTypes = useMemo(() => {
91
+ const sortTypes = {};
92
+ const filterTypes = {};
93
+ for (const col of columns) {
94
+ const sType = inferColumnSortType(data, col);
95
+ sortTypes[col.key] = sType;
96
+ filterTypes[col.key] = inferColumnFilterType(data, col, sType);
97
+ }
98
+ return { sortTypes, filterTypes };
99
+ }, [columns, data]);
100
+ // 测量并初始化/更新未手动调整过的列宽
101
+ const manualResizedKeysRef = useRef(new Set());
102
+ useEffect(() => {
103
+ setColumnWidths((prev) => {
104
+ let changed = false;
105
+ const next = { ...prev };
106
+ for (const col of columns) {
107
+ if (next[col.key] === undefined || !manualResizedKeysRef.current.has(col.key)) {
108
+ const measured = autoMeasureWidths
109
+ ? computeInitialColumnWidth(col, data, { density, headerWrap })
110
+ : (col.width ?? 140);
111
+ if (next[col.key] !== measured) {
112
+ next[col.key] = measured;
113
+ changed = true;
114
+ }
115
+ }
116
+ }
117
+ return changed ? next : prev;
118
+ });
119
+ }, [columns, data, autoMeasureWidths, density, headerWrap]);
120
+ // 客户端模式下过滤 + 排序;服务端模式直接使用输入 data
121
+ const filteredRows = useMemo(() => {
122
+ if (queryMode === 'server')
123
+ return data;
124
+ return applyClientFilters(data, columns, activeFilters, inferredTypes.sortTypes);
125
+ }, [queryMode, data, columns, activeFilters, inferredTypes.sortTypes]);
126
+ const processedRows = useMemo(() => {
127
+ if (queryMode === 'server')
128
+ return filteredRows;
129
+ return applyClientSort(filteredRows, columns, activeSort, inferredTypes.sortTypes);
130
+ }, [queryMode, filteredRows, columns, activeSort, inferredTypes.sortTypes]);
131
+ useEffect(() => {
132
+ onFilteredRowsChange?.(processedRows);
133
+ }, [processedRows, onFilteredRowsChange]);
134
+ // 行选择:规范化 Set,并在筛选变化时可选清理不可见行
135
+ const selectedKeySet = useMemo(() => {
136
+ if (!selection)
137
+ return new Set();
138
+ return selection.selectedKeys instanceof Set
139
+ ? selection.selectedKeys
140
+ : new Set(selection.selectedKeys);
141
+ }, [selection]);
142
+ const rowKeyList = useMemo(() => processedRows.map((row, index) => resolveRowKey(row, index, rowKey)), [processedRows, rowKey]);
143
+ useEffect(() => {
144
+ if (!selection || !selection.pruneHiddenSelection || selectedKeySet.size === 0)
145
+ return;
146
+ const visibleSet = new Set(rowKeyList);
147
+ const next = new Set();
148
+ let pruned = false;
149
+ for (const key of selectedKeySet) {
150
+ if (visibleSet.has(key)) {
151
+ next.add(key);
152
+ }
153
+ else {
154
+ pruned = true;
155
+ }
156
+ }
157
+ if (pruned) {
158
+ const nextRows = processedRows.filter((row, index) => next.has(resolveRowKey(row, index, rowKey)));
159
+ selection.onChange(next, nextRows);
160
+ }
161
+ }, [selection, selectedKeySet, rowKeyList, processedRows, rowKey]);
162
+ const visibleColumns = useMemo(() => hiddenColumnKeys.size === 0
163
+ ? columns
164
+ : columns.filter((col) => !hiddenColumnKeys.has(col.key)), [columns, hiddenColumnKeys]);
165
+ const handleLocateColumn = useCallback((key) => {
166
+ setLocatedColumnKey(key);
167
+ requestAnimationFrame(() => {
168
+ const container = scrollContainerRef.current;
169
+ const th = headerCellRefs.current[key];
170
+ if (container && th) {
171
+ const thRect = th.getBoundingClientRect();
172
+ const containerRect = container.getBoundingClientRect();
173
+ const targetScrollLeft = container.scrollLeft + (thRect.left - containerRect.left) - containerRect.width / 3;
174
+ container.scrollTo({
175
+ left: Math.max(0, targetScrollLeft),
176
+ behavior: 'smooth',
177
+ });
178
+ }
179
+ });
180
+ setTimeout(() => {
181
+ setLocatedColumnKey((prev) => (prev === key ? null : prev));
182
+ }, 1800);
183
+ }, []);
184
+ const handleToggleColumnVisibility = useCallback((key) => {
185
+ setHiddenColumnKeys((prev) => {
186
+ const next = new Set(prev);
187
+ if (next.has(key))
188
+ next.delete(key);
189
+ else
190
+ next.add(key);
191
+ return next;
192
+ });
193
+ }, []);
194
+ // 固定列偏移计算与窄屏降级保护
195
+ const fixedLeftColumns = useMemo(() => visibleColumns.filter((col) => col.fixed === 'left'), [visibleColumns]);
196
+ const selectionColWidth = selection ? (density === 'ultra' ? 32 : density === 'compact' ? 36 : 42) : 0;
197
+ const sequenceColWidth = showSequenceColumn ? (density === 'ultra' ? 40 : density === 'compact' ? 46 : 54) : 0;
198
+ const fixedBaseOffset = selectionColWidth + sequenceColWidth;
199
+ const totalFixedWidth = useMemo(() => {
200
+ return fixedLeftColumns.reduce((sum, col) => sum + (columnWidths[col.key] ?? col.width ?? 140), fixedBaseOffset);
201
+ }, [fixedLeftColumns, columnWidths, fixedBaseOffset]);
202
+ useEffect(() => {
203
+ const el = scrollContainerRef.current;
204
+ if (!el || typeof ResizeObserver === 'undefined')
205
+ return;
206
+ const check = () => {
207
+ if (fixedLeftColumns.length === 0) {
208
+ setNarrowContainer(false);
209
+ return;
210
+ }
211
+ setNarrowContainer(el.clientWidth > 0 && el.clientWidth < totalFixedWidth + 180);
212
+ };
213
+ check();
214
+ const observer = new ResizeObserver(check);
215
+ observer.observe(el);
216
+ return () => observer.disconnect();
217
+ }, [fixedLeftColumns.length, totalFixedWidth]);
218
+ const stickyOffsets = useMemo(() => {
219
+ const offsets = {};
220
+ if (narrowContainer)
221
+ return offsets;
222
+ let currentLeft = fixedBaseOffset;
223
+ for (const col of fixedLeftColumns) {
224
+ offsets[col.key] = currentLeft;
225
+ currentLeft += columnWidths[col.key] ?? col.width ?? 140;
226
+ }
227
+ return offsets;
228
+ }, [narrowContainer, fixedBaseOffset, fixedLeftColumns, columnWidths]);
229
+ const lastFixedLeftKey = !narrowContainer && fixedLeftColumns.length > 0
230
+ ? fixedLeftColumns[fixedLeftColumns.length - 1].key
231
+ : null;
232
+ // 列排序切换
233
+ const handleToggleSort = useCallback((columnKey, shiftKey = false) => {
234
+ const existingIndex = activeSort.findIndex((s) => s.key === columnKey);
235
+ const existing = existingIndex >= 0 ? activeSort[existingIndex] : null;
236
+ let nextRule = null;
237
+ if (!existing) {
238
+ nextRule = { key: columnKey, direction: 'asc' };
239
+ }
240
+ else if (existing.direction === 'asc') {
241
+ nextRule = { key: columnKey, direction: 'desc' };
242
+ }
243
+ else {
244
+ nextRule = null;
245
+ }
246
+ if (multiSort && shiftKey) {
247
+ const next = [...activeSort];
248
+ if (existingIndex >= 0) {
249
+ if (nextRule)
250
+ next[existingIndex] = nextRule;
251
+ else
252
+ next.splice(existingIndex, 1);
253
+ }
254
+ else if (nextRule) {
255
+ next.push(nextRule);
256
+ }
257
+ setSort(next);
258
+ }
259
+ else {
260
+ setSort(nextRule ? [nextRule] : []);
261
+ }
262
+ }, [activeSort, multiSort, setSort]);
263
+ // 列宽拖拽调整
264
+ const startResize = useCallback((column, startX) => {
265
+ const initialWidth = columnWidths[column.key] ?? column.width ?? 140;
266
+ const minW = column.minWidth ?? 64;
267
+ const maxW = column.maxWidth ?? 640;
268
+ const handleMove = (event) => {
269
+ const delta = event.clientX - startX;
270
+ const nextWidth = Math.max(minW, Math.min(maxW, Math.round(initialWidth + delta)));
271
+ manualResizedKeysRef.current.add(column.key);
272
+ setColumnWidths((prev) => ({ ...prev, [column.key]: nextWidth }));
273
+ };
274
+ const handleUp = () => {
275
+ window.removeEventListener('pointermove', handleMove);
276
+ window.removeEventListener('pointerup', handleUp);
277
+ document.body.style.cursor = '';
278
+ document.body.style.userSelect = '';
279
+ };
280
+ document.body.style.cursor = 'col-resize';
281
+ document.body.style.userSelect = 'none';
282
+ window.addEventListener('pointermove', handleMove);
283
+ window.addEventListener('pointerup', handleUp);
284
+ }, [columnWidths]);
285
+ const handleResizeKeyDown = useCallback((column, event) => {
286
+ if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight')
287
+ return;
288
+ event.preventDefault();
289
+ const step = event.shiftKey ? 24 : 10;
290
+ const delta = event.key === 'ArrowRight' ? step : -step;
291
+ const minW = column.minWidth ?? 64;
292
+ const maxW = column.maxWidth ?? 640;
293
+ setColumnWidths((prev) => {
294
+ const current = prev[column.key] ?? column.width ?? 140;
295
+ manualResizedKeysRef.current.add(column.key);
296
+ return {
297
+ ...prev,
298
+ [column.key]: Math.max(minW, Math.min(maxW, current + delta)),
299
+ };
300
+ });
301
+ }, []);
302
+ const handleResetColumnWidth = useCallback((column) => {
303
+ manualResizedKeysRef.current.delete(column.key);
304
+ const measured = computeInitialColumnWidth(column, data, { density, headerWrap });
305
+ setColumnWidths((prev) => ({ ...prev, [column.key]: measured }));
306
+ }, [data, density, headerWrap]);
307
+ // 打开单元格编辑器
308
+ const openCellEditor = useCallback((row, rKey, column) => {
309
+ if (!editing || editing.enabled === false)
310
+ return;
311
+ if (column.masked)
312
+ return;
313
+ const canEdit = editing.canEditCell
314
+ ? editing.canEditCell(row, column)
315
+ : column.edit?.editable !== false;
316
+ if (!canEdit)
317
+ return;
318
+ const raw = readColumnRawValue(row, column);
319
+ setEditingRow(row);
320
+ setEditingCol(column);
321
+ setEditorTarget({
322
+ rowKey: rKey,
323
+ columnKey: column.key,
324
+ columnLabel: column.label,
325
+ value: raw,
326
+ schema: column.edit ?? { valueType: 'text', nullable: true },
327
+ });
328
+ }, [editing]);
329
+ // TanStack Table 实例(用于统一列模型、Cell 上下文管理)
330
+ const tanstackColumns = useMemo(() => visibleColumns.map((col) => ({
331
+ id: col.key,
332
+ accessorFn: (row) => readColumnRawValue(row, col),
333
+ header: () => col.label,
334
+ cell: (info) => {
335
+ const row = info.row.original;
336
+ const rIndex = info.row.index;
337
+ const rKey = rowKeyList[rIndex] ?? String(rIndex);
338
+ const value = info.getValue();
339
+ const formatted = formatCellDisplayValue(value, row, col);
340
+ const isNull = value === null || value === undefined;
341
+ const isEditable = Boolean(editing && editing.enabled !== false) &&
342
+ !col.masked &&
343
+ (editing?.canEditCell
344
+ ? editing.canEditCell(row, col)
345
+ : col.edit?.editable !== false);
346
+ if (col.renderCell) {
347
+ return col.renderCell(value, row, {
348
+ row,
349
+ rowIndex: rIndex,
350
+ column: col,
351
+ formattedValue: formatted,
352
+ isNull,
353
+ isEditable,
354
+ openEditor: () => openCellEditor(row, rKey, col),
355
+ });
356
+ }
357
+ if (col.masked) {
358
+ return (_jsx("span", { className: "dt-cell-masked", title: "\u654F\u611F\u5B57\u6BB5\u5DF2\u8131\u654F", children: formatted }));
359
+ }
360
+ if (value === null || value === undefined) {
361
+ return _jsx("span", { className: "dt-null-badge", children: "NULL" });
362
+ }
363
+ if (isMissingCellValue(value, col.missingValue ?? '-')) {
364
+ return _jsx("span", { className: "dt-muted-cell", children: formatted });
365
+ }
366
+ return _jsx("span", { className: "dt-cell-text", children: formatted });
367
+ },
368
+ })), [visibleColumns, rowKeyList, editing, openCellEditor]);
369
+ const table = useReactTable({
370
+ data: processedRows,
371
+ columns: tanstackColumns,
372
+ getCoreRowModel: getCoreRowModel(),
373
+ manualSorting: true,
374
+ manualFiltering: true,
375
+ getRowId: (row, index) => resolveRowKey(row, index, rowKey),
376
+ });
377
+ const tableRows = table.getRowModel().rows;
378
+ // TanStack Virtual 虚拟滚动
379
+ const useVirtual = virtualConfig.enabled && !renderRow;
380
+ const rowVirtualizer = useVirtualizer({
381
+ count: useVirtual ? tableRows.length : 0,
382
+ getScrollElement: () => scrollContainerRef.current,
383
+ estimateSize: () => virtualConfig.rowHeight,
384
+ overscan: virtualConfig.overscan,
385
+ measureElement: virtualConfig.dynamicHeight
386
+ ? (el) => el.getBoundingClientRect().height
387
+ : undefined,
388
+ });
389
+ // 当密度或行高配置变化时,强制清空 TanStack Virtual 的行高缓存并重算总高度与偏移
390
+ useEffect(() => {
391
+ if (!useVirtual)
392
+ return;
393
+ rowVirtualizer.measure();
394
+ }, [useVirtual, rowVirtualizer, virtualConfig.rowHeight, virtualConfig.dynamicHeight, density]);
395
+ const virtualItems = useVirtual ? rowVirtualizer.getVirtualItems() : [];
396
+ const totalVirtualSize = useVirtual ? rowVirtualizer.getTotalSize() : 0;
397
+ const paddingTop = useVirtual && virtualItems.length > 0 ? virtualItems[0].start : 0;
398
+ const paddingBottom = useVirtual && virtualItems.length > 0
399
+ ? totalVirtualSize - virtualItems[virtualItems.length - 1].end
400
+ : 0;
401
+ useEffect(() => {
402
+ if (!onVisibleRowsChange)
403
+ return;
404
+ if (useVirtual) {
405
+ onVisibleRowsChange(virtualItems
406
+ .map((item) => tableRows[item.index]?.original)
407
+ .filter((r) => r !== undefined));
408
+ }
409
+ else {
410
+ onVisibleRowsChange(processedRows);
411
+ }
412
+ }, [useVirtual, virtualItems, tableRows, processedRows, onVisibleRowsChange]);
413
+ // 弹出筛选面板的列与枚举计数
414
+ const activeFilterCol = useMemo(() => columns.find((c) => c.key === openFilterKey) ?? null, [columns, openFilterKey]);
415
+ const activeEnumCounts = useMemo(() => {
416
+ if (!activeFilterCol)
417
+ return [];
418
+ const fType = inferredTypes.filterTypes[activeFilterCol.key];
419
+ if (fType !== 'enum')
420
+ return [];
421
+ if (queryMode === 'server' && serverEnumCounts?.[activeFilterCol.key]) {
422
+ return serverEnumCounts[activeFilterCol.key];
423
+ }
424
+ const candidateRows = applyClientFilters(data, columns, activeFilters, inferredTypes.sortTypes, activeFilterCol.key);
425
+ return computeEnumOptionCounts(data, candidateRows, activeFilterCol);
426
+ }, [
427
+ activeFilterCol,
428
+ inferredTypes,
429
+ queryMode,
430
+ serverEnumCounts,
431
+ data,
432
+ columns,
433
+ activeFilters,
434
+ ]);
435
+ // 全选状态计算
436
+ const selectableKeys = useMemo(() => {
437
+ if (!selection)
438
+ return [];
439
+ return processedRows
440
+ .map((row, idx) => ({
441
+ row,
442
+ key: rowKeyList[idx],
443
+ selectable: selection.isRowSelectable ? selection.isRowSelectable(row) : true,
444
+ }))
445
+ .filter((item) => item.selectable);
446
+ }, [selection, processedRows, rowKeyList]);
447
+ const selectedInVisibleCount = useMemo(() => {
448
+ if (!selection)
449
+ return 0;
450
+ return selectableKeys.filter((item) => selectedKeySet.has(item.key)).length;
451
+ }, [selection, selectableKeys, selectedKeySet]);
452
+ const allSelected = selectableKeys.length > 0 && selectedInVisibleCount === selectableKeys.length;
453
+ const someSelected = selectedInVisibleCount > 0 && selectedInVisibleCount < selectableKeys.length;
454
+ const handleToggleSelectAll = () => {
455
+ if (!selection)
456
+ return;
457
+ const next = new Set(selectedKeySet);
458
+ if (allSelected) {
459
+ for (const item of selectableKeys)
460
+ next.delete(item.key);
461
+ }
462
+ else {
463
+ for (const item of selectableKeys)
464
+ next.add(item.key);
465
+ }
466
+ const nextRows = processedRows.filter((row, idx) => next.has(rowKeyList[idx]));
467
+ selection.onChange(next, nextRows);
468
+ };
469
+ const handleToggleRow = (key) => {
470
+ if (!selection)
471
+ return;
472
+ const next = new Set(selectedKeySet);
473
+ if (next.has(key))
474
+ next.delete(key);
475
+ else
476
+ next.add(key);
477
+ const nextRows = processedRows.filter((row, idx) => next.has(rowKeyList[idx]));
478
+ selection.onChange(next, nextRows);
479
+ };
480
+ // 计算 columnActions 跨列合并布局
481
+ const renderedColumnActions = useMemo(() => {
482
+ if (!columnActions || columnActions.length === 0)
483
+ return null;
484
+ const actionByStartKey = new Map();
485
+ const coveredKeys = new Set();
486
+ for (const action of columnActions) {
487
+ const keys = action.spanKeys && action.spanKeys.length > 0
488
+ ? action.spanKeys
489
+ : [action.key];
490
+ const firstIdx = visibleColumns.findIndex((c) => keys.includes(c.key));
491
+ if (firstIdx < 0)
492
+ continue;
493
+ let span = 0;
494
+ for (let i = firstIdx; i < visibleColumns.length; i += 1) {
495
+ if (keys.includes(visibleColumns[i].key)) {
496
+ span += 1;
497
+ coveredKeys.add(visibleColumns[i].key);
498
+ }
499
+ else {
500
+ break;
501
+ }
502
+ }
503
+ if (span > 0) {
504
+ actionByStartKey.set(visibleColumns[firstIdx].key, { item: action, colSpan: span });
505
+ }
506
+ }
507
+ const cells = [];
508
+ if (selection)
509
+ cells.push(_jsx("th", { className: "dt-action-th" }, "__sel_action"));
510
+ if (showSequenceColumn)
511
+ cells.push(_jsx("th", { className: "dt-action-th" }, "__seq_action"));
512
+ for (const col of visibleColumns) {
513
+ const match = actionByStartKey.get(col.key);
514
+ if (match) {
515
+ cells.push(_jsx("th", { colSpan: match.colSpan, className: "dt-action-th", children: match.item.render() }, `action_${col.key}`));
516
+ }
517
+ else if (!coveredKeys.has(col.key)) {
518
+ cells.push(_jsx("th", { className: "dt-action-th" }, `action_empty_${col.key}`));
519
+ }
520
+ }
521
+ return _jsx("tr", { className: "dt-action-row", children: cells });
522
+ }, [columnActions, visibleColumns, selection, showSequenceColumn]);
523
+ const totalColCount = visibleColumns.length + (selection ? 1 : 0) + (showSequenceColumn ? 1 : 0);
524
+ const totalTableWidth = useMemo(() => {
525
+ const colsWidth = visibleColumns.reduce((sum, col) => sum + (columnWidths[col.key] ?? col.width ?? 140), 0);
526
+ return colsWidth + selectionColWidth + sequenceColWidth;
527
+ }, [visibleColumns, columnWidths, selectionColWidth, sequenceColWidth]);
528
+ const renderStandardRow = (tanRow, virtualIndex, measureRef) => {
529
+ const row = tanRow.original;
530
+ const idx = virtualIndex ?? tanRow.index;
531
+ const rKey = rowKeyList[idx] ?? tanRow.id;
532
+ const isSelected = selection ? selectedKeySet.has(rKey) : false;
533
+ const extraClass = typeof rowClassName === 'function' ? rowClassName(row, idx) : (rowClassName ?? '');
534
+ if (renderRow) {
535
+ const renderDefaultCell = (col) => {
536
+ const cell = tanRow.getAllCells().find((c) => c.column.id === col.key);
537
+ if (!cell)
538
+ return null;
539
+ return flexRender(cell.column.columnDef.cell, cell.getContext());
540
+ };
541
+ return renderRow(row, {
542
+ rowIndex: idx,
543
+ rowKey: rKey,
544
+ visibleColumns,
545
+ columnWidths,
546
+ stickyOffsets,
547
+ lastFixedLeftKey,
548
+ renderDefaultCell,
549
+ });
550
+ }
551
+ return (_jsxs("tr", { ref: measureRef, "data-index": idx, style: useVirtual && !virtualConfig.dynamicHeight
552
+ ? { height: virtualConfig.rowHeight }
553
+ : undefined, className: `dt-tr ${isSelected ? 'is-selected' : ''} ${onRowClick ? 'is-clickable' : ''} ${extraClass}`.trim(), onClick: () => onRowClick?.(row, idx), children: [selection && (_jsx("td", { className: `dt-td dt-td-checkbox ${!narrowContainer ? 'dt-sticky-left' : ''}`, style: {
554
+ width: selectionColWidth,
555
+ left: !narrowContainer ? 0 : undefined,
556
+ }, onClick: (e) => e.stopPropagation(), children: _jsx("button", { type: "button", role: "checkbox", "aria-checked": isSelected, "aria-label": `选择第 ${idx + 1} 行`, disabled: selection.isRowSelectable ? !selection.isRowSelectable(row) : false, className: `dt-checkbox-btn ${isSelected ? 'is-checked' : ''}`, onClick: () => handleToggleRow(rKey), children: isSelected && _jsx(Check, { size: 12, strokeWidth: 3 }) }) })), showSequenceColumn && (_jsx("td", { className: `dt-td dt-td-seq ${!narrowContainer ? 'dt-sticky-left' : ''}`, style: {
557
+ width: sequenceColWidth,
558
+ left: !narrowContainer ? selectionColWidth : undefined,
559
+ }, children: pagination
560
+ ? (pagination.page - 1) * pagination.pageSize + idx + 1
561
+ : idx + 1 })), tanRow.getVisibleCells().map((cell, colIndex) => {
562
+ const col = visibleColumns[colIndex];
563
+ if (!col)
564
+ return null;
565
+ const isFixed = col.fixed === 'left' && !narrowContainer;
566
+ const stickyLeft = isFixed ? stickyOffsets[col.key] : undefined;
567
+ const isLastFixed = col.key === lastFixedLeftKey;
568
+ const width = columnWidths[col.key] ?? col.width ?? 140;
569
+ const isEditable = Boolean(editing && editing.enabled !== false) &&
570
+ !col.masked &&
571
+ (editing?.canEditCell
572
+ ? editing.canEditCell(row, col)
573
+ : col.edit?.editable !== false);
574
+ const rawVal = readColumnRawValue(row, col);
575
+ const formattedTitle = col.masked
576
+ ? undefined
577
+ : formatCellDisplayValue(rawVal, row, col);
578
+ const triggerEdit = (e) => {
579
+ if (!isEditable)
580
+ return;
581
+ e.stopPropagation();
582
+ openCellEditor(row, rKey, col);
583
+ };
584
+ return (_jsx("td", { className: `dt-td dt-align-${col.align ?? 'left'} ${isFixed ? 'dt-sticky-left' : ''} ${isLastFixed ? 'dt-sticky-shadow' : ''} ${isEditable ? 'dt-td-editable' : ''}`.trim(), style: {
585
+ width,
586
+ minWidth: width,
587
+ maxWidth: width,
588
+ left: stickyLeft,
589
+ }, tabIndex: isEditable ? 0 : undefined, onClick: editing?.trigger === 'click' ? triggerEdit : undefined, onDoubleClick: editing?.trigger !== 'click' ? triggerEdit : undefined, onKeyDown: (e) => {
590
+ if (isEditable && (e.key === 'Enter' || e.key === 'F2')) {
591
+ e.preventDefault();
592
+ openCellEditor(row, rKey, col);
593
+ }
594
+ }, title: isEditable
595
+ ? `${formattedTitle ?? ''}(双击或按 Enter 编辑)`
596
+ : formattedTitle, children: _jsx("div", { className: "dt-cell-inner", children: flexRender(cell.column.columnDef.cell, cell.getContext()) }) }, cell.id));
597
+ })] }, rKey));
598
+ };
599
+ return (_jsxs("div", { className: `dt-root dt-density-${density} ${className}`.trim(), style: style, children: [(toolbar || columnManager) && (_jsxs("div", { className: "dt-toolbar", children: [_jsx("div", { className: "dt-toolbar-main", children: toolbar }), columnManager && (_jsxs("button", { ref: columnManagerBtnRef, type: "button", className: `dt-btn dt-btn-secondary dt-btn-sm ${hiddenColumnKeys.size > 0 || columnManagerOpen ? 'is-active' : ''}`, onClick: () => setColumnManagerOpen((prev) => !prev), "aria-expanded": columnManagerOpen, title: "\u641C\u7D22\u5B9A\u4F4D\u6216\u9690\u85CF/\u663E\u793A\u5217", children: [_jsx(Columns3, { size: 14 }), _jsxs("span", { children: ["\u641C\u7D22\u5217 (", visibleColumns.length, "/", columns.length, ")"] })] }))] })), _jsxs("div", { className: "dt-surface", children: [loading && (_jsxs("div", { className: "dt-loading-bar", "aria-live": "polite", children: [_jsx(Loader2, { size: 14, className: "dt-spin" }), _jsx("span", { children: "\u6B63\u5728\u52A0\u8F7D\u6570\u636E..." })] })), _jsx("div", { ref: scrollContainerRef, className: "dt-scroll-container", style: virtualConfig.enabled
600
+ ? { maxHeight: virtualConfig.maxHeight }
601
+ : undefined, children: _jsxs("table", { className: "dt-table", "aria-label": ariaLabel, style: { width: totalTableWidth }, children: [_jsxs("thead", { className: "dt-thead", children: [renderedColumnActions, headerExtras, _jsxs("tr", { className: "dt-header-row", children: [selection && (_jsx("th", { className: `dt-th dt-th-checkbox ${!narrowContainer ? 'dt-sticky-left' : ''}`, style: {
602
+ width: selectionColWidth,
603
+ minWidth: selectionColWidth,
604
+ left: !narrowContainer ? 0 : undefined,
605
+ }, children: _jsx("button", { type: "button", role: "checkbox", "aria-checked": allSelected ? true : someSelected ? 'mixed' : false, "aria-label": "\u5168\u9009\u5F53\u524D\u5217\u8868", className: `dt-checkbox-btn ${allSelected || someSelected ? 'is-checked' : ''}`, onClick: handleToggleSelectAll, children: allSelected ? (_jsx(Check, { size: 12, strokeWidth: 3 })) : someSelected ? (_jsx(Minus, { size: 12, strokeWidth: 3 })) : null }) })), showSequenceColumn && (_jsx("th", { className: `dt-th dt-th-seq ${!narrowContainer ? 'dt-sticky-left' : ''}`, style: {
606
+ width: sequenceColWidth,
607
+ minWidth: sequenceColWidth,
608
+ left: !narrowContainer ? selectionColWidth : undefined,
609
+ }, children: sequenceLabel })), visibleColumns.map((col) => {
610
+ const width = columnWidths[col.key] ?? col.width ?? 140;
611
+ const sortable = col.sortable !== false;
612
+ const filterable = col.filterable !== false;
613
+ const sortIndex = activeSort.findIndex((s) => s.key === col.key);
614
+ const sortDir = sortIndex >= 0 ? activeSort[sortIndex].direction : null;
615
+ const filterActive = isColumnFilterActive(activeFilters[col.key]);
616
+ const filterOpen = openFilterKey === col.key;
617
+ const toolsPinned = Boolean(sortDir || filterActive || filterOpen);
618
+ const isFixed = col.fixed === 'left' && !narrowContainer;
619
+ const stickyLeft = isFixed ? stickyOffsets[col.key] : undefined;
620
+ const isLastFixed = col.key === lastFixedLeftKey;
621
+ const resizable = col.resizable !== false;
622
+ const allowHeaderWrap = col.headerWrap ?? headerWrap;
623
+ const isLocated = locatedColumnKey === col.key;
624
+ return (_jsxs("th", { ref: (el) => {
625
+ headerCellRefs.current[col.key] = el;
626
+ }, className: `dt-th dt-align-${col.align ?? 'left'} ${isFixed ? 'dt-sticky-left' : ''} ${isLastFixed ? 'dt-sticky-shadow' : ''} ${toolsPinned ? 'has-active-tools' : ''} ${isLocated ? 'is-located' : ''}`.trim(), style: {
627
+ width,
628
+ minWidth: width,
629
+ maxWidth: width,
630
+ left: stickyLeft,
631
+ }, "aria-sort": sortDir === 'asc'
632
+ ? 'ascending'
633
+ : sortDir === 'desc'
634
+ ? 'descending'
635
+ : 'none', children: [_jsxs("div", { className: "dt-th-inner", children: [col.renderHeader ? (col.renderHeader({
636
+ column: col,
637
+ sortDirection: sortDir,
638
+ sortIndex,
639
+ isFilterActive: filterActive,
640
+ isFilterOpen: filterOpen,
641
+ toggleSort: () => handleToggleSort(col.key, false),
642
+ openFilter: () => setOpenFilterKey((prev) => prev === col.key ? null : col.key),
643
+ })) : (_jsx("button", { type: "button", className: `dt-th-label-btn ${sortable ? 'is-sortable' : ''}`, title: col.headerTooltip ?? col.label, onClick: (e) => {
644
+ if (sortable)
645
+ handleToggleSort(col.key, e.shiftKey);
646
+ }, children: _jsx("span", { className: `dt-th-label-text ${allowHeaderWrap ? 'is-wrap' : ''}`, children: col.label }) })), (sortable || filterable) && (_jsxs("div", { className: `dt-header-tools ${toolsPinned ? 'is-pinned' : ''}`, children: [sortable && (_jsxs("button", { type: "button", className: `dt-header-tool-btn ${sortDir ? 'is-active' : ''}`, "aria-label": `排序 ${col.label}`, title: sortDir === 'asc'
647
+ ? '升序(点击切换降序)'
648
+ : sortDir === 'desc'
649
+ ? '降序(点击取消排序)'
650
+ : '点击排序', onClick: (e) => {
651
+ e.stopPropagation();
652
+ handleToggleSort(col.key, e.shiftKey);
653
+ }, children: [sortDir === 'asc' ? (_jsx(ArrowUp, { size: 13 })) : sortDir === 'desc' ? (_jsx(ArrowDown, { size: 13 })) : (_jsx(ArrowUpDown, { size: 13 })), multiSort && sortIndex >= 0 && activeSort.length > 1 && (_jsx("span", { className: "dt-sort-badge", children: sortIndex + 1 }))] })), filterable && (_jsx("button", { ref: (el) => {
654
+ filterAnchorRefs.current[col.key] = el;
655
+ }, type: "button", className: `dt-header-tool-btn ${filterActive || filterOpen ? 'is-active' : ''}`, "aria-label": `筛选 ${col.label}`, "aria-expanded": filterOpen, title: `筛选 ${col.label}`, onClick: (e) => {
656
+ e.stopPropagation();
657
+ setOpenFilterKey((prev) => prev === col.key ? null : col.key);
658
+ }, children: _jsx(Filter, { size: 12.5 }) }))] }))] }), resizable && (_jsx("div", { role: "separator", "aria-orientation": "vertical", "aria-label": `调整 ${col.label} 列宽`, tabIndex: 0, className: "dt-col-resizer", onPointerDown: (e) => {
659
+ e.preventDefault();
660
+ e.stopPropagation();
661
+ startResize(col, e.clientX);
662
+ }, onDoubleClick: (e) => {
663
+ e.stopPropagation();
664
+ handleResetColumnWidth(col);
665
+ }, onKeyDown: (e) => handleResizeKeyDown(col, e) }))] }, col.key));
666
+ })] })] }), _jsx("tbody", { className: "dt-tbody", children: tableRows.length === 0 ? (_jsx("tr", { className: "dt-empty-row", children: _jsx("td", { colSpan: totalColCount, className: "dt-empty-cell", children: emptyNode ?? (_jsx("div", { className: "dt-empty-state", children: _jsx("span", { children: loading ? '正在查询数据...' : emptyText }) })) }) })) : useVirtual ? (_jsxs(_Fragment, { children: [paddingTop > 0 && (_jsx("tr", { className: "dt-virtual-spacer", "aria-hidden": "true", children: _jsx("td", { colSpan: totalColCount, style: { height: paddingTop, padding: 0 } }) })), virtualItems.map((vItem) => {
667
+ const tanRow = tableRows[vItem.index];
668
+ if (!tanRow)
669
+ return null;
670
+ return renderStandardRow(tanRow, vItem.index, virtualConfig.dynamicHeight
671
+ ? rowVirtualizer.measureElement
672
+ : undefined);
673
+ }), paddingBottom > 0 && (_jsx("tr", { className: "dt-virtual-spacer", "aria-hidden": "true", children: _jsx("td", { colSpan: totalColCount, style: { height: paddingBottom, padding: 0 } }) }))] })) : (tableRows.map((tanRow) => renderStandardRow(tanRow))) })] }) })] }), pagination && (_jsxs("div", { className: "dt-pagination", children: [_jsxs("div", { className: "dt-pagination-info", children: ["\u5171 ", _jsx("strong", { children: pagination.totalCount }), " \u6761 \u00B7 \u7B2C", ' ', _jsx("strong", { children: pagination.page }), " /", ' ', Math.max(1, Math.ceil(pagination.totalCount / pagination.pageSize)), " \u9875"] }), _jsxs("div", { className: "dt-pagination-controls", children: [pagination.onPageSizeChange && (_jsx("select", { className: "dt-select-sm", "aria-label": "\u6BCF\u9875\u6761\u6570", value: pagination.pageSize, onChange: (e) => pagination.onPageSizeChange?.(Number(e.target.value)), children: (pagination.pageSizeOptions ?? [20, 50, 100, 200]).map((size) => (_jsxs("option", { value: size, children: [size, " \u6761/\u9875"] }, size))) })), _jsx("button", { type: "button", className: "dt-btn dt-btn-secondary dt-btn-sm", disabled: pagination.page <= 1, onClick: () => pagination.onPageChange(pagination.page - 1), children: "\u4E0A\u4E00\u9875" }), _jsx("button", { type: "button", className: "dt-btn dt-btn-secondary dt-btn-sm", disabled: pagination.page >=
674
+ Math.max(1, Math.ceil(pagination.totalCount / pagination.pageSize)), onClick: () => pagination.onPageChange(pagination.page + 1), children: "\u4E0B\u4E00\u9875" })] })] })), footer && _jsx("div", { className: "dt-footer", children: footer }), _jsx(Popover, { open: Boolean(activeFilterCol), anchorRef: {
675
+ current: activeFilterCol
676
+ ? (filterAnchorRefs.current[activeFilterCol.key] ?? null)
677
+ : null,
678
+ }, onClose: () => setOpenFilterKey(null), align: "right", children: activeFilterCol && (_jsx(ColumnFilterPopover, { columnLabel: activeFilterCol.label, filterType: inferredTypes.filterTypes[activeFilterCol.key], sortType: inferredTypes.sortTypes[activeFilterCol.key], value: activeFilters[activeFilterCol.key], enumCounts: activeEnumCounts, onChange: (nextFilter) => {
679
+ const nextMap = { ...activeFilters };
680
+ if (nextFilter) {
681
+ nextMap[activeFilterCol.key] = nextFilter;
682
+ }
683
+ else {
684
+ delete nextMap[activeFilterCol.key];
685
+ }
686
+ setFilters(nextMap);
687
+ }, onClose: () => setOpenFilterKey(null) })) }), _jsx(Popover, { open: columnManagerOpen, anchorRef: columnManagerBtnRef, onClose: () => setColumnManagerOpen(false), align: "right", children: _jsx(ColumnManagerPopover, { columns: columns, hiddenKeys: hiddenColumnKeys, onToggleColumn: handleToggleColumnVisibility, onShowAll: () => setHiddenColumnKeys(new Set()), onLocateColumn: handleLocateColumn, onClose: () => setColumnManagerOpen(false) }) }), _jsx(CellEditorDialog, { target: editorTarget, onClose: () => {
688
+ setEditorTarget(null);
689
+ setEditingRow(null);
690
+ setEditingCol(null);
691
+ }, onSave: async (nextValue) => {
692
+ if (!editing || !editorTarget || !editingRow || !editingCol)
693
+ return;
694
+ await editing.onSaveCell({
695
+ row: editingRow,
696
+ rowKey: editorTarget.rowKey,
697
+ column: editingCol,
698
+ value: nextValue,
699
+ previousValue: editorTarget.value,
700
+ });
701
+ } })] }));
702
+ }
703
+ //# sourceMappingURL=DataTable.js.map