mirror of
https://github.com/facebook/docusaurus.git
synced 2025-07-07 11:57:55 +02:00
feat(v2): add back to top button (#4912)
* feat(v2): add back to top button * Test on mobiles * Use clean-btn class * Fix case * clearer useScrollPosition() hook * fix useScrollPosition typing + dangerous 0 fallback value + refactor a bit backToTop button * useless fallback * Handle both browsers with/without native smooth scrollBehavior support * fix SupportsNativeSmoothScrolling using document on SSR * revert to smoothScrollTopPolyfill usage Co-authored-by: slorber <lorber.sebastien@gmail.com>
This commit is contained in:
parent
bb0c9eed0d
commit
c935fe2a37
6 changed files with 187 additions and 11 deletions
|
@ -9,25 +9,32 @@ import {useEffect, useRef} from 'react';
|
|||
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
|
||||
import type {ScrollPosition} from '@theme/hooks/useScrollPosition';
|
||||
|
||||
const getScrollPosition = (): ScrollPosition => ({
|
||||
scrollX: ExecutionEnvironment.canUseDOM ? window.pageXOffset : 0,
|
||||
scrollY: ExecutionEnvironment.canUseDOM ? window.pageYOffset : 0,
|
||||
});
|
||||
const getScrollPosition = (): ScrollPosition | null => {
|
||||
return ExecutionEnvironment.canUseDOM
|
||||
? {
|
||||
scrollX: window.pageXOffset,
|
||||
scrollY: window.pageYOffset,
|
||||
}
|
||||
: null;
|
||||
};
|
||||
|
||||
const useScrollPosition = (
|
||||
effect?: (position: ScrollPosition, lastPosition: ScrollPosition) => void,
|
||||
effect: (
|
||||
position: ScrollPosition,
|
||||
lastPosition: ScrollPosition | null,
|
||||
) => void,
|
||||
deps = [],
|
||||
): void => {
|
||||
const scrollPosition = useRef(getScrollPosition());
|
||||
const lastPositionRef = useRef<ScrollPosition | null>(getScrollPosition());
|
||||
|
||||
const handleScroll = () => {
|
||||
const currentScrollPosition = getScrollPosition();
|
||||
const currentPosition = getScrollPosition()!;
|
||||
|
||||
if (effect) {
|
||||
effect(currentScrollPosition, scrollPosition.current);
|
||||
effect(currentPosition, lastPositionRef.current);
|
||||
}
|
||||
|
||||
scrollPosition.current = currentScrollPosition;
|
||||
lastPositionRef.current = currentPosition;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue