@@ -64,13 +64,37 @@ settingsContainer?.addEventListener("mouseleave", () => {
6464settingsContainer ?. addEventListener ( "mousemove" , resetInteractionTimeout ) ;
6565settingsContainer ?. addEventListener ( "click" , resetInteractionTimeout ) ;
6666
67+ // Keeps track of how many clicked anchors we're waiting for
68+ let activeAnchorScrolls = 0 ;
69+
70+ // Returns a promise that resolves when scrolling stops. It checks every 200ms
71+ // until the scrollTop stops changing.
72+ function waitUntilScrollFinishes ( ) {
73+ return new Promise ( ( resolve ) => {
74+ let prevScrollTop = window . scrollY || document . documentElement . scrollTop ;
75+ const wait = ( ) => setTimeout ( ( ) => {
76+ const scrollTop = window . scrollY || document . documentElement . scrollTop ;
77+ if ( scrollTop === prevScrollTop ) {
78+ resolve ( )
79+ } else {
80+ prevScrollTop = scrollTop ;
81+ wait ( ) ;
82+ }
83+ } , 200 ) ;
84+ wait ( ) ;
85+ } )
86+ }
87+
6788// When the user scrolls up, open the settings container
6889window . addEventListener (
6990 "scroll" ,
7091 ( ) => {
7192 let currentScroll = window . scrollY || document . documentElement . scrollTop ;
72- // if we're scrolled up to where the container lives, close immediately
73- if ( currentScroll < 120 ) {
93+
94+ if ( activeAnchorScrolls > 0 ) {
95+ // Do nothing if the scroll is from clicking an anchor link
96+ } else if ( currentScroll < 120 ) {
97+ // if we're scrolled up to where the container lives, close immediately
7498 closeSettings ( ) ;
7599 } else if (
76100 lastScrollTop > currentScroll &&
@@ -84,3 +108,26 @@ window.addEventListener(
84108 } ,
85109 false ,
86110) ;
111+
112+ const preventSettings = ( ) => {
113+ activeAnchorScrolls ++ ;
114+ waitUntilScrollFinishes ( ) . then ( ( ) => {
115+ activeAnchorScrolls -- ;
116+ } ) ;
117+ } ;
118+
119+ const mutationObserver = new MutationObserver ( ( mutations ) => {
120+ for ( const mutation of mutations ) {
121+ for ( const node of mutation . addedNodes ) {
122+ if ( node . nodeName === 'A' && node . getAttribute ( 'href' ) && node . getAttribute ( 'href' ) . startsWith ( '#' ) ) {
123+ node . addEventListener ( 'click' , preventSettings ) ;
124+ }
125+ }
126+ }
127+ } ) ;
128+ mutationObserver . observe ( document , { childList : true } ) ;
129+ window . addEventListener ( 'load' , ( ) => {
130+ for ( const a of document . querySelectorAll ( 'a[href^="#"]' ) ) {
131+ a . addEventListener ( 'click' , preventSettings ) ;
132+ }
133+ } ) ;
0 commit comments