-
-
Notifications
You must be signed in to change notification settings - Fork 132
/
Table.tsx
1244 lines (1079 loc) · 36.3 KB
/
Table.tsx
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { useRef, useCallback, useImperativeHandle, useReducer, useMemo } from 'react';
import * as ReactIs from 'react-is';
import { getTranslateDOMPositionXY } from 'dom-lib/translateDOMPositionXY';
import PropTypes from 'prop-types';
import isFunction from 'lodash/isFunction';
import debounce from 'lodash/debounce';
import Row, { RowProps } from './Row';
import CellGroup from './CellGroup';
import Scrollbar, { ScrollbarInstance } from './Scrollbar';
import MouseArea from './MouseArea';
import Loader from './Loader';
import EmptyMessage from './EmptyMessage';
import TableContext from './TableContext';
import Cell, { InnerCellProps } from './Cell';
import HeaderCell, { HeaderCellProps } from './HeaderCell';
import Column, { ColumnProps } from './Column';
import ColumnGroup from './ColumnGroup';
import {
SCROLLBAR_WIDTH,
CELL_PADDING_HEIGHT,
SORT_TYPE,
TREE_DEPTH,
ROW_HEADER_HEIGHT,
ROW_HEIGHT
} from './constants';
import {
mergeCells,
isRTL,
findRowKeys,
resetLeftForCells,
useClassNames,
useControlled,
useUpdateEffect,
useCellDescriptor,
useTableDimension,
useTableRows,
useAffix,
useScrollListener,
usePosition,
useTableData,
isSupportTouchEvent
} from './utils';
import type {
StandardProps,
SortType,
RowKeyType,
TableLocaleType,
TableSizeChangeEventName,
RowDataType
} from './@types/common';
import { flattenChildren } from './utils/children';
export interface TableProps<Row extends RowDataType, Key extends RowKeyType>
extends Omit<StandardProps, 'onScroll' | 'children'> {
/**
* The height of the table will be automatically expanded according to the number of data rows,
* and no vertical scroll bar will appear
* */
autoHeight?: boolean;
/**
* Force the height of the table to be equal to the height of its parent container.
* Cannot be used together with autoHeight.
*/
fillHeight?: boolean;
/** Affix the table header to the specified position on the page */
affixHeader?: boolean | number;
/** Affix the table horizontal scrollbar to the specified position on the page */
affixHorizontalScrollbar?: boolean | number;
/** Show the border of the table */
bordered?: boolean;
/** Display the borders of table cells */
cellBordered?: boolean;
/** Default sort type */
defaultSortType?: SortType;
/** Disable scroll bar */
disabledScroll?: boolean;
/** Expand all nodes By default */
defaultExpandAllRows?: boolean;
/** Specify the default expanded row by rowkey */
defaultExpandedRowKeys?: readonly Key[];
/** Table data */
data?: readonly Row[];
/** Specify the default expanded row by rowkey (Controlled) */
expandedRowKeys?: readonly Key[];
/** The visible height of the table (the height of the scrollable container). */
height?: number;
/** The minimum height of the table. The height is maintained even when the content is not stretched. */
minHeight?: number;
/**
* The maximum height of the table.
* Usually used together with `autoHeight`. When the height of the table exceeds `maxHeight`, the table will have a scroll bar.
*/
maxHeight?: number;
/** The row of the table has a mouseover effect */
hover?: boolean;
/** The height of the table header */
headerHeight?: number;
/** The component localized character set. */
locale?: TableLocaleType;
/** Show loading */
loading?: boolean;
/** Whether to enable loading animation */
loadAnimation?: boolean;
/** The row height of the table */
rowHeight?: number | ((rowData?: Row) => number);
/** Each row corresponds to the unique key in data */
rowKey?: RowKeyType;
/** The table will be displayed as a tree structure */
isTree?: boolean;
/** Set the height of an expandable area */
rowExpandedHeight?: ((rowData?: Row) => number) | number;
/** Add an optional extra class name to row */
rowClassName?: string | ((rowData: Row, rowIndex: number) => string);
/** Whether to display the header of the table */
showHeader?: boolean;
/** Sort Column Name */
sortColumn?: string;
/** Sort type */
sortType?: SortType;
/**
* Use the return value of `shouldUpdateScroll` to determine
* whether to update the scroll after the table size is updated.
*/
shouldUpdateScroll?:
| boolean
| ((event: TableSizeChangeEventName) => {
x?: number;
y?: number;
});
/** Enable 3D transition rendering to improve performance when scrolling. */
translate3d?: boolean;
/** Right to left */
rtl?: boolean;
/** The width of the table. When it is not set, it will adapt according to the container */
width?: number;
/**
* Whether to appear line breaks where text overflows its content box
* https://developer.mozilla.org/en-US/docs/Web/CSS/word-break
*/
wordWrap?: boolean | 'break-all' | 'break-word' | 'keep-all';
/** Effectively render large tabular data */
virtualized?: boolean;
/** Tree table, the callback function in the expanded node */
renderTreeToggle?: (
expandButton: React.ReactNode,
rowData?: Row,
expanded?: boolean
) => React.ReactNode;
/** Customize what you can do to expand a zone */
renderRowExpanded?: (rowData?: Row) => React.ReactNode;
/** Custom row element */
renderRow?: (children?: React.ReactNode, rowData?: Row) => React.ReactNode;
/** Customized data is empty display content */
renderEmpty?: (info: React.ReactNode) => React.ReactNode;
/** Customize the display content in the data load */
renderLoading?: (loading: React.ReactNode) => React.ReactNode;
/** Click the callback function after the row and return to rowDate */
onRowClick?: (rowData: Row, event: React.MouseEvent) => void;
/** Callback after right-click row */
onRowContextMenu?: (rowData: Row, event: React.MouseEvent) => void;
/** Callback function for scroll bar scrolling */
onScroll?: (scrollX: number, scrollY: number) => void;
/** Click the callback function of the sort sequence to return the value sortColumn, sortType */
onSortColumn?: (dataKey: string, sortType?: SortType) => void;
/** Tree table, the callback function in the expanded node */
onExpandChange?: (expanded: boolean, rowData: Row) => void;
/** Callback for the `touchstart` event. */
onTouchStart?: (event: React.TouchEvent) => void;
/** Callback for the `touchmove` event. */
onTouchMove?: (event: React.TouchEvent) => void;
/** Callback for the `touchend` event. */
onTouchEnd?: (event: React.TouchEvent) => void;
/**
* Callback after table data update.
* @deprecated use `shouldUpdateScroll` instead
**/
onDataUpdated?: (nextData: Row[], scrollTo: (coord: { x: number; y: number }) => void) => void;
/**
* A ref attached to the table body element
* @deprecated use `ref` instead (see `ref.current.body`)
**/
bodyRef?: (ref: HTMLElement) => void;
children?:
| React.ReactNode
| React.ReactNode[]
| ((props: {
Cell: (
props: InnerCellProps<Row, Key> & React.RefAttributes<HTMLDivElement>
) => React.ReactElement;
Column: (props: ColumnProps<Row>) => React.ReactElement;
ColumnGroup: typeof ColumnGroup;
HeaderCell: (
props: HeaderCellProps<Row, Key> & React.RefAttributes<HTMLDivElement>
) => React.ReactElement;
}) => React.ReactNode | React.ReactNode[]);
}
interface TableRowProps extends RowProps {
key?: string | number;
rowIndex: number;
depth?: number;
}
const DATA_PLACEHOLDER = [];
const getChildrenProps = {
Cell,
HeaderCell,
Column,
ColumnGroup
};
const Table = React.forwardRef(
<Row extends RowDataType, Key extends RowKeyType>(props: TableProps<Row, Key>, ref) => {
const {
affixHeader,
children: getChildren,
classPrefix = 'rs-table',
className,
data: dataProp = DATA_PLACEHOLDER,
defaultSortType = SORT_TYPE.DESC as SortType,
width: widthProp,
expandedRowKeys: expandedRowKeysProp,
defaultExpandAllRows,
defaultExpandedRowKeys,
style,
id,
isTree,
hover = true,
bordered,
cellBordered,
wordWrap,
loading,
locale = {
emptyMessage: 'No data found',
loading: 'Loading...'
},
showHeader = true,
sortColumn,
rowHeight = ROW_HEIGHT,
sortType: sortTypeProp,
headerHeight: headerHeightProp = ROW_HEADER_HEIGHT,
minHeight = 0,
maxHeight,
height = 200,
autoHeight,
fillHeight,
rtl: rtlProp,
translate3d,
rowKey,
virtualized,
rowClassName,
rowExpandedHeight = 100,
disabledScroll,
affixHorizontalScrollbar,
loadAnimation,
shouldUpdateScroll = true,
renderRow: renderRowProp,
renderRowExpanded: renderRowExpandedProp,
renderLoading,
renderEmpty,
onSortColumn,
onScroll,
renderTreeToggle,
onRowClick,
onRowContextMenu,
onExpandChange,
onTouchStart,
onTouchMove,
onTouchEnd,
...rest
} = props;
const children = useMemo(
() => flattenChildren(isFunction(getChildren) ? getChildren(getChildrenProps) : getChildren),
[getChildren]
);
const isAutoHeight = useMemo(() => autoHeight && !maxHeight, [autoHeight, maxHeight]);
const {
withClassPrefix,
merge: mergeCls,
prefix
} = useClassNames(classPrefix, typeof classPrefix !== 'undefined');
// Use `forceUpdate` to force the component to re-render after manipulating the DOM.
const [, forceUpdate] = useReducer(x => x + 1, 0);
const [expandedRowKeys, setExpandedRowKeys] = useControlled(
expandedRowKeysProp,
defaultExpandAllRows
? findRowKeys(dataProp, rowKey, isFunction(renderRowExpandedProp))
: defaultExpandedRowKeys || []
);
const data = useTableData({ data: dataProp, isTree, expandedRowKeys, rowKey });
if (isTree) {
if (!rowKey) {
throw new Error('The `rowKey` is required when set isTree');
} else if (data.length > 0) {
if (!data[0].hasOwnProperty(rowKey)) {
throw new Error('The `rowKey` is not found in data');
}
}
}
const { tableRowsMaxHeight, bindTableRowsRef } = useTableRows({
data: dataProp,
expandedRowKeys,
wordWrap,
prefix
});
const headerHeight = showHeader ? headerHeightProp : 0;
const rtl = rtlProp || isRTL();
const getRowHeight = () => {
return typeof rowHeight === 'function' ? rowHeight() : rowHeight;
};
const translateDOMPositionXY = useRef(
getTranslateDOMPositionXY({ forceUseTransform: true, enable3DTransform: translate3d })
);
// Check for the existence of fixed columns in all column properties.
const shouldFixedColumn = children.some(
child => ReactIs.isElement(child) && child?.props?.fixed
);
// Check all column properties for the existence of rowSpan.
const shouldRowSpanColumn = children.some(
child => ReactIs.isElement(child) && child?.props?.rowSpan
);
const visibleRows = useRef<React.ReactNode[]>([]);
const mouseAreaRef = useRef<HTMLDivElement>(null);
const tableRef = useRef<HTMLDivElement>(null);
const tableHeaderRef = useRef<HTMLDivElement>(null);
const affixHeaderWrapperRef = useRef<HTMLDivElement>(null);
const headerWrapperRef = useRef<HTMLDivElement>(null);
const tableBodyRef = useRef<HTMLDivElement>(null);
const wheelWrapperRef = useRef<HTMLDivElement>(null);
const scrollbarXRef = useRef<ScrollbarInstance>(null);
const scrollbarYRef = useRef<ScrollbarInstance>(null);
const handleTableResizeChange = (_prevSize, event: TableSizeChangeEventName) => {
forceUpdate();
/**
* Reset the position of the scroll bar after the table size changes.
*/
if (typeof shouldUpdateScroll === 'function') {
onScrollTo(shouldUpdateScroll(event));
} else if (shouldUpdateScroll) {
const vertical = event === 'bodyHeightChanged';
vertical ? onScrollTop(0) : onScrollLeft(0);
}
if (event === 'bodyWidthChanged') {
deferUpdatePosition();
}
};
const {
contentHeight,
contentWidth,
minScrollY,
minScrollX,
scrollY,
scrollX,
tableWidth,
tableOffset,
headerOffset,
setScrollY,
setScrollX,
getTableHeight
} = useTableDimension({
// The data should be flattened,
// otherwise the array length required to calculate the scroll height in the TreeTable is not real.
data,
width: widthProp,
rowHeight,
tableRef,
headerWrapperRef,
prefix,
affixHeader,
affixHorizontalScrollbar,
headerHeight,
height,
minHeight,
maxHeight,
autoHeight,
fillHeight,
children,
expandedRowKeys,
showHeader,
bordered,
onTableScroll: debounce((coords: { x?: number; y?: number }) => onScrollTo(coords), 100),
onTableResizeChange: handleTableResizeChange
});
useAffix({
getTableHeight,
contentHeight,
affixHorizontalScrollbar,
affixHeader,
tableOffset,
headerOffset,
headerHeight,
scrollbarXRef,
affixHeaderWrapperRef
});
const { forceUpdatePosition, deferUpdatePosition } = usePosition({
data: dataProp,
height,
tableWidth,
tableRef,
prefix,
translateDOMPositionXY,
wheelWrapperRef,
headerWrapperRef,
affixHeaderWrapperRef,
tableHeaderRef,
scrollX,
scrollY,
contentWidth,
shouldFixedColumn
});
const {
isScrolling,
onScrollHorizontal,
onScrollVertical,
onScrollBody,
onScrollTop,
onScrollLeft,
onScrollTo,
onScrollByKeydown
} = useScrollListener({
rtl,
data: dataProp,
height,
virtualized,
getTableHeight,
contentHeight,
headerHeight,
autoHeight: isAutoHeight,
maxHeight,
tableBodyRef,
scrollbarXRef,
scrollbarYRef,
disabledScroll,
loading,
tableRef,
contentWidth,
tableWidth,
scrollY,
minScrollY,
minScrollX,
scrollX,
setScrollX,
setScrollY,
forceUpdatePosition,
deferUpdatePosition,
onScroll,
onTouchStart,
onTouchMove,
onTouchEnd
});
const { headerCells, bodyCells, allColumnsWidth, hasCustomTreeCol } = useCellDescriptor({
children,
rtl,
mouseAreaRef,
tableRef,
minScrollX,
scrollX,
tableWidth,
headerHeight,
showHeader,
sortType: sortTypeProp,
defaultSortType,
sortColumn,
prefix,
onSortColumn,
// Force table update after column width change, so scrollbar re-renders.
onHeaderCellResize: forceUpdate,
rowHeight
});
const colCounts = useRef(headerCells?.length || 0);
useUpdateEffect(() => {
if (headerCells?.length !== colCounts.current) {
onScrollLeft(0);
colCounts.current = headerCells?.length || 0;
}
}, [children]);
useImperativeHandle(ref, () => ({
get root() {
return tableRef.current;
},
get body() {
return wheelWrapperRef.current;
},
// The scroll position of the table
get scrollPosition() {
return {
top: Math.abs(scrollY.current),
left: Math.abs(scrollX.current)
};
},
scrollTop: onScrollTop,
scrollLeft: onScrollLeft
}));
const rowWidth = allColumnsWidth > tableWidth.current ? allColumnsWidth : tableWidth.current;
// Whether to show vertical scroll bar
const hasVerticalScrollbar =
!isAutoHeight && contentHeight.current > getTableHeight() - headerHeight;
// Whether to show the horizontal scroll bar
const hasHorizontalScrollbar = contentWidth.current > tableWidth.current;
const classes = mergeCls(
className,
withClassPrefix({
bordered,
loading,
treetable: isTree,
hover: hover && !shouldRowSpanColumn,
'has-rowspan': shouldRowSpanColumn,
'word-wrap': wordWrap,
'cell-bordered': cellBordered
})
);
const styles = {
width: widthProp || 'auto',
height: getTableHeight(),
...style
};
const renderRowExpanded = useCallback(
(rowData?: Row) => {
let height = 0;
if (typeof rowExpandedHeight === 'function') {
height = rowExpandedHeight(rowData);
} else {
height = rowExpandedHeight;
}
const styles = { height };
if (typeof renderRowExpandedProp === 'function') {
return (
<div className={prefix('row-expanded')} style={styles}>
{renderRowExpandedProp(rowData)}
</div>
);
}
return null;
},
[prefix, renderRowExpandedProp, rowExpandedHeight]
);
const renderRow = (
props: TableRowProps,
cells: any[],
shouldRenderExpandedRow?: boolean,
rowData?: any
) => {
const { depth, rowIndex, ...restRowProps } = props;
if (typeof rowClassName === 'function') {
restRowProps.className = rowClassName(rowData, rowIndex);
} else {
restRowProps.className = rowClassName;
}
const rowStyles: React.CSSProperties = {
...props?.style
};
let rowRight = 0;
if (rtl && contentWidth.current > tableWidth.current) {
rowRight = tableWidth.current - contentWidth.current;
rowStyles.right = rowRight;
}
let rowNode: React.ReactNode = null;
// IF there are fixed columns, add a fixed group
if (shouldFixedColumn && contentWidth.current > tableWidth.current) {
const fixedLeftCells: React.ReactNode[] = [];
const fixedRightCells: React.ReactNode[] = [];
const scrollCells: React.ReactNode[] = [];
let fixedLeftCellGroupWidth = 0;
let fixedRightCellGroupWidth = 0;
for (let i = 0; i < cells.length; i++) {
const cell = cells[i];
const { fixed, width } = cell.props;
let isFixedStart = fixed === 'left' || fixed === true;
let isFixedEnd = fixed === 'right';
if (rtl) {
isFixedStart = fixed === 'right';
isFixedEnd = fixed === 'left' || fixed === true;
}
if (isFixedStart) {
fixedLeftCells.push(cell);
fixedLeftCellGroupWidth += width;
} else if (isFixedEnd) {
fixedRightCells.push(cell);
fixedRightCellGroupWidth += width;
} else {
scrollCells.push(cell);
}
}
if (hasVerticalScrollbar && fixedRightCellGroupWidth) {
fixedRightCellGroupWidth += SCROLLBAR_WIDTH;
}
rowNode = (
<>
{fixedLeftCellGroupWidth ? (
<CellGroup
fixed="left"
height={props.isHeaderRow ? props.headerHeight : props.height}
width={fixedLeftCellGroupWidth}
style={
rtl
? { right: tableWidth.current - fixedLeftCellGroupWidth - rowRight }
: undefined
}
>
{mergeCells(resetLeftForCells(fixedLeftCells))}
</CellGroup>
) : null}
<CellGroup>{mergeCells(scrollCells)}</CellGroup>
{fixedRightCellGroupWidth ? (
<CellGroup
fixed="right"
style={
rtl
? { right: 0 - rowRight }
: { left: tableWidth.current - fixedRightCellGroupWidth }
}
height={props.isHeaderRow ? props.headerHeight : props.height}
width={fixedRightCellGroupWidth}
>
{mergeCells(
resetLeftForCells(fixedRightCells, hasVerticalScrollbar ? SCROLLBAR_WIDTH : 0)
)}
</CellGroup>
) : null}
{shouldRenderExpandedRow && renderRowExpanded(rowData)}
</>
);
} else {
rowNode = (
<>
<CellGroup>{mergeCells(cells)}</CellGroup>
{shouldRenderExpandedRow && renderRowExpanded(rowData)}
</>
);
}
return (
<Row {...restRowProps} data-depth={depth} style={rowStyles}>
{renderRowProp ? renderRowProp(rowNode, rowData) : rowNode}
</Row>
);
};
const renderTableHeader = (headerCells: any[], rowWidth: number) => {
const top = typeof affixHeader === 'number' ? affixHeader : 0;
const rowProps: TableRowProps = {
'aria-rowindex': 1,
rowRef: tableHeaderRef,
width: rowWidth,
height: getRowHeight(),
headerHeight,
isHeaderRow: true,
top: 0,
rowIndex: -1
};
const fixedStyle: React.CSSProperties = {
position: 'fixed',
overflow: 'hidden',
height: headerHeight,
width: tableWidth.current,
top
};
// Affix header
const header = (
<div className={prefix('affix-header')} style={fixedStyle} ref={affixHeaderWrapperRef}>
{renderRow(rowProps, headerCells)}
</div>
);
return (
<React.Fragment>
{(affixHeader === 0 || affixHeader) && header}
<div role="rowgroup" className={prefix('header-row-wrapper')} ref={headerWrapperRef}>
{renderRow(rowProps, headerCells)}
</div>
</React.Fragment>
);
};
const shouldRenderExpandedRow = useCallback(
(rowData: Row) => {
if (
isFunction(renderRowExpandedProp) &&
!isTree &&
rowKey &&
expandedRowKeys.some(key => key === rowData[rowKey])
) {
return true;
}
return false;
},
[expandedRowKeys, isTree, renderRowExpandedProp, rowKey]
);
const bindRowClick = useCallback(
(rowData: Row) => {
return (event: React.MouseEvent) => {
onRowClick?.(rowData, event);
};
},
[onRowClick]
);
const bindRowContextMenu = useCallback(
(rowData: Row) => {
return (event: React.MouseEvent) => {
onRowContextMenu?.(rowData, event);
};
},
[onRowContextMenu]
);
const handleTreeToggle = useCallback(
(treeRowKey: any, _rowIndex: number, rowData: Row) => {
let open = false;
const nextExpandedRowKeys: Key[] = [];
for (let i = 0; i < expandedRowKeys.length; i++) {
const key = expandedRowKeys[i];
if (key === treeRowKey) {
open = true;
} else {
nextExpandedRowKeys.push(key);
}
}
if (!open) {
nextExpandedRowKeys.push(treeRowKey);
}
setExpandedRowKeys(nextExpandedRowKeys);
onExpandChange?.(!open, rowData);
},
[expandedRowKeys, onExpandChange, setExpandedRowKeys]
);
/**
* Records the status of merged rows.
* { cellKey: [count,index]}
*/
const rowSpanState = useRef<{ [cellKey: string]: [number, number] }>({});
const renderRowData = (
bodyCells: any[],
rowData: any,
props: TableRowProps & { cellHeight?: number },
shouldRenderExpandedRow?: boolean
) => {
const hasChildren = isTree && rowData.children && Array.isArray(rowData.children);
const nextRowKey =
rowKey && typeof rowData[rowKey] !== 'undefined' ? rowData[rowKey] : props.key;
const { cellHeight, ...restRowProps } = props;
const rowProps: TableRowProps = {
...restRowProps,
key: nextRowKey,
'aria-rowindex': (props.key as number) + 2,
rowRef: bindTableRowsRef(props.key as any, rowData),
onClick: bindRowClick(rowData),
onContextMenu: bindRowContextMenu(rowData)
};
const expanded = expandedRowKeys.some(key => rowKey && key === rowData[rowKey]);
const cells: React.ReactNode[] = [];
for (let i = 0; i < bodyCells.length; i++) {
const cell = bodyCells[i];
const rowSpan: number = cell.props?.rowSpan?.(rowData);
const dataCellHeight = rowSpan ? rowSpan * (cellHeight || ROW_HEIGHT) : cellHeight;
const cellKey = cell.props.dataKey || i;
// Record the cell state of the merged row
if (rowSpanState.current[cellKey]?.[1] > 0) {
rowSpanState.current[cellKey][1] -= 1;
// Restart counting when merged to the last cell.
if (rowSpanState.current[cellKey][1] === 0) {
rowSpanState.current[cellKey][0] = 0;
}
}
if (rowSpan) {
// The state of the initial merged cell
rowSpanState.current[cellKey] = [rowSpan, rowSpan];
rowProps.rowSpan = rowSpan;
rowProps.style = { overflow: 'inherit' };
}
// Cells marked as deleted when checking for merged cell.
const removedCell =
cell.props?.rowSpan && !rowSpan && rowSpanState.current[cellKey]?.[0] !== 0
? true
: false;
cells.push(
React.cloneElement(cell, {
'aria-rowspan': rowSpan ? rowSpan : undefined,
hasChildren,
rowData,
rowIndex: props.rowIndex,
wordWrap,
height: dataCellHeight,
depth: props.depth,
renderTreeToggle,
onTreeToggle: handleTreeToggle,
rowKey: nextRowKey,
expanded,
rowSpan,
removed: removedCell
})
);
}
return renderRow(rowProps, cells, shouldRenderExpandedRow, rowData);
};
const renderScrollbar = () => {
const height = getTableHeight();
if (disabledScroll) {
return null;
}
const scrollbars: React.ReactNode[] = [];
if (hasHorizontalScrollbar) {
scrollbars.push(
<Scrollbar
key="scrollbar"
tableId={id}
style={{ width: tableWidth.current }}
length={tableWidth.current}
onScroll={onScrollHorizontal}
scrollLength={contentWidth.current}
ref={scrollbarXRef}
/>
);
}
if (hasVerticalScrollbar) {
scrollbars.push(
<Scrollbar
vertical
key="vertical-scrollbar"
tableId={id}
length={height - headerHeight}
onScroll={onScrollVertical}
scrollLength={contentHeight.current}
ref={scrollbarYRef}
/>
);
}
return scrollbars;
};
const renderTableBody = (bodyCells: any[], rowWidth: number) => {
const height = getTableHeight();
const bodyHeight = height - headerHeight;
const bodyStyles = {
top: headerHeight,
height: bodyHeight
};
let contentHeight = 0;
let topHideHeight = 0;
let bottomHideHeight = 0;
visibleRows.current = [];
if (data) {
let top = 0; // Row position
let minTop = Math.abs(scrollY.current);
let startHeight = 0;
if (typeof rowExpandedHeight === 'function') {
startHeight = data.length ? rowExpandedHeight(data[0]) : 100;
} else {
startHeight = rowExpandedHeight;
}
let maxTop = minTop + height + startHeight;
const isCustomRowHeight = typeof rowHeight === 'function';
const isUncertainHeight = !!renderRowExpandedProp || isCustomRowHeight || wordWrap;
// If virtualized is enabled and the row height in the Table is variable,
// you need to loop through the data to get the height of each row.
if ((isUncertainHeight && virtualized) || !virtualized) {
// Avoid white screens on the top and bottom of the table when touching and scrolling on the mobile terminal.
// So supplement the display data row.
if (isSupportTouchEvent()) {
const coveredHeight = height * 3;
minTop = Math.max(minTop - coveredHeight, 0);
maxTop = maxTop + coveredHeight;
}
for (let index = 0; index < data.length; index++) {
const rowData = data[index];
const maxHeight = tableRowsMaxHeight[index];
const expandedRow = shouldRenderExpandedRow(rowData);