2022-05-13 04:21:08 +00:00
|
|
|
/**
|
2024-05-26 03:18:18 +00:00
|
|
|
* Initialize a direction observer based on scroll behavior.
|
2022-11-10 01:02:21 +00:00
|
|
|
*
|
2024-05-26 03:18:18 +00:00
|
|
|
* @param {Function} onScrollDown - Function to be called when scrolling down.
|
|
|
|
* @param {Function} onScrollUp - Function to be called when scrolling up.
|
|
|
|
* @param {number} threshold - The threshold for significant scroll position change.
|
2022-11-10 01:02:21 +00:00
|
|
|
*/
|
|
|
|
function initDirectionObserver( onScrollDown, onScrollUp, threshold ) {
|
|
|
|
let lastScrollTop = window.scrollY;
|
|
|
|
|
|
|
|
const onScroll = () => {
|
2024-05-26 03:18:18 +00:00
|
|
|
// Check if the scroll position has changed significantly
|
2022-11-10 01:02:21 +00:00
|
|
|
const scrollTop = window.scrollY;
|
|
|
|
|
|
|
|
if ( Math.abs( scrollTop - lastScrollTop ) < threshold ) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2024-05-26 03:18:18 +00:00
|
|
|
// Determine scroll direction and trigger appropriate functions
|
2022-11-10 01:02:21 +00:00
|
|
|
if ( scrollTop > lastScrollTop ) {
|
|
|
|
onScrollDown();
|
|
|
|
} else {
|
|
|
|
onScrollUp();
|
|
|
|
}
|
|
|
|
lastScrollTop = scrollTop;
|
|
|
|
};
|
|
|
|
|
2024-07-01 17:19:59 +00:00
|
|
|
const throttledOnScroll = mw.util.throttle( onScroll, 100 );
|
2024-06-10 02:58:17 +00:00
|
|
|
window.addEventListener( 'scroll', throttledOnScroll );
|
2022-11-10 01:02:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create an observer based on element visiblity.
|
2022-05-13 04:21:08 +00:00
|
|
|
* Based on Vector
|
|
|
|
*
|
2022-11-10 01:02:21 +00:00
|
|
|
* @param {Function} onHidden functionality for when the element is visible
|
|
|
|
* @param {Function} onVisible functionality for when the element is hidden
|
2022-05-13 04:21:08 +00:00
|
|
|
* @return {IntersectionObserver}
|
|
|
|
*/
|
2022-11-10 01:02:21 +00:00
|
|
|
function initIntersectionObserver( onHidden, onVisible ) {
|
2022-05-13 04:21:08 +00:00
|
|
|
/* eslint-disable-next-line compat/compat */
|
2024-05-26 03:18:18 +00:00
|
|
|
return new IntersectionObserver( ( [ entry ] ) => {
|
|
|
|
if ( entry.isIntersecting ) {
|
|
|
|
// Viewport is within the target element.
|
|
|
|
onVisible();
|
|
|
|
} else if ( entry.boundingClientRect.top < 0 ) {
|
2022-05-13 04:21:08 +00:00
|
|
|
// Viewport has crossed the bottom edge of the target element.
|
2022-11-10 01:02:21 +00:00
|
|
|
onHidden();
|
2022-05-13 04:21:08 +00:00
|
|
|
}
|
|
|
|
} );
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
2022-11-10 01:02:21 +00:00
|
|
|
initDirectionObserver,
|
|
|
|
initIntersectionObserver
|
2022-05-13 04:21:08 +00:00
|
|
|
};
|