@xfe-repo/web-router 1.1.6 → 1.2.2

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.
@@ -0,0 +1,59 @@
1
+ import { History } from 'history';
2
+ import { LoadableComponent, loadableReady } from '@loadable/component';
3
+ import { ParsedQuery } from 'query-string';
4
+ import React, { ReactElement, PropsWithChildren, ComponentType } from 'react';
5
+ import { RegisterComponentStatic } from '@xfe-repo/web-register';
6
+ import { LinkProps as LinkProps$1 } from 'react-router-dom';
7
+ export * from 'react-router-dom';
8
+ import * as react_jsx_runtime from 'react/jsx-runtime';
9
+
10
+ type PageComponent = LoadableComponent<any> & RegisterComponentStatic;
11
+ type RouteConfig = {
12
+ path: string;
13
+ Component: PageComponent;
14
+ };
15
+ type GetRoutesConfig = {
16
+ pagesIndexPath: string[];
17
+ getRoutePath?: (path: string) => string;
18
+ getPageComponents: (path: string) => Promise<any>;
19
+ fallback?: ReactElement;
20
+ };
21
+ declare const routerIndexRegx: RegExp;
22
+ declare const routerDynamicRegx: RegExp;
23
+ declare const getRoutes: (config: GetRoutesConfig) => RouteConfig[];
24
+
25
+ type RouterProps = PropsWithChildren<{
26
+ navigator: NavigatorType;
27
+ routes: RouteConfig[];
28
+ basename?: string;
29
+ NotFoundPageComponent?: ComponentType;
30
+ }>;
31
+ declare const Router: React.MemoExoticComponent<(props: RouterProps) => react_jsx_runtime.JSX.Element>;
32
+
33
+ type LinkProps = Omit<LinkProps$1, 'to'> & {
34
+ to: string;
35
+ reLaunch?: boolean;
36
+ preload?: boolean;
37
+ };
38
+ declare const Link: React.MemoExoticComponent<(props: LinkProps) => react_jsx_runtime.JSX.Element>;
39
+
40
+ type NavigatorStack = {
41
+ pathname: string;
42
+ };
43
+ interface NavigatorType extends History {
44
+ stack: NavigatorStack[];
45
+ reLaunch: (path: string, state?: any) => void;
46
+ preload: (path: string, isReplace?: boolean, query?: ParsedQuery<string | number | boolean>) => Promise<void>;
47
+ leave: (path: string) => void;
48
+ }
49
+ type CreateNavigatorOptions = {
50
+ mode: 'static' | 'browser' | 'hash';
51
+ routes: RouteConfig[];
52
+ initPathname?: string;
53
+ redirect?: (path: string) => void;
54
+ };
55
+ declare function createNavigator(options: CreateNavigatorOptions): NavigatorType;
56
+ declare const getClientNavigator: () => NavigatorType;
57
+ declare const routerReady: typeof loadableReady;
58
+
59
+ export { type CreateNavigatorOptions, type GetRoutesConfig, Link, type NavigatorStack, type NavigatorType, type PageComponent, type RouteConfig, Router, createNavigator, getClientNavigator, getRoutes, routerDynamicRegx, routerIndexRegx, routerReady };
package/dist/index.mjs ADDED
@@ -0,0 +1,457 @@
1
+ // src/index.ts
2
+ function _array_like_to_array(arr, len) {
3
+ if (len == null || len > arr.length) len = arr.length;
4
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
5
+ return arr2;
6
+ }
7
+ function _array_with_holes(arr) {
8
+ if (Array.isArray(arr)) return arr;
9
+ }
10
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
11
+ try {
12
+ var info = gen[key](arg);
13
+ var value = info.value;
14
+ } catch (error) {
15
+ reject(error);
16
+ return;
17
+ }
18
+ if (info.done) {
19
+ resolve(value);
20
+ } else {
21
+ Promise.resolve(value).then(_next, _throw);
22
+ }
23
+ }
24
+ function _async_to_generator(fn) {
25
+ return function() {
26
+ var self = this, args = arguments;
27
+ return new Promise(function(resolve, reject) {
28
+ var gen = fn.apply(self, args);
29
+ function _next(value) {
30
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
31
+ }
32
+ function _throw(err) {
33
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
34
+ }
35
+ _next(undefined);
36
+ });
37
+ };
38
+ }
39
+ function _define_property(obj, key, value) {
40
+ if (key in obj) {
41
+ Object.defineProperty(obj, key, {
42
+ value: value,
43
+ enumerable: true,
44
+ configurable: true,
45
+ writable: true
46
+ });
47
+ } else {
48
+ obj[key] = value;
49
+ }
50
+ return obj;
51
+ }
52
+ function _iterable_to_array_limit(arr, i) {
53
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
54
+ if (_i == null) return;
55
+ var _arr = [];
56
+ var _n = true;
57
+ var _d = false;
58
+ var _s, _e;
59
+ try {
60
+ for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
61
+ _arr.push(_s.value);
62
+ if (i && _arr.length === i) break;
63
+ }
64
+ } catch (err) {
65
+ _d = true;
66
+ _e = err;
67
+ } finally{
68
+ try {
69
+ if (!_n && _i["return"] != null) _i["return"]();
70
+ } finally{
71
+ if (_d) throw _e;
72
+ }
73
+ }
74
+ return _arr;
75
+ }
76
+ function _non_iterable_rest() {
77
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
78
+ }
79
+ function _object_spread(target) {
80
+ for(var i = 1; i < arguments.length; i++){
81
+ var source = arguments[i] != null ? arguments[i] : {};
82
+ var ownKeys = Object.keys(source);
83
+ if (typeof Object.getOwnPropertySymbols === "function") {
84
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
85
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
86
+ }));
87
+ }
88
+ ownKeys.forEach(function(key) {
89
+ _define_property(target, key, source[key]);
90
+ });
91
+ }
92
+ return target;
93
+ }
94
+ function _sliced_to_array(arr, i) {
95
+ return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
96
+ }
97
+ function _unsupported_iterable_to_array(o, minLen) {
98
+ if (!o) return;
99
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
100
+ var n = Object.prototype.toString.call(o).slice(8, -1);
101
+ if (n === "Object" && o.constructor) n = o.constructor.name;
102
+ if (n === "Map" || n === "Set") return Array.from(n);
103
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
104
+ }
105
+ function _ts_generator(thisArg, body) {
106
+ var f, y, t, g, _ = {
107
+ label: 0,
108
+ sent: function() {
109
+ if (t[0] & 1) throw t[1];
110
+ return t[1];
111
+ },
112
+ trys: [],
113
+ ops: []
114
+ };
115
+ return g = {
116
+ next: verb(0),
117
+ "throw": verb(1),
118
+ "return": verb(2)
119
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
120
+ return this;
121
+ }), g;
122
+ function verb(n) {
123
+ return function(v) {
124
+ return step([
125
+ n,
126
+ v
127
+ ]);
128
+ };
129
+ }
130
+ function step(op) {
131
+ if (f) throw new TypeError("Generator is already executing.");
132
+ while(_)try {
133
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
134
+ if (y = 0, t) op = [
135
+ op[0] & 2,
136
+ t.value
137
+ ];
138
+ switch(op[0]){
139
+ case 0:
140
+ case 1:
141
+ t = op;
142
+ break;
143
+ case 4:
144
+ _.label++;
145
+ return {
146
+ value: op[1],
147
+ done: false
148
+ };
149
+ case 5:
150
+ _.label++;
151
+ y = op[1];
152
+ op = [
153
+ 0
154
+ ];
155
+ continue;
156
+ case 7:
157
+ op = _.ops.pop();
158
+ _.trys.pop();
159
+ continue;
160
+ default:
161
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
162
+ _ = 0;
163
+ continue;
164
+ }
165
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
166
+ _.label = op[1];
167
+ break;
168
+ }
169
+ if (op[0] === 6 && _.label < t[1]) {
170
+ _.label = t[1];
171
+ t = op;
172
+ break;
173
+ }
174
+ if (t && _.label < t[2]) {
175
+ _.label = t[2];
176
+ _.ops.push(op);
177
+ break;
178
+ }
179
+ if (t[2]) _.ops.pop();
180
+ _.trys.pop();
181
+ continue;
182
+ }
183
+ op = body.call(thisArg, _);
184
+ } catch (e) {
185
+ op = [
186
+ 6,
187
+ e
188
+ ];
189
+ y = 0;
190
+ } finally{
191
+ f = t = 0;
192
+ }
193
+ if (op[0] & 5) throw op[1];
194
+ return {
195
+ value: op[0] ? op[1] : void 0,
196
+ done: true
197
+ };
198
+ }
199
+ }
200
+ import { createHashHistory, createBrowserHistory, createMemoryHistory } from "history";
201
+ import { loadableReady } from "@loadable/component";
202
+ import { matchRoutes } from "react-router-dom";
203
+ import queryString from "query-string";
204
+ import { isProduction } from "@xfe-repo/web-utils/env";
205
+ export * from "react-router-dom";
206
+ // src/routes.ts
207
+ import loadable from "@loadable/component";
208
+ var routerIndexRegx = /^(?!.*component)(.*)?\/index(\[[^.]+])?\.(ts|js)x?$/;
209
+ var routerDynamicRegx = /\[([^.]+)]/;
210
+ var getRoutes = function(config) {
211
+ var pagesIndexPath = config.pagesIndexPath, getRoutePath = config.getRoutePath, getPageComponents = config.getPageComponents, fallback = config.fallback;
212
+ var routes = [];
213
+ pagesIndexPath.forEach(function(pageIndexPath) {
214
+ var _pageIndexPath_match;
215
+ if (pageIndexPath.startsWith("./")) return;
216
+ var pageComponent = loadable(function() {
217
+ return getPageComponents(pageIndexPath);
218
+ }, {
219
+ fallback: fallback
220
+ });
221
+ var routerPath = getRoutePath ? getRoutePath(pageIndexPath) : pageIndexPath.replace(routerIndexRegx, "$1");
222
+ if (routerPath === "home" || routerPath === "index") routerPath = "/";
223
+ var dynamicRoute = ((_pageIndexPath_match = pageIndexPath.match(routerDynamicRegx)) === null || _pageIndexPath_match === void 0 ? void 0 : _pageIndexPath_match[1]) || "";
224
+ if (dynamicRoute) routerPath = "".concat(routerPath, "/").concat(dynamicRoute);
225
+ var config2 = {
226
+ path: routerPath,
227
+ Component: pageComponent
228
+ };
229
+ routes.push(config2);
230
+ });
231
+ return routes;
232
+ };
233
+ // src/Router.tsx
234
+ import { memo, useState, useEffect } from "react";
235
+ import { Router as OriginalRouter, Routes, Route } from "react-router-dom";
236
+ import { jsx, jsxs } from "react/jsx-runtime";
237
+ var Router = memo(function(props) {
238
+ var navigator = props.navigator, routes = props.routes, _props_basename = props.basename, basename = _props_basename === void 0 ? "/" : _props_basename, children = props.children, NotFoundPageComponent = props.NotFoundPageComponent;
239
+ var _useState = _sliced_to_array(useState({
240
+ action: navigator.action,
241
+ location: navigator.location
242
+ }), 2), navigatorState = _useState[0], setNavigatorState = _useState[1];
243
+ useEffect(function() {
244
+ return navigator.listen(setNavigatorState);
245
+ }, [
246
+ navigator
247
+ ]);
248
+ return /* @__PURE__ */ jsx(OriginalRouter, {
249
+ navigator: navigator,
250
+ navigationType: navigatorState.action,
251
+ location: navigatorState.location,
252
+ basename: basename,
253
+ children: /* @__PURE__ */ jsx(Routes, {
254
+ children: /* @__PURE__ */ jsxs(Route, {
255
+ path: "/",
256
+ element: children,
257
+ children: [
258
+ routes.map(function(param) {
259
+ var path = param.path, Component = param.Component;
260
+ return /* @__PURE__ */ jsx(Route, {
261
+ path: path,
262
+ Component: Component
263
+ }, path);
264
+ }),
265
+ NotFoundPageComponent && /* @__PURE__ */ jsx(Route, {
266
+ path: "*",
267
+ Component: NotFoundPageComponent
268
+ })
269
+ ]
270
+ })
271
+ })
272
+ });
273
+ });
274
+ // src/Link.tsx
275
+ import { memo as memo2, useMemo } from "react";
276
+ import { Link as OriginalLink } from "react-router-dom";
277
+ import { jsx as jsx2 } from "react/jsx-runtime";
278
+ var Link = memo2(function(props) {
279
+ var to = props.to, children = props.children, reLaunch = props.reLaunch, preload = props.preload, replace = props.replace, className = props.className;
280
+ var _navigator2 = useMemo(function() {
281
+ return getClientNavigator();
282
+ }, []);
283
+ if (/http(s)?:\/{2}/.test(to)) {
284
+ var handleLink = function(e) {
285
+ e.preventDefault();
286
+ window.location.href = to;
287
+ };
288
+ return /* @__PURE__ */ jsx2("a", {
289
+ href: to,
290
+ onClick: handleLink,
291
+ className: className,
292
+ children: children
293
+ });
294
+ }
295
+ if (reLaunch) {
296
+ var handleLink1 = function(e) {
297
+ e.preventDefault();
298
+ _navigator2.reLaunch(to);
299
+ };
300
+ return /* @__PURE__ */ jsx2("a", {
301
+ href: to,
302
+ onClick: handleLink1,
303
+ className: className,
304
+ children: children
305
+ });
306
+ }
307
+ if (preload) {
308
+ var handleLink2 = function() {
309
+ var _ref = _async_to_generator(function(e) {
310
+ return _ts_generator(this, function(_state) {
311
+ switch(_state.label){
312
+ case 0:
313
+ e.preventDefault();
314
+ return [
315
+ 4,
316
+ _navigator2.preload(to, replace)
317
+ ];
318
+ case 1:
319
+ _state.sent();
320
+ return [
321
+ 2
322
+ ];
323
+ }
324
+ });
325
+ });
326
+ return function handleLink2(e) {
327
+ return _ref.apply(this, arguments);
328
+ };
329
+ }();
330
+ return /* @__PURE__ */ jsx2("a", {
331
+ href: to,
332
+ onClick: handleLink2,
333
+ className: className,
334
+ children: children
335
+ });
336
+ }
337
+ return /* @__PURE__ */ jsx2(OriginalLink, _object_spread({}, props));
338
+ });
339
+ // src/index.ts
340
+ var _navigator;
341
+ function createNavigator(options) {
342
+ var mode = options.mode, _options_initPathname = options.initPathname, initPathname = _options_initPathname === void 0 ? "/" : _options_initPathname, routes = options.routes;
343
+ var originHistory;
344
+ if (mode === "static") {
345
+ originHistory = createMemoryHistory({
346
+ initialEntries: [
347
+ initPathname
348
+ ]
349
+ });
350
+ } else if (mode === "browser") {
351
+ originHistory = createBrowserHistory();
352
+ } else {
353
+ originHistory = createHashHistory();
354
+ }
355
+ _navigator = originHistory;
356
+ var initialStack = [
357
+ {
358
+ pathname: _navigator.location.pathname
359
+ }
360
+ ];
361
+ var stack = _navigator.stack = initialStack;
362
+ _navigator.listen(function(param) {
363
+ var location = param.location, action = param.action;
364
+ var pathname = location.pathname;
365
+ if (action === "PUSH") {
366
+ stack.push({
367
+ pathname: pathname
368
+ });
369
+ } else if (action === "REPLACE") {
370
+ stack.pop();
371
+ stack.push({
372
+ pathname: pathname
373
+ });
374
+ } else if (action === "POP") {
375
+ stack.pop();
376
+ }
377
+ if (!isProduction) console.log("router", action, pathname, stack);
378
+ });
379
+ _navigator.reLaunch = function(path, state) {
380
+ var _stack_;
381
+ var shouldBlack = -stack.length + 1;
382
+ if (shouldBlack < 0) _navigator.go(shouldBlack);
383
+ if (((_stack_ = stack[0]) === null || _stack_ === void 0 ? void 0 : _stack_.pathname) === path) return;
384
+ setTimeout(function() {
385
+ _navigator.replace(path, state);
386
+ }, 1);
387
+ };
388
+ _navigator.preload = function() {
389
+ var _ref = _async_to_generator(function(path, isReplace, query) {
390
+ var _matchRoutes_, _matchRoutes, _path_split, tmp, originPath, tmp1, search, matchPath, currentRoute, _pageModule_default_emitOnLoad, _pageModule_default, pageModule, _currentRoute_Component_emitOnLoad, _currentRoute_Component;
391
+ return _ts_generator(this, function(_state) {
392
+ switch(_state.label){
393
+ case 0:
394
+ _path_split = _sliced_to_array(path.split("?"), 2), tmp = _path_split[0], originPath = tmp === void 0 ? "" : tmp, tmp1 = _path_split[1], search = tmp1 === void 0 ? "" : tmp1;
395
+ matchPath = originPath.toLowerCase();
396
+ currentRoute = (_matchRoutes = matchRoutes(routes, matchPath)) === null || _matchRoutes === void 0 ? void 0 : (_matchRoutes_ = _matchRoutes[0]) === null || _matchRoutes_ === void 0 ? void 0 : _matchRoutes_.route;
397
+ query = query || queryString.parse(search, {
398
+ parseBooleans: true,
399
+ parseNumbers: true
400
+ });
401
+ if (!!(currentRoute === null || currentRoute === void 0 ? void 0 : currentRoute.Component.config)) return [
402
+ 3,
403
+ 3
404
+ ];
405
+ return [
406
+ 4,
407
+ currentRoute === null || currentRoute === void 0 ? void 0 : currentRoute.Component.load()
408
+ ];
409
+ case 1:
410
+ pageModule = _state.sent();
411
+ return [
412
+ 4,
413
+ (_pageModule_default = pageModule.default) === null || _pageModule_default === void 0 ? void 0 : (_pageModule_default_emitOnLoad = _pageModule_default.emitOnLoad) === null || _pageModule_default_emitOnLoad === void 0 ? void 0 : _pageModule_default_emitOnLoad.call(_pageModule_default, {
414
+ isPreload: true,
415
+ query: query
416
+ })
417
+ ];
418
+ case 2:
419
+ _state.sent();
420
+ return [
421
+ 3,
422
+ 5
423
+ ];
424
+ case 3:
425
+ return [
426
+ 4,
427
+ currentRoute === null || currentRoute === void 0 ? void 0 : (_currentRoute_Component = currentRoute.Component) === null || _currentRoute_Component === void 0 ? void 0 : (_currentRoute_Component_emitOnLoad = _currentRoute_Component.emitOnLoad) === null || _currentRoute_Component_emitOnLoad === void 0 ? void 0 : _currentRoute_Component_emitOnLoad.call(_currentRoute_Component, {
428
+ isPreload: true,
429
+ query: query
430
+ })
431
+ ];
432
+ case 4:
433
+ _state.sent();
434
+ _state.label = 5;
435
+ case 5:
436
+ if (isReplace) {
437
+ _navigator.replace(path);
438
+ } else {
439
+ _navigator.push(path);
440
+ }
441
+ return [
442
+ 2
443
+ ];
444
+ }
445
+ });
446
+ });
447
+ return function(path, isReplace, query) {
448
+ return _ref.apply(this, arguments);
449
+ };
450
+ }();
451
+ return _navigator;
452
+ }
453
+ var getClientNavigator = function() {
454
+ return _navigator;
455
+ };
456
+ var routerReady = loadableReady;
457
+ export { Link, Router, createNavigator, getClientNavigator, getRoutes, routerDynamicRegx, routerIndexRegx, routerReady };
package/package.json CHANGED
@@ -1,9 +1,21 @@
1
1
  {
2
2
  "name": "@xfe-repo/web-router",
3
- "version": "1.1.6",
3
+ "version": "1.2.2",
4
4
  "sideEffects": false,
5
5
  "module": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "import": {
10
+ "types": "./dist/index.d.mts",
11
+ "default": "./dist/index.mjs"
12
+ },
13
+ "require": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ }
17
+ }
18
+ },
7
19
  "files": [
8
20
  "dist"
9
21
  ],
@@ -12,15 +24,18 @@
12
24
  "history": "^5.3.0",
13
25
  "query-string": "^7.1.3",
14
26
  "react-router-dom": "6.28.0",
15
- "@xfe-repo/web-utils": "1.1.4"
27
+ "@xfe-repo/web-utils": "1.3.5"
16
28
  },
17
29
  "devDependencies": {
18
30
  "@types/loadable__component": "^5.13.9",
19
31
  "@types/node": "^20.16.5",
20
32
  "@types/react": "^18",
21
- "@xfe-repo/eslint-config": "0.0.4",
22
- "@xfe-repo/web-register": "1.1.3",
23
- "@xfe-repo/typescript-config": "0.0.6"
33
+ "@xfe-repo/eslint-config": "0.0.5",
34
+ "@xfe-repo/typescript-config": "0.0.6",
35
+ "@xfe-repo/web-register": "1.3.4"
36
+ },
37
+ "publishConfig": {
38
+ "registry": "https://registry.npmjs.org/"
24
39
  },
25
40
  "scripts": {
26
41
  "build": "tsup",