routing: ignore repeats

This commit is contained in:
He4eT 2023-06-05 00:47:23 +03:00
commit 9f41e076ed
2 changed files with 30 additions and 24 deletions

View file

@ -20,7 +20,7 @@ import '~/src/style/base.css'
function App () {
const themeEngine = useThemeEngine()
const [location] = useHashLocation()
const [currentLocation] = useHashLocation()
const playerView = (themeEngine, singleWindow) =>
function view (params) {
@ -35,7 +35,7 @@ function App () {
<Router hook={useHashLocation}>
<div className={[
'app',
extractView(location),
extractView(currentLocation),
themeEngine.currentTheme].join(' ')}>
<Switch>

View file

@ -1,29 +1,10 @@
import {
useState, useEffect, useCallback,
useCallback, useEffect, useState,
} from 'preact/hooks'
export const useHashLocation = () => {
const currentLoc = () =>
const windowLocation = () =>
window.location.hash.replace('#', '') || '/'
const [loc, setLoc] = useState(currentLoc())
useEffect(() => {
const handler = () => {
setLoc(currentLoc())
window.scrollTo(0, 0)
}
handler()
window.addEventListener('hashchange', handler)
return () => window.removeEventListener('hashchange', handler)
}, [])
const navigate = useCallback((to) =>
(window.location.hash = to.replace('#/', '')), [])
return [loc, navigate]
}
export const buildPlayLinkHref = ({url}) =>
`/#/play/${encodeURIComponent(url)}`
@ -31,3 +12,28 @@ export const extractView = (location) => {
const currentView = location.split('/').filter(Boolean)[0]
return currentView || ''
}
export const useHashLocation = () => {
const [currentLocation, setCurrentLocation] =
useState(windowLocation())
useEffect(() => {
const onHashChange = () => {
let newLocation = windowLocation()
if (newLocation !== currentLocation) {
setCurrentLocation(newLocation)
window.scrollTo(0, 0)
}
}
onHashChange()
window.addEventListener('hashchange', onHashChange)
return () => window.removeEventListener('hashchange', onHashChange)
}, [currentLocation, setCurrentLocation])
const navigate = useCallback((to) => {
window.location.hash = to.replace('#/', '')
}, [])
return [currentLocation, navigate]
}