diff --git a/lib/app/composables/router.js b/lib/app/composables/router.js index 25230089..265a57cc 100644 --- a/lib/app/composables/router.js +++ b/lib/app/composables/router.js @@ -3,8 +3,9 @@ import { reactive, provide } from 'vue' export const RouteSymbol = Symbol() export function useRouter() { + const loc = location const route = reactive({ - path: location.pathname, + path: loc.pathname, scrollPosition: window.scrollY }) @@ -16,16 +17,30 @@ export function useRouter() { (e) => { if (e.target.tagName === 'A') { const { href, target } = e.target + const url = new URL(href) if ( target !== `_blank` && - href.startsWith(`${location.protocol}//${location.host}`) + url.protocol === loc.protocol && + url.hostname === loc.hostname ) { - e.preventDefault() - // save scroll position before changing url - saveScrollPosition() - history.pushState(null, '', href) - route.path = location.pathname - route.scrollPosition = 0 + if (url.pathname === loc.pathname) { + // smooth scroll bewteen hash anchors in the same page + if (url.hash !== loc.hash) { + e.preventDefault() + window.scrollTo({ + left: 0, + top: e.target.offsetTop, + behavior: 'smooth' + }) + } + } else { + e.preventDefault() + // save scroll position before changing url + saveScrollPosition() + history.pushState(null, '', href) + route.path = loc.pathname + route.scrollPosition = 0 + } } } }, @@ -39,7 +54,7 @@ export function useRouter() { */ (e) => { route.path = location.pathname - route.scrollPosition = e.state && e.state.scrollPosition || 0 + route.scrollPosition = (e.state && e.state.scrollPosition) || 0 } )