@tarojs/router 3.5.0-canary.1 → 3.5.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.
Files changed (44) hide show
  1. package/dist/animation.d.ts +4 -0
  2. package/dist/animation.js +29 -0
  3. package/dist/api.d.ts +7 -0
  4. package/dist/api.js +103 -0
  5. package/dist/events/resize.d.ts +2 -0
  6. package/dist/events/resize.js +13 -0
  7. package/dist/events/scroll.d.ts +2 -0
  8. package/dist/events/scroll.js +31 -0
  9. package/dist/history.d.ts +5 -0
  10. package/dist/history.js +100 -0
  11. package/dist/index.cjs.d.ts +23 -0
  12. package/dist/index.cjs.js +1043 -0
  13. package/dist/index.cjs.js.map +1 -0
  14. package/dist/index.d.ts +4 -0
  15. package/dist/index.esm.d.ts +23 -0
  16. package/dist/index.esm.js +1026 -0
  17. package/dist/index.esm.js.map +1 -0
  18. package/dist/index.js +4 -2674
  19. package/dist/router/index.d.ts +11 -0
  20. package/dist/router/index.js +22 -0
  21. package/dist/router/mpa.d.ts +10 -0
  22. package/dist/router/mpa.js +62 -0
  23. package/dist/router/multi-page.d.ts +27 -0
  24. package/dist/router/multi-page.js +112 -0
  25. package/dist/router/page.d.ts +42 -0
  26. package/dist/router/page.js +281 -0
  27. package/dist/router/spa.d.ts +3 -0
  28. package/dist/router/spa.js +130 -0
  29. package/dist/router/stack.d.ts +18 -0
  30. package/dist/router/stack.js +59 -0
  31. package/dist/tabbar.d.ts +2 -0
  32. package/dist/tabbar.js +29 -0
  33. package/dist/utils/index.d.ts +15 -0
  34. package/dist/utils/index.js +47 -0
  35. package/dist/utils/navigate.d.ts +5 -0
  36. package/dist/utils/navigate.js +44 -0
  37. package/package.json +18 -17
  38. package/types/api.d.ts +13 -0
  39. package/types/history.d.ts +6 -0
  40. package/types/router.d.ts +30 -0
  41. package/dist/index.js.map +0 -1
  42. package/dist/router.esm.js +0 -2650
  43. package/dist/router.esm.js.map +0 -1
  44. package/types/index.d.ts +0 -287
