UNPKG

1.91 kBJavaScriptView Raw
1class History {
2 constructor() {
3 return [];
4 }
5}
6
7export default ({ app, store }, inject) => {
8 const history = new History();
9
10 inject('history', history);
11
12 const userInteractionTimeout = 250;
13 let isUserTriggeredNavigation = false;
14 let disableBackNav = true;
15
16 const isBackNav = (toState, fromState) => {
17 if (app.$history.length < 2) {
18 return false;
19 }
20
21 const prevState = app.$history[0];
22
23 if (
24 prevState.fullPath === toState.fullPath &&
25 fromState.fullPath.split('/').length > toState.fullPath.split('/').length
26 ) {
27 return true;
28 }
29
30 return false;
31 };
32
33 const interact = () => {
34 isUserTriggeredNavigation = true;
35
36 setTimeout(() => {
37 isUserTriggeredNavigation = false;
38 }, userInteractionTimeout);
39 };
40
41 if (process.client) {
42 window.addEventListener('keydown', interact);
43 window.addEventListener('mousedown', interact);
44 window.addEventListener('touchstart', interact);
45
46 app.router.afterEach((to, from) => {
47 const state = {
48 name: from.name,
49 fullPath: from.fullPath,
50 path: from.path,
51 params: from.params,
52 query: from.query,
53 scrollY: window.scrollY,
54 };
55
56 app.$history.unshift(state);
57 store.commit('HISTORY', state);
58 });
59
60 app.router.beforeEach((to, from, next) => {
61 if (disableBackNav && isUserTriggeredNavigation && isBackNav(to, from)) {
62 disableBackNav = false;
63
64 next(false);
65
66 if (to.fullPath === app.$history[0].fullPath) {
67 const fullPath = window.location.href;
68 window.history.forward();
69 setTimeout(() => {
70 if (fullPath === window.location.href) {
71 window.history.back();
72 }
73 }, 100);
74 } else {
75 window.history.back();
76 }
77
78 return;
79 }
80
81 disableBackNav = true;
82 next();
83 });
84 }
85};