@tarojs/router 3.3.12 → 3.4.0-beta.0

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