UNPKG

ra-core

Version:

Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React

82 lines 2.96 kB
"use strict"; 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; var react_1 = require("react"); var react_router_1 = require("react-router"); var debounce_1 = __importDefault(require("lodash/debounce")); var store_1 = require("../store"); /** * 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> * ); * }; */ var useRestoreScrollPosition = function (storeKey, debounceMs) { if (debounceMs === void 0) { debounceMs = 250; } var _a = (0, exports.useTrackScrollPosition)(storeKey, debounceMs), position = _a[0], setPosition = _a[1]; var location = (0, react_router_1.useLocation)(); (0, react_1.useEffect)(function () { var _a; if (position != null && ((_a = location.state) === null || _a === void 0 ? void 0 : _a._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> * ); * }; */ var useTrackScrollPosition = function (storeKey, debounceMs) { if (debounceMs === void 0) { debounceMs = 250; } var _a = (0, store_1.useStore)(storeKey), position = _a[0], setPosition = _a[1]; (0, react_1.useEffect)(function () { if (typeof window === 'undefined') { return; } var handleScroll = (0, debounce_1.default)(function () { setPosition(window.scrollY); }, debounceMs); window.addEventListener('scroll', handleScroll); return function () { window.removeEventListener('scroll', handleScroll); }; }, [debounceMs, setPosition]); return [position, setPosition]; }; exports.useTrackScrollPosition = useTrackScrollPosition; //# sourceMappingURL=useRestoreScrollPosition.js.map