@tarojs/router 3.4.3 → 3.4.6

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.
@@ -1,2649 +1,672 @@
1
- import _extends from '@babel/runtime/helpers/esm/extends';
2
- import _objectSpread from '@babel/runtime/helpers/objectSpread2';
3
- import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
4
- import _regeneratorRuntime from '@babel/runtime/regenerator';
5
- import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
6
- import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
7
- import _createClass from '@babel/runtime/helpers/createClass';
8
- import _defineProperty from '@babel/runtime/helpers/defineProperty';
9
- import { requestAnimationFrame, Current, container, SERVICE_IDENTIFIER, createPageConfig, stringify, eventCenter } from '@tarojs/runtime';
10
- import _typeof from '@babel/runtime/helpers/typeof';
11
- import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
12
- import _createForOfIteratorHelper from '@babel/runtime/helpers/createForOfIteratorHelper';
1
+ import { createBrowserHistory, createHashHistory, parsePath, Action } from 'history';
2
+ import { requestAnimationFrame, Current, container, SERVICE_IDENTIFIER, eventCenter, createPageConfig, stringify } from '@tarojs/runtime';
3
+ import UniversalRouter from 'universal-router';
4
+ import queryString from 'query-string';
13
5
  import { initTabBarApis } from '@tarojs/taro';
14
6
 
