@wot-ui/router 0.0.4

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/dist/index.cjs ADDED
@@ -0,0 +1,281 @@
1
+ let vue = require("vue");
2
+
3
+ //#region src/types.ts
4
+ const START_LOCATION_NORMALIZED = {
5
+ path: "/",
6
+ name: void 0,
7
+ params: {},
8
+ query: {},
9
+ hash: "",
10
+ fullPath: "/",
11
+ meta: {}
12
+ };
13
+
14
+ //#endregion
15
+ //#region src/utils.ts
16
+ /**
17
+ * 解析 URL 参数
18
+ * @param path 完整路径
19
+ * @returns 参数对象
20
+ */
21
+ function getUrlParams(path) {
22
+ const index = path.indexOf("?");
23
+ if (index === -1) return {};
24
+ const queryStr = path.slice(index + 1);
25
+ const params = {};
26
+ for (const pair of queryStr.split("&")) {
27
+ const [key, value] = pair.split("=");
28
+ if (key) try {
29
+ params[decodeURIComponent(key)] = value ? decodeURIComponent(value) : "";
30
+ } catch {
31
+ params[key] = value || "";
32
+ }
33
+ }
34
+ return params;
35
+ }
36
+ /**
37
+ * 序列化参数并拼接到 URL
38
+ * @param path 基础路径
39
+ * @param query 参数对象
40
+ * @returns 完整路径
41
+ */
42
+ function stringifyQuery(path, query) {
43
+ if (!query || Object.keys(query).length === 0) return path;
44
+ const queryStr = Object.keys(query).filter((key) => query[key] !== void 0 && query[key] !== null).map((key) => {
45
+ const val = query[key];
46
+ return `${encodeURIComponent(key)}=${encodeURIComponent(String(val))}`;
47
+ }).join("&");
48
+ if (!queryStr) return path;
49
+ return `${path}${path.includes("?") ? "&" : "?"}${queryStr}`;
50
+ }
51
+ /**
52
+ * 规范化 URL (去除多余的 /)
53
+ */
54
+ function normalizeUrl(url) {
55
+ return url.replace(/\/{2,}/g, "/");
56
+ }
57
+
58
+ //#endregion
59
+ //#region src/router.ts
60
+ const routerKey = Symbol("router");
61
+ const routeKey = Symbol("route");
62
+ function createRouter(options) {
63
+ const currentRoute = (0, vue.shallowRef)(START_LOCATION_NORMALIZED);
64
+ const routes = options.routes || [];
65
+ const beforeGuards = [];
66
+ const afterGuards = [];
67
+ function resolve(to) {
68
+ if (typeof to === "string") return resolvePath(to);
69
+ if (to.name) {
70
+ const route = routes.find((r) => r.name === to.name);
71
+ if (!route) {
72
+ console.warn(`[router] Route with name '${to.name}' not found`);
73
+ return {
74
+ ...START_LOCATION_NORMALIZED,
75
+ path: "/"
76
+ };
77
+ }
78
+ const path = fillParams(route.path, to.params);
79
+ return {
80
+ path,
81
+ name: to.name,
82
+ params: to.params || {},
83
+ query: to.query || {},
84
+ hash: to.hash || "",
85
+ fullPath: stringifyQuery(path, to.query || {}),
86
+ meta: route.meta || {}
87
+ };
88
+ }
89
+ if (to.path) return resolvePath(to.path, to.query);
90
+ return { ...START_LOCATION_NORMALIZED };
91
+ }
92
+ function resolvePath(path, query) {
93
+ const normalizedPath = normalizeUrl(path.split("?")[0]);
94
+ const route = routes.find((r) => r.path === normalizedPath || r.aliasPath === normalizedPath);
95
+ const finalQuery = {
96
+ ...getUrlParams(path),
97
+ ...query || {}
98
+ };
99
+ return {
100
+ path: normalizedPath,
101
+ name: route?.name,
102
+ params: {},
103
+ query: finalQuery,
104
+ hash: "",
105
+ fullPath: stringifyQuery(normalizedPath, finalQuery),
106
+ meta: route?.meta || {}
107
+ };
108
+ }
109
+ function fillParams(path, params) {
110
+ if (!params) return path;
111
+ let res = path;
112
+ for (const key in params) res = res.replace(new RegExp(`:${key}`, "g"), String(params[key]));
113
+ return res;
114
+ }
115
+ function push(to) {
116
+ return navigate(to, "push");
117
+ }
118
+ function replace(to) {
119
+ return navigate(to, "replace");
120
+ }
121
+ function replaceAll(to) {
122
+ return navigate(to, "replaceAll");
123
+ }
124
+ function pushTab(to) {
125
+ return navigate(to, "pushTab");
126
+ }
127
+ function back(back$1) {
128
+ if (back$1 === void 0 || typeof back$1 === "number") uni.navigateBack({ delta: back$1 ?? 1 });
129
+ else uni.navigateBack(back$1);
130
+ }
131
+ async function navigate(to, type) {
132
+ const targetLocation = resolve(to);
133
+ const fromLocation = (0, vue.unref)(currentRoute);
134
+ try {
135
+ await runGuardQueue(beforeGuards, targetLocation, fromLocation);
136
+ } catch (error) {
137
+ if (error && (error.message === "NavigationCancelled" || error.message === "NavigationRedirect")) {
138
+ if (error.message === "NavigationRedirect" && error.to) return navigate(error.to, type);
139
+ return Promise.reject(error);
140
+ }
141
+ return Promise.reject(error);
142
+ }
143
+ const url = targetLocation.fullPath;
144
+ performUniNavigate(typeof to === "object" && to.navType || type || "push", url);
145
+ currentRoute.value = targetLocation;
146
+ afterGuards.forEach((guard) => guard(targetLocation, fromLocation));
147
+ return Promise.resolve();
148
+ }
149
+ function performUniNavigate(type, url) {
150
+ switch (type) {
151
+ case "push":
152
+ uni.navigateTo({ url });
153
+ break;
154
+ case "replace":
155
+ uni.redirectTo({ url });
156
+ break;
157
+ case "pushTab":
158
+ uni.switchTab({ url });
159
+ break;
160
+ case "replaceAll":
161
+ uni.reLaunch({ url });
162
+ break;
163
+ case "back":
164
+ uni.navigateBack({});
165
+ break;
166
+ default: uni.navigateTo({ url });
167
+ }
168
+ }
169
+ async function runGuardQueue(guards, to, from) {
170
+ for (const guard of guards) await new Promise((resolve$1, reject) => {
171
+ const next = (val) => {
172
+ if (val === false) reject(/* @__PURE__ */ new Error("NavigationCancelled"));
173
+ else if (val === void 0) resolve$1();
174
+ else {
175
+ const error = /* @__PURE__ */ new Error("NavigationRedirect");
176
+ error.to = val;
177
+ reject(error);
178
+ }
179
+ };
180
+ const res = guard(to, from, next);
181
+ if (res instanceof Promise) res.then((val) => {
182
+ if (val === false) reject(/* @__PURE__ */ new Error("NavigationCancelled"));
183
+ else if (val === void 0 || val === true) resolve$1();
184
+ else {
185
+ const error = /* @__PURE__ */ new Error("NavigationRedirect");
186
+ error.to = val;
187
+ reject(error);
188
+ }
189
+ }).catch(reject);
190
+ else if (res !== void 0 && typeof res !== "function") if (res === false) reject(/* @__PURE__ */ new Error("NavigationCancelled"));
191
+ else if (res === true) resolve$1();
192
+ else {
193
+ const error = /* @__PURE__ */ new Error("NavigationRedirect");
194
+ error.to = res;
195
+ reject(error);
196
+ }
197
+ });
198
+ }
199
+ function beforeEach(guard) {
200
+ beforeGuards.push(guard);
201
+ return () => {
202
+ const i = beforeGuards.indexOf(guard);
203
+ if (i > -1) beforeGuards.splice(i, 1);
204
+ };
205
+ }
206
+ function afterEach(guard) {
207
+ afterGuards.push(guard);
208
+ return () => {
209
+ const i = afterGuards.indexOf(guard);
210
+ if (i > -1) afterGuards.splice(i, 1);
211
+ };
212
+ }
213
+ function install(app) {
214
+ app.provide(routerKey, router);
215
+ app.provide(routeKey, currentRoute);
216
+ app.config.globalProperties.$Router = router;
217
+ Object.defineProperty(app.config.globalProperties, "$Route", {
218
+ enumerable: true,
219
+ get: () => (0, vue.unref)(currentRoute)
220
+ });
221
+ app.mixin({
222
+ onLoad(query) {
223
+ if (this.$mpType === "page") syncRouteFromPage(router, query, afterGuards);
224
+ },
225
+ onShow() {
226
+ if (this.$mpType === "page") syncRouteFromPage(router, void 0, afterGuards);
227
+ }
228
+ });
229
+ }
230
+ function syncRouteFromPage(router$1, query, afterGuards$1) {
231
+ const pages = getCurrentPages();
232
+ const page = pages[pages.length - 1];
233
+ if (page && page.route) {
234
+ const fullPath = page.$page?.fullPath || `/${page.route}`;
235
+ const q = query || getUrlParams(fullPath);
236
+ const newPath = `/${page.route}`;
237
+ if (router$1.currentRoute.value.path === newPath) return;
238
+ const from = (0, vue.unref)(router$1.currentRoute);
239
+ const matched = router$1.routes.find((r) => r.path === newPath || r.aliasPath === newPath);
240
+ const to = {
241
+ path: newPath,
242
+ name: matched?.name,
243
+ meta: matched?.meta || {},
244
+ params: {},
245
+ query: q,
246
+ hash: "",
247
+ fullPath: fullPath.startsWith("/") ? fullPath : `/${fullPath}`
248
+ };
249
+ router$1.currentRoute.value = to;
250
+ afterGuards$1?.forEach((guard) => guard(to, from));
251
+ }
252
+ }
253
+ const router = {
254
+ currentRoute,
255
+ routes,
256
+ push,
257
+ replace,
258
+ replaceAll,
259
+ pushTab,
260
+ back,
261
+ beforeEach,
262
+ afterEach,
263
+ install
264
+ };
265
+ return router;
266
+ }
267
+
268
+ //#endregion
269
+ //#region src/index.ts
270
+ function useRouter() {
271
+ return (0, vue.inject)(routerKey);
272
+ }
273
+ function useRoute() {
274
+ return (0, vue.inject)(routeKey);
275
+ }
276
+
277
+ //#endregion
278
+ exports.START_LOCATION_NORMALIZED = START_LOCATION_NORMALIZED;
279
+ exports.createRouter = createRouter;
280
+ exports.useRoute = useRoute;
281
+ exports.useRouter = useRouter;
@@ -0,0 +1,72 @@
1
+ import { App, Ref } from "vue";
2
+
3
+ //#region src/types.d.ts
4
+ type RouteParams = Record<string, string | string[]>;
5
+ type LocationQuery = Record<string, string | null | (string | null)[]>;
6
+ type RouteMeta = Record<string | number | symbol, unknown>;
7
+ type AnimationType = 'auto' | 'none' | 'slide-out-right' | 'slide-out-left' | 'slide-out-top' | 'slide-out-bottom' | 'fade-out' | 'zoom-in' | 'zoom-fade-in' | 'pop-out';
8
+ interface RouteLocationBase {
9
+ animationType?: AnimationType;
10
+ animationDuration?: number;
11
+ }
12
+ interface RouteBackLocation extends RouteLocationBase {
13
+ delta?: number;
14
+ }
15
+ interface RouteRecordRaw {
16
+ path: string;
17
+ name?: string;
18
+ meta?: RouteMeta;
19
+ aliasPath?: string;
20
+ [key: string]: any;
21
+ }
22
+ interface RouteLocationNormalized {
23
+ path: string;
24
+ name?: string | symbol;
25
+ params: RouteParams;
26
+ query: LocationQuery;
27
+ hash: string;
28
+ fullPath: string;
29
+ meta: RouteMeta;
30
+ redirectedFrom?: RouteLocationNormalized;
31
+ }
32
+ type RouteLocationRaw = string | {
33
+ path?: string;
34
+ name?: string;
35
+ params?: RouteParams;
36
+ query?: LocationQuery;
37
+ hash?: string;
38
+ replace?: boolean;
39
+ navType?: NavType;
40
+ animationType?: string;
41
+ animationDuration?: number;
42
+ };
43
+ interface RouterOptions {
44
+ routes: RouteRecordRaw[];
45
+ }
46
+ type NavigationGuardNext = (to?: RouteLocationRaw | false | void) => void;
47
+ type NavigationGuard = (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => Promise<void | RouteLocationRaw | false | boolean> | void | RouteLocationRaw | false | boolean;
48
+ type NavigationHookAfter = (to: RouteLocationNormalized, from: RouteLocationNormalized) => void;
49
+ type NavType = 'push' | 'replace' | 'replaceAll' | 'pushTab' | 'back';
50
+ type RouteBackRaw = number | RouteBackLocation;
51
+ interface Router {
52
+ readonly currentRoute: Ref<RouteLocationNormalized>;
53
+ readonly routes: RouteRecordRaw[];
54
+ push: (to: RouteLocationRaw) => Promise<any>;
55
+ replace: (to: RouteLocationRaw) => Promise<any>;
56
+ replaceAll: (to: RouteLocationRaw) => Promise<any>;
57
+ pushTab: (to: RouteLocationRaw) => Promise<any>;
58
+ back: (back?: RouteBackRaw) => void;
59
+ beforeEach: (guard: NavigationGuard) => () => void;
60
+ afterEach: (guard: NavigationHookAfter) => () => void;
61
+ install: (app: App) => void;
62
+ }
63
+ declare const START_LOCATION_NORMALIZED: RouteLocationNormalized;
64
+ //#endregion
65
+ //#region src/router.d.ts
66
+ declare function createRouter(options: RouterOptions): Router;
67
+ //#endregion
68
+ //#region src/index.d.ts
69
+ declare function useRouter(): Router;
70
+ declare function useRoute(): RouteLocationNormalized;
71
+ //#endregion
72
+ export { AnimationType, LocationQuery, NavType, NavigationGuard, NavigationGuardNext, NavigationHookAfter, RouteBackLocation, RouteBackRaw, RouteLocationBase, RouteLocationNormalized, RouteLocationRaw, RouteMeta, RouteParams, RouteRecordRaw, Router, RouterOptions, START_LOCATION_NORMALIZED, createRouter, useRoute, useRouter };
@@ -0,0 +1,72 @@
1
+ import { App, Ref } from "vue";
2
+
3
+ //#region src/types.d.ts
4
+ type RouteParams = Record<string, string | string[]>;
5
+ type LocationQuery = Record<string, string | null | (string | null)[]>;
6
+ type RouteMeta = Record<string | number | symbol, unknown>;
7
+ type AnimationType = 'auto' | 'none' | 'slide-out-right' | 'slide-out-left' | 'slide-out-top' | 'slide-out-bottom' | 'fade-out' | 'zoom-in' | 'zoom-fade-in' | 'pop-out';
8
+ interface RouteLocationBase {
9
+ animationType?: AnimationType;
10
+ animationDuration?: number;
11
+ }
12
+ interface RouteBackLocation extends RouteLocationBase {
13
+ delta?: number;
14
+ }
15
+ interface RouteRecordRaw {
16
+ path: string;
17
+ name?: string;
18
+ meta?: RouteMeta;
19
+ aliasPath?: string;
20
+ [key: string]: any;
21
+ }
22
+ interface RouteLocationNormalized {
23
+ path: string;
24
+ name?: string | symbol;
25
+ params: RouteParams;
26
+ query: LocationQuery;
27
+ hash: string;
28
+ fullPath: string;
29
+ meta: RouteMeta;
30
+ redirectedFrom?: RouteLocationNormalized;
31
+ }
32
+ type RouteLocationRaw = string | {
33
+ path?: string;
34
+ name?: string;
35
+ params?: RouteParams;
36
+ query?: LocationQuery;
37
+ hash?: string;
38
+ replace?: boolean;
39
+ navType?: NavType;
40
+ animationType?: string;
41
+ animationDuration?: number;
42
+ };
43
+ interface RouterOptions {
44
+ routes: RouteRecordRaw[];
45
+ }
46
+ type NavigationGuardNext = (to?: RouteLocationRaw | false | void) => void;
47
+ type NavigationGuard = (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => Promise<void | RouteLocationRaw | false | boolean> | void | RouteLocationRaw | false | boolean;
48
+ type NavigationHookAfter = (to: RouteLocationNormalized, from: RouteLocationNormalized) => void;
49
+ type NavType = 'push' | 'replace' | 'replaceAll' | 'pushTab' | 'back';
50
+ type RouteBackRaw = number | RouteBackLocation;
51
+ interface Router {
52
+ readonly currentRoute: Ref<RouteLocationNormalized>;
53
+ readonly routes: RouteRecordRaw[];
54
+ push: (to: RouteLocationRaw) => Promise<any>;
55
+ replace: (to: RouteLocationRaw) => Promise<any>;
56
+ replaceAll: (to: RouteLocationRaw) => Promise<any>;
57
+ pushTab: (to: RouteLocationRaw) => Promise<any>;
58
+ back: (back?: RouteBackRaw) => void;
59
+ beforeEach: (guard: NavigationGuard) => () => void;
60
+ afterEach: (guard: NavigationHookAfter) => () => void;
61
+ install: (app: App) => void;
62
+ }
63
+ declare const START_LOCATION_NORMALIZED: RouteLocationNormalized;
64
+ //#endregion
65
+ //#region src/router.d.ts
66
+ declare function createRouter(options: RouterOptions): Router;
67
+ //#endregion
68
+ //#region src/index.d.ts
69
+ declare function useRouter(): Router;
70
+ declare function useRoute(): RouteLocationNormalized;
71
+ //#endregion
72
+ export { AnimationType, LocationQuery, NavType, NavigationGuard, NavigationGuardNext, NavigationHookAfter, RouteBackLocation, RouteBackRaw, RouteLocationBase, RouteLocationNormalized, RouteLocationRaw, RouteMeta, RouteParams, RouteRecordRaw, Router, RouterOptions, START_LOCATION_NORMALIZED, createRouter, useRoute, useRouter };
package/dist/index.mjs ADDED
@@ -0,0 +1,278 @@
1
+ import { inject, shallowRef, unref } from "vue";
2
+
3
+ //#region src/types.ts
4
+ const START_LOCATION_NORMALIZED = {
5
+ path: "/",
6
+ name: void 0,
7
+ params: {},
8
+ query: {},
9
+ hash: "",
10
+ fullPath: "/",
11
+ meta: {}
12
+ };
13
+
14
+ //#endregion
15
+ //#region src/utils.ts
16
+ /**
17
+ * 解析 URL 参数
18
+ * @param path 完整路径
19
+ * @returns 参数对象
20
+ */
21
+ function getUrlParams(path) {
22
+ const index = path.indexOf("?");
23
+ if (index === -1) return {};
24
+ const queryStr = path.slice(index + 1);
25
+ const params = {};
26
+ for (const pair of queryStr.split("&")) {
27
+ const [key, value] = pair.split("=");
28
+ if (key) try {
29
+ params[decodeURIComponent(key)] = value ? decodeURIComponent(value) : "";
30
+ } catch {
31
+ params[key] = value || "";
32
+ }
33
+ }
34
+ return params;
35
+ }
36
+ /**
37
+ * 序列化参数并拼接到 URL
38
+ * @param path 基础路径
39
+ * @param query 参数对象
40
+ * @returns 完整路径
41
+ */
42
+ function stringifyQuery(path, query) {
43
+ if (!query || Object.keys(query).length === 0) return path;
44
+ const queryStr = Object.keys(query).filter((key) => query[key] !== void 0 && query[key] !== null).map((key) => {
45
+ const val = query[key];
46
+ return `${encodeURIComponent(key)}=${encodeURIComponent(String(val))}`;
47
+ }).join("&");
48
+ if (!queryStr) return path;
49
+ return `${path}${path.includes("?") ? "&" : "?"}${queryStr}`;
50
+ }
51
+ /**
52
+ * 规范化 URL (去除多余的 /)
53
+ */
54
+ function normalizeUrl(url) {
55
+ return url.replace(/\/{2,}/g, "/");
56
+ }
57
+
58
+ //#endregion
59
+ //#region src/router.ts
60
+ const routerKey = Symbol("router");
61
+ const routeKey = Symbol("route");
62
+ function createRouter(options) {
63
+ const currentRoute = shallowRef(START_LOCATION_NORMALIZED);
64
+ const routes = options.routes || [];
65
+ const beforeGuards = [];
66
+ const afterGuards = [];
67
+ function resolve(to) {
68
+ if (typeof to === "string") return resolvePath(to);
69
+ if (to.name) {
70
+ const route = routes.find((r) => r.name === to.name);
71
+ if (!route) {
72
+ console.warn(`[router] Route with name '${to.name}' not found`);
73
+ return {
74
+ ...START_LOCATION_NORMALIZED,
75
+ path: "/"
76
+ };
77
+ }
78
+ const path = fillParams(route.path, to.params);
79
+ return {
80
+ path,
81
+ name: to.name,
82
+ params: to.params || {},
83
+ query: to.query || {},
84
+ hash: to.hash || "",
85
+ fullPath: stringifyQuery(path, to.query || {}),
86
+ meta: route.meta || {}
87
+ };
88
+ }
89
+ if (to.path) return resolvePath(to.path, to.query);
90
+ return { ...START_LOCATION_NORMALIZED };
91
+ }
92
+ function resolvePath(path, query) {
93
+ const normalizedPath = normalizeUrl(path.split("?")[0]);
94
+ const route = routes.find((r) => r.path === normalizedPath || r.aliasPath === normalizedPath);
95
+ const finalQuery = {
96
+ ...getUrlParams(path),
97
+ ...query || {}
98
+ };
99
+ return {
100
+ path: normalizedPath,
101
+ name: route?.name,
102
+ params: {},
103
+ query: finalQuery,
104
+ hash: "",
105
+ fullPath: stringifyQuery(normalizedPath, finalQuery),
106
+ meta: route?.meta || {}
107
+ };
108
+ }
109
+ function fillParams(path, params) {
110
+ if (!params) return path;
111
+ let res = path;
112
+ for (const key in params) res = res.replace(new RegExp(`:${key}`, "g"), String(params[key]));
113
+ return res;
114
+ }
115
+ function push(to) {
116
+ return navigate(to, "push");
117
+ }
118
+ function replace(to) {
119
+ return navigate(to, "replace");
120
+ }
121
+ function replaceAll(to) {
122
+ return navigate(to, "replaceAll");
123
+ }
124
+ function pushTab(to) {
125
+ return navigate(to, "pushTab");
126
+ }
127
+ function back(back$1) {
128
+ if (back$1 === void 0 || typeof back$1 === "number") uni.navigateBack({ delta: back$1 ?? 1 });
129
+ else uni.navigateBack(back$1);
130
+ }
131
+ async function navigate(to, type) {
132
+ const targetLocation = resolve(to);
133
+ const fromLocation = unref(currentRoute);
134
+ try {
135
+ await runGuardQueue(beforeGuards, targetLocation, fromLocation);
136
+ } catch (error) {
137
+ if (error && (error.message === "NavigationCancelled" || error.message === "NavigationRedirect")) {
138
+ if (error.message === "NavigationRedirect" && error.to) return navigate(error.to, type);
139
+ return Promise.reject(error);
140
+ }
141
+ return Promise.reject(error);
142
+ }
143
+ const url = targetLocation.fullPath;
144
+ performUniNavigate(typeof to === "object" && to.navType || type || "push", url);
145
+ currentRoute.value = targetLocation;
146
+ afterGuards.forEach((guard) => guard(targetLocation, fromLocation));
147
+ return Promise.resolve();
148
+ }
149
+ function performUniNavigate(type, url) {
150
+ switch (type) {
151
+ case "push":
152
+ uni.navigateTo({ url });
153
+ break;
154
+ case "replace":
155
+ uni.redirectTo({ url });
156
+ break;
157
+ case "pushTab":
158
+ uni.switchTab({ url });
159
+ break;
160
+ case "replaceAll":
161
+ uni.reLaunch({ url });
162
+ break;
163
+ case "back":
164
+ uni.navigateBack({});
165
+ break;
166
+ default: uni.navigateTo({ url });
167
+ }
168
+ }
169
+ async function runGuardQueue(guards, to, from) {
170
+ for (const guard of guards) await new Promise((resolve$1, reject) => {
171
+ const next = (val) => {
172
+ if (val === false) reject(/* @__PURE__ */ new Error("NavigationCancelled"));
173
+ else if (val === void 0) resolve$1();
174
+ else {
175
+ const error = /* @__PURE__ */ new Error("NavigationRedirect");
176
+ error.to = val;
177
+ reject(error);
178
+ }
179
+ };
180
+ const res = guard(to, from, next);
181
+ if (res instanceof Promise) res.then((val) => {
182
+ if (val === false) reject(/* @__PURE__ */ new Error("NavigationCancelled"));
183
+ else if (val === void 0 || val === true) resolve$1();
184
+ else {
185
+ const error = /* @__PURE__ */ new Error("NavigationRedirect");
186
+ error.to = val;
187
+ reject(error);
188
+ }
189
+ }).catch(reject);
190
+ else if (res !== void 0 && typeof res !== "function") if (res === false) reject(/* @__PURE__ */ new Error("NavigationCancelled"));
191
+ else if (res === true) resolve$1();
192
+ else {
193
+ const error = /* @__PURE__ */ new Error("NavigationRedirect");
194
+ error.to = res;
195
+ reject(error);
196
+ }
197
+ });
198
+ }
199
+ function beforeEach(guard) {
200
+ beforeGuards.push(guard);
201
+ return () => {
202
+ const i = beforeGuards.indexOf(guard);
203
+ if (i > -1) beforeGuards.splice(i, 1);
204
+ };
205
+ }
206
+ function afterEach(guard) {
207
+ afterGuards.push(guard);
208
+ return () => {
209
+ const i = afterGuards.indexOf(guard);
210
+ if (i > -1) afterGuards.splice(i, 1);
211
+ };
212
+ }
213
+ function install(app) {
214
+ app.provide(routerKey, router);
215
+ app.provide(routeKey, currentRoute);
216
+ app.config.globalProperties.$Router = router;
217
+ Object.defineProperty(app.config.globalProperties, "$Route", {
218
+ enumerable: true,
219
+ get: () => unref(currentRoute)
220
+ });
221
+ app.mixin({
222
+ onLoad(query) {
223
+ if (this.$mpType === "page") syncRouteFromPage(router, query, afterGuards);
224
+ },
225
+ onShow() {
226
+ if (this.$mpType === "page") syncRouteFromPage(router, void 0, afterGuards);
227
+ }
228
+ });
229
+ }
230
+ function syncRouteFromPage(router$1, query, afterGuards$1) {
231
+ const pages = getCurrentPages();
232
+ const page = pages[pages.length - 1];
233
+ if (page && page.route) {
234
+ const fullPath = page.$page?.fullPath || `/${page.route}`;
235
+ const q = query || getUrlParams(fullPath);
236
+ const newPath = `/${page.route}`;
237
+ if (router$1.currentRoute.value.path === newPath) return;
238
+ const from = unref(router$1.currentRoute);
239
+ const matched = router$1.routes.find((r) => r.path === newPath || r.aliasPath === newPath);
240
+ const to = {
241
+ path: newPath,
242
+ name: matched?.name,
243
+ meta: matched?.meta || {},
244
+ params: {},
245
+ query: q,
246
+ hash: "",
247
+ fullPath: fullPath.startsWith("/") ? fullPath : `/${fullPath}`
248
+ };
249
+ router$1.currentRoute.value = to;
250
+ afterGuards$1?.forEach((guard) => guard(to, from));
251
+ }
252
+ }
253
+ const router = {
254
+ currentRoute,
255
+ routes,
256
+ push,
257
+ replace,
258
+ replaceAll,
259
+ pushTab,
260
+ back,
261
+ beforeEach,
262
+ afterEach,
263
+ install
264
+ };
265
+ return router;
266
+ }
267
+
268
+ //#endregion
269
+ //#region src/index.ts
270
+ function useRouter() {
271
+ return inject(routerKey);
272
+ }
273
+ function useRoute() {
274
+ return inject(routeKey);
275
+ }
276
+
277
+ //#endregion
278
+ export { START_LOCATION_NORMALIZED, createRouter, useRoute, useRouter };
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@wot-ui/router",
3
+ "version": "0.0.4",
4
+ "description": "轻量级 uni-app vue3 路由库",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "module": "dist/index.mjs",
8
+ "types": "dist/index.d.mts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.mts",
12
+ "import": "./dist/index.mjs",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "unpkg": "dist/index.global.js",
17
+ "jsdelivr": "dist/index.global.js",
18
+ "packageManager": "pnpm@9.9.0",
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "scripts": {
23
+ "clean": "rimraf dist",
24
+ "build": "tsdown",
25
+ "dev": "tsdown --watch",
26
+ "lint": "eslint --fix --ext .json,.js,.ts src"
27
+ },
28
+ "license": "MIT",
29
+ "keywords": [
30
+ "uni-app",
31
+ "router",
32
+ "uni-mini-router",
33
+ "@wot-ui/router"
34
+ ],
35
+ "peerDependencies": {
36
+ "vue": "~3.4.38"
37
+ },
38
+ "devDependencies": {
39
+ "@commitlint/cli": "^17.4.4",
40
+ "@commitlint/config-conventional": "^17.4.4",
41
+ "@dcloudio/types": "^3.4.12",
42
+ "@types/node": "^20.16.2",
43
+ "@typescript-eslint/eslint-plugin": "^5.54.1",
44
+ "@typescript-eslint/parser": "^5.54.1",
45
+ "eslint": "^8.57.0",
46
+ "eslint-config-prettier": "^8.7.0",
47
+ "eslint-plugin-import": "^2.25.2",
48
+ "eslint-plugin-n": "^15.0.0",
49
+ "eslint-plugin-prettier": "^4.2.1",
50
+ "git-cz": "^4.9.0",
51
+ "husky": "^8.0.3",
52
+ "lint-staged": "^13.1.2",
53
+ "prettier": "^2.8.4",
54
+ "rimraf": "^4.4.0",
55
+ "standard-version": "^9.5.0",
56
+ "ts-jest": "^29.0.5",
57
+ "tsdown": "^0.18.2",
58
+ "typescript": "~5.5.4"
59
+ }
60
+ }