Implement <ScrollRestoration /> (#5086)
### Description Implement <ScrollRestoration /> ### Refs [https://github.com/twentyhq/twenty/issues/4357](https://github.com/twentyhq/twenty/issues/4183) ### Demo https://github.com/twentyhq/twenty/assets/140154534/321242e1-4751-4204-8c86-e9b921c1733e Fixes #4357 --------- Co-authored-by: gitstart-twenty <gitstart-twenty@users.noreply.github.com> Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com> Co-authored-by: v1b3m <vibenjamin6@gmail.com> Co-authored-by: RubensRafael <rubensrafael2@live.com>
This commit is contained in:
committed by
GitHub
parent
992602b307
commit
0e525caf01
34
packages/twenty-front/src/hooks/useScrollRestoration.ts
Normal file
34
packages/twenty-front/src/hooks/useScrollRestoration.ts
Normal file
@ -0,0 +1,34 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useLocation, useNavigation } from 'react-router-dom';
|
||||
import { useRecoilState, useRecoilValue } from 'recoil';
|
||||
|
||||
import { overlayScrollbarsState } from '@/ui/utilities/scroll/states/overlayScrollbarsState';
|
||||
import { scrollPositionState } from '@/ui/utilities/scroll/states/scrollPositionState';
|
||||
import { isDefined } from '~/utils/isDefined';
|
||||
|
||||
/**
|
||||
* Note that `location.key` is used in the cache key, not `location.pathname`,
|
||||
* so the same path navigated to at different points in the history stack will
|
||||
* not share the same scroll position.
|
||||
*/
|
||||
export const useScrollRestoration = (viewportHeight?: number) => {
|
||||
const key = `scroll-position-${useLocation().key}`;
|
||||
const { state } = useNavigation();
|
||||
|
||||
const [scrollPosition, setScrollPosition] = useRecoilState(
|
||||
scrollPositionState(key),
|
||||
);
|
||||
|
||||
const overlayScrollbars = useRecoilValue(overlayScrollbarsState);
|
||||
|
||||
const scrollWrapper = overlayScrollbars?.elements().viewport;
|
||||
const skip = isDefined(viewportHeight) && scrollPosition > viewportHeight;
|
||||
|
||||
useEffect(() => {
|
||||
if (state === 'loading') {
|
||||
setScrollPosition(scrollWrapper?.scrollTop ?? 0);
|
||||
} else if (state === 'idle' && isDefined(scrollWrapper) && !skip) {
|
||||
scrollWrapper.scrollTo({ top: scrollPosition });
|
||||
}
|
||||
}, [key, state, scrollWrapper, skip, scrollPosition, setScrollPosition]);
|
||||
};
|
||||
Reference in New Issue
Block a user