diff --git a/src/index.js b/src/index.js index 6a6a80c..875239f 100644 --- a/src/index.js +++ b/src/index.js @@ -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 () {
diff --git a/src/routing.js b/src/routing.js index 25a3084..315b64b 100644 --- a/src/routing.js +++ b/src/routing.js @@ -1,33 +1,39 @@ import { - useState, useEffect, useCallback, + useCallback, useEffect, useState, } from 'preact/hooks' -export const useHashLocation = () => { - const currentLoc = () => - window.location.hash.replace('#', '') || '/' +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 }) => +export const buildPlayLinkHref = ({url}) => `/#/play/${encodeURIComponent(url)}` 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] +}