chore: StackGuard
All checks were successful
CI / cache-and-install (push) Successful in 55s

This commit is contained in:
严浩
2024-08-10 16:41:48 +08:00
parent 0afdfc5d2c
commit d0ba655182
16 changed files with 251 additions and 181 deletions

View File

@ -1,8 +1,8 @@
{ {
"$schema": "https://json.schemastore.org/prettierrc", "$schema": "https://json.schemastore.org/prettierrc",
"semi": false, "semi": true,
"tabWidth": 2, "tabWidth": 2,
"singleQuote": true, "singleQuote": true,
"printWidth": 100, "printWidth": 120,
"trailingComma": "none" "trailingComma": "none"
} }

2
components.d.ts vendored
View File

@ -2,7 +2,7 @@
// @ts-nocheck // @ts-nocheck
// Generated by unplugin-vue-components // Generated by unplugin-vue-components
// Read more: https://github.com/vuejs/core/pull/3399 // Read more: https://github.com/vuejs/core/pull/3399
export { } export {}
/* prettier-ignore */ /* prettier-ignore */
declare module 'vue' { declare module 'vue' {

View File

@ -3,7 +3,7 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="shotcut icon" href="logo@3x.png" /> <link rel="icon" href="/favicon.ico">
<meta name="viewport" <meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover, user-scalable=no" /> content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover, user-scalable=no" />
<meta name="format-detection" content="telephone=no"> <meta name="format-detection" content="telephone=no">

View File

@ -1,7 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
defineProps<{ defineProps<{
msg: string msg: string;
}>() }>();
</script> </script>
<template> <template>

View File

@ -1,11 +1,11 @@
import { describe, it, expect } from 'vitest' import { describe, it, expect } from 'vitest';
import { mount } from '@vue/test-utils' import { mount } from '@vue/test-utils';
import HelloWorld from '../HelloWorld.vue' import HelloWorld from '../HelloWorld.vue';
describe('HelloWorld', () => { describe('HelloWorld', () => {
it('renders properly', () => { it('renders properly', () => {
const wrapper = mount(HelloWorld, { props: { msg: 'Hello Vitest' } }) const wrapper = mount(HelloWorld, { props: { msg: 'Hello Vitest' } });
expect(wrapper.text()).toContain('Hello Vitest') expect(wrapper.text()).toContain('Hello Vitest');
}) });
}) });

View File

@ -1,13 +1,10 @@
import './assets/main.css' import './assets/main.css';
import 'virtual:uno.css' import 'virtual:uno.css';
import { createApp } from 'vue' import { createApp } from 'vue';
import { createPinia } from 'pinia' import { createPinia } from 'pinia';
import App from './App.vue' import App from './App.vue';
import { router } from './router' import { router } from './router';
createApp(App) createApp(App).use(createPinia()).use(router).mount('#app');
.use(createPinia())
.use(router)
.mount('#app')

View File

@ -1,13 +1,73 @@
<script setup lang="ts"> <script lang="ts" setup>
import { router } from '@/router';
definePage({ definePage({
alias: '/' alias: '/'
}) });
const testButtons = [
{
text: 'Page1 -> Page2',
onClick: async () => {
console.clear();
console.debug('⚙️ 预期结果:', ['Page1', 'Page2']);
await router.push({ name: 'Page1' });
await router.push({ name: 'Page2' });
}
},
{
text: 'A -> (B) -> C',
onClick: async () => {
console.clear();
console.debug('⚙️ 预期结果: ', ['Page1', 'Page3']);
await router.push({ name: 'Page1' });
await router.push({ name: 'Page2' });
await router.push({ name: 'Page3', replace: true });
}
},
{
text: 'A -> B -> C -> go(-2)',
onClick: async () => {
console.clear();
console.debug('⚙️ 预期结果: ', ['/', '/Page1📍', '/Page2', '/Page3']);
await router.push({ name: 'Page1' });
await router.push({ name: 'Page2' });
await router.push({ name: 'Page3' });
router.go(-2);
}
},
{
text: 'A -> B -> C -> go(-1) -> (D)',
onClick: async () => {
console.clear();
console.debug('⚙️ 预期结果: ', ['/', 'Page1', 'Page4📍', 'Page3']);
await router.push({ name: 'Page1' });
await router.push({ name: 'Page2' });
await router.push({ name: 'Page3' });
router.go(-1);
function popStateListener() {
console.debug('back执行完成, 替换"Page2"为"Page4"');
router.replace({ name: 'Page4' });
window.removeEventListener('popstate', popStateListener);
}
window.addEventListener('popstate', popStateListener);
}
}
];
</script> </script>
<template> <template>
<div class="flex gap-2"> <div class="flex flex-col gap-2 items-start">
<t-button @click="$router.push({ name: 'Page1' })">ToPage1</t-button> <div class="flex gap-2">
<t-button @click="$router.push({ name: 'Page2' })">ToPage2</t-button> <t-button @click="$router.push({ name: 'Page1' })">ToPage1</t-button>
<t-button @click="$router.push({ name: 'Page3' })">ToPage3</t-button> <t-button @click="$router.push({ name: 'Page2' })">ToPage2</t-button>
<t-button @click="$router.push({ name: 'Page3' })">ToPage3</t-button>
</div>
<template v-for="btn in testButtons" :key="btn.text">
<t-button theme="primary" @click="btn.onClick">{{ btn.text }}</t-button>
</template>
</div> </div>
</template> </template>

View File

@ -27,5 +27,5 @@ function backToHome() {
onMounted(() => { onMounted(() => {
// console.log('router.currentRoute.value.from :>> ', router.currentRoute.value.from); // console.log('router.currentRoute.value.from :>> ', router.currentRoute.value.from);
// backToHome() // backToHome()
}) });
</script> </script>

1
src/pages/page-4.vue Normal file
View File

@ -0,0 +1 @@
<template>page-4</template>

View File

@ -1,26 +1,26 @@
import NProgress from 'nprogress' import NProgress from 'nprogress';
import type { Router } from 'vue-router' import type { Router } from 'vue-router';
import { createLogGuard, createStackGuard } from './log-guard' import { createLogGuard, createStackGuard } from './log-guard';
// Don't change the order of creation // Don't change the order of creation
export function setupRouterGuard(router: Router) { export function setupRouterGuard(router: Router) {
createProgressGuard(router) createProgressGuard(router);
createLogGuard(router) createLogGuard(router);
createStackGuard(router) createStackGuard(router);
router.onError((error) => { router.onError((error) => {
console.debug('🚨 [router error]: ', error) console.debug('🚨 [router error]: ', error);
}) });
} }
export function createProgressGuard(router: Router) { export function createProgressGuard(router: Router) {
router.beforeEach(() => { router.beforeEach(() => {
NProgress.start() NProgress.start();
}) });
router.afterEach(() => { router.afterEach(() => {
NProgress.done() NProgress.done();
}) });
} }

View File

@ -1,147 +1,158 @@
import { START_LOCATION } from 'vue-router' import { START_LOCATION } from 'vue-router';
import type { RouteLocationNormalized, Router } from 'vue-router' import type { RouteLocationNormalized, Router } from 'vue-router';
export function createLogGuard(router: Router) { export function createLogGuard(router: Router) {
router.beforeEach(async (to, from, next) => { router.beforeEach(async (to, from, next) => {
console.debug( console.debug(
'🚗 ====================', '🚗 ====================',
`[beforeEach]`, `[beforeEach]`,
`[${from === START_LOCATION ? 'START_LOCATION' : String(from.name || '')}]`, `[${from === START_LOCATION ? 'START_LOCATION' : String(from.name || '')}]`,
`-> [${String(to.name)}].`, `-> [${String(to.name)}].`,
'====================' '===================='
) );
next() next();
}) });
router.afterEach(async (to, from, failure) => { router.afterEach(async (to, from, failure) => {
console.debug( console.debug(
'🚗 ====================', '🚗 ====================',
` [afterEach]`, ` [afterEach]`,
`[${from === START_LOCATION ? 'START_LOCATION' : String(from.name || '')}]`, `[${from === START_LOCATION ? 'START_LOCATION' : String(from.name || '')}]`,
`-> [${String(to.name)}].`, `-> [${String(to.name)}].`,
'==================== 🚗🚗🚗', '==================== 🚗🚗🚗',
`failure: `, `failure: `,
failure failure
) );
}) });
} }
export function createStackGuard(router: Router) { export function createStackGuard(router: Router) {
// const stack = router.stack = { /* list: [] as RouteLocationNormalized[], */ currentStackIndex: 0 } // const stack = router.stack = { /* list: [] as RouteLocationNormalized[], */ currentStackIndex: 0 }
let startPosition = -1 let startPosition = -1;
let curPosition = -1 let curPosition = -1;
// if ($__DEV__) Object.assign(window, { stack }) // if ($__DEV__) Object.assign(window, { stack })
const _routerHistory = router.options.history const _routerHistory = router.options.history;
/* window.addEventListener('beforeunload', function (event) { /* window.addEventListener('beforeunload', function (event) {
console.debug("🚥", '[onbeforeunload]', "event :>> ", event); console.debug("🚥", '[onbeforeunload]', "event :>> ", event);
const confirmationMessage = "\\o/"; const confirmationMessage = "\\o/";
(event || window.event).returnValue = confirmationMessage; //Gecko + IE (event || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome etc. return confirmationMessage; //Webkit, Safari, Chrome etc.
}) */ }) */
_routerHistory.listen((to, from, info) => { _routerHistory.listen((to, from, info) => {
console.debug('🚥 listen', ':') console.debug('🚥 listen', ':');
console.debug('🚥 listen', 'from :>> ', from) console.debug('🚥 listen', 'from :>> ', from);
console.debug('🚥 listen', 'to :>> ', to) // TODO: 在afterEach那里核对 console.debug('🚥 listen', 'to :>> ', to); // TODO: 在afterEach那里核对
console.debug('🚥 listen', 'info :>> ', info) console.debug('🚥 listen', 'info :>> ', info);
// lastNavigationInfo.lastInfo = info; // lastNavigationInfo.lastInfo = info;
}); });
// ############################# // #############################
// 重写 router.history 方法 // 重写 router.history 方法
// ############################# // #############################
(() => { () => {
const routerHistoryPush = _routerHistory.push const routerHistoryPush = _routerHistory.push;
_routerHistory.push = function (...args) { _routerHistory.push = function (...args) {
console.debug('🚥 [router]', 'push: args :>> ', args) console.debug('🚥 [router]', 'push: args :>> ', args);
return routerHistoryPush.call(this, ...args) return routerHistoryPush.call(this, ...args);
} };
const routerHistoryReplace = _routerHistory.replace const routerHistoryReplace = _routerHistory.replace;
_routerHistory.replace = function (...args) { _routerHistory.replace = function (...args) {
console.debug('🚥 [router]', 'replace: args :>> ', args) console.debug('🚥 [router]', 'replace: args :>> ', args);
// lastNavigationInfo.replace = true; // lastNavigationInfo.replace = true;
return routerHistoryReplace.call(this, ...args) return routerHistoryReplace.call(this, ...args);
} };
const routerHistoryGo = _routerHistory.go const routerHistoryGo = _routerHistory.go;
_routerHistory.go = function (...args) { _routerHistory.go = function (...args) {
console.debug('🚥 [router]', 'go: args :>> ', args) console.debug('🚥 [router]', 'go: args :>> ', args);
return routerHistoryGo.call(this, ...args) return routerHistoryGo.call(this, ...args);
} };
})/* () */; } /* () ;*/;
// ############################# // #############################
// 重写 window.history 方法 // 重写 window.history 方法
// ############################# // #############################
(() => { () => {
const browserHistoryBack = window.history.back const browserHistoryBack = window.history.back;
window.history.back = function (...args) { window.history.back = function (...args) {
console.debug('🌐 [Browser]', 'history.back: args :>> ', args) console.debug('🌐 [Browser]', 'history.back: args :>> ', args);
return browserHistoryBack.call(this, ...args) return browserHistoryBack.call(this, ...args);
} };
const browserHistoryForward = window.history.forward const browserHistoryForward = window.history.forward;
window.history.forward = function (...args) { window.history.forward = function (...args) {
console.debug('🌐 [Browser]', 'history.forward: args :>> ', args) console.debug('🌐 [Browser]', 'history.forward: args :>> ', args);
return browserHistoryForward.call(this, ...args) return browserHistoryForward.call(this, ...args);
} };
const browserHistoryGo = window.history.go const browserHistoryGo = window.history.go;
window.history.go = function (...args) { window.history.go = function (...args) {
console.debug('🌐 [Browser]', 'history.go: args :>> ', args) console.debug('🌐 [Browser]', 'history.go: args :>> ', args);
return browserHistoryGo.call(this, ...args) return browserHistoryGo.call(this, ...args);
} };
const browserHistoryPushState = window.history.pushState const browserHistoryPushState = window.history.pushState;
window.history.pushState = function (...args) { window.history.pushState = function (...args) {
console.debug('🌐 [Browser]', 'history.pushState: args :>> ', args) console.debug('🌐 [Browser]', 'history.pushState: args :>> ', args);
return browserHistoryPushState.call(this, ...args) return browserHistoryPushState.call(this, ...args);
} };
const browserHistoryReplaceState = window.history.replaceState const browserHistoryReplaceState = window.history.replaceState;
window.history.replaceState = function (...args) { window.history.replaceState = function (...args) {
console.debug('🌐 [Browser]', 'history.replaceState: args :>> ', args) console.debug('🌐 [Browser]', 'history.replaceState: args :>> ', args);
return browserHistoryReplaceState.call(this, ...args) return browserHistoryReplaceState.call(this, ...args);
} };
})/* () */; }; /* () */
router.beforeEach(async (to) => { /* router.beforeEach(async (to) => {
if (to.name === 'Page3') { if (to.name === 'Page3') {
return { name: 'Page2' } return { name: 'Page2' }
} }
}) }) */
router.afterEach(async (to, from, failure) => { router.afterEach(async (to, from, failure) => {
if (failure) return if (failure) return;
if (from === START_LOCATION) { if (from === START_LOCATION) {
startPosition = history.state.position startPosition = history.state.position;
curPosition = startPosition - 1 curPosition = startPosition - 1;
} }
const newPostion = history.state.position const newPostion = history.state.position;
// console.log('history.state.position :>> ', history.state.position); // console.log('history.state.position :>> ', history.state.position);
console.log('startPosition :>> ', startPosition); console.log('startPosition :>> ', startPosition);
console.log('newPostion :>> ', newPostion); console.log('newPostion :>> ', newPostion);
const delta = newPostion - curPosition const delta = newPostion - curPosition;
if (newPostion > curPosition) { const stackIdx = newPostion - startPosition;
console.log('👉🏻'); if (newPostion > curPosition) {
} else if (newPostion < curPosition) { console.log('👉🏻');
console.log('👈🏻'); } else if (newPostion < curPosition) {
} else { console.log('👈🏻');
console.log('👌🏻'); // stack.splice(delta)
} } else {
console.log('delta :>> ', delta); console.log('🔄');
}
Object.assign(to, { locationHref: window.location.href });
stack[stackIdx] = to as StackItem;
console.log('delta :>> ', delta);
curPosition = newPostion; curPosition = newPostion;
console.log(
console.log(`%c${'-'.repeat(80)}`, 'color: #409EFF;') 'stack :>> ',
}) stack.map((item, index) => (stackIdx === index ? `🔵 ${item.name}` : item.name)),
stack,
);
console.log(`%c${'-'.repeat(80)}`, 'color: #409EFF;');
});
} }
declare type StackItem = RouteLocationNormalized & { locationHref: string };
const stack: StackItem[] = [];
Object.assign(window, { stack });

View File

@ -1,17 +1,17 @@
import { createRouter, createWebHistory } from 'vue-router' import { createRouter, createWebHistory } from 'vue-router';
import { routes, handleHotUpdate } from 'vue-router/auto-routes' import { routes, handleHotUpdate } from 'vue-router/auto-routes';
import { setupRouterGuard } from './guard' import { setupRouterGuard } from './guard';
export const router = createRouter({ export const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL), history: createWebHistory(import.meta.env.BASE_URL),
routes, routes,
strict: true strict: true
}) });
if ($__DEV__) Object.assign(window, { router }) if ($__DEV__) Object.assign(window, { router });
setupRouterGuard(router) setupRouterGuard(router);
if (import.meta.hot) { if (import.meta.hot) {
handleHotUpdate(router) handleHotUpdate(router);
} }

