Skip to content

Commit

Permalink
scroll position fix when entering new view
Browse files Browse the repository at this point in the history
  • Loading branch information
mmalmi committed Aug 25, 2023
1 parent b3d90e0 commit 28102be
Showing 1 changed file with 9 additions and 36 deletions.
45 changes: 9 additions & 36 deletions src/js/views/View.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ const listener = function () {
window.addEventListener('popstate', listener);

const View = ({ children, hideHeader = false, hideSideBar = false }) => {
const observerRef = useRef<any>(null);
const restoreScrollPosition = () => {
const currentHistoryState = window.history.state;
const position = currentHistoryState?.scrollPosition || 0;
window.scrollTo(0, position);
};

const saveScrollPosition = debounce(() => {
const position = window.scrollY || document.documentElement.scrollTop;
Expand All @@ -27,46 +31,15 @@ const View = ({ children, hideHeader = false, hideSideBar = false }) => {
window.history.replaceState(newHistoryState, '');
}, 100);

const restoreScrollPosition = (observe = true) => {
const currentHistoryState = window.history.state;
const previousHistoryState = window.history.state?.previousState;
if (!isInitialLoad && currentHistoryState !== previousHistoryState) {
observe && observeScrollElement();
const position = window.history.state?.scrollPosition || 0;
if (position) {
window.scrollTo(0, position);
}
useEffect(() => {
if (!isInitialLoad) {
restoreScrollPosition();
} else {
const oldState = window.history.state || {};
const newHistoryState = {
...oldState,
previousState: currentHistoryState,
};
window.history.replaceState(newHistoryState, '');
isInitialLoad = false;
}
};

const observeScrollElement = () => {
observerRef.current = new ResizeObserver((entries) => {
entries.forEach(() => {
restoreScrollPosition(false);
});
});

observerRef.current.observe(document.body);
setTimeout(() => {
observerRef.current.disconnect();
}, 1000);
};

useEffect(() => {
restoreScrollPosition();
window.addEventListener('scroll', saveScrollPosition);

return () => {
if (observerRef.current) {
observerRef.current.disconnect();
}
window.removeEventListener('scroll', saveScrollPosition);
};
}, []);
Expand Down

0 comments on commit 28102be

Please sign in to comment.