-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathTable.tsx
1381 lines (1244 loc) · 45.7 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 {AriaLabelingProps, HoverEvents, Key, LinkDOMProps, RefObject} from '@react-types/shared';
import {BaseCollection, Collection, CollectionBuilder, CollectionNode, createBranchComponent, createLeafComponent, useCachedChildren} from '@react-aria/collections';
import {buildHeaderRows, TableColumnResizeState} from '@react-stately/table';
import {ButtonContext} from './Button';
import {CheckboxContext} from './RSPContexts';
import {CollectionProps, CollectionRendererContext, DefaultCollectionRenderer, ItemRenderProps} from './Collection';
import {ColumnSize, ColumnStaticSize, TableCollection as ITableCollection, TableProps as SharedTableProps} from '@react-types/table';
import {ContextValue, DEFAULT_SLOT, DOMProps, Provider, RenderProps, ScrollableProps, SlotProps, StyleProps, StyleRenderProps, useContextProps, useRenderProps} from './utils';
import {DisabledBehavior, DraggableCollectionState, DroppableCollectionState, MultipleSelectionState, Node, SelectionBehavior, SelectionMode, SortDirection, TableState, useMultipleSelectionState, useTableColumnResizeState, useTableState} from 'react-stately';
import {DragAndDropContext, DropIndicatorContext, DropIndicatorProps, useDndPersistedKeys, useRenderDropIndicator} from './DragAndDrop';
import {DragAndDropHooks} from './useDragAndDrop';
import {DraggableItemResult, DragPreviewRenderer, DropIndicatorAria, DroppableCollectionResult, FocusScope, ListKeyboardDelegate, mergeProps, useFocusRing, useHover, useLocale, useLocalizedStringFormatter, useTable, useTableCell, useTableColumnHeader, useTableColumnResize, useTableHeaderRow, useTableRow, useTableRowGroup, useTableSelectAllCheckbox, useTableSelectionCheckbox, useVisuallyHidden} from 'react-aria';
import {filterDOMProps, isScrollable, mergeRefs, useLayoutEffect, useObjectRef, useResizeObserver} from '@react-aria/utils';
import {GridNode} from '@react-types/grid';
// @ts-ignore
import intlMessages from '../intl/*.json';
import React, {createContext, ForwardedRef, forwardRef, JSX, ReactElement, ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState} from 'react';
import ReactDOM from 'react-dom';
class TableCollection<T> extends BaseCollection<T> implements ITableCollection<T> {
headerRows: GridNode<T>[] = [];
columns: GridNode<T>[] = [];
rows: GridNode<T>[] = [];
rowHeaderColumnKeys: Set<Key> = new Set();
head: CollectionNode<T> = new CollectionNode('tableheader', -1);
body: CollectionNode<T> = new CollectionNode('tablebody', -2);
columnsDirty = true;
addNode(node: CollectionNode<T>) {
super.addNode(node);
this.columnsDirty ||= node.type === 'column';
if (node.type === 'tableheader') {
this.head = node;
}
if (node.type === 'tablebody') {
this.body = node;
}
}
commit(firstKey: Key, lastKey: Key, isSSR = false) {
this.updateColumns(isSSR);
this.rows = [];
for (let row of this.getChildren(this.body.key)) {
let lastChildKey = (row as CollectionNode<T>).lastChildKey;
if (lastChildKey != null) {
let lastCell = this.getItem(lastChildKey) as GridNode<T>;
let numberOfCellsInRow = (lastCell.colIndex ?? lastCell.index) + (lastCell.colSpan ?? 1);
if (numberOfCellsInRow !== this.columns.length && !isSSR) {
throw new Error(`Cell count must match column count. Found ${numberOfCellsInRow} cells and ${this.columns.length} columns.`);
}
}
this.rows.push(row);
}
super.commit(firstKey, lastKey, isSSR);
}
private updateColumns(isSSR: boolean) {
if (!this.columnsDirty) {
return;
}
this.rowHeaderColumnKeys = new Set();
this.columns = [];
let columnKeyMap = new Map();
let visit = (node: Node<T>) => {
switch (node.type) {
case 'column':
columnKeyMap.set(node.key, node);
if (!node.hasChildNodes) {
node.index = this.columns.length;
this.columns.push(node);
if (node.props.isRowHeader) {
this.rowHeaderColumnKeys.add(node.key);
}
}
break;
}
for (let child of this.getChildren(node.key)) {
visit(child);
}
};
for (let node of this.getChildren(this.head.key)) {
visit(node);
}
this.headerRows = buildHeaderRows(columnKeyMap, this.columns);
this.columnsDirty = false;
if (this.rowHeaderColumnKeys.size === 0 && this.columns.length > 0 && !isSSR) {
throw new Error('A table must have at least one Column with the isRowHeader prop set to true');
}
}
get columnCount() {
return this.columns.length;
}
*[Symbol.iterator]() {
// Wait until the collection is initialized.
if (this.head.key === -1) {
return;
}
yield this.head;
yield this.body;
}
get size() {
return this.rows.length;
}
getFirstKey() {
return this.body.firstChildKey;
}
getLastKey() {
return this.body.lastChildKey;
}
getKeyAfter(key: Key) {
let node = this.getItem(key);
if (node?.type === 'column') {
return node.nextKey ?? null;
}
return super.getKeyAfter(key);
}
getKeyBefore(key: Key) {
let node = this.getItem(key);
if (node?.type === 'column') {
return node.prevKey ?? null;
}
let k = super.getKeyBefore(key);
if (k != null && this.getItem(k)?.type === 'tablebody') {
return null;
}
return k;
}
getChildren(key: Key): Iterable<Node<T>> {
if (!this.getItem(key)) {
for (let row of this.headerRows) {
if (row.key === key) {
return row.childNodes;
}
}
}
return super.getChildren(key);
}
clone() {
let collection = super.clone();
collection.headerRows = this.headerRows;
collection.columns = this.columns;
collection.rowHeaderColumnKeys = this.rowHeaderColumnKeys;
collection.head = this.head;
collection.body = this.body;
return collection;
}
getTextValue(key: Key): string {
let row = this.getItem(key);
if (!row) {
return '';
}
// If the row has a textValue, use that.
if (row.textValue) {
return row.textValue;
}
// Otherwise combine the text of each of the row header columns.
let rowHeaderColumnKeys = this.rowHeaderColumnKeys;
let text: string[] = [];
for (let cell of this.getChildren(key)) {
let column = this.columns[cell.index!];
if (rowHeaderColumnKeys.has(column.key) && cell.textValue) {
text.push(cell.textValue);
}
if (text.length === rowHeaderColumnKeys.size) {
break;
}
}
return text.join(' ');
}
}
interface ResizableTableContainerContextValue {
tableWidth: number,
tableRef: RefObject<HTMLTableElement | null>,
scrollRef: RefObject<HTMLElement | null>,
// Dependency inject useTableColumnResizeState so it doesn't affect bundle size unless you're using ResizableTableContainer.
useTableColumnResizeState: typeof useTableColumnResizeState,
onResizeStart?: (widths: Map<Key, ColumnSize>) => void,
onResize?: (widths: Map<Key, ColumnSize>) => void,
onResizeEnd?: (widths: Map<Key, ColumnSize>) => void
}
const ResizableTableContainerContext = createContext<ResizableTableContainerContextValue | null>(null);
export interface ResizableTableContainerProps extends DOMProps, ScrollableProps<HTMLDivElement> {
/**
* Handler that is called when a user starts a column resize.
*/
onResizeStart?: (widths: Map<Key, ColumnSize>) => void,
/**
* Handler that is called when a user performs a column resize.
* Can be used with the width property on columns to put the column widths into
* a controlled state.
*/
onResize?: (widths: Map<Key, ColumnSize>) => void,
/**
* Handler that is called after a user performs a column resize.
* Can be used to store the widths of columns for another future session.
*/
onResizeEnd?: (widths: Map<Key, ColumnSize>) => void
}
export const ResizableTableContainer = forwardRef(function ResizableTableContainer(props: ResizableTableContainerProps, ref: ForwardedRef<HTMLDivElement>) {
let containerRef = useObjectRef(ref);
let tableRef = useRef<HTMLTableElement>(null);
let scrollRef = useRef<HTMLElement | null>(null);
let [width, setWidth] = useState(0);
useLayoutEffect(() => {
// Walk up the DOM from the Table to the ResizableTableContainer and stop
// when we reach the first scrollable element. This is what we'll measure
// to determine column widths (important due to width of scrollbars).
// This will usually be the ResizableTableContainer for native tables, and
// the Table itself for virtualized tables.
let table = tableRef.current as HTMLElement | null;
while (table && table !== containerRef.current && !isScrollable(table)) {
table = table.parentElement;
}
scrollRef.current = table;
}, [containerRef]);
useResizeObserver({
ref: scrollRef,
box: 'border-box',
onResize() {
setWidth(scrollRef.current?.clientWidth ?? 0);
}
});
useLayoutEffect(() => {
setWidth(scrollRef.current?.clientWidth ?? 0);
}, []);
let ctx = useMemo(() => ({
tableRef,
scrollRef,
tableWidth: width,
useTableColumnResizeState,
onResizeStart: props.onResizeStart,
onResize: props.onResize,
onResizeEnd: props.onResizeEnd
}), [tableRef, width, props.onResizeStart, props.onResize, props.onResizeEnd]);
return (
<div
{...filterDOMProps(props as any)}
ref={containerRef}
className={props.className || 'react-aria-ResizableTableContainer'}
style={props.style}
onScroll={props.onScroll}>
<ResizableTableContainerContext.Provider value={ctx}>
{props.children}
</ResizableTableContainerContext.Provider>
</div>
);
});
export const TableContext = createContext<ContextValue<TableProps, HTMLTableElement>>(null);
export const TableStateContext = createContext<TableState<any> | null>(null);
export const TableColumnResizeStateContext = createContext<TableColumnResizeState<unknown> | null>(null);
export interface TableRenderProps {
/**
* Whether the table is currently focused.
* @selector [data-focused]
*/
isFocused: boolean,
/**
* Whether the table is currently keyboard focused.
* @selector [data-focus-visible]
*/
isFocusVisible: boolean,
/**
* Whether the table is currently the active drop target.
* @selector [data-drop-target]
*/
isDropTarget: boolean,
/**
* State of the table.
*/
state: TableState<unknown>
}
export interface TableProps extends Omit<SharedTableProps<any>, 'children'>, StyleRenderProps<TableRenderProps>, SlotProps, AriaLabelingProps, ScrollableProps<HTMLTableElement> {
/** The elements that make up the table. Includes the TableHeader, TableBody, Columns, and Rows. */
children?: ReactNode,
/**
* How multiple selection should behave in the collection.
* @default "toggle"
*/
selectionBehavior?: SelectionBehavior,
/**
* Whether `disabledKeys` applies to all interactions, or only selection.
* @default "selection"
*/
disabledBehavior?: DisabledBehavior,
/** Handler that is called when a user performs an action on the row. */
onRowAction?: (key: Key) => void,
/** The drag and drop hooks returned by `useDragAndDrop` used to enable drag and drop behavior for the Table. */
dragAndDropHooks?: DragAndDropHooks
}
/**
* A table displays data in rows and columns and enables a user to navigate its contents via directional navigation keys,
* and optionally supports row selection and sorting.
*/
export const Table = forwardRef(function Table(props: TableProps, ref: ForwardedRef<HTMLTableElement>) {
[props, ref] = useContextProps(props, ref, TableContext);
// Separate selection state so we have access to it from collection components via useTableOptions.
let selectionState = useMultipleSelectionState(props);
let {selectionBehavior, selectionMode, disallowEmptySelection} = selectionState;
let hasDragHooks = !!props.dragAndDropHooks?.useDraggableCollectionState;
let ctx = useMemo(() => ({
selectionBehavior: selectionMode === 'none' ? null : selectionBehavior,
selectionMode,
disallowEmptySelection,
allowsDragging: hasDragHooks
}), [selectionBehavior, selectionMode, disallowEmptySelection, hasDragHooks]);
let content = (
<TableOptionsContext.Provider value={ctx}>
<Collection {...props} />
</TableOptionsContext.Provider>
);
return (
<CollectionBuilder content={content} createCollection={() => new TableCollection<any>()}>
{collection => <TableInner props={props} forwardedRef={ref} selectionState={selectionState} collection={collection} />}
</CollectionBuilder>
);
});
interface TableInnerProps {
props: TableProps,
forwardedRef: ForwardedRef<HTMLTableElement>,
selectionState: MultipleSelectionState,
collection: ITableCollection<Node<object>>
}
function TableInner({props, forwardedRef: ref, selectionState, collection}: TableInnerProps) {
let tableContainerContext = useContext(ResizableTableContainerContext);
ref = useObjectRef(useMemo(() => mergeRefs(ref, tableContainerContext?.tableRef), [ref, tableContainerContext?.tableRef]));
let state = useTableState({
...props,
collection,
children: undefined,
UNSAFE_selectionState: selectionState
});
let {isVirtualized, layoutDelegate, dropTargetDelegate: ctxDropTargetDelegate, CollectionRoot} = useContext(CollectionRendererContext);
let {dragAndDropHooks} = props;
let {gridProps} = useTable({
...props,
layoutDelegate,
isVirtualized
}, state, ref);
let selectionManager = state.selectionManager;
let hasDragHooks = !!dragAndDropHooks?.useDraggableCollectionState;
let hasDropHooks = !!dragAndDropHooks?.useDroppableCollectionState;
let dragHooksProvided = useRef(hasDragHooks);
let dropHooksProvided = useRef(hasDropHooks);
useEffect(() => {
if (dragHooksProvided.current !== hasDragHooks) {
console.warn('Drag hooks were provided during one render, but not another. This should be avoided as it may produce unexpected behavior.');
}
if (dropHooksProvided.current !== hasDropHooks) {
console.warn('Drop hooks were provided during one render, but not another. This should be avoided as it may produce unexpected behavior.');
}
}, [hasDragHooks, hasDropHooks]);
let dragState: DraggableCollectionState | undefined = undefined;
let dropState: DroppableCollectionState | undefined = undefined;
let droppableCollection: DroppableCollectionResult | undefined = undefined;
let isRootDropTarget = false;
let dragPreview: JSX.Element | null = null;
let preview = useRef<DragPreviewRenderer>(null);
if (hasDragHooks && dragAndDropHooks) {
dragState = dragAndDropHooks.useDraggableCollectionState!({
collection,
selectionManager,
preview: dragAndDropHooks.renderDragPreview ? preview : undefined
});
dragAndDropHooks.useDraggableCollection!({}, dragState, ref);
let DragPreview = dragAndDropHooks.DragPreview!;
dragPreview = dragAndDropHooks.renderDragPreview
? <DragPreview ref={preview}>{dragAndDropHooks.renderDragPreview}</DragPreview>
: null;
}
if (hasDropHooks && dragAndDropHooks) {
dropState = dragAndDropHooks.useDroppableCollectionState!({
collection,
selectionManager
});
let keyboardDelegate = new ListKeyboardDelegate({
collection,
disabledKeys: selectionManager.disabledKeys,
disabledBehavior: selectionManager.disabledBehavior,
ref,
layoutDelegate
});
let dropTargetDelegate = dragAndDropHooks.dropTargetDelegate || ctxDropTargetDelegate || new dragAndDropHooks.ListDropTargetDelegate(collection.rows, ref);
droppableCollection = dragAndDropHooks.useDroppableCollection!({
keyboardDelegate,
dropTargetDelegate
}, dropState, ref);
isRootDropTarget = dropState.isDropTarget({type: 'root'});
}
let {focusProps, isFocused, isFocusVisible} = useFocusRing();
let renderProps = useRenderProps({
className: props.className,
style: props.style,
defaultClassName: 'react-aria-Table',
values: {
isDropTarget: isRootDropTarget,
isFocused,
isFocusVisible,
state
}
});
let isListDraggable = !!(hasDragHooks && !dragState?.isDisabled);
let style = renderProps.style;
let layoutState: TableColumnResizeState<unknown> | null = null;
if (tableContainerContext) {
layoutState = tableContainerContext.useTableColumnResizeState({
tableWidth: tableContainerContext.tableWidth
}, state);
if (!isVirtualized) {
style = {
...style,
tableLayout: 'fixed',
width: 'fit-content'
};
}
}
let ElementType = useElementType('table');
return (
<Provider
values={[
[TableStateContext, state],
[TableColumnResizeStateContext, layoutState],
[DragAndDropContext, {dragAndDropHooks, dragState, dropState}],
[DropIndicatorContext, {render: TableDropIndicatorWrapper}]
]}>
<FocusScope>
<ElementType
{...filterDOMProps(props)}
{...renderProps}
{...mergeProps(gridProps, focusProps, droppableCollection?.collectionProps)}
style={style}
ref={ref}
slot={props.slot || undefined}
onScroll={props.onScroll}
data-allows-dragging={isListDraggable || undefined}
data-drop-target={isRootDropTarget || undefined}
data-focused={isFocused || undefined}
data-focus-visible={isFocusVisible || undefined}>
<CollectionRoot
collection={collection}
scrollRef={tableContainerContext?.scrollRef ?? ref}
persistedKeys={useDndPersistedKeys(selectionManager, dragAndDropHooks, dropState)} />
</ElementType>
</FocusScope>
{dragPreview}
</Provider>
);
}
function useElementType<E extends keyof JSX.IntrinsicElements>(element: E): E | 'div' {
let {isVirtualized} = useContext(CollectionRendererContext);
return isVirtualized ? 'div' : element;
}
export interface TableOptionsContextValue {
/** The type of selection that is allowed in the table. */
selectionMode: SelectionMode,
/** The selection behavior for the table. If selectionMode is `"none"`, this will be `null`. */
selectionBehavior: SelectionBehavior | null,
/** Whether the table allows empty selection. */
disallowEmptySelection: boolean,
/** Whether the table allows rows to be dragged. */
allowsDragging: boolean
}
const TableOptionsContext = createContext<TableOptionsContextValue | null>(null);
/**
* Returns options from the parent `<Table>` component.
*/
export function useTableOptions(): TableOptionsContextValue {
return useContext(TableOptionsContext)!;
}
export interface TableHeaderRenderProps {
/**
* Whether the table header is currently hovered with a mouse.
* @selector [data-hovered]
*/
isHovered: boolean
}
export interface TableHeaderProps<T> extends StyleRenderProps<TableHeaderRenderProps>, HoverEvents {
/** A list of table columns. */
columns?: Iterable<T>,
/** A list of `Column(s)` or a function. If the latter, a list of columns must be provided using the `columns` prop. */
children?: ReactNode | ((item: T) => ReactElement),
/** Values that should invalidate the column cache when using dynamic collections. */
dependencies?: ReadonlyArray<any>
}
/**
* A header within a `<Table>`, containing the table columns.
*/
export const TableHeader = /*#__PURE__*/ createBranchComponent(
'tableheader',
<T extends object>(props: TableHeaderProps<T>, ref: ForwardedRef<HTMLTableSectionElement>) => {
let collection = useContext(TableStateContext)!.collection as TableCollection<unknown>;
let headerRows = useCachedChildren({
items: collection.headerRows,
children: useCallback((item: Node<unknown>) => {
switch (item.type) {
case 'headerrow':
return <TableHeaderRow item={item} />;
default:
throw new Error('Unsupported node type in TableHeader: ' + item.type);
}
}, [])
});
let THead = useElementType('thead');
let {rowGroupProps} = useTableRowGroup();
let {hoverProps, isHovered} = useHover({
onHoverStart: props.onHoverStart,
onHoverChange: props.onHoverChange,
onHoverEnd: props.onHoverEnd
});
let renderProps = useRenderProps({
className: props.className,
style: props.style,
defaultClassName: 'react-aria-TableHeader',
values: {
isHovered
}
});
return (
<THead
{...mergeProps(filterDOMProps(props as any), rowGroupProps, hoverProps)}
{...renderProps}
ref={ref}
data-hovered={isHovered || undefined}>
{headerRows}
</THead>
);
},
props => (
<Collection dependencies={props.dependencies} items={props.columns}>
{props.children}
</Collection>
)
);
function TableHeaderRow({item}: {item: GridNode<any>}) {
let ref = useRef<HTMLTableRowElement>(null);
let state = useContext(TableStateContext)!;
let {isVirtualized, CollectionBranch} = useContext(CollectionRendererContext);
let {rowProps} = useTableHeaderRow({node: item, isVirtualized}, state, ref);
let {checkboxProps} = useTableSelectAllCheckbox(state);
let TR = useElementType('tr');
return (
<TR {...rowProps} ref={ref}>
<Provider
values={[
[CheckboxContext, {
slots: {
selection: checkboxProps
}
}]
]}>
<CollectionBranch collection={state.collection} parent={item} />
</Provider>
</TR>
);
}
export interface ColumnRenderProps {
/**
* Whether the item is currently hovered with a mouse.
* @selector [data-hovered]
*/
isHovered: boolean,
/**
* Whether the item is currently focused.
* @selector [data-focused]
*/
isFocused: boolean,
/**
* Whether the item is currently keyboard focused.
* @selector [data-focus-visible]
*/
isFocusVisible: boolean,
/**
* Whether the column allows sorting.
* @selector [data-allows-sorting]
*/
allowsSorting: boolean,
/**
* The current sort direction.
* @selector [data-sort-direction="ascending | descending"]
*/
sortDirection: SortDirection | undefined,
/**
* Whether the column is currently being resized.
* @selector [data-resizing]
*/
isResizing: boolean,
/**
* Triggers sorting for this column in the given direction.
*/
sort(direction: SortDirection): void,
/**
* Starts column resizing if the table is contained in a `<ResizableTableContainer>` element.
*/
startResize(): void
}
export interface ColumnProps extends RenderProps<ColumnRenderProps> {
/** The unique id of the column. */
id?: Key,
/** Whether the column allows sorting. */
allowsSorting?: boolean,
/** Whether a column is a [row header](https://www.w3.org/TR/wai-aria-1.1/#rowheader) and should be announced by assistive technology during row navigation. */
isRowHeader?: boolean,
/** A string representation of the column's contents, used for accessibility announcements. */
textValue?: string,
/** The width of the column. This prop only applies when the `<Table>` is wrapped in a `<ResizableTableContainer>`. */
width?: ColumnSize | null,
/** The default width of the column. This prop only applies when the `<Table>` is wrapped in a `<ResizableTableContainer>`. */
defaultWidth?: ColumnSize | null,
/** The minimum width of the column. This prop only applies when the `<Table>` is wrapped in a `<ResizableTableContainer>`. */
minWidth?: ColumnStaticSize | null,
/** The maximum width of the column. This prop only applies when the `<Table>` is wrapped in a `<ResizableTableContainer>`. */
maxWidth?: ColumnStaticSize | null
}
/**
* A column within a `<Table>`.
*/
export const Column = /*#__PURE__*/ createLeafComponent('column', (props: ColumnProps, forwardedRef: ForwardedRef<HTMLTableCellElement>, column: GridNode<unknown>) => {
let ref = useObjectRef<HTMLTableHeaderCellElement>(forwardedRef);
let state = useContext(TableStateContext)!;
let {isVirtualized} = useContext(CollectionRendererContext);
let {columnHeaderProps} = useTableColumnHeader(
{node: column, isVirtualized},
state,
ref
);
let {isFocused, isFocusVisible, focusProps} = useFocusRing();
let layoutState = useContext(TableColumnResizeStateContext);
let isResizing = false;
if (layoutState) {
isResizing = layoutState.resizingColumn === column.key;
} else {
for (let prop in ['width', 'defaultWidth', 'minWidth', 'maxWidth']) {
if (prop in column.props) {
console.warn(`The ${prop} prop on a <Column> only applies when a <Table> is wrapped in a <ResizableTableContainer>. If you aren't using column resizing, you can set the width of a column with CSS.`);
}
}
}
let {hoverProps, isHovered} = useHover({isDisabled: !props.allowsSorting});
let renderProps = useRenderProps({
...props,
id: undefined,
children: column.rendered,
defaultClassName: 'react-aria-Column',
values: {
isHovered,
isFocused,
isFocusVisible,
allowsSorting: column.props.allowsSorting,
sortDirection: state.sortDescriptor?.column === column.key
? state.sortDescriptor.direction
: undefined,
isResizing,
startResize: () => {
if (layoutState) {
layoutState.startResize(column.key);
state.setKeyboardNavigationDisabled(true);
} else {
throw new Error('Wrap your <Table> in a <ResizableTableContainer> to enable column resizing');
}
},
sort: (direction) => {
state.sort(column.key, direction);
}
}
});
let style = renderProps.style;
if (layoutState) {
style = {...style, width: layoutState.getColumnWidth(column.key)};
}
let TH = useElementType('th');
return (
<TH
{...mergeProps(filterDOMProps(props as any), columnHeaderProps, focusProps, hoverProps)}
{...renderProps}
style={style}
ref={ref}
data-hovered={isHovered || undefined}
data-focused={isFocused || undefined}
data-focus-visible={isFocusVisible || undefined}
data-resizing={isResizing || undefined}
data-allows-sorting={column.props.allowsSorting || undefined}
data-sort-direction={state.sortDescriptor?.column === column.key ? state.sortDescriptor.direction : undefined}>
<Provider
values={[
[ColumnResizerContext, {column, triggerRef: ref}],
[CollectionRendererContext, DefaultCollectionRenderer]
]}>
{renderProps.children}
</Provider>
</TH>
);
});
export interface ColumnResizerRenderProps {
/**
* Whether the resizer is currently hovered with a mouse.
* @selector [data-hovered]
*/
isHovered: boolean,
/**
* Whether the resizer is currently focused.
* @selector [data-focused]
*/
isFocused: boolean,
/**
* Whether the resizer is currently keyboard focused.
* @selector [data-focus-visible]
*/
isFocusVisible: boolean,
/**
* Whether the resizer is currently being resized.
* @selector [data-resizing]
*/
isResizing: boolean,
/**
* The direction that the column is currently resizable.
* @selector [data-resizable-direction="right | left | both"]
*/
resizableDirection: 'right' | 'left' | 'both'
}
export interface ColumnResizerProps extends HoverEvents, RenderProps<ColumnResizerRenderProps> {
/** A custom accessibility label for the resizer. */
'aria-label'?: string
}
interface ColumnResizerContextValue {
column: GridNode<unknown>,
triggerRef: RefObject<HTMLDivElement | null>
}
const ColumnResizerContext = createContext<ColumnResizerContextValue | null>(null);
export const ColumnResizer = forwardRef(function ColumnResizer(props: ColumnResizerProps, ref: ForwardedRef<HTMLDivElement>) {
let layoutState = useContext(TableColumnResizeStateContext);
if (!layoutState) {
throw new Error('Wrap your <Table> in a <ResizableTableContainer> to enable column resizing');
}
let stringFormatter = useLocalizedStringFormatter(intlMessages, 'react-aria-components');
let {onResizeStart, onResize, onResizeEnd} = useContext(ResizableTableContainerContext)!;
let {column, triggerRef} = useContext(ColumnResizerContext)!;
let inputRef = useRef<HTMLInputElement>(null);
let {resizerProps, inputProps, isResizing} = useTableColumnResize(
{
column,
'aria-label': props['aria-label'] || stringFormatter.format('tableResizer'),
onResizeStart,
onResize,
onResizeEnd,
triggerRef
},
layoutState,
inputRef
);
let {focusProps, isFocused, isFocusVisible} = useFocusRing();
let {hoverProps, isHovered} = useHover(props);
let isEResizable = layoutState.getColumnMinWidth(column.key) >= layoutState.getColumnWidth(column.key);
let isWResizable = layoutState.getColumnMaxWidth(column.key) <= layoutState.getColumnWidth(column.key);
let {direction} = useLocale();
let resizableDirection: ColumnResizerRenderProps['resizableDirection'] = 'both';
if (isEResizable) {
resizableDirection = direction === 'rtl' ? 'right' : 'left';
} else if (isWResizable) {
resizableDirection = direction === 'rtl' ? 'left' : 'right';
} else {
resizableDirection = 'both';
}
let objectRef = useObjectRef(ref);
let [cursor, setCursor] = useState('');
useEffect(() => {
if (!objectRef.current) {
return;
}
let style = window.getComputedStyle(objectRef.current);
setCursor(style.cursor);
}, [objectRef, resizableDirection]);
let renderProps = useRenderProps({
...props,
defaultClassName: 'react-aria-ColumnResizer',
values: {
isFocused,
isFocusVisible,
isResizing,
isHovered,
resizableDirection
}
});
let [isMouseDown, setMouseDown] = useState(false);
let onPointerDown = (e: PointerEvent) => {
if (e.pointerType === 'mouse') {
setMouseDown(true);
}
};
if (!isResizing && isMouseDown) {
setMouseDown(false);
}
return (
<div
ref={objectRef}
role="presentation"
{...filterDOMProps(props as any)}
{...renderProps}
{...mergeProps(resizerProps, {onPointerDown}, hoverProps)}
data-hovered={isHovered || undefined}
data-focused={isFocused || undefined}
data-focus-visible={isFocusVisible || undefined}
data-resizing={isResizing || undefined}
data-resizable-direction={resizableDirection}>
{renderProps.children}
<input
ref={inputRef}
{...mergeProps(inputProps, focusProps)} />
{isResizing && isMouseDown && ReactDOM.createPortal(<div style={{position: 'fixed', top: 0, left: 0, bottom: 0, right: 0, cursor}} />, document.body)}
</div>
);
});
export interface TableBodyRenderProps {
/**
* Whether the table body has no rows and should display its empty state.
* @selector [data-empty]
*/
isEmpty: boolean,
/**
* Whether the Table is currently the active drop target.
* @selector [data-drop-target]
*/
isDropTarget: boolean
}
export interface TableBodyProps<T> extends CollectionProps<T>, StyleRenderProps<TableBodyRenderProps> {
/** Provides content to display when there are no rows in the table. */
renderEmptyState?: (props: TableBodyRenderProps) => ReactNode
}
/**
* The body of a `<Table>`, containing the table rows.
*/
export const TableBody = /*#__PURE__*/ createBranchComponent('tablebody', <T extends object>(props: TableBodyProps<T>, ref: ForwardedRef<HTMLTableSectionElement>) => {
let state = useContext(TableStateContext)!;
let {isVirtualized} = useContext(CollectionRendererContext);
let collection = state.collection;
let {CollectionBranch} = useContext(CollectionRendererContext);
let {dragAndDropHooks, dropState} = useContext(DragAndDropContext);
let isDroppable = !!dragAndDropHooks?.useDroppableCollectionState && !dropState?.isDisabled;
let isRootDropTarget = isDroppable && !!dropState && (dropState.isDropTarget({type: 'root'}) ?? false);
let renderValues = {
isDropTarget: isRootDropTarget,
isEmpty: collection.size === 0
};
let renderProps = useRenderProps({
...props,
id: undefined,
children: undefined,
defaultClassName: 'react-aria-TableBody',
values: renderValues
});
let emptyState;
let TR = useElementType('tr');
let TD = useElementType('td');
let numColumns = collection.columnCount;
if (collection.size === 0 && props.renderEmptyState && state) {
let rowProps = {};
let rowHeaderProps = {};
let style = {};
if (isVirtualized) {
rowProps['aria-rowindex'] = collection.headerRows.length + 1;
rowHeaderProps['aria-colspan'] = numColumns;
style = {display: 'contents'};
} else {
rowHeaderProps['colSpan'] = numColumns;
}
emptyState = (
<TR role="row" {...rowProps} style={style}>
<TD role="rowheader" {...rowHeaderProps} style={style}>
{props.renderEmptyState(renderValues)}
</TD>
</TR>
);
}
let {rowGroupProps} = useTableRowGroup();
let TBody = useElementType('tbody');
// TODO: TableBody doesn't support being the scrollable body of the table yet, to revisit if needed. Would need to
// call useLoadMore here and walk up the DOM to the nearest scrollable element to set scrollRef
return (
<TBody
{...mergeProps(filterDOMProps(props as any), rowGroupProps)}
{...renderProps}
ref={ref}
data-empty={collection.size === 0 || undefined}>
{isDroppable && <RootDropIndicator />}
<CollectionBranch
collection={collection}
parent={collection.body}
renderDropIndicator={useRenderDropIndicator(dragAndDropHooks, dropState)} />
{emptyState}
</TBody>
);
});
export interface RowRenderProps extends ItemRenderProps {
/** Whether the row's children have keyboard focus. */
isFocusVisibleWithin: boolean
}
export interface RowProps<T> extends StyleRenderProps<RowRenderProps>, LinkDOMProps, HoverEvents {
/** The unique id of the row. */
id?: Key,
/** A list of columns used when dynamically rendering cells. */
columns?: Iterable<T>,
/** The cells within the row. Supports static items or a function for dynamic rendering. */
children?: ReactNode | ((item: T) => ReactElement),