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