-
Notifications
You must be signed in to change notification settings - Fork 658
Expand file tree
/
Copy pathTreeView.tsx
More file actions
978 lines (883 loc) · 31 KB
/
TreeView.tsx
File metadata and controls
978 lines (883 loc) · 31 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
import {
ChevronDownIcon,
ChevronRightIcon,
FileDirectoryFillIcon,
FileDirectoryOpenFillIcon,
type Icon,
} from '@primer/octicons-react'
import {clsx} from 'clsx'
import React, {useCallback, useEffect} from 'react'
import classes from './TreeView.module.css'
import {ConfirmationDialog} from '../ConfirmationDialog/ConfirmationDialog'
import Spinner from '../Spinner'
import Text from '../Text'
import VisuallyHidden from '../_VisuallyHidden'
import {useControllableState} from '../hooks/useControllableState'
import {useId} from '../hooks/useId'
import useSafeTimeout from '../hooks/useSafeTimeout'
import {useSlots} from '../hooks/useSlots'
import {getAccessibleName} from './shared'
import {getFirstChildElement, useRovingTabIndex} from './useRovingTabIndex'
import {useTypeahead} from './useTypeahead'
import {SkeletonAvatar} from '../SkeletonAvatar'
import {SkeletonText} from '../SkeletonText'
import {Dialog} from '../Dialog'
import {Button, IconButton} from '../Button'
import {ActionList} from '../ActionList'
import {getAccessibleKeybindingHintString} from '../KeybindingHint'
import {useIsMacOS} from '../hooks'
import {Tooltip} from '../TooltipV2'
import {isSlot} from '../utils/is-slot'
import type {FCWithSlotMarker} from '../utils/types'
import {AriaStatus} from '../live-region'
// ----------------------------------------------------------------------------
// Context
const RootContext = React.createContext<{
announceUpdate: (message: string) => void
// We cache the expanded state of tree items so we can preserve the state
// across remounts. This is necessary because we unmount tree items
// when their parent is collapsed.
expandedStateCache: React.RefObject<Map<string, boolean> | null>
scrollElementIntoView: (element: Element | null | undefined) => void
}>({
announceUpdate: () => {},
expandedStateCache: {current: new Map()},
scrollElementIntoView: () => {},
})
const ItemContext = React.createContext<{
itemId: string
level: number
isSubTreeEmpty: boolean
setIsSubTreeEmpty: React.Dispatch<React.SetStateAction<boolean>>
isExpanded: boolean
setIsExpanded: (isExpanded: boolean) => void
leadingVisualId: string
trailingVisualId: string
trailingActionId: string
}>({
itemId: '',
level: 1,
isSubTreeEmpty: false,
setIsSubTreeEmpty: () => {},
isExpanded: false,
setIsExpanded: () => {},
leadingVisualId: '',
trailingVisualId: '',
trailingActionId: '',
})
// ----------------------------------------------------------------------------
// TreeView
export type TreeViewProps = {
'aria-label'?: React.AriaAttributes['aria-label']
'aria-labelledby'?: React.AriaAttributes['aria-labelledby']
children: React.ReactNode
flat?: boolean
truncate?: boolean
className?: string
style?: React.CSSProperties
}
export type TreeViewSecondaryActions = {
label: string
onClick: () => void
icon: Icon
count?: number | string
className?: string
}
/* Size of toggle icon in pixels. */
const TOGGLE_ICON_SIZE = 12
const Root: React.FC<TreeViewProps> = ({
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledby,
children,
flat,
truncate = true,
className,
style,
}) => {
const containerRef = React.useRef<HTMLUListElement>(null)
const mouseDownRef = React.useRef<boolean>(false)
const [ariaLiveMessage, setAriaLiveMessage] = React.useState('')
const announceUpdate = React.useCallback((message: string) => {
setAriaLiveMessage(message)
}, [])
const onMouseDown = useCallback(() => {
mouseDownRef.current = true
}, [])
useEffect(() => {
function onMouseUp() {
mouseDownRef.current = false
}
document.addEventListener('mouseup', onMouseUp)
return () => {
document.removeEventListener('mouseup', onMouseUp)
}
}, [])
useRovingTabIndex({containerRef, mouseDownRef})
useTypeahead({
containerRef,
onFocusChange: element => {
if (element instanceof HTMLElement) {
element.focus()
}
},
})
// Deferred scroll-into-view: coalesces multiple scroll requests within
// the same animation frame so that rapid keyboard navigation (held key)
// only triggers one scrollIntoView + reflow per frame instead of per keystroke.
const pendingScrollRef = React.useRef<number | null>(null)
const scrollElementIntoView = useCallback((element: Element | null | undefined) => {
if (!element) return
if (pendingScrollRef.current !== null) {
cancelAnimationFrame(pendingScrollRef.current)
}
pendingScrollRef.current = requestAnimationFrame(() => {
pendingScrollRef.current = null
if (!element.isConnected) return
element.scrollIntoView({block: 'nearest', inline: 'nearest'})
})
}, [])
useEffect(() => {
return () => {
if (pendingScrollRef.current !== null) {
cancelAnimationFrame(pendingScrollRef.current)
}
}
}, [])
const expandedStateCache = React.useRef<Map<string, boolean> | null>(null)
if (expandedStateCache.current === null) {
expandedStateCache.current = new Map()
}
return (
<RootContext.Provider
value={{
announceUpdate,
expandedStateCache,
scrollElementIntoView,
}}
>
<>
<VisuallyHidden>
<AriaStatus announceOnShow>{ariaLiveMessage}</AriaStatus>
</VisuallyHidden>
<ul
ref={containerRef}
role="tree"
aria-label={ariaLabel}
aria-labelledby={ariaLabelledby}
data-omit-spacer={flat}
data-truncate-text={truncate || false}
onMouseDown={onMouseDown}
className={clsx(className, classes.TreeViewRootUlStyles)}
style={style}
>
{children}
</ul>
</>
</RootContext.Provider>
)
}
Root.displayName = 'TreeView'
// ----------------------------------------------------------------------------
// TreeView.Item
export type TreeViewItemProps = {
'aria-label'?: React.AriaAttributes['aria-label']
'aria-labelledby'?: React.AriaAttributes['aria-labelledby']
id: string
children: React.ReactNode
containIntrinsicSize?: string
current?: boolean
defaultExpanded?: boolean
expanded?: boolean | null
onExpandedChange?: (expanded: boolean) => void
onSelect?: (event: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>) => void
className?: string
secondaryActions?: TreeViewSecondaryActions[]
}
const Item = React.forwardRef<HTMLElement, TreeViewItemProps>(
(
{
id: itemId,
containIntrinsicSize,
current: isCurrentItem = false,
defaultExpanded,
expanded,
onExpandedChange,
onSelect,
children,
className,
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledby,
secondaryActions,
},
ref,
) => {
const [slots, rest] = useSlots(children, {
leadingAction: LeadingAction,
leadingVisual: LeadingVisual,
trailingVisual: TrailingVisual,
})
const {expandedStateCache, scrollElementIntoView} = React.useContext(RootContext)
const labelId = useId()
const leadingVisualId = useId()
const trailingVisualId = useId()
const trailingActionId = useId()
const [isExpanded, setIsExpanded] = useControllableState({
name: itemId,
// If the item was previously mounted, its expanded state might be cached.
// We check the cache first, and then fall back to the defaultExpanded prop.
// If defaultExpanded is not provided, we default to false unless the item
// is the current item, in which case we default to true.
defaultValue: () => expandedStateCache.current?.get(itemId) ?? defaultExpanded ?? isCurrentItem,
value: expanded === null ? false : expanded,
onChange: onExpandedChange,
})
const {level} = React.useContext(ItemContext)
const {hasSubTree, subTree, childrenWithoutSubTree} = useSubTree(rest)
const [isSubTreeEmpty, setIsSubTreeEmpty] = React.useState(!hasSubTree)
const [actionCommandPressed, setActionCommandPressed] = React.useState(false)
const [isFocused, setIsFocused] = React.useState(false)
const isMacOS = useIsMacOS()
// Set the expanded state and cache it
const setIsExpandedWithCache = React.useCallback(
// eslint-disable-next-line react-hooks/preserve-manual-memoization
(newIsExpanded: boolean) => {
setIsExpanded(newIsExpanded)
expandedStateCache.current?.set(itemId, newIsExpanded)
},
[itemId, setIsExpanded, expandedStateCache],
)
// Expand or collapse the subtree
const toggle = React.useCallback(
(event?: React.MouseEvent | React.KeyboardEvent) => {
setIsExpandedWithCache(!isExpanded)
event?.stopPropagation()
},
[isExpanded, setIsExpandedWithCache],
)
const activateActionsDialog = React.useCallback(() => {
if (!secondaryActions) return
if (secondaryActions.length > 1) {
// If there are multiple secondary actions, open the action dialog
// as this allows users to select the action they want to interact with.
setActionCommandPressed(true)
} else {
// If there is only one secondary action, trigger it directly
const action = secondaryActions[0].onClick
action()
}
}, [secondaryActions])
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLElement>) => {
switch (event.key) {
case 'Enter':
case ' ':
if (onSelect) {
onSelect(event)
} else {
toggle(event)
}
event.stopPropagation()
break
case 'ArrowRight':
// Ignore if modifier keys are pressed
if (event.altKey || event.metaKey) return
event.preventDefault()
event.stopPropagation()
setIsExpandedWithCache(true)
break
case 'ArrowLeft':
// Ignore if modifier keys are pressed
if (event.altKey || event.metaKey) return
event.preventDefault()
event.stopPropagation()
setIsExpandedWithCache(false)
break
case 'U':
case 'u':
if (!(event.shiftKey && (event.metaKey || event.ctrlKey))) return
activateActionsDialog()
break
}
},
[onSelect, setIsExpandedWithCache, toggle, activateActionsDialog],
)
const ariaDescribedByIds = [
slots.leadingVisual ? leadingVisualId : null,
slots.trailingVisual ? trailingVisualId : null,
].filter(Boolean)
const shortcut = `Shift+${isMacOS ? 'Meta' : 'Control'}+U`
const trailingActionShortcutText = `Press (${getAccessibleKeybindingHintString(shortcut, isMacOS)}) for more actions.`
return (
<ItemContext.Provider
value={{
itemId,
level: level + 1,
isSubTreeEmpty,
setIsSubTreeEmpty,
isExpanded,
setIsExpanded: setIsExpandedWithCache,
leadingVisualId,
trailingVisualId,
trailingActionId,
}}
>
{/* @ts-ignore Box doesn't have type support for `ref` used in combination with `as` */}
<li
className={clsx('PRIVATE_TreeView-item', className, classes.TreeViewItem)}
ref={ref as React.ForwardedRef<HTMLLIElement>}
tabIndex={0}
id={itemId}
role="treeitem"
aria-label={
secondaryActions ? (ariaLabel ? `${ariaLabel}. ${trailingActionShortcutText}` : undefined) : ariaLabel
}
aria-labelledby={
ariaLabel ? undefined : `${ariaLabelledby || labelId} ${secondaryActions ? trailingActionId : ''}`.trim()
}
aria-describedby={ariaDescribedByIds.length ? ariaDescribedByIds.join(' ') : undefined}
aria-level={level}
aria-expanded={(isSubTreeEmpty && (!isExpanded || !hasSubTree)) || expanded === null ? undefined : isExpanded}
aria-current={isCurrentItem ? 'true' : undefined}
aria-selected={isFocused ? 'true' : 'false'}
data-has-leading-action={slots.leadingAction ? true : undefined}
onKeyDown={handleKeyDown}
onFocus={event => {
// Defer scroll to the next animation frame so that rapid keyboard
// navigation (held key) coalesces into a single reflow per frame
scrollElementIntoView(event.currentTarget.firstElementChild)
// Set the focused state
setIsFocused(true)
// Prevent focus event from bubbling up to parent items
event.stopPropagation()
}}
onBlur={() => setIsFocused(false)}
onClick={event => {
if (onSelect) {
onSelect(event)
} else {
toggle(event)
}
event.stopPropagation()
}}
onAuxClick={event => {
if (onSelect && event.button === 1) {
onSelect(event)
}
event.stopPropagation()
}}
>
<div
className={clsx('PRIVATE_TreeView-item-container', classes.TreeViewItemContainer)}
style={{
// @ts-ignore CSS custom property
'--level': level,
contentVisibility: containIntrinsicSize ? 'auto' : undefined,
containIntrinsicSize,
}}
>
<div style={{gridArea: 'spacer', display: 'flex'}}>
<LevelIndicatorLines level={level} />
</div>
{slots.leadingAction}
{hasSubTree ? (
// This lint rule is disabled due to the guidelines in the `TreeView` api docs.
// https://github.com/github/primer/blob/main/apis/tree-view-api.md#the-expandcollapse-chevron-toggle
// This has specific advice that the chevron be available only to pointer event.
// If they take up a button role, they become unnecessary and numerous tab stops.
<div
className={clsx(
'PRIVATE_TreeView-item-toggle',
onSelect && 'PRIVATE_TreeView-item-toggle--hover',
level === 1 && 'PRIVATE_TreeView-item-toggle--end',
classes.TreeViewItemToggle,
classes.TreeViewItemToggleHover,
classes.TreeViewItemToggleEnd,
)}
onClick={event => {
if (onSelect) {
toggle(event)
}
}}
>
{isExpanded ? (
<ChevronDownIcon size={TOGGLE_ICON_SIZE} />
) : (
<ChevronRightIcon size={TOGGLE_ICON_SIZE} />
)}
</div>
) : null}
<div id={labelId} className={clsx('PRIVATE_TreeView-item-content', classes.TreeViewItemContent)}>
{slots.leadingVisual}
<span className={clsx('PRIVATE_TreeView-item-content-text', classes.TreeViewItemContentText)}>
{childrenWithoutSubTree}
</span>
{slots.trailingVisual}
</div>
{secondaryActions ? (
<>
<TrailingAction items={secondaryActions} shortcutText={trailingActionShortcutText} />
{actionCommandPressed ? (
<ActionDialog items={secondaryActions} onClose={() => setActionCommandPressed(false)} />
) : null}
</>
) : null}
</div>
{subTree}
</li>
</ItemContext.Provider>
)
},
)
/** Lines to indicate the depth of an item in a TreeView */
const LevelIndicatorLines: React.FC<{level: number}> = ({level}) => {
return (
<div style={{width: '100%', display: 'flex'}}>
{Array.from({length: level - 1}).map((_, index) => (
<div key={index} className={clsx('PRIVATE_TreeView-item-level-line', classes.TreeViewItemLevelLine)} />
))}
</div>
)
}
Item.displayName = 'TreeView.Item'
// ----------------------------------------------------------------------------
// TreeView.SubTree
export type SubTreeState = 'initial' | 'loading' | 'done' | 'error'
export type TreeViewSubTreeProps = {
children?: React.ReactNode
state?: SubTreeState
/**
* Display a skeleton loading state with the specified count of items
*/
count?: number
'aria-label'?: string
}
const SubTree: FCWithSlotMarker<TreeViewSubTreeProps> = ({count, state, children, 'aria-label': ariaLabel}) => {
const {announceUpdate} = React.useContext(RootContext)
const {itemId, isExpanded, isSubTreeEmpty, setIsSubTreeEmpty} = React.useContext(ItemContext)
const loadingItemRef = React.useRef<HTMLElement>(null)
const ref = React.useRef<HTMLElement>(null)
const [loadingFocused, setLoadingFocused] = React.useState(false)
const [subTreeLabel, setSubTreeLabel] = React.useState('')
const previousState = usePreviousValue(state)
const {safeSetTimeout} = useSafeTimeout()
React.useEffect(() => {
// If `state` is undefined, we're working in a synchronous context and need
// to detect if the sub-tree has content. If `state === 'done` then we're
// working in an asynchronous context and need to see if there is content
// that has been loaded in.
if (state === undefined || state === 'done') {
if (!isSubTreeEmpty && !children) {
setIsSubTreeEmpty(true)
} else if (isSubTreeEmpty && children) {
setIsSubTreeEmpty(false)
}
}
}, [state, isSubTreeEmpty, setIsSubTreeEmpty, children])
// Handle transition from loading to done state
React.useEffect(() => {
const parentElement = document.getElementById(itemId)
if (!parentElement) return
setSubTreeLabel(getAccessibleName(parentElement))
if (previousState === 'loading' && state === 'done') {
// Announce update to screen readers
const parentName = getAccessibleName(parentElement)
if (ref.current?.childElementCount) {
announceUpdate(`${parentName} content loaded`)
} else {
announceUpdate(`${parentName} is empty`)
}
// Move focus to the first child if the loading indicator
// was focused when the async items finished loading
if (loadingFocused) {
const firstChild = getFirstChildElement(parentElement)
if (firstChild) {
safeSetTimeout(() => {
firstChild.focus()
})
} else {
safeSetTimeout(() => {
parentElement.focus()
})
}
setLoadingFocused(false)
}
} else if (state === 'loading') {
const parentName = getAccessibleName(parentElement)
announceUpdate(`${parentName} content loading`)
}
}, [loadingFocused, previousState, state, itemId, announceUpdate, ref, safeSetTimeout])
// Track focus on the loading indicator
React.useEffect(() => {
function handleFocus() {
setLoadingFocused(true)
}
function handleBlur(event: FocusEvent) {
// Skip blur events that are caused by the element being removed from the DOM.
// This can happen when the loading indicator is focused when async items are
// done loading and the loading indicator is removed from the DOM.
// If `loadingFocused` is `true` when `state` is `"done"` then the loading indicator
// was focused when the async items finished loading and we need to move focus to the
// first child.
if (!event.relatedTarget) return
setLoadingFocused(false)
}
const loadingElement = loadingItemRef.current
if (!loadingElement) return
loadingElement.addEventListener('focus', handleFocus)
loadingElement.addEventListener('blur', handleBlur)
return () => {
loadingElement.removeEventListener('focus', handleFocus)
loadingElement.removeEventListener('blur', handleBlur)
}
}, [loadingItemRef, state])
if (!isExpanded) {
return null
}
return (
<ul
role="group"
style={{
listStyle: 'none',
padding: 0,
margin: 0,
}}
// @ts-ignore Box doesn't have type support for `ref` used in combination with `as`
ref={ref}
aria-label={ariaLabel || subTreeLabel}
>
{state === 'loading' ? <LoadingItem ref={loadingItemRef} count={count} /> : children}
{isSubTreeEmpty && state !== 'loading' ? <EmptyItem /> : null}
</ul>
)
}
SubTree.displayName = 'TreeView.SubTree'
SubTree.__SLOT__ = Symbol('TreeView.SubTree')
function usePreviousValue<T>(value: T): T {
const ref = React.useRef(value)
React.useEffect(() => {
ref.current = value
}, [value])
// eslint-disable-next-line react-hooks/refs
return ref.current
}
const SkeletonItem = () => {
return (
<span
className={clsx(
classes.TreeViewSkeletonItemContainerStyle,
classes.TreeViewItemSkeleton,
'PRIVATE_TreeView-item-skeleton',
)}
>
<SkeletonAvatar size={16} square />
<SkeletonText className={classes.TreeItemSkeletonTextStyles} />
</span>
)
}
type LoadingItemProps = {
count?: number
}
const LoadingItem = React.forwardRef<HTMLElement, LoadingItemProps>(({count}, ref) => {
const itemId = useId()
if (count) {
return (
<Item id={itemId} ref={ref}>
{Array.from({length: count}).map((_, i) => {
return <SkeletonItem aria-hidden={true} key={i} />
})}
<div className={clsx('PRIVATE_VisuallyHidden', classes.TreeViewVisuallyHidden)}>Loading {count} items</div>
</Item>
)
}
return (
<Item id={itemId} ref={ref}>
<LeadingVisual>
<Spinner size="small" />
</LeadingVisual>
<Text className="fgColor-muted">Loading...</Text>
</Item>
)
})
const EmptyItem = React.forwardRef<HTMLElement>((props, ref) => {
return (
<Item expanded={null} id={useId()} ref={ref}>
<Text className="fgColor-muted">No items found</Text>
</Item>
)
})
function useSubTree(children: React.ReactNode) {
return React.useMemo(() => {
const subTree = React.Children.toArray(children).find(
child => React.isValidElement(child) && (child.type === SubTree || isSlot(child, SubTree)),
)
const childrenWithoutSubTree = React.Children.toArray(children).filter(
child => !(React.isValidElement(child) && (child.type === SubTree || isSlot(child, SubTree))),
)
return {
subTree,
childrenWithoutSubTree,
hasSubTree: Boolean(subTree),
}
}, [children])
}
// ----------------------------------------------------------------------------
// TreeView.LeadingVisual and TreeView.TrailingVisual
export type TreeViewVisualProps = {
children: React.ReactNode | ((props: {isExpanded: boolean}) => React.ReactNode)
// Provide an accessible name for the visual. This should provide information
// about what the visual indicates or represents
label?: string
}
const LeadingVisual: React.FC<TreeViewVisualProps> = props => {
const {isExpanded, leadingVisualId} = React.useContext(ItemContext)
const children = typeof props.children === 'function' ? props.children({isExpanded}) : props.children
return (
<>
<div
className={clsx('PRIVATE_VisuallyHidden', classes.TreeViewVisuallyHidden)}
aria-hidden={true}
id={leadingVisualId}
>
{props.label}
</div>
<div className={clsx('PRIVATE_TreeView-item-visual', classes.TreeViewItemVisual)} aria-hidden={true}>
{children}
</div>
</>
)
}
LeadingVisual.displayName = 'TreeView.LeadingVisual'
const TrailingVisual: React.FC<TreeViewVisualProps> = props => {
const {isExpanded, trailingVisualId} = React.useContext(ItemContext)
const children = typeof props.children === 'function' ? props.children({isExpanded}) : props.children
return (
<>
<div
className={clsx('PRIVATE_VisuallyHidden', classes.TreeViewVisuallyHidden)}
aria-hidden={true}
id={trailingVisualId}
>
{props.label}
</div>
<div className={clsx('PRIVATE_TreeView-item-visual', classes.TreeViewItemVisual)} aria-hidden={true}>
{children}
</div>
</>
)
}
TrailingVisual.displayName = 'TreeView.TrailingVisual'
// ----------------------------------------------------------------------------
// TreeView.LeadingAction
const LeadingAction: React.FC<TreeViewVisualProps> = props => {
const {isExpanded} = React.useContext(ItemContext)
const children = typeof props.children === 'function' ? props.children({isExpanded}) : props.children
return (
<>
<div className={clsx('PRIVATE_VisuallyHidden', classes.TreeViewVisuallyHidden)} aria-hidden={true}>
{props.label}
</div>
<div
className={clsx('PRIVATE_TreeView-item-leading-action', classes.TreeViewItemLeadingAction)}
aria-hidden={true}
>
{children}
</div>
</>
)
}
LeadingAction.displayName = 'TreeView.LeadingAction'
// ----------------------------------------------------------------------------
// TreeView.TrailingAction
export type TreeViewTrailingAction = {
items: TreeViewSecondaryActions[]
shortcutText: string
}
const TrailingAction = (props: TreeViewTrailingAction) => {
const {trailingActionId, itemId} = React.useContext(ItemContext)
const {items, shortcutText} = props
return (
<>
<div id={trailingActionId} className={clsx('PRIVATE_VisuallyHidden', classes.TreeViewVisuallyHidden)}>
- {shortcutText}
</div>
<div
className={classes.TreeViewItemTrailingAction}
aria-hidden={true}
onClick={event =>
// Prevent focus event from bubbling up to parent items
// This is needed to prevent the TreeView from interfering with trailing actions
event.stopPropagation()
}
onKeyDown={event => event.stopPropagation()}
>
{items.map(({label, onClick, icon, count, className}, index) => {
// If there is a count, we render a Button instead of an IconButton,
// as IconButton doesn't support displaying a count.
if (count) {
return (
<Tooltip key={index} text={label}>
<Button
aria-label={label}
leadingVisual={icon}
variant="invisible"
className={clsx(className, classes.TreeViewItemTrailingActionButton)}
onClick={onClick}
onKeyDown={() => {
// hack to send focus back to the tree item after the action is triggered via click
// this is needed because the trailing action shouldn't be focused, as it does not interact well with
// the focus management of TreeView
const parentElement = document.getElementById(itemId)
parentElement?.focus()
}}
tabIndex={-1}
aria-hidden={true}
count={count}
/>
</Tooltip>
)
}
return (
<IconButton
icon={icon}
variant="invisible"
aria-label={label}
className={clsx(className, classes.TreeViewItemTrailingActionButton)}
onClick={onClick}
tabIndex={-1}
aria-hidden={true}
key={index}
onKeyDown={() => {
const parentElement = document.getElementById(itemId)
parentElement?.focus()
}}
/>
)
})}
</div>
</>
)
}
TrailingAction.displayName = 'TreeView.TrailingAction'
// ----------------------------------------------------------------------------
// TreeView.ActionDialog
export type TreeViewActionDialogProps = {
items: TreeViewSecondaryActions[]
onClose?: () => void
}
const ActionDialog: React.FC<TreeViewActionDialogProps> = ({items, onClose}) => {
const {itemId} = React.useContext(ItemContext)
return (
<div
onClick={event => {
// Prevent click events from bubbling up to the TreeView
// and interfering with keyboard navigation
event.stopPropagation()
}}
onKeyDown={event => {
if (['Backspace', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Enter'].includes(event.key)) {
// Prevent keyboard events from bubbling up to the TreeView
// and interfering with keyboard navigation
event.stopPropagation()
}
}}
>
<Dialog
title="Supplemental actions"
onClose={() => {
if (onClose) {
onClose()
}
// Focus parent item after the dialog is closed
setTimeout(() => {
const parentElement = document.getElementById(itemId)
parentElement?.focus()
})
}}
>
<ActionList>
{items.map(({label, onClick, icon: Icon, count}, index) => (
<ActionList.Item key={index} onSelect={onClick}>
<ActionList.LeadingVisual>
<Icon />
</ActionList.LeadingVisual>
{label}
{count ? (
<ActionList.TrailingVisual>
{count}
<VisuallyHidden>items</VisuallyHidden>
</ActionList.TrailingVisual>
) : null}
</ActionList.Item>
))}
</ActionList>
</Dialog>
</div>
)
}
ActionDialog.displayName = 'TreeView.ActionDialog'
// ----------------------------------------------------------------------------
// TreeView.DirectoryIcon
const DirectoryIcon = () => {
const {isExpanded} = React.useContext(ItemContext)
const Icon = isExpanded ? FileDirectoryOpenFillIcon : FileDirectoryFillIcon
return (
<div className={clsx('PRIVATE_TreeView-directory-icon', classes.TreeViewDirectoryIcon)}>
<Icon />
</div>
)
}
// ----------------------------------------------------------------------------
// TreeView.ErrorDialog
export type TreeViewErrorDialogProps = {
children: React.ReactNode
title?: string
onRetry?: () => void
onDismiss?: () => void
}
const ErrorDialog: React.FC<TreeViewErrorDialogProps> = ({title = 'Error', children, onRetry, onDismiss}) => {
const {itemId, setIsExpanded} = React.useContext(ItemContext)
return (
<div
onKeyDown={event => {
if (['Backspace', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Enter'].includes(event.key)) {
// Prevent keyboard events from bubbling up to the TreeView
// and interfering with keyboard navigation
event.stopPropagation()
}
}}
>
<ConfirmationDialog
title={title}
onClose={gesture => {
// Focus parent item after the dialog is closed
setTimeout(() => {
const parentElement = document.getElementById(itemId)
parentElement?.focus()
})
if (gesture === 'confirm') {
onRetry?.()
} else {
setIsExpanded(false)
onDismiss?.()
}
}}
confirmButtonContent="Retry"
cancelButtonContent="Dismiss"
>
{children}
</ConfirmationDialog>
</div>
)
}
ErrorDialog.displayName = 'TreeView.ErrorDialog'
// ----------------------------------------------------------------------------
// Export
export const TreeView = Object.assign(Root, {
Item,
SubTree,
LeadingAction,
LeadingVisual,
TrailingVisual,
DirectoryIcon,
ErrorDialog,
})