@tarojs/shared 3.5.0-beta.0 → 3.5.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,27 @@
1
+ declare type Callback1<T1> = (arg1: T1) => any;
2
+ declare type Callback2<T1, T2> = (arg1: T1, arg2: T2) => any;
3
+ declare type Callback3<T1, T2, T3> = (arg1: T1, arg2: T2, arg3: T3) => any;
4
+ declare type Callback4<T1, T2, T3, T4> = (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => any;
5
+ declare type Callback5<T1, T2, T3, T4, T5> = (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => any;
6
+ declare type Callback6Rest<T1, T2, T3, T4, T5, T6> = (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, ...rest: any[]) => any;
7
+ export declare class Events {
8
+ protected callbacks?: Record<string, unknown>;
9
+ static eventSplitter: RegExp;
10
+ constructor(opts?: any);
11
+ on<T>(event: string, callback: Callback1<T>, context?: any): this;
12
+ on<T1, T2>(event: string, callback: Callback2<T1, T2>, context?: any): this;
13
+ on<T1, T2, T3>(event: string, callback: Callback3<T1, T2, T3>, context?: any): this;
14
+ on<T1, T2, T3, T4>(event: string, callback: Callback4<T1, T2, T3, T4>, comtext: any): this;
15
+ on<T1, T2, T3, T4, T5>(event: string, callback: Callback5<T1, T2, T3, T4, T5>, context?: any): this;
16
+ on<T1, T2, T3, T4, T5, T6>(event: string, callback: Callback6Rest<T1, T2, T3, T4, T5, T6>, context?: any): this;
17
+ once(events: any, callback: any, context: any): this;
18
+ off(events: any, callback?: any, context?: any): this;
19
+ trigger(event: string): any;
20
+ trigger<T1>(event: string, arg: T1): any;
21
+ trigger<T1, T2>(event: string, arg1: T1, arg2: T2): any;
22
+ trigger<T1, T2, T3>(event: string, arg1: T1, arg2: T2, arg3: T3): any;
23
+ trigger<T1, T2, T3, T4>(event: string, arg1: T1, arg2: T2, arg3: T3, arg4: T4): any;
24
+ trigger<T1, T2, T3, T4, T5>(event: string, arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5): any;
25
+ trigger<T1, T2, T3, T4, T5, T6>(event: string, arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, ...rest: any[]): any;
26
+ }
27
+ export {};
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  export * from './components';
2
+ export * from './event-emitter';
2
3
  export * from './is';
3
4
  export * from './native-apis';
5
+ export * from './runtime-hooks';
4
6
  export { Shortcuts } from './shortcuts';
5
7
  export * from './utils';
package/dist/index.js CHANGED
@@ -4,8 +4,8 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  const DEFAULT_EMPTY_ARRAY = '[]';
6
6
  const NO_DEFAULT_VALUE = '';
7
- const DEFAULT_TRUE = 'true';
8
- const DEFAULT_FALSE = 'false';
7
+ const DEFAULT_TRUE = '!0';
8
+ const DEFAULT_FALSE = '!1';
9
9
  const touchEvents = {
10
10
  bindTouchStart: NO_DEFAULT_VALUE,
11
11
  bindTouchMove: NO_DEFAULT_VALUE,
@@ -338,6 +338,87 @@ const nestElements = new Map([
338
338
  ['swiper-item', 4]
339
339
  ]);
340
340
 
341
+ class Events {
342
+ constructor(opts) {
343
+ var _a;
344
+ this.callbacks = (_a = opts === null || opts === void 0 ? void 0 : opts.callbacks) !== null && _a !== void 0 ? _a : {};
345
+ }
346
+ on(eventName, callback, context) {
347
+ let event, node, tail, list;
348
+ if (!callback) {
349
+ return this;
350
+ }
351
+ eventName = eventName.split(Events.eventSplitter);
352
+ this.callbacks || (this.callbacks = {});
353
+ const calls = this.callbacks;
354
+ while ((event = eventName.shift())) {
355
+ list = calls[event];
356
+ node = list ? list.tail : {};
357
+ node.next = tail = {};
358
+ node.context = context;
359
+ node.callback = callback;
360
+ calls[event] = {
361
+ tail,
362
+ next: list ? list.next : node
363
+ };
364
+ }
365
+ return this;
366
+ }
367
+ once(events, callback, context) {
368
+ const wrapper = (...args) => {
369
+ callback.apply(this, args);
370
+ this.off(events, wrapper, context);
371
+ };
372
+ this.on(events, wrapper, context);
373
+ return this;
374
+ }
375
+ off(events, callback, context) {
376
+ let event, calls, node, tail, cb, ctx;
377
+ if (!(calls = this.callbacks)) {
378
+ return this;
379
+ }
380
+ if (!(events || callback || context)) {
381
+ delete this.callbacks;
382
+ return this;
383
+ }
384
+ events = events ? events.split(Events.eventSplitter) : Object.keys(calls);
385
+ while ((event = events.shift())) {
386
+ node = calls[event];
387
+ delete calls[event];
388
+ if (!node || !(callback || context)) {
389
+ continue;
390
+ }
391
+ tail = node.tail;
392
+ while ((node = node.next) !== tail) {
393
+ cb = node.callback;
394
+ ctx = node.context;
395
+ if ((callback && cb !== callback) || (context && ctx !== context)) {
396
+ this.on(event, cb, ctx);
397
+ }
398
+ }
399
+ }
400
+ return this;
401
+ }
402
+ trigger(events) {
403
+ let event, node, calls, tail;
404
+ if (!(calls = this.callbacks)) {
405
+ return this;
406
+ }
407
+ events = events.split(Events.eventSplitter);
408
+ const rest = [].slice.call(arguments, 1);
409
+ while ((event = events.shift())) {
410
+ if ((node = calls[event])) {
411
+ tail = node.tail;
412
+ while ((node = node.next) !== tail) {
413
+ node.callback.apply(node.context || this, rest);
414
+ }
415
+ }
416
+ }
417
+ return this;
418
+ }
419
+ }
420
+ Events.eventSplitter = /\s+/;
421
+
341
422
  function isString(o) {
342
423
  return typeof o === 'string';
343
424
  }
@@ -364,10 +445,161 @@ function isBooleanStringLiteral(o) {
364
445
  }
365
446
  const isArray = Array.isArray;
366
447
 
448
+ exports.HOOK_TYPE = void 0;
449
+ (function (HOOK_TYPE) {
450
+ HOOK_TYPE[HOOK_TYPE["SINGLE"] = 0] = "SINGLE";
451
+ HOOK_TYPE[HOOK_TYPE["MULTI"] = 1] = "MULTI";
452
+ HOOK_TYPE[HOOK_TYPE["WATERFALL"] = 2] = "WATERFALL";
453
+ })(exports.HOOK_TYPE || (exports.HOOK_TYPE = {}));
454
+ const defaultMiniLifecycle = {
455
+ app: [
456
+ 'onLaunch',
457
+ 'onShow',
458
+ 'onHide'
459
+ ],
460
+ page: [
461
+ 'onLoad',
462
+ 'onUnload',
463
+ 'onReady',
464
+ 'onShow',
465
+ 'onHide',
466
+ [
467
+ 'onPullDownRefresh',
468
+ 'onReachBottom',
469
+ 'onPageScroll',
470
+ 'onResize',
471
+ 'onTabItemTap',
472
+ 'onTitleClick',
473
+ 'onOptionMenuClick',
474
+ 'onPopMenuClick',
475
+ 'onPullIntercept',
476
+ 'onAddToFavorites'
477
+ ]
478
+ ]
479
+ };
480
+ function TaroHook(type, initial) {
481
+ return {
482
+ type,
483
+ initial: initial || null
484
+ };
485
+ }
486
+ class TaroHooks extends Events {
487
+ constructor(hooks, opts) {
488
+ super(opts);
489
+ this.hooks = hooks;
490
+ for (const hookName in hooks) {
491
+ const { initial } = hooks[hookName];
492
+ if (isFunction(initial)) {
493
+ this.on(hookName, initial);
494
+ }
495
+ }
496
+ }
497
+ tapOneOrMany(hookName, callback) {
498
+ const list = isFunction(callback) ? [callback] : callback;
499
+ list.forEach(cb => this.on(hookName, cb));
500
+ }
501
+ tap(hookName, callback) {
502
+ const hooks = this.hooks;
503
+ const { type, initial } = hooks[hookName];
504
+ if (type === exports.HOOK_TYPE.SINGLE) {
505
+ this.off(hookName);
506
+ this.on(hookName, isFunction(callback) ? callback : callback[callback.length - 1]);
507
+ }
508
+ else {
509
+ initial && this.off(hookName, initial);
510
+ this.tapOneOrMany(hookName, callback);
511
+ }
512
+ }
513
+ call(hookName, ...rest) {
514
+ var _a;
515
+ const hook = this.hooks[hookName];
516
+ if (!hook)
517
+ return;
518
+ const { type } = hook;
519
+ const calls = this.callbacks;
520
+ if (!calls)
521
+ return;
522
+ const list = calls[hookName];
523
+ if (list) {
524
+ const tail = list.tail;
525
+ let node = list.next;
526
+ let args = rest;
527
+ let res;
528
+ while (node !== tail) {
529
+ res = (_a = node.callback) === null || _a === void 0 ? void 0 : _a.apply(node.context || this, args);
530
+ if (type === exports.HOOK_TYPE.WATERFALL) {
531
+ const params = [res];
532
+ args = params;
533
+ }
534
+ node = node.next;
535
+ }
536
+ return res;
537
+ }
538
+ }
539
+ isExist(hookName) {
540
+ var _a;
541
+ return Boolean((_a = this.callbacks) === null || _a === void 0 ? void 0 : _a[hookName]);
542
+ }
543
+ }
544
+ const hooks = new TaroHooks({
545
+ getMiniLifecycle: TaroHook(exports.HOOK_TYPE.SINGLE, defaultConfig => defaultConfig),
546
+ getMiniLifecycleImpl: TaroHook(exports.HOOK_TYPE.SINGLE, function () {
547
+ return this.call('getMiniLifecycle', defaultMiniLifecycle);
548
+ }),
549
+ getLifecycle: TaroHook(exports.HOOK_TYPE.SINGLE, (instance, lifecycle) => instance[lifecycle]),
550
+ getPathIndex: TaroHook(exports.HOOK_TYPE.SINGLE, indexOfNode => `[${indexOfNode}]`),
551
+ getEventCenter: TaroHook(exports.HOOK_TYPE.SINGLE, Events => new Events()),
552
+ isBubbleEvents: TaroHook(exports.HOOK_TYPE.SINGLE, eventName => {
553
+ /**
554
+ * 支持冒泡的事件, 除 支付宝小程序外,其余的可冒泡事件都和微信保持一致
555
+ * 详见 见 https://developers.weixin.qq.com/miniprogram/dev/framework/view/wxml/event.html
556
+ */
557
+ const BUBBLE_EVENTS = new Set([
558
+ 'touchstart',
559
+ 'touchmove',
560
+ 'touchcancel',
561
+ 'touchend',
562
+ 'touchforcechange',
563
+ 'tap',
564
+ 'longpress',
565
+ 'longtap',
566
+ 'transitionend',
567
+ 'animationstart',
568
+ 'animationiteration',
569
+ 'animationend'
570
+ ]);
571
+ return BUBBLE_EVENTS.has(eventName);
572
+ }),
573
+ getSpecialNodes: TaroHook(exports.HOOK_TYPE.SINGLE, () => ['view', 'text', 'image']),
574
+ onRemoveAttribute: TaroHook(exports.HOOK_TYPE.SINGLE),
575
+ batchedEventUpdates: TaroHook(exports.HOOK_TYPE.SINGLE),
576
+ mergePageInstance: TaroHook(exports.HOOK_TYPE.SINGLE),
577
+ modifyPageObject: TaroHook(exports.HOOK_TYPE.SINGLE),
578
+ createPullDownComponent: TaroHook(exports.HOOK_TYPE.SINGLE),
579
+ getDOMNode: TaroHook(exports.HOOK_TYPE.SINGLE),
580
+ modifyHydrateData: TaroHook(exports.HOOK_TYPE.SINGLE),
581
+ modifySetAttrPayload: TaroHook(exports.HOOK_TYPE.SINGLE),
582
+ modifyRmAttrPayload: TaroHook(exports.HOOK_TYPE.SINGLE),
583
+ onAddEvent: TaroHook(exports.HOOK_TYPE.SINGLE),
584
+ modifyMpEvent: TaroHook(exports.HOOK_TYPE.MULTI),
585
+ modifyMpEventImpl: TaroHook(exports.HOOK_TYPE.SINGLE, function (e) {
586
+ try {
587
+ // 有些小程序的事件对象的某些属性只读
588
+ this.call('modifyMpEvent', e);
589
+ }
590
+ catch (error) {
591
+ console.warn('[Taro modifyMpEvent hook Error]: ', error);
592
+ }
593
+ }),
594
+ modifyTaroEvent: TaroHook(exports.HOOK_TYPE.MULTI),
595
+ modifyDispatchEvent: TaroHook(exports.HOOK_TYPE.MULTI),
596
+ initNativeApi: TaroHook(exports.HOOK_TYPE.MULTI),
597
+ patchElement: TaroHook(exports.HOOK_TYPE.MULTI)
598
+ });
599
+
367
600
  const EMPTY_OBJ = {};
368
601
  const EMPTY_ARR = [];
369
602
  const noop = (..._) => { };
370
- const defaultReconciler = Object.create(null);
371
603
  /**
372
604
  * box creates a boxed value.
373
605
  *
@@ -490,19 +722,55 @@ function mergeInternalComponents(components) {
490
722
  internalComponents[name] = components[name];
491
723
  }
492
724
  });
725
+ return internalComponents;
726
+ }
727
+ function getComponentsAlias(origin) {
728
+ const mapping = {};
729
+ const viewAttrs = origin.View;
730
+ const extraList = {
731
+ '#text': {},
732
+ StaticView: viewAttrs,
733
+ StaticImage: origin.Image,
734
+ StaticText: origin.Text,
735
+ PureView: viewAttrs,
736
+ CatchView: viewAttrs
737
+ };
738
+ origin = Object.assign(Object.assign({}, origin), extraList);
739
+ Object.keys(origin)
740
+ .sort((a, b) => {
741
+ const reg = /^(Static|Pure|Catch)*(View|Image|Text)$/;
742
+ if (reg.test(a)) {
743
+ return -1;
744
+ }
745
+ else if (reg.test(b)) {
746
+ return 1;
747
+ }
748
+ else {
749
+ return a >= b ? 1 : -1;
750
+ }
751
+ })
752
+ .forEach((key, num) => {
753
+ const obj = {
754
+ _num: String(num)
755
+ };
756
+ Object.keys(origin[key])
757
+ .filter(attr => !(/^bind/.test(attr)) && !['focus', 'blur'].includes(attr))
758
+ .sort()
759
+ .forEach((attr, index) => {
760
+ obj[toCamelCase(attr)] = 'p' + index;
761
+ });
762
+ mapping[toDashed(key)] = obj;
763
+ });
764
+ return mapping;
493
765
  }
494
- function mergeReconciler(hostConfig) {
495
- Object.keys(hostConfig).forEach(key => {
496
- const value = hostConfig[key];
497
- const raw = defaultReconciler[key];
498
- defaultReconciler[key] = !raw
499
- ? value
500
- : (isArray(raw)
501
- ? raw.concat(value)
502
- : [raw, value]);
766
+ function mergeReconciler(hostConfig, hooksForTest) {
767
+ const obj = hooksForTest || hooks;
768
+ const keys = Object.keys(hostConfig);
769
+ keys.forEach(key => {
770
+ obj.tap(key, hostConfig[key]);
503
771
  });
504
772
  }
505
- function unsupport(api) {
773
+ function nonsupport(api) {
506
774
  return function () {
507
775
  console.warn(`小程序暂不支持 ${api}`);
508
776
  };
@@ -695,6 +963,7 @@ function getNormalRequest(global) {
695
963
  };
696
964
  requestTask = global.request(options);
697
965
  });
966
+ equipTaskMethodsIntoPromise(requestTask, p);
698
967
  p.abort = (cb) => {
699
968
  cb && cb();
700
969
  if (requestTask) {
@@ -745,7 +1014,7 @@ function processApis(taro, global, config = {}) {
745
1014
  options = transformResult.options;
746
1015
  // 新 key 可能不存在
747
1016
  if (!global.hasOwnProperty(key)) {
748
- return unsupport(key)();
1017
+ return nonsupport(key)();
749
1018
  }
750
1019
  }
751
1020
  let task = null;
@@ -782,13 +1051,8 @@ function processApis(taro, global, config = {}) {
782
1051
  }
783
1052
  });
784
1053
  // 给 promise 对象挂载属性
785
- if (['request', 'uploadFile', 'downloadFile'].includes(key)) {
786
- const taskMethods = ['abort', 'onHeadersReceived', 'offHeadersReceived', 'onProgressUpdate', 'offProgressUpdate', 'onChunkReceived', 'offChunkReceived'];
787
- task && taskMethods.forEach(method => {
788
- if (method in task) {
789
- p[method] = task[method].bind(task);
790
- }
791
- });
1054
+ if (['uploadFile', 'downloadFile'].includes(key)) {
1055
+ equipTaskMethodsIntoPromise(task, p);
792
1056
  p.progress = cb => {
793
1057
  task === null || task === void 0 ? void 0 : task.onProgressUpdate(cb);
794
1058
  return p;
@@ -810,7 +1074,7 @@ function processApis(taro, global, config = {}) {
810
1074
  }
811
1075
  // API 不存在
812
1076
  if (!global.hasOwnProperty(platformKey)) {
813
- taro[key] = unsupport(key);
1077
+ taro[key] = nonsupport(key);
814
1078
  return;
815
1079
  }
816
1080
  if (isFunction(global[key])) {
@@ -837,14 +1101,14 @@ function processApis(taro, global, config = {}) {
837
1101
  */
838
1102
  function equipCommonApis(taro, global, apis = {}) {
839
1103
  taro.canIUseWebp = getCanIUseWebp(taro);
840
- taro.getCurrentPages = getCurrentPages || unsupport('getCurrentPages');
841
- taro.getApp = getApp || unsupport('getApp');
1104
+ taro.getCurrentPages = getCurrentPages || nonsupport('getCurrentPages');
1105
+ taro.getApp = getApp || nonsupport('getApp');
842
1106
  taro.env = global.env || {};
843
1107
  try {
844
- taro.requirePlugin = requirePlugin || unsupport('requirePlugin');
1108
+ taro.requirePlugin = requirePlugin || nonsupport('requirePlugin');
845
1109
  }
846
1110
  catch (error) {
847
- taro.requirePlugin = unsupport('requirePlugin');
1111
+ taro.requirePlugin = nonsupport('requirePlugin');
848
1112
  }
849
1113
  // request & interceptors
850
1114
  const request = apis.request || getNormalRequest(global);
@@ -856,6 +1120,21 @@ function equipCommonApis(taro, global, apis = {}) {
856
1120
  taro.addInterceptor = link.addInterceptor.bind(link);
857
1121
  taro.cleanInterceptors = link.cleanInterceptors.bind(link);
858
1122
  taro.miniGlobal = taro.options.miniGlobal = global;
1123
+ }
1124
+ /**
1125
+ * 将Task对象中的方法挂载到promise对象中,适配小程序api原生返回结果
1126
+ * @param task Task对象 {RequestTask | DownloadTask | UploadTask}
1127
+ * @param promise Promise
1128
+ */
1129
+ function equipTaskMethodsIntoPromise(task, promise) {
1130
+ if (!task || !promise)
1131
+ return;
1132
+ const taskMethods = ['abort', 'onHeadersReceived', 'offHeadersReceived', 'onProgressUpdate', 'offProgressUpdate', 'onChunkReceived', 'offChunkReceived'];
1133
+ task && taskMethods.forEach(method => {
1134
+ if (method in task) {
1135
+ promise[method] = task[method].bind(task);
1136
+ }
1137
+ });
859
1138
  }
860
1139
 
861
1140
  // 字符串简写
@@ -874,6 +1153,9 @@ exports.Shortcuts = void 0;
874
1153
 
875
1154
  exports.EMPTY_ARR = EMPTY_ARR;
876
1155
  exports.EMPTY_OBJ = EMPTY_OBJ;
1156
+ exports.Events = Events;
1157
+ exports.TaroHook = TaroHook;
1158
+ exports.TaroHooks = TaroHooks;
877
1159
  exports.animation = animation;
878
1160
  exports.box = box;
879
1161
  exports.cacheDataGet = cacheDataGet;
@@ -881,11 +1163,12 @@ exports.cacheDataHas = cacheDataHas;
881
1163
  exports.cacheDataSet = cacheDataSet;
882
1164
  exports.capitalize = capitalize;
883
1165
  exports.controlledComponent = controlledComponent;
884
- exports.defaultReconciler = defaultReconciler;
885
1166
  exports.ensure = ensure;
886
1167
  exports.focusComponents = focusComponents;
1168
+ exports.getComponentsAlias = getComponentsAlias;
887
1169
  exports.getUniqueKey = getUniqueKey;
888
1170
  exports.hasOwn = hasOwn;
1171
+ exports.hooks = hooks;
889
1172
  exports.indent = indent;
890
1173
  exports.internalComponents = internalComponents;
891
1174
  exports.isArray = isArray;
@@ -900,6 +1183,7 @@ exports.isUndefined = isUndefined;
900
1183
  exports.mergeInternalComponents = mergeInternalComponents;
901
1184
  exports.mergeReconciler = mergeReconciler;
902
1185
  exports.nestElements = nestElements;
1186
+ exports.nonsupport = nonsupport;
903
1187
  exports.noop = noop;
904
1188
  exports.processApis = processApis;
905
1189
  exports.queryToJson = queryToJson;
@@ -910,7 +1194,6 @@ exports.toDashed = toDashed;
910
1194
  exports.toKebabCase = toKebabCase;
911
1195
  exports.touchEvents = touchEvents;
912
1196
  exports.unbox = unbox;
913
- exports.unsupport = unsupport;
914
1197
  exports.voidElements = voidElements;
915
1198
  exports.warn = warn;
916
1199
  //# sourceMappingURL=index.js.map