-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathTreeView.tsx
More file actions
470 lines (434 loc) · 14 KB
/
TreeView.tsx
File metadata and controls
470 lines (434 loc) · 14 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
/*
* 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 {ActionButtonGroupContext} from './ActionButtonGroup';
import {ActionMenuContext} from './ActionMenu';
import {baseColor, colorMix, focusRing, fontRelative, style} from '../style' with {type: 'macro'};
import {
Button,
ButtonContext,
ListLayout,
Provider,
TreeItemProps as RACTreeItemProps,
TreeProps as RACTreeProps,
Tree,
TreeItem,
TreeItemContent,
TreeItemContentProps,
TreeLoadMoreItem,
TreeLoadMoreItemProps,
useContextProps,
Virtualizer
} from 'react-aria-components';
import {centerBaseline} from './CenterBaseline';
import {Checkbox} from './Checkbox';
import Chevron from '../ui-icons/Chevron';
import {DOMRef, forwardRefType, GlobalDOMAttributes, Key, LoadingState} from '@react-types/shared';
import {getAllowedOverrides, StylesPropWithHeight, UnsafeStyles} from './style-utils' with {type: 'macro'};
import {IconContext} from './Icon';
// @ts-ignore
import intlMessages from '../intl/*.json';
import {ProgressCircle} from './ProgressCircle';
import {raw} from '../style/style-macro' with {type: 'macro'};
import React, {createContext, forwardRef, JSXElementConstructor, ReactElement, ReactNode, useRef} from 'react';
import {Text, TextContext} from './Content';
import {useActionBarContainer} from './ActionBar';
import {useDOMRef} from '@react-spectrum/utils';
import {useLocale, useLocalizedStringFormatter} from 'react-aria';
import {useScale} from './utils';
interface S2TreeProps {
/** Handler that is called when a user performs an action on a row. */
onAction?: (key: Key) => void,
/** Provides the ActionBar to display when items are selected in the TreeView. */
renderActionBar?: (selectedKeys: 'all' | Set<Key>) => ReactElement
}
export interface TreeViewProps<T> extends Omit<RACTreeProps<T>, 'style' | 'className' | 'render' | 'onRowAction' | 'selectionBehavior' | 'onScroll' | 'onCellAction' | 'dragAndDropHooks' | keyof GlobalDOMAttributes>, UnsafeStyles, S2TreeProps {
/** Spectrum-defined styles, returned by the `style()` macro. */
styles?: StylesPropWithHeight
}
export interface TreeViewItemProps extends Omit<RACTreeItemProps, 'className' | 'style' | 'render' | 'onClick' | keyof GlobalDOMAttributes> {
/** Whether this item has children, even if not loaded yet. */
hasChildItems?: boolean
}
export interface TreeViewLoadMoreItemProps extends Pick<TreeLoadMoreItemProps, 'onLoadMore'> {
/** The current loading state of the TreeView or TreeView row. */
loadingState?: LoadingState
}
interface TreeRendererContextValue {
renderer?: (item) => ReactElement<any, string | JSXElementConstructor<any>>
}
const TreeRendererContext = createContext<TreeRendererContextValue>({});
const treeViewWrapper = style({
minHeight: 0,
minWidth: 0,
display: 'flex',
isolation: 'isolate',
disableTapHighlight: true,
position: 'relative',
overflow: 'clip'
}, getAllowedOverrides({height: true}));
// TODO: the below is needed so the borders of the top and bottom row isn't cut off if the TreeView is wrapped within a container by always reserving the 2px needed for the
// keyboard focus ring. Perhaps find a different way of rendering the outlines since the top of the item doesn't
// scroll into view due to how the ring is offset. Alternatively, have the tree render the top/bottom outline like it does in Listview
const tree = style({
...focusRing(),
outlineOffset: -2, // make certain we are visible inside overflow hidden containers
userSelect: 'none',
minHeight: 0,
minWidth: 0,
width: 'full',
height: 'full',
overflow: 'auto',
boxSizing: 'border-box',
justifyContent: {
isEmpty: 'center'
},
alignItems: {
isEmpty: 'center'
},
'--indent': {
type: 'width',
value: 16
}
});
/**
* A tree view provides users with a way to navigate nested hierarchical information.
*/
export const TreeView = /*#__PURE__*/ (forwardRef as forwardRefType)(function TreeView<T extends object>(props: TreeViewProps<T>, ref: DOMRef<HTMLDivElement>) {
let {children, UNSAFE_className, UNSAFE_style} = props;
let scale = useScale();
let renderer;
if (typeof children === 'function') {
renderer = children;
}
let domRef = useDOMRef(ref);
let scrollRef = useRef<HTMLElement | null>(null);
let {selectedKeys, onSelectionChange, actionBar, actionBarHeight} = useActionBarContainer({...props, scrollRef});
let treeContent = (
<Virtualizer
layout={ListLayout}
layoutOptions={{
rowHeight: scale === 'large' ? 50 : 40
}}>
<TreeRendererContext.Provider value={{renderer}}>
<Tree
{...props}
style={{
...(!props.renderActionBar ? UNSAFE_style : {}),
paddingBottom: actionBarHeight > 0 ? actionBarHeight + 8 : 0,
scrollPaddingBottom: actionBarHeight > 0 ? actionBarHeight + 8 : 0
}}
className={renderProps => (!props.renderActionBar ? (UNSAFE_className ?? '') : '') + tree({...renderProps})}
selectionBehavior="toggle"
selectedKeys={selectedKeys}
defaultSelectedKeys={undefined}
onSelectionChange={onSelectionChange}
ref={props.renderActionBar ? (scrollRef as any) : domRef}>
{props.children}
</Tree>
</TreeRendererContext.Provider>
</Virtualizer>
);
if (props.renderActionBar) {
return (
<div
ref={domRef}
className={(UNSAFE_className ?? '') + treeViewWrapper(null, props.styles)}
style={UNSAFE_style}>
{treeContent}
{actionBar}
</div>
);
}
return treeContent;
});
const rowBackgroundColor = {
default: '--s2-container-bg',
isFocusVisibleWithin: colorMix('gray-25', 'gray-900', 7),
isHovered: colorMix('gray-25', 'gray-900', 7),
isPressed: colorMix('gray-25', 'gray-900', 10),
isSelected: {
default: colorMix('gray-25', 'gray-900', 7),
isFocusVisibleWithin: colorMix('gray-25', 'gray-900', 10),
isHovered: colorMix('gray-25', 'gray-900', 10),
isPressed: colorMix('gray-25', 'gray-900', 10)
},
forcedColors: {
default: 'Background'
}
} as const;
const treeRow = style({
position: 'relative',
display: 'flex',
height: 40,
width: 'full',
boxSizing: 'border-box',
font: 'ui',
color: {
default: baseColor('neutral-subdued'),
isSelected: baseColor('neutral'),
forcedColors: 'ButtonText'
},
outlineStyle: 'none',
cursor: {
default: 'default',
isLink: 'pointer'
},
'--rowBackgroundColor': {
type: 'backgroundColor',
value: rowBackgroundColor
},
'--rowFocusIndicatorColor': {
type: 'outlineColor',
value: {
default: 'focus-ring',
forcedColors: 'Highlight'
}
}
});
const treeCellGrid = style({
display: 'grid',
width: 'full',
height: 'full',
boxSizing: 'border-box',
alignContent: 'center',
alignItems: 'center',
gridTemplateColumns: ['auto', 'auto', 'auto', 'auto', 'auto', '1fr', 'minmax(0, auto)', 'auto'],
gridTemplateRows: '1fr',
gridTemplateAreas: [
'drag-handle checkbox level-padding expand-button icon content actions actionmenu'
],
backgroundColor: '--rowBackgroundColor',
paddingEnd: 4, // account for any focus rings on the last item in the cell
color: {
isDisabled: {
default: 'gray-400',
forcedColors: 'GrayText'
}
},
'--rowSelectedBorderColor': {
type: 'outlineColor',
value: {
default: 'gray-800',
isFocusVisible: 'focus-ring',
forcedColors: 'Highlight'
}
},
'--rowForcedFocusBorderColor': {
type: 'outlineColor',
value: {
default: 'focus-ring',
forcedColors: 'Highlight'
}
}
});
const treeCheckbox = style({
gridArea: 'checkbox',
marginStart: 12,
marginEnd: 0,
paddingEnd: 0,
visibility: {
default: 'visible',
isDisabled: 'hidden'
}
});
const treeIcon = style({
gridArea: 'icon',
marginEnd: 'text-to-visual',
'--iconPrimary': {
type: 'fill',
value: 'currentColor'
}
});
const treeContent = style({
gridArea: 'content',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden'
});
const treeActions = style({
gridArea: 'actions',
/* TODO: I made this one up, confirm desired behavior. These paddings are to make sure the action group has enough padding for the focus ring */
marginStart: 2,
marginEnd: 4
});
const treeActionMenu = style({
gridArea: 'actionmenu'
});
const treeRowFocusIndicator = raw(`
&:before {
content: "";
display: inline-block;
position: sticky;
inset-inline-start: 0;
width: 3px;
height: 100%;
margin-inline-end: -3px;
margin-block-end: 1px;
z-index: 3;
background-color: var(--rowFocusIndicatorColor);
}`
);
export const TreeViewItem = (props: TreeViewItemProps): ReactNode => {
let {
href
} = props;
return (
<TreeItem
{...props}
className={(renderProps) => treeRow({
...renderProps,
isLink: !!href
}) + (renderProps.isFocusVisible ? ' ' + treeRowFocusIndicator : '')} />
);
};
export interface TreeViewItemContentProps extends Omit<TreeItemContentProps, 'children'> {
/** Rendered contents of the tree item or child items. */
children: ReactNode
}
export const TreeViewItemContent = (props: TreeViewItemContentProps): ReactNode => {
let {
children
} = props;
let scale = useScale();
return (
<TreeItemContent>
{({isExpanded, hasChildItems, selectionMode, selectionBehavior, isDisabled, isSelected, id, state}) => {
let isNextSelected = false;
let isNextFocused = false;
let keyAfter = state.collection.getKeyAfter(id);
if (keyAfter != null) {
isNextSelected = state.selectionManager.isSelected(keyAfter);
}
let isFirst = state.collection.getFirstKey() === id;
return (
<div className={treeCellGrid({isDisabled, isNextSelected, isSelected, isFirst, isNextFocused})}>
{selectionMode !== 'none' && selectionBehavior === 'toggle' && (
// TODO: add transition?
<div className={treeCheckbox({isDisabled: isDisabled || !state.selectionManager.canSelectItem(id) || state.disabledKeys.has(id)})}>
<Checkbox slot="selection" />
</div>
)}
<div
className={style({
gridArea: 'level-padding',
width: 'calc(calc(var(--tree-item-level, 0) - 1) * var(--indent))'
})} />
<ExpandableRowChevron isDisabled={isDisabled} isExpanded={isExpanded} scale={scale} isHidden={!(hasChildItems)} />
<Provider
values={[
[TextContext, {styles: treeContent}],
[IconContext, {
render: centerBaseline({slot: 'icon', styles: treeIcon}),
styles: style({size: fontRelative(20), flexShrink: 0})
}],
[ActionButtonGroupContext, {styles: treeActions, isDisabled}],
[ActionMenuContext, {styles: treeActionMenu, isQuiet: true, isDisabled}]
]}>
{typeof children === 'string' ? <Text>{children}</Text> : children}
</Provider>
</div>
);
}}
</TreeItemContent>
);
};
const centeredWrapper = style({
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: 'full',
height: 'full'
});
export const TreeViewLoadMoreItem = (props: TreeViewLoadMoreItemProps): ReactNode => {
let {loadingState, onLoadMore} = props;
let stringFormatter = useLocalizedStringFormatter(intlMessages, '@react-spectrum/s2');
let isLoading = loadingState === 'loading' || loadingState === 'loadingMore';
return (
<TreeLoadMoreItem isLoading={isLoading} onLoadMore={onLoadMore} className={style({width: 'full', marginY: 4})}>
{() => {
return (
<div className={centeredWrapper}>
<ProgressCircle
isIndeterminate
aria-label={stringFormatter.format('table.loadingMore')} />
</div>
);
}}
</TreeLoadMoreItem>
);
};
interface ExpandableRowChevronProps {
isExpanded?: boolean,
isDisabled?: boolean,
isRTL?: boolean,
scale: 'medium' | 'large',
isHidden?: boolean
}
const expandButton = style<ExpandableRowChevronProps>({
gridArea: 'expand-button',
color: {
default: 'inherit',
isDisabled: {
default: 'disabled',
forcedColors: 'GrayText'
}
},
height: 40,
width: 40,
display: 'flex',
flexWrap: 'wrap',
alignContent: 'center',
justifyContent: 'center',
outlineStyle: 'none',
cursor: 'default',
transform: {
isExpanded: {
default: 'rotate(90deg)',
isRTL: 'rotate(-90deg)'
}
},
padding: 0,
transition: 'default',
backgroundColor: 'transparent',
borderStyle: 'none',
disableTapHighlight: true,
visibility: {
isHidden: 'hidden'
}
});
function ExpandableRowChevron(props: ExpandableRowChevronProps) {
let expandButtonRef = useRef<HTMLButtonElement>(null);
let [fullProps, ref] = useContextProps({...props, slot: 'chevron'}, expandButtonRef, ButtonContext);
let {isExpanded, scale, isHidden} = fullProps;
let {direction} = useLocale();
return (
<Button
{...props}
ref={ref}
slot="chevron"
className={renderProps => expandButton({...renderProps, isExpanded, isRTL: direction === 'rtl', scale, isHidden})}>
<Chevron
className={style({
scale: {
direction: {
ltr: '1',
rtl: '-1'
}
},
'--iconPrimary': {
type: 'fill',
value: 'currentColor'
}
})({direction})} />
</Button>
);
}