15
- var r,
16
- B = r || (r = {});
17
- B.Pop = "POP";
18
- B.Push = "PUSH";
19
- B.Replace = "REPLACE";
20
- var C = "production" !== process.env.NODE_ENV ? function (b) {
21
- return Object.freeze(b);
22
- } : function (b) {
23
- return b;
24
- };
25
-
26
- function D(b, h) {
27
- if (!b) {
28
- "undefined" !== typeof console && console.warn(h);
29
-
30
- try {
31
- throw Error(h);
32
- } catch (k) {}
33
- }
34
- }
35
-
36
- function E(b) {
37
- b.preventDefault();
38
- b.returnValue = "";
39
- }
40
-
41
- function F() {
42
- var b = [];
43
- return {
44
- get length() {
45
- return b.length;
46
- },
47
-
48
- push: function push(h) {
49
- b.push(h);
50
- return function () {
51
- b = b.filter(function (k) {
52
- return k !== h;
53
- });
54
- };
55
- },
56
- call: function call(h) {
57
- b.forEach(function (k) {
58
- return k && k(h);
59
- });
60
- }
61
- };
62
- }
63
-
64
- function H() {
65
- return Math.random().toString(36).substr(2, 8);
66
- }
67
-
68
- function I(b) {
69
- var h = b.pathname,
70
- k = b.search;
71
- b = b.hash;
72
- return (void 0 === h ? "/" : h) + (void 0 === k ? "" : k) + (void 0 === b ? "" : b);
73
- }
74
-
75
- function J(b) {
76
- var h = {};
77
-
78
- if (b) {
79
- var k = b.indexOf("#");
80
- 0 <= k && (h.hash = b.substr(k), b = b.substr(0, k));
81
- k = b.indexOf("?");
82
- 0 <= k && (h.search = b.substr(k), b = b.substr(0, k));
83
- b && (h.pathname = b);
84
- }
85
-
86
- return h;
87
- }
88
-
89
- function createBrowserHistory(b) {
90
- function h() {
91
- var c = p.location,
92
- a = m.state || {};
93
- return [a.idx, C({
94
- pathname: c.pathname,
95
- search: c.search,
96
- hash: c.hash,
97
- state: a.usr || null,
98
- key: a.key || "default"
99
- })];
100
- }
101
-
102
- function k(c) {
103
- return "string" === typeof c ? c : I(c);
104
- }
105
-
106
- function x(c, a) {
107
- void 0 === a && (a = null);
108
- return C(_extends({
109
- pathname: q.pathname,
110
- hash: "",
111
- search: ""
112
- }, "string" === typeof c ? J(c) : c, {
113
- state: a,
114
- key: H()
115
- }));
116
- }
117
-
118
- function z(c) {
119
- t = c;
120
- c = h();
121
- v = c[0];
122
- q = c[1];
123
- d.call({
124
- action: t,
125
- location: q
126
- });
127
- }
128
-
129
- function A(c, a) {
130
- function e() {
131
- A(c, a);
132
- }
133
-
134
- var l = r.Push,
135
- g = x(c, a);
136
-
137
- if (!f.length || (f.call({
138
- action: l,
139
- location: g,
140
- retry: e
141
- }), !1)) {
142
- var n = [{
143
- usr: g.state,
144
- key: g.key,
145
- idx: v + 1
146
- }, k(g)];
147
- g = n[0];
148
- n = n[1];
149
-
150
- try {
151
- m.pushState(g, "", n);
152
- } catch (G) {
153
- p.location.assign(n);
154
- }
155
-
156
- z(l);
157
- }
158
- }
159
-
160
- function y(c, a) {
161
- function e() {
162
- y(c, a);
163
- }
164
-
165
- var l = r.Replace,
166
- g = x(c, a);
167
- f.length && (f.call({
168
- action: l,
169
- location: g,
170
- retry: e
171
- }), 1) || (g = [{
172
- usr: g.state,
173
- key: g.key,
174
- idx: v
175
- }, k(g)], m.replaceState(g[0], "", g[1]), z(l));
176
- }
177
-
178
- function w(c) {
179
- m.go(c);
180
- }
181
-
182
- void 0 === b && (b = {});
183
- b = b.window;
184
- var p = void 0 === b ? document.defaultView : b,
185
- m = p.history,
186
- u = null;
187
- p.addEventListener("popstate", function () {
188
- if (u) f.call(u), u = null;else {
189
- var c = r.Pop,
190
- a = h(),
191
- e = a[0];
192
- a = a[1];
193
- if (f.length) {
194
- if (null != e) {
195
- var l = v - e;
196
- l && (u = {
197
- action: c,
198
- location: a,
199
- retry: function retry() {
200
- w(-1 * l);
201
- }
202
- }, w(l));
203
- } else "production" !== process.env.NODE_ENV ? D(!1, "You are trying to block a POP navigation to a location that was not created by the history library. The block will fail silently in production, but in general you should do all navigation with the history library (instead of using window.history.pushState directly) to avoid this situation.") : void 0;
204
- } else z(c);
205
- }
206
- });
207
- var t = r.Pop;
208
- b = h();
209
- var v = b[0],
210
- q = b[1],
211
- d = F(),
212
- f = F();
213
- null == v && (v = 0, m.replaceState(_extends({}, m.state, {
214
- idx: v
215
- }), ""));
216
- return {
217
- get action() {
218
- return t;
219
- },
220
-
221
- get location() {
222
- return q;
223
- },
224
-
225
- createHref: k,
226
- push: A,
227
- replace: y,
228
- go: w,
229
- back: function back() {
230
- w(-1);
231
- },
232
- forward: function forward() {
233
- w(1);
234
- },
235
- listen: function listen(c) {
236
- return d.push(c);
237
- },
238
- block: function block(c) {
239
- var a = f.push(c);
240
- 1 === f.length && p.addEventListener("beforeunload", E);
241
- return function () {
242
- a();
243
- f.length || p.removeEventListener("beforeunload", E);
244
- };
245
- }
246
- };
247
- }
248
-
249
- function createHashHistory(b) {
250
- function h() {
251
- var a = J(m.location.hash.substr(1)),
252
- e = a.pathname,
253
- l = a.search;
254
- a = a.hash;
255
- var g = u.state || {};
256
- return [g.idx, C({
257
- pathname: void 0 === e ? "/" : e,
258
- search: void 0 === l ? "" : l,
259
- hash: void 0 === a ? "" : a,
260
- state: g.usr || null,
261
- key: g.key || "default"
262
- })];
263
- }
264
-
265
- function k() {
266
- if (t) c.call(t), t = null;else {
267
- var a = r.Pop,
268
- e = h(),
269
- l = e[0];
270
- e = e[1];
271
- if (c.length) {
272
- if (null != l) {
273
- var g = q - l;
274
- g && (t = {
275
- action: a,
276
- location: e,
277
- retry: function retry() {
278
- p(-1 * g);
279
- }
280
- }, p(g));
281
- } else "production" !== process.env.NODE_ENV ? D(!1, "You are trying to block a POP navigation to a location that was not created by the history library. The block will fail silently in production, but in general you should do all navigation with the history library (instead of using window.history.pushState directly) to avoid this situation.") : void 0;
282
- } else A(a);
283
- }
284
- }
285
-
286
- function x(a) {
287
- var e = document.querySelector("base"),
288
- l = "";
289
- e && e.getAttribute("href") && (e = m.location.href, l = e.indexOf("#"), l = -1 === l ? e : e.slice(0, l));
290
- return l + "#" + ("string" === typeof a ? a : I(a));
291
- }
292
-
293
- function z(a, e) {
294
- void 0 === e && (e = null);
295
- return C(_extends({
296
- pathname: d.pathname,
297
- hash: "",
298
- search: ""
299
- }, "string" === typeof a ? J(a) : a, {
300
- state: e,
301
- key: H()
302
- }));
303
- }
304
-
305
- function A(a) {
306
- v = a;
307
- a = h();
308
- q = a[0];
309
- d = a[1];
310
- f.call({
311
- action: v,
312
- location: d
313
- });
314
- }
315
-
316
- function y(a, e) {
317
- function l() {
318
- y(a, e);
319
- }
320
-
321
- var g = r.Push,
322
- n = z(a, e);
323
- "production" !== process.env.NODE_ENV ? D("/" === n.pathname.charAt(0), "Relative pathnames are not supported in hash history.push(" + JSON.stringify(a) + ")") : void 0;
324
-
325
- if (!c.length || (c.call({
326
- action: g,
327
- location: n,
328
- retry: l
329
- }), !1)) {
330
- var G = [{
331
- usr: n.state,
332
- key: n.key,
333
- idx: q + 1
334
- }, x(n)];
335
- n = G[0];
336
- G = G[1];
337
-
338
- try {
339
- u.pushState(n, "", G);
340
- } catch (K) {
341
- m.location.assign(G);
342
- }
343
-
344
- A(g);
345
- }
346
- }
347
-
348
- function w(a, e) {
349
- function l() {
350
- w(a, e);
7
+ let history;
8
+ let basename = '/';
9
+ function setHistoryMode(mode, base = '/') {
10
+ const options = {
11
+ window
12
+ };
13
+ basename = base;
14
+ if (mode === 'browser') {
15
+ history = createBrowserHistory(options);
351
16
  }
352
-
353
- var g = r.Replace,
354
- n = z(a, e);
355
- "production" !== process.env.NODE_ENV ? D("/" === n.pathname.charAt(0), "Relative pathnames are not supported in hash history.replace(" + JSON.stringify(a) + ")") : void 0;
356
- c.length && (c.call({
357
- action: g,
358
- location: n,
359
- retry: l
360
- }), 1) || (n = [{
361
- usr: n.state,
362
- key: n.key,
363
- idx: q
364
- }, x(n)], u.replaceState(n[0], "", n[1]), A(g));
365
- }
366
-
367
- function p(a) {
368
- u.go(a);
369
- }
370
-
371
- void 0 === b && (b = {});
372
- b = b.window;
373
- var m = void 0 === b ? document.defaultView : b,
374
- u = m.history,
375
- t = null;
376
- m.addEventListener("popstate", k);
377
- m.addEventListener("hashchange", function () {
378
- var a = h()[1];
379
- I(a) !== I(d) && k();
380
- });
381
- var v = r.Pop;
382
- b = h();
383
- var q = b[0],
384
- d = b[1],
385
- f = F(),
386
- c = F();
387
- null == q && (q = 0, u.replaceState(_extends({}, u.state, {
388
- idx: q
389
- }), ""));
390
- return {
391
- get action() {
392
- return v;
393
- },
394
-
395
- get location() {
396
- return d;
397
- },
398
-
399
- createHref: x,
400
- push: y,
401
- replace: w,
402
- go: p,
403
- back: function back() {
404
- p(-1);
405
- },
406
- forward: function forward() {
407
- p(1);
408
- },
409
- listen: function listen(a) {
410
- return f.push(a);
411
- },
412
- block: function block(a) {
413
- var e = c.push(a);
414
- 1 === c.length && m.addEventListener("beforeunload", E);
415
- return function () {
416
- e();
417
- c.length || m.removeEventListener("beforeunload", E);
418
- };
17
+ else {
18
+ // default is hash
19
+ history = createHashHistory(options);
419
20
  }
420
- };
421
- }
422
-
423
- var history;
424
- var basename = '/';
425
- function setHistoryMode(mode) {
426
- var base = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '/';
427
- var options = {
428
- window: window
429
- };
430
- basename = base;
431
-
432
- if (mode === 'browser') {
433
- history = createBrowserHistory(options);
434
- } else {
435
- // default is hash
436
- history = createHashHistory(options);
437
- }
438
21
  }
439
- function prependBasename() {
440
- var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
441
- return basename.replace(/\/$/, '') + '/' + url.replace(/^\//, '');
22
+ function prependBasename(url = '') {
23
+ return basename.replace(/\/$/, '') + '/' + url.replace(/^\//, '');
442
24
  }
443
- var hasBasename = function hasBasename() {
444
- var path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
445
- var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
446
- return new RegExp('^' + prefix + '(\\/|\\?|#|$)', 'i').test(path);
447
- };
448
- var stripBasename = function stripBasename() {
449
- var path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
450
- var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
451
- return hasBasename(path, prefix) ? path.substr(prefix.length) : path;
452
- };
453
-
454
- var Stacks = /*#__PURE__*/function () {
455
- function Stacks() {
456
- _classCallCheck(this, Stacks);
457
-
458
- _defineProperty(this, "stacks", []);
459
-
460
- _defineProperty(this, "backDelta", 0);
461
- }
25
+ const hasBasename = (path = '', prefix = '') => new RegExp('^' + prefix + '(\\/|\\?|#|$)', 'i').test(path);
26
+ const stripBasename = (path = '', prefix = '') => hasBasename(path, prefix) ? path.substr(prefix.length) : path;
462
27
 
463
- _createClass(Stacks, [{
464
- key: "delta",
465
- set: function set(delta) {
466
- if (delta > 0) {
467
- this.backDelta = delta;
468
- } else if (this.backDelta > 0) {
469
- --this.backDelta;
470
- } else {
471
- this.backDelta = 0;
472
- }
28
+ class Stacks {
29
+ stacks = [];
30
+ backDelta = 0;
31
+ set delta(delta) {
32
+ if (delta > 0) {
33
+ this.backDelta = delta;
34
+ }
35
+ else if (this.backDelta > 0) {
36
+ --this.backDelta;
37
+ }
38
+ else {
39
+ this.backDelta = 0;
40
+ }
473
41
  }
474
- }, {
475
- key: "length",
476
- get: function get() {
477
- return this.stacks.length;
42
+ get delta() {
43
+ return this.backDelta;
478
44
  }
479
- }, {
480
- key: "last",
481
- get: function get() {
482
- return this.stacks[this.length - 1];
45
+ get length() {
46
+ return this.stacks.length;
483
47
  }
484
- }, {
485
- key: "get",
486
- value: function get() {
487
- return this.stacks;
48
+ get last() {
49
+ return this.stacks[this.length - 1];
488
50
  }
489
- }, {
490
- key: "getItem",
491
- value: function getItem(index) {
492
- return this.stacks[index];
51
+ get() {
52
+ return this.stacks;
493
53
  }
494
- }, {
495
- key: "getLastIndex",
496
- value: function getLastIndex(pathname) {
497
- var stateWith = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
498
-
499
- var list = _toConsumableArray(this.stacks).reverse();
500
-
501
- return list.findIndex(function (page, i) {
502
- var _page$path;
503
-
504
- return i >= stateWith && ((_page$path = page.path) === null || _page$path === void 0 ? void 0 : _page$path.replace(/\?.*/g, '')) === pathname;
505
- });
54
+ getItem(index) {
55
+ return this.stacks[index];
506
56
  }
507
- }, {
508
- key: "getDelta",
509
- value: function getDelta(pathname) {
510
- if (this.backDelta >= 1) {
511
- return this.backDelta;
512
- }
513
-
514
- var index = this.getLastIndex(pathname); // NOTE: 此处为了修复浏览器后退多级页面,在大量重复路由状况下可能出现判断错误的情况 (增强判断能力只能考虑在 query 中新增参数来判断,暂时搁置)
515
-
516
- return index > 0 ? index : 1;
57
+ getLastIndex(pathname, stateWith = 1) {
58
+ const list = [...this.stacks].reverse();
59
+ return list.findIndex((page, i) => i >= stateWith && page.path?.replace(/\?.*/g, '') === pathname);
517
60
  }
518
- }, {
519
- key: "getPrevIndex",
520
- value: function getPrevIndex(pathname) {
521
- var stateWith = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
522
- var lastIndex = this.getLastIndex(pathname, stateWith);
523
-
524
- if (lastIndex < 0) {
525
- return -1;
526
- }
527
-
528
- return this.length - 1 - lastIndex;
61
+ getDelta(pathname) {
62
+ if (this.backDelta >= 1) {
63
+ return this.backDelta;
64
+ }
65
+ const index = this.getLastIndex(pathname);
66
+ // NOTE: 此处为了修复浏览器后退多级页面,在大量重复路由状况下可能出现判断错误的情况 (增强判断能力只能考虑在 query 中新增参数来判断,暂时搁置)
67
+ return index > 0 ? index : 1;
68
+ }
69
+ getPrevIndex(pathname, stateWith = 1) {
70
+ const lastIndex = this.getLastIndex(pathname, stateWith);
71
+ if (lastIndex < 0) {
72
+ return -1;
73
+ }
74
+ return this.length - 1 - lastIndex;
529
75
  }
530
- }, {
531
- key: "pop",
532
- value: function pop() {
533
- return this.stacks.pop();
76
+ pop() {
77
+ return this.stacks.pop();
534
78
  }
535
- }, {
536
- key: "push",
537
- value: function push(page) {
538
- return this.stacks.push(page);
79
+ push(page) {
80
+ return this.stacks.push(page);
539
81
  }
540
- }]);
541
-
542
- return Stacks;
543
- }();
544
-
545
- var stacks = new Stacks();
82
+ }
83
+ const stacks = new Stacks();
546
84
 
547
85
  function addLeadingSlash(path) {
548
- if (path == null) {
549
- return '';
550
- }
551
-
552
- return path.charAt(0) === '/' ? path : '/' + path;
86
+ if (path == null) {
87
+ return '';
88
+ }
89
+ return path.charAt(0) === '/' ? path : '/' + path;
553
90
  }
554
-
555
- var RoutesAlias = /*#__PURE__*/function () {
556
- function RoutesAlias() {
557
- var _this = this;
558
-
559
- _classCallCheck(this, RoutesAlias);
560
-
561
- _defineProperty(this, "conf", []);
562
-
563
- _defineProperty(this, "getConfig", function () {
564
- var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
565
-
566
- var customRoute = _this.conf.filter(function (arr) {
567
- return arr.includes(url);
568
- });
569
-
570
- return customRoute[0];
571
- });
572
-
573
- _defineProperty(this, "getOrigin", function () {
574
- var _this$getConfig;
575
-
576
- var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
577
- return ((_this$getConfig = _this.getConfig(url)) === null || _this$getConfig === void 0 ? void 0 : _this$getConfig[0]) || url;
578
- });
579
-
580
- _defineProperty(this, "getAlias", function () {
581
- var _this$getConfig2;
582
-
583
- var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
584
- return ((_this$getConfig2 = _this.getConfig(url)) === null || _this$getConfig2 === void 0 ? void 0 : _this$getConfig2[1]) || url;
585
- });
586
-
587
- _defineProperty(this, "getAll", function () {
588
- var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
589
- return _this.conf.filter(function (arr) {
590
- return arr.includes(url);
591
- }).reduceRight(function (p, a) {
592
- p.unshift(a[1]);
593
- return p;
594
- }, [url]);
595
- });
596
- }
597
-
598
- _createClass(RoutesAlias, [{
599
- key: "set",
600
- value: function set() {
601
- var _this2 = this;
602
-
603
- var customRoutes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
604
-
605
- var _loop = function _loop(_key) {
606
- var path = customRoutes[_key];
607
- _key = addLeadingSlash(_key);
608
-
609
- if (typeof path === 'string') {
610
- _this2.conf.push([_key, addLeadingSlash(path)]);
611
- } else if ((path === null || path === void 0 ? void 0 : path.length) > 0) {
612
- var _this2$conf;
613
-
614
- (_this2$conf = _this2.conf).push.apply(_this2$conf, _toConsumableArray(path.map(function (p) {
615
- return [_key, addLeadingSlash(p)];
616
- })));
91
+ class RoutesAlias {
92
+ conf = [];
93
+ set(customRoutes = {}) {
94
+ for (let key in customRoutes) {
95
+ const path = customRoutes[key];
96
+ key = addLeadingSlash(key);
97
+ if (typeof path === 'string') {
98
+ this.conf.push([key, addLeadingSlash(path)]);
99
+ }
100
+ else if (path?.length > 0) {
101
+ this.conf.push(...path.map(p => [key, addLeadingSlash(p)]));
102
+ }
617
103
  }
618
-
619
- key = _key;
620
- };
621
-
622
- for (var key in customRoutes) {
623
- _loop(key);
624
- }
625
104
  }
626
- }]);
627
-
628
- return RoutesAlias;
629
- }();
630
-
631
- var routesAlias = new RoutesAlias();
632
-
633
- function processNavigateUrl(option) {
634
- var _pathPieces$pathname;
635
-
636
- var pathPieces = J(option.url); // 处理相对路径
637
-
638
- if ((_pathPieces$pathname = pathPieces.pathname) !== null && _pathPieces$pathname !== void 0 && _pathPieces$pathname.includes('./')) {
639
- var parts = routesAlias.getOrigin(history.location.pathname).split('/');
640
- parts.pop();
641
- pathPieces.pathname.split('/').forEach(function (item) {
642
- if (item === '.') {
643
- return;
644
- }
645
-
646
- item === '..' ? parts.pop() : parts.push(item);
647
- });
648
- pathPieces.pathname = parts.join('/');
649
- } // 处理自定义路由
650
-
651
-
652
- pathPieces.pathname = routesAlias.getAlias(addLeadingSlash(pathPieces.pathname)); // 处理 basename
653
-
654
- pathPieces.pathname = prependBasename(pathPieces.pathname); // hack fix history v5 bug: https://github.com/remix-run/history/issues/814
655
-
656
- if (!pathPieces.search) pathPieces.search = '';
657
- return pathPieces;
658
- }
659
-
660
- function navigate(_x, _x2) {
661
- return _navigate.apply(this, arguments);
105
+ getConfig = (url = '') => {
106
+ const customRoute = this.conf.filter((arr) => {
107
+ return arr.includes(url);
108
+ });
109
+ return customRoute[0];
110
+ };
111
+ getOrigin = (url = '') => {
112
+ return this.getConfig(url)?.[0] || url;
113
+ };
114
+ getAlias = (url = '') => {
115
+ return this.getConfig(url)?.[1] || url;
116
+ };
117
+ getAll = (url = '') => {
118
+ return this.conf.filter((arr) => {
119
+ return arr.includes(url);
120
+ }).reduceRight((p, a) => {
121
+ p.unshift(a[1]);
122
+ return p;
123
+ }, [url]);
124
+ };
662
125
  }
126
+ const routesAlias = new RoutesAlias();
663
127
 
664
- function _navigate() {
665
- _navigate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(option, method) {
666
- return _regeneratorRuntime.wrap(function _callee$(_context) {
667
- while (1) {
668
- switch (_context.prev = _context.next) {
669
- case 0:
670
- return _context.abrupt("return", new Promise(function (resolve, reject) {
671
- var success = option.success,
672
- complete = option.complete,
673
- fail = option.fail;
674
- var unListen = history.listen(function () {
675
- var res = {
676
- errMsg: "".concat(method, ":ok")
677
- };
678
- success === null || success === void 0 ? void 0 : success(res);
679
- complete === null || complete === void 0 ? void 0 : complete(res);
680
- resolve(res);
681
- unListen();
682
- });
683
-
684
- try {
685
- if ('url' in option) {
686
- var pathPieces = processNavigateUrl(option);
687
- var state = {
688
- timestamp: Date.now()
689
- };
690
-
691
- if (method === 'navigateTo') {
128
+ function processNavigateUrl(option) {
129
+ const pathPieces = parsePath(option.url);
130
+ // 处理相对路径
131
+ if (pathPieces.pathname?.includes('./')) {
132
+ const parts = routesAlias.getOrigin(history.location.pathname).split('/');
133
+ parts.pop();
134
+ pathPieces.pathname.split('/').forEach((item) => {
135
+ if (item === '.') {
136
+ return;
137
+ }
138
+ item === '..' ? parts.pop() : parts.push(item);
139
+ });
140
+ pathPieces.pathname = parts.join('/');
141
+ }
142
+ // 处理自定义路由
143
+ pathPieces.pathname = routesAlias.getAlias(addLeadingSlash(pathPieces.pathname));
144
+ // 处理 basename
145
+ pathPieces.pathname = prependBasename(pathPieces.pathname);
146
+ // hack fix history v5 bug: https://github.com/remix-run/history/issues/814
147
+ if (!pathPieces.search)
148
+ pathPieces.search = '';
149
+ return pathPieces;
150
+ }
151
+ async function navigate(option, method) {
152
+ return new Promise((resolve, reject) => {
153
+ const { success, complete, fail } = option;
154
+ const unListen = history.listen(() => {
155
+ const res = { errMsg: `${method}:ok` };
156
+ success?.(res);
157
+ complete?.(res);
158
+ resolve(res);
159
+ unListen();
160
+ });
161
+ try {
162
+ if ('url' in option) {
163
+ const pathPieces = processNavigateUrl(option);
164
+ const state = { timestamp: Date.now() };
165
+ if (method === 'navigateTo') {
692
166
  history.push(pathPieces, state);
693
- } else if (method === 'redirectTo' || method === 'switchTab') {
167
+ }
168
+ else if (method === 'redirectTo' || method === 'switchTab') {
694
169
  history.replace(pathPieces, state);
695
- } else if (method === 'reLaunch') {
170
+ }
171
+ else if (method === 'reLaunch') {
696
172
  stacks.delta = stacks.length;
697
173
  history.replace(pathPieces, state);
698
- }
699
- } else if (method === 'navigateBack') {
700
- stacks.delta = option.delta;
701
- history.go(-option.delta);
702
174
  }
703
- } catch (error) {
704
- var res = {
705
- errMsg: "".concat(method, ":fail ").concat(error.message || error)
706
- };
707
- fail === null || fail === void 0 ? void 0 : fail(res);
708
- complete === null || complete === void 0 ? void 0 : complete(res);
709
- reject(res);
710
- }
711
- }));
712
-
713
- case 1:
714
- case "end":
715
- return _context.stop();
175
+ }
176
+ else if (method === 'navigateBack') {
177
+ stacks.delta = option.delta;
178
+ history.go(-option.delta);
179
+ }
716
180
  }
717
- }
718
- }, _callee);
719
- }));
720
- return _navigate.apply(this, arguments);
181
+ catch (error) {
182
+ const res = { errMsg: `${method}:fail ${error.message || error}` };
183
+ fail?.(res);
184
+ complete?.(res);
185
+ reject(res);
186
+ }
187
+ });
721
188
  }
722
-
723
189
  function navigateTo(option) {
724
- return navigate(option, 'navigateTo');
190
+ return navigate(option, 'navigateTo');
725
191
  }
726
192
  function redirectTo(option) {
727
- return navigate(option, 'redirectTo');
193
+ return navigate(option, 'redirectTo');
728
194
  }
729
- function navigateBack() {
730
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
731
- delta: 1
732
- };
733
-
734
- if (!options.delta || options.delta < 1) {
735
- options.delta = 1;
736
- }
737
-
738
- return navigate(options, 'navigateBack');
195
+ function navigateBack(options = { delta: 1 }) {
196
+ if (!options.delta || options.delta < 1) {
197
+ options.delta = 1;
198
+ }
199
+ return navigate(options, 'navigateBack');
739
200
  }
740
201
  function switchTab(option) {
741
- return navigate(option, 'switchTab');
202
+ return navigate(option, 'switchTab');
742
203
  }
743
204
  function reLaunch(option) {
744
- return navigate(option, 'reLaunch');
205
+ return navigate(option, 'reLaunch');
745
206
  }
746
207
  function getCurrentPages() {
747
- var pages = stacks.get();
748
- return pages.map(function (e) {
749
- return _objectSpread(_objectSpread({}, e), {}, {
750
- route: e.path || ''
751
- });
752
- });
208
+ const pages = stacks.get();
209
+ return pages.map(e => ({ ...e, route: e.path || '' }));
753
210
  }
754
211
 
755
- var pathToRegexp$2 = {exports: {}};
756
-
757
- pathToRegexp$2.exports = pathToRegexp;
758
- pathToRegexp$2.exports.match = match;
759
- pathToRegexp$2.exports.regexpToFunction = regexpToFunction;
760
- pathToRegexp$2.exports.parse = parse;
761
- pathToRegexp$2.exports.compile = compile;
762
- pathToRegexp$2.exports.tokensToFunction = tokensToFunction;
763
- pathToRegexp$2.exports.tokensToRegExp = tokensToRegExp;
764
- /**
765
- * Default configs.
766
- */
767
-
768
- var DEFAULT_DELIMITER = '/';
769
- /**
770
- * The main path matching regexp utility.
771
- *
772
- * @type {RegExp}
773
- */
774
-
775
- var PATH_REGEXP = new RegExp([// Match escaped characters that would otherwise appear in future matches.
776
- // This allows the user to escape special characters that won't transform.
777
- '(\\\\.)', // Match Express-style parameters and un-named parameters with a prefix
778
- // and optional suffixes. Matches appear as:
779
- //
780
- // ":test(\\d+)?" => ["test", "\d+", undefined, "?"]
781
- // "(\\d+)" => [undefined, undefined, "\d+", undefined]
782
- '(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?'].join('|'), 'g');
783
212
  /**
784
- * Parse a string for the raw tokens.
785
- *
786
- * @param {string} str
787
- * @param {Object=} options
788
- * @return {!Array}
213
+ * 插入页面动画需要的样式
789
214
  */
790
-
791
- function parse(str, options) {
792
- var tokens = [];
793
- var key = 0;
794
- var index = 0;
795
- var path = '';
796
- var defaultDelimiter = options && options.delimiter || DEFAULT_DELIMITER;
797
- var whitelist = options && options.whitelist || undefined;
798
- var pathEscaped = false;
799
- var res;
800
-
801
- while ((res = PATH_REGEXP.exec(str)) !== null) {
802
- var m = res[0];
803
- var escaped = res[1];
804
- var offset = res.index;
805
- path += str.slice(index, offset);
806
- index = offset + m.length; // Ignore already escaped sequences.
807
-
808
- if (escaped) {
809
- path += escaped[1];
810
- pathEscaped = true;
811
- continue;
812
- }
813
-
814
- var prev = '';
815
- var name = res[2];
816
- var capture = res[3];
817
- var group = res[4];
818
- var modifier = res[5];
819
-
820
- if (!pathEscaped && path.length) {
821
- var k = path.length - 1;
822
- var c = path[k];
823
- var matches = whitelist ? whitelist.indexOf(c) > -1 : true;
824
-
825
- if (matches) {
826
- prev = c;
827
- path = path.slice(0, k);
828
- }
829
- } // Push the current path onto the tokens.
830
-
831
-
832
- if (path) {
833
- tokens.push(path);
834
- path = '';
835
- pathEscaped = false;
836
- }
837
-
838
- var repeat = modifier === '+' || modifier === '*';
839
- var optional = modifier === '?' || modifier === '*';
840
- var pattern = capture || group;
841
- var delimiter = prev || defaultDelimiter;
842
- tokens.push({
843
- name: name || key++,
844
- prefix: prev,
845
- delimiter: delimiter,
846
- optional: optional,
847
- repeat: repeat,
848
- pattern: pattern ? escapeGroup(pattern) : '[^' + escapeString(delimiter === defaultDelimiter ? delimiter : delimiter + defaultDelimiter) + ']+?'
849
- });
850
- } // Push any remaining characters.
851
-
852
-
853
- if (path || index < str.length) {
854
- tokens.push(path + str.substr(index));
855
- }
856
-
857
- return tokens;
215
+ function loadAnimateStyle(ms = 300) {
216
+ const css = `
217
+ .taro_router .taro_page {
218
+ position: absolute;
219
+ left: 0;
220
+ top: 0;
221
+ width: 100%;
222
+ height: 100%;
223
+ background-color: #fff;
224
+ transform: translate(100%, 0);
225
+ transition: transform ${ms}ms;
226
+ z-index: 0;
858
227
  }
859
- /**
860
- * Compile a string to a template function for the path.
861
- *
862
- * @param {string} str
863
- * @param {Object=} options
864
- * @return {!function(Object=, Object=)}
865
- */
866
-
867
228
 
868
- function compile(str, options) {
869
- return tokensToFunction(parse(str, options), options);
229
+ .taro_router .taro_page.taro_tabbar_page,
230
+ .taro_router .taro_page.taro_page_show.taro_page_stationed {
231
+ transform: none;
870
232
  }
871
- /**
872
- * Create path match function from `path-to-regexp` spec.
873
- */
874
233
 
875
-
876
- function match(str, options) {
877
- var keys = [];
878
- var re = pathToRegexp(str, keys, options);
879
- return regexpToFunction(re, keys);
234
+ .taro_router .taro_page.taro_page_show {
235
+ transform: translate(0, 0);
236
+ }`;
237
+ const style = document.createElement('style');
238
+ style.innerHTML = css;
239
+ document.getElementsByTagName('head')[0].appendChild(style);
880
240
  }
881
- /**
882
- * Create a path match function from `path-to-regexp` output.
883
- */
884
-
885
-
886
- function regexpToFunction(re, keys) {
887
- return function (pathname, options) {
888
- var m = re.exec(pathname);
889
- if (!m) return false;
890
- var path = m[0];
891
- var index = m.index;
892
- var params = {};
893
- var decode = options && options.decode || decodeURIComponent;
894
-
895
- for (var i = 1; i < m.length; i++) {
896
- if (m[i] === undefined) continue;
897
- var key = keys[i - 1];
898
241
 
899
- if (key.repeat) {
900
- params[key.name] = m[i].split(key.delimiter).map(function (value) {
901
- return decode(value, key);
902
- });
903
- } else {
904
- params[key.name] = decode(m[i], key);
905
- }
242
+ // @ts-nocheck
243
+ function initTabbar(config) {
244
+ if (config.tabBar == null) {
245
+ return;
906
246
  }
247
+ // TODO: custom-tab-bar
248
+ const tabbar = document.createElement('taro-tabbar');
249
+ const homePage = config.entryPagePath || (config.pages ? config.pages[0] : '');
250
+ tabbar.conf = config.tabBar;
251
+ tabbar.conf.homePage = history.location.pathname === '/' ? homePage : history.location.pathname;
252
+ const routerConfig = config.router;
253
+ tabbar.conf.mode = routerConfig && routerConfig.mode ? routerConfig.mode : 'hash';
254
+ if (routerConfig.customRoutes) {
255
+ tabbar.conf.custom = true;
256
+ tabbar.conf.customRoutes = routerConfig.customRoutes;
257
+ }
258
+ else {
259
+ tabbar.conf.custom = false;
260
+ tabbar.conf.customRoutes = {};
261
+ }
262
+ if (typeof routerConfig.basename !== 'undefined') {
263
+ tabbar.conf.basename = routerConfig.basename;
264
+ }
265
+ const container = document.getElementById('container');
266
+ container?.appendChild(tabbar);
267
+ initTabBarApis(config);
268
+ }
907
269
 
908
- return {
909
- path: path,
910
- index: index,
911
- params: params
270
+ let pageResizeFn;
271
+ function bindPageResize(page) {
272
+ window.removeEventListener('resize', pageResizeFn);
273
+ pageResizeFn = function () {
274
+ page.onResize && page.onResize({
275
+ size: {
276
+ windowHeight: window.innerHeight,
277
+ windowWidth: window.innerWidth
278
+ }
279
+ });
280
+ };
281
+ window.addEventListener('resize', pageResizeFn, false);
282
+ }
283
+
284
+ let pageScrollFn;
285
+ let pageDOM = window;
286
+ function bindPageScroll(page, pageEl, distance = 50) {
287
+ pageEl.removeEventListener('scroll', pageScrollFn);
288
+ pageDOM = pageEl;
289
+ let isReachBottom = false;
290
+ pageScrollFn = function () {
291
+ page.onPageScroll && page.onPageScroll({
292
+ scrollTop: pageDOM instanceof Window ? window.scrollY : pageDOM.scrollTop
293
+ });
294
+ if (isReachBottom && getOffset() > distance) {
295
+ isReachBottom = false;
296
+ }
297
+ if (page.onReachBottom &&
298
+ !isReachBottom &&
299
+ getOffset() < distance) {
300
+ isReachBottom = true;
301
+ page.onReachBottom();
302
+ }
912
303
  };
913
- };
304
+ pageDOM.addEventListener('scroll', pageScrollFn, false);
914
305
  }
915
- /**
916
- * Expose a method for transforming tokens into the path function.
917
- */
918
-
919
-
920
- function tokensToFunction(tokens, options) {
921
- // Compile all the tokens into regexps.
922
- var matches = new Array(tokens.length); // Compile all the patterns before compilation.
923
-
924
- for (var i = 0; i < tokens.length; i++) {
925
- if (_typeof(tokens[i]) === 'object') {
926
- matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$', flags(options));
306
+ function getOffset() {
307
+ if (pageDOM instanceof Window) {
308
+ return document.documentElement.scrollHeight - window.scrollY - window.innerHeight;
309
+ }
310
+ else {
311
+ return pageDOM.scrollHeight - pageDOM.scrollTop - pageDOM.clientHeight;
312
+ }
313
+ }
314
+
315
+ function setDisplay(el, type = '') {
316
+ if (el) {
317
+ el.style.display = type;
318
+ }
319
+ }
320
+ class PageHandler {
321
+ config;
322
+ defaultAnimation = { duration: 300, delay: 50 };
323
+ unloadTimer;
324
+ hideTimer;
325
+ lastHidePage;
326
+ lastUnloadPage;
327
+ constructor(config) {
328
+ this.config = config;
329
+ this.mount();
330
+ }
331
+ get appId() { return 'app'; }
332
+ get router() { return this.config.router; }
333
+ get routerMode() { return this.router.mode || 'hash'; }
334
+ get customRoutes() { return this.router.customRoutes || {}; }
335
+ get routes() { return this.config.routes; }
336
+ get tabBarList() { return this.config.tabBar?.list || []; }
337
+ get PullDownRefresh() { return this.config.PullDownRefresh; }
338
+ get animation() { return this.config?.animation ?? this.defaultAnimation; }
339
+ get animationDelay() {
340
+ return (typeof this.animation === 'object'
341
+ ? this.animation.delay
342
+ : this.animation
343
+ ? this.defaultAnimation?.delay
344
+ : 0) || 0;
345
+ }
346
+ get animationDuration() {
347
+ return (typeof this.animation === 'object'
348
+ ? this.animation.duration
349
+ : this.animation
350
+ ? this.defaultAnimation?.duration
351
+ : 0) || 0;
352
+ }
353
+ set pathname(p) { this.router.pathname = p; }
354
+ get pathname() { return this.router.pathname; }
355
+ get basename() { return this.router.basename || ''; }
356
+ get pageConfig() {
357
+ return this.routes.find(r => {
358
+ const routePath = stripBasename(this.pathname, this.basename);
359
+ const pagePath = addLeadingSlash(r.path);
360
+ return pagePath === routePath || routesAlias.getConfig(pagePath)?.includes(routePath);
361
+ });
927
362
  }
928
- }
929
-
930
- return function (data, options) {
931
- var path = '';
932
- var encode = options && options.encode || encodeURIComponent;
933
- var validate = options ? options.validate !== false : true;
934
-
935
- for (var i = 0; i < tokens.length; i++) {
936
- var token = tokens[i];
937
-
938
- if (typeof token === 'string') {
939
- path += token;
940
- continue;
941
- }
942
-
943
- var value = data ? data[token.name] : undefined;
944
- var segment;
945
-
946
- if (Array.isArray(value)) {
947
- if (!token.repeat) {
948
- throw new TypeError('Expected "' + token.name + '" to not repeat, but got array');
363
+ get isTabBar() {
364
+ const routePath = stripBasename(this.pathname, this.basename);
365
+ const pagePath = Object.entries(this.customRoutes).find(([, target]) => {
366
+ if (typeof target === 'string') {
367
+ return target === routePath;
368
+ }
369
+ else if (target?.length > 0) {
370
+ return target.includes(routePath);
371
+ }
372
+ return false;
373
+ })?.[0] || routePath;
374
+ return !!pagePath && this.tabBarList.some(t => t.pagePath === pagePath);
375
+ }
376
+ isSamePage(page) {
377
+ const routePath = stripBasename(this.pathname, this.basename);
378
+ const pagePath = stripBasename(page?.path, this.basename);
379
+ return pagePath.startsWith(routePath + '?');
380
+ }
381
+ get search() {
382
+ let search = '?';
383
+ if (this.routerMode === 'hash') {
384
+ const idx = location.hash.indexOf('?');
385
+ if (idx > -1) {
386
+ search = location.hash.slice(idx);
387
+ }
949
388
  }
950
-
951
- if (value.length === 0) {
952
- if (token.optional) continue;
953
- throw new TypeError('Expected "' + token.name + '" to not be empty');
389
+ else {
390
+ search = location.search;
954
391
  }
955
-
956
- for (var j = 0; j < value.length; j++) {
957
- segment = encode(value[j], token);
958
-
959
- if (validate && !matches[i].test(segment)) {
960
- throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '"');
961
- }
962
-
963
- path += (j === 0 ? token.prefix : token.delimiter) + segment;
392
+ return search.substr(1);
393
+ }
394
+ getQuery(stamp = 0, search = '', options = {}) {
395
+ search = search ? `${search}&${this.search}` : this.search;
396
+ const query = search
397
+ ? queryString.parse(search, { decode: false })
398
+ : {};
399
+ query.stamp = stamp.toString();
400
+ return { ...query, ...options };
401
+ }
402
+ mount() {
403
+ setHistoryMode(this.routerMode, this.router.basename);
404
+ document.getElementById('app')?.remove();
405
+ this.animation && loadAnimateStyle(this.animationDuration);
406
+ const app = document.createElement('div');
407
+ app.id = this.appId;
408
+ app.classList.add('taro_router');
409
+ if (this.tabBarList.length > 1) {
410
+ const container = document.createElement('div');
411
+ container.classList.add('taro-tabbar__container');
412
+ container.id = 'container';
413
+ const panel = document.createElement('div');
414
+ panel.classList.add('taro-tabbar__panel');
415
+ panel.appendChild(app);
416
+ container.appendChild(panel);
417
+ document.body.appendChild(container);
418
+ initTabbar(this.config);
964
419
  }
965
-
966
- continue;
967
- }
968
-
969
- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
970
- segment = encode(String(value), token);
971
-
972
- if (validate && !matches[i].test(segment)) {
973
- throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but got "' + segment + '"');
420
+ else {
421
+ document.body.appendChild(app);
974
422
  }
975
-
976
- path += token.prefix + segment;
977
- continue;
978
- }
979
-
980
- if (token.optional) continue;
981
- throw new TypeError('Expected "' + token.name + '" to be ' + (token.repeat ? 'an array' : 'a string'));
982
423
  }
983
-
984
- return path;
985
- };
986
- }
987
- /**
988
- * Escape a regular expression string.
989
- *
990
- * @param {string} str
991
- * @return {string}
992
- */
993
-
994
-
995
- function escapeString(str) {
996
- return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1');
997
- }
998
- /**
999
- * Escape the capturing group by escaping special characters and meaning.
1000
- *
1001
- * @param {string} group
1002
- * @return {string}
1003
- */
1004
-
1005
-
1006
- function escapeGroup(group) {
1007
- return group.replace(/([=!:$/()])/g, '\\$1');
1008
- }
1009
- /**
1010
- * Get the flags for a regexp from the options.
1011
- *
1012
- * @param {Object} options
1013
- * @return {string}
1014
- */
1015
-
1016
-
1017
- function flags(options) {
1018
- return options && options.sensitive ? '' : 'i';
1019
- }
1020
- /**
1021
- * Pull out keys from a regexp.
1022
- *
1023
- * @param {!RegExp} path
1024
- * @param {Array=} keys
1025
- * @return {!RegExp}
1026
- */
1027
-
1028
-
1029
- function regexpToRegexp(path, keys) {
1030
- if (!keys) return path; // Use a negative lookahead to match only capturing groups.
1031
-
1032
- var groups = path.source.match(/\((?!\?)/g);
1033
-
1034
- if (groups) {
1035
- for (var i = 0; i < groups.length; i++) {
1036
- keys.push({
1037
- name: i,
1038
- prefix: null,
1039
- delimiter: null,
1040
- optional: false,
1041
- repeat: false,
1042
- pattern: null
1043
- });
424
+ onReady(page, onLoad = true) {
425
+ const pageEl = this.getPageContainer(page);
426
+ if (pageEl && !pageEl?.['__isReady']) {
427
+ const el = pageEl.firstElementChild;
428
+ el?.['componentOnReady']?.()?.then(() => {
429
+ requestAnimationFrame(() => {
430
+ page.onReady?.();
431
+ pageEl['__isReady'] = true;
432
+ });
433
+ });
434
+ onLoad && (pageEl['__page'] = page);
435
+ }
1044
436
  }
1045
- }
1046
-
1047
- return path;
1048
- }
1049
- /**
1050
- * Transform an array into a regexp.
1051
- *
1052
- * @param {!Array} path
1053
- * @param {Array=} keys
1054
- * @param {Object=} options
1055
- * @return {!RegExp}
1056
- */
1057
-
1058
-
1059
- function arrayToRegexp(path, keys, options) {
1060
- var parts = [];
1061
-
1062
- for (var i = 0; i < path.length; i++) {
1063
- parts.push(pathToRegexp(path[i], keys, options).source);
1064
- }
1065
-
1066
- return new RegExp('(?:' + parts.join('|') + ')', flags(options));
1067
- }
1068
- /**
1069
- * Create a path regexp from string input.
1070
- *
1071
- * @param {string} path
1072
- * @param {Array=} keys
1073
- * @param {Object=} options
1074
- * @return {!RegExp}
1075
- */
1076
-
1077
-
1078
- function stringToRegexp(path, keys, options) {
1079
- return tokensToRegExp(parse(path, options), keys, options);
1080
- }
1081
- /**
1082
- * Expose a function for taking tokens and returning a RegExp.
1083
- *
1084
- * @param {!Array} tokens
1085
- * @param {Array=} keys
1086
- * @param {Object=} options
1087
- * @return {!RegExp}
1088
- */
1089
-
1090
-
1091
- function tokensToRegExp(tokens, keys, options) {
1092
- options = options || {};
1093
- var strict = options.strict;
1094
- var start = options.start !== false;
1095
- var end = options.end !== false;
1096
- var delimiter = options.delimiter || DEFAULT_DELIMITER;
1097
- var endsWith = [].concat(options.endsWith || []).map(escapeString).concat('$').join('|');
1098
- var route = start ? '^' : ''; // Iterate over the tokens and create our regexp string.
1099
-
1100
- for (var i = 0; i < tokens.length; i++) {
1101
- var token = tokens[i];
1102
-
1103
- if (typeof token === 'string') {
1104
- route += escapeString(token);
1105
- } else {
1106
- var capture = token.repeat ? '(?:' + token.pattern + ')(?:' + escapeString(token.delimiter) + '(?:' + token.pattern + '))*' : token.pattern;
1107
- if (keys) keys.push(token);
1108
-
1109
- if (token.optional) {
1110
- if (!token.prefix) {
1111
- route += '(' + capture + ')?';
1112
- } else {
1113
- route += '(?:' + escapeString(token.prefix) + '(' + capture + '))?';
437
+ load(page, pageConfig = {}, stacksIndex = 0) {
438
+ if (!page)
439
+ return;
440
+ // NOTE: 页面栈推入太晚可能导致 getCurrentPages 无法获取到当前页面实例
441
+ stacks.push(page);
442
+ const param = this.getQuery(stacks.length, '', page.options);
443
+ let pageEl = this.getPageContainer(page);
444
+ if (pageEl) {
445
+ setDisplay(pageEl);
446
+ this.isTabBar && pageEl.classList.add('taro_tabbar_page');
447
+ this.addAnimation(pageEl, stacksIndex === 0);
448
+ page.onShow?.();
449
+ this.bindPageEvents(page, pageEl, pageConfig);
450
+ }
451
+ else {
452
+ page.onLoad?.(param, () => {
453
+ pageEl = this.getPageContainer(page);
454
+ this.isTabBar && pageEl?.classList.add('taro_tabbar_page');
455
+ this.addAnimation(pageEl, stacksIndex === 0);
456
+ this.onReady(page, true);
457
+ page.onShow?.();
458
+ this.bindPageEvents(page, pageEl, pageConfig);
459
+ });
1114
460
  }
1115
- } else {
1116
- route += escapeString(token.prefix) + '(' + capture + ')';
1117
- }
1118
- }
1119
- }
1120
-
1121
- if (end) {
1122
- if (!strict) route += '(?:' + escapeString(delimiter) + ')?';
1123
- route += endsWith === '$' ? '$' : '(?=' + endsWith + ')';
1124
- } else {
1125
- var endToken = tokens[tokens.length - 1];
1126
- var isEndDelimited = typeof endToken === 'string' ? endToken[endToken.length - 1] === delimiter : endToken === undefined;
1127
- if (!strict) route += '(?:' + escapeString(delimiter) + '(?=' + endsWith + '))?';
1128
- if (!isEndDelimited) route += '(?=' + escapeString(delimiter) + '|' + endsWith + ')';
1129
- }
1130
-
1131
- return new RegExp(route, flags(options));
1132
- }
1133
- /**
1134
- * Normalize the given path string, returning a regular expression.
1135
- *
1136
- * An empty array can be passed in for the keys, which will hold the
1137
- * placeholder key descriptions. For example, using `/user/:id`, `keys` will
1138
- * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
1139
- *
1140
- * @param {(string|RegExp|Array)} path
1141
- * @param {Array=} keys
1142
- * @param {Object=} options
1143
- * @return {!RegExp}
1144
- */
1145
-
1146
-
1147
- function pathToRegexp(path, keys, options) {
1148
- if (path instanceof RegExp) {
1149
- return regexpToRegexp(path, keys);
1150
- }
1151
-
1152
- if (Array.isArray(path)) {
1153
- return arrayToRegexp(path, keys, options);
1154
- }
1155
-
1156
- return stringToRegexp(path, keys, options);
1157
- }
1158
-
1159
- var pathToRegexp$1 = pathToRegexp$2.exports;
1160
-
1161
- var hasOwnProperty = Object.prototype.hasOwnProperty;
1162
- var cache = new Map();
1163
-
1164
- function decodeParam(val) {
1165
- try {
1166
- return decodeURIComponent(val);
1167
- } catch (err) {
1168
- return val;
1169
- }
1170
- }
1171
-
1172
- function matchPath(route, pathname, parentKeys, parentParams) {
1173
- var end = !route.children;
1174
- var cacheKey = (route.path || '') + "|" + end;
1175
- var regexp = cache.get(cacheKey);
1176
-
1177
- if (!regexp) {
1178
- var keys = [];
1179
- regexp = {
1180
- keys: keys,
1181
- pattern: pathToRegexp$1(route.path || '', keys, {
1182
- end: end
1183
- })
1184
- };
1185
- cache.set(cacheKey, regexp);
1186
- }
1187
-
1188
- var m = regexp.pattern.exec(pathname);
1189
-
1190
- if (!m) {
1191
- return null;
1192
- }
1193
-
1194
- var path = m[0];
1195
- var params = Object.assign({}, parentParams);
1196
-
1197
- for (var i = 1; i < m.length; i++) {
1198
- var key = regexp.keys[i - 1];
1199
- var prop = key.name;
1200
- var value = m[i];
1201
-
1202
- if (value !== undefined || !hasOwnProperty.call(params, prop)) {
1203
- if (key.repeat) {
1204
- params[prop] = value ? value.split(key.delimiter).map(decodeParam) : [];
1205
- } else {
1206
- params[prop] = value ? decodeParam(value) : value;
1207
- }
1208
461
  }
1209
- }
1210
-
1211
- return {
1212
- path: !end && path.charAt(path.length - 1) === '/' ? path.substr(1) : path,
1213
- keys: parentKeys.concat(regexp.keys),
1214
- params: params
1215
- };
1216
- }
1217
-
1218
- function matchRoute(route, baseUrl, pathname, parentKeys, parentParams) {
1219
- var match;
1220
- var childMatches;
1221
- var childIndex = 0;
1222
- return {
1223
- next: function next(routeToSkip) {
1224
- if (route === routeToSkip) {
1225
- return {
1226
- done: true
1227
- };
1228
- }
1229
-
1230
- if (!match) {
1231
- match = matchPath(route, pathname, parentKeys, parentParams);
1232
-
1233
- if (match) {
1234
- return {
1235
- done: false,
1236
- value: {
1237
- route: route,
1238
- baseUrl: baseUrl,
1239
- path: match.path,
1240
- keys: match.keys,
1241
- params: match.params
462
+ unload(page, delta = 1, top = false) {
463
+ if (!page)
464
+ return;
465
+ stacks.delta = --delta;
466
+ stacks.pop();
467
+ if (this.animation && top) {
468
+ if (this.unloadTimer) {
469
+ clearTimeout(this.unloadTimer);
470
+ this.lastUnloadPage?.onUnload?.();
471
+ this.unloadTimer = null;
1242
472
  }
1243
- };
473
+ this.lastUnloadPage = page;
474
+ const pageEl = this.getPageContainer(page);
475
+ pageEl?.classList.remove('taro_page_stationed');
476
+ pageEl?.classList.remove('taro_page_show');
477
+ this.unloadTimer = setTimeout(() => {
478
+ this.unloadTimer = null;
479
+ this.lastUnloadPage?.onUnload?.();
480
+ }, this.animationDuration);
1244
481
  }
1245
- }
1246
-
1247
- if (match && route.children) {
1248
- while (childIndex < route.children.length) {
1249
- if (!childMatches) {
1250
- var childRoute = route.children[childIndex];
1251
- childRoute.parent = route;
1252
- childMatches = matchRoute(childRoute, baseUrl + match.path, pathname.substr(match.path.length), match.keys, match.params);
1253
- }
1254
-
1255
- var childMatch = childMatches.next(routeToSkip);
1256
-
1257
- if (!childMatch.done) {
1258
- return {
1259
- done: false,
1260
- value: childMatch.value
1261
- };
1262
- }
1263
-
1264
- childMatches = null;
1265
- childIndex++;
482
+ else {
483
+ const pageEl = this.getPageContainer(page);
484
+ pageEl?.classList.remove('taro_page_stationed');
485
+ pageEl?.classList.remove('taro_page_show');
486
+ page?.onUnload?.();
1266
487
  }
1267
- }
1268
-
1269
- return {
1270
- done: true
1271
- };
488
+ if (delta >= 1)
489
+ this.unload(stacks.last, delta);
1272
490
  }
1273
- };
1274
- }
1275
-
1276
- function resolveRoute(context, params) {
1277
- if (typeof context.route.action === 'function') {
1278
- return context.route.action(context, params);
1279
- }
1280
-
1281
- return undefined;
1282
- }
1283
-
1284
- function isChildRoute(parentRoute, childRoute) {
1285
- var route = childRoute;
1286
-
1287
- while (route) {
1288
- route = route.parent;
1289
-
1290
- if (route === parentRoute) {
1291
- return true;
1292
- }
1293
- }
1294
-
1295
- return false;
1296
- }
1297
-
1298
- var UniversalRouter = function () {
1299
- function UniversalRouter(routes, options) {
1300
- if (options === void 0) {
1301
- options = {};
1302
- }
1303
-
1304
- if (!routes || _typeof(routes) !== 'object') {
1305
- throw new TypeError('Invalid routes');
1306
- }
1307
-
1308
- this.baseUrl = options.baseUrl || '';
1309
- this.errorHandler = options.errorHandler;
1310
- this.resolveRoute = options.resolveRoute || resolveRoute;
1311
- this.context = Object.assign({
1312
- router: this
1313
- }, options.context);
1314
- this.root = Array.isArray(routes) ? {
1315
- path: '',
1316
- children: routes,
1317
- parent: null
1318
- } : routes;
1319
- this.root.parent = null;
1320
- }
1321
-
1322
- var _proto = UniversalRouter.prototype;
1323
-
1324
- _proto.resolve = function resolve(pathnameOrContext) {
1325
- var _this = this;
1326
-
1327
- var context = Object.assign({}, this.context, {}, typeof pathnameOrContext === 'string' ? {
1328
- pathname: pathnameOrContext
1329
- } : pathnameOrContext);
1330
- var match = matchRoute(this.root, this.baseUrl, context.pathname.substr(this.baseUrl.length), [], null);
1331
- var resolve = this.resolveRoute;
1332
- var matches = null;
1333
- var nextMatches = null;
1334
- var currentContext = context;
1335
-
1336
- function next(resume, parent, prevResult) {
1337
- if (parent === void 0) {
1338
- parent = matches.value.route;
1339
- }
1340
-
1341
- var routeToSkip = prevResult === null && !matches.done && matches.value.route;
1342
- matches = nextMatches || match.next(routeToSkip);
1343
- nextMatches = null;
1344
-
1345
- if (!resume) {
1346
- if (matches.done || !isChildRoute(parent, matches.value.route)) {
1347
- nextMatches = matches;
1348
- return Promise.resolve(null);
491
+ show(page, pageConfig = {}, stacksIndex = 0) {
492
+ if (!page)
493
+ return;
494
+ const param = this.getQuery(stacks.length, '', page.options);
495
+ let pageEl = this.getPageContainer(page);
496
+ if (pageEl) {
497
+ setDisplay(pageEl);
498
+ this.addAnimation(pageEl, stacksIndex === 0);
499
+ page.onShow?.();
500
+ this.bindPageEvents(page, pageEl, pageConfig);
1349
501
  }
1350
- }
1351
-
1352
- if (matches.done) {
1353
- var error = new Error('Route not found');
1354
- error.status = 404;
1355
- return Promise.reject(error);
1356
- }
1357
-
1358
- currentContext = Object.assign({}, context, {}, matches.value);
1359
- return Promise.resolve(resolve(currentContext, matches.value.params)).then(function (result) {
1360
- if (result !== null && result !== undefined) {
1361
- return result;
502
+ else {
503
+ page.onLoad?.(param, () => {
504
+ pageEl = this.getPageContainer(page);
505
+ this.addAnimation(pageEl, stacksIndex === 0);
506
+ this.onReady(page, false);
507
+ page.onShow?.();
508
+ this.bindPageEvents(page, pageEl, pageConfig);
509
+ });
1362
510
  }
1363
-
1364
- return next(resume, parent, result);
1365
- });
1366
- }
1367
-
1368
- context.next = next;
1369
- return Promise.resolve().then(function () {
1370
- return next(true, _this.root);
1371
- })["catch"](function (error) {
1372
- if (_this.errorHandler) {
1373
- return _this.errorHandler(error, currentContext);
1374
- }
1375
-
1376
- throw error;
1377
- });
1378
- };
1379
-
1380
- return UniversalRouter;
1381
- }();
1382
-
1383
- UniversalRouter.pathToRegexp = pathToRegexp$1;
1384
-
1385
- var queryString = {};
1386
-
1387
- var strictUriEncode = function strictUriEncode(str) {
1388
- return encodeURIComponent(str).replace(/[!'()*]/g, function (x) {
1389
- return "%".concat(x.charCodeAt(0).toString(16).toUpperCase());
1390
- });
1391
- };
1392
-
1393
- var token = '%[a-f0-9]{2}';
1394
- var singleMatcher = new RegExp(token, 'gi');
1395
- var multiMatcher = new RegExp('(' + token + ')+', 'gi');
1396
-
1397
- function decodeComponents(components, split) {
1398
- try {
1399
- // Try to decode the entire string first
1400
- return decodeURIComponent(components.join(''));
1401
- } catch (err) {// Do nothing
1402
- }
1403
-
1404
- if (components.length === 1) {
1405
- return components;
1406
- }
1407
-
1408
- split = split || 1; // Split the array in 2 parts
1409
-
1410
- var left = components.slice(0, split);
1411
- var right = components.slice(split);
1412
- return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));
1413
- }
1414
-
1415
- function decode(input) {
1416
- try {
1417
- return decodeURIComponent(input);
1418
- } catch (err) {
1419
- var tokens = input.match(singleMatcher);
1420
-
1421
- for (var i = 1; i < tokens.length; i++) {
1422
- input = decodeComponents(tokens, i).join('');
1423
- tokens = input.match(singleMatcher);
1424
- }
1425
-
1426
- return input;
1427
- }
1428
- }
1429
-
1430
- function customDecodeURIComponent(input) {
1431
- // Keep track of all the replacements and prefill the map with the `BOM`
1432
- var replaceMap = {
1433
- '%FE%FF': "\uFFFD\uFFFD",
1434
- '%FF%FE': "\uFFFD\uFFFD"
1435
- };
1436
- var match = multiMatcher.exec(input);
1437
-
1438
- while (match) {
1439
- try {
1440
- // Decode as big chunks as possible
1441
- replaceMap[match[0]] = decodeURIComponent(match[0]);
1442
- } catch (err) {
1443
- var result = decode(match[0]);
1444
-
1445
- if (result !== match[0]) {
1446
- replaceMap[match[0]] = result;
1447
- }
1448
- }
1449
-
1450
- match = multiMatcher.exec(input);
1451
- } // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else
1452
-
1453
-
1454
- replaceMap['%C2'] = "\uFFFD";
1455
- var entries = Object.keys(replaceMap);
1456
-
1457
- for (var i = 0; i < entries.length; i++) {
1458
- // Replace all decoded components
1459
- var key = entries[i];
1460
- input = input.replace(new RegExp(key, 'g'), replaceMap[key]);
1461
- }
1462
-
1463
- return input;
1464
- }
1465
-
1466
- var decodeUriComponent = function decodeUriComponent(encodedURI) {
1467
- if (typeof encodedURI !== 'string') {
1468
- throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + _typeof(encodedURI) + '`');
1469
- }
1470
-
1471
- try {
1472
- encodedURI = encodedURI.replace(/\+/g, ' '); // Try the built in decoder first
1473
-
1474
- return decodeURIComponent(encodedURI);
1475
- } catch (err) {
1476
- // Fallback to a more advanced decoder
1477
- return customDecodeURIComponent(encodedURI);
1478
- }
1479
- };
1480
-
1481
- var splitOnFirst = function splitOnFirst(string, separator) {
1482
- if (!(typeof string === 'string' && typeof separator === 'string')) {
1483
- throw new TypeError('Expected the arguments to be of type `string`');
1484
- }
1485
-
1486
- if (separator === '') {
1487
- return [string];
1488
- }
1489
-
1490
- var separatorIndex = string.indexOf(separator);
1491
-
1492
- if (separatorIndex === -1) {
1493
- return [string];
1494
- }
1495
-
1496
- return [string.slice(0, separatorIndex), string.slice(separatorIndex + separator.length)];
1497
- };
1498
-
1499
- var filterObj = function filterObj(obj, predicate) {
1500
- var ret = {};
1501
- var keys = Object.keys(obj);
1502
- var isArr = Array.isArray(predicate);
1503
-
1504
- for (var i = 0; i < keys.length; i++) {
1505
- var key = keys[i];
1506
- var val = obj[key];
1507
-
1508
- if (isArr ? predicate.indexOf(key) !== -1 : predicate(key, val, obj)) {
1509
- ret[key] = val;
1510
511
  }
1511
- }
1512
-
1513
- return ret;
1514
- };
1515
-
1516
- (function (exports) {
1517
-
1518
- var strictUriEncode$1 = strictUriEncode;
1519
- var decodeComponent = decodeUriComponent;
1520
- var splitOnFirst$1 = splitOnFirst;
1521
- var filterObject = filterObj;
1522
-
1523
- var isNullOrUndefined = function isNullOrUndefined(value) {
1524
- return value === null || value === undefined;
1525
- };
1526
-
1527
- function encoderForArrayFormat(options) {
1528
- switch (options.arrayFormat) {
1529
- case 'index':
1530
- return function (key) {
1531
- return function (result, value) {
1532
- var index = result.length;
1533
-
1534
- if (value === undefined || options.skipNull && value === null || options.skipEmptyString && value === '') {
1535
- return result;
1536
- }
1537
-
1538
- if (value === null) {
1539
- return [].concat(_toConsumableArray(result), [[encode(key, options), '[', index, ']'].join('')]);
1540
- }
1541
-
1542
- return [].concat(_toConsumableArray(result), [[encode(key, options), '[', encode(index, options), ']=', encode(value, options)].join('')]);
1543
- };
1544
- };
1545
-
1546
- case 'bracket':
1547
- return function (key) {
1548
- return function (result, value) {
1549
- if (value === undefined || options.skipNull && value === null || options.skipEmptyString && value === '') {
1550
- return result;
1551
- }
1552
-
1553
- if (value === null) {
1554
- return [].concat(_toConsumableArray(result), [[encode(key, options), '[]'].join('')]);
1555
- }
1556
-
1557
- return [].concat(_toConsumableArray(result), [[encode(key, options), '[]=', encode(value, options)].join('')]);
1558
- };
1559
- };
1560
-
1561
- case 'comma':
1562
- case 'separator':
1563
- return function (key) {
1564
- return function (result, value) {
1565
- if (value === null || value === undefined || value.length === 0) {
1566
- return result;
1567
- }
1568
-
1569
- if (result.length === 0) {
1570
- return [[encode(key, options), '=', encode(value, options)].join('')];
1571
- }
1572
-
1573
- return [[result, encode(value, options)].join(options.arrayFormatSeparator)];
1574
- };
1575
- };
1576
-
1577
- default:
1578
- return function (key) {
1579
- return function (result, value) {
1580
- if (value === undefined || options.skipNull && value === null || options.skipEmptyString && value === '') {
1581
- return result;
1582
- }
1583
-
1584
- if (value === null) {
1585
- return [].concat(_toConsumableArray(result), [encode(key, options)]);
1586
- }
1587
-
1588
- return [].concat(_toConsumableArray(result), [[encode(key, options), '=', encode(value, options)].join('')]);
1589
- };
1590
- };
1591
- }
1592
- }
1593
-
1594
- function parserForArrayFormat(options) {
1595
- var result;
1596
-
1597
- switch (options.arrayFormat) {
1598
- case 'index':
1599
- return function (key, value, accumulator) {
1600
- result = /\[(\d*)\]$/.exec(key);
1601
- key = key.replace(/\[\d*\]$/, '');
1602
-
1603
- if (!result) {
1604
- accumulator[key] = value;
1605
- return;
1606
- }
1607
-
1608
- if (accumulator[key] === undefined) {
1609
- accumulator[key] = {};
1610
- }
1611
-
1612
- accumulator[key][result[1]] = value;
1613
- };
1614
-
1615
- case 'bracket':
1616
- return function (key, value, accumulator) {
1617
- result = /(\[\])$/.exec(key);
1618
- key = key.replace(/\[\]$/, '');
1619
-
1620
- if (!result) {
1621
- accumulator[key] = value;
512
+ hide(page) {
513
+ if (!page)
1622
514
  return;
1623
- }
1624
-
1625
- if (accumulator[key] === undefined) {
1626
- accumulator[key] = [value];
1627
- return;
1628
- }
1629
-
1630
- accumulator[key] = [].concat(accumulator[key], value);
1631
- };
1632
-
1633
- case 'comma':
1634
- case 'separator':
1635
- return function (key, value, accumulator) {
1636
- var isArray = typeof value === 'string' && value.includes(options.arrayFormatSeparator);
1637
- var isEncodedArray = typeof value === 'string' && !isArray && decode(value, options).includes(options.arrayFormatSeparator);
1638
- value = isEncodedArray ? decode(value, options) : value;
1639
- var newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map(function (item) {
1640
- return decode(item, options);
1641
- }) : value === null ? value : decode(value, options);
1642
- accumulator[key] = newValue;
1643
- };
1644
-
1645
- default:
1646
- return function (key, value, accumulator) {
1647
- if (accumulator[key] === undefined) {
1648
- accumulator[key] = value;
1649
- return;
1650
- }
1651
-
1652
- accumulator[key] = [].concat(accumulator[key], value);
1653
- };
1654
- }
1655
- }
1656
-
1657
- function validateArrayFormatSeparator(value) {
1658
- if (typeof value !== 'string' || value.length !== 1) {
1659
- throw new TypeError('arrayFormatSeparator must be single character string');
1660
- }
1661
- }
1662
-
1663
- function encode(value, options) {
1664
- if (options.encode) {
1665
- return options.strict ? strictUriEncode$1(value) : encodeURIComponent(value);
1666
- }
1667
-
1668
- return value;
1669
- }
1670
-
1671
- function decode(value, options) {
1672
- if (options.decode) {
1673
- return decodeComponent(value);
1674
- }
1675
-
1676
- return value;
1677
- }
1678
-
1679
- function keysSorter(input) {
1680
- if (Array.isArray(input)) {
1681
- return input.sort();
1682
- }
1683
-
1684
- if (_typeof(input) === 'object') {
1685
- return keysSorter(Object.keys(input)).sort(function (a, b) {
1686
- return Number(a) - Number(b);
1687
- }).map(function (key) {
1688
- return input[key];
1689
- });
1690
- }
1691
-
1692
- return input;
1693
- }
1694
-
1695
- function removeHash(input) {
1696
- var hashStart = input.indexOf('#');
1697
-
1698
- if (hashStart !== -1) {
1699
- input = input.slice(0, hashStart);
1700
- }
1701
-
1702
- return input;
1703
- }
1704
-
1705
- function getHash(url) {
1706
- var hash = '';
1707
- var hashStart = url.indexOf('#');
1708
-
1709
- if (hashStart !== -1) {
1710
- hash = url.slice(hashStart);
1711
- }
1712
-
1713
- return hash;
1714
- }
1715
-
1716
- function extract(input) {
1717
- input = removeHash(input);
1718
- var queryStart = input.indexOf('?');
1719
-
1720
- if (queryStart === -1) {
1721
- return '';
1722
- }
1723
-
1724
- return input.slice(queryStart + 1);
1725
- }
1726
-
1727
- function parseValue(value, options) {
1728
- if (options.parseNumbers && !Number.isNaN(Number(value)) && typeof value === 'string' && value.trim() !== '') {
1729
- value = Number(value);
1730
- } else if (options.parseBooleans && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) {
1731
- value = value.toLowerCase() === 'true';
1732
- }
1733
-
1734
- return value;
1735
- }
1736
-
1737
- function parse(query, options) {
1738
- options = Object.assign({
1739
- decode: true,
1740
- sort: true,
1741
- arrayFormat: 'none',
1742
- arrayFormatSeparator: ',',
1743
- parseNumbers: false,
1744
- parseBooleans: false
1745
- }, options);
1746
- validateArrayFormatSeparator(options.arrayFormatSeparator);
1747
- var formatter = parserForArrayFormat(options); // Create an object with no prototype
1748
-
1749
- var ret = Object.create(null);
1750
-
1751
- if (typeof query !== 'string') {
1752
- return ret;
1753
- }
1754
-
1755
- query = query.trim().replace(/^[?#&]/, '');
1756
-
1757
- if (!query) {
1758
- return ret;
1759
- }
1760
-
1761
- var _iterator = _createForOfIteratorHelper(query.split('&')),
1762
- _step;
1763
-
1764
- try {
1765
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
1766
- var param = _step.value;
1767
-
1768
- if (param === '') {
1769
- continue;
515
+ // NOTE: 修复多页并发问题,此处可能因为路由跳转过快,执行时页面可能还没有创建成功
516
+ const pageEl = this.getPageContainer(page);
517
+ if (pageEl) {
518
+ if (this.hideTimer) {
519
+ clearTimeout(this.hideTimer);
520
+ this.hideTimer = null;
521
+ setDisplay(this.lastHidePage, 'none');
522
+ }
523
+ this.lastHidePage = pageEl;
524
+ this.hideTimer = setTimeout(() => {
525
+ this.hideTimer = null;
526
+ setDisplay(this.lastHidePage, 'none');
527
+ }, this.animationDuration + this.animationDelay);
528
+ page.onHide?.();
1770
529
  }
1771
-
1772
- var _splitOnFirst = splitOnFirst$1(options.decode ? param.replace(/\+/g, ' ') : param, '='),
1773
- _splitOnFirst2 = _slicedToArray(_splitOnFirst, 2),
1774
- _key = _splitOnFirst2[0],
1775
- _value = _splitOnFirst2[1]; // Missing `=` should be `null`:
1776
- // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
1777
-
1778
-
1779
- _value = _value === undefined ? null : ['comma', 'separator'].includes(options.arrayFormat) ? _value : decode(_value, options);
1780
- formatter(decode(_key, options), _value, ret);
1781
- }
1782
- } catch (err) {
1783
- _iterator.e(err);
1784
- } finally {
1785
- _iterator.f();
1786
- }
1787
-
1788
- for (var _i = 0, _Object$keys = Object.keys(ret); _i < _Object$keys.length; _i++) {
1789
- var key = _Object$keys[_i];
1790
- var value = ret[key];
1791
-
1792
- if (_typeof(value) === 'object' && value !== null) {
1793
- for (var _i2 = 0, _Object$keys2 = Object.keys(value); _i2 < _Object$keys2.length; _i2++) {
1794
- var k = _Object$keys2[_i2];
1795
- value[k] = parseValue(value[k], options);
530
+ else {
531
+ setTimeout(() => this.hide(page), 0);
1796
532
  }
1797
- } else {
1798
- ret[key] = parseValue(value, options);
1799
- }
1800
533
  }
1801
-
1802
- if (options.sort === false) {
1803
- return ret;
1804
- }
1805
-
1806
- return (options.sort === true ? Object.keys(ret).sort() : Object.keys(ret).sort(options.sort)).reduce(function (result, key) {
1807
- var value = ret[key];
1808
-
1809
- if (Boolean(value) && _typeof(value) === 'object' && !Array.isArray(value)) {
1810
- // Sort object keys, not values
1811
- result[key] = keysSorter(value);
1812
- } else {
1813
- result[key] = value;
1814
- }
1815
-
1816
- return result;
1817
- }, Object.create(null));
1818
- }
1819
-
1820
- exports.extract = extract;
1821
- exports.parse = parse;
1822
-
1823
- exports.stringify = function (object, options) {
1824
- if (!object) {
1825
- return '';
1826
- }
1827
-
1828
- options = Object.assign({
1829
- encode: true,
1830
- strict: true,
1831
- arrayFormat: 'none',
1832
- arrayFormatSeparator: ','
1833
- }, options);
1834
- validateArrayFormatSeparator(options.arrayFormatSeparator);
1835
-
1836
- var shouldFilter = function shouldFilter(key) {
1837
- return options.skipNull && isNullOrUndefined(object[key]) || options.skipEmptyString && object[key] === '';
1838
- };
1839
-
1840
- var formatter = encoderForArrayFormat(options);
1841
- var objectCopy = {};
1842
-
1843
- for (var _i3 = 0, _Object$keys3 = Object.keys(object); _i3 < _Object$keys3.length; _i3++) {
1844
- var key = _Object$keys3[_i3];
1845
-
1846
- if (!shouldFilter(key)) {
1847
- objectCopy[key] = object[key];
1848
- }
1849
- }
1850
-
1851
- var keys = Object.keys(objectCopy);
1852
-
1853
- if (options.sort !== false) {
1854
- keys.sort(options.sort);
1855
- }
1856
-
1857
- return keys.map(function (key) {
1858
- var value = object[key];
1859
-
1860
- if (value === undefined) {
1861
- return '';
1862
- }
1863
-
1864
- if (value === null) {
1865
- return encode(key, options);
1866
- }
1867
-
1868
- if (Array.isArray(value)) {
1869
- return value.reduce(formatter(key), []).join('&');
1870
- }
1871
-
1872
- return encode(key, options) + '=' + encode(value, options);
1873
- }).filter(function (x) {
1874
- return x.length > 0;
1875
- }).join('&');
1876
- };
1877
-
1878
- exports.parseUrl = function (url, options) {
1879
- options = Object.assign({
1880
- decode: true
1881
- }, options);
1882
-
1883
- var _splitOnFirst3 = splitOnFirst$1(url, '#'),
1884
- _splitOnFirst4 = _slicedToArray(_splitOnFirst3, 2),
1885
- url_ = _splitOnFirst4[0],
1886
- hash = _splitOnFirst4[1];
1887
-
1888
- return Object.assign({
1889
- url: url_.split('?')[0] || '',
1890
- query: parse(extract(url), options)
1891
- }, options && options.parseFragmentIdentifier && hash ? {
1892
- fragmentIdentifier: decode(hash, options)
1893
- } : {});
1894
- };
1895
-
1896
- exports.stringifyUrl = function (object, options) {
1897
- options = Object.assign({
1898
- encode: true,
1899
- strict: true
1900
- }, options);
1901
- var url = removeHash(object.url).split('?')[0] || '';
1902
- var queryFromUrl = exports.extract(object.url);
1903
- var parsedQueryFromUrl = exports.parse(queryFromUrl, {
1904
- sort: false
1905
- });
1906
- var query = Object.assign(parsedQueryFromUrl, object.query);
1907
- var queryString = exports.stringify(query, options);
1908
-
1909
- if (queryString) {
1910
- queryString = "?".concat(queryString);
1911
- }
1912
-
1913
- var hash = getHash(object.url);
1914
-
1915
- if (object.fragmentIdentifier) {
1916
- hash = "#".concat(encode(object.fragmentIdentifier, options));
1917
- }
1918
-
1919
- return "".concat(url).concat(queryString).concat(hash);
1920
- };
1921
-
1922
- exports.pick = function (input, filter, options) {
1923
- options = Object.assign({
1924
- parseFragmentIdentifier: true
1925
- }, options);
1926
-
1927
- var _exports$parseUrl = exports.parseUrl(input, options),
1928
- url = _exports$parseUrl.url,
1929
- query = _exports$parseUrl.query,
1930
- fragmentIdentifier = _exports$parseUrl.fragmentIdentifier;
1931
-
1932
- return exports.stringifyUrl({
1933
- url: url,
1934
- query: filterObject(query, filter),
1935
- fragmentIdentifier: fragmentIdentifier
1936
- }, options);
1937
- };
1938
-
1939
- exports.exclude = function (input, filter, options) {
1940
- var exclusionFilter = Array.isArray(filter) ? function (key) {
1941
- return !filter.includes(key);
1942
- } : function (key, value) {
1943
- return !filter(key, value);
1944
- };
1945
- return exports.pick(input, exclusionFilter, options);
1946
- };
1947
- })(queryString);
1948
-
1949
- /**
1950
- * 插入页面动画需要的样式
1951
- */
1952
- function loadAnimateStyle() {
1953
- var ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 300;
1954
- var css = "\n.taro_router .taro_page {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n background-color: #fff;\n transform: translate(100%, 0);\n transition: transform ".concat(ms, "ms;\n z-index: 0;\n}\n\n.taro_router .taro_page.taro_tabbar_page,\n.taro_router .taro_page.taro_page_show.taro_page_stationed {\n transform: none;\n}\n\n.taro_router .taro_page.taro_page_show {\n transform: translate(0, 0);\n}");
1955
- var style = document.createElement('style');
1956
- style.innerHTML = css;
1957
- document.getElementsByTagName('head')[0].appendChild(style);
1958
- }
1959
-
1960
- // @ts-nocheck
1961
- function initTabbar(config) {
1962
- if (config.tabBar == null) {
1963
- return;
1964
- } // TODO: custom-tab-bar
1965
-
1966
-
1967
- var tabbar = document.createElement('taro-tabbar');
1968
- var homePage = config.entryPagePath || (config.pages ? config.pages[0] : '');
1969
- tabbar.conf = config.tabBar;
1970
- tabbar.conf.homePage = history.location.pathname === '/' ? homePage : history.location.pathname;
1971
- var routerConfig = config.router;
1972
- tabbar.conf.mode = routerConfig && routerConfig.mode ? routerConfig.mode : 'hash';
1973
-
1974
- if (routerConfig.customRoutes) {
1975
- tabbar.conf.custom = true;
1976
- tabbar.conf.customRoutes = routerConfig.customRoutes;
1977
- } else {
1978
- tabbar.conf.custom = false;
1979
- tabbar.conf.customRoutes = {};
1980
- }
1981
-
1982
- if (typeof routerConfig.basename !== 'undefined') {
1983
- tabbar.conf.basename = routerConfig.basename;
1984
- }
1985
-
1986
- var container = document.getElementById('container');
1987
- container === null || container === void 0 ? void 0 : container.appendChild(tabbar);
1988
- initTabBarApis(config);
1989
- }
1990
-
1991
- var pageResizeFn;
1992
- function bindPageResize(page) {
1993
- window.removeEventListener('resize', pageResizeFn);
1994
-
1995
- pageResizeFn = function pageResizeFn() {
1996
- page.onResize && page.onResize({
1997
- size: {
1998
- windowHeight: window.innerHeight,
1999
- windowWidth: window.innerWidth
2000
- }
2001
- });
2002
- };
2003
-
2004
- window.addEventListener('resize', pageResizeFn, false);
2005
- }
2006
-
2007
- var pageScrollFn;
2008
- var pageDOM = window;
2009
- function bindPageScroll(page, pageEl) {
2010
- var distance = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 50;
2011
- pageEl.removeEventListener('scroll', pageScrollFn);
2012
- pageDOM = pageEl;
2013
- var isReachBottom = false;
2014
-
2015
- pageScrollFn = function pageScrollFn() {
2016
- page.onPageScroll && page.onPageScroll({
2017
- scrollTop: pageDOM instanceof Window ? window.scrollY : pageDOM.scrollTop
2018
- });
2019
-
2020
- if (isReachBottom && getOffset() > distance) {
2021
- isReachBottom = false;
2022
- }
2023
-
2024
- if (page.onReachBottom && !isReachBottom && getOffset() < distance) {
2025
- isReachBottom = true;
2026
- page.onReachBottom();
2027
- }
2028
- };
2029
-
2030
- pageDOM.addEventListener('scroll', pageScrollFn, false);
2031
- }
2032
-
2033
- function getOffset() {
2034
- if (pageDOM instanceof Window) {
2035
- return document.documentElement.scrollHeight - window.scrollY - window.innerHeight;
2036
- } else {
2037
- return pageDOM.scrollHeight - pageDOM.scrollTop - pageDOM.clientHeight;
2038
- }
2039
- }
2040
-
2041
- function setDisplay(el) {
2042
- var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
2043
-
2044
- if (el) {
2045
- el.style.display = type;
2046
- }
2047
- }
2048
-
2049
- var PageHandler = /*#__PURE__*/function () {
2050
- function PageHandler(config) {
2051
- _classCallCheck(this, PageHandler);
2052
-
2053
- _defineProperty(this, "config", void 0);
2054
-
2055
- _defineProperty(this, "defaultAnimation", {
2056
- duration: 300,
2057
- delay: 50
2058
- });
2059
-
2060
- _defineProperty(this, "unloadTimer", void 0);
2061
-
2062
- _defineProperty(this, "hideTimer", void 0);
2063
-
2064
- _defineProperty(this, "lastHidePage", void 0);
2065
-
2066
- _defineProperty(this, "lastUnloadPage", void 0);
2067
-
2068
- this.config = config;
2069
- this.mount();
2070
- }
2071
-
2072
- _createClass(PageHandler, [{
2073
- key: "appId",
2074
- get: function get() {
2075
- return 'app';
2076
- }
2077
- }, {
2078
- key: "router",
2079
- get: function get() {
2080
- return this.config.router;
2081
- }
2082
- }, {
2083
- key: "routerMode",
2084
- get: function get() {
2085
- return this.router.mode || 'hash';
2086
- }
2087
- }, {
2088
- key: "customRoutes",
2089
- get: function get() {
2090
- return this.router.customRoutes || {};
2091
- }
2092
- }, {
2093
- key: "routes",
2094
- get: function get() {
2095
- return this.config.routes;
2096
- }
2097
- }, {
2098
- key: "tabBarList",
2099
- get: function get() {
2100
- var _this$config$tabBar;
2101
-
2102
- return ((_this$config$tabBar = this.config.tabBar) === null || _this$config$tabBar === void 0 ? void 0 : _this$config$tabBar.list) || [];
2103
- }
2104
- }, {
2105
- key: "PullDownRefresh",
2106
- get: function get() {
2107
- return this.config.PullDownRefresh;
2108
- }
2109
- }, {
2110
- key: "animation",
2111
- get: function get() {
2112
- var _this$config$animatio, _this$config;
2113
-
2114
- return (_this$config$animatio = (_this$config = this.config) === null || _this$config === void 0 ? void 0 : _this$config.animation) !== null && _this$config$animatio !== void 0 ? _this$config$animatio : this.defaultAnimation;
2115
- }
2116
- }, {
2117
- key: "animationDelay",
2118
- get: function get() {
2119
- var _this$defaultAnimatio;
2120
-
2121
- return (_typeof(this.animation) === 'object' ? this.animation.delay : this.animation ? (_this$defaultAnimatio = this.defaultAnimation) === null || _this$defaultAnimatio === void 0 ? void 0 : _this$defaultAnimatio.delay : 0) || 0;
2122
- }
2123
- }, {
2124
- key: "animationDuration",
2125
- get: function get() {
2126
- var _this$defaultAnimatio2;
2127
-
2128
- return (_typeof(this.animation) === 'object' ? this.animation.duration : this.animation ? (_this$defaultAnimatio2 = this.defaultAnimation) === null || _this$defaultAnimatio2 === void 0 ? void 0 : _this$defaultAnimatio2.duration : 0) || 0;
2129
- }
2130
- }, {
2131
- key: "pathname",
2132
- get: function get() {
2133
- return this.router.pathname;
2134
- },
2135
- set: function set(p) {
2136
- this.router.pathname = p;
2137
- }
2138
- }, {
2139
- key: "basename",
2140
- get: function get() {
2141
- return this.router.basename || '';
2142
- }
2143
- }, {
2144
- key: "pageConfig",
2145
- get: function get() {
2146
- var _this = this;
2147
-
2148
- return this.routes.find(function (r) {
2149
- var _routesAlias$getConfi;
2150
-
2151
- var routePath = stripBasename(_this.pathname, _this.basename);
2152
- var pagePath = addLeadingSlash(r.path);
2153
- return pagePath === routePath || ((_routesAlias$getConfi = routesAlias.getConfig(pagePath)) === null || _routesAlias$getConfi === void 0 ? void 0 : _routesAlias$getConfi.includes(routePath));
2154
- });
2155
- }
2156
- }, {
2157
- key: "isTabBar",
2158
- get: function get() {
2159
- var _Object$entries$find;
2160
-
2161
- var routePath = stripBasename(this.pathname, this.basename);
2162
- var pagePath = ((_Object$entries$find = Object.entries(this.customRoutes).find(function (_ref) {
2163
- var _ref2 = _slicedToArray(_ref, 2),
2164
- target = _ref2[1];
2165
-
2166
- if (typeof target === 'string') {
2167
- return target === routePath;
2168
- } else if ((target === null || target === void 0 ? void 0 : target.length) > 0) {
2169
- return target.includes(routePath);
534
+ addAnimation(pageEl, first = false) {
535
+ if (!pageEl)
536
+ return;
537
+ if (this.animation && !first) {
538
+ setTimeout(() => {
539
+ pageEl.classList.add('taro_page_show');
540
+ setTimeout(() => {
541
+ pageEl.classList.add('taro_page_stationed');
542
+ }, this.animationDuration);
543
+ }, this.animationDelay);
2170
544
  }
2171
-
2172
- return false;
2173
- })) === null || _Object$entries$find === void 0 ? void 0 : _Object$entries$find[0]) || routePath;
2174
- return !!pagePath && this.tabBarList.some(function (t) {
2175
- return t.pagePath === pagePath;
2176
- });
2177
- }
2178
- }, {
2179
- key: "isSamePage",
2180
- value: function isSamePage(page) {
2181
- var routePath = stripBasename(this.pathname, this.basename);
2182
- var pagePath = stripBasename(page === null || page === void 0 ? void 0 : page.path, this.basename);
2183
- return pagePath.startsWith(routePath + '?');
2184
- }
2185
- }, {
2186
- key: "search",
2187
- get: function get() {
2188
- var search = '?';
2189
-
2190
- if (this.routerMode === 'hash') {
2191
- var idx = location.hash.indexOf('?');
2192
-
2193
- if (idx > -1) {
2194
- search = location.hash.slice(idx);
545
+ else {
546
+ pageEl.classList.add('taro_page_show');
547
+ pageEl.classList.add('taro_page_stationed');
2195
548
  }
2196
- } else {
2197
- search = location.search;
2198
- }
2199
-
2200
- return search.substr(1);
2201
549
  }
2202
- }, {
2203
- key: "getQuery",
2204
- value: function getQuery() {
2205
- var stamp = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
2206
- var search = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
2207
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2208
- search = search ? "".concat(search, "&").concat(this.search) : this.search;
2209
- var query = search ? queryString.parse(search) : {};
2210
- query.stamp = stamp.toString();
2211
- return _objectSpread(_objectSpread({}, query), options);
2212
- }
2213
- }, {
2214
- key: "mount",
2215
- value: function mount() {
2216
- var _document$getElementB;
2217
-
2218
- setHistoryMode(this.routerMode, this.router.basename);
2219
- (_document$getElementB = document.getElementById('app')) === null || _document$getElementB === void 0 ? void 0 : _document$getElementB.remove();
2220
- this.animation && loadAnimateStyle(this.animationDuration);
2221
- var app = document.createElement('div');
2222
- app.id = this.appId;
2223
- app.classList.add('taro_router');
2224
-
2225
- if (this.tabBarList.length > 1) {
2226
- var container = document.createElement('div');
2227
- container.classList.add('taro-tabbar__container');
2228
- container.id = 'container';
2229
- var panel = document.createElement('div');
2230
- panel.classList.add('taro-tabbar__panel');
2231
- panel.appendChild(app);
2232
- container.appendChild(panel);
2233
- document.body.appendChild(container);
2234
- initTabbar(this.config);
2235
- } else {
2236
- document.body.appendChild(app);
2237
- }
2238
- }
2239
- }, {
2240
- key: "onReady",
2241
- value: function onReady(page) {
2242
- var onLoad = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
2243
- var pageEl = this.getPageContainer(page);
2244
-
2245
- if (pageEl && !(pageEl !== null && pageEl !== void 0 && pageEl['__isReady'])) {
2246
- var _el$componentOnReady, _el$componentOnReady$;
2247
-
2248
- var el = pageEl.firstElementChild;
2249
- el === null || el === void 0 ? void 0 : (_el$componentOnReady = el['componentOnReady']) === null || _el$componentOnReady === void 0 ? void 0 : (_el$componentOnReady$ = _el$componentOnReady.call(el)) === null || _el$componentOnReady$ === void 0 ? void 0 : _el$componentOnReady$.then(function () {
2250
- requestAnimationFrame(function () {
2251
- var _page$onReady;
2252
-
2253
- (_page$onReady = page.onReady) === null || _page$onReady === void 0 ? void 0 : _page$onReady.call(page);
2254
- pageEl['__isReady'] = true;
2255
- });
2256
- });
2257
- onLoad && (pageEl['__page'] = page);
2258
- }
2259
- }
2260
- }, {
2261
- key: "load",
2262
- value: function load(page) {
2263
- var _this2 = this;
2264
-
2265
- var pageConfig = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2266
- var stacksIndex = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
2267
- if (!page) return; // NOTE: 页面栈推入太晚可能导致 getCurrentPages 无法获取到当前页面实例
2268
-
2269
- stacks.push(page);
2270
- var param = this.getQuery(stacks.length, '', page.options);
2271
- var pageEl = this.getPageContainer(page);
2272
-
2273
- if (pageEl) {
2274
- var _page$onShow;
2275
-
2276
- setDisplay(pageEl);
2277
- this.isTabBar && pageEl.classList.add('taro_tabbar_page');
2278
- this.addAnimation(pageEl, stacksIndex === 0);
2279
- (_page$onShow = page.onShow) === null || _page$onShow === void 0 ? void 0 : _page$onShow.call(page);
2280
- this.bindPageEvents(page, pageEl, pageConfig);
2281
- } else {
2282
- var _page$onLoad;
2283
-
2284
- (_page$onLoad = page.onLoad) === null || _page$onLoad === void 0 ? void 0 : _page$onLoad.call(page, param, function () {
2285
- var _pageEl, _page$onShow2;
2286
-
2287
- pageEl = _this2.getPageContainer(page);
2288
- _this2.isTabBar && ((_pageEl = pageEl) === null || _pageEl === void 0 ? void 0 : _pageEl.classList.add('taro_tabbar_page'));
2289
-
2290
- _this2.addAnimation(pageEl, stacksIndex === 0);
2291
-
2292
- _this2.onReady(page, true);
2293
-
2294
- (_page$onShow2 = page.onShow) === null || _page$onShow2 === void 0 ? void 0 : _page$onShow2.call(page);
2295
-
2296
- _this2.bindPageEvents(page, pageEl, pageConfig);
2297
- });
2298
- }
2299
- }
2300
- }, {
2301
- key: "unload",
2302
- value: function unload(page) {
2303
- var _this3 = this;
2304
-
2305
- var delta = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
2306
- var top = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
2307
- if (!page) return;
2308
- stacks.delta = --delta;
2309
- stacks.pop();
2310
-
2311
- if (this.animation && top) {
2312
- if (this.unloadTimer) {
2313
- var _this$lastUnloadPage, _this$lastUnloadPage$;
2314
-
2315
- clearTimeout(this.unloadTimer);
2316
- (_this$lastUnloadPage = this.lastUnloadPage) === null || _this$lastUnloadPage === void 0 ? void 0 : (_this$lastUnloadPage$ = _this$lastUnloadPage.onUnload) === null || _this$lastUnloadPage$ === void 0 ? void 0 : _this$lastUnloadPage$.call(_this$lastUnloadPage);
2317
- this.unloadTimer = null;
550
+ getPageContainer(page) {
551
+ const path = page ? page?.path : Current.page?.path;
552
+ const id = path?.replace(/([^a-z0-9\u00a0-\uffff_-])/ig, '\\$1');
553
+ if (page) {
554
+ return document.querySelector(`.taro_page#${id}`);
2318
555
  }
2319
-
2320
- this.lastUnloadPage = page;
2321
- var pageEl = this.getPageContainer(page);
2322
- pageEl === null || pageEl === void 0 ? void 0 : pageEl.classList.remove('taro_page_stationed');
2323
- pageEl === null || pageEl === void 0 ? void 0 : pageEl.classList.remove('taro_page_show');
2324
- this.unloadTimer = setTimeout(function () {
2325
- var _this3$lastUnloadPage, _this3$lastUnloadPage2;
2326
-
2327
- _this3.unloadTimer = null;
2328
- (_this3$lastUnloadPage = _this3.lastUnloadPage) === null || _this3$lastUnloadPage === void 0 ? void 0 : (_this3$lastUnloadPage2 = _this3$lastUnloadPage.onUnload) === null || _this3$lastUnloadPage2 === void 0 ? void 0 : _this3$lastUnloadPage2.call(_this3$lastUnloadPage);
2329
- }, this.animationDuration);
2330
- } else {
2331
- var _page$onUnload;
2332
-
2333
- var _pageEl2 = this.getPageContainer(page);
2334
-
2335
- _pageEl2 === null || _pageEl2 === void 0 ? void 0 : _pageEl2.classList.remove('taro_page_stationed');
2336
- _pageEl2 === null || _pageEl2 === void 0 ? void 0 : _pageEl2.classList.remove('taro_page_show');
2337
- page === null || page === void 0 ? void 0 : (_page$onUnload = page.onUnload) === null || _page$onUnload === void 0 ? void 0 : _page$onUnload.call(page);
2338
- }
2339
-
2340
- if (delta >= 1) this.unload(stacks.last, delta);
2341
- }
2342
- }, {
2343
- key: "show",
2344
- value: function show(page) {
2345
- var _this4 = this;
2346
-
2347
- var pageConfig = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2348
- var stacksIndex = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
2349
- if (!page) return;
2350
- var param = this.getQuery(stacks.length, '', page.options);
2351
- var pageEl = this.getPageContainer(page);
2352
-
2353
- if (pageEl) {
2354
- var _page$onShow3;
2355
-
2356
- setDisplay(pageEl);
2357
- this.addAnimation(pageEl, stacksIndex === 0);
2358
- (_page$onShow3 = page.onShow) === null || _page$onShow3 === void 0 ? void 0 : _page$onShow3.call(page);
2359
- this.bindPageEvents(page, pageEl, pageConfig);
2360
- } else {
2361
- var _page$onLoad2;
2362
-
2363
- (_page$onLoad2 = page.onLoad) === null || _page$onLoad2 === void 0 ? void 0 : _page$onLoad2.call(page, param, function () {
2364
- var _page$onShow4;
2365
-
2366
- pageEl = _this4.getPageContainer(page);
2367
-
2368
- _this4.addAnimation(pageEl, stacksIndex === 0);
2369
-
2370
- _this4.onReady(page, false);
2371
-
2372
- (_page$onShow4 = page.onShow) === null || _page$onShow4 === void 0 ? void 0 : _page$onShow4.call(page);
2373
-
2374
- _this4.bindPageEvents(page, pageEl, pageConfig);
2375
- });
2376
- }
2377
- }
2378
- }, {
2379
- key: "hide",
2380
- value: function hide(page) {
2381
- var _this5 = this;
2382
-
2383
- if (!page) return; // NOTE: 修复多页并发问题,此处可能因为路由跳转过快,执行时页面可能还没有创建成功
2384
-
2385
- var pageEl = this.getPageContainer(page);
2386
-
2387
- if (pageEl) {
2388
- var _page$onHide;
2389
-
2390
- if (this.hideTimer) {
2391
- clearTimeout(this.hideTimer);
2392
- this.hideTimer = null;
2393
- setDisplay(this.lastHidePage, 'none');
556
+ const el = (id
557
+ ? document.querySelector(`.taro_page#${id}`)
558
+ : document.querySelector('.taro_page') ||
559
+ document.querySelector('.taro_router'));
560
+ return el || window;
561
+ }
562
+ bindPageEvents(page, pageEl, config = {}) {
563
+ if (!pageEl) {
564
+ pageEl = this.getPageContainer();
2394
565
  }
2395
-
2396
- this.lastHidePage = pageEl;
2397
- this.hideTimer = setTimeout(function () {
2398
- _this5.hideTimer = null;
2399
- setDisplay(_this5.lastHidePage, 'none');
2400
- }, this.animationDuration + this.animationDelay);
2401
- (_page$onHide = page.onHide) === null || _page$onHide === void 0 ? void 0 : _page$onHide.call(page);
2402
- } else {
2403
- setTimeout(function () {
2404
- return _this5.hide(page);
2405
- }, 0);
2406
- }
566
+ const distance = config.onReachBottomDistance || this.config.window?.onReachBottomDistance || 50;
567
+ bindPageScroll(page, pageEl, distance);
568
+ bindPageResize(page);
2407
569
  }
2408
- }, {
2409
- key: "addAnimation",
2410
- value: function addAnimation(pageEl) {
2411
- var _this6 = this;
2412
-
2413
- var first = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
2414
- if (!pageEl) return;
2415
-
2416
- if (this.animation && !first) {
2417
- setTimeout(function () {
2418
- pageEl.classList.add('taro_page_show');
2419
- setTimeout(function () {
2420
- pageEl.classList.add('taro_page_stationed');
2421
- }, _this6.animationDuration);
2422
- }, this.animationDelay);
2423
- } else {
2424
- pageEl.classList.add('taro_page_show');
2425
- pageEl.classList.add('taro_page_stationed');
2426
- }
2427
- }
2428
- }, {
2429
- key: "getPageContainer",
2430
- value: function getPageContainer(page) {
2431
- var _Current$page;
2432
-
2433
- var path = page ? page === null || page === void 0 ? void 0 : page.path : (_Current$page = Current.page) === null || _Current$page === void 0 ? void 0 : _Current$page.path;
2434
- var id = path === null || path === void 0 ? void 0 : path.replace(/([^a-z0-9\u00a0-\uffff_-])/ig, '\\$1');
2435
-
2436
- if (page) {
2437
- return document.querySelector(".taro_page#".concat(id));
2438
- }
2439
-
2440
- var el = id ? document.querySelector(".taro_page#".concat(id)) : document.querySelector('.taro_page') || document.querySelector('.taro_router');
2441
- return el || window;
2442
- }
2443
- }, {
2444
- key: "bindPageEvents",
2445
- value: function bindPageEvents(page, pageEl) {
2446
- var _this$config$window;
2447
-
2448
- var config = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2449
-
2450
- if (!pageEl) {
2451
- pageEl = this.getPageContainer();
2452
- }
2453
-
2454
- var distance = config.onReachBottomDistance || ((_this$config$window = this.config.window) === null || _this$config$window === void 0 ? void 0 : _this$config$window.onReachBottomDistance) || 50;
2455
- bindPageScroll(page, pageEl, distance);
2456
- bindPageResize(page);
2457
- }
2458
- }]);
2459
-
2460
- return PageHandler;
2461
- }();
570
+ }
2462
571
 
572
+ /* eslint-disable dot-notation */
2463
573
  function createRouter(app, config, framework) {
2464
- var _routes$0$path, _app$onLaunch, _app$onShow;
2465
-
2466
- var handler = new PageHandler(config);
2467
- var runtimeHooks = container.get(SERVICE_IDENTIFIER.Hooks);
2468
- routesAlias.set(handler.router.customRoutes);
2469
- var basename = handler.router.basename;
2470
- var routes = handler.routes.map(function (route) {
2471
- return {
2472
- path: routesAlias.getAll(addLeadingSlash(route.path)),
2473
- action: route.load
2474
- };
2475
- });
2476
- var entryPagePath = config.entryPagePath || ((_routes$0$path = routes[0].path) === null || _routes$0$path === void 0 ? void 0 : _routes$0$path[0]);
2477
- var router = new UniversalRouter(routes, {
2478
- baseUrl: basename || ''
2479
- });
2480
- var launchParam = handler.getQuery(stacks.length);
2481
- (_app$onLaunch = app.onLaunch) === null || _app$onLaunch === void 0 ? void 0 : _app$onLaunch.call(app, launchParam);
2482
-
2483
- var render = /*#__PURE__*/function () {
2484
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref) {
2485
- var _config$window;
2486
-
2487
- var location, action, element, _app$onPageNotFound, pageConfig, enablePullDownRefresh, _pageConfig$navigatio, currentPage, pathname, shouldLoad, prevIndex, delta, _prevIndex, _delta, _element$default, _runtimeHooks$createP, el, loadConfig, stacksIndex, page;
2488
-
2489
- return _regeneratorRuntime.wrap(function _callee$(_context) {
2490
- while (1) {
2491
- switch (_context.prev = _context.next) {
2492
- case 0:
2493
- location = _ref.location, action = _ref.action;
2494
- handler.pathname = location.pathname;
2495
- _context.prev = 2;
2496
- _context.next = 5;
2497
- return router.resolve(handler.router.forcePath || handler.pathname);
2498
-
2499
- case 5:
2500
- element = _context.sent;
2501
- _context.next = 15;
2502
- break;
2503
-
2504
- case 8:
2505
- _context.prev = 8;
2506
- _context.t0 = _context["catch"](2);
2507
-
2508
- if (!(_context.t0.status === 404)) {
2509
- _context.next = 14;
2510
- break;
2511
- }
2512
-
2513
- (_app$onPageNotFound = app.onPageNotFound) === null || _app$onPageNotFound === void 0 ? void 0 : _app$onPageNotFound.call(app, {
574
+ const handler = new PageHandler(config);
575
+ const runtimeHooks = container.get(SERVICE_IDENTIFIER.Hooks);
576
+ routesAlias.set(handler.router.customRoutes);
577
+ const basename = handler.router.basename;
578
+ const routes = handler.routes.map(route => ({
579
+ path: routesAlias.getAll(addLeadingSlash(route.path)),
580
+ action: route.load
581
+ }));
582
+ const entryPagePath = config.entryPagePath || routes[0].path?.[0];
583
+ const router = new UniversalRouter(routes, { baseUrl: basename || '' });
584
+ const launchParam = handler.getQuery(stacks.length);
585
+ app.onLaunch?.(launchParam);
586
+ const render = async ({ location, action }) => {
587
+ handler.pathname = location.pathname;
588
+ let element;
589
+ try {
590
+ element = await router.resolve(handler.router.forcePath || handler.pathname);
591
+ }
592
+ catch (error) {
593
+ if (error.status === 404) {
594
+ app.onPageNotFound?.({
595
+ path: handler.pathname
596
+ });
597
+ }
598
+ else {
599
+ throw new Error(error);
600
+ }
601
+ }
602
+ if (!element)
603
+ return;
604
+ const pageConfig = handler.pageConfig;
605
+ let enablePullDownRefresh = config?.window?.enablePullDownRefresh || false;
606
+ eventCenter.trigger('__taroRouterChange', {
607
+ toLocation: {
2514
608
  path: handler.pathname
2515
- });
2516
- _context.next = 15;
2517
- break;
2518
-
2519
- case 14:
2520
- throw new Error(_context.t0);
2521
-
2522
- case 15:
2523
- if (element) {
2524
- _context.next = 17;
2525
- break;
2526
- }
2527
-
2528
- return _context.abrupt("return");
2529
-
2530
- case 17:
2531
- pageConfig = handler.pageConfig;
2532
- enablePullDownRefresh = (config === null || config === void 0 ? void 0 : (_config$window = config.window) === null || _config$window === void 0 ? void 0 : _config$window.enablePullDownRefresh) || false;
2533
- eventCenter.trigger('__taroRouterChange', {
2534
- toLocation: {
2535
- path: handler.pathname
2536
- }
2537
- });
2538
-
2539
- if (pageConfig) {
2540
- document.title = (_pageConfig$navigatio = pageConfig.navigationBarTitleText) !== null && _pageConfig$navigatio !== void 0 ? _pageConfig$navigatio : document.title;
2541
-
2542
- if (typeof pageConfig.enablePullDownRefresh === 'boolean') {
2543
- enablePullDownRefresh = pageConfig.enablePullDownRefresh;
2544
- }
2545
- }
2546
-
2547
- currentPage = Current.page;
2548
- pathname = handler.pathname;
2549
- shouldLoad = false;
2550
-
2551
- if (!(action === 'POP')) {
2552
- _context.next = 31;
2553
- break;
2554
- }
2555
-
2556
- // NOTE: 浏览器事件退后多次时,该事件只会被触发一次
2557
- prevIndex = stacks.getPrevIndex(pathname);
2558
- delta = stacks.getDelta(pathname);
2559
- handler.unload(currentPage, delta, prevIndex > -1);
2560
-
2561
- if (prevIndex > -1) {
609
+ }
610
+ });
611
+ if (pageConfig) {
612
+ document.title = pageConfig.navigationBarTitleText ?? document.title;
613
+ if (typeof pageConfig.enablePullDownRefresh === 'boolean') {
614
+ enablePullDownRefresh = pageConfig.enablePullDownRefresh;
615
+ }
616
+ }
617
+ const currentPage = Current.page;
618
+ const pathname = handler.pathname;
619
+ let shouldLoad = false;
620
+ if (action === 'POP') {
621
+ // NOTE: 浏览器事件退后多次时,该事件只会被触发一次
622
+ const prevIndex = stacks.getPrevIndex(pathname);
623
+ const delta = stacks.getDelta(pathname);
624
+ handler.unload(currentPage, delta, prevIndex > -1);
625
+ if (prevIndex > -1) {
2562
626
  handler.show(stacks.getItem(prevIndex), pageConfig, prevIndex);
2563
- } else {
627
+ }
628
+ else {
2564
629
  shouldLoad = true;
2565
- }
2566
-
2567
- _context.next = 42;
2568
- break;
2569
-
2570
- case 31:
2571
- if (!handler.isTabBar) {
2572
- _context.next = 40;
2573
- break;
2574
- }
2575
-
2576
- if (!handler.isSamePage(currentPage)) {
2577
- _context.next = 34;
2578
- break;
2579
- }
2580
-
2581
- return _context.abrupt("return");
2582
-
2583
- case 34:
2584
- _prevIndex = stacks.getPrevIndex(pathname, 0);
2585
- handler.hide(currentPage);
2586
-
2587
- if (!(_prevIndex > -1)) {
2588
- _context.next = 38;
2589
- break;
2590
- }
2591
-
2592
- return _context.abrupt("return", handler.show(stacks.getItem(_prevIndex), pageConfig, _prevIndex));
2593
-
2594
- case 38:
2595
- _context.next = 41;
2596
- break;
2597
-
2598
- case 40:
2599
- if (action === 'REPLACE') {
2600
- _delta = stacks.getDelta(pathname); // NOTE: 页面路由记录并不会清空,只是移除掉缓存的 stack 以及页面
2601
-
2602
- handler.unload(currentPage, _delta);
2603
- } else if (action === 'PUSH') {
630
+ }
631
+ }
632
+ else {
633
+ if (handler.isTabBar) {
634
+ if (handler.isSamePage(currentPage))
635
+ return;
636
+ const prevIndex = stacks.getPrevIndex(pathname, 0);
2604
637
  handler.hide(currentPage);
2605
- }
2606
-
2607
- case 41:
2608
- shouldLoad = true;
2609
-
2610
- case 42:
2611
- if (!(shouldLoad || stacks.length < 1)) {
2612
- _context.next = 50;
2613
- break;
2614
- }
2615
-
2616
- el = (_element$default = element.default) !== null && _element$default !== void 0 ? _element$default : element;
2617
- loadConfig = _objectSpread({}, pageConfig);
2618
- stacksIndex = stacks.length;
2619
- delete loadConfig['path'];
2620
- delete loadConfig['load'];
2621
- page = createPageConfig(enablePullDownRefresh ? (_runtimeHooks$createP = runtimeHooks.createPullDownComponent) === null || _runtimeHooks$createP === void 0 ? void 0 : _runtimeHooks$createP.call(runtimeHooks, el, location.pathname, framework, handler.PullDownRefresh) : el, pathname + stringify(handler.getQuery(stacksIndex)), {}, loadConfig);
2622
- return _context.abrupt("return", handler.load(page, pageConfig, stacksIndex));
2623
-
2624
- case 50:
2625
- case "end":
2626
- return _context.stop();
2627
- }
638
+ if (prevIndex > -1) {
639
+ // NOTE: tabbar 页且之前出现过,直接复用
640
+ return handler.show(stacks.getItem(prevIndex), pageConfig, prevIndex);
641
+ }
642
+ }
643
+ else if (action === 'REPLACE') {
644
+ const delta = stacks.getDelta(pathname);
645
+ // NOTE: 页面路由记录并不会清空,只是移除掉缓存的 stack 以及页面
646
+ handler.unload(currentPage, delta);
647
+ }
648
+ else if (action === 'PUSH') {
649
+ handler.hide(currentPage);
650
+ }
651
+ shouldLoad = true;
652
+ }
653
+ if (shouldLoad || stacks.length < 1) {
654
+ const el = element.default ?? element;
655
+ const loadConfig = { ...pageConfig };
656
+ const stacksIndex = stacks.length;
657
+ delete loadConfig['path'];
658
+ delete loadConfig['load'];
659
+ const page = createPageConfig(enablePullDownRefresh ? runtimeHooks.createPullDownComponent?.(el, location.pathname, framework, handler.PullDownRefresh) : el, pathname + stringify(handler.getQuery(stacksIndex)), {}, loadConfig);
660
+ return handler.load(page, pageConfig, stacksIndex);
2628
661
  }
2629
- }, _callee, null, [[2, 8]]);
2630
- }));
2631
-
2632
- return function render(_x) {
2633
- return _ref2.apply(this, arguments);
2634
662
  };
2635
- }();
2636
-
2637
- if (history.location.pathname === '/') {
2638
- history.replace(prependBasename(entryPagePath + history.location.search));
2639
- }
2640
-
2641
- render({
2642
- location: history.location,
2643
- action: r.Push
2644
- });
2645
- (_app$onShow = app.onShow) === null || _app$onShow === void 0 ? void 0 : _app$onShow.call(app, launchParam);
2646
- return history.listen(render);
663
+ const stripped = stripBasename(history.location.pathname, handler.basename);
664
+ if (stripped === '/' || stripped === '') {
665
+ history.replace(prependBasename(entryPagePath + history.location.search));
666
+ }
667
+ render({ location: history.location, action: Action.Push });
668
+ app.onShow?.(launchParam);
669
+ return history.listen(render);
2647
670
  }
2648
671
 
2649
672
  export { createRouter, getCurrentPages, history, navigateBack, navigateTo, reLaunch, redirectTo, switchTab };