@resourge/react-fetch
Version:
[](LICENSE)
60 lines (57 loc) • 1.82 kB
JavaScript
/**
* react-fetch v1.41.3
*
* Copyright (c) resourge.
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
import { useRef, useEffect } from 'react';
import { ScrollRestorationIdIsUndefined } from '../errors/ScrollRestorationIdIsUndefined';
import { IS_DEV } from '../utils/constants';
import { useOnScroll } from './useOnScroll/useOnScroll';
const useBaseScrollRestoration = (visitedUrl, action, scrollRestorationId = (_window => (_window = window) == null || (_window = _window.location) == null ? void 0 : _window.pathname)()) => {
if (IS_DEV) {
if (!scrollRestorationId) {
throw new ScrollRestorationIdIsUndefined();
}
}
const canRestore = useRef(false);
const [ref, onScroll] = useOnScroll(pos => {
const existingRecord = visitedUrl.get(scrollRestorationId);
visitedUrl.set(scrollRestorationId, {
...existingRecord,
pos
});
});
useEffect(() => {
canRestore.current = action === 'pop';
}, [action]);
useEffect(() => {
if (action !== 'pop') {
visitedUrl.delete(scrollRestorationId);
}
}, []);
const scrollRestore = (behavior = 'auto') => {
if (canRestore.current) {
const existingRecord = visitedUrl.get(scrollRestorationId);
if (existingRecord !== undefined) {
globalThis.requestAnimationFrame(() => {
if (ref.current) {
ref.current.scrollTo({
...existingRecord,
behavior,
animated: behavior === 'smooth'
});
}
});
visitedUrl.delete(scrollRestorationId);
}
}
};
return [scrollRestore, ref, onScroll];
};
export { useBaseScrollRestoration };
//# sourceMappingURL=useBaseScrollRestoration.js.map