vitarx-router 1.0.0-beta.13 → 1.0.0-beta.15

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.
@@ -360,7 +360,7 @@ export declare enum NavigateStatus {
360
360
  /**
361
361
  * 重定向处理器
362
362
  */
363
- export declare type RedirectHandler = (this: Router, to: RouteLocation) => RouteTarget;
363
+ export declare type RedirectHandler = (this: Router, to: RouteLocation) => RouteTarget | undefined;
364
364
 
365
365
  /**
366
366
  * 路由路线配置
@@ -761,7 +761,7 @@ export declare class RouterLink extends Widget<RouterLinkProps> {
761
761
  *
762
762
  * @protected
763
763
  */
764
- protected target: Computed<RouteTarget>;
764
+ protected target: Computed<RouteTarget | undefined>;
765
765
  /**
766
766
  * 路由目标对应的`RouteLocation`对象
767
767
  *
@@ -769,7 +769,7 @@ export declare class RouterLink extends Widget<RouterLinkProps> {
769
769
  *
770
770
  * @protected
771
771
  */
772
- protected location: Computed<RouteLocation>;
772
+ protected location: Computed<RouteLocation | undefined>;
773
773
  /**
774
774
  * 激活状态
775
775
  *
@@ -836,7 +836,7 @@ export declare interface RouterLinkProps {
836
836
  *
837
837
  * 可选值:
838
838
  * - none:不计算激活状态
839
- * - obscure:模糊匹配,只要目标路由的路径包含当前路由的路径,就认为当前路由处于激活状态
839
+ * - obscure:模糊匹配,只要目标路由的路径以当前路由的路径开头,就认为当前路由处于激活状态
840
840
  * - strict:严格匹配,只有目标路由的路径完全匹配当前路由的路径,才认为当前路由处于激活状态
841
841
  *
842
842
  * @default 'none'
@@ -1074,7 +1074,7 @@ export declare class RouterView extends Widget<RouteOptions> {
1074
1074
  *
1075
1075
  * @protected
1076
1076
  */
1077
- protected get currentElement(): VNode | undefined;
1077
+ protected get currentElement(): VNode<WidgetType> | undefined;
1078
1078
  /**
1079
1079
  * 当前路由器视图要显示的组件
1080
1080
  *
@@ -1,7 +1,7 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value;
3
3
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
4
- import { reactive, markRaw, shallowReactive, createElement, LazyWidget, deepClone, isDeepEqual, Widget, shallowRef, inject, provide, watch, Fragment, Computed, isString } from "vitarx";
4
+ import { reactive, markRaw, shallowReactive, createElement, LazyWidget, deepClone, isDeepEqual, isObject, Widget, shallowRef, inject, provide, watch, Fragment, Computed, isString } from "vitarx";
5
5
  var NavigateStatus = /* @__PURE__ */ ((NavigateStatus2) => (NavigateStatus2[NavigateStatus2.success = 0] = "success", NavigateStatus2[NavigateStatus2.aborted = 1] = "aborted", NavigateStatus2[NavigateStatus2.cancelled = 2] = "cancelled", NavigateStatus2[NavigateStatus2.duplicated = 3] = "duplicated", NavigateStatus2[NavigateStatus2.not_matched = 4] = "not_matched", NavigateStatus2[NavigateStatus2.exception = 5] = "exception", NavigateStatus2))(NavigateStatus || {});
6
6
  function validateInjectPropsRule(rule) {
7
7
  return typeof rule == "boolean" || typeof rule == "function" || typeof rule == "object" && rule !== null;
@@ -51,7 +51,7 @@ function validateWidget(route) {
51
51
  if (!("widget" in route)) {
52
52
  if (route.children.length === 0)
53
53
  throw new TypeError(
54
- `[Vitarx.Router][TYPE_ERROR]:${route.path} 路由线路配置的 widget 属性缺失,它可以是函数式小部件、类小部件,亦或是一个惰性加载器。`
54
+ `[Vitarx.Router][ERROR]:${route.path} 路由线路配置的 widget 属性缺失,且没有children,它是一个不规范的路由。`
55
55
  );
56
56
  route.widget = void 0;
57
57
  return;
@@ -65,11 +65,11 @@ function validateWidget(route) {
65
65
  for (const k in route.widget)
66
66
  if (typeof route.widget[k] != "function")
67
67
  throw new TypeError(
68
- `[Vitarx.Router][TYPE_ERROR]:${route.path} 路由线路配置的 widget 命名视图 ${k} 类型有误,它可以是函数式小部件、类小部件,亦或是一个惰性加载器。`
68
+ `[Vitarx.Router][ERROR]:${route.path} 路由线路配置的 widget 命名视图 ${k} 类型有误,它可以是函数式小部件、类小部件,亦或是一个惰性加载器。`
69
69
  );
70
70
  } else
71
71
  throw new TypeError(
72
- `[Vitarx.Router][TYPE_ERROR]:${route.path} 路由线路配置的 widget 类型有误,它可以是函数式小部件、类小部件,亦或是一个惰性加载器。`
72
+ `[Vitarx.Router][ERROR]:${route.path} 路由线路配置的 widget 类型有误,它可以是函数式小部件、类小部件,亦或是一个惰性加载器。`
73
73
  );
74
74
  }
75
75
  const LAZY_LOADER_SYMBOL = Symbol("LazyLoader");
@@ -402,9 +402,23 @@ class RouterRegistry {
402
402
  registerRoute(route, group) {
403
403
  const normalizedRoute = normalizeRoute(route, group, this.suffix);
404
404
  if (group && this._parentRoute.set(normalizedRoute, group), isRouteGroup(normalizedRoute)) {
405
- route.widget && this.recordRoute(normalizedRoute);
405
+ this.recordRoute(normalizedRoute);
406
406
  for (const child of normalizedRoute.children)
407
407
  this.registerRoute(child, normalizedRoute);
408
+ normalizedRoute.redirect || (normalizedRoute.redirect = function(to) {
409
+ var _a;
410
+ let first = normalizedRoute.children[0];
411
+ for (; first; ) {
412
+ if (first.redirect)
413
+ return typeof first.redirect == "function" ? first.redirect.call(this, to) : first.redirect;
414
+ if (first.widget) return { index: first.path };
415
+ first = (_a = first.children) == null ? void 0 : _a[0];
416
+ }
417
+ console.error(
418
+ `[Vitarx.Router][ERROR]:${normalizedRoute.path} 分组路由在没有配置重定向的情况下,它的第一个子路由必须具有widget或redirect,否则无法匹配视图`,
419
+ normalizedRoute
420
+ );
421
+ });
408
422
  } else
409
423
  this.recordRoute(normalizedRoute);
410
424
  }
@@ -719,11 +733,17 @@ const _RouterCore = class _RouterCore extends RouterRegistry {
719
733
  const isCurrentTask = () => this._currentTaskId === taskId, from = deepClone(this.currentRouteLocation), performNavigation = async (_target, isRedirect) => {
720
734
  const to = this.createRouteLocation(_target), matched = to.matched.at(-1);
721
735
  if (matched != null && matched.redirect) {
722
- if (typeof matched.redirect == "string")
723
- return performNavigation({ index: matched.redirect }, !0);
724
- if (typeof matched.redirect == "function")
725
- return performNavigation(matched.redirect.call(this, to), !0);
726
- } else to.matched.length === 1 && matched.children.length && to.matched.push(matched.children[0]);
736
+ let redirectTarget;
737
+ if (typeof matched.redirect == "object" && matched.redirect.index)
738
+ redirectTarget = matched.redirect;
739
+ else if (typeof matched.redirect == "string")
740
+ redirectTarget = { index: matched.redirect };
741
+ else if (typeof matched.redirect == "function") {
742
+ const redirectHandleResult = matched.redirect.call(this, to);
743
+ isObject(redirectHandleResult) && (redirectTarget = redirectHandleResult);
744
+ }
745
+ if (redirectTarget != null && redirectTarget.index) return performNavigation(redirectTarget, !0);
746
+ }
727
747
  const createNavigateResult = (overrides = {}) => ({
728
748
  from,
729
749
  to,
@@ -1257,15 +1277,22 @@ class RouterLink extends Widget {
1257
1277
  */
1258
1278
  __publicField(this, "active");
1259
1279
  __publicField(this, "htmlProps");
1260
- this.target = new Computed(() => markRaw(isString(props.to) ? { index: props.to } : props.to)), this.location = new Computed(() => {
1280
+ this.target = new Computed(() => {
1281
+ if (this.props.to)
1282
+ return markRaw(isString(props.to) ? { index: props.to } : props.to);
1283
+ }), this.location = new Computed(() => {
1284
+ if (!this.target.value) return;
1261
1285
  const location = RouterCore.instance.createRouteLocation(this.target.value);
1262
1286
  return location.matched.length || console.warn(
1263
1287
  `[Vitarx.RouterLink][WARN]:索引:${this.target.value.index},未匹配到任何有效的路由线路,请检查to属性是否配置正确!`
1264
1288
  ), markRaw(location);
1265
- }), props.active !== void 0 && props.active !== "none" && (this.active = new Computed(() => this.target.value.index.startsWith("/") ? props.active === "obscure" ? RouterCore.instance.currentRouteLocation.fullPath.startsWith(
1289
+ }), props.active !== void 0 && props.active !== "none" && (this.active = new Computed(() => !this.target.value || !this.location.value ? !1 : this.target.value.index.startsWith("/") ? props.active === "obscure" ? RouterCore.instance.currentRouteLocation.fullPath.startsWith(
1266
1290
  this.location.value.path
1267
1291
  ) : this.location.value.path === RouterCore.instance.currentRouteLocation.path : !!RouterCore.instance.currentRouteLocation.matched.find(
1268
- (route) => route.name === this.target.value.index
1292
+ (route) => {
1293
+ var _a;
1294
+ return route.name === ((_a = this.target.value) == null ? void 0 : _a.index);
1295
+ }
1269
1296
  ))), this.htmlProps = new Computed(() => {
1270
1297
  const props2 = {
1271
1298
  href: this.href,
@@ -1291,7 +1318,8 @@ class RouterLink extends Widget {
1291
1318
  * 路由目标地址
1292
1319
  */
1293
1320
  get href() {
1294
- return this.location.value.fullPath;
1321
+ var _a;
1322
+ return ((_a = this.location.value) == null ? void 0 : _a.fullPath) || "javascript:void(0)";
1295
1323
  }
1296
1324
  /**
1297
1325
  * 导航到目标路由
@@ -1301,7 +1329,12 @@ class RouterLink extends Widget {
1301
1329
  * @param e
1302
1330
  */
1303
1331
  navigate(e) {
1304
- e.stopPropagation(), e.preventDefault(), !this.isDisabled && RouterCore.instance.navigate(this.location.value).then();
1332
+ e.preventDefault(), this.location.value && !this.isDisabled && RouterCore.instance.navigate(this.location.value).then((res) => {
1333
+ var _a;
1334
+ res.status !== NavigateStatus.success && console.warn(
1335
+ `[Vitarx.RouterLink][WARN]:导航到索引:${(_a = this.target.value) == null ? void 0 : _a.index}失败,${res.message}`
1336
+ );
1337
+ });
1305
1338
  }
1306
1339
  build() {
1307
1340
  return createElement("a", this.htmlProps.value);
@@ -1 +1 @@
1
- (function(global,factory){typeof exports=="object"&&typeof module<"u"?factory(exports,require("vitarx")):typeof define=="function"&&define.amd?define(["exports","vitarx"],factory):(global=typeof globalThis<"u"?globalThis:global||self,factory(global.VitarxRouter={},global.Vitarx))})(this,function(exports2,vitarx){"use strict";var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value);var NavigateStatus=(NavigateStatus2=>(NavigateStatus2[NavigateStatus2.success=0]="success",NavigateStatus2[NavigateStatus2.aborted=1]="aborted",NavigateStatus2[NavigateStatus2.cancelled=2]="cancelled",NavigateStatus2[NavigateStatus2.duplicated=3]="duplicated",NavigateStatus2[NavigateStatus2.not_matched=4]="not_matched",NavigateStatus2[NavigateStatus2.exception=5]="exception",NavigateStatus2))(NavigateStatus||{});function validateInjectPropsRule(rule){return typeof rule=="boolean"||typeof rule=="function"||typeof rule=="object"&&rule!==null}function validateInjectProps(route){if(route.widget===void 0)return;if(!("injectProps"in route)){route.injectProps=generateDefaultInjectProps(route,!0);return}const injectProps=route.injectProps;if(typeof injectProps=="object")isDefaultInjectProps(injectProps)?validateInjectPropsForDefault(route,injectProps):validateInjectPropsForNamed(route,injectProps);else if(validateInjectPropsRule(injectProps))route.injectProps=generateDefaultInjectProps(route,injectProps);else throw new TypeError(`[Vitarx.Router][TYPE_ERROR]:${route.path} 路由线路配置的 injectProps 类型有误,它可以是布尔值、函数,亦或是一个{string:any}类型的对象。`)}function isDefaultInjectProps(injectProps){return Object.keys(injectProps).length===1&&"default"in injectProps}function validateInjectPropsForDefault(route,injectProps){if(!validateInjectPropsRule(injectProps.default))throw new TypeError(`[Vitarx.Router][TYPE_ERROR]:${route.path} 路由线路配置的 injectProps.default 类型有误,它可以是布尔值、函数,亦或是一个{string:any}类型的对象。`)}function validateInjectPropsForNamed(route,injectProps){for(const key of Object.keys(route.widget))if(key in injectProps){if(!validateInjectPropsRule(injectProps[key]))throw new TypeError(`[Vitarx.Router][TYPE_ERROR]:${route.path} 路由线路配置的 injectProps.${key} 类型有误,它可以是布尔值、函数,亦或是一个{string:any}类型的对象。`)}else injectProps[key]=!0}function generateDefaultInjectProps(route,rule){const injectProps={};for(const key of Object.keys(route.widget))injectProps[key]=rule;return injectProps}function validateWidget(route){if(!("widget"in route)){if(route.children.length===0)throw new TypeError(`[Vitarx.Router][TYPE_ERROR]:${route.path} 路由线路配置的 widget 属性缺失,它可以是函数式小部件、类小部件,亦或是一个惰性加载器。`);route.widget=void 0;return}if(typeof route.widget=="function")route.widget={default:route.widget};else if(typeof route.widget=="object"&&route.widget!==null){if(Object.keys(route.widget).length===0)route.widget=void 0;else for(const k in route.widget)if(typeof route.widget[k]!="function")throw new TypeError(`[Vitarx.Router][TYPE_ERROR]:${route.path} 路由线路配置的 widget 命名视图 ${k} 类型有误,它可以是函数式小部件、类小部件,亦或是一个惰性加载器。`)}else throw new TypeError(`[Vitarx.Router][TYPE_ERROR]:${route.path} 路由线路配置的 widget 类型有误,它可以是函数式小部件、类小部件,亦或是一个惰性加载器。`)}const LAZY_LOADER_SYMBOL=Symbol("LazyLoader");function isVariablePath(path){return/\{[^}]+}/.test(path)}function optionalVariableCount(path){const pathWithoutSpaces=path.replace(/\s+/g,""),regex=/\{[\w-]+\?}/g,matches=pathWithoutSpaces.match(regex);return matches?matches.length:0}function isRouteGroup(route){return"children"in route&&route.children!==void 0&&route.children.length>0}function createDynamicPattern(path,pattern,strict,defaultPattern){let optional=0;const processVariable=(varName,isOptional)=>{const regex=pattern[varName];if(regex?regex instanceof RegExp||(console.warn(`[Vitarx.Router][WARN]:${path} 动态路径${varName}变量的自定义正则表达式必须是 RegExp 类型`),pattern[varName]=defaultPattern):pattern[varName]=defaultPattern,isOptional)return optional++,`(?:(${pattern[varName].source}))?`;if(optional)throw new Error(`[Vitarx.Router][ERROR]:动态路径 ${path} 中,可选变量 ${varName} 后不能存在任何必填变量`);return`(${pattern[varName].source})`},processedPath=path.replace(/{([^}?]+)\?}/g,(_,varName)=>processVariable(varName,!0)).replace(/{([^}]+)}/g,(_,varName)=>processVariable(varName,!1)).replace(/\//g,"\\/").replace(/\/?$/,"/?"),flags=strict?"":"i",segments=path.replace(/^\/|\/$/g,"").split("/").length;return{regex:new RegExp(`^${processedPath}$`,flags),length:segments,optional}}function formatPath(path){return path=`/${path}`.replace(/\s+/g,"").replace(/\/+/g,"/"),path.length?path==="/"||path==="/#/"?path:path.replace(/\/$/,""):"/"}function mergePathParams(path,params){if(!isVariablePath(path))return path;const oldPath=path;return path=path.replace(/{([^}]+)\?*}/g,(_match,paramName)=>{const isOptional=paramName.endsWith("?");if(isOptional&&(paramName=paramName.slice(0,-1)),params[paramName]===void 0){if(isOptional)return"";throw new TypeError(`[Vitarx.Router.mergePathParams] 访问路由${oldPath}时缺少参数:${paramName}`)}return String(params[paramName]).replace(/\s+/g,"_")}),formatPath(path)}function isLazyLoad(lazyLoader){return typeof lazyLoader=="function"&&lazyLoader[LAZY_LOADER_SYMBOL]}function formatHash(hash,addHashPrefix){return typeof hash!="string"||!hash?"":(hash=hash.trim(),hash.startsWith("#")?hash:`#${hash}`)}function queryStringToObject(queryString){queryString=decodeURIComponent(queryString);const params=new URLSearchParams(queryString.startsWith("?")?queryString.substring(1):queryString),obj={};return params.forEach((value,key)=>obj[key]=value),obj}function objectToQueryString(obj){const queryString=new URLSearchParams(obj).toString();return queryString?`?${queryString}`:""}function urlToRouteTarget(url,mode,base){let path=decodeURIComponent(url.pathname),hash=decodeURIComponent(url.hash),query=queryStringToObject(url.search);if(path=formatPath(path.startsWith(base)?path.slice(base.length):path),mode==="hash"&&hash.includes("#/")){const hashPart=hash.slice(1),[fullPath,anchor]=hashPart.split("#");path=formatPath(fullPath||"/"),hash=anchor?`#${anchor}`:""}return{index:path,hash,query}}function splitPathAndSuffix(path){const suffix=getPathSuffix(path);return suffix&&(path=path.slice(0,-suffix.length)),{path,suffix:suffix.substring(1)}}function getPathSuffix(path){const match=path.match(/^(.*?)(\.[a-zA-Z0-9]+)$/);return match?match[2]:""}function isRouteLocationTypeObject(obj){if(typeof obj!="object"||obj===null)return!1;const keys=["index","fullPath","path","hash","params","query","matched","meta"];for(const key of keys)if(!Object.prototype.hasOwnProperty.call(obj,key))return!1;return!0}function normalizeRoute(route,group,suffix){if(route.meta=route.meta||{},route.pattern=route.pattern||{},route.children=route.children||[],!Array.isArray(route.children))throw new TypeError(`[Vitarx.Router][TYPE_ERROR]:${route.path} 路由线路配置 children 类型错误,它必须是数组类型。`);if(!route.path.trim())throw new TypeError("[Vitarx.Router][TYPE_ERROR]:路由线路配置 path 不能为空");return route.path=formatPath(group?`${group.path}/${route.path}`:route.path),validateWidget(route),validateInjectProps(route),route.suffix??(route.suffix=(group==null?void 0:group.suffix)??suffix),route.afterEnter??(route.afterEnter=group==null?void 0:group.afterEnter),route.beforeEnter??(route.beforeEnter=group==null?void 0:group.beforeEnter),route}function validateSuffix(suffix,allowSuffix,inputPath,routePath){return allowSuffix==="*"?!0:allowSuffix===!1?inputPath===routePath:Array.isArray(allowSuffix)?allowSuffix.includes(suffix):suffix===allowSuffix}class RouterRegistry{constructor(options){__publicField(this,"_options");__publicField(this,"_namedRoutes",new Map);__publicField(this,"_dynamicRoutes",new Map);__publicField(this,"_pathRoutes",new Map);__publicField(this,"_parentRoute",new WeakMap);this._options={base:"/",strict:!1,mode:"path",scrollBehavior:"smooth",suffix:"*",pattern:/[\w.]+/,...options},this._options.base=`/${this._options.base.replace(/^\/+|\/+$/g,"")}`}get options(){return this._options}get mode(){return this._options.mode}get pathRoutes(){return this._pathRoutes}get namedRoutes(){return this._namedRoutes}get dynamicRoutes(){return this._dynamicRoutes}get routes(){return this._options.routes}get basePath(){return this._options.base}get suffix(){return this._options.suffix}removeRoute(index,isRemoveFromRoutes=!0){const deleteRoute=this.findRoute(index);if(deleteRoute){if(isRouteGroup(deleteRoute))for(const child of deleteRoute.children)this.removeRoute(child.path,!1);this._pathRoutes.delete(deleteRoute.path),deleteRoute.name&&this._namedRoutes.delete(deleteRoute.name),this.removeDynamicRoute(deleteRoute.path),isRemoveFromRoutes&&this.removedFromRoutes(deleteRoute)}}addRoute(route,parent){if(parent){const parentRoute=this.findRoute(parent);if(!parentRoute)throw new Error(`[Vitarx.Router.addRoute][ERROR]:父路由${parent}不存在`);this.registerRoute(route,parentRoute)}else this.registerRoute(route),this._options.routes.push(route)}findRoute(target){const isRouterTarget=typeof target=="object",index=isRouterTarget?target.index:target;if(typeof index!="string")throw new TypeError(`[Vitarx.Router.getRoute][ERROR]:路由索引${target}类型错误,必须给定字符串类型`);if(index.startsWith("/")){const matched=this.matchRoute(index);return matched?(matched.params&&isRouterTarget&&(target.params=Object.assign(target.params||{},matched.params)),matched.route):void 0}return this.findNamedRoute(index)}findNamedRoute(name){return this._namedRoutes.get(name)}findParentRoute(route){return this._parentRoute.get(route)}matchRoute(path){let formattedPath=formatPath(path);this._options.strict||(formattedPath=formattedPath.toLowerCase());try{const{path:shortPath,suffix}=splitPathAndSuffix(formattedPath),staticRoute=this._pathRoutes.get(shortPath);if(staticRoute&&validateSuffix(suffix,staticRoute.suffix,formattedPath,staticRoute.path))return{route:staticRoute,params:void 0};const segmentCount=shortPath.split("/").filter(Boolean).length,candidates=this._dynamicRoutes.get(segmentCount);if(candidates){const normalizedPath=`${shortPath}/`,regexCache=new Map;for(const{regex,route}of candidates){const match=(regexCache.get(regex.source)||regex).exec(normalizedPath);if(!match)continue;const params={},keys=Object.keys(route.pattern);for(let i=0;i<keys.length;i++)params[keys[i]]=match[i+1];if(validateSuffix(suffix,route.suffix,formattedPath,formattedPath))return{route,params}}}if(!suffix&&!shortPath.endsWith("/index")){const indexRoute=this._pathRoutes.get(`${shortPath==="/"?"":shortPath}/index`);if(indexRoute&&validateSuffix(suffix,indexRoute.suffix,formattedPath,indexRoute.path))return{route:indexRoute,params:void 0}}else if(shortPath==="/index"){const indexRoute=this._pathRoutes.get("/");if(indexRoute&&validateSuffix(suffix,indexRoute.suffix,formattedPath,indexRoute.path))return{route:indexRoute,params:void 0}}}catch(error){console.error("Error in matchRoute:",error);return}}setupRoutes(routes){for(const route of routes)this.registerRoute(route)}removedFromRoutes(route){const parent=this.findParentRoute(route);if(parent!=null&&parent.children){const index=parent.children.indexOf(route);index!==-1&&parent.children.splice(index,1)}else{const index=this._options.routes.indexOf(route);index!==-1&&this._options.routes.splice(index,1)}}removeDynamicRoute(path){if(!isVariablePath(path))return;const length=path.split("/").filter(Boolean).length,removeRouteFromRecords=key=>{const records=this._dynamicRoutes.get(key);if(records){for(let i=0;i<records.length;i++)if(records[i].route.path===path){records.splice(i,1);break}}};removeRouteFromRecords(length);const count=optionalVariableCount(path);if(count>0)for(let i=1;i<=count;i++)removeRouteFromRecords(length-i)}registerRoute(route,group){const normalizedRoute=normalizeRoute(route,group,this.suffix);if(group&&this._parentRoute.set(normalizedRoute,group),isRouteGroup(normalizedRoute)){route.widget&&this.recordRoute(normalizedRoute);for(const child of normalizedRoute.children)this.registerRoute(child,normalizedRoute)}else this.recordRoute(normalizedRoute)}strictPath(path){return this._options.strict?path:path.toLowerCase()}recordRoute(route){if(route.name){if(route.name.startsWith("/")&&(route.name=route.name.replace(/^\//,""),console.warn(`[Vitarx.Router][WARN]:命名路由(name)不要以/开头: ${route.name},因为内部需要使用/区分path、name`)),this._namedRoutes.has(route.name))throw new Error(`[Vitarx.Router][ERROR]:检测到重复的路由名称(name): ${route.name}`);this._namedRoutes.set(route.name,route)}const path=this.strictPath(route.path);if(this._pathRoutes.has(path))throw new Error(`[Vitarx.Router][ERROR]:检测到重复的路由路径(path): ${route.path}`);this._pathRoutes.set(path,route),isVariablePath(route.path)&&this.recordDynamicRoute(route)}recordDynamicRoute(route){const{regex,length,optional}=createDynamicPattern(route.path,route.pattern,this.options.strict,this.options.pattern),addToLengthMap=len=>{this._dynamicRoutes.has(len)||this._dynamicRoutes.set(len,[]),this._dynamicRoutes.get(len).push({regex,route})};if(addToLengthMap(length),optional>0)for(let i=1;i<=optional;i++)addToLengthMap(length-i)}}const __stringValueKeys=["path","hash","index","fullPath"];function patchUpdate(location,newLocation){diffUpdateArrays(location.matched,newLocation.matched),diffUpdateObjects(location.params,newLocation.params),diffUpdateObjects(location.query,newLocation.query),diffUpdateObjects(location.meta,newLocation.meta);for(const key of __stringValueKeys)location[key]!==newLocation[key]&&(location[key]=newLocation[key])}function diffUpdateArrays(a,b){for(let i=0;i<b.length;i++)a[i]!==b[i]&&(a[i]=b[i]);a.length>b.length&&(a.length=b.length)}function diffUpdateObjects(a,b){const aKeys=Object.keys(a),bKeys=Object.keys(b);for(const key of bKeys)Object.prototype.hasOwnProperty.call(b,key)&&(a[key]=b[key]);for(const key in aKeys)key in b||delete a[key]}const _RouterCore=class _RouterCore extends RouterRegistry{constructor(options){if(_RouterCore._instance)throw new Error("[Vitarx.Router.constructor]:路由器实例已存在,不能创建多个实例");super(options);__publicField(this,"_currentTaskId",null);__publicField(this,"_taskCounter",0);__publicField(this,"_pendingReplace",null);__publicField(this,"_pendingPush",null);__publicField(this,"_scrollBehaviorHandler");__publicField(this,"_currentRouteLocation");__publicField(this,"_isBrowser",typeof window<"u"&&typeof window.document<"u");__publicField(this,"_scrollBehavior","auto");this._currentRouteLocation=vitarx.reactive({index:this._options.base,path:this._options.base,hash:"",fullPath:this._options.base,params:{},query:{},matched:vitarx.shallowReactive([]),meta:vitarx.markRaw({})})}static get instance(){if(!_RouterCore._instance)throw new Error("[Vitarx.Router.instance]:路由器实例未初始化");return _RouterCore._instance}get isBrowser(){return this._isBrowser}get scrollBehavior(){return this._scrollBehavior}get options(){return this._options}get mode(){return this._options.mode}get initialized(){return _RouterCore._instance!==void 0}get currentRouteLocation(){return this._currentRouteLocation}get isPendingNavigation(){return!!(this._pendingReplace||this._pendingPush)}get pendingReplaceData(){return this._pendingReplace}get pendingPushData(){return this._pendingPush}static routeView(route,name){const widgetMap=route.widget;if(!widgetMap||!(name in widgetMap))return;const widget=widgetMap[name];return isLazyLoad(widget)?vitarx.createElement(vitarx.LazyWidget,{children:widget,key:route.path}):vitarx.createElement(widget)}back(){return this.go(-1)}forward(){return this.go(1)}replace(target){return typeof target=="string"?this.navigate({index:target,isReplace:!0}):(target.isReplace=!0,this.navigate(target))}push(target){return typeof target=="string"?this.navigate({index:target,isReplace:!1}):(target.isReplace=!1,this.navigate(target))}initialize(){return _RouterCore._instance?this:(this.setupRoutes(this._options.routes),typeof this.options.scrollBehavior=="function"?this._scrollBehaviorHandler=this.options.scrollBehavior:this._scrollBehavior=this.options.scrollBehavior,this.initializeRouter(),_RouterCore._instance=this,this)}scrollTo(scrollTarget){if(!(this.isBrowser||!scrollTarget||typeof scrollTarget!="object")){if("el"in scrollTarget){const{el,...rest}=scrollTarget,element=typeof el=="string"?document.querySelector(el):el;element&&element instanceof Element?element.scrollIntoView?element.scrollIntoView({behavior:this.scrollBehavior,...rest}):window.scrollTo({behavior:this.scrollBehavior,top:element.getBoundingClientRect().top+window.scrollY,left:element.getBoundingClientRect().left+window.scrollX}):console.warn(`[Vitarx.Router.scrollTo][WARN]:元素${el}不存在,无法完成滚动到目标元素操作`);return}window.scrollTo({behavior:this.scrollBehavior,...scrollTarget})}}createRouteLocation(target){if(isRouteLocationTypeObject(target))return target;const route=this.findRoute(target),{index,query={},params={},hash=""}=target;let path;const matched=[];if(route){let suffix=getPathSuffix(index);this.suffix&&suffix&&!route.path.endsWith(suffix)?path=mergePathParams(route.path+suffix,params):path=mergePathParams(route.path,params);let parent=this.findParentRoute(route);for(;parent;)parent.widget&&matched.unshift(parent),parent=this.findParentRoute(parent);matched.push(route)}else path=formatPath(index);const meta=(route==null?void 0:route.meta)||{},hashStr=formatHash(hash),fullPath=this.makeFullPath(path,query,hashStr);return{index,path,hash:hashStr,fullPath,params,query,matched,meta}}navigate(target){const taskId=++this._taskCounter;this._currentTaskId=taskId;const isCurrentTask=()=>this._currentTaskId===taskId,from=vitarx.deepClone(this.currentRouteLocation),performNavigation=async(_target,isRedirect)=>{const to=this.createRouteLocation(_target),matched=to.matched.at(-1);if(matched!=null&&matched.redirect){if(typeof matched.redirect=="string")return performNavigation({index:matched.redirect},!0);if(typeof matched.redirect=="function")return performNavigation(matched.redirect.call(this,to),!0)}else to.matched.length===1&&matched.children.length&&to.matched.push(matched.children[0]);const createNavigateResult=(overrides={})=>({from,to,status:NavigateStatus.success,message:"导航成功",redirectFrom:isRedirect?target:void 0,...overrides});if(this.isSameNavigate(to,this.currentRouteLocation))return createNavigateResult({status:NavigateStatus.duplicated,message:"导航到相同的路由,被系统阻止!"});try{const result=await this.onBeforeEach(to,this.currentRouteLocation);return result===!1?createNavigateResult({status:NavigateStatus.aborted,message:"导航被前置守卫钩子阻止"}):isCurrentTask()?typeof result=="object"&&result.index!==_target.index?(result.isReplace??(result.isReplace=!1),performNavigation(result,!0)):to.matched.length?(_target.isReplace?(this._pendingReplace=to,this.replaceHistory(to)):(this._pendingPush=to,this.pushHistory(to)),createNavigateResult()):createNavigateResult({status:NavigateStatus.not_matched,message:`未匹配到任何路由规则,被系统阻止!请检测目标索引(${to.index})是否已注册路由。`}):createNavigateResult({status:NavigateStatus.cancelled,message:"已被新的导航请求替代,取消此次导航!"})}catch(error){return console.error("[Vitarx.Router.navigate][ERROR]:导航时捕获到了异常",error),createNavigateResult({status:NavigateStatus.exception,message:"导航时捕获到了异常",error})}};return performNavigation(target,!1)}_completeViewRender(){}completeNavigation(data,savedPosition){const from=this._currentRouteLocation;if(this._completeViewRender=()=>{this.onScrollBehavior(this.currentRouteLocation,from,savedPosition).then(),this.onAfterEach(this.currentRouteLocation,from)},data)this.updateRouteLocation(data);else if(this._pendingReplace)this.updateRouteLocation(this._pendingReplace);else if(this._pendingPush)this.updateRouteLocation(this._pendingPush);else throw new Error("[Vitarx.Router.completeNavigation][ERROR]:没有处于等待状态的导航请求。");this._pendingReplace=null,this._pendingPush=null}updateQuery(query){vitarx.isDeepEqual(this._currentRouteLocation.query,query)||(this._currentRouteLocation.query=query,this._currentRouteLocation.fullPath=this.makeFullPath(this._currentRouteLocation.path,query,this._currentRouteLocation.hash))}updateHash(hash){typeof hash!="string"&&console.warn(`[Vitarx.Router.updateHash][WARN]:hash值只能是字符串类型,给定${hash}`);const newHash=formatHash(hash);newHash!==this._currentRouteLocation.hash&&(this._currentRouteLocation.hash=newHash,this._currentRouteLocation.fullPath=this.makeFullPath(this._currentRouteLocation.path,this._currentRouteLocation.query,newHash))}makeFullPath(path,query,hash){return hash&&!hash.startsWith("#")&&(hash=`#${hash}`),typeof query=="object"&&(query=objectToQueryString(query)),this.mode==="hash"?formatPath(`${this.basePath}/${query}#${path}${hash}`):formatPath(`${this.basePath}${path}${query}${hash}`)}isSameNavigate(to,from){return vitarx.isDeepEqual(to,from)}onBeforeEach(to,from){var _a;const matched=to.matched.at(-1);return matched&&"beforeEnter"in matched&&typeof matched.beforeEnter=="function"?matched.beforeEnter.call(this,to,from):(_a=this._options.beforeEach)==null?void 0:_a.call(this,to,from)}onAfterEach(to,from){var _a;const matched=to.matched.at(-1);return matched&&"afterEnter"in matched&&typeof matched.afterEnter=="function"?matched.afterEnter.call(this,to,from):(_a=this._options.afterEach)==null?void 0:_a.call(this,to,from)}updateRouteLocation(newLocation){patchUpdate(this._currentRouteLocation,newLocation)}async onScrollBehavior(to,from,savedPosition){try{if(this._scrollBehaviorHandler){const scrollTarget=await this._scrollBehaviorHandler(to,from,savedPosition);scrollTarget&&this.scrollTo(scrollTarget)}else this.scrollTo(savedPosition)}catch(e){console.error("[Vitarx.Router.onScrollBehavior]['ERROR']:处理滚动行为时捕获到了异常",e)}}};__publicField(_RouterCore,"_instance");let RouterCore=_RouterCore;class RouterHistory extends RouterCore{constructor(options){["path","hash"].includes(options.mode)||(options.mode="hash"),super(options),options.mode==="hash"&&this.ensureHash()}get currentRouteTarget(){return urlToRouteTarget(window.location,this.mode,this.basePath)}get webHistory(){return window.history}go(delta){this.webHistory.go(delta)}initializeRouter(){window.addEventListener("popstate",this.onPopState.bind(this)),this.replace(this.currentRouteTarget).then(res=>{res.status!==NavigateStatus.success&&console.warn(`[VitarxRouter.initializeRouter]:路由初始化匹配失败,${res.message}`)})}pushHistory(data){this.saveCurrentScrollPosition(),this.webHistory.pushState(this.createState(data),"",data.fullPath),this.completeNavigation(data)}replaceHistory(data){var _a;const scrollPosition=(_a=this.webHistory.state)==null?void 0:_a.scrollPosition;this.webHistory.replaceState(this.createState(data),"",data.fullPath),this.completeNavigation(data,scrollPosition)}saveCurrentScrollPosition(){const scrollPosition={left:window.scrollX,top:window.scrollY,behavior:this.scrollBehavior};this.webHistory.replaceState({...this.webHistory.state,scrollPosition},"",window.location.href)}createState(data,hash,query){const{matched,...state}=data;return typeof hash=="string"&&(state.hash=hash),typeof query=="object"&&(state.query=query),JSON.parse(JSON.stringify(state))}onPopState(event){var _a;let newTarget;(_a=event.state)!=null&&_a.index?newTarget={index:event.state.index,hash:event.state.hash,query:event.state.query}:newTarget=this.currentRouteTarget,this.replace(newTarget).then(res=>{if(!res.redirectFrom&&this.mode==="hash"&&res.status!==NavigateStatus.success)if(res.status===NavigateStatus.not_matched){if(res.to.index.startsWith("/")){const anchorId=res.to.index.slice(1),element=window.document.getElementById(anchorId);element&&element.scrollIntoView({behavior:this.scrollBehavior}),this.updateHash(`#${anchorId}`),this.webHistory.replaceState(this.createState(this.currentRouteLocation),"",this.currentRouteLocation.fullPath)}}else res.status===NavigateStatus.duplicated&&this.webHistory.replaceState(this.createState(this.currentRouteLocation),"",this.currentRouteLocation.fullPath)})}ensureHash(){const{pathname,search,hash}=window.location;if(!hash){const path=`${this.basePath}${search}#${pathname}`;window.location.replace(path)}}}class RouterMemory extends RouterCore{constructor(options){super(options);__publicField(this,"_history",[]);__publicField(this,"_pendingGo",null);__publicField(this,"_currentIndex",0);options.mode="memory"}get currentIndex(){return this._currentIndex}go(delta){if(!delta)return;const currentIndex=this.currentIndex,targetIndex=Math.max(0,Math.min(this._history.length-1,currentIndex+delta));if(targetIndex===currentIndex)return;const target=this._history[targetIndex];this._pendingGo=targetIndex,this.navigate(target).then(res=>{res.status!==NavigateStatus.success&&(this._pendingGo=null)})}initializeRouter(){this._history.push(this.currentRouteLocation)}pushHistory(data){this._updateHistory(data,!1)}replaceHistory(data){this._updateHistory(data,!0)}_updateHistory(data,isReplace){let newIndex;if(this._pendingGo!==null)this._history[this._pendingGo]=data,newIndex=this._pendingGo;else if(isReplace)this._history[this.currentIndex]=data,newIndex=this.currentIndex;else{const nextIndex=this.currentIndex+1;nextIndex<this._history.length?(this._history[nextIndex]=data,this._history.length=nextIndex+1,newIndex=nextIndex):(this._history.push(data),newIndex=this._history.length-1)}this._currentIndex=newIndex,this.completeNavigation(data),this._pendingGo=null}}function defineRoutes(...routes){return routes}function defineRoute(route){return route}function createRouter(options){let router;return!(window!=null&&window.location)&&options.mode!=="memory"?(console.warn("当前环境非浏览器端,强制使用内存模式路由"),options.mode="memory",new RouterMemory(options).initialize()):(options.mode==="memory"?router=new RouterMemory(options):router=new RouterHistory(options),router.initialize())}function useRouter(){return RouterCore.instance}function useRoute(){return RouterCore.instance.currentRouteLocation}function lazy(lazyLoader){return Object.defineProperty(lazyLoader,LAZY_LOADER_SYMBOL,{value:!0}),lazyLoader}const INDEX_SYMBOL=Symbol("RouterViewCounter");class RouterView extends vitarx.Widget{constructor(props){super(props);__publicField(this,"_$index");__publicField(this,"_$currentRoute");__publicField(this,"_$currentElement",vitarx.shallowRef());const parentIndex=vitarx.inject(INDEX_SYMBOL,-1,this);this._$index=parentIndex+1,vitarx.provide(INDEX_SYMBOL,this._$index,this),this._$currentRoute=this.matchedRoute,this._$currentRoute&&(this._$currentElement.value=RouterCore.routeView(this._$currentRoute,this.name)),vitarx.watch(this.location.matched,(_c,o)=>{const newRoute=o[this.index];newRoute!==this._$currentRoute&&(this._$currentRoute=newRoute,this._$currentElement.value=newRoute?RouterCore.routeView(newRoute,this.name):void 0)})}get index(){return this._$index}get isLastView(){return this.index===this.location.matched.length-1&&this.name==="default"}get name(){return this.props.name||"default"}get matchedRoute(){return this.location.matched[this.index]}get currentElement(){return this._$currentElement.value}get currentWidget(){var _a;return(_a=this._$currentElement.value)==null?void 0:_a.type}get location(){return RouterCore.instance.currentRouteLocation}onMounted(){this.completeViewRender()}onUpdated(){this.completeViewRender()}build(){return this.currentElement||vitarx.createElement(vitarx.Fragment)}completeViewRender(){this.isLastView&&RouterCore.instance._completeViewRender()}}class RouterLink extends vitarx.Widget{constructor(props){super(props);__publicField(this,"target");__publicField(this,"location");__publicField(this,"active");__publicField(this,"htmlProps");this.target=new vitarx.Computed(()=>vitarx.markRaw(vitarx.isString(props.to)?{index:props.to}:props.to)),this.location=new vitarx.Computed(()=>{const location=RouterCore.instance.createRouteLocation(this.target.value);return location.matched.length||console.warn(`[Vitarx.RouterLink][WARN]:索引:${this.target.value.index},未匹配到任何有效的路由线路,请检查to属性是否配置正确!`),vitarx.markRaw(location)}),props.active!==void 0&&props.active!=="none"&&(this.active=new vitarx.Computed(()=>this.target.value.index.startsWith("/")?props.active==="obscure"?RouterCore.instance.currentRouteLocation.fullPath.startsWith(this.location.value.path):this.location.value.path===RouterCore.instance.currentRouteLocation.path:!!RouterCore.instance.currentRouteLocation.matched.find(route=>route.name===this.target.value.index))),this.htmlProps=new vitarx.Computed(()=>{const props2={href:this.href,onClick:e=>this.navigate(e),children:this.children,style:this.props.style,class:this.props.class};return this.isActive&&(props2["aria-current"]="page"),this.isDisabled&&(props2.disabled=!0),props2})}get isActive(){var _a;return((_a=this.active)==null?void 0:_a.value)&&!this.isDisabled}get isDisabled(){return this.props.disabled??!1}get href(){return this.location.value.fullPath}navigate(e){e.stopPropagation(),e.preventDefault(),!this.isDisabled&&RouterCore.instance.navigate(this.location.value).then()}build(){return vitarx.createElement("a",this.htmlProps.value)}}exports2.HistoryRouter=RouterHistory,exports2.MemoryRouter=RouterMemory,exports2.NavigateStatus=NavigateStatus,exports2.Router=RouterCore,exports2.RouterLink=RouterLink,exports2.RouterView=RouterView,exports2.createRouter=createRouter,exports2.defineRoute=defineRoute,exports2.defineRoutes=defineRoutes,exports2.lazy=lazy,exports2.useRoute=useRoute,exports2.useRouter=useRouter,Object.defineProperty(exports2,Symbol.toStringTag,{value:"Module"})});
1
+ (function(global,factory){typeof exports=="object"&&typeof module<"u"?factory(exports,require("vitarx")):typeof define=="function"&&define.amd?define(["exports","vitarx"],factory):(global=typeof globalThis<"u"?globalThis:global||self,factory(global.VitarxRouter={},global.Vitarx))})(this,function(exports2,vitarx){"use strict";var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value);var NavigateStatus=(NavigateStatus2=>(NavigateStatus2[NavigateStatus2.success=0]="success",NavigateStatus2[NavigateStatus2.aborted=1]="aborted",NavigateStatus2[NavigateStatus2.cancelled=2]="cancelled",NavigateStatus2[NavigateStatus2.duplicated=3]="duplicated",NavigateStatus2[NavigateStatus2.not_matched=4]="not_matched",NavigateStatus2[NavigateStatus2.exception=5]="exception",NavigateStatus2))(NavigateStatus||{});function validateInjectPropsRule(rule){return typeof rule=="boolean"||typeof rule=="function"||typeof rule=="object"&&rule!==null}function validateInjectProps(route){if(route.widget===void 0)return;if(!("injectProps"in route)){route.injectProps=generateDefaultInjectProps(route,!0);return}const injectProps=route.injectProps;if(typeof injectProps=="object")isDefaultInjectProps(injectProps)?validateInjectPropsForDefault(route,injectProps):validateInjectPropsForNamed(route,injectProps);else if(validateInjectPropsRule(injectProps))route.injectProps=generateDefaultInjectProps(route,injectProps);else throw new TypeError(`[Vitarx.Router][TYPE_ERROR]:${route.path} 路由线路配置的 injectProps 类型有误,它可以是布尔值、函数,亦或是一个{string:any}类型的对象。`)}function isDefaultInjectProps(injectProps){return Object.keys(injectProps).length===1&&"default"in injectProps}function validateInjectPropsForDefault(route,injectProps){if(!validateInjectPropsRule(injectProps.default))throw new TypeError(`[Vitarx.Router][TYPE_ERROR]:${route.path} 路由线路配置的 injectProps.default 类型有误,它可以是布尔值、函数,亦或是一个{string:any}类型的对象。`)}function validateInjectPropsForNamed(route,injectProps){for(const key of Object.keys(route.widget))if(key in injectProps){if(!validateInjectPropsRule(injectProps[key]))throw new TypeError(`[Vitarx.Router][TYPE_ERROR]:${route.path} 路由线路配置的 injectProps.${key} 类型有误,它可以是布尔值、函数,亦或是一个{string:any}类型的对象。`)}else injectProps[key]=!0}function generateDefaultInjectProps(route,rule){const injectProps={};for(const key of Object.keys(route.widget))injectProps[key]=rule;return injectProps}function validateWidget(route){if(!("widget"in route)){if(route.children.length===0)throw new TypeError(`[Vitarx.Router][ERROR]:${route.path} 路由线路配置的 widget 属性缺失,且没有children,它是一个不规范的路由。`);route.widget=void 0;return}if(typeof route.widget=="function")route.widget={default:route.widget};else if(typeof route.widget=="object"&&route.widget!==null){if(Object.keys(route.widget).length===0)route.widget=void 0;else for(const k in route.widget)if(typeof route.widget[k]!="function")throw new TypeError(`[Vitarx.Router][ERROR]:${route.path} 路由线路配置的 widget 命名视图 ${k} 类型有误,它可以是函数式小部件、类小部件,亦或是一个惰性加载器。`)}else throw new TypeError(`[Vitarx.Router][ERROR]:${route.path} 路由线路配置的 widget 类型有误,它可以是函数式小部件、类小部件,亦或是一个惰性加载器。`)}const LAZY_LOADER_SYMBOL=Symbol("LazyLoader");function isVariablePath(path){return/\{[^}]+}/.test(path)}function optionalVariableCount(path){const pathWithoutSpaces=path.replace(/\s+/g,""),regex=/\{[\w-]+\?}/g,matches=pathWithoutSpaces.match(regex);return matches?matches.length:0}function isRouteGroup(route){return"children"in route&&route.children!==void 0&&route.children.length>0}function createDynamicPattern(path,pattern,strict,defaultPattern){let optional=0;const processVariable=(varName,isOptional)=>{const regex=pattern[varName];if(regex?regex instanceof RegExp||(console.warn(`[Vitarx.Router][WARN]:${path} 动态路径${varName}变量的自定义正则表达式必须是 RegExp 类型`),pattern[varName]=defaultPattern):pattern[varName]=defaultPattern,isOptional)return optional++,`(?:(${pattern[varName].source}))?`;if(optional)throw new Error(`[Vitarx.Router][ERROR]:动态路径 ${path} 中,可选变量 ${varName} 后不能存在任何必填变量`);return`(${pattern[varName].source})`},processedPath=path.replace(/{([^}?]+)\?}/g,(_,varName)=>processVariable(varName,!0)).replace(/{([^}]+)}/g,(_,varName)=>processVariable(varName,!1)).replace(/\//g,"\\/").replace(/\/?$/,"/?"),flags=strict?"":"i",segments=path.replace(/^\/|\/$/g,"").split("/").length;return{regex:new RegExp(`^${processedPath}$`,flags),length:segments,optional}}function formatPath(path){return path=`/${path}`.replace(/\s+/g,"").replace(/\/+/g,"/"),path.length?path==="/"||path==="/#/"?path:path.replace(/\/$/,""):"/"}function mergePathParams(path,params){if(!isVariablePath(path))return path;const oldPath=path;return path=path.replace(/{([^}]+)\?*}/g,(_match,paramName)=>{const isOptional=paramName.endsWith("?");if(isOptional&&(paramName=paramName.slice(0,-1)),params[paramName]===void 0){if(isOptional)return"";throw new TypeError(`[Vitarx.Router.mergePathParams] 访问路由${oldPath}时缺少参数:${paramName}`)}return String(params[paramName]).replace(/\s+/g,"_")}),formatPath(path)}function isLazyLoad(lazyLoader){return typeof lazyLoader=="function"&&lazyLoader[LAZY_LOADER_SYMBOL]}function formatHash(hash,addHashPrefix){return typeof hash!="string"||!hash?"":(hash=hash.trim(),hash.startsWith("#")?hash:`#${hash}`)}function queryStringToObject(queryString){queryString=decodeURIComponent(queryString);const params=new URLSearchParams(queryString.startsWith("?")?queryString.substring(1):queryString),obj={};return params.forEach((value,key)=>obj[key]=value),obj}function objectToQueryString(obj){const queryString=new URLSearchParams(obj).toString();return queryString?`?${queryString}`:""}function urlToRouteTarget(url,mode,base){let path=decodeURIComponent(url.pathname),hash=decodeURIComponent(url.hash),query=queryStringToObject(url.search);if(path=formatPath(path.startsWith(base)?path.slice(base.length):path),mode==="hash"&&hash.includes("#/")){const hashPart=hash.slice(1),[fullPath,anchor]=hashPart.split("#");path=formatPath(fullPath||"/"),hash=anchor?`#${anchor}`:""}return{index:path,hash,query}}function splitPathAndSuffix(path){const suffix=getPathSuffix(path);return suffix&&(path=path.slice(0,-suffix.length)),{path,suffix:suffix.substring(1)}}function getPathSuffix(path){const match=path.match(/^(.*?)(\.[a-zA-Z0-9]+)$/);return match?match[2]:""}function isRouteLocationTypeObject(obj){if(typeof obj!="object"||obj===null)return!1;const keys=["index","fullPath","path","hash","params","query","matched","meta"];for(const key of keys)if(!Object.prototype.hasOwnProperty.call(obj,key))return!1;return!0}function normalizeRoute(route,group,suffix){if(route.meta=route.meta||{},route.pattern=route.pattern||{},route.children=route.children||[],!Array.isArray(route.children))throw new TypeError(`[Vitarx.Router][TYPE_ERROR]:${route.path} 路由线路配置 children 类型错误,它必须是数组类型。`);if(!route.path.trim())throw new TypeError("[Vitarx.Router][TYPE_ERROR]:路由线路配置 path 不能为空");return route.path=formatPath(group?`${group.path}/${route.path}`:route.path),validateWidget(route),validateInjectProps(route),route.suffix??(route.suffix=(group==null?void 0:group.suffix)??suffix),route.afterEnter??(route.afterEnter=group==null?void 0:group.afterEnter),route.beforeEnter??(route.beforeEnter=group==null?void 0:group.beforeEnter),route}function validateSuffix(suffix,allowSuffix,inputPath,routePath){return allowSuffix==="*"?!0:allowSuffix===!1?inputPath===routePath:Array.isArray(allowSuffix)?allowSuffix.includes(suffix):suffix===allowSuffix}class RouterRegistry{constructor(options){__publicField(this,"_options");__publicField(this,"_namedRoutes",new Map);__publicField(this,"_dynamicRoutes",new Map);__publicField(this,"_pathRoutes",new Map);__publicField(this,"_parentRoute",new WeakMap);this._options={base:"/",strict:!1,mode:"path",scrollBehavior:"smooth",suffix:"*",pattern:/[\w.]+/,...options},this._options.base=`/${this._options.base.replace(/^\/+|\/+$/g,"")}`}get options(){return this._options}get mode(){return this._options.mode}get pathRoutes(){return this._pathRoutes}get namedRoutes(){return this._namedRoutes}get dynamicRoutes(){return this._dynamicRoutes}get routes(){return this._options.routes}get basePath(){return this._options.base}get suffix(){return this._options.suffix}removeRoute(index,isRemoveFromRoutes=!0){const deleteRoute=this.findRoute(index);if(deleteRoute){if(isRouteGroup(deleteRoute))for(const child of deleteRoute.children)this.removeRoute(child.path,!1);this._pathRoutes.delete(deleteRoute.path),deleteRoute.name&&this._namedRoutes.delete(deleteRoute.name),this.removeDynamicRoute(deleteRoute.path),isRemoveFromRoutes&&this.removedFromRoutes(deleteRoute)}}addRoute(route,parent){if(parent){const parentRoute=this.findRoute(parent);if(!parentRoute)throw new Error(`[Vitarx.Router.addRoute][ERROR]:父路由${parent}不存在`);this.registerRoute(route,parentRoute)}else this.registerRoute(route),this._options.routes.push(route)}findRoute(target){const isRouterTarget=typeof target=="object",index=isRouterTarget?target.index:target;if(typeof index!="string")throw new TypeError(`[Vitarx.Router.getRoute][ERROR]:路由索引${target}类型错误,必须给定字符串类型`);if(index.startsWith("/")){const matched=this.matchRoute(index);return matched?(matched.params&&isRouterTarget&&(target.params=Object.assign(target.params||{},matched.params)),matched.route):void 0}return this.findNamedRoute(index)}findNamedRoute(name){return this._namedRoutes.get(name)}findParentRoute(route){return this._parentRoute.get(route)}matchRoute(path){let formattedPath=formatPath(path);this._options.strict||(formattedPath=formattedPath.toLowerCase());try{const{path:shortPath,suffix}=splitPathAndSuffix(formattedPath),staticRoute=this._pathRoutes.get(shortPath);if(staticRoute&&validateSuffix(suffix,staticRoute.suffix,formattedPath,staticRoute.path))return{route:staticRoute,params:void 0};const segmentCount=shortPath.split("/").filter(Boolean).length,candidates=this._dynamicRoutes.get(segmentCount);if(candidates){const normalizedPath=`${shortPath}/`,regexCache=new Map;for(const{regex,route}of candidates){const match=(regexCache.get(regex.source)||regex).exec(normalizedPath);if(!match)continue;const params={},keys=Object.keys(route.pattern);for(let i=0;i<keys.length;i++)params[keys[i]]=match[i+1];if(validateSuffix(suffix,route.suffix,formattedPath,formattedPath))return{route,params}}}if(!suffix&&!shortPath.endsWith("/index")){const indexRoute=this._pathRoutes.get(`${shortPath==="/"?"":shortPath}/index`);if(indexRoute&&validateSuffix(suffix,indexRoute.suffix,formattedPath,indexRoute.path))return{route:indexRoute,params:void 0}}else if(shortPath==="/index"){const indexRoute=this._pathRoutes.get("/");if(indexRoute&&validateSuffix(suffix,indexRoute.suffix,formattedPath,indexRoute.path))return{route:indexRoute,params:void 0}}}catch(error){console.error("Error in matchRoute:",error);return}}setupRoutes(routes){for(const route of routes)this.registerRoute(route)}removedFromRoutes(route){const parent=this.findParentRoute(route);if(parent!=null&&parent.children){const index=parent.children.indexOf(route);index!==-1&&parent.children.splice(index,1)}else{const index=this._options.routes.indexOf(route);index!==-1&&this._options.routes.splice(index,1)}}removeDynamicRoute(path){if(!isVariablePath(path))return;const length=path.split("/").filter(Boolean).length,removeRouteFromRecords=key=>{const records=this._dynamicRoutes.get(key);if(records){for(let i=0;i<records.length;i++)if(records[i].route.path===path){records.splice(i,1);break}}};removeRouteFromRecords(length);const count=optionalVariableCount(path);if(count>0)for(let i=1;i<=count;i++)removeRouteFromRecords(length-i)}registerRoute(route,group){const normalizedRoute=normalizeRoute(route,group,this.suffix);if(group&&this._parentRoute.set(normalizedRoute,group),isRouteGroup(normalizedRoute)){this.recordRoute(normalizedRoute);for(const child of normalizedRoute.children)this.registerRoute(child,normalizedRoute);normalizedRoute.redirect||(normalizedRoute.redirect=function(to){var _a;let first=normalizedRoute.children[0];for(;first;){if(first.redirect)return typeof first.redirect=="function"?first.redirect.call(this,to):first.redirect;if(first.widget)return{index:first.path};first=(_a=first.children)==null?void 0:_a[0]}console.error(`[Vitarx.Router][ERROR]:${normalizedRoute.path} 分组路由在没有配置重定向的情况下,它的第一个子路由必须具有widget或redirect,否则无法匹配视图`,normalizedRoute)})}else this.recordRoute(normalizedRoute)}strictPath(path){return this._options.strict?path:path.toLowerCase()}recordRoute(route){if(route.name){if(route.name.startsWith("/")&&(route.name=route.name.replace(/^\//,""),console.warn(`[Vitarx.Router][WARN]:命名路由(name)不要以/开头: ${route.name},因为内部需要使用/区分path、name`)),this._namedRoutes.has(route.name))throw new Error(`[Vitarx.Router][ERROR]:检测到重复的路由名称(name): ${route.name}`);this._namedRoutes.set(route.name,route)}const path=this.strictPath(route.path);if(this._pathRoutes.has(path))throw new Error(`[Vitarx.Router][ERROR]:检测到重复的路由路径(path): ${route.path}`);this._pathRoutes.set(path,route),isVariablePath(route.path)&&this.recordDynamicRoute(route)}recordDynamicRoute(route){const{regex,length,optional}=createDynamicPattern(route.path,route.pattern,this.options.strict,this.options.pattern),addToLengthMap=len=>{this._dynamicRoutes.has(len)||this._dynamicRoutes.set(len,[]),this._dynamicRoutes.get(len).push({regex,route})};if(addToLengthMap(length),optional>0)for(let i=1;i<=optional;i++)addToLengthMap(length-i)}}const __stringValueKeys=["path","hash","index","fullPath"];function patchUpdate(location,newLocation){diffUpdateArrays(location.matched,newLocation.matched),diffUpdateObjects(location.params,newLocation.params),diffUpdateObjects(location.query,newLocation.query),diffUpdateObjects(location.meta,newLocation.meta);for(const key of __stringValueKeys)location[key]!==newLocation[key]&&(location[key]=newLocation[key])}function diffUpdateArrays(a,b){for(let i=0;i<b.length;i++)a[i]!==b[i]&&(a[i]=b[i]);a.length>b.length&&(a.length=b.length)}function diffUpdateObjects(a,b){const aKeys=Object.keys(a),bKeys=Object.keys(b);for(const key of bKeys)Object.prototype.hasOwnProperty.call(b,key)&&(a[key]=b[key]);for(const key in aKeys)key in b||delete a[key]}const _RouterCore=class _RouterCore extends RouterRegistry{constructor(options){if(_RouterCore._instance)throw new Error("[Vitarx.Router.constructor]:路由器实例已存在,不能创建多个实例");super(options);__publicField(this,"_currentTaskId",null);__publicField(this,"_taskCounter",0);__publicField(this,"_pendingReplace",null);__publicField(this,"_pendingPush",null);__publicField(this,"_scrollBehaviorHandler");__publicField(this,"_currentRouteLocation");__publicField(this,"_isBrowser",typeof window<"u"&&typeof window.document<"u");__publicField(this,"_scrollBehavior","auto");this._currentRouteLocation=vitarx.reactive({index:this._options.base,path:this._options.base,hash:"",fullPath:this._options.base,params:{},query:{},matched:vitarx.shallowReactive([]),meta:vitarx.markRaw({})})}static get instance(){if(!_RouterCore._instance)throw new Error("[Vitarx.Router.instance]:路由器实例未初始化");return _RouterCore._instance}get isBrowser(){return this._isBrowser}get scrollBehavior(){return this._scrollBehavior}get options(){return this._options}get mode(){return this._options.mode}get initialized(){return _RouterCore._instance!==void 0}get currentRouteLocation(){return this._currentRouteLocation}get isPendingNavigation(){return!!(this._pendingReplace||this._pendingPush)}get pendingReplaceData(){return this._pendingReplace}get pendingPushData(){return this._pendingPush}static routeView(route,name){const widgetMap=route.widget;if(!widgetMap||!(name in widgetMap))return;const widget=widgetMap[name];return isLazyLoad(widget)?vitarx.createElement(vitarx.LazyWidget,{children:widget,key:route.path}):vitarx.createElement(widget)}back(){return this.go(-1)}forward(){return this.go(1)}replace(target){return typeof target=="string"?this.navigate({index:target,isReplace:!0}):(target.isReplace=!0,this.navigate(target))}push(target){return typeof target=="string"?this.navigate({index:target,isReplace:!1}):(target.isReplace=!1,this.navigate(target))}initialize(){return _RouterCore._instance?this:(this.setupRoutes(this._options.routes),typeof this.options.scrollBehavior=="function"?this._scrollBehaviorHandler=this.options.scrollBehavior:this._scrollBehavior=this.options.scrollBehavior,this.initializeRouter(),_RouterCore._instance=this,this)}scrollTo(scrollTarget){if(!(this.isBrowser||!scrollTarget||typeof scrollTarget!="object")){if("el"in scrollTarget){const{el,...rest}=scrollTarget,element=typeof el=="string"?document.querySelector(el):el;element&&element instanceof Element?element.scrollIntoView?element.scrollIntoView({behavior:this.scrollBehavior,...rest}):window.scrollTo({behavior:this.scrollBehavior,top:element.getBoundingClientRect().top+window.scrollY,left:element.getBoundingClientRect().left+window.scrollX}):console.warn(`[Vitarx.Router.scrollTo][WARN]:元素${el}不存在,无法完成滚动到目标元素操作`);return}window.scrollTo({behavior:this.scrollBehavior,...scrollTarget})}}createRouteLocation(target){if(isRouteLocationTypeObject(target))return target;const route=this.findRoute(target),{index,query={},params={},hash=""}=target;let path;const matched=[];if(route){let suffix=getPathSuffix(index);this.suffix&&suffix&&!route.path.endsWith(suffix)?path=mergePathParams(route.path+suffix,params):path=mergePathParams(route.path,params);let parent=this.findParentRoute(route);for(;parent;)parent.widget&&matched.unshift(parent),parent=this.findParentRoute(parent);matched.push(route)}else path=formatPath(index);const meta=(route==null?void 0:route.meta)||{},hashStr=formatHash(hash),fullPath=this.makeFullPath(path,query,hashStr);return{index,path,hash:hashStr,fullPath,params,query,matched,meta}}navigate(target){const taskId=++this._taskCounter;this._currentTaskId=taskId;const isCurrentTask=()=>this._currentTaskId===taskId,from=vitarx.deepClone(this.currentRouteLocation),performNavigation=async(_target,isRedirect)=>{const to=this.createRouteLocation(_target),matched=to.matched.at(-1);if(matched!=null&&matched.redirect){let redirectTarget;if(typeof matched.redirect=="object"&&matched.redirect.index)redirectTarget=matched.redirect;else if(typeof matched.redirect=="string")redirectTarget={index:matched.redirect};else if(typeof matched.redirect=="function"){const redirectHandleResult=matched.redirect.call(this,to);vitarx.isObject(redirectHandleResult)&&(redirectTarget=redirectHandleResult)}if(redirectTarget!=null&&redirectTarget.index)return performNavigation(redirectTarget,!0)}const createNavigateResult=(overrides={})=>({from,to,status:NavigateStatus.success,message:"导航成功",redirectFrom:isRedirect?target:void 0,...overrides});if(this.isSameNavigate(to,this.currentRouteLocation))return createNavigateResult({status:NavigateStatus.duplicated,message:"导航到相同的路由,被系统阻止!"});try{const result=await this.onBeforeEach(to,this.currentRouteLocation);return result===!1?createNavigateResult({status:NavigateStatus.aborted,message:"导航被前置守卫钩子阻止"}):isCurrentTask()?typeof result=="object"&&result.index!==_target.index?(result.isReplace??(result.isReplace=!1),performNavigation(result,!0)):to.matched.length?(_target.isReplace?(this._pendingReplace=to,this.replaceHistory(to)):(this._pendingPush=to,this.pushHistory(to)),createNavigateResult()):createNavigateResult({status:NavigateStatus.not_matched,message:`未匹配到任何路由规则,被系统阻止!请检测目标索引(${to.index})是否已注册路由。`}):createNavigateResult({status:NavigateStatus.cancelled,message:"已被新的导航请求替代,取消此次导航!"})}catch(error){return console.error("[Vitarx.Router.navigate][ERROR]:导航时捕获到了异常",error),createNavigateResult({status:NavigateStatus.exception,message:"导航时捕获到了异常",error})}};return performNavigation(target,!1)}_completeViewRender(){}completeNavigation(data,savedPosition){const from=this._currentRouteLocation;if(this._completeViewRender=()=>{this.onScrollBehavior(this.currentRouteLocation,from,savedPosition).then(),this.onAfterEach(this.currentRouteLocation,from)},data)this.updateRouteLocation(data);else if(this._pendingReplace)this.updateRouteLocation(this._pendingReplace);else if(this._pendingPush)this.updateRouteLocation(this._pendingPush);else throw new Error("[Vitarx.Router.completeNavigation][ERROR]:没有处于等待状态的导航请求。");this._pendingReplace=null,this._pendingPush=null}updateQuery(query){vitarx.isDeepEqual(this._currentRouteLocation.query,query)||(this._currentRouteLocation.query=query,this._currentRouteLocation.fullPath=this.makeFullPath(this._currentRouteLocation.path,query,this._currentRouteLocation.hash))}updateHash(hash){typeof hash!="string"&&console.warn(`[Vitarx.Router.updateHash][WARN]:hash值只能是字符串类型,给定${hash}`);const newHash=formatHash(hash);newHash!==this._currentRouteLocation.hash&&(this._currentRouteLocation.hash=newHash,this._currentRouteLocation.fullPath=this.makeFullPath(this._currentRouteLocation.path,this._currentRouteLocation.query,newHash))}makeFullPath(path,query,hash){return hash&&!hash.startsWith("#")&&(hash=`#${hash}`),typeof query=="object"&&(query=objectToQueryString(query)),this.mode==="hash"?formatPath(`${this.basePath}/${query}#${path}${hash}`):formatPath(`${this.basePath}${path}${query}${hash}`)}isSameNavigate(to,from){return vitarx.isDeepEqual(to,from)}onBeforeEach(to,from){var _a;const matched=to.matched.at(-1);return matched&&"beforeEnter"in matched&&typeof matched.beforeEnter=="function"?matched.beforeEnter.call(this,to,from):(_a=this._options.beforeEach)==null?void 0:_a.call(this,to,from)}onAfterEach(to,from){var _a;const matched=to.matched.at(-1);return matched&&"afterEnter"in matched&&typeof matched.afterEnter=="function"?matched.afterEnter.call(this,to,from):(_a=this._options.afterEach)==null?void 0:_a.call(this,to,from)}updateRouteLocation(newLocation){patchUpdate(this._currentRouteLocation,newLocation)}async onScrollBehavior(to,from,savedPosition){try{if(this._scrollBehaviorHandler){const scrollTarget=await this._scrollBehaviorHandler(to,from,savedPosition);scrollTarget&&this.scrollTo(scrollTarget)}else this.scrollTo(savedPosition)}catch(e){console.error("[Vitarx.Router.onScrollBehavior]['ERROR']:处理滚动行为时捕获到了异常",e)}}};__publicField(_RouterCore,"_instance");let RouterCore=_RouterCore;class RouterHistory extends RouterCore{constructor(options){["path","hash"].includes(options.mode)||(options.mode="hash"),super(options),options.mode==="hash"&&this.ensureHash()}get currentRouteTarget(){return urlToRouteTarget(window.location,this.mode,this.basePath)}get webHistory(){return window.history}go(delta){this.webHistory.go(delta)}initializeRouter(){window.addEventListener("popstate",this.onPopState.bind(this)),this.replace(this.currentRouteTarget).then(res=>{res.status!==NavigateStatus.success&&console.warn(`[VitarxRouter.initializeRouter]:路由初始化匹配失败,${res.message}`)})}pushHistory(data){this.saveCurrentScrollPosition(),this.webHistory.pushState(this.createState(data),"",data.fullPath),this.completeNavigation(data)}replaceHistory(data){var _a;const scrollPosition=(_a=this.webHistory.state)==null?void 0:_a.scrollPosition;this.webHistory.replaceState(this.createState(data),"",data.fullPath),this.completeNavigation(data,scrollPosition)}saveCurrentScrollPosition(){const scrollPosition={left:window.scrollX,top:window.scrollY,behavior:this.scrollBehavior};this.webHistory.replaceState({...this.webHistory.state,scrollPosition},"",window.location.href)}createState(data,hash,query){const{matched,...state}=data;return typeof hash=="string"&&(state.hash=hash),typeof query=="object"&&(state.query=query),JSON.parse(JSON.stringify(state))}onPopState(event){var _a;let newTarget;(_a=event.state)!=null&&_a.index?newTarget={index:event.state.index,hash:event.state.hash,query:event.state.query}:newTarget=this.currentRouteTarget,this.replace(newTarget).then(res=>{if(!res.redirectFrom&&this.mode==="hash"&&res.status!==NavigateStatus.success)if(res.status===NavigateStatus.not_matched){if(res.to.index.startsWith("/")){const anchorId=res.to.index.slice(1),element=window.document.getElementById(anchorId);element&&element.scrollIntoView({behavior:this.scrollBehavior}),this.updateHash(`#${anchorId}`),this.webHistory.replaceState(this.createState(this.currentRouteLocation),"",this.currentRouteLocation.fullPath)}}else res.status===NavigateStatus.duplicated&&this.webHistory.replaceState(this.createState(this.currentRouteLocation),"",this.currentRouteLocation.fullPath)})}ensureHash(){const{pathname,search,hash}=window.location;if(!hash){const path=`${this.basePath}${search}#${pathname}`;window.location.replace(path)}}}class RouterMemory extends RouterCore{constructor(options){super(options);__publicField(this,"_history",[]);__publicField(this,"_pendingGo",null);__publicField(this,"_currentIndex",0);options.mode="memory"}get currentIndex(){return this._currentIndex}go(delta){if(!delta)return;const currentIndex=this.currentIndex,targetIndex=Math.max(0,Math.min(this._history.length-1,currentIndex+delta));if(targetIndex===currentIndex)return;const target=this._history[targetIndex];this._pendingGo=targetIndex,this.navigate(target).then(res=>{res.status!==NavigateStatus.success&&(this._pendingGo=null)})}initializeRouter(){this._history.push(this.currentRouteLocation)}pushHistory(data){this._updateHistory(data,!1)}replaceHistory(data){this._updateHistory(data,!0)}_updateHistory(data,isReplace){let newIndex;if(this._pendingGo!==null)this._history[this._pendingGo]=data,newIndex=this._pendingGo;else if(isReplace)this._history[this.currentIndex]=data,newIndex=this.currentIndex;else{const nextIndex=this.currentIndex+1;nextIndex<this._history.length?(this._history[nextIndex]=data,this._history.length=nextIndex+1,newIndex=nextIndex):(this._history.push(data),newIndex=this._history.length-1)}this._currentIndex=newIndex,this.completeNavigation(data),this._pendingGo=null}}function defineRoutes(...routes){return routes}function defineRoute(route){return route}function createRouter(options){let router;return!(window!=null&&window.location)&&options.mode!=="memory"?(console.warn("当前环境非浏览器端,强制使用内存模式路由"),options.mode="memory",new RouterMemory(options).initialize()):(options.mode==="memory"?router=new RouterMemory(options):router=new RouterHistory(options),router.initialize())}function useRouter(){return RouterCore.instance}function useRoute(){return RouterCore.instance.currentRouteLocation}function lazy(lazyLoader){return Object.defineProperty(lazyLoader,LAZY_LOADER_SYMBOL,{value:!0}),lazyLoader}const INDEX_SYMBOL=Symbol("RouterViewCounter");class RouterView extends vitarx.Widget{constructor(props){super(props);__publicField(this,"_$index");__publicField(this,"_$currentRoute");__publicField(this,"_$currentElement",vitarx.shallowRef());const parentIndex=vitarx.inject(INDEX_SYMBOL,-1,this);this._$index=parentIndex+1,vitarx.provide(INDEX_SYMBOL,this._$index,this),this._$currentRoute=this.matchedRoute,this._$currentRoute&&(this._$currentElement.value=RouterCore.routeView(this._$currentRoute,this.name)),vitarx.watch(this.location.matched,(_c,o)=>{const newRoute=o[this.index];newRoute!==this._$currentRoute&&(this._$currentRoute=newRoute,this._$currentElement.value=newRoute?RouterCore.routeView(newRoute,this.name):void 0)})}get index(){return this._$index}get isLastView(){return this.index===this.location.matched.length-1&&this.name==="default"}get name(){return this.props.name||"default"}get matchedRoute(){return this.location.matched[this.index]}get currentElement(){return this._$currentElement.value}get currentWidget(){var _a;return(_a=this._$currentElement.value)==null?void 0:_a.type}get location(){return RouterCore.instance.currentRouteLocation}onMounted(){this.completeViewRender()}onUpdated(){this.completeViewRender()}build(){return this.currentElement||vitarx.createElement(vitarx.Fragment)}completeViewRender(){this.isLastView&&RouterCore.instance._completeViewRender()}}class RouterLink extends vitarx.Widget{constructor(props){super(props);__publicField(this,"target");__publicField(this,"location");__publicField(this,"active");__publicField(this,"htmlProps");this.target=new vitarx.Computed(()=>{if(this.props.to)return vitarx.markRaw(vitarx.isString(props.to)?{index:props.to}:props.to)}),this.location=new vitarx.Computed(()=>{if(!this.target.value)return;const location=RouterCore.instance.createRouteLocation(this.target.value);return location.matched.length||console.warn(`[Vitarx.RouterLink][WARN]:索引:${this.target.value.index},未匹配到任何有效的路由线路,请检查to属性是否配置正确!`),vitarx.markRaw(location)}),props.active!==void 0&&props.active!=="none"&&(this.active=new vitarx.Computed(()=>!this.target.value||!this.location.value?!1:this.target.value.index.startsWith("/")?props.active==="obscure"?RouterCore.instance.currentRouteLocation.fullPath.startsWith(this.location.value.path):this.location.value.path===RouterCore.instance.currentRouteLocation.path:!!RouterCore.instance.currentRouteLocation.matched.find(route=>{var _a;return route.name===((_a=this.target.value)==null?void 0:_a.index)}))),this.htmlProps=new vitarx.Computed(()=>{const props2={href:this.href,onClick:e=>this.navigate(e),children:this.children,style:this.props.style,class:this.props.class};return this.isActive&&(props2["aria-current"]="page"),this.isDisabled&&(props2.disabled=!0),props2})}get isActive(){var _a;return((_a=this.active)==null?void 0:_a.value)&&!this.isDisabled}get isDisabled(){return this.props.disabled??!1}get href(){var _a;return((_a=this.location.value)==null?void 0:_a.fullPath)||"javascript:void(0)"}navigate(e){e.preventDefault(),this.location.value&&!this.isDisabled&&RouterCore.instance.navigate(this.location.value).then(res=>{var _a;res.status!==NavigateStatus.success&&console.warn(`[Vitarx.RouterLink][WARN]:导航到索引:${(_a=this.target.value)==null?void 0:_a.index}失败,${res.message}`)})}build(){return vitarx.createElement("a",this.htmlProps.value)}}exports2.HistoryRouter=RouterHistory,exports2.MemoryRouter=RouterMemory,exports2.NavigateStatus=NavigateStatus,exports2.Router=RouterCore,exports2.RouterLink=RouterLink,exports2.RouterView=RouterView,exports2.createRouter=createRouter,exports2.defineRoute=defineRoute,exports2.defineRoutes=defineRoutes,exports2.lazy=lazy,exports2.useRoute=useRoute,exports2.useRouter=useRouter,Object.defineProperty(exports2,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vitarx-router",
3
- "version": "1.0.0-beta.13",
3
+ "version": "1.0.0-beta.15",
4
4
  "description": "Vitarx前端框架的配套路由器",
5
5
  "type": "module",
6
6
  "main": "dist/vitarx-router.umd.js",