@@ -295,24 +295,26 @@ function TreeViewFinderComponant(props: Readonly<TreeViewFinderProps>) {
295
295
} , [ expandedProp ] ) ;
296
296
297
297
useEffect ( ( ) => {
298
- if ( ! selectedProp ) {
298
+ const hasSelected = selectedProp && selectedProp . length > 0 ;
299
+ const hasExpanded = expandedProp && expandedProp . length > 0 ;
300
+
301
+ // Only proceed if we have either selected or expanded elements and auto scroll is allowed
302
+ if ( ( ! hasSelected && ! hasExpanded ) || ! autoScrollAllowed ) {
299
303
return ;
300
304
}
301
- // if we have selected elements by default, we scroll to it
302
- if ( selectedProp . length > 0 && autoScrollAllowed ) {
303
- // we check if all expanded nodes by default all already expanded first
304
- const isNodeExpanded = expandedProp ?. every ( ( itemId ) => expanded ?. includes ( itemId ) ) ;
305
-
306
- // we got the last element that we suppose to scroll to
307
- const lastScrollRef = scrollRef . current [ scrollRef . current . length - 1 ] ;
308
- if ( isNodeExpanded && lastScrollRef ) {
309
- lastScrollRef . scrollIntoView ( {
310
- behavior : 'smooth' ,
311
- block : 'center' ,
312
- inline : 'center' ,
313
- } ) ;
314
- setAutoScrollAllowed ( false ) ;
315
- }
305
+
306
+ // we check if all expanded nodes by default all already expanded first
307
+ const isNodeExpanded = expandedProp ?. every ( ( itemId ) => expanded ?. includes ( itemId ) ) ;
308
+
309
+ // we got the last element that we suppose to scroll to
310
+ const lastScrollRef = scrollRef . current [ scrollRef . current . length - 1 ] ;
311
+ if ( isNodeExpanded && lastScrollRef ) {
312
+ lastScrollRef . scrollIntoView ( {
313
+ behavior : 'smooth' ,
314
+ block : 'center' ,
315
+ inline : 'center' ,
316
+ } ) ;
317
+ setAutoScrollAllowed ( false ) ;
316
318
}
317
319
} , [ expanded , selectedProp , expandedProp , data , autoScrollAllowed ] ) ;
318
320
@@ -412,7 +414,13 @@ function TreeViewFinderComponant(props: Readonly<TreeViewFinderProps>) {
412
414
} ,
413
415
} }
414
416
ref = { ( element ) => {
415
- if ( selectedProp ?. includes ( node . id ) ) {
417
+ // Add to scroll ref if it's a selected element, or if no selected elements and it's an expanded element
418
+ const shouldAddToScrollRef =
419
+ selectedProp && selectedProp . length > 0
420
+ ? selectedProp . includes ( node . id )
421
+ : ( expandedProp ?. includes ( node . id ) ?? false ) ;
422
+
423
+ if ( shouldAddToScrollRef ) {
416
424
scrollRef . current . push ( element ) ;
417
425
}
418
426
} }
0 commit comments