|
1 | 1 | import type { RouterConfig } from '@nuxt/schema' |
2 | | -// https://router.vuejs.org/api/interfaces/routeroptions.html |
3 | | -export default <RouterConfig> { |
4 | | - scrollBehavior (to, _form, savedPosition) { |
5 | | - if (history.state.stop) { return } |
6 | 2 |
|
7 | | - if (history.state.smooth) { |
8 | | - return { |
9 | | - el: history.state.smooth, |
10 | | - behavior: 'smooth' |
11 | | - } |
12 | | - } |
13 | | - |
14 | | - if (to.hash) { |
15 | | - const el = document.querySelector(to.hash) as any |
| 3 | +function findHashPosition (hash): { el: any, behavior: ScrollBehavior, top: number } { |
| 4 | + const el = document.querySelector(hash) |
| 5 | + // vue-router does not incorporate scroll-margin-top on its own. |
| 6 | + if (el) { |
| 7 | + const top = parseFloat(getComputedStyle(el).scrollMarginTop) |
16 | 8 |
|
17 | | - if (!el) { return } |
18 | | - |
19 | | - const { marginTop } = getComputedStyle(el) |
| 9 | + return { |
| 10 | + el: hash, |
| 11 | + behavior: 'smooth', |
| 12 | + top |
| 13 | + } |
| 14 | + } |
| 15 | +} |
20 | 16 |
|
21 | | - const marginTopValue = parseInt(marginTop) |
| 17 | +// https://router.vuejs.org/api/#routeroptions |
| 18 | +export default <RouterConfig>{ |
| 19 | + scrollBehavior (to, from, savedPosition) { |
| 20 | + const nuxtApp = useNuxtApp() |
22 | 21 |
|
23 | | - const offset = (document.querySelector(to.hash) as any).offsetTop - marginTopValue |
| 22 | + // If history back |
| 23 | + if (savedPosition) { |
| 24 | + // Handle Suspense resolution |
| 25 | + return new Promise((resolve) => { |
| 26 | + nuxtApp.hooks.hookOnce('page:finish', () => { |
| 27 | + setTimeout(() => resolve(savedPosition), 50) |
| 28 | + }) |
| 29 | + }) |
| 30 | + } |
24 | 31 |
|
25 | | - return { |
26 | | - top: offset, |
27 | | - behavior: 'smooth' |
28 | | - } |
| 32 | + // Scroll to heading on click |
| 33 | + if (to.hash) { |
| 34 | + return new Promise((resolve) => { |
| 35 | + if (to.path === from.path) { |
| 36 | + setTimeout(() => resolve(findHashPosition(to.hash)), 50) |
| 37 | + } else { |
| 38 | + nuxtApp.hooks.hookOnce('page:finish', () => { |
| 39 | + setTimeout(() => resolve(findHashPosition(to.hash)), 50) |
| 40 | + }) |
| 41 | + } |
| 42 | + }) |
29 | 43 | } |
30 | 44 |
|
31 | 45 | // Scroll to top of window |
32 | | - if (savedPosition) { |
33 | | - return savedPosition |
34 | | - } else { |
35 | | - return { top: 0 } |
36 | | - } |
| 46 | + return { top: 0 } |
37 | 47 | } |
38 | 48 | } |
0 commit comments