From d922734f93fa229796b7ae7d2a288104895ec0eb Mon Sep 17 00:00:00 2001 From: Benjamin Arias Date: Fri, 9 Sep 2022 09:45:02 +0200 Subject: [PATCH] =?UTF-8?q?Sauvegarde=20de=20la=20position=20de=20scroll?= =?UTF-8?q?=20page=20suivante/pr=C3=A9c=C3=A9dente=20(#2273)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: add useSaveScrollPosition hook + CustomRouter * fix: Remplace useLayoutEffect par useEffect * feat: remplace l'usage d'history par un event listener * chore: Renommage du hook --- site/source/App.tsx | 3 ++ .../hooks/useSaveAndRestoreScrollPosition.ts | 30 +++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 site/source/hooks/useSaveAndRestoreScrollPosition.ts diff --git a/site/source/App.tsx b/site/source/App.tsx index 584ad2104..589300b1c 100644 --- a/site/source/App.tsx +++ b/site/source/App.tsx @@ -23,6 +23,7 @@ import { useTranslation } from 'react-i18next' import { useSelector } from 'react-redux' import { Route, Routes } from 'react-router-dom' import styled, { css } from 'styled-components' +import { useSaveAndRestoreScrollPosition } from './hooks/useSaveAndRestoreScrollPosition' import Accessibilité from './pages/Accessibilité' import Budget from './pages/Budget/Budget' import Créer from './pages/Creer' @@ -109,6 +110,8 @@ const App = () => { const { relativeSitePaths } = useSitePaths() const isEmbedded = useIsEmbedded() + useSaveAndRestoreScrollPosition() + return ( {!isEmbedded &&
} diff --git a/site/source/hooks/useSaveAndRestoreScrollPosition.ts b/site/source/hooks/useSaveAndRestoreScrollPosition.ts new file mode 100644 index 000000000..a3010d291 --- /dev/null +++ b/site/source/hooks/useSaveAndRestoreScrollPosition.ts @@ -0,0 +1,30 @@ +import { debounce } from '@/utils' +import { useEffect } from 'react' +import { useLocation, useNavigationType } from 'react-router-dom' + +const POP_ACTION_LABEL = 'POP' + +export const useSaveAndRestoreScrollPosition = () => { + const location = useLocation() + const navigationType = useNavigationType() + + useEffect(() => { + const scrollPosition = sessionStorage.getItem(location.pathname) + + if (scrollPosition && navigationType === POP_ACTION_LABEL) { + window.scrollTo(0, parseInt(scrollPosition)) + } + }, [location, navigationType]) + + useEffect(() => { + const saveScrollYPosition = debounce(100, () => { + sessionStorage.setItem(location.pathname, String(window.scrollY)) + }) as (this: Window, ev: Event) => any + + window.addEventListener('scroll', saveScrollYPosition) + + return () => { + window.removeEventListener('scroll', saveScrollYPosition) + } + }, [location.pathname]) +}