From 950b341696b4f48d9be78d73ee83ecdac02f8700 Mon Sep 17 00:00:00 2001 From: Benjamin Canac Date: Thu, 11 May 2023 14:17:01 +0200 Subject: [PATCH] docs: prevent aside to scroll up on page change --- docs/app.vue | 16 +++++++- docs/app/router.options.ts | 66 +++++++++++++----------------- docs/components/docs/DocsAside.vue | 4 +- docs/layouts/default.vue | 18 +------- 4 files changed, 46 insertions(+), 58 deletions(-) diff --git a/docs/app.vue b/docs/app.vue index 1d45f828..776b39d6 100644 --- a/docs/app.vue +++ b/docs/app.vue @@ -3,7 +3,21 @@
- +
+ + +
+ + + + +
+ + +
+ + +
diff --git a/docs/app/router.options.ts b/docs/app/router.options.ts index 23202d07..9380f053 100644 --- a/docs/app/router.options.ts +++ b/docs/app/router.options.ts @@ -1,48 +1,38 @@ import type { RouterConfig } from '@nuxt/schema' +// https://router.vuejs.org/api/interfaces/routeroptions.html +export default { + scrollBehavior (to, _form, savedPosition) { + if (history.state.stop) { return } -function findHashPosition (hash): { el: any, behavior: ScrollBehavior, top: number } { - const el = document.querySelector(hash) - // vue-router does not incorporate scroll-margin-top on its own. - if (el) { - const top = parseFloat(getComputedStyle(el).scrollMarginTop) - - return { - el: hash, - behavior: 'smooth', - top - } - } -} - -// https://router.vuejs.org/api/#routeroptions -export default { - scrollBehavior (to, from, savedPosition) { - const nuxtApp = useNuxtApp() - - // If history back - if (savedPosition) { - // Handle Suspense resolution - return new Promise((resolve) => { - nuxtApp.hooks.hookOnce('page:finish', () => { - setTimeout(() => resolve(savedPosition), 50) - }) - }) + if (history.state.smooth) { + return { + el: history.state.smooth, + behavior: 'smooth' + } } - // Scroll to heading on click if (to.hash) { - return new Promise((resolve) => { - if (to.path === from.path) { - setTimeout(() => resolve(findHashPosition(to.hash)), 50) - } else { - nuxtApp.hooks.hookOnce('page:finish', () => { - setTimeout(() => resolve(findHashPosition(to.hash)), 50) - }) - } - }) + const el = document.querySelector(to.hash) as any + + if (!el) { return } + + const { marginTop } = getComputedStyle(el) + + const marginTopValue = parseInt(marginTop) + + const offset = (document.querySelector(to.hash) as any).offsetTop - marginTopValue + + return { + top: offset, + behavior: 'smooth' + } } // Scroll to top of window - return { top: 0 } + if (savedPosition) { + return savedPosition + } else { + return { top: 0 } + } } } diff --git a/docs/components/docs/DocsAside.vue b/docs/components/docs/DocsAside.vue index 4b0da556..dc365f46 100644 --- a/docs/components/docs/DocsAside.vue +++ b/docs/components/docs/DocsAside.vue @@ -1,7 +1,5 @@