View File

@ -1,12 +1,12 @@
import { ref, computed } from 'vue' import { ref, computed } from 'vue';
import { defineStore } from 'pinia' import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', () => { export const useCounterStore = defineStore('counter', () => {
const count = ref(0) const count = ref(0);
const doubleCount = computed(() => count.value * 2) const doubleCount = computed(() => count.value * 2);
function increment() { function increment() {
count.value++ count.value++;
} }
return { count, doubleCount, increment } return { count, doubleCount, increment };
}) });

View File

@ -1,7 +1,7 @@
import 'vue-router' import 'vue-router';
// 为了确保这个文件被当作一个模块,添加至少一个 `export` 声明 // 为了确保这个文件被当作一个模块,添加至少一个 `export` 声明
export { } export {};
// declare module 'vue-router' { // declare module 'vue-router' {
// interface RouteMeta { // interface RouteMeta {

View File

@ -1,7 +1,7 @@
export {} export {};
declare global { declare global {
const $__DEV__: boolean const $__DEV__: boolean;
} }
/* declare module 'vue' { /* declare module 'vue' {

1
typed-router.d.ts vendored
View File

@ -22,5 +22,6 @@ declare module 'vue-router/auto-routes' {
'Page1': RouteRecordInfo<'Page1', '/page-1', Record<never, never>, Record<never, never>>, 'Page1': RouteRecordInfo<'Page1', '/page-1', Record<never, never>, Record<never, never>>,
'Page2': RouteRecordInfo<'Page2', '/page-2', Record<never, never>, Record<never, never>>, 'Page2': RouteRecordInfo<'Page2', '/page-2', Record<never, never>, Record<never, never>>,
'Page3': RouteRecordInfo<'Page3', '/page-3', Record<never, never>, Record<never, never>>, 'Page3': RouteRecordInfo<'Page3', '/page-3', Record<never, never>, Record<never, never>>,
'Page4': RouteRecordInfo<'Page4', '/page-4', Record<never, never>, Record<never, never>>,
} }
} }