scrollBehaviour.ts
1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Handles the scroll behavior on route navigation
*
* @param {object} to Route object of next page
* @param {object} from Route object of previous page
* @param {object} savedPosition Used by popstate navigations
* @returns {(object|boolean)} Scroll position or `false`
*/
// @ts-ignore
export async function scrollBehavior(to, from, savedPosition) {
await scrollWaiter.wait();
// Use predefined scroll behavior if defined, defaults to no scroll behavior
const behavior = document.documentElement.style.scrollBehavior || 'auto';
// Returning the `savedPosition` (if available) will result in a native-like
// behavior when navigating with back/forward buttons
if (savedPosition) {
return { ...savedPosition, behavior };
}
// Scroll to anchor by returning the selector
if (to.hash) {
return { el: decodeURI(to.hash), behavior };
}
// Check if any matched route config has meta that discourages scrolling to top
if (to.matched.some((m: any) => m.meta.scrollToTop === false)) {
// Leave scroll as it is
return false;
}
// Always scroll to top
return { left: 0, top: 0, behavior };
}
// see https://github.com/vuejs/vue-router-next/blob/master/playground/scrollWaiter.ts
class ScrollQueue {
private resolve: (() => void) | null = null;
private promise: Promise<any> | null = null;
add() {
this.promise = new Promise((resolve) => {
this.resolve = resolve as () => void;
});
}
flush() {
this.resolve && this.resolve();
this.resolve = null;
this.promise = null;
}
async wait() {
await this.promise;
}
}
export const scrollWaiter = new ScrollQueue();