@@ -57,6 +57,7 @@ interface IUseTreeProps {
57
57
onExpand ?: ( props : ITreeViewOnExpandProps ) => void ;
58
58
multiSelect ?: boolean ;
59
59
propagateSelectUpwards ?: boolean ;
60
+ treeRef ?: React . MutableRefObject < HTMLUListElement | null > ;
60
61
propagateSelect ?: boolean ;
61
62
// eslint-disable-next-line @typescript-eslint/no-explicit-any
62
63
onLoadData ?: ( props : ITreeViewOnLoadDataProps ) => Promise < any > ;
@@ -80,6 +81,7 @@ const useTree = ({
80
81
multiSelect,
81
82
propagateSelect,
82
83
propagateSelectUpwards,
84
+ treeRef,
83
85
} : IUseTreeProps ) => {
84
86
const treeParentNode = getTreeParent ( data ) ;
85
87
const [ state , dispatch ] = useReducer ( treeReducer , {
@@ -417,10 +419,16 @@ const useTree = ({
417
419
nodeRefs ?. current != null &&
418
420
leafRefs ?. current != null
419
421
) {
420
- const tabbableNode = nodeRefs . current [ tabbableId ] ;
421
- const leafNode = leafRefs . current [ lastInteractedWith ] ;
422
- scrollToRef ( leafNode ) ;
423
- focusRef ( tabbableNode ) ;
422
+ const isTreeActive = ( treeRef ?. current == null ) ||
423
+ ( document . activeElement && treeRef . current . contains ( document . activeElement ) ) ;
424
+ if ( isTreeActive ) {
425
+ // Only scroll and focus on the tree when it is the active element on the page.
426
+ // This prevents controlled updates from scrolling to the tree and giving it focus.
427
+ const tabbableNode = nodeRefs . current [ tabbableId ] ;
428
+ const leafNode = leafRefs . current [ lastInteractedWith ] ;
429
+ scrollToRef ( leafNode ) ;
430
+ focusRef ( tabbableNode ) ;
431
+ }
424
432
}
425
433
} , [ tabbableId , nodeRefs , leafRefs , lastInteractedWith ] ) ;
426
434
@@ -543,6 +551,10 @@ const TreeView = React.forwardRef<HTMLUListElement, ITreeViewProps>(
543
551
validateTreeViewData ( data ) ;
544
552
const nodeRefs = useRef ( { } ) ;
545
553
const leafRefs = useRef ( { } ) ;
554
+ let innerRef = useRef < HTMLUListElement | null > ( null ) ;
555
+ if ( ref != null ) {
556
+ innerRef = ref as React . MutableRefObject < HTMLUListElement > ;
557
+ }
546
558
const [ state , dispatch ] = useTree ( {
547
559
data,
548
560
controlledSelectedIds : selectedIds ,
@@ -560,14 +572,10 @@ const TreeView = React.forwardRef<HTMLUListElement, ITreeViewProps>(
560
572
multiSelect,
561
573
propagateSelect,
562
574
propagateSelectUpwards,
575
+ treeRef : innerRef ,
563
576
} ) ;
564
577
propagateSelect = propagateSelect && multiSelect ;
565
578
566
- let innerRef = useRef < HTMLUListElement | null > ( null ) ;
567
- if ( ref != null ) {
568
- innerRef = ref as React . MutableRefObject < HTMLUListElement > ;
569
- }
570
-
571
579
return (
572
580
< ul
573
581
className = { cx ( baseClassNames . root , className ) }
0 commit comments