@@ -0,0 +1,1043 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var history = require('history');
6
+ var runtime = require('@tarojs/runtime');
7
+ var MobileDetect = require('mobile-detect');
8
+ var queryString = require('query-string');
9
+ var taro = require('@tarojs/taro');
10
+ var UniversalRouter = require('universal-router');
11
+
12
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
13
+
14
+ var MobileDetect__default = /*#__PURE__*/_interopDefaultLegacy(MobileDetect);
15
+ var queryString__default = /*#__PURE__*/_interopDefaultLegacy(queryString);
16
+ var UniversalRouter__default = /*#__PURE__*/_interopDefaultLegacy(UniversalRouter);
17
+
18
+ /*! *****************************************************************************
19
+ Copyright (c) Microsoft Corporation.
20
+
21
+ Permission to use, copy, modify, and/or distribute this software for any
22
+ purpose with or without fee is hereby granted.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
25
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
26
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
27
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
28
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
29
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
30
+ PERFORMANCE OF THIS SOFTWARE.
31
+ ***************************************************************************** */
32
+
33
+ function __awaiter(thisArg, _arguments, P, generator) {
34
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
35
+ return new (P || (P = Promise))(function (resolve, reject) {
36
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
37
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
38
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
39
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
40
+ });
41
+ }
42
+
43
+ // export const removeLeadingSlash = (str = '') => str.replace(/^\.?\//, '')
44
+ // export const removeTrailingSearch = (str = '') => str.replace(/\?[\s\S]*$/, '')
45
+ const addLeadingSlash = (url = '') => (url.charAt(0) === '/' ? url : '/' + url);
46
+ const hasBasename = (path = '', prefix = '') => new RegExp('^' + prefix + '(\\/|\\?|#|$)', 'i').test(path) || path === prefix;
47
+ const stripBasename = (path = '', prefix = '') => hasBasename(path, prefix) ? path.substring(prefix.length) : path;
48
+ const stripTrailing = (str = '') => str.replace(/[?#][\s\S]*$/, '');
49
+ class RoutesAlias {
50
+ constructor() {
51
+ this.conf = [];
52
+ this.getConfig = (url = '') => {
53
+ const customRoute = this.conf.filter((arr) => {
54
+ return arr.includes(url);
55
+ });
56
+ return customRoute[0];
57
+ };
58
+ this.getOrigin = (url = '') => {
59
+ var _a;
60
+ return ((_a = this.getConfig(url)) === null || _a === void 0 ? void 0 : _a[0]) || url;
61
+ };
62
+ this.getAlias = (url = '') => {
63
+ var _a;
64
+ return ((_a = this.getConfig(url)) === null || _a === void 0 ? void 0 : _a[1]) || url;
65
+ };
66
+ this.getAll = (url = '') => {
67
+ return this.conf
68
+ .filter((arr) => arr.includes(url))
69
+ .reduceRight((p, a) => {
70
+ p.unshift(a[1]);
71
+ return p;
72
+ }, []);
73
+ };
74
+ }
75
+ set(customRoutes = {}) {
76
+ for (let key in customRoutes) {
77
+ const path = customRoutes[key];
78
+ key = addLeadingSlash(key);
79
+ if (typeof path === 'string') {
80
+ this.conf.push([key, addLeadingSlash(path)]);
81
+ }
82
+ else if ((path === null || path === void 0 ? void 0 : path.length) > 0) {
83
+ this.conf.push(...path.map(p => [key, addLeadingSlash(p)]));
84
+ }
85
+ }
86
+ }
87
+ }
88
+ const routesAlias = new RoutesAlias();
89
+
90
+ class RouterConfig {
91
+ static set config(e) {
92
+ this.__config = e;
93
+ }
94
+ static get config() {
95
+ return this.__config;
96
+ }
97
+ static get pages() {
98
+ return this.config.pages || [];
99
+ }
100
+ static get router() {
101
+ return this.config.router || {};
102
+ }
103
+ static get mode() {
104
+ return this.router.mode || 'hash';
105
+ }
106
+ static get customRoutes() { return this.router.customRoutes || {}; }
107
+ static isPage(url = '') {
108
+ return this.pages.findIndex(e => addLeadingSlash(e) === url) !== -1;
109
+ }
110
+ }
111
+
112
+ exports.history = void 0;
113
+ let basename = '/';
114
+ class MpaHistory {
115
+ constructor() {
116
+ this.back = window.history.back;
117
+ this.forward = window.history.forward;
118
+ this.pushState = this.eventState('pushState');
119
+ this.replaceState = this.eventState('replaceState');
120
+ }
121
+ get location() {
122
+ return {
123
+ pathname: window.location.pathname,
124
+ search: window.location.search,
125
+ hash: window.location.hash,
126
+ key: `${window.history.length}`,
127
+ state: window.history.state
128
+ };
129
+ }
130
+ createHref(_to) {
131
+ throw new Error('Method not implemented.');
132
+ }
133
+ parseUrl(to) {
134
+ let url = to.pathname || '';
135
+ if (RouterConfig.isPage(url)) {
136
+ url += '.html';
137
+ }
138
+ if (to.search) {
139
+ url += `?${to.search}`;
140
+ }
141
+ if (to.hash) {
142
+ url += `#${to.hash}`;
143
+ }
144
+ return url;
145
+ }
146
+ push(to, _state = {}) {
147
+ window.location.pathname = this.parseUrl(to);
148
+ // this.pushState(_state, '', this.parseUrl(to))
149
+ }
150
+ replace(to, _state = {}) {
151
+ window.location.replace(this.parseUrl(to));
152
+ // this.replaceState(_state, '', this.parseUrl(to))
153
+ }
154
+ go(delta) {
155
+ window.history.go(delta);
156
+ }
157
+ listen(listener) {
158
+ function callback(e) {
159
+ if (e.action === 'pushState') {
160
+ listener({ action: history.Action.Push, location: this.location });
161
+ }
162
+ else if (e.action === 'replaceState') {
163
+ listener({ action: history.Action.Replace, location: this.location });
164
+ }
165
+ else {
166
+ // NOTE: 这里包括 back、forward、go 三种可能,并非是 POP 事件
167
+ listener({ action: history.Action.Pop, location: this.location });
168
+ }
169
+ }
170
+ window.addEventListener('popstate', callback);
171
+ return () => {
172
+ window.removeEventListener('popstate', callback);
173
+ };
174
+ }
175
+ block(_blocker) {
176
+ throw new Error('Method not implemented.');
177
+ }
178
+ eventState(action) {
179
+ return (data, unused, url) => {
180
+ const wrapper = window.history[action](data, unused, url);
181
+ const evt = new Event(action);
182
+ evt.action = action;
183
+ evt.state = data;
184
+ evt.unused = unused;
185
+ evt.url = url;
186
+ window.dispatchEvent(evt);
187
+ return wrapper;
188
+ };
189
+ }
190
+ }
191
+ function setHistoryMode(mode, base = '/') {
192
+ const options = {
193
+ window
194
+ };
195
+ basename = base;
196
+ if (mode === 'browser') {
197
+ exports.history = history.createBrowserHistory(options);
198
+ }
199
+ else if (mode === 'multi') {
200
+ exports.history = new MpaHistory();
201
+ }
202
+ else {
203
+ // default is hash
204
+ exports.history = history.createHashHistory(options);
205
+ }
206
+ }
207
+ function prependBasename(url = '') {
208
+ return basename.replace(/\/$/, '') + '/' + url.replace(/^\//, '');
209
+ }
210
+
211
+ class Stacks {
212
+ constructor() {
213
+ this.stacks = [];
214
+ this.backDelta = 0;
215
+ }
216
+ set delta(delta) {
217
+ if (delta > 0) {
218
+ this.backDelta = delta;
219
+ }
220
+ else if (this.backDelta > 0) {
221
+ --this.backDelta;
222
+ }
223
+ else {
224
+ this.backDelta = 0;
225
+ }
226
+ }
227
+ get delta() {
228
+ return this.backDelta;
229
+ }
230
+ get length() {
231
+ return this.stacks.length;
232
+ }
233
+ get last() {
234
+ return this.stacks[this.length - 1];
235
+ }
236
+ get() {
237
+ return this.stacks;
238
+ }
239
+ getItem(index) {
240
+ return this.stacks[index];
241
+ }
242
+ getLastIndex(pathname, stateWith = 1) {
243
+ const list = [...this.stacks].reverse();
244
+ return list.findIndex((page, i) => { var _a; return i >= stateWith && ((_a = page.path) === null || _a === void 0 ? void 0 : _a.replace(/\?.*/g, '')) === pathname; });
245
+ }
246
+ getDelta(pathname) {
247
+ if (this.backDelta >= 1) {
248
+ return this.backDelta;
249
+ }
250
+ const index = this.getLastIndex(pathname);
251
+ // NOTE: 此处为了修复浏览器后退多级页面,在大量重复路由状况下可能出现判断错误的情况 (增强判断能力只能考虑在 query 中新增参数来判断,暂时搁置)
252
+ return index > 0 ? index : 1;
253
+ }
254
+ getPrevIndex(pathname, stateWith = 1) {
255
+ const lastIndex = this.getLastIndex(pathname, stateWith);
256
+ if (lastIndex < 0) {
257
+ return -1;
258
+ }
259
+ return this.length - 1 - lastIndex;
260
+ }
261
+ pop() {
262
+ return this.stacks.pop();
263
+ }
264
+ push(page) {
265
+ return this.stacks.push(page);
266
+ }
267
+ }
268
+ const stacks = new Stacks();
269
+
270
+ function processNavigateUrl(option) {
271
+ var _a;
272
+ const pathPieces = history.parsePath(option.url);
273
+ // 处理相对路径
274
+ if ((_a = pathPieces.pathname) === null || _a === void 0 ? void 0 : _a.includes('./')) {
275
+ const parts = routesAlias.getOrigin(exports.history.location.pathname).split('/');
276
+ parts.pop();
277
+ pathPieces.pathname.split('/').forEach((item) => {
278
+ if (item === '.') {
279
+ return;
280
+ }
281
+ item === '..' ? parts.pop() : parts.push(item);
282
+ });
283
+ pathPieces.pathname = parts.join('/');
284
+ }
285
+ // 处理自定义路由
286
+ pathPieces.pathname = routesAlias.getAlias(addLeadingSlash(pathPieces.pathname));
287
+ // 处理 basename
288
+ pathPieces.pathname = prependBasename(pathPieces.pathname);
289
+ // hack fix history v5 bug: https://github.com/remix-run/history/issues/814
290
+ if (!pathPieces.search)
291
+ pathPieces.search = '';
292
+ return pathPieces;
293
+ }
294
+ function navigate(option, method) {
295
+ return __awaiter(this, void 0, void 0, function* () {
296
+ return new Promise((resolve, reject) => {
297
+ const { success, complete, fail } = option;
298
+ const unListen = exports.history.listen(() => {
299
+ const res = { errMsg: `${method}:ok` };
300
+ success === null || success === void 0 ? void 0 : success(res);
301
+ complete === null || complete === void 0 ? void 0 : complete(res);
302
+ resolve(res);
303
+ unListen();
304
+ });
305
+ try {
306
+ if ('url' in option) {
307
+ const pathPieces = processNavigateUrl(option);
308
+ const state = { timestamp: Date.now() };
309
+ if (method === 'navigateTo') {
310
+ exports.history.push(pathPieces, state);
311
+ }
312
+ else if (method === 'redirectTo' || method === 'switchTab') {
313
+ exports.history.replace(pathPieces, state);
314
+ }
315
+ else if (method === 'reLaunch') {
316
+ stacks.delta = stacks.length;
317
+ exports.history.replace(pathPieces, state);
318
+ }
319
+ }
320
+ else if (method === 'navigateBack') {
321
+ stacks.delta = option.delta;
322
+ exports.history.go(-option.delta);
323
+ }
324
+ }
325
+ catch (error) {
326
+ const res = { errMsg: `${method}:fail ${error.message || error}` };
327
+ fail === null || fail === void 0 ? void 0 : fail(res);
328
+ complete === null || complete === void 0 ? void 0 : complete(res);
329
+ reject(res);
330
+ }
331
+ });
332
+ });
333
+ }
334
+ function navigateTo(option) {
335
+ return navigate(option, 'navigateTo');
336
+ }
337
+ function redirectTo(option) {
338
+ return navigate(option, 'redirectTo');
339
+ }
340
+ function navigateBack(option = { delta: 1 }) {
341
+ if (!option.delta || option.delta < 1) {
342
+ option.delta = 1;
343
+ }
344
+ return navigate(option, 'navigateBack');
345
+ }
346
+ function switchTab(option) {
347
+ return navigate(option, 'switchTab');
348
+ }
349
+ function reLaunch(option) {
350
+ return navigate(option, 'reLaunch');
351
+ }
352
+ function getCurrentPages() {
353
+ if (process.env.NODE_ENV === 'development' && RouterConfig.mode === 'multi') {
354
+ console.warn('多页面路由模式不支持使用 getCurrentPages 方法!');
355
+ }
356
+ const pages = stacks.get();
357
+ return pages.map(e => (Object.assign(Object.assign({}, e), { route: e.path || '' })));
358
+ }
359
+
360
+ let md;
361
+ let preTitle = document.title;
362
+ let isLoadDdEntry = false;
363
+ function getMobileDetect() {
364
+ if (!md) {
365
+ md = new MobileDetect__default["default"](navigator.userAgent);
366
+ }
367
+ return md;
368
+ }
369
+ function setTitle(title) {
370
+ return __awaiter(this, void 0, void 0, function* () {
371
+ if (preTitle === title)
372
+ return title;
373
+ document.title = title;
374
+ preTitle = title;
375
+ if (process.env.SUPPORT_DINGTALK_NAVIGATE !== 'disabled' && isDingTalk()) {
376
+ if (!isLoadDdEntry) {
377
+ isLoadDdEntry = true;
378
+ require('dingtalk-jsapi/platform');
379
+ }
380
+ const setDingTitle = require('dingtalk-jsapi/api/biz/navigation/setTitle').default;
381
+ setDingTitle({ title });
382
+ }
383
+ return title;
384
+ });
385
+ }
386
+ function isDingTalk() {
387
+ const md = getMobileDetect();
388
+ return md.match(/DingTalk/ig);
389
+ }
390
+
391
+ let pageResizeFn;
392
+ function bindPageResize(page) {
393
+ pageResizeFn && window.removeEventListener('resize', pageResizeFn);
394
+ pageResizeFn = function () {
395
+ page.onResize && page.onResize({
396
+ size: {
397
+ windowHeight: window.innerHeight,
398
+ windowWidth: window.innerWidth
399
+ }
400
+ });
401
+ };
402
+ window.addEventListener('resize', pageResizeFn, false);
403
+ }
404
+
405
+ let pageScrollFn;
406
+ let pageDOM = window;
407
+ function bindPageScroll(page, pageEl, distance = 50) {
408
+ pageScrollFn && pageEl.removeEventListener('scroll', pageScrollFn);
409
+ pageDOM = pageEl;
410
+ let isReachBottom = false;
411
+ pageScrollFn = function () {
412
+ var _a;
413
+ (_a = page.onPageScroll) === null || _a === void 0 ? void 0 : _a.call(page, {
414
+ scrollTop: pageDOM instanceof Window ? window.scrollY : pageDOM.scrollTop
415
+ });
416
+ if (isReachBottom && getOffset() > distance) {
417
+ isReachBottom = false;
418
+ }
419
+ if (page.onReachBottom &&
420
+ !isReachBottom &&
421
+ getOffset() < distance) {
422
+ isReachBottom = true;
423
+ page.onReachBottom();
424
+ }
425
+ };
426
+ pageDOM.addEventListener('scroll', pageScrollFn, false);
427
+ }
428
+ function getOffset() {
429
+ if (pageDOM instanceof Window) {
430
+ return document.documentElement.scrollHeight - window.scrollY - window.innerHeight;
431
+ }
432
+ else {
433
+ return pageDOM.scrollHeight - pageDOM.scrollTop - pageDOM.clientHeight;
434
+ }
435
+ }
436
+
437
+ // @ts-nocheck
438
+ function initTabbar(config) {
439
+ if (config.tabBar == null) {
440
+ return;
441
+ }
442
+ // TODO: custom-tab-bar
443
+ const tabbar = document.createElement('taro-tabbar');
444
+ const homePage = config.entryPagePath || (config.pages ? config.pages[0] : '');
445
+ tabbar.conf = config.tabBar;
446
+ tabbar.conf.homePage = exports.history.location.pathname === '/' ? homePage : exports.history.location.pathname;
447
+ const routerConfig = config.router;
448
+ tabbar.conf.mode = routerConfig && routerConfig.mode ? routerConfig.mode : 'hash';
449
+ if (routerConfig.customRoutes) {
450
+ tabbar.conf.custom = true;
451
+ tabbar.conf.customRoutes = routerConfig.customRoutes;
452
+ }
453
+ else {
454
+ tabbar.conf.custom = false;
455
+ tabbar.conf.customRoutes = {};
456
+ }
457
+ if (typeof routerConfig.basename !== 'undefined') {
458
+ tabbar.conf.basename = routerConfig.basename;
459
+ }
460
+ const container = document.getElementById('container');
461
+ container === null || container === void 0 ? void 0 : container.appendChild(tabbar);
462
+ taro.initTabBarApis(config);
463
+ }
464
+
465
+ /* eslint-disable dot-notation */
466
+ class MultiPageHandler {
467
+ constructor(config) {
468
+ this.config = config;
469
+ this.mount();
470
+ }
471
+ get appId() { return 'app'; }
472
+ get router() { return this.config.router || {}; }
473
+ get routerMode() { return this.router.mode || 'hash'; }
474
+ get customRoutes() { return this.router.customRoutes || {}; }
475
+ get tabBarList() { var _a; return ((_a = this.config.tabBar) === null || _a === void 0 ? void 0 : _a.list) || []; }
476
+ get PullDownRefresh() { return this.config.PullDownRefresh; }
477
+ set pathname(p) { this.router.pathname = p; }
478
+ get pathname() { return this.router.pathname; }
479
+ get basename() { return this.router.basename || ''; }
480
+ get pageConfig() { return this.config.route; }
481
+ get isTabBar() {
482
+ var _a;
483
+ const routePath = stripBasename(this.pathname, this.basename);
484
+ const pagePath = ((_a = Object.entries(this.customRoutes).find(([, target]) => {
485
+ if (typeof target === 'string') {
486
+ return target === routePath;
487
+ }
488
+ else if ((target === null || target === void 0 ? void 0 : target.length) > 0) {
489
+ return target.includes(routePath);
490
+ }
491
+ return false;
492
+ })) === null || _a === void 0 ? void 0 : _a[0]) || routePath;
493
+ return !!pagePath && this.tabBarList.some(t => t.pagePath === pagePath);
494
+ }
495
+ get search() { return location.search.substr(1); }
496
+ getQuery(search = '', options = {}) {
497
+ search = search ? `${search}&${this.search}` : this.search;
498
+ const query = search
499
+ ? queryString__default["default"].parse(search)
500
+ : {};
501
+ return Object.assign(Object.assign({}, query), options);
502
+ }
503
+ mount() {
504
+ var _a;
505
+ setHistoryMode(this.routerMode, this.router.basename);
506
+ (_a = document.getElementById('app')) === null || _a === void 0 ? void 0 : _a.remove();
507
+ const app = document.createElement('div');
508
+ app.id = this.appId;
509
+ app.classList.add('taro_router');
510
+ if (this.tabBarList.length > 1) {
511
+ const container = document.createElement('div');
512
+ container.classList.add('taro-tabbar__container');
513
+ container.id = 'container';
514
+ const panel = document.createElement('div');
515
+ panel.classList.add('taro-tabbar__panel');
516
+ panel.appendChild(app);
517
+ container.appendChild(panel);
518
+ document.body.appendChild(container);
519
+ initTabbar(this.config);
520
+ }
521
+ else {
522
+ document.body.appendChild(app);
523
+ }
524
+ }
525
+ onReady(page, onLoad = true) {
526
+ var _a;
527
+ const pageEl = this.getPageContainer(page);
528
+ if (pageEl && !(pageEl === null || pageEl === void 0 ? void 0 : pageEl['__isReady'])) {
529
+ const el = pageEl.firstElementChild;
530
+ (_a = el === null || el === void 0 ? void 0 : el['componentOnReady']) === null || _a === void 0 ? void 0 : _a.call(el);
531
+ onLoad && (pageEl['__page'] = page);
532
+ }
533
+ }
534
+ load(page, pageConfig = {}) {
535
+ var _a;
536
+ if (!page)
537
+ return;
538
+ (_a = page.onLoad) === null || _a === void 0 ? void 0 : _a.call(page, this.getQuery('', page.options), () => {
539
+ var _a;
540
+ const pageEl = this.getPageContainer(page);
541
+ this.isTabBar && (pageEl === null || pageEl === void 0 ? void 0 : pageEl.classList.add('taro_tabbar_page'));
542
+ this.onReady(page, true);
543
+ (_a = page.onShow) === null || _a === void 0 ? void 0 : _a.call(page);
544
+ this.bindPageEvents(page, pageEl, pageConfig);
545
+ });
546
+ }
547
+ getPageContainer(page) {
548
+ var _a;
549
+ const path = page ? page === null || page === void 0 ? void 0 : page.path : (_a = runtime.Current.page) === null || _a === void 0 ? void 0 : _a.path;
550
+ const id = path === null || path === void 0 ? void 0 : path.replace(/([^a-z0-9\u00a0-\uffff_-])/ig, '\\$1');
551
+ if (page) {
552
+ return document.querySelector(`.taro_page#${id}`);
553
+ }
554
+ const el = (id
555
+ ? document.querySelector(`.taro_page#${id}`)
556
+ : document.querySelector('.taro_page') ||
557
+ document.querySelector('.taro_router'));
558
+ return el || window;
559
+ }
560
+ bindPageEvents(page, pageEl, config = {}) {
561
+ var _a;
562
+ if (!pageEl) {
563
+ pageEl = this.getPageContainer();
564
+ }
565
+ const distance = config.onReachBottomDistance || ((_a = this.config.window) === null || _a === void 0 ? void 0 : _a.onReachBottomDistance) || 50;
566
+ bindPageScroll(page, pageEl, distance);
567
+ bindPageResize(page);
568
+ }
569
+ }
570
+
571
+ // TODO 支持多路由 (APP 生命周期仅触发一次)
572
+ /** Note: 关于多页面应用
573
+ * - 需要配置路由映射(根目录跳转、404 页面……)
574
+ * - app.onPageNotFound 事件不支持
575
+ * - 应用生命周期可能多次触发
576
+ * - TabBar 会多次加载
577
+ * - 不支持路由动画
578
+ */
579
+ function createMultiRouter(app, config, framework) {
580
+ var _a, _b, _c, _d, _e, _f;
581
+ return __awaiter(this, void 0, void 0, function* () {
582
+ RouterConfig.config = config;
583
+ const handler = new MultiPageHandler(config);
584
+ const launchParam = handler.getQuery();
585
+ (_a = app.onLaunch) === null || _a === void 0 ? void 0 : _a.call(app, launchParam);
586
+ app.onError && window.addEventListener('error', e => { var _a; return (_a = app.onError) === null || _a === void 0 ? void 0 : _a.call(app, e.message); });
587
+ const pathName = config.pageName;
588
+ const pageConfig = handler.pageConfig;
589
+ let element;
590
+ try {
591
+ element = yield ((_b = pageConfig.load) === null || _b === void 0 ? void 0 : _b.call(pageConfig));
592
+ }
593
+ catch (error) {
594
+ throw new Error(error);
595
+ }
596
+ if (!element)
597
+ return;
598
+ let enablePullDownRefresh = ((_c = config === null || config === void 0 ? void 0 : config.window) === null || _c === void 0 ? void 0 : _c.enablePullDownRefresh) || false;
599
+ runtime.eventCenter.trigger('__taroRouterChange', {
600
+ toLocation: {
601
+ path: pathName
602
+ }
603
+ });
604
+ if (pageConfig) {
605
+ setTitle((_d = pageConfig.navigationBarTitleText) !== null && _d !== void 0 ? _d : document.title);
606
+ if (typeof pageConfig.enablePullDownRefresh === 'boolean') {
607
+ enablePullDownRefresh = pageConfig.enablePullDownRefresh;
608
+ }
609
+ }
610
+ const el = (_e = element.default) !== null && _e !== void 0 ? _e : element;
611
+ const loadConfig = Object.assign({}, pageConfig);
612
+ delete loadConfig['path'];
613
+ delete loadConfig['load'];
614
+ const page = runtime.createPageConfig(enablePullDownRefresh ? runtime.hooks.call('createPullDownComponent', el, location.pathname, framework, config.PullDownRefresh) : el, pathName + runtime.stringify(launchParam), {}, loadConfig);
615
+ handler.load(page, pageConfig);
616
+ (_f = app.onShow) === null || _f === void 0 ? void 0 : _f.call(app, launchParam);
617
+ });
618
+ }
619
+
620
+ /**
621
+ * 插入页面动画需要的样式
622
+ */
623
+ function loadAnimateStyle(ms = 300) {
624
+ const css = `
625
+ .taro_router .taro_page {
626
+ position: absolute;
627
+ left: 0;
628
+ top: 0;
629
+ width: 100%;
630
+ height: 100%;
631
+ background-color: #fff;
632
+ transform: translate(100%, 0);
633
+ transition: transform ${ms}ms;
634
+ z-index: 0;
635
+ }
636
+
637
+ .taro_router .taro_page.taro_tabbar_page,
638
+ .taro_router .taro_page.taro_page_show.taro_page_stationed {
639
+ transform: none;
640
+ }
641
+
642
+ .taro_router .taro_page.taro_page_show {
643
+ transform: translate(0, 0);
644
+ }`;
645
+ const style = document.createElement('style');
646
+ style.innerHTML = css;
647
+ document.getElementsByTagName('head')[0].appendChild(style);
648
+ }
649
+
650
+ /* eslint-disable dot-notation */
651
+ function setDisplay(el, type = '') {
652
+ if (el) {
653
+ el.style.display = type;
654
+ }
655
+ }
656
+ class PageHandler {
657
+ constructor(config) {
658
+ this.defaultAnimation = { duration: 300, delay: 50 };
659
+ this.config = config;
660
+ this.mount();
661
+ }
662
+ get appId() { return 'app'; }
663
+ get router() { return this.config.router || {}; }
664
+ get routerMode() { return this.router.mode || 'hash'; }
665
+ get customRoutes() { return this.router.customRoutes || {}; }
666
+ get routes() { return this.config.routes || []; }
667
+ get tabBarList() { var _a; return ((_a = this.config.tabBar) === null || _a === void 0 ? void 0 : _a.list) || []; }
668
+ get PullDownRefresh() { return this.config.PullDownRefresh; }
669
+ get animation() { var _a, _b; return (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.animation) !== null && _b !== void 0 ? _b : this.defaultAnimation; }
670
+ get animationDelay() {
671
+ var _a;
672
+ return (typeof this.animation === 'object'
673
+ ? this.animation.delay
674
+ : this.animation
675
+ ? (_a = this.defaultAnimation) === null || _a === void 0 ? void 0 : _a.delay
676
+ : 0) || 0;
677
+ }
678
+ get animationDuration() {
679
+ var _a;
680
+ return (typeof this.animation === 'object'
681
+ ? this.animation.duration
682
+ : this.animation
683
+ ? (_a = this.defaultAnimation) === null || _a === void 0 ? void 0 : _a.duration
684
+ : 0) || 0;
685
+ }
686
+ set pathname(p) { this.router.pathname = p; }
687
+ get pathname() { return this.router.pathname; }
688
+ get basename() { return this.router.basename || ''; }
689
+ get homePage() {
690
+ return this.config.entryPagePath || this.routes[0].path || this.basename;
691
+ }
692
+ get pageConfig() {
693
+ const routePath = stripBasename(this.pathname, this.basename);
694
+ const homePage = this.homePage;
695
+ return this.routes.find(r => {
696
+ var _a;
697
+ const pagePath = addLeadingSlash(r.path);
698
+ return [pagePath, homePage].includes(routePath) || ((_a = routesAlias.getConfig(pagePath)) === null || _a === void 0 ? void 0 : _a.includes(routePath));
699
+ });
700
+ }
701
+ get isTabBar() {
702
+ var _a;
703
+ const routePath = stripBasename(this.pathname, this.basename);
704
+ const pagePath = ((_a = Object.entries(this.customRoutes).find(([, target]) => {
705
+ if (typeof target === 'string') {
706
+ return target === routePath;
707
+ }
708
+ else if ((target === null || target === void 0 ? void 0 : target.length) > 0) {
709
+ return target.includes(routePath);
710
+ }
711
+ return false;
712
+ })) === null || _a === void 0 ? void 0 : _a[0]) || routePath;
713
+ return !!pagePath && this.tabBarList.some(t => stripTrailing(t.pagePath) === pagePath);
714
+ }
715
+ isSamePage(page) {
716
+ const routePath = stripBasename(this.pathname, this.basename);
717
+ const pagePath = stripBasename(page === null || page === void 0 ? void 0 : page.path, this.basename);
718
+ return pagePath.startsWith(routePath + '?');
719
+ }
720
+ get search() {
721
+ let search = '?';
722
+ if (this.routerMode === 'hash') {
723
+ const idx = location.hash.indexOf('?');
724
+ if (idx > -1) {
725
+ search = location.hash.slice(idx);
726
+ }
727
+ }
728
+ else {
729
+ search = location.search;
730
+ }
731
+ return search.substr(1);
732
+ }
733
+ getQuery(stamp = 0, search = '', options = {}) {
734
+ search = search ? `${search}&${this.search}` : this.search;
735
+ const query = search
736
+ ? queryString__default["default"].parse(search, { decode: false })
737
+ : {};
738
+ query.stamp = stamp.toString();
739
+ return Object.assign(Object.assign({}, query), options);
740
+ }
741
+ mount() {
742
+ var _a;
743
+ setHistoryMode(this.routerMode, this.router.basename);
744
+ (_a = document.getElementById('app')) === null || _a === void 0 ? void 0 : _a.remove();
745
+ this.animation && loadAnimateStyle(this.animationDuration);
746
+ const app = document.createElement('div');
747
+ app.id = this.appId;
748
+ app.classList.add('taro_router');
749
+ if (this.tabBarList.length > 1) {
750
+ const container = document.createElement('div');
751
+ container.classList.add('taro-tabbar__container');
752
+ container.id = 'container';
753
+ const panel = document.createElement('div');
754
+ panel.classList.add('taro-tabbar__panel');
755
+ panel.appendChild(app);
756
+ container.appendChild(panel);
757
+ document.body.appendChild(container);
758
+ initTabbar(this.config);
759
+ }
760
+ else {
761
+ document.body.appendChild(app);
762
+ }
763
+ }
764
+ onReady(page, onLoad = true) {
765
+ var _a, _b;
766
+ const pageEl = this.getPageContainer(page);
767
+ if (pageEl && !(pageEl === null || pageEl === void 0 ? void 0 : pageEl['__isReady'])) {
768
+ const el = pageEl.firstElementChild;
769
+ (_b = (_a = el === null || el === void 0 ? void 0 : el['componentOnReady']) === null || _a === void 0 ? void 0 : _a.call(el)) === null || _b === void 0 ? void 0 : _b.then(() => {
770
+ runtime.requestAnimationFrame(() => {
771
+ var _a;
772
+ (_a = page.onReady) === null || _a === void 0 ? void 0 : _a.call(page);
773
+ pageEl['__isReady'] = true;
774
+ });
775
+ });
776
+ onLoad && (pageEl['__page'] = page);
777
+ }
778
+ }
779
+ load(page, pageConfig = {}, stacksIndex = 0) {
780
+ var _a, _b;
781
+ if (!page)
782
+ return;
783
+ // NOTE: 页面栈推入太晚可能导致 getCurrentPages 无法获取到当前页面实例
784
+ stacks.push(page);
785
+ const param = this.getQuery(stacks.length, '', page.options);
786
+ let pageEl = this.getPageContainer(page);
787
+ if (pageEl) {
788
+ setDisplay(pageEl);
789
+ this.isTabBar && pageEl.classList.add('taro_tabbar_page');
790
+ this.addAnimation(pageEl, stacksIndex === 0);
791
+ (_a = page.onShow) === null || _a === void 0 ? void 0 : _a.call(page);
792
+ this.bindPageEvents(page, pageEl, pageConfig);
793
+ }
794
+ else {
795
+ (_b = page.onLoad) === null || _b === void 0 ? void 0 : _b.call(page, param, () => {
796
+ var _a;
797
+ pageEl = this.getPageContainer(page);
798
+ this.isTabBar && (pageEl === null || pageEl === void 0 ? void 0 : pageEl.classList.add('taro_tabbar_page'));
799
+ this.addAnimation(pageEl, stacksIndex === 0);
800
+ this.onReady(page, true);
801
+ (_a = page.onShow) === null || _a === void 0 ? void 0 : _a.call(page);
802
+ this.bindPageEvents(page, pageEl, pageConfig);
803
+ });
804
+ }
805
+ }
806
+ unload(page, delta = 1, top = false) {
807
+ var _a, _b, _c;
808
+ if (!page)
809
+ return;
810
+ stacks.delta = --delta;
811
+ stacks.pop();
812
+ if (this.animation && top) {
813
+ if (this.unloadTimer) {
814
+ clearTimeout(this.unloadTimer);
815
+ (_b = (_a = this.lastUnloadPage) === null || _a === void 0 ? void 0 : _a.onUnload) === null || _b === void 0 ? void 0 : _b.call(_a);
816
+ this.unloadTimer = null;
817
+ }
818
+ this.lastUnloadPage = page;
819
+ const pageEl = this.getPageContainer(page);
820
+ pageEl === null || pageEl === void 0 ? void 0 : pageEl.classList.remove('taro_page_stationed');
821
+ pageEl === null || pageEl === void 0 ? void 0 : pageEl.classList.remove('taro_page_show');
822
+ this.unloadTimer = setTimeout(() => {
823
+ var _a, _b;
824
+ this.unloadTimer = null;
825
+ (_b = (_a = this.lastUnloadPage) === null || _a === void 0 ? void 0 : _a.onUnload) === null || _b === void 0 ? void 0 : _b.call(_a);
826
+ }, this.animationDuration);
827
+ }
828
+ else {
829
+ const pageEl = this.getPageContainer(page);
830
+ pageEl === null || pageEl === void 0 ? void 0 : pageEl.classList.remove('taro_page_stationed');
831
+ pageEl === null || pageEl === void 0 ? void 0 : pageEl.classList.remove('taro_page_show');
832
+ (_c = page === null || page === void 0 ? void 0 : page.onUnload) === null || _c === void 0 ? void 0 : _c.call(page);
833
+ }
834
+ if (delta >= 1)
835
+ this.unload(stacks.last, delta);
836
+ }
837
+ show(page, pageConfig = {}, stacksIndex = 0) {
838
+ var _a, _b;
839
+ if (!page)
840
+ return;
841
+ const param = this.getQuery(stacks.length, '', page.options);
842
+ let pageEl = this.getPageContainer(page);
843
+ if (pageEl) {
844
+ setDisplay(pageEl);
845
+ this.addAnimation(pageEl, stacksIndex === 0);
846
+ (_a = page.onShow) === null || _a === void 0 ? void 0 : _a.call(page);
847
+ this.bindPageEvents(page, pageEl, pageConfig);
848
+ }
849
+ else {
850
+ (_b = page.onLoad) === null || _b === void 0 ? void 0 : _b.call(page, param, () => {
851
+ var _a;
852
+ pageEl = this.getPageContainer(page);
853
+ this.addAnimation(pageEl, stacksIndex === 0);
854
+ this.onReady(page, false);
855
+ (_a = page.onShow) === null || _a === void 0 ? void 0 : _a.call(page);
856
+ this.bindPageEvents(page, pageEl, pageConfig);
857
+ });
858
+ }
859
+ }
860
+ hide(page) {
861
+ var _a;
862
+ if (!page)
863
+ return;
864
+ // NOTE: 修复多页并发问题,此处可能因为路由跳转过快,执行时页面可能还没有创建成功
865
+ const pageEl = this.getPageContainer(page);
866
+ if (pageEl) {
867
+ if (this.hideTimer) {
868
+ clearTimeout(this.hideTimer);
869
+ this.hideTimer = null;
870
+ setDisplay(this.lastHidePage, 'none');
871
+ }
872
+ this.lastHidePage = pageEl;
873
+ this.hideTimer = setTimeout(() => {
874
+ this.hideTimer = null;
875
+ setDisplay(this.lastHidePage, 'none');
876
+ }, this.animationDuration + this.animationDelay);
877
+ (_a = page.onHide) === null || _a === void 0 ? void 0 : _a.call(page);
878
+ }
879
+ else {
880
+ setTimeout(() => this.hide(page), 0);
881
+ }
882
+ }
883
+ addAnimation(pageEl, first = false) {
884
+ if (!pageEl)
885
+ return;
886
+ if (this.animation && !first) {
887
+ setTimeout(() => {
888
+ pageEl.classList.add('taro_page_show');
889
+ setTimeout(() => {
890
+ pageEl.classList.add('taro_page_stationed');
891
+ }, this.animationDuration);
892
+ }, this.animationDelay);
893
+ }
894
+ else {
895
+ pageEl.classList.add('taro_page_show');
896
+ pageEl.classList.add('taro_page_stationed');
897
+ }
898
+ }
899
+ getPageContainer(page) {
900
+ var _a;
901
+ const path = page ? page === null || page === void 0 ? void 0 : page.path : (_a = runtime.Current.page) === null || _a === void 0 ? void 0 : _a.path;
902
+ const id = path === null || path === void 0 ? void 0 : path.replace(/([^a-z0-9\u00a0-\uffff_-])/ig, '\\$1');
903
+ if (page) {
904
+ return document.querySelector(`.taro_page#${id}`);
905
+ }
906
+ const el = (id
907
+ ? document.querySelector(`.taro_page#${id}`)
908
+ : document.querySelector('.taro_page') ||
909
+ document.querySelector('.taro_router'));
910
+ return el || window;
911
+ }
912
+ bindPageEvents(page, pageEl, config = {}) {
913
+ var _a;
914
+ if (!pageEl) {
915
+ pageEl = this.getPageContainer();
916
+ }
917
+ const distance = config.onReachBottomDistance || ((_a = this.config.window) === null || _a === void 0 ? void 0 : _a.onReachBottomDistance) || 50;
918
+ bindPageScroll(page, pageEl, distance);
919
+ bindPageResize(page);
920
+ }
921
+ }
922
+
923
+ function createRouter(app, config, framework) {
924
+ var _a, _b;
925
+ RouterConfig.config = config;
926
+ const handler = new PageHandler(config);
927
+ routesAlias.set(handler.router.customRoutes);
928
+ const basename = handler.router.basename;
929
+ const routes = handler.routes.map(route => {
930
+ const routePath = addLeadingSlash(route.path);
931
+ const paths = routesAlias.getAll(routePath);
932
+ return {
933
+ path: paths.length < 1 ? routePath : paths,
934
+ action: route.load
935
+ };
936
+ });
937
+ const router = new UniversalRouter__default["default"](routes, { baseUrl: basename || '' });
938
+ const launchParam = handler.getQuery(stacks.length);
939
+ (_a = app.onLaunch) === null || _a === void 0 ? void 0 : _a.call(app, launchParam);
940
+ app.onError && window.addEventListener('error', e => { var _a; return (_a = app.onError) === null || _a === void 0 ? void 0 : _a.call(app, e.message); });
941
+ const render = ({ location, action }) => __awaiter(this, void 0, void 0, function* () {
942
+ var _c, _d, _e, _f, _g;
943
+ handler.pathname = decodeURI(location.pathname);
944
+ let element, params;
945
+ try {
946
+ const result = yield router.resolve(handler.router.forcePath || handler.pathname);
947
+ [element, , params] = yield Promise.all(result);
948
+ }
949
+ catch (error) {
950
+ if (error.status === 404) {
951
+ (_c = app.onPageNotFound) === null || _c === void 0 ? void 0 : _c.call(app, {
952
+ path: handler.pathname
953
+ });
954
+ }
955
+ else {
956
+ throw new Error(error);
957
+ }
958
+ }
959
+ if (!element)
960
+ return;
961
+ const pageConfig = handler.pageConfig;
962
+ let enablePullDownRefresh = ((_d = config === null || config === void 0 ? void 0 : config.window) === null || _d === void 0 ? void 0 : _d.enablePullDownRefresh) || false;
963
+ runtime.eventCenter.trigger('__taroRouterChange', {
964
+ toLocation: {
965
+ path: handler.pathname
966
+ }
967
+ });
968
+ if (pageConfig) {
969
+ document.title = (_e = pageConfig.navigationBarTitleText) !== null && _e !== void 0 ? _e : document.title;
970
+ setTitle((_f = pageConfig.navigationBarTitleText) !== null && _f !== void 0 ? _f : document.title);
971
+ if (typeof pageConfig.enablePullDownRefresh === 'boolean') {
972
+ enablePullDownRefresh = pageConfig.enablePullDownRefresh;
973
+ }
974
+ }
975
+ const currentPage = runtime.Current.page;
976
+ const pathname = handler.pathname;
977
+ let shouldLoad = false;
978
+ if (action === 'POP') {
979
+ // NOTE: 浏览器事件退后多次时,该事件只会被触发一次
980
+ const prevIndex = stacks.getPrevIndex(pathname);
981
+ const delta = stacks.getDelta(pathname);
982
+ // NOTE: Safari 内核浏览器在非应用页面返回上一页时,会触发额外的 POP 事件,此处需避免当前页面被错误卸载
983
+ if (currentPage !== stacks.getItem(prevIndex)) {
984
+ handler.unload(currentPage, delta, prevIndex > -1);
985
+ if (prevIndex > -1) {
986
+ handler.show(stacks.getItem(prevIndex), pageConfig, prevIndex);
987
+ }
988
+ else {
989
+ shouldLoad = true;
990
+ }
991
+ }
992
+ }
993
+ else {
994
+ if (handler.isTabBar) {
995
+ if (handler.isSamePage(currentPage))
996
+ return;
997
+ const prevIndex = stacks.getPrevIndex(pathname, 0);
998
+ handler.hide(currentPage);
999
+ if (prevIndex > -1) {
1000
+ // NOTE: tabbar 页且之前出现过,直接复用
1001
+ return handler.show(stacks.getItem(prevIndex), pageConfig, prevIndex);
1002
+ }
1003
+ }
1004
+ else if (action === 'REPLACE') {
1005
+ const delta = stacks.getDelta(pathname);
1006
+ // NOTE: 页面路由记录并不会清空,只是移除掉缓存的 stack 以及页面
1007
+ handler.unload(currentPage, delta);
1008
+ }
1009
+ else if (action === 'PUSH') {
1010
+ handler.hide(currentPage);
1011
+ }
1012
+ shouldLoad = true;
1013
+ }
1014
+ if (shouldLoad || stacks.length < 1) {
1015
+ const el = (_g = element.default) !== null && _g !== void 0 ? _g : element;
1016
+ const loadConfig = Object.assign({}, pageConfig);
1017
+ const stacksIndex = stacks.length;
1018
+ delete loadConfig['path'];
1019
+ delete loadConfig['load'];
1020
+ const page = runtime.createPageConfig(enablePullDownRefresh ? runtime.hooks.call('createPullDownComponent', el, location.pathname, framework, handler.PullDownRefresh) : el, pathname + runtime.stringify(handler.getQuery(stacksIndex)), {}, loadConfig);
1021
+ if (params)
1022
+ page.options = params;
1023
+ return handler.load(page, pageConfig, stacksIndex);
1024
+ }
1025
+ });
1026
+ const routePath = stripBasename(exports.history.location.pathname, handler.basename);
1027
+ if (routePath === '/' || routePath === '') {
1028
+ exports.history.replace(prependBasename(handler.homePage + exports.history.location.search));
1029
+ }
1030
+ render({ location: exports.history.location, action: history.Action.Push });
1031
+ (_b = app.onShow) === null || _b === void 0 ? void 0 : _b.call(app, launchParam);
1032
+ return exports.history.listen(render);
1033
+ }
1034
+
1035
+ exports.createMultiRouter = createMultiRouter;
1036
+ exports.createRouter = createRouter;
1037
+ exports.getCurrentPages = getCurrentPages;
1038
+ exports.navigateBack = navigateBack;
1039
+ exports.navigateTo = navigateTo;
1040
+ exports.reLaunch = reLaunch;
1041
+ exports.redirectTo = redirectTo;
1042
+ exports.switchTab = switchTab;
1043
+ //# sourceMappingURL=index.cjs.js.map