This repository has been archived by the owner on Feb 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 219
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactor withScrollToTop to remove useCallback and use typescript
- Loading branch information
1 parent
0905b40
commit e62c42b
Showing
2 changed files
with
77 additions
and
83 deletions.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
/** | ||
* External dependencies | ||
*/ | ||
import { useRef } from '@wordpress/element'; | ||
|
||
/** | ||
* Internal dependencies | ||
*/ | ||
import './style.scss'; | ||
|
||
interface ScrollToTopProps { | ||
focusableSelector?: string; | ||
} | ||
|
||
const maybeScrollToTop = ( scrollPoint: HTMLElement ): void => { | ||
const yPos = scrollPoint.getBoundingClientRect().bottom; | ||
const isScrollPointVisible = yPos >= 0 && yPos <= window.innerHeight; | ||
|
||
if ( ! isScrollPointVisible ) { | ||
scrollPoint.scrollIntoView(); | ||
} | ||
}; | ||
|
||
const moveFocusToTop = ( | ||
scrollPoint: HTMLElement, | ||
focusableSelector: string | ||
): void => { | ||
const focusableElements = | ||
scrollPoint.parentElement?.querySelectorAll( focusableSelector ) || []; | ||
|
||
if ( focusableElements.length ) { | ||
( focusableElements[ 0 ] as HTMLElement )?.focus(); | ||
} | ||
}; | ||
|
||
const scrollToHTMLElement = ( | ||
scrollPoint: HTMLElement, | ||
{ focusableSelector }: ScrollToTopProps | ||
): void => { | ||
if ( ! window || ! Number.isFinite( window.innerHeight ) ) { | ||
return; | ||
} | ||
|
||
maybeScrollToTop( scrollPoint ); | ||
|
||
if ( focusableSelector ) { | ||
moveFocusToTop( scrollPoint, focusableSelector ); | ||
} | ||
}; | ||
|
||
/** | ||
* 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; |