Compare commits

...

3 Commits

Author SHA1 Message Date
Damian Głowala
6097d039c3
Merge df5038a272 into 9bf8465806 2024-11-19 17:37:04 -05:00
Damian Glowala
df5038a272 chore: simplify conditional statements 2024-09-14 10:36:49 +02:00
Damian Glowala
d8d89b9dee fix(nuxt): wait for page:finish hook in CSR before scrolling to hash on page enter 2024-09-14 10:31:16 +02:00

View File

@ -28,13 +28,11 @@ export default <RouterConfig> {
}
// Hash routes on the same page, no page hook is fired so resolve here
if (to.path === from.path) {
if (from.hash && !to.hash) {
if (to.path === from.path && !to.hash) {
if (from.hash) {
return { left: 0, top: 0 }
}
if (to.hash) {
return { el: to.hash, top: _getHashElementScrollMarginTop(to.hash), behavior }
}
// The route isn't changing so keep current scroll position
return false
}
@ -42,12 +40,15 @@ export default <RouterConfig> {
// Wait for `page:transition:finish` or `page:finish` depending on if transitions are enabled or not
const hasTransition = (route: RouteLocationNormalized) => !!(route.meta.pageTransition ?? defaultPageTransition)
const hookToWait = (hasTransition(from) && hasTransition(to)) ? 'page:transition:finish' : 'page:finish'
return new Promise((resolve) => {
nuxtApp.hooks.hookOnce(hookToWait, async () => {
await new Promise(resolve => setTimeout(resolve, 0))
if (to.hash) {
position = { el: to.hash, top: _getHashElementScrollMarginTop(to.hash), behavior }
}
resolve(position)
})
})
@ -57,11 +58,13 @@ export default <RouterConfig> {
function _getHashElementScrollMarginTop (selector: string): number {
try {
const elem = document.querySelector(selector)
if (elem) {
return (Number.parseFloat(getComputedStyle(elem).scrollMarginTop) || 0) + (Number.parseFloat(getComputedStyle(document.documentElement).scrollPaddingTop) || 0)
}
} catch {
// ignore any errors parsing scrollMarginTop
}
return 0
}