solely 0.7.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -1
- package/dist/router/core.cjs +1 -1
- package/dist/router/core.d.ts +30 -0
- package/dist/router/core.js +1 -1
- package/dist/router/router-view.cjs +1 -1
- package/dist/router/router-view.d.ts +10 -0
- package/dist/router/router-view.js +1 -1
- package/dist/router/types.d.ts +3 -1
- package/dist/shared/env.cjs +1 -1
- package/dist/shared/env.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1347,7 +1347,22 @@ Solely 提供了两个内置的路由组件:
|
|
|
1347
1347
|
<!-- 基本用法 -->
|
|
1348
1348
|
<router-view></router-view>
|
|
1349
1349
|
|
|
1350
|
-
<!--
|
|
1350
|
+
<!-- 启动占位 + 404 兜底(两者都是内置组件,直接用) -->
|
|
1351
|
+
<router-view loading="solely-skeleton" not-found="solely-not-found"></router-view>
|
|
1352
|
+
```
|
|
1353
|
+
|
|
1354
|
+
`router-view` 区分三种结果:**还在等待**时渲染 `loading` 指定的占位组件(未配置则保持空白,**不会**误渲染成 404)——「还在等待」既包括首次导航尚未完成,也包括之后又发起了一次导航(此时即便当前无匹配,也先显示占位而不是 404);等待结束且有匹配时渲染页面;结束且无匹配时才渲染 `not-found`。
|
|
1355
|
+
|
|
1356
|
+
想确保启动期不出现空白,也可以在挂载前等待首次导航:
|
|
1357
|
+
|
|
1358
|
+
```typescript
|
|
1359
|
+
const router = await routerReady;
|
|
1360
|
+
await router.isReady();
|
|
1361
|
+
```
|
|
1362
|
+
|
|
1363
|
+
**嵌套路由视图**
|
|
1364
|
+
|
|
1365
|
+
```html
|
|
1351
1366
|
<div class="layout">
|
|
1352
1367
|
<aside>
|
|
1353
1368
|
<router-link to="/user/profile">个人资料</router-link>
|
package/dist/router/core.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../shared/env.cjs");let t=null,
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../shared/env.cjs");let t=null,i=null,s=null;function r(){return t?Promise.resolve(t):(s||(s=new Promise(e=>{i=e})),s)}const a=(()=>{const e=()=>r();return Object.defineProperties(e,{then:{value:(e,t)=>r().then(e,t),writable:!1,enumerable:!1,configurable:!0},catch:{value:e=>r().catch(e),writable:!1,enumerable:!1,configurable:!0},finally:{value:e=>r().finally(e),writable:!1,enumerable:!1,configurable:!0},[Symbol.toStringTag]:{value:"Promise",writable:!1,enumerable:!1,configurable:!0}}),e})();class n{routes;base;mode;beforeEachGuard;afterEachGuard;currentRoute=null;listeners=new Set;componentCache=new Map;keepAliveCache=new Map;keepAliveKeys=[];navigationId=0;maxKeepAlive;navigated=!1;pendingNavId=null;readyDeferred=null;constructor(e){this.routes=e.routes,this.base=this.normalizeBase(e.base),this.mode=e.mode||"history",this.beforeEachGuard=e.beforeEach,this.afterEachGuard=e.afterEach,this.maxKeepAlive=e.maxKeepAlive}normalizeBase(e){let t=e||"/";return t.startsWith("/")||(t="/"+t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}static MAX_REDIRECTS=20;matchRoute(e="/"){return this.matchRouteInternal(e,new Set,0)}matchRouteInternal(t,i,s){if(s>=n.MAX_REDIRECTS)return e.IS_DEV&&console.error(`[Router] Too many redirects (max ${n.MAX_REDIRECTS}), last path: ${t}`),null;const r=this.normalizePath(t);if(i.has(r))return e.IS_DEV&&console.error(`[Router] Circular redirect detected: ${r}`),null;i.add(r);const[a,h]=r.split("?"),o=a.split("/").filter(Boolean),l=this.parseQuery(h),c=this.recursiveMatch(this.routes,o);if(c){const e=c.matched[c.matched.length-1];return e.config.redirect?this.matchRouteInternal(e.config.redirect,i,s+1):{matched:c.matched,params:c.params,query:l,fullPath:r,meta:c.matched.reduce((e,t)=>({...e,...t.config.meta||{}}),{})}}return null}recursiveMatch(e,t){const i=[...e].sort((e,t)=>this.calculateScore(t.path)-this.calculateScore(e.path));for(const s of i){const e=s.path.split("/").filter(Boolean),i={};let r=!0;if(0===e.length&&0===t.length)return{matched:[{config:s,params:{}}],params:{}};for(let s=0;s<e.length;s++){const a=e[s],n=t[s];if(a.startsWith(":")){if(!n){r=!1;break}Object.defineProperty(i,a.slice(1),{value:n,writable:!0,enumerable:!0,configurable:!0})}else{if("*"===a){r=!0;break}if(a!==n){r=!1;break}}}if(r){const r=e.length,a=t.slice(r),n={config:s,params:i};if(a.length>0&&s.children){const e=this.recursiveMatch(s.children,a);if(e)return{matched:[n,...e.matched],params:{...i,...e.params}}}else if(0===a.length||e.includes("*"))return{matched:[n],params:i}}}return null}calculateScore(e="/"){const t=e.split("/").filter(Boolean);return 0===t.length?1:t.reduce((e,t)=>t.startsWith(":")?e+5:"*"===t?e+0:e+10,0)}parseQuery(e){const t={};return e?(new URLSearchParams(e).forEach((e,i)=>{Object.defineProperty(t,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}),t):t}normalizePath(e="/"){const t=e&&"string"==typeof e?e:"/",i=t.indexOf("?"),s=-1===i?t:t.slice(0,i),r=-1===i?"":t.slice(i+1);let a=s;return a.startsWith("/")||(a="/"+a),a.length>1&&a.endsWith("/")&&(a=a.slice(0,-1)),r?`${a}?${r}`:a}getPath(){let e;try{e="hash"===this.mode?window.location.hash.slice(1)||"/":`${window.location.pathname}${window.location.search}`}catch{e="/"}const t=this.base||"/";return"/"===t||e!==t&&!e.startsWith(t+"/")||(e=e.slice(t.length)||"/"),this.normalizePath(e)}updateBrowserHistory(e="/",t){const i=this.normalizePath(e),s=this.base||"/";if("hash"===this.mode)t?window.location.replace(`#${i}`):window.location.hash=i;else{const e=s.endsWith("/")?s.slice(0,-1):s,r="/"===e?i:e+i;t?window.history.replaceState({path:r},"",r):window.history.pushState({path:r},"",r)}}async navigate(e="/",t=!1,i=!1){const s=++this.navigationId;this.pendingNavId=s;try{const a=this.normalizePath(e),n=this.currentRoute,h=this.matchRoute(a);if(!h)return{success:!1,error:`No route matched: ${a}`};if(n&&n.fullPath===h.fullPath)return{success:!0};if(this.beforeEachGuard)try{const e=await this.beforeEachGuard(h,n);if(s!==this.navigationId)return{success:!1,cancelled:!0};if(!1===e)return{success:!1,cancelled:!0};if("string"==typeof e)return this.navigate(e,t)}catch(r){return s!==this.navigationId?{success:!1,cancelled:!0}:{success:!1,error:r instanceof Error?r.message:"Guard Error"}}return s!==this.navigationId?{success:!1,cancelled:!0}:(this.currentRoute=h,i||this.updateBrowserHistory(a,t),this.notifyListeners(),this.afterEachGuard&&this.afterEachGuard(h,n),{success:!0})}finally{this.pendingNavId===s&&(this.pendingNavId=null,s===this.navigationId&&this.markReady())}}resolve(e="/"){const t=this.normalizePath(e);if("hash"===this.mode)return`#${t}`;const i=this.base.endsWith("/")?this.base.slice(0,-1):this.base;return"/"===i?t:i+t}get modeType(){return this.mode}pushWithQuery(e="/",t){const i=new URLSearchParams(t).toString(),s=e.includes("?")?"&":"?";return this.push(e+(i?s+i:""))}push(e="/"){return this.navigate(e,!1)}replace(e="/"){return this.navigate(e,!0)}back(){window.history.back()}forward(){window.history.forward()}listen(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notifyListeners(){this.listeners.forEach(e=>e())}isStarted=!1;handleRouteChange=null;setupListeners(){this.isStarted||(this.isStarted=!0,this.handleRouteChange=()=>{this.navigate(this.getPath(),!0,!0)},"hash"===this.mode?window.addEventListener("hashchange",this.handleRouteChange):window.addEventListener("popstate",this.handleRouteChange),"hash"!==this.mode||window.location.hash||(window.location.hash="/"),this.navigate(this.getPath(),!0).catch(t=>{e.IS_DEV&&console.error("[Router] 首导航异常:",t)}))}destroy(){this.navigationId++,this.handleRouteChange&&("hash"===this.mode?window.removeEventListener("hashchange",this.handleRouteChange):window.removeEventListener("popstate",this.handleRouteChange),this.handleRouteChange=null),this.isStarted=!1,this.listeners.clear(),this.componentCache.clear();for(const e of this.keepAliveCache.values())e.dispose?.();this.keepAliveCache.clear(),this.keepAliveKeys=[],this.currentRoute=null,this.navigated=!1,this.pendingNavId=null,this.readyDeferred?.resolve(),this.readyDeferred=null,t=null}getCurrentRoute(){return this.currentRoute}get hasNavigated(){return this.navigated}get isNavigating(){return null!==this.pendingNavId}isReady(){if(this.navigated&&null===this.pendingNavId)return Promise.resolve();if(!this.readyDeferred){let e;const t=new Promise(t=>{e=t});this.readyDeferred={promise:t,resolve:e}}return this.readyDeferred.promise}markReady(){this.navigated=!0,this.readyDeferred?.resolve(),this.readyDeferred=null}getKeepAlive(e){const t=this.keepAliveCache.get(e);if(t){const t=this.keepAliveKeys.indexOf(e);-1!==t&&(this.keepAliveKeys.splice(t,1),this.keepAliveKeys.push(e))}return t}setKeepAlive(e,t){if(this.keepAliveCache.has(e)){const i=this.keepAliveCache.get(e);i&&i!==t&&i.dispose?.(),this.keepAliveCache.set(e,t);const s=this.keepAliveKeys.indexOf(e);-1!==s&&(this.keepAliveKeys.splice(s,1),this.keepAliveKeys.push(e))}else this.keepAliveCache.set(e,t),this.keepAliveKeys.push(e),this.evictKeepAlive()}hasKeepAlive(e){return this.keepAliveCache.has(e)}evictKeepAlive(){if(this.maxKeepAlive)for(;this.keepAliveKeys.length>this.maxKeepAlive;){const e=this.keepAliveKeys.shift();if(e){const t=this.keepAliveCache.get(e);t?.dispose?.(),this.keepAliveCache.delete(e)}}}cacheKey(e){return this.normalizePath(e)}prefetch(e){const t=this.matchRoute(e);if(!t)return;const i=this.cacheKey(t.fullPath),s=t.matched[t.matched.length-1];if(!s?.config.component)return;const r=s.config.component;if("function"!=typeof r)return;if(this.componentCache.has(i))return;const a=r();this.componentCache.set(i,a),a.catch(()=>{this.componentCache.delete(i)})}getComponentFromCache(e){return this.componentCache.get(this.cacheKey(e))}}exports.Router=n,exports.createRouter=function(e){return t||(t=new n(e),i&&i(t),i=null,s=null,t)},exports.getRouter=function(){return t},exports.routerReady=a;
|
package/dist/router/core.d.ts
CHANGED
|
@@ -32,6 +32,11 @@ export declare class Router {
|
|
|
32
32
|
private keepAliveKeys;
|
|
33
33
|
private navigationId;
|
|
34
34
|
private maxKeepAlive;
|
|
35
|
+
/** 首次导航(含守卫与重定向)是否已 settled */
|
|
36
|
+
private navigated;
|
|
37
|
+
/** 尚未完成的「最新一次」导航的 navId;null 表示当前没有导航在飞 */
|
|
38
|
+
private pendingNavId;
|
|
39
|
+
private readyDeferred;
|
|
35
40
|
constructor(options: RouterOptions);
|
|
36
41
|
private normalizeBase;
|
|
37
42
|
private static readonly MAX_REDIRECTS;
|
|
@@ -58,6 +63,31 @@ export declare class Router {
|
|
|
58
63
|
setupListeners(): void;
|
|
59
64
|
destroy(): void;
|
|
60
65
|
getCurrentRoute(): RouteMatch | null;
|
|
66
|
+
/**
|
|
67
|
+
* 首次导航是否已完成(成功或失败均算完成)。
|
|
68
|
+
*
|
|
69
|
+
* 用于区分「启动中」与「真的没有匹配路由」:`currentRoute === null` 在启动阶段
|
|
70
|
+
* 是正常状态,不应被上层当成 404。
|
|
71
|
+
*/
|
|
72
|
+
get hasNavigated(): boolean;
|
|
73
|
+
/**
|
|
74
|
+
* 是否有导航正在进行(含卡在异步守卫里的那次)。
|
|
75
|
+
*
|
|
76
|
+
* `isReady()` 在仍有导航在飞时保持 pending —— 否则调用方会在两次导航之间醒来,
|
|
77
|
+
* 读到 `currentRoute === null` 而把「还在导航」当成「无匹配」。
|
|
78
|
+
*/
|
|
79
|
+
get isNavigating(): boolean;
|
|
80
|
+
/**
|
|
81
|
+
* 等待首次导航 settled。
|
|
82
|
+
*
|
|
83
|
+
* 语义与 `routerReady` 对齐:`setupListeners()` 之前调用会保持 pending,
|
|
84
|
+
* 需配合「先 setupListeners 再 await」的启动顺序;`destroy()` 后重置,
|
|
85
|
+
* 且销毁时仍 pending 的等待会被立即 resolve(不 reject),调用方据此结束等待;
|
|
86
|
+
* 销毁**之后**再调用会一直 pending —— 该实例已作废,不应继续使用。
|
|
87
|
+
*/
|
|
88
|
+
isReady(): Promise<void>;
|
|
89
|
+
/** 唯一调用点(`navigate()` 的 finally)已保证 `pendingNavId` 为 null */
|
|
90
|
+
private markReady;
|
|
61
91
|
getKeepAlive(key: string): HTMLElement | undefined;
|
|
62
92
|
setKeepAlive(key: string, el: HTMLElement): void;
|
|
63
93
|
hasKeepAlive(key: string): boolean;
|
package/dist/router/core.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{IS_DEV as e}from"../shared/env.js";let t=null,
|
|
1
|
+
import{IS_DEV as e}from"../shared/env.js";let t=null,i=null,s=null;function a(){return t?Promise.resolve(t):(s||(s=new Promise(e=>{i=e})),s)}const r=(()=>{const e=()=>a();return Object.defineProperties(e,{then:{value:(e,t)=>a().then(e,t),writable:!1,enumerable:!1,configurable:!0},catch:{value:e=>a().catch(e),writable:!1,enumerable:!1,configurable:!0},finally:{value:e=>a().finally(e),writable:!1,enumerable:!1,configurable:!0},[Symbol.toStringTag]:{value:"Promise",writable:!1,enumerable:!1,configurable:!0}}),e})();function n(e){return t||(t=new o(e),i&&i(t),i=null,s=null,t)}function h(){return t}class o{routes;base;mode;beforeEachGuard;afterEachGuard;currentRoute=null;listeners=new Set;componentCache=new Map;keepAliveCache=new Map;keepAliveKeys=[];navigationId=0;maxKeepAlive;navigated=!1;pendingNavId=null;readyDeferred=null;constructor(e){this.routes=e.routes,this.base=this.normalizeBase(e.base),this.mode=e.mode||"history",this.beforeEachGuard=e.beforeEach,this.afterEachGuard=e.afterEach,this.maxKeepAlive=e.maxKeepAlive}normalizeBase(e){let t=e||"/";return t.startsWith("/")||(t="/"+t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}static MAX_REDIRECTS=20;matchRoute(e="/"){return this.matchRouteInternal(e,new Set,0)}matchRouteInternal(t,i,s){if(s>=o.MAX_REDIRECTS)return e&&console.error(`[Router] Too many redirects (max ${o.MAX_REDIRECTS}), last path: ${t}`),null;const a=this.normalizePath(t);if(i.has(a))return e&&console.error(`[Router] Circular redirect detected: ${a}`),null;i.add(a);const[r,n]=a.split("?"),h=r.split("/").filter(Boolean),l=this.parseQuery(n),c=this.recursiveMatch(this.routes,h);if(c){const e=c.matched[c.matched.length-1];return e.config.redirect?this.matchRouteInternal(e.config.redirect,i,s+1):{matched:c.matched,params:c.params,query:l,fullPath:a,meta:c.matched.reduce((e,t)=>({...e,...t.config.meta||{}}),{})}}return null}recursiveMatch(e,t){const i=[...e].sort((e,t)=>this.calculateScore(t.path)-this.calculateScore(e.path));for(const s of i){const e=s.path.split("/").filter(Boolean),i={};let a=!0;if(0===e.length&&0===t.length)return{matched:[{config:s,params:{}}],params:{}};for(let s=0;s<e.length;s++){const r=e[s],n=t[s];if(r.startsWith(":")){if(!n){a=!1;break}Object.defineProperty(i,r.slice(1),{value:n,writable:!0,enumerable:!0,configurable:!0})}else{if("*"===r){a=!0;break}if(r!==n){a=!1;break}}}if(a){const a=e.length,r=t.slice(a),n={config:s,params:i};if(r.length>0&&s.children){const e=this.recursiveMatch(s.children,r);if(e)return{matched:[n,...e.matched],params:{...i,...e.params}}}else if(0===r.length||e.includes("*"))return{matched:[n],params:i}}}return null}calculateScore(e="/"){const t=e.split("/").filter(Boolean);return 0===t.length?1:t.reduce((e,t)=>t.startsWith(":")?e+5:"*"===t?e+0:e+10,0)}parseQuery(e){const t={};return e?(new URLSearchParams(e).forEach((e,i)=>{Object.defineProperty(t,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}),t):t}normalizePath(e="/"){const t=e&&"string"==typeof e?e:"/",i=t.indexOf("?"),s=-1===i?t:t.slice(0,i),a=-1===i?"":t.slice(i+1);let r=s;return r.startsWith("/")||(r="/"+r),r.length>1&&r.endsWith("/")&&(r=r.slice(0,-1)),a?`${r}?${a}`:r}getPath(){let e;try{e="hash"===this.mode?window.location.hash.slice(1)||"/":`${window.location.pathname}${window.location.search}`}catch{e="/"}const t=this.base||"/";return"/"===t||e!==t&&!e.startsWith(t+"/")||(e=e.slice(t.length)||"/"),this.normalizePath(e)}updateBrowserHistory(e="/",t){const i=this.normalizePath(e),s=this.base||"/";if("hash"===this.mode)t?window.location.replace(`#${i}`):window.location.hash=i;else{const e=s.endsWith("/")?s.slice(0,-1):s,a="/"===e?i:e+i;t?window.history.replaceState({path:a},"",a):window.history.pushState({path:a},"",a)}}async navigate(e="/",t=!1,i=!1){const s=++this.navigationId;this.pendingNavId=s;try{const r=this.normalizePath(e),n=this.currentRoute,h=this.matchRoute(r);if(!h)return{success:!1,error:`No route matched: ${r}`};if(n&&n.fullPath===h.fullPath)return{success:!0};if(this.beforeEachGuard)try{const e=await this.beforeEachGuard(h,n);if(s!==this.navigationId)return{success:!1,cancelled:!0};if(!1===e)return{success:!1,cancelled:!0};if("string"==typeof e)return this.navigate(e,t)}catch(a){return s!==this.navigationId?{success:!1,cancelled:!0}:{success:!1,error:a instanceof Error?a.message:"Guard Error"}}return s!==this.navigationId?{success:!1,cancelled:!0}:(this.currentRoute=h,i||this.updateBrowserHistory(r,t),this.notifyListeners(),this.afterEachGuard&&this.afterEachGuard(h,n),{success:!0})}finally{this.pendingNavId===s&&(this.pendingNavId=null,s===this.navigationId&&this.markReady())}}resolve(e="/"){const t=this.normalizePath(e);if("hash"===this.mode)return`#${t}`;const i=this.base.endsWith("/")?this.base.slice(0,-1):this.base;return"/"===i?t:i+t}get modeType(){return this.mode}pushWithQuery(e="/",t){const i=new URLSearchParams(t).toString(),s=e.includes("?")?"&":"?";return this.push(e+(i?s+i:""))}push(e="/"){return this.navigate(e,!1)}replace(e="/"){return this.navigate(e,!0)}back(){window.history.back()}forward(){window.history.forward()}listen(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notifyListeners(){this.listeners.forEach(e=>e())}isStarted=!1;handleRouteChange=null;setupListeners(){this.isStarted||(this.isStarted=!0,this.handleRouteChange=()=>{this.navigate(this.getPath(),!0,!0)},"hash"===this.mode?window.addEventListener("hashchange",this.handleRouteChange):window.addEventListener("popstate",this.handleRouteChange),"hash"!==this.mode||window.location.hash||(window.location.hash="/"),this.navigate(this.getPath(),!0).catch(t=>{e&&console.error("[Router] 首导航异常:",t)}))}destroy(){this.navigationId++,this.handleRouteChange&&("hash"===this.mode?window.removeEventListener("hashchange",this.handleRouteChange):window.removeEventListener("popstate",this.handleRouteChange),this.handleRouteChange=null),this.isStarted=!1,this.listeners.clear(),this.componentCache.clear();for(const e of this.keepAliveCache.values())e.dispose?.();this.keepAliveCache.clear(),this.keepAliveKeys=[],this.currentRoute=null,this.navigated=!1,this.pendingNavId=null,this.readyDeferred?.resolve(),this.readyDeferred=null,t=null}getCurrentRoute(){return this.currentRoute}get hasNavigated(){return this.navigated}get isNavigating(){return null!==this.pendingNavId}isReady(){if(this.navigated&&null===this.pendingNavId)return Promise.resolve();if(!this.readyDeferred){let e;const t=new Promise(t=>{e=t});this.readyDeferred={promise:t,resolve:e}}return this.readyDeferred.promise}markReady(){this.navigated=!0,this.readyDeferred?.resolve(),this.readyDeferred=null}getKeepAlive(e){const t=this.keepAliveCache.get(e);if(t){const t=this.keepAliveKeys.indexOf(e);-1!==t&&(this.keepAliveKeys.splice(t,1),this.keepAliveKeys.push(e))}return t}setKeepAlive(e,t){if(this.keepAliveCache.has(e)){const i=this.keepAliveCache.get(e);i&&i!==t&&i.dispose?.(),this.keepAliveCache.set(e,t);const s=this.keepAliveKeys.indexOf(e);-1!==s&&(this.keepAliveKeys.splice(s,1),this.keepAliveKeys.push(e))}else this.keepAliveCache.set(e,t),this.keepAliveKeys.push(e),this.evictKeepAlive()}hasKeepAlive(e){return this.keepAliveCache.has(e)}evictKeepAlive(){if(this.maxKeepAlive)for(;this.keepAliveKeys.length>this.maxKeepAlive;){const e=this.keepAliveKeys.shift();if(e){const t=this.keepAliveCache.get(e);t?.dispose?.(),this.keepAliveCache.delete(e)}}}cacheKey(e){return this.normalizePath(e)}prefetch(e){const t=this.matchRoute(e);if(!t)return;const i=this.cacheKey(t.fullPath),s=t.matched[t.matched.length-1];if(!s?.config.component)return;const a=s.config.component;if("function"!=typeof a)return;if(this.componentCache.has(i))return;const r=a();this.componentCache.set(i,r),r.catch(()=>{this.componentCache.delete(i)})}getComponentFromCache(e){return this.componentCache.get(this.cacheKey(e))}}export{o as Router,n as createRouter,h as getRouter,r as routerReady};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./core.cjs"),t=require("../runtime/component/base-element.cjs"),
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./core.cjs"),t=require("../shared/env.cjs"),r=require("../runtime/component/base-element.cjs"),s=require("../runtime/component/decorators.cjs");Object.getOwnPropertyDescriptor;const o=new WeakMap;exports.default=class extends r.default{unsubscribe;level=0;currentElement=null;currentTagName=null;managedNodes=new Set;scheduled=!1;latestLoadId=0;abortController=null;disposed=!1;router=null;warnTimer;async mounted(){if(this.disposed=!1,this.detectLevel(),this.router=await e.routerReady(),!this.disposed){if(this.unsubscribe=this.router.listen(()=>this.scheduleLoad()),null===this.router.getCurrentRoute()){const r=this.latestLoadId;for(this.router.hasNavigated&&!this.router.isNavigating||(this.renderPending(),t.IS_DEV&&!this.router.hasNavigated&&this.warnIfNeverStarted()),await this.router.isReady();!this.disposed&&null===this.router.getCurrentRoute()&&this.router.isNavigating;)await this.router.isReady();if(this.disposed)return;if(e.getRouter()!==this.router)return;if(this.latestLoadId!==r)return}this.loadRoute(this.router.getCurrentRoute())}}unmounted(){this.disposed=!0,void 0!==this.warnTimer&&(window.clearTimeout(this.warnTimer),this.warnTimer=void 0),this.abortController?.abort(),this.abortController=null,this.unsubscribe?.(),this.clear()}scheduleLoad(){!this.router||this.scheduled||this.disposed||(this.scheduled=!0,queueMicrotask(()=>{this.scheduled=!1,!this.disposed&&this.router&&this.loadRoute(this.router.getCurrentRoute())}))}warnIfNeverStarted(){this.warnTimer=window.setTimeout(()=>{this.warnTimer=void 0,!this.disposed&&this.router&&!1===this.router.hasNavigated&&console.warn("[router-view] 首次导航 3s 内仍未完成,router-view 会保持占位状态:若尚未调用 router.setupListeners() 请补上;若守卫确实耗时较长,可忽略此提示")},3e3)}detectLevel(){let e=0,t=this.parentElement;for(;t;){const r=t.closest("router-view");if(r){if(e++,t=r.parentElement,!t){const e=r.getRootNode();t=e instanceof ShadowRoot?e.host:null}}else{const e=t.getRootNode();t=e instanceof ShadowRoot?e.host:null}}this.level=e}async loadRoute(e){this.abortController&&(this.abortController.abort(),this.abortController=null);const t=++this.latestLoadId,r=e?.matched[this.level];if(!r)return void this.handleEmptyRoute();const{config:s}=r;let o=s.tagName;if(!o&&"function"==typeof s.component){this.renderLoading();const r=new AbortController;this.abortController=r;try{const i=this.router?.getComponentFromCache?.(e?.fullPath),n=i?await i:await s.component();if(r.signal.aborted||t!==this.latestLoadId||this.disposed)return;o="string"==typeof n?n:n.tagName}catch(i){if(r.signal.aborted||t!==this.latestLoadId||this.disposed)return;return void this.renderError(`Load Error: ${i}`)}finally{this.abortController===r&&(this.abortController=null)}}if(t===this.latestLoadId&&!this.disposed)if(o)if(!s.forceReload&&this.currentElement&&this.currentTagName===o.toLowerCase())this.syncState(this.currentElement,e?.params||{},e?.query||{},s.props);else{this.clear();const t=this.getOrCreateComponent(o,s,e);this.syncState(t,e?.params||{},e?.query||{},s.props),this.appendManagedNode(t),this.currentElement=t,this.currentTagName=o.toLowerCase()}else this.clear()}syncState(e,t,r,s={}){const i=e=>e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),n=function(e){let t=o.get(e);return t||(t={routerAttrs:new Set,propKeys:new Set},o.set(e,t)),t}(e),a=new Map;Object.entries(t).forEach(([e,t])=>a.set(i(e),String(t))),Object.entries(r).forEach(([e,t])=>a.set(`query-${i(e)}`,String(t))),n.routerAttrs.forEach(t=>{a.has(t)||(e.removeAttribute(t),n.routerAttrs.delete(t))}),a.forEach((t,r)=>{e.getAttribute(r)!==t&&e.setAttribute(r,t),n.routerAttrs.add(r)});const d=new Set(Object.keys(s)),l=e;n.propKeys.forEach(e=>{d.has(e)||(l[e]=void 0)}),Object.entries(s).forEach(([e,t])=>{l[e]!==t&&(l[e]=t)}),n.propKeys=d}getOrCreateComponent(e,t,r){if(!r)throw new Error("Route is required to create or retrieve component");const s=t.keepAliveKey?t.keepAliveKey(r,this.level):this.buildKeepAliveKey(e,r),o=t.keepAlive&&this.router?.getKeepAlive(s);if(o)return o;const i=document.createElement(e);return t.keepAlive&&this.router?.setKeepAlive(s,i),i}buildKeepAliveKey(e,t){const r=t.matched[this.level],s=r?.config.path??e.toLowerCase(),o=Object.values(r?.params??{});return o.length?`${this.level}:${s}:${o.join("|")}`:`${this.level}:${s}`}handleEmptyRoute(){if(0===this.level){this.clear();const e=this.$data.notFound;if(e){const t=document.createElement(e);this.appendManagedNode(t),this.currentElement=t,this.currentTagName=e.toLowerCase()}else this.renderError("404 Not Found")}else this.clear()}appendManagedNode(e){e.parentNode!==this&&this.appendChild(e),this.managedNodes.add(e)}clear(){this.managedNodes.forEach(e=>{e.parentNode===this&&this.removeChild(e)}),this.managedNodes.clear(),this.currentElement=null,this.currentTagName=null}renderPlaceholder(e){this.clear();const t=this.$data.loading;if(t)return void this.appendManagedNode(document.createElement(t));if(!e)return;const r=document.createElement("div");r.style.cssText="padding:20px; color:#999;",r.textContent=e,this.appendManagedNode(r)}renderLoading(){this.renderPlaceholder("Loading...")}renderPending(){this.renderPlaceholder()}renderError(e){this.clear();const t=document.createElement("div");t.style.cssText="padding:20px; color:#ff4d4f;",t.textContent=e,this.appendManagedNode(t)}},exports.default=((e,t)=>{for(var r,s=t,o=e.length-1;o>=0;o--)(r=e[o])&&(s=r(s)||s);return s})([s.CustomElement({tagName:"router-view",props:[{name:"notFound",type:"string",default:""},{name:"loading",type:"string",default:""}]})],exports.default);
|
|
@@ -2,6 +2,7 @@ import { BaseElement } from '../runtime/component';
|
|
|
2
2
|
import { RouteMatch } from './types';
|
|
3
3
|
declare class RouterView extends BaseElement<{
|
|
4
4
|
notFound: string;
|
|
5
|
+
loading: string;
|
|
5
6
|
}> {
|
|
6
7
|
private unsubscribe?;
|
|
7
8
|
private level;
|
|
@@ -13,9 +14,12 @@ declare class RouterView extends BaseElement<{
|
|
|
13
14
|
private abortController;
|
|
14
15
|
private disposed;
|
|
15
16
|
private router;
|
|
17
|
+
private warnTimer?;
|
|
16
18
|
mounted(): Promise<void>;
|
|
17
19
|
unmounted(): void;
|
|
18
20
|
private scheduleLoad;
|
|
21
|
+
/** DEV 提示:首导航 3s 内未 settle —— 可能是忘了 setupListeners(),也可能是守卫本身很慢 */
|
|
22
|
+
private warnIfNeverStarted;
|
|
19
23
|
private detectLevel;
|
|
20
24
|
loadRoute(route: RouteMatch | null): Promise<void>;
|
|
21
25
|
private syncState;
|
|
@@ -24,7 +28,13 @@ declare class RouterView extends BaseElement<{
|
|
|
24
28
|
private handleEmptyRoute;
|
|
25
29
|
private appendManagedNode;
|
|
26
30
|
private clear;
|
|
31
|
+
/**
|
|
32
|
+
* 渲染占位内容:优先使用 `loading` 指定的占位组件,未配置时按需渲染兜底文本。
|
|
33
|
+
* 启动阶段(首导航未完成)不传 fallbackText,保持空白。
|
|
34
|
+
*/
|
|
35
|
+
private renderPlaceholder;
|
|
27
36
|
private renderLoading;
|
|
37
|
+
private renderPending;
|
|
28
38
|
private renderError;
|
|
29
39
|
}
|
|
30
40
|
export default RouterView;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{routerReady as e}from"./core.js";import
|
|
1
|
+
import{routerReady as e,getRouter as t}from"./core.js";import{IS_DEV as r}from"../shared/env.js";import o from"../runtime/component/base-element.js";import{CustomElement as s}from"../runtime/component/decorators.js";Object.getOwnPropertyDescriptor;const i=new WeakMap;let n=class extends o{unsubscribe;level=0;currentElement=null;currentTagName=null;managedNodes=new Set;scheduled=!1;latestLoadId=0;abortController=null;disposed=!1;router=null;warnTimer;async mounted(){if(this.disposed=!1,this.detectLevel(),this.router=await e(),!this.disposed){if(this.unsubscribe=this.router.listen(()=>this.scheduleLoad()),null===this.router.getCurrentRoute()){const e=this.latestLoadId;for(this.router.hasNavigated&&!this.router.isNavigating||(this.renderPending(),r&&!this.router.hasNavigated&&this.warnIfNeverStarted()),await this.router.isReady();!this.disposed&&null===this.router.getCurrentRoute()&&this.router.isNavigating;)await this.router.isReady();if(this.disposed)return;if(t()!==this.router)return;if(this.latestLoadId!==e)return}this.loadRoute(this.router.getCurrentRoute())}}unmounted(){this.disposed=!0,void 0!==this.warnTimer&&(window.clearTimeout(this.warnTimer),this.warnTimer=void 0),this.abortController?.abort(),this.abortController=null,this.unsubscribe?.(),this.clear()}scheduleLoad(){!this.router||this.scheduled||this.disposed||(this.scheduled=!0,queueMicrotask(()=>{this.scheduled=!1,!this.disposed&&this.router&&this.loadRoute(this.router.getCurrentRoute())}))}warnIfNeverStarted(){this.warnTimer=window.setTimeout(()=>{this.warnTimer=void 0,!this.disposed&&this.router&&!1===this.router.hasNavigated&&console.warn("[router-view] 首次导航 3s 内仍未完成,router-view 会保持占位状态:若尚未调用 router.setupListeners() 请补上;若守卫确实耗时较长,可忽略此提示")},3e3)}detectLevel(){let e=0,t=this.parentElement;for(;t;){const r=t.closest("router-view");if(r){if(e++,t=r.parentElement,!t){const e=r.getRootNode();t=e instanceof ShadowRoot?e.host:null}}else{const e=t.getRootNode();t=e instanceof ShadowRoot?e.host:null}}this.level=e}async loadRoute(e){this.abortController&&(this.abortController.abort(),this.abortController=null);const t=++this.latestLoadId,r=e?.matched[this.level];if(!r)return void this.handleEmptyRoute();const{config:o}=r;let s=o.tagName;if(!s&&"function"==typeof o.component){this.renderLoading();const r=new AbortController;this.abortController=r;try{const i=this.router?.getComponentFromCache?.(e?.fullPath),n=i?await i:await o.component();if(r.signal.aborted||t!==this.latestLoadId||this.disposed)return;s="string"==typeof n?n:n.tagName}catch(i){if(r.signal.aborted||t!==this.latestLoadId||this.disposed)return;return void this.renderError(`Load Error: ${i}`)}finally{this.abortController===r&&(this.abortController=null)}}if(t===this.latestLoadId&&!this.disposed)if(s)if(!o.forceReload&&this.currentElement&&this.currentTagName===s.toLowerCase())this.syncState(this.currentElement,e?.params||{},e?.query||{},o.props);else{this.clear();const t=this.getOrCreateComponent(s,o,e);this.syncState(t,e?.params||{},e?.query||{},o.props),this.appendManagedNode(t),this.currentElement=t,this.currentTagName=s.toLowerCase()}else this.clear()}syncState(e,t,r,o={}){const s=e=>e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),n=function(e){let t=i.get(e);return t||(t={routerAttrs:new Set,propKeys:new Set},i.set(e,t)),t}(e),a=new Map;Object.entries(t).forEach(([e,t])=>a.set(s(e),String(t))),Object.entries(r).forEach(([e,t])=>a.set(`query-${s(e)}`,String(t))),n.routerAttrs.forEach(t=>{a.has(t)||(e.removeAttribute(t),n.routerAttrs.delete(t))}),a.forEach((t,r)=>{e.getAttribute(r)!==t&&e.setAttribute(r,t),n.routerAttrs.add(r)});const d=new Set(Object.keys(o)),l=e;n.propKeys.forEach(e=>{d.has(e)||(l[e]=void 0)}),Object.entries(o).forEach(([e,t])=>{l[e]!==t&&(l[e]=t)}),n.propKeys=d}getOrCreateComponent(e,t,r){if(!r)throw new Error("Route is required to create or retrieve component");const o=t.keepAliveKey?t.keepAliveKey(r,this.level):this.buildKeepAliveKey(e,r),s=t.keepAlive&&this.router?.getKeepAlive(o);if(s)return s;const i=document.createElement(e);return t.keepAlive&&this.router?.setKeepAlive(o,i),i}buildKeepAliveKey(e,t){const r=t.matched[this.level],o=r?.config.path??e.toLowerCase(),s=Object.values(r?.params??{});return s.length?`${this.level}:${o}:${s.join("|")}`:`${this.level}:${o}`}handleEmptyRoute(){if(0===this.level){this.clear();const e=this.$data.notFound;if(e){const t=document.createElement(e);this.appendManagedNode(t),this.currentElement=t,this.currentTagName=e.toLowerCase()}else this.renderError("404 Not Found")}else this.clear()}appendManagedNode(e){e.parentNode!==this&&this.appendChild(e),this.managedNodes.add(e)}clear(){this.managedNodes.forEach(e=>{e.parentNode===this&&this.removeChild(e)}),this.managedNodes.clear(),this.currentElement=null,this.currentTagName=null}renderPlaceholder(e){this.clear();const t=this.$data.loading;if(t)return void this.appendManagedNode(document.createElement(t));if(!e)return;const r=document.createElement("div");r.style.cssText="padding:20px; color:#999;",r.textContent=e,this.appendManagedNode(r)}renderLoading(){this.renderPlaceholder("Loading...")}renderPending(){this.renderPlaceholder()}renderError(e){this.clear();const t=document.createElement("div");t.style.cssText="padding:20px; color:#ff4d4f;",t.textContent=e,this.appendManagedNode(t)}};n=((e,t)=>{for(var r,o=t,s=e.length-1;s>=0;s--)(r=e[s])&&(o=r(o)||o);return o})([s({tagName:"router-view",props:[{name:"notFound",type:"string",default:""},{name:"loading",type:"string",default:""}]})],n);export{n as default};
|
package/dist/router/types.d.ts
CHANGED
|
@@ -41,7 +41,9 @@ export interface RouteConfig {
|
|
|
41
41
|
*/
|
|
42
42
|
async?: boolean;
|
|
43
43
|
/** * 404 页面组件标签名。
|
|
44
|
-
*
|
|
44
|
+
* @deprecated 该字段从未生效:路径不匹配时 `matchRoute()` 直接返回 null,
|
|
45
|
+
* 不存在可读取的 config,因此无法取到本字段。
|
|
46
|
+
* 请改用 `{ path: '*', tagName: 'xxx' }` 兜底路由,或 RouterView 的 `not-found` 属性。
|
|
45
47
|
*/
|
|
46
48
|
notFoundComponent?: string;
|
|
47
49
|
}
|
package/dist/shared/env.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=(()=>{const e=globalThis;if(!0===e.__IS_PROD__)return!1;if("undefined"!=typeof window){if(window.location?.search.includes("debug"))return!0;if(!0===e.__DEBUG__||!0===e.__IS_DEV__)return!0}const o=e.process?.env?.NODE_ENV;return"production"!==o&&("development"===o||!("undefined"==typeof window||!["localhost","127.0.0.1","0.0.0.0"].includes(window.location?.hostname||"")))})(),o=!e;exports.IS_DEV=e,exports.IS_PROD=o,exports.SOLELY_VERSION="0.7.
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=(()=>{const e=globalThis;if(!0===e.__IS_PROD__)return!1;if("undefined"!=typeof window){if(window.location?.search.includes("debug"))return!0;if(!0===e.__DEBUG__||!0===e.__IS_DEV__)return!0}const o=e.process?.env?.NODE_ENV;return"production"!==o&&("development"===o||!("undefined"==typeof window||!["localhost","127.0.0.1","0.0.0.0"].includes(window.location?.hostname||"")))})(),o=!e;exports.IS_DEV=e,exports.IS_PROD=o,exports.SOLELY_VERSION="0.7.1";
|
package/dist/shared/env.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const n=(()=>{const n=globalThis;if(!0===n.__IS_PROD__)return!1;if("undefined"!=typeof window){if(window.location?.search.includes("debug"))return!0;if(!0===n.__DEBUG__||!0===n.__IS_DEV__)return!0}const o=n.process?.env?.NODE_ENV;return"production"!==o&&("development"===o||!("undefined"==typeof window||!["localhost","127.0.0.1","0.0.0.0"].includes(window.location?.hostname||"")))})(),o=!n,e="0.7.
|
|
1
|
+
const n=(()=>{const n=globalThis;if(!0===n.__IS_PROD__)return!1;if("undefined"!=typeof window){if(window.location?.search.includes("debug"))return!0;if(!0===n.__DEBUG__||!0===n.__IS_DEV__)return!0}const o=n.process?.env?.NODE_ENV;return"production"!==o&&("development"===o||!("undefined"==typeof window||!["localhost","127.0.0.1","0.0.0.0"].includes(window.location?.hostname||"")))})(),o=!n,e="0.7.1";export{n as IS_DEV,o as IS_PROD,e as SOLELY_VERSION};
|
package/package.json
CHANGED