ra-core
Version:
Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React
79 lines • 2.77 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useTrackScrollPosition = exports.useRestoreScrollPosition = void 0;
const react_1 = require("react");
const debounce_js_1 = __importDefault(require("lodash/debounce.js"));
const store_1 = require("../store/index.cjs");
const useLocation_1 = require("./useLocation.cjs");
/**
* A hook that tracks the scroll position and restores it when the component mounts.
* @param storeKey The key under which to store the scroll position in the store
* @param debounceMs The debounce time in milliseconds
*
* @example
* import { useRestoreScrollPosition } from 'ra-core';
*
* const MyCustomPage = () => {
* useRestoreScrollPosition('my-list');
*
* return (
* <div>
* <h1>My Custom Page</h1>
* <VeryLongContent />
* </div>
* );
* };
*/
const useRestoreScrollPosition = (storeKey, debounceMs = 250) => {
const [position, setPosition] = (0, exports.useTrackScrollPosition)(storeKey, debounceMs);
const location = (0, useLocation_1.useLocation)();
(0, react_1.useEffect)(() => {
if (position != null && location.state?._scrollToTop !== true) {
setPosition(undefined);
window.scrollTo(0, position);
}
// We only want to run this effect on mount
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
};
exports.useRestoreScrollPosition = useRestoreScrollPosition;
/**
* A hook that tracks the scroll position and stores it.
* @param storeKey The key under which to store the scroll position in the store
* @param debounceMs The debounce time in milliseconds
*
* @example
* import { useTrackScrollPosition } from 'ra-core';
*
* const MyCustomPage = () => {
* useTrackScrollPosition('my-list');
*
* return (
* <div>
* <h1>My Custom Page</h1>
* <VeryLongContent />
* </div>
* );
* };
*/
const useTrackScrollPosition = (storeKey, debounceMs = 250) => {
const [position, setPosition] = (0, store_1.useStore)(storeKey);
(0, react_1.useEffect)(() => {
if (typeof window === 'undefined') {
return;
}
const handleScroll = (0, debounce_js_1.default)(() => {
setPosition(window.scrollY);
}, debounceMs);
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, [debounceMs, setPosition]);
return [position, setPosition];
};
exports.useTrackScrollPosition = useTrackScrollPosition;
//# sourceMappingURL=useRestoreScrollPosition.js.map