Sauvegarde de la position de scroll page suivante/précédente (#2273)

* feat: add useSaveScrollPosition hook + CustomRouter

* fix: Remplace useLayoutEffect par useEffect

* feat: remplace l'usage d'history par un event listener

* chore: Renommage du hook
pull/2277/head
Benjamin Arias 2022-09-09 09:45:02 +02:00 committed by GitHub
parent 3b57fc87de
commit d922734f93
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 0 deletions

View File

@ -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 (
<StyledLayout isEmbeded={isEmbedded}>
{!isEmbedded && <Header />}

View File

@ -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])
}