2021-07-22 11:03:00 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import { useRef } from '@wordpress/element';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
|
|
|
import './style.scss';
|
|
|
|
|
|
|
|
interface ScrollToTopProps {
|
|
|
|
focusableSelector?: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
const maybeScrollToTop = ( scrollPoint: HTMLElement ): void => {
|
2021-07-26 14:05:09 +00:00
|
|
|
if ( ! scrollPoint ) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-07-22 11:03:00 +00:00
|
|
|
const yPos = scrollPoint.getBoundingClientRect().bottom;
|
|
|
|
const isScrollPointVisible = yPos >= 0 && yPos <= window.innerHeight;
|
|
|
|
|
|
|
|
if ( ! isScrollPointVisible ) {
|
|
|
|
scrollPoint.scrollIntoView();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2021-07-23 13:21:59 +00:00
|
|
|
const moveFocusToElement = (
|
2021-07-22 11:03:00 +00:00
|
|
|
scrollPoint: HTMLElement,
|
|
|
|
focusableSelector: string
|
|
|
|
): void => {
|
|
|
|
const focusableElements =
|
|
|
|
scrollPoint.parentElement?.querySelectorAll( focusableSelector ) || [];
|
|
|
|
|
|
|
|
if ( focusableElements.length ) {
|
2021-07-26 14:05:09 +00:00
|
|
|
const targetElement = focusableElements[ 0 ] as HTMLElement;
|
|
|
|
maybeScrollToTop( targetElement );
|
|
|
|
targetElement?.focus();
|
2021-07-23 13:21:59 +00:00
|
|
|
} else {
|
|
|
|
maybeScrollToTop( scrollPoint );
|
2021-07-22 11:03:00 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const scrollToHTMLElement = (
|
|
|
|
scrollPoint: HTMLElement,
|
2021-07-26 14:05:09 +00:00
|
|
|
options: ScrollToTopProps
|
2021-07-22 11:03:00 +00:00
|
|
|
): void => {
|
2021-07-26 14:05:09 +00:00
|
|
|
const { focusableSelector } = options || {};
|
|
|
|
|
2021-07-22 11:03:00 +00:00
|
|
|
if ( ! window || ! Number.isFinite( window.innerHeight ) ) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if ( focusableSelector ) {
|
2021-07-26 14:05:09 +00:00
|
|
|
moveFocusToElement( scrollPoint, focusableSelector );
|
2021-07-23 13:21:59 +00:00
|
|
|
} else {
|
|
|
|
maybeScrollToTop( scrollPoint );
|
2021-07-22 11:03:00 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* HOC that provides a function to scroll to the top of the component.
|
|
|
|
*/
|
|
|
|
const withScrollToTop = (
|
|
|
|
OriginalComponent: React.FunctionComponent< Record< string, unknown > >
|
|
|
|
) => {
|
|
|
|
return ( props: Record< string, unknown > ): JSX.Element => {
|
|
|
|
const scrollPointRef = useRef< HTMLDivElement >( null );
|
|
|
|
const scrollToTop = ( args: ScrollToTopProps ) => {
|
|
|
|
if ( scrollPointRef.current !== null ) {
|
|
|
|
scrollToHTMLElement( scrollPointRef.current, args );
|
|
|
|
}
|
|
|
|
};
|
|
|
|
return (
|
|
|
|
<>
|
|
|
|
<div
|
|
|
|
className="with-scroll-to-top__scroll-point"
|
|
|
|
ref={ scrollPointRef }
|
|
|
|
aria-hidden
|
|
|
|
/>
|
|
|
|
<OriginalComponent { ...props } scrollToTop={ scrollToTop } />
|
|
|
|
</>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
export default withScrollToTop;
|