-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathTableView.tsx
More file actions
1627 lines (1529 loc) · 52 KB
/
TableView.tsx
File metadata and controls
1627 lines (1529 loc) · 52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
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
/*
* Copyright 2024 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import {ActionButton, ActionButtonContext} from './ActionButton';
import {baseColor, centerPadding, colorMix, focusRing, fontRelative, lightDark, setColorScheme, space, style} from '../style' with {type: 'macro'};
import {Button, ButtonContext} from 'react-aria-components/Button';
import {ButtonGroup} from './ButtonGroup';
import {
CellRenderProps,
ColumnRenderProps,
ColumnResizer,
Cell as RACCell,
CellProps as RACCellProps,
Column as RACColumn,
ColumnProps as RACColumnProps,
Row as RACRow,
RowProps as RACRowProps,
Table as RACTable,
TableBody as RACTableBody,
TableBodyProps as RACTableBodyProps,
TableHeader as RACTableHeader,
TableHeaderProps as RACTableHeaderProps,
TableProps as RACTableProps,
ResizableTableContainer,
RowRenderProps,
TableBodyRenderProps,
TableLoadMoreItem,
TableRenderProps,
useTableOptions
} from 'react-aria-components/Table';
import {Checkbox} from './Checkbox';
import Checkmark from '../s2wf-icons/S2_Icon_Checkmark_20_N.svg';
import Chevron from '../ui-icons/Chevron';
import Close from '../s2wf-icons/S2_Icon_Close_20_N.svg';
import {Collection} from 'react-aria/Collection';
import {CollectionRendererContext, DefaultCollectionRenderer} from 'react-aria-components/CollectionBuilder';
import {ColumnSize} from 'react-stately/useTableState';
import {ContextValue, DEFAULT_SLOT, Provider, useSlottedContext} from 'react-aria-components/slots';
import {controlFont, getAllowedOverrides, StylesPropWithHeight, UnsafeStyles} from './style-utils' with {type: 'macro'};
import {css} from '../style/style-macro' with {type: 'macro'};
import {CustomDialog} from './CustomDialog';
import {DialogContainer} from './DialogContainer';
import {DOMProps, DOMRef, DOMRefValue, forwardRefType, GlobalDOMAttributes, LinkDOMProps, LoadingState, Node} from '@react-types/shared';
import {Form} from 'react-aria-components/Form';
import {getActiveElement, isFocusWithin, nodeContains} from 'react-aria/private/utils/shadowdom/DOMFunctions';
import {getOwnerDocument} from 'react-aria/private/utils/domHelpers';
import {GridNode} from 'react-stately/private/grid/GridCollection';
import {IconContext} from './Icon';
import intlMessages from '../intl/*.json';
import {Key} from '@react-types/shared';
import {LayoutNode} from 'react-stately/useVirtualizerState';
import {Menu, MenuItem, MenuSection, MenuTrigger} from './Menu';
import Nubbin from '../ui-icons/S2_MoveHorizontalTableWidget.svg';
import {OverlayTriggerStateContext} from 'react-aria-components/Dialog';
import {ProgressCircle} from './ProgressCircle';
import {CheckboxContext as RACCheckboxContext} from 'react-aria-components/Checkbox';
// @ts-ignore
import {Popover as RACPopover} from 'react-aria-components/Popover';
import React, {createContext, CSSProperties, FormEvent, FormHTMLAttributes, ForwardedRef, forwardRef, ReactElement, ReactNode, RefObject, useCallback, useContext, useEffect, useMemo, useRef, useState} from 'react';
import {Rect, TableLayout, Virtualizer} from 'react-aria-components/Virtualizer';
import SortDownArrow from '../s2wf-icons/S2_Icon_SortDown_20_N.svg';
import SortUpArrow from '../s2wf-icons/S2_Icon_SortUp_20_N.svg';
import {Button as SpectrumButton} from './Button';
import {useActionBarContainer} from './ActionBar';
import {useDOMRef} from './useDOMRef';
import {useLayoutEffect} from 'react-aria/private/utils/useLayoutEffect';
import {useLocale} from 'react-aria/I18nProvider';
import {useLocalizedStringFormatter} from 'react-aria/useLocalizedStringFormatter';
import {useMediaQuery} from './useMediaQuery';
import {useObjectRef} from 'react-aria/useObjectRef';
import {useScale} from './utils';
import {useSpectrumContextProps} from './useSpectrumContextProps';
import {VisuallyHidden} from 'react-aria/VisuallyHidden';
interface S2TableProps {
/** Whether the Table should be displayed with a quiet style. */
isQuiet?: boolean,
/**
* Sets the amount of vertical padding within each cell.
* @default 'regular'
*/
density?: 'compact' | 'spacious' | 'regular',
/**
* Sets the overflow behavior for the cell contents.
* @default 'truncate'
*/
overflowMode?: 'wrap' | 'truncate',
// TODO: will we contine with onAction or rename to onRowAction like it is in RAC?
/** Handler that is called when a user performs an action on a row. */
onAction?: (key: Key) => void,
/**
* 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,
/** The current loading state of the table. */
loadingState?: LoadingState,
/** Handler that is called when more items should be loaded, e.g. while scrolling near the bottom. */
onLoadMore?: () => any,
/** Provides the ActionBar to display when rows are selected in the TableView. */
renderActionBar?: (selectedKeys: 'all' | Set<Key>) => ReactElement
}
// TODO: Note that loadMore and loadingState are now on the Table instead of on the TableBody
export interface TableViewProps extends Omit<RACTableProps, 'style' | 'className' | 'render' | 'onRowAction' | 'selectionBehavior' | 'onScroll' | 'onCellAction' | 'dragAndDropHooks' | keyof GlobalDOMAttributes>, DOMProps, UnsafeStyles, S2TableProps {
/** Spectrum-defined styles, returned by the `style()` macro. */
styles?: StylesPropWithHeight
}
let InternalTableContext = createContext<TableViewProps & {layout?: S2TableLayout<unknown>, setIsInResizeMode?:(val: boolean) => void, isInResizeMode?: boolean, selectionMode?: 'none' | 'single' | 'multiple'}>({});
const tableWrapper = style({
minHeight: 0,
minWidth: 0,
display: 'flex',
isolation: 'isolate',
disableTapHighlight: true,
position: 'relative',
// Clip ActionBar animation.
overflow: 'clip'
}, getAllowedOverrides({height: true}));
const table = style<TableRenderProps & S2TableProps & {isCheckboxSelection?: boolean}>({
width: 'full',
height: 'full',
boxSizing: 'border-box',
userSelect: 'none',
minHeight: 0,
minWidth: 0,
fontFamily: 'sans',
fontWeight: 'normal',
overflow: 'auto',
backgroundColor: {
default: 'gray-25',
isQuiet: 'transparent',
forcedColors: 'Background'
},
borderColor: 'gray-300',
borderStyle: 'solid',
borderWidth: {
default: 1,
isQuiet: 0
},
...focusRing(),
outlineOffset: -1, // Cover the border
borderRadius: {
default: '[6px]',
isQuiet: 'none'
},
// Multiple browser bugs from scrollIntoView and scrollPadding:
// Bug: Table doesn't scroll items into view perfectly in Chrome
// https://issues.chromium.org/issues/365913982
// Bug: Table scrolls to the left when navigating up/down through the checkboxes when body is scrolled to the right.
// https://issues.chromium.org/issues/40067778
// https://bugs.webkit.org/show_bug.cgi?id=272799
// Base reproduction: https://codepen.io/lfdanlu/pen/zYVVGPW
scrollPaddingTop: 32,
scrollPaddingStart: {
isCheckboxSelection: 40
}
});
// component-height-100
const DEFAULT_HEADER_HEIGHT = {
medium: 32,
large: 40
};
const ROW_HEIGHTS = {
compact: {
medium: 32, // table-row-height-medium-compact (aka component-height-100)
large: 40
},
regular: {
medium: 40, // table-row-height-medium-regular
large: 50
},
spacious: {
medium: 48, // table-row-height-medium-spacious
large: 60
}
};
export class S2TableLayout<T> extends TableLayout<T> {
protected isStickyColumn(node: GridNode<T>): boolean {
return node.props.isSticky;
}
protected buildCollection(): LayoutNode[] {
let [header, body] = super.buildCollection();
if (!header) {
return [];
}
let {layoutInfo} = body;
// TableLayout's buildCollection always sets the body width to the max width between the header width, but
// we want the body to be sticky and only as wide as the table so it is always in view if loading/empty
let isEmptyOrLoading = this.virtualizer?.collection.size === 0;
if (isEmptyOrLoading) {
layoutInfo.rect.width = this.virtualizer!.size.width - 80;
}
return [
header,
body
];
}
protected buildLoader(node: Node<T>, x: number, y: number): LayoutNode {
let layoutNode = super.buildLoader(node, x, y);
let {layoutInfo} = layoutNode;
layoutInfo.allowOverflow = true;
layoutInfo.rect.width = this.virtualizer!.size.width;
// If performing first load or empty, the body will be sticky so we don't want to apply sticky to the loader, otherwise it will
// affect the positioning of the empty state renderer
let collection = this.virtualizer!.collection;
let isEmptyOrLoading = collection?.size === 0;
layoutInfo.isSticky = !isEmptyOrLoading;
return layoutNode;
}
// y is the height of the headers
protected buildBody(y: number): LayoutNode {
let layoutNode = super.buildBody(y);
let {layoutInfo} = layoutNode;
// Needs overflow for sticky loader
layoutInfo.allowOverflow = true;
// If loading or empty, we'll want the body to be sticky and centered
let isEmptyOrLoading = this.virtualizer?.collection.size === 0;
if (isEmptyOrLoading) {
layoutInfo.rect = new Rect(40, 40, this.virtualizer!.size.width - 80, this.virtualizer!.size.height - 80);
layoutInfo.isSticky = true;
}
return {...layoutNode, layoutInfo};
}
protected buildRow(node: GridNode<T>, x: number, y: number): LayoutNode {
let layoutNode = super.buildRow(node, x, y);
layoutNode.layoutInfo.allowOverflow = true;
// Needs overflow for sticky selection/drag cells
return layoutNode;
}
protected buildTableHeader(): LayoutNode {
let layoutNode = super.buildTableHeader();
// Needs overflow for sticky selection/drag column
layoutNode.layoutInfo.allowOverflow = true;
return layoutNode;
}
protected buildColumn(node: GridNode<T>, x: number, y: number): LayoutNode {
let layoutNode = super.buildColumn(node, x, y);
// Needs overflow for the resize handle
layoutNode.layoutInfo.allowOverflow = true;
return layoutNode;
}
}
export const TableContext = createContext<ContextValue<Partial<TableViewProps>, DOMRefValue<HTMLDivElement>>>(null);
/**
* Tables are containers for displaying information. They allow users to quickly scan, sort, compare, and take action on large amounts of data.
*/
export const TableView = forwardRef(function TableView(props: TableViewProps, ref: DOMRef<HTMLDivElement>) {
[props, ref] = useSpectrumContextProps(props, ref, TableContext);
let {
UNSAFE_style,
UNSAFE_className,
isQuiet = false,
density = 'regular',
overflowMode = 'truncate',
styles,
loadingState,
onResize: propsOnResize,
onResizeStart: propsOnResizeStart,
onResizeEnd: propsOnResizeEnd,
onAction,
onLoadMore,
selectionMode = 'none',
...otherProps
} = props;
let domRef = useDOMRef(ref);
let scale = useScale();
// Starts when the user selects resize from the menu, ends when resizing ends
// used to control the visibility of the resizer Nubbin
let [isInResizeMode, setIsInResizeMode] = useState(false);
let onResizeStart = useCallback((widths) => {
propsOnResizeStart?.(widths);
}, [propsOnResizeStart]);
let onResizeEnd = useCallback((widths) => {
setIsInResizeMode(false);
propsOnResizeEnd?.(widths);
}, [propsOnResizeEnd, setIsInResizeMode]);
let context = useMemo(() => ({
isQuiet,
density,
overflowMode,
loadingState,
onLoadMore,
isInResizeMode,
setIsInResizeMode,
selectionMode
}), [isQuiet, density, overflowMode, loadingState, onLoadMore, isInResizeMode, setIsInResizeMode, selectionMode]);
let scrollRef = useRef<HTMLElement | null>(null);
let isCheckboxSelection = selectionMode === 'multiple' || selectionMode === 'single';
let {selectedKeys, onSelectionChange, actionBar, actionBarHeight} = useActionBarContainer({...props, scrollRef});
return (
<ResizableTableContainer
// TODO: perhaps this ref should be attached to the RACTable but it expects a table type ref which isn't true in the virtualized case
ref={domRef}
onResize={propsOnResize}
onResizeEnd={onResizeEnd}
onResizeStart={onResizeStart}
className={(UNSAFE_className || '') + tableWrapper(null, styles)}
style={UNSAFE_style}>
<Virtualizer
layout={S2TableLayout}
layoutOptions={{
rowHeight: overflowMode === 'wrap'
? undefined
: ROW_HEIGHTS[density][scale],
estimatedRowHeight: overflowMode === 'wrap'
? ROW_HEIGHTS[density][scale]
: undefined,
// No need for estimated headingHeight since the headers aren't affected by overflow mode: wrap
headingHeight: DEFAULT_HEADER_HEIGHT[scale],
loaderHeight: 60
}}>
<InternalTableContext.Provider value={context}>
<RACTable
ref={scrollRef as any}
style={{
// Fix webkit bug where scrollbars appear above the checkboxes/other table elements
WebkitTransform: 'translateZ(0)',
// Add padding at the bottom when the action bar is visible so users can scroll to the last items.
// Also add scroll padding so navigating with the keyboard doesn't go behind the action bar.
paddingBottom: actionBarHeight > 0 ? actionBarHeight + 8 : 0,
scrollPaddingBottom: actionBarHeight > 0 ? actionBarHeight + 8 : 0
}}
className={renderProps => table({
...renderProps,
isCheckboxSelection,
isQuiet
})}
selectionBehavior="toggle"
selectionMode={selectionMode}
onRowAction={onAction}
{...otherProps}
selectedKeys={selectedKeys}
defaultSelectedKeys={undefined}
onSelectionChange={onSelectionChange} />
</InternalTableContext.Provider>
</Virtualizer>
{actionBar}
</ResizableTableContainer>
);
});
const centeredWrapper = style({
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: 'full',
height: 'full'
});
export interface TableBodyProps<T> extends Omit<RACTableBodyProps<T>, 'style' | 'className' | 'render' | keyof GlobalDOMAttributes> {}
/**
* The body of a `<Table>`, containing the table rows.
*/
export const TableBody = /*#__PURE__*/ (forwardRef as forwardRefType)(function TableBody<T extends object>(props: TableBodyProps<T>, ref: DOMRef<HTMLDivElement>) {
let {items, renderEmptyState, children, dependencies = []} = props;
let domRef = useDOMRef(ref);
let {loadingState, onLoadMore} = useContext(InternalTableContext);
let isLoading = loadingState === 'loading' || loadingState === 'loadingMore';
let emptyRender;
let renderer = children;
let stringFormatter = useLocalizedStringFormatter(intlMessages, '@react-spectrum/s2');
// TODO: still is offset strangely if loadingMore when there aren't any items in the table, see http://localhost:6006/?path=/story/tableview--empty-state&args=loadingState:loadingMore
// This is because we don't distinguish between loadingMore and loading in the layout, resulting in a different rect being used to build the body. Perhaps can be considered as a user error
// if they pass loadingMore without having any other items in the table. Alternatively, could update the layout so it knows the current loading state.
let loadMoreSpinner = (
<TableLoadMoreItem isLoading={loadingState === 'loadingMore'} onLoadMore={onLoadMore} className={style({height: 'full', width: 'full'})}>
<div className={centeredWrapper}>
<ProgressCircle
isIndeterminate
aria-label={stringFormatter.format('table.loadingMore')} />
</div>
</TableLoadMoreItem>
);
// If the user is rendering their rows in dynamic fashion, wrap their render function in Collection so we can inject
// the loader. Otherwise it is a static renderer and thus we can simply add the table loader after
// TODO: this assumes that the user isn't providing their children in some wrapper though and/or isn't doing a map of children
// (though I guess they wouldn't provide items then so the check for this is still valid in the latter case)...
if (typeof children === 'function' && items) {
renderer = (
<>
<Collection items={items} dependencies={dependencies}>
{children}
</Collection>
{loadMoreSpinner}
</>
);
} else {
renderer = (
<>
{children}
{loadMoreSpinner}
</>
);
}
if (renderEmptyState != null && !isLoading) {
emptyRender = (props: TableBodyRenderProps) => (
<div className={centeredWrapper}>
<CollectionRendererContext.Provider value={DefaultCollectionRenderer}>
{renderEmptyState(props)}
</CollectionRendererContext.Provider>
</div>
);
} else if (loadingState === 'loading') {
emptyRender = () => (
<div className={centeredWrapper}>
<ProgressCircle
isIndeterminate
aria-label={stringFormatter.format('table.loading')} />
</div>
);
}
return (
<RACTableBody
// @ts-ignore
ref={domRef}
className={style({height: 'full'})}
{...props}
renderEmptyState={emptyRender}
dependencies={[loadingState]}>
{renderer}
</RACTableBody>
);
});
const cellFocus = {
outlineStyle: {
default: 'none',
isFocusVisible: 'solid'
},
outlineOffset: -2,
outlineWidth: 2,
outlineColor: {
default: 'focus-ring',
forcedColors: 'Highlight'
},
borderRadius: '[6px]'
} as const;
function CellFocusRing() {
return <div role="presentation" className={style({...cellFocus, position: 'absolute', inset: 0, pointerEvents: 'none'})({isFocusVisible: true})} />;
}
const columnStyles = style({
height: 'inherit',
boxSizing: 'border-box',
color: {
default: baseColor('neutral'),
forcedColors: 'ButtonText'
},
paddingX: {
default: 16,
isMenu: 0
},
textAlign: {
align: {
start: 'start',
center: 'center',
end: 'end'
}
},
outlineStyle: 'none',
position: 'relative',
fontSize: controlFont(),
fontFamily: 'sans',
fontWeight: 'bold',
display: 'flex',
borderColor: {
default: 'gray-300',
forcedColors: 'ButtonBorder'
},
borderTopWidth: {
default: 0,
isQuiet: 1
},
borderBottomWidth: 1,
borderStartWidth: 0,
borderEndWidth: {
default: 0,
isMenu: 1
},
borderStyle: 'solid',
forcedColorAdjust: 'none'
});
export interface ColumnProps extends Omit<RACColumnProps, 'style' | 'className' | 'render' | keyof GlobalDOMAttributes> {
/** Whether the column should render a divider between it and the next column. */
showDivider?: boolean,
/** Whether the column allows resizing. */
allowsResizing?: boolean,
/**
* The alignment of the column's contents relative to its allotted width.
* @default 'start'
*/
align?: 'start' | 'center' | 'end',
/** The content to render as the column header. */
children: ReactNode,
/** Menu fragment to be rendered inside the column header's menu. */
menuItems?: ReactNode
}
/**
* A column within a `<Table>`.
*/
export const Column = forwardRef(function Column(props: ColumnProps, ref: DOMRef<HTMLDivElement>) {
let {isQuiet} = useContext(InternalTableContext);
let {allowsResizing, children, align = 'start'} = props;
let domRef = useDOMRef(ref);
let isMenu = allowsResizing || !!props.menuItems;
return (
<RACColumn {...props} ref={domRef} style={{borderInlineEndColor: 'transparent'}} className={renderProps => columnStyles({...renderProps, isMenu, align, isQuiet})}>
{({allowsSorting, sortDirection, isFocusVisible, sort, startResize}) => (
<>
{/* Note this is mainly for column's without a dropdown menu. If there is a dropdown menu, the button is styled to have a focus ring for simplicity
(no need to juggle showing this focus ring if focus is on the menu button and not if it is on the resizer) */}
{/* Separate absolutely positioned element because appyling the ring on the column directly via outline means the ring's required borderRadius will cause the bottom gray border to curve as well */}
{isFocusVisible && <CellFocusRing />}
{isMenu ?
(
<ColumnWithMenu isColumnResizable={allowsResizing} menuItems={props.menuItems} allowsSorting={allowsSorting} sortDirection={sortDirection} sort={sort} startResize={startResize} align={align}>
{children}
</ColumnWithMenu>
) : (
<ColumnContents align={align} allowsSorting={allowsSorting} sortDirection={sortDirection}>
{children}
</ColumnContents>
)
}
</>
)}
</RACColumn>
);
});
const columnContentWrapper = style({
minWidth: 0,
display: 'flex',
alignItems: 'center',
width: 'full',
justifyContent: {
align: {
default: 'start',
center: 'center',
end: 'end'
}
}
});
const sortIcon = style({
size: fontRelative(16),
flexShrink: 0,
marginEnd: {
default: 8,
isButton: 'text-to-visual'
},
verticalAlign: 'bottom',
'--iconPrimary': {
type: 'fill',
value: 'currentColor'
}
});
interface ColumnContentProps extends Pick<ColumnRenderProps, 'allowsSorting' | 'sortDirection'>, Pick<ColumnProps, 'align' | 'children'> {}
function ColumnContents(props: ColumnContentProps) {
let {align, allowsSorting, sortDirection, children} = props;
return (
<div className={columnContentWrapper({align})}>
{allowsSorting && (
<Provider
values={[
[IconContext, {
styles: sortIcon({})
}]
]}>
{sortDirection != null && (
sortDirection === 'ascending' ? <SortUpArrow /> : <SortDownArrow />
)}
</Provider>
)}
<span className={columnHeaderText}>
{children}
</span>
</div>
);
}
const resizableMenuButtonWrapper = style({
...cellFocus,
color: 'gray-800', // body-color
width: 'full',
position: 'relative',
display: 'flex',
alignItems: 'center',
justifyContent: {
align: {
default: 'start',
center: 'center',
end: 'end'
}
},
// TODO: when align: end, the dropdown arrow is misaligned with the text, not sure how best to make the svg be flush with the end of the button other than modifying the
// paddingEnd
paddingX: 16,
backgroundColor: 'transparent',
borderStyle: 'none',
fontSize: controlFont(),
fontFamily: 'sans',
fontWeight: 'bold'
});
const resizerHandleContainer = style({
display: {
default: '--resizerDisplay',
isResizing: 'block',
isInResizeMode: 'block'
},
width: 12,
height: 'full',
position: 'absolute',
top: 0,
insetEnd: space(-6),
cursor: {
default: 'none',
resizableDirection: {
'left': 'e-resize',
'right': 'w-resize',
'both': 'ew-resize'
}
}
});
const resizerHandle = style<{isFocusVisible: boolean, isResizing: boolean}>({
backgroundColor: {
default: 'gray-300',
isFocusVisible: lightDark('informative-900', 'informative-700'), // --spectrum-informative-background-color-default, can't use `informative` because that will use the focusVisible version
isResizing: lightDark('informative-900', 'informative-700'),
forcedColors: {
default: 'Background',
isFocusVisible: 'Highlight',
isResizing: 'Highlight'
}
},
height: {
default: 'full',
isResizing: 'screen'
},
width: {
default: 1,
isResizing: 2
},
position: 'absolute',
insetStart: space(6)
});
const columnHeaderText = style({
truncate: true,
// Make it so the text doesn't completely disappear when column is resized to smallest width + both sort and chevron icon is rendered
minWidth: fontRelative(16),
flexGrow: 0,
flexShrink: 1,
flexBasis: 'auto'
});
const chevronIcon = style({
rotate: 90,
marginStart: 'text-to-visual',
minWidth: fontRelative(16),
flexShrink: 0,
'--iconPrimary': {
type: 'fill',
value: 'currentColor'
}
});
const nubbin = style({
position: 'absolute',
top: 0,
insetStart: space(-1),
size: fontRelative(16),
fill: {
default: lightDark('informative-900', 'informative-700'), // --spectrum-informative-background-color-default, can't use `informative` because that won't be the background color value
forcedColors: 'Highlight'
},
'--iconPrimary': {
type: 'fill',
value: {
default: 'white',
forcedColors: 'HighlightText'
}
}
});
interface ColumnWithMenuProps extends Pick<ColumnRenderProps, 'allowsSorting' | 'sort' | 'sortDirection' | 'startResize'>, Pick<ColumnProps, 'align' | 'children'> {
isColumnResizable?: boolean,
menuItems?: ReactNode
}
function ColumnWithMenu(props: ColumnWithMenuProps) {
let {allowsSorting, sortDirection, sort, startResize, children, align, isColumnResizable, menuItems} = props;
let {setIsInResizeMode, isInResizeMode} = useContext(InternalTableContext);
let stringFormatter = useLocalizedStringFormatter(intlMessages, '@react-spectrum/s2');
const onMenuSelect = (key) => {
switch (key) {
case 'sort-asc':
sort('ascending');
break;
case 'sort-desc':
sort('descending');
break;
case 'resize':
setIsInResizeMode?.(true);
startResize();
break;
}
};
let items = useMemo(() => {
let options: Array<{label: string, id: string}> = [];
if (isColumnResizable) {
options = [{
label: stringFormatter.format('table.resizeColumn'),
id: 'resize'
}];
}
if (allowsSorting) {
options = [
{
label: stringFormatter.format('table.sortAscending'),
id: 'sort-asc'
},
{
label: stringFormatter.format('table.sortDescending'),
id: 'sort-desc'
},
...options
];
}
return options;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [allowsSorting, isColumnResizable]);
let buttonAlignment = 'start';
let menuAlign = 'start' as 'start' | 'end';
if (align === 'center') {
buttonAlignment = 'center';
} else if (align === 'end') {
buttonAlignment = 'end';
menuAlign = 'end';
}
return (
<>
<MenuTrigger align={menuAlign}>
<Button className={(renderProps) => resizableMenuButtonWrapper({...renderProps, align: buttonAlignment})}>
{allowsSorting && (
<Provider
values={[
[IconContext, {
styles: sortIcon({isButton: true})
}]
]}>
{sortDirection != null && (
sortDirection === 'ascending' ? <SortUpArrow /> : <SortDownArrow />
)}
</Provider>
)}
<div className={columnHeaderText}>
{children}
</div>
<Chevron size="M" className={chevronIcon} />
</Button>
<Menu onAction={onMenuSelect} styles={style({minWidth: 128})}>
{items.length > 0 && (
<MenuSection>
<Collection items={items}>
{(item) => <MenuItem>{item?.label}</MenuItem>}
</Collection>
</MenuSection>
)}
{menuItems}
</Menu>
</MenuTrigger>
{isColumnResizable && (
<div data-react-aria-prevent-focus="true">
<ColumnResizer data-react-aria-prevent-focus="true" className={({resizableDirection, isResizing}) => resizerHandleContainer({resizableDirection, isResizing, isInResizeMode})}>
{({isFocusVisible, isResizing}) => (
<>
<ResizerIndicator isFocusVisible={isFocusVisible} isResizing={isResizing} />
{(isFocusVisible || isInResizeMode) && isResizing && <div className={nubbin}><Nubbin /></div>}
</>
)}
</ColumnResizer>
</div>
)}
</>
);
}
function ResizerIndicator({isFocusVisible, isResizing}) {
return (
<div className={resizerHandle({isFocusVisible, isResizing})} />
);
}
const tableHeader = style({
height: 'full',
width: 'full',
backgroundColor: 'gray-75',
// Attempt to prevent 1px area where you can see scrolled cell content between the table outline and the table header
marginTop: '[-1px]',
'--resizerDisplay': {
type: 'display',
value: {
default: 'none',
isHovered: 'block'
}
}
});
const selectAllCheckbox = style({
});
const selectAllCheckboxColumn = style({
paddingStart: {
default: 0,
':has([slot="selection"])': 16
},
paddingEnd: {
default: 0,
':has(slot="selection")': 8
},
paddingY: 0,
height: 'full',
boxSizing: 'border-box',
outlineStyle: 'none',
position: 'relative',
display: 'flex',
alignContent: 'center',
alignItems: 'center',
justifyContent: 'start',
borderColor: {
default: 'gray-300',
forcedColors: 'ButtonBorder'
},
borderXWidth: 0,
borderTopWidth: {
default: 0,
isQuiet: 1
},
borderBottomWidth: 1,
borderStyle: 'solid',
backgroundColor: 'gray-75'
});
export interface TableHeaderProps<T> extends Omit<RACTableHeaderProps<T>, 'style' | 'className' | 'render' | 'onHoverChange' | 'onHoverStart' | 'onHoverEnd' | keyof GlobalDOMAttributes> {}
/**
* A header within a `<Table>`, containing the table columns.
*/
export const TableHeader = /*#__PURE__*/ (forwardRef as forwardRefType)(function TableHeader<T extends object>({columns, dependencies, children}: TableHeaderProps<T>, ref: DOMRef<HTMLDivElement>) {
let scale = useScale();
let {selectionBehavior, selectionMode} = useTableOptions();
let {isQuiet} = useContext(InternalTableContext);
let domRef = useDOMRef(ref);
return (
(<RACTableHeader
// @ts-ignore
ref={domRef}
className={tableHeader}>
{/* Add extra columns for selection. */}
{selectionBehavior === 'toggle' && (
// Also isSticky prop is applied just for the layout, will decide what the RAC api should be later
// @ts-ignore
(<RACColumn isSticky width={scale === 'medium' ? 40 : 52} minWidth={scale === 'medium' ? 40 : 52} className={selectAllCheckboxColumn({isQuiet})}>
{({isFocusVisible}) => (
<>
{selectionMode === 'single' &&
<>
{isFocusVisible && <CellFocusRing />}
<VisuallyHiddenSelectAllLabel />
</>
}
{selectionMode === 'multiple' &&
<Checkbox styles={selectAllCheckbox} slot="selection" />
}
</>
)}
</RACColumn>)
)}
<Collection items={columns} dependencies={dependencies}>
{children}
</Collection>
</RACTableHeader>)
);
});
function VisuallyHiddenSelectAllLabel() {
let checkboxProps = useSlottedContext(RACCheckboxContext, 'selection');
return (
<VisuallyHidden>{checkboxProps?.['aria-label']}</VisuallyHidden>
);
}
const commonCellStyles = {
borderColor: 'transparent',
borderBottomWidth: 1,
borderTopWidth: 0,
borderXWidth: 0,
borderStyle: 'solid',
position: 'relative',
color: '--rowTextColor',
outlineStyle: 'none',
paddingX: 16 // table-edge-to-content
} as const;
const treeColumnStyles = {
'--indent': {
type: 'width',
value: 16
},
'--treeColumnPadding': {
type: 'width',
value: {
default: 16,
isTreeColumnWithNoChildren: 36
}
},
paddingStart: {
default: 16,
isTreeColumn: 'calc(var(--treeColumnPadding) + (var(--table-row-level, 1) - 1) * var(--indent))'
}
} as const;
const cell = style<CellRenderProps & S2TableProps & {isDivider: boolean, isTreeColumnWithNoChildren: boolean}>({
...commonCellStyles,
...treeColumnStyles,
minHeight: {
default: 40,
density: {
compact: 32,
spacious: 48
}
},
boxSizing: 'border-box',
height: 'full',
width: 'full',
fontSize: controlFont(),
alignItems: 'center',
display: 'flex',