File size: 1,551 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
import { useEffect, useRef } from '@wordpress/element';
/**
* Persist the value in memory so when the element is unmounted it doesn't get lost.
*/
const cachedScrollPositions: Record< string, number > = {};
export const useHelpCenterArticleScroll = (
postId: number | undefined,
scrollParentRef: React.RefObject< HTMLElement >
) => {
const timeoutRef = useRef< ReturnType< typeof setTimeout > | null >( null );
useEffect( () => {
if ( ! postId || ! scrollParentRef?.current ) {
return;
}
const scrollRef = scrollParentRef?.current;
const scrollBehaviour = scrollRef.style.scrollBehavior;
// temporary disable smooth scrolling
scrollRef.style.scrollBehavior = 'auto';
if ( cachedScrollPositions[ postId ] ) {
scrollRef.scrollTop = cachedScrollPositions[ postId ];
} else {
scrollRef.scrollTop = 0;
}
// restore smooth scrolling
scrollRef.style.scrollBehavior = scrollBehaviour;
const handleScroll = ( event: { target: EventTarget | null } ) => {
if ( timeoutRef.current ) {
clearTimeout( timeoutRef.current );
}
timeoutRef.current = setTimeout( () => {
if ( event.target === scrollParentRef.current ) {
cachedScrollPositions[ postId ] = Number( scrollRef.scrollTop );
}
}, 250 );
};
scrollRef.addEventListener( 'scroll', handleScroll );
return () => {
if ( timeoutRef.current ) {
clearTimeout( timeoutRef.current ); // Clear the timeout during cleanup
}
scrollRef?.removeEventListener( 'scroll', handleScroll );
};
}, [ postId, scrollParentRef ] );
};
|