@@ -25,6 +25,11 @@ class FocusOnScroll extends React.Component<IFocusOnScrollProps, IFocusOnScrollS
2525 super ( props ) ;
2626 this . state = {
2727 focusIndex : getFocusIndex ( this . props . focusOn ) ,
28+ /** focusOnTriggered: This field prevents scroll event listener to execute
29+ * when user specified focused index. It means in focusOnHandler
30+ * when we call window.scrollY() function it prevents triggering scroll event
31+ **/
32+ focusOnTriggered : false ,
2833 } ;
2934 }
3035 private debounceResizeHandler = ( ) => debounce ( this . scrollHandler , DELAY_TIME_IN_MS ) ;
@@ -63,9 +68,21 @@ class FocusOnScroll extends React.Component<IFocusOnScrollProps, IFocusOnScrollS
6368 return ;
6469 }
6570 const { height } = focusElement . getBoundingClientRect ( ) ;
66- const scrollPosition = ( focusElement . offsetTop + ( height / 2 ) ) - ( window . innerHeight / 2 ) ;
67- window . scrollTo ( 0 , scrollPosition - 1 ) ;
68- this . setFocusIndex ( focusIndex ) ;
71+ const scrollPosition = Math . max ( ( focusElement . offsetTop + ( height / 2 ) ) - ( window . innerHeight / 2 ) , 1 ) ;
72+
73+ this . setState ( {
74+ focusOnTriggered : true ,
75+ } , ( ) => {
76+ window . scrollTo ( {
77+ top : scrollPosition - 1 ,
78+ left : 0 ,
79+ behavior : 'smooth' ,
80+ } ) ;
81+ this . setFocusIndex ( focusIndex ) ;
82+ setTimeout ( ( ) => {
83+ this . setState ( { focusOnTriggered : false } ) ;
84+ } , DELAY_TIME_IN_MS ) ;
85+ } ) ;
6986 }
7087
7188 /**
@@ -91,6 +108,9 @@ class FocusOnScroll extends React.Component<IFocusOnScrollProps, IFocusOnScrollS
91108 }
92109
93110 public scrollHandler = ( ) : void => {
111+ if ( this . state . focusOnTriggered ) {
112+ return ;
113+ }
94114 const focusIndex = findFocusElement ( ) ;
95115 if ( focusIndex ) {
96116 this . setFocusIndex ( focusIndex ) ;
0 commit comments