55 lines
1.2 KiB
TypeScript
55 lines
1.2 KiB
TypeScript
// handle route history
|
|
import type {
|
|
NavigationGuard,
|
|
RouteLocationNormalized,
|
|
RouteLocationRaw,
|
|
Router,
|
|
} from "vue-router";
|
|
|
|
const routeHistory: RouteLocationNormalized[] = [];
|
|
const MAX_HISTORY = 10;
|
|
let isFirstNavigation = true;
|
|
|
|
let lastNavigationWasPush = false;
|
|
|
|
export function setLastNavigationWasPush(value: boolean) {
|
|
lastNavigationWasPush = value;
|
|
}
|
|
|
|
export function getLastNavigationWasPush() {
|
|
return lastNavigationWasPush;
|
|
}
|
|
|
|
export const addToHistory: NavigationGuard = (to, from, next) => {
|
|
// Add the current route to the history, and ensure it doesn't exceed the maximum length
|
|
if (isFirstNavigation) {
|
|
isFirstNavigation = false;
|
|
} else if (lastNavigationWasPush) {
|
|
routeHistory.push(from);
|
|
}
|
|
|
|
if (routeHistory.length > MAX_HISTORY) {
|
|
routeHistory.shift();
|
|
}
|
|
|
|
lastNavigationWasPush = false;
|
|
next();
|
|
};
|
|
|
|
export function getPreviousRoute() {
|
|
if (routeHistory.length > 0) {
|
|
return routeHistory[routeHistory.length - 1];
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
export function routerBackOrFallback(router: Router, fallbackRoute: RouteLocationRaw) {
|
|
// Check the latest route in history
|
|
const previousRoute = getPreviousRoute();
|
|
if (previousRoute) {
|
|
router.back();
|
|
} else {
|
|
router.push(fallbackRoute);
|
|
}
|
|
}
|