package.react-utils.useRestoreScrollPosition.useRestoreScrollPosition.js Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of neeto-commons-frontend Show documentation
Show all versions of neeto-commons-frontend Show documentation
A package encapsulating common code across neeto projects including initializers, utility functions, common components and hooks and so on.
import { useEffect } from "react";
import { assoc, dissoc, prop } from "ramda";
import useFuncDebounce from "../useFuncDebounce";
import withImmutableActions from "../withImmutableActions";
import { create } from "zustand";
/** @type {import("neetocommons/react-utils").ZustandStoreHook} */
var useScrollStore = create(withImmutableActions(function (set, get) {
return {
scrollPositions: {},
setScrollPosition: function setScrollPosition(key, value) {
return set(function (state) {
return {
scrollPositions: assoc(key, value, state.scrollPositions)
};
});
},
removeScrollPosition: function removeScrollPosition(key) {
return set(function (state) {
return {
scrollPositions: dissoc(key, state.scrollPositions)
};
});
},
getScrollPosition: function getScrollPosition(key) {
return get().scrollPositions[key];
}
};
}));
var useRestoreScrollPosition = function useRestoreScrollPosition(key, ref) {
var setScrollPosition = useScrollStore(prop("setScrollPosition"));
var getScrollPosition = useScrollStore(prop("getScrollPosition"));
var handleScroll = useFuncDebounce(function () {
if (!ref.current) return;
setScrollPosition(key, ref.current.scrollTop);
}, 500);
useEffect(function () {
if (ref.current) {
var savedScrollPosition = getScrollPosition(key);
if (savedScrollPosition !== undefined) {
ref.current.scrollTop = savedScrollPosition;
}
ref.current.addEventListener("scroll", handleScroll);
}
return function () {
if (ref.current) {
ref.current.removeEventListener("scroll", handleScroll);
}
};
}, [key]);
};
export var useSetScrollPosition = function useSetScrollPosition() {
return useScrollStore(prop("setScrollPosition"));
};
export var useGetScrollPosition = function useGetScrollPosition() {
return useScrollStore(prop("getScrollPosition"));
};
export var useRemoveScrollPosition = function useRemoveScrollPosition() {
return useScrollStore(prop("removeScrollPosition"));
};
export default useRestoreScrollPosition;
//# sourceMappingURL=useRestoreScrollPosition.js.map