@tarojs/with-weapp 4.0.0-beta.93 → 4.0.0-beta.95

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.
@@ -5,59 +5,56 @@
5
5
  })(this, (function (exports, runtime, taro) { 'use strict';
6
6
 
7
7
  const json = JSON;
8
- const clone = obj => json.parse(stringify(obj));
8
+
9
+ const clone = (obj) => json.parse(stringify(obj));
10
+
9
11
  const isArray = Array.isArray || function (x) {
10
- return {}.toString.call(x) === '[object Array]';
12
+ return {}.toString.call(x) === '[object Array]'
11
13
  };
14
+
12
15
  const objectKeys = Object.keys || function (obj) {
13
- const has = Object.prototype.hasOwnProperty || function () {
14
- return true;
15
- };
16
+ const has = Object.prototype.hasOwnProperty || function () { return true };
16
17
  const keys = [];
17
18
  for (const key in obj) {
18
19
  if (has.call(obj, key)) keys.push(key);
19
20
  }
20
- return keys;
21
+ return keys
21
22
  };
22
- function stringify(obj, opts) {
23
+
24
+ function stringify (obj, opts) {
23
25
  if (!opts) opts = {};
24
- if (typeof opts === 'function') opts = {
25
- cmp: opts
26
- };
26
+ if (typeof opts === 'function') opts = { cmp: opts };
27
27
  let space = opts.space || '';
28
28
  if (typeof space === 'number') space = Array(space + 1).join(' ');
29
- const cycles = typeof opts.cycles === 'boolean' ? opts.cycles : false;
30
- const replacer = opts.replacer || function (key, value) {
31
- return value;
32
- };
33
- const cmp = opts.cmp && function (f) {
29
+ const cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
30
+ const replacer = opts.replacer || function (key, value) { return value };
31
+
32
+ const cmp = opts.cmp && (function (f) {
34
33
  return function (node) {
35
34
  return function (a, b) {
36
- const aobj = {
37
- key: a,
38
- value: node[a]
39
- };
40
- const bobj = {
41
- key: b,
42
- value: node[b]
43
- };
44
- return f(aobj, bobj);
45
- };
46
- };
47
- }(opts.cmp);
35
+ const aobj = { key: a, value: node[a] };
36
+ const bobj = { key: b, value: node[b] };
37
+ return f(aobj, bobj)
38
+ }
39
+ }
40
+ })(opts.cmp);
41
+
48
42
  const seen = [];
49
- return function stringify(parent, key, node, level) {
50
- const indent = space ? '\n' + new Array(level + 1).join(space) : '';
43
+ return (function stringify (parent, key, node, level) {
44
+ const indent = space ? ('\n' + new Array(level + 1).join(space)) : '';
51
45
  const colonSeparator = space ? ': ' : ':';
46
+
52
47
  if (node && node.toJSON && typeof node.toJSON === 'function') {
53
48
  node = node.toJSON();
54
49
  }
50
+
55
51
  node = replacer.call(parent, key, node);
52
+
56
53
  if (node === undefined) {
57
- return;
54
+ return
58
55
  }
59
56
  if (typeof node !== 'object' || node === null) {
60
- return json.stringify(node);
57
+ return json.stringify(node)
61
58
  }
62
59
  if (isArray(node)) {
63
60
  const out = [];
@@ -65,41 +62,47 @@
65
62
  const item = stringify(node, i, node[i], level + 1) || json.stringify(null);
66
63
  out.push(indent + space + item);
67
64
  }
68
- return '[' + out.join(',') + indent + ']';
65
+ return '[' + out.join(',') + indent + ']'
69
66
  } else {
70
67
  if (seen.indexOf(node) !== -1) {
71
- if (cycles) return json.stringify('__cycle__');
72
- throw new TypeError('Converting circular structure to JSON');
68
+ if (cycles) return json.stringify('__cycle__')
69
+ throw new TypeError('Converting circular structure to JSON')
73
70
  } else seen.push(node);
71
+
74
72
  const keys = objectKeys(node).sort(cmp && cmp(node));
75
73
  const out = [];
76
74
  for (let i = 0; i < keys.length; i++) {
77
75
  const key = keys[i];
78
76
  const value = stringify(node, key, node[key], level + 1);
79
- if (!value) continue;
80
- const keyValue = json.stringify(key) + colonSeparator + value;
77
+
78
+ if (!value) continue
79
+
80
+ const keyValue = json.stringify(key) +
81
+ colonSeparator +
82
+ value;
83
+
81
84
  out.push(indent + space + keyValue);
82
85
  }
83
86
  seen.splice(seen.indexOf(node), 1);
84
- return '{' + out.join(',') + indent + '}';
87
+ return '{' + out.join(',') + indent + '}'
85
88
  }
86
- }({
87
- '': obj
88
- }, '', obj, 0);
89
+ })({ '': obj }, '', obj, 0)
89
90
  }
90
91
 
91
92
  /*eslint-disable*/
92
93
  const ARRAYTYPE = '[object Array]';
93
94
  const OBJECTTYPE = '[object Object]';
94
95
  const FUNCTIONTYPE = '[object Function]';
95
- function diff(current, pre) {
96
+
97
+ function diff (current, pre) {
96
98
  const result = {};
97
99
  syncKeys(current, pre);
98
100
  _diff(current, pre, '', result);
99
- return result;
101
+ return result
100
102
  }
101
- function syncKeys(current, pre) {
102
- if (current === pre) return;
103
+
104
+ function syncKeys (current, pre) {
105
+ if (current === pre) return
103
106
  const rootCurrentType = type(current);
104
107
  const rootPreType = type(pre);
105
108
  if (rootCurrentType == OBJECTTYPE && rootPreType == OBJECTTYPE) {
@@ -121,8 +124,9 @@
121
124
  }
122
125
  }
123
126
  }
124
- function _diff(current, pre, path, result) {
125
- if (current === pre) return;
127
+
128
+ function _diff (current, pre, path, result) {
129
+ if (current === pre) return
126
130
  const rootCurrentType = type(current);
127
131
  const rootPreType = type(pre);
128
132
  if (rootCurrentType == OBJECTTYPE) {
@@ -177,805 +181,854 @@
177
181
  setResult(result, path, current);
178
182
  }
179
183
  }
180
- function setResult(result, k, v) {
184
+
185
+ function setResult (result, k, v) {
181
186
  if (type(v) != FUNCTIONTYPE) {
182
187
  result[k] = v;
183
188
  }
184
189
  }
185
- function type(obj) {
186
- return Object.prototype.toString.call(obj);
190
+
191
+ function type (obj) {
192
+ return Object.prototype.toString.call(obj)
187
193
  }
188
194
 
189
195
  var TaroLifeCycles;
190
196
  (function (TaroLifeCycles) {
191
- TaroLifeCycles["WillMount"] = "componentWillMount";
192
- TaroLifeCycles["DidMount"] = "componentDidMount";
193
- TaroLifeCycles["DidShow"] = "componentDidShow";
194
- TaroLifeCycles["DidHide"] = "componentDidHide";
195
- TaroLifeCycles["WillUnmount"] = "componentWillUnmount";
197
+ TaroLifeCycles["WillMount"] = "componentWillMount";
198
+ TaroLifeCycles["DidMount"] = "componentDidMount";
199
+ TaroLifeCycles["DidShow"] = "componentDidShow";
200
+ TaroLifeCycles["DidHide"] = "componentDidHide";
201
+ TaroLifeCycles["WillUnmount"] = "componentWillUnmount";
196
202
  })(TaroLifeCycles || (TaroLifeCycles = {}));
197
203
  const lifecycleMap = {
198
- [TaroLifeCycles.WillMount]: ['created'],
199
- [TaroLifeCycles.DidMount]: ['attached'],
200
- [TaroLifeCycles.DidShow]: ['onShow'],
201
- [TaroLifeCycles.DidHide]: ['onHide'],
202
- [TaroLifeCycles.WillUnmount]: ['detached', 'onUnload']
204
+ [TaroLifeCycles.WillMount]: ['created'],
205
+ [TaroLifeCycles.DidMount]: ['attached'],
206
+ [TaroLifeCycles.DidShow]: ['onShow'],
207
+ [TaroLifeCycles.DidHide]: ['onHide'],
208
+ [TaroLifeCycles.WillUnmount]: ['detached', 'onUnload']
203
209
  };
204
210
  const lifecycles = new Set(['ready']);
205
211
  for (const key in lifecycleMap) {
206
- const lifecycle = lifecycleMap[key];
207
- lifecycle.forEach(l => lifecycles.add(l));
212
+ const lifecycle = lifecycleMap[key];
213
+ lifecycle.forEach(l => lifecycles.add(l));
208
214
  }
209
- const uniquePageLifecycle = ['onPullDownRefresh', 'onReachBottom', 'onShareAppMessage', 'onShareTimeline', 'onAddToFavorites', 'onPageScroll', 'onResize', 'onTabItemTap'];
210
- const appOptions = ['onLaunch', 'onShow', 'onHide', 'onError', 'onPageNotFound', 'onUnhandledRejection', 'onThemeChange'];
215
+ const uniquePageLifecycle = [
216
+ 'onPullDownRefresh',
217
+ 'onReachBottom',
218
+ 'onShareAppMessage',
219
+ 'onShareTimeline',
220
+ 'onAddToFavorites',
221
+ 'onPageScroll',
222
+ 'onResize',
223
+ 'onTabItemTap'
224
+ ];
225
+ const appOptions = [
226
+ 'onLaunch',
227
+ 'onShow',
228
+ 'onHide',
229
+ 'onError',
230
+ 'onPageNotFound',
231
+ 'onUnhandledRejection',
232
+ 'onThemeChange'
233
+ ];
211
234
 
212
235
  /**
213
236
  * Simple bind, faster than native
214
237
  */
215
238
  function bind(fn /*: Function */, ctx /*: Object */) {
216
- if (!fn) return false;
217
- function boundFn(a) {
218
- const l /*: number */ = arguments.length;
219
- return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx);
220
- }
221
- // record original fn length
222
- boundFn._length = fn.length;
223
- return boundFn;
239
+ if (!fn)
240
+ return false;
241
+ function boundFn(a) {
242
+ const l /*: number */ = arguments.length;
243
+ return l ? (l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a)) : fn.call(ctx);
244
+ }
245
+ // record original fn length
246
+ boundFn._length = fn.length;
247
+ return boundFn;
224
248
  }
225
249
  function isEqual(obj1, obj2) {
226
- return JSON.stringify(obj1) === JSON.stringify(obj2);
250
+ return JSON.stringify(obj1) === JSON.stringify(obj2);
227
251
  }
228
252
  function safeGet(obj, propsArg, defaultValue) {
229
- if (!obj) {
230
- return defaultValue;
231
- }
232
- let props, prop;
233
- if (Array.isArray(propsArg)) {
234
- props = propsArg.slice(0);
235
- }
236
- if (typeof propsArg === 'string') {
237
- props = propsArg.replace(/\[(.+?)\]/g, '.$1');
238
- props = props.split('.');
239
- }
240
- if (typeof propsArg === 'symbol') {
241
- props = [propsArg];
242
- }
243
- if (!Array.isArray(props)) {
244
- throw new Error('props arg must be an array, a string or a symbol');
245
- }
246
- while (props.length) {
247
- prop = props.shift();
248
253
  if (!obj) {
249
- return defaultValue;
254
+ return defaultValue;
250
255
  }
251
- obj = obj[prop];
252
- if (obj === undefined) {
253
- return defaultValue;
256
+ let props, prop;
257
+ if (Array.isArray(propsArg)) {
258
+ props = propsArg.slice(0);
254
259
  }
255
- }
256
- return obj;
260
+ if (typeof propsArg === 'string') {
261
+ props = propsArg.replace(/\[(.+?)\]/g, '.$1');
262
+ props = props.split('.');
263
+ }
264
+ if (typeof propsArg === 'symbol') {
265
+ props = [propsArg];
266
+ }
267
+ if (!Array.isArray(props)) {
268
+ throw new Error('props arg must be an array, a string or a symbol');
269
+ }
270
+ while (props.length) {
271
+ prop = props.shift();
272
+ if (!obj) {
273
+ return defaultValue;
274
+ }
275
+ obj = obj[prop];
276
+ if (obj === undefined) {
277
+ return defaultValue;
278
+ }
279
+ }
280
+ return obj;
257
281
  }
258
282
  function safeSet(obj, props, value) {
259
- if (typeof props === 'string') {
260
- props = props.replace(/\[(.+?)\]/g, '.$1');
261
- props = props.split('.');
262
- }
263
- if (typeof props === 'symbol') {
264
- props = [props];
265
- }
266
- const lastProp = props.pop();
267
- if (!lastProp) {
268
- return false;
269
- }
270
- let thisProp;
271
- while (thisProp = props.shift()) {
272
- if (typeof obj[thisProp] === 'undefined') {
273
- obj[thisProp] = {};
283
+ if (typeof props === 'string') {
284
+ props = props.replace(/\[(.+?)\]/g, '.$1');
285
+ props = props.split('.');
274
286
  }
275
- // 直接按路径修改 this.state 可能会导致 nextProps 也被修改
276
- // 因此按路径寻找时,每一层都复制一遍
277
- if (Array.isArray(obj[thisProp])) {
278
- obj[thisProp] = [...obj[thisProp]];
279
- } else if (typeof obj[thisProp] === 'object') {
280
- obj[thisProp] = Object.assign({}, obj[thisProp]);
287
+ if (typeof props === 'symbol') {
288
+ props = [props];
281
289
  }
282
- obj = obj[thisProp];
283
- if (!obj || typeof obj !== 'object') {
284
- return false;
290
+ const lastProp = props.pop();
291
+ if (!lastProp) {
292
+ return false;
285
293
  }
286
- }
287
- obj[lastProp] = value;
288
- return true;
294
+ let thisProp;
295
+ while ((thisProp = props.shift())) {
296
+ if (typeof obj[thisProp] === 'undefined') {
297
+ obj[thisProp] = {};
298
+ }
299
+ // 直接按路径修改 this.state 可能会导致 nextProps 也被修改
300
+ // 因此按路径寻找时,每一层都复制一遍
301
+ if (Array.isArray(obj[thisProp])) {
302
+ obj[thisProp] = [...obj[thisProp]];
303
+ }
304
+ else if (typeof obj[thisProp] === 'object') {
305
+ obj[thisProp] = Object.assign({}, obj[thisProp]);
306
+ }
307
+ obj = obj[thisProp];
308
+ if (!obj || typeof obj !== 'object') {
309
+ return false;
310
+ }
311
+ }
312
+ obj[lastProp] = value;
313
+ return true;
289
314
  }
290
315
  function report(msg) {
291
- console.warn('[Taro Convert Warning] ' + msg);
316
+ console.warn('[Taro Convert Warning] ' + msg);
292
317
  }
293
- const nonsupport = new Map([['onError', '不支持 App 的 onError 生命周期方法。'], ['onPageNotFound', '不支持 App 的 onPageNotFound 生命周期方法。'], ['onUnhandledRejection', '不支持 App 的 onUnhandledRejection 生命周期方法。'], ['onThemeChange', '不支持 App 的 onThemeChange 生命周期方法。'], ['moved', '不支持自定义组件的 moved 生命周期。'], ['externalClasses', '不支持自定义组件的 externalClasses 功能。'], ['relations', '不支持自定义组件的 relations 功能。'], ['options', '不支持自定义组件的 options 功能。'], ['definitionFilter', '不支持自定义组件的 definitionFilter 功能。'], ['selectComponent', 'selectComponent 方法产生不到目标效果,请使用 React 的 ref 进行重构。'], ['selectAllComponents', 'selectAllComponents 方法产生不到目标效果,请使用 React 的 ref 进行重构。'], ['selectOwnerComponent', 'selectOwnerComponent 方法产生不到目标效果,请使用 React 语法重构。'], ['groupSetData', 'groupSetData 方法产生不到目标效果,请使用 React 语法重构。']]);
318
+ const nonsupport = new Map([
319
+ ['onError', '不支持 App 的 onError 生命周期方法。'],
320
+ ['onPageNotFound', '不支持 App 的 onPageNotFound 生命周期方法。'],
321
+ ['onUnhandledRejection', '不支持 App 的 onUnhandledRejection 生命周期方法。'],
322
+ ['onThemeChange', '不支持 App 的 onThemeChange 生命周期方法。'],
323
+ ['moved', '不支持自定义组件的 moved 生命周期。'],
324
+ ['externalClasses', '不支持自定义组件的 externalClasses 功能。'],
325
+ ['relations', '不支持自定义组件的 relations 功能。'],
326
+ ['options', '不支持自定义组件的 options 功能。'],
327
+ ['definitionFilter', '不支持自定义组件的 definitionFilter 功能。'],
328
+ ['selectComponent', 'selectComponent 方法产生不到目标效果,请使用 React 的 ref 进行重构。'],
329
+ ['selectAllComponents', 'selectAllComponents 方法产生不到目标效果,请使用 React 的 ref 进行重构。'],
330
+ ['selectOwnerComponent', 'selectOwnerComponent 方法产生不到目标效果,请使用 React 语法重构。'],
331
+ ['groupSetData', 'groupSetData 方法产生不到目标效果,请使用 React 语法重构。']
332
+ ]);
294
333
  function flattenBehaviors(behavior, behaviorMap) {
295
- if (typeof behavior === 'string') {
296
- return report(`不支持使用内置 Behavior: [${behavior}]`);
297
- }
298
- const subBehaviors = behavior.behaviors;
299
- if (subBehaviors === null || subBehaviors === void 0 ? void 0 : subBehaviors.length) {
300
- subBehaviors.forEach(subBehavior => flattenBehaviors(subBehavior, behaviorMap));
301
- }
302
- Object.keys(behavior).forEach(key => {
303
- // 不支持的属性
304
- if (nonsupport.has(key)) {
305
- const advise = nonsupport.get(key);
306
- return report(advise);
334
+ if (typeof behavior === 'string') {
335
+ return report(`不支持使用内置 Behavior: [${behavior}]`);
307
336
  }
308
- if (behaviorMap.has(key)) {
309
- const list = behaviorMap.get(key);
310
- const value = behavior[key];
311
- list.push(value);
337
+ const subBehaviors = behavior.behaviors;
338
+ if (subBehaviors === null || subBehaviors === void 0 ? void 0 : subBehaviors.length) {
339
+ subBehaviors.forEach(subBehavior => flattenBehaviors(subBehavior, behaviorMap));
312
340
  }
313
- });
341
+ Object.keys(behavior).forEach(key => {
342
+ // 不支持的属性
343
+ if (nonsupport.has(key)) {
344
+ const advise = nonsupport.get(key);
345
+ return report(advise);
346
+ }
347
+ if (behaviorMap.has(key)) {
348
+ const list = behaviorMap.get(key);
349
+ const value = behavior[key];
350
+ list.push(value);
351
+ }
352
+ });
314
353
  }
315
354
 
316
355
  /**
317
356
  * 该模块仅存放 convert 转换时用到的工具函数或变量
318
357
  */
319
358
  const cacheOptions = {
320
- cacheOptions: {},
321
- setOptionsToCache: function (options) {
322
- if (Object.keys(options).length !== 0) {
323
- this.cacheOptions = options;
359
+ cacheOptions: {},
360
+ setOptionsToCache: function (options) {
361
+ if (Object.keys(options).length !== 0) {
362
+ this.cacheOptions = options;
363
+ }
364
+ },
365
+ getOptionsFromCache: function () {
366
+ return this.cacheOptions;
324
367
  }
325
- },
326
- getOptionsFromCache: function () {
327
- return this.cacheOptions;
328
- }
329
368
  };
330
369
  function toCamelCase(s) {
331
- let camel = '';
332
- let nextCap = false;
333
- for (let i = 0; i < s.length; i++) {
334
- if (s[i] !== '-') {
335
- camel += nextCap ? s[i].toUpperCase() : s[i];
336
- nextCap = false;
337
- } else {
338
- nextCap = true;
370
+ let camel = '';
371
+ let nextCap = false;
372
+ for (let i = 0; i < s.length; i++) {
373
+ if (s[i] !== '-') {
374
+ camel += nextCap ? s[i].toUpperCase() : s[i];
375
+ nextCap = false;
376
+ }
377
+ else {
378
+ nextCap = true;
379
+ }
339
380
  }
340
- }
341
- return camel;
381
+ return camel;
342
382
  }
343
383
  const convertToArray = function (value, fn) {
344
- if (value instanceof Array) {
345
- return value.map(fn);
346
- } else if (typeof value === 'number') {
347
- return Array.from({
348
- length: value
349
- }, (_, index) => index).map(fn);
350
- } else if (typeof value === 'string') {
351
- return Array.from(value).map(fn);
352
- } else if (typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype) {
353
- const result = Object.keys(value).map(item => {
354
- return fn(value[item], item);
355
- });
356
- return result;
357
- }
384
+ if (value instanceof Array) {
385
+ return value.map(fn);
386
+ }
387
+ else if (typeof value === 'number') {
388
+ return Array.from({
389
+ length: value
390
+ }, (_, index) => index).map(fn);
391
+ }
392
+ else if (typeof value === 'string') {
393
+ return Array.from(value).map(fn);
394
+ }
395
+ else if (typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype) {
396
+ const result = Object.keys(value).map((item) => {
397
+ return fn(value[item], item);
398
+ });
399
+ return result;
400
+ }
358
401
  };
359
402
  const getTarget = (target, Taro) => {
360
- if (!target) {
361
- return {
362
- dataset: {}
363
- };
364
- }
365
- if (Taro.getEnv() === Taro.ENV_TYPE.HARMONYHYBRID || Taro.getEnv() === Taro.ENV_TYPE.WEB) {
366
- if (target.fullDataset) {
367
- return {
368
- dataset: target.fullDataset
369
- };
403
+ if (!target) {
404
+ return { dataset: {} };
370
405
  }
371
- const fullDataset = {};
372
- // 获取元素的所有属性
373
- const targetAttrKeys = Object.keys(target);
374
- // 遍历所有属性
375
- for (let i = 0; i < targetAttrKeys.length; i++) {
376
- if (targetAttrKeys[i].startsWith('data-')) {
377
- fullDataset[toCamelCase(targetAttrKeys[i].replace(/^data-/, '').toLowerCase())] = target[targetAttrKeys[i]];
378
- }
406
+ if (Taro.getEnv() === Taro.ENV_TYPE.HARMONYHYBRID || Taro.getEnv() === Taro.ENV_TYPE.WEB) {
407
+ if (target.fullDataset) {
408
+ return { dataset: target.fullDataset };
409
+ }
410
+ const fullDataset = {};
411
+ // 获取元素的所有属性
412
+ const targetAttrKeys = Object.keys(target);
413
+ // 遍历所有属性
414
+ for (let i = 0; i < targetAttrKeys.length; i++) {
415
+ if (targetAttrKeys[i].startsWith('data-')) {
416
+ fullDataset[toCamelCase(targetAttrKeys[i].replace(/^data-/, '').toLowerCase())] = target[targetAttrKeys[i]];
417
+ }
418
+ }
419
+ target.fullDataset = fullDataset;
420
+ return { dataset: fullDataset };
379
421
  }
380
- target.fullDataset = fullDataset;
381
- return {
382
- dataset: fullDataset
383
- };
384
- }
385
- return target;
422
+ return target;
386
423
  };
387
424
 
388
425
  function defineGetter(component, key, getter) {
389
- Object.defineProperty(component, key, {
390
- enumerable: true,
391
- configurable: true,
392
- get: () => {
393
- if (getter === 'props') {
394
- return component.props;
395
- }
396
- return component.state;
397
- // return {
398
- // ...component.state,
399
- // ...component.props
400
- // }
401
- }
402
- });
426
+ Object.defineProperty(component, key, {
427
+ enumerable: true,
428
+ configurable: true,
429
+ get: () => {
430
+ if (getter === 'props') {
431
+ return component.props;
432
+ }
433
+ return component.state;
434
+ // return {
435
+ // ...component.state,
436
+ // ...component.props
437
+ // }
438
+ }
439
+ });
403
440
  }
404
-
405
441
  function propToState(newValue, _oldValue, key) {
406
- this.state[key] = newValue;
442
+ this.state[key] = newValue;
407
443
  }
408
444
  function isFunction(o) {
409
- return typeof o === 'function';
445
+ return typeof o === 'function';
410
446
  }
411
447
  function withWeapp(weappConf, isApp = false) {
412
- if (typeof weappConf === 'object' && Object.keys(weappConf).length === 0) {
413
- report('withWeapp 请传入“App/页面/组件“的配置对象。如果原生写法使用了基类,请将基类组合后的配置对象传入,详情请参考文档。');
414
- }
415
- return ConnectComponent => {
416
- var _a;
417
- const behaviorMap = new Map([['properties', []], ['data', []], ['methods', []], ['created', []], ['attached', []], ['ready', []], ['detached', []], ['lifetimes', []]]);
418
- const behaviorProperties = {};
419
- if ((_a = weappConf.behaviors) === null || _a === void 0 ? void 0 : _a.length) {
420
- const {
421
- behaviors
422
- } = weappConf;
423
- behaviors.forEach(behavior => flattenBehaviors(behavior, behaviorMap));
424
- const propertiesList = behaviorMap.get('properties');
425
- if (propertiesList.length) {
426
- propertiesList.forEach(property => {
427
- Object.assign(behaviorProperties, property);
428
- });
429
- Object.keys(behaviorProperties).forEach(propName => {
430
- const propValue = behaviorProperties[propName];
431
- if (!weappConf.properties) {
432
- weappConf.properties = {};
433
- }
434
- if (!weappConf.properties.hasOwnProperty(propName)) {
435
- if (propValue && typeof propValue === 'object' && propValue.value) {
436
- propValue.value = clone(propValue.value);
437
- }
438
- weappConf.properties[propName] = propValue;
439
- }
440
- });
441
- }
448
+ if (typeof weappConf === 'object' && Object.keys(weappConf).length === 0) {
449
+ report('withWeapp 请传入“App/页面/组件“的配置对象。如果原生写法使用了基类,请将基类组合后的配置对象传入,详情请参考文档。');
442
450
  }
443
- class BaseComponent extends ConnectComponent {
444
- constructor(props) {
445
- super(props);
446
- this._observeProps = [];
447
- // mixins 可以多次调用生命周期
448
- this.willMounts = [];
449
- this.didMounts = [];
450
- this.didHides = [];
451
- this.didShows = [];
452
- this.willUnmounts = [];
453
- this.eventDestroyList = [];
454
- this.current = runtime.getCurrentInstance();
455
- this.taroGlobalData = Object.create(null);
456
- this.safeExecute = (func, ...args) => {
457
- if (isFunction(func)) func.apply(this, args);
458
- };
459
- this.setData = (obj, callback) => {
460
- let oldState;
461
- if (this.observers && Object.keys(Object.keys(this.observers))) {
462
- oldState = clone(this.state);
463
- }
464
- Object.keys(obj).forEach(key => {
465
- safeSet(this.state, key, obj[key]);
466
- });
467
- this.setState(this.state, () => {
468
- this.triggerObservers(this.state, oldState);
469
- if (callback) {
470
- callback.call(this);
471
- }
472
- });
473
- };
474
- this.triggerEvent = (eventName, detail, options) => {
475
- if (options) {
476
- report('triggerEvent 不支持事件选项。');
477
- }
478
- // eventName support kebab case
479
- if (eventName.match(/[a-z]+-[a-z]+/g)) {
480
- eventName = eventName.replace(/-[a-z]/g, function (match) {
481
- return match[1].toUpperCase();
482
- });
483
- }
484
- const props = this.props;
485
- const dataset = {};
486
- for (const key in props) {
487
- if (!key.startsWith('data-')) continue;
488
- dataset[key.replace(/^data-/, '')] = props[key];
489
- }
490
- const func = props[`on${eventName[0].toUpperCase()}${eventName.slice(1)}`];
491
- if (isFunction(func)) {
492
- func.call(this, {
493
- type: eventName,
494
- detail,
495
- target: {
496
- id: props.id || '',
497
- dataset
498
- },
499
- currentTarget: {
500
- id: props.id || '',
501
- dataset
502
- }
503
- });
504
- }
505
- };
506
- this.hasBehavior = this.componentMethodsProxy('hasBehavior');
507
- this.createSelectorQuery = this.componentMethodsProxy('createSelectorQuery');
508
- this.createIntersectionObserver = this.componentMethodsProxy('createIntersectionObserver');
509
- this.createMediaQueryObserver = this.componentMethodsProxy('createMediaQueryObserver');
510
- this.getRelationNodes = this.componentMethodsProxy('getRelationNodes');
511
- this.getTabBar = this.componentMethodsProxy('getTabBar');
512
- this.getPageId = this.componentMethodsProxy('getPageId');
513
- this.animate = this.componentMethodsProxy('animate');
514
- this.clearAnimation = this.componentMethodsProxy('clearAnimation');
515
- this.setUpdatePerformanceListener = this.componentMethodsProxy('setUpdatePerformanceListener');
516
- this.state = this.state || {};
517
- this.init(weappConf);
518
- defineGetter(this, 'data', 'state');
519
- defineGetter(this, 'properties', 'props');
520
- this.initComputed(weappConf);
521
- }
522
- initProps(props) {
523
- const properties = {};
524
- for (const propKey in props) {
525
- if (props.hasOwnProperty(propKey)) {
526
- const propValue = props[propKey];
527
- // propValue 可能是 null, 构造函数, 对象
528
- const observers = [propToState];
529
- if (propValue === null || propValue === undefined) {
530
- // propValue为null、undefined情况
531
- properties[propKey] = null;
532
- } else if (isFunction(propValue)) {
533
- // propValue为Function,即Array、String、Boolean等情况时
534
- if (propValue.name === 'Array') {
535
- properties[propKey] = [];
536
- } else if (propValue.name === 'String') {
537
- properties[propKey] = '';
538
- } else if (propValue.name === 'Boolean') {
539
- properties[propKey] = false;
540
- } else if (propValue.name === 'Number') {
541
- properties[propKey] = 0;
542
- } else {
543
- properties[propKey] = null;
544
- }
545
- } else if (typeof propValue === 'object') {
546
- // propValue为对象时
547
- properties[propKey] = propValue.value;
548
- if (propValue.observer) {
549
- observers.push(propValue.observer);
550
- }
551
- } else {
552
- properties[propKey] = null;
451
+ return (ConnectComponent) => {
452
+ var _a;
453
+ const behaviorMap = new Map([
454
+ ['properties', []],
455
+ ['data', []],
456
+ ['methods', []],
457
+ ['created', []],
458
+ ['attached', []],
459
+ ['ready', []],
460
+ ['detached', []],
461
+ ['lifetimes', []]
462
+ ]);
463
+ const behaviorProperties = {};
464
+ if ((_a = weappConf.behaviors) === null || _a === void 0 ? void 0 : _a.length) {
465
+ const { behaviors } = weappConf;
466
+ behaviors.forEach(behavior => flattenBehaviors(behavior, behaviorMap));
467
+ const propertiesList = behaviorMap.get('properties');
468
+ if (propertiesList.length) {
469
+ propertiesList.forEach(property => {
470
+ Object.assign(behaviorProperties, property);
471
+ });
472
+ Object.keys(behaviorProperties).forEach(propName => {
473
+ const propValue = behaviorProperties[propName];
474
+ if (!weappConf.properties) {
475
+ weappConf.properties = {};
476
+ }
477
+ if (!weappConf.properties.hasOwnProperty(propName)) {
478
+ if (propValue && typeof propValue === 'object' && propValue.value) {
479
+ propValue.value = clone(propValue.value);
480
+ }
481
+ weappConf.properties[propName] = propValue;
482
+ }
483
+ });
553
484
  }
554
- this._observeProps.push({
555
- name: propKey,
556
- observers: observers
557
- });
558
- }
559
485
  }
560
- this.state = Object.assign(Object.assign({}, properties), this.state);
561
- }
562
- init(options) {
563
- var _a, _b, _c;
564
- // 处理 Behaviors
565
- if ((_a = options.behaviors) === null || _a === void 0 ? void 0 : _a.length) {
566
- for (const [key, list] of behaviorMap.entries()) {
567
- switch (key) {
568
- case 'created':
569
- case 'attached':
570
- case 'detached':
571
- case 'ready':
572
- list.forEach(fn => this.initLifeCycles(key, fn));
573
- break;
486
+ class BaseComponent extends ConnectComponent {
487
+ constructor(props) {
488
+ super(props);
489
+ this._observeProps = [];
490
+ // mixins 可以多次调用生命周期
491
+ this.willMounts = [];
492
+ this.didMounts = [];
493
+ this.didHides = [];
494
+ this.didShows = [];
495
+ this.willUnmounts = [];
496
+ this.eventDestroyList = [];
497
+ this.current = runtime.getCurrentInstance();
498
+ this.taroGlobalData = Object.create(null);
499
+ this.safeExecute = (func, ...args) => {
500
+ if (isFunction(func))
501
+ func.apply(this, args);
502
+ };
503
+ this.setData = (obj, callback) => {
504
+ let oldState;
505
+ if (this.observers && Object.keys(Object.keys(this.observers))) {
506
+ oldState = clone(this.state);
507
+ }
508
+ Object.keys(obj).forEach(key => {
509
+ safeSet(this.state, key, obj[key]);
510
+ });
511
+ this.setState(this.state, () => {
512
+ this.triggerObservers(this.state, oldState);
513
+ if (callback) {
514
+ callback.call(this);
515
+ }
516
+ });
517
+ };
518
+ this.triggerEvent = (eventName, detail, options) => {
519
+ if (options) {
520
+ report('triggerEvent 不支持事件选项。');
521
+ }
522
+ // eventName support kebab case
523
+ if (eventName.match(/[a-z]+-[a-z]+/g)) {
524
+ eventName = eventName.replace(/-[a-z]/g, function (match) {
525
+ return match[1].toUpperCase();
526
+ });
527
+ }
528
+ const props = this.props;
529
+ const dataset = {};
530
+ for (const key in props) {
531
+ if (!key.startsWith('data-'))
532
+ continue;
533
+ dataset[key.replace(/^data-/, '')] = props[key];
534
+ }
535
+ const func = props[`on${eventName[0].toUpperCase()}${eventName.slice(1)}`];
536
+ if (isFunction(func)) {
537
+ func.call(this, {
538
+ type: eventName,
539
+ detail,
540
+ target: {
541
+ id: props.id || '',
542
+ dataset
543
+ },
544
+ currentTarget: {
545
+ id: props.id || '',
546
+ dataset
547
+ }
548
+ });
549
+ }
550
+ };
551
+ this.hasBehavior = this.componentMethodsProxy('hasBehavior');
552
+ this.createSelectorQuery = this.componentMethodsProxy('createSelectorQuery');
553
+ this.createIntersectionObserver = this.componentMethodsProxy('createIntersectionObserver');
554
+ this.createMediaQueryObserver = this.componentMethodsProxy('createMediaQueryObserver');
555
+ this.getRelationNodes = this.componentMethodsProxy('getRelationNodes');
556
+ this.getTabBar = this.componentMethodsProxy('getTabBar');
557
+ this.getPageId = this.componentMethodsProxy('getPageId');
558
+ this.animate = this.componentMethodsProxy('animate');
559
+ this.clearAnimation = this.componentMethodsProxy('clearAnimation');
560
+ this.setUpdatePerformanceListener = this.componentMethodsProxy('setUpdatePerformanceListener');
561
+ this.state = this.state || {};
562
+ this.init(weappConf);
563
+ defineGetter(this, 'data', 'state');
564
+ defineGetter(this, 'properties', 'props');
565
+ this.initComputed(weappConf);
574
566
  }
575
- }
576
- }
577
- for (const confKey in options) {
578
- // 不支持的属性
579
- if (nonsupport.has(confKey)) {
580
- const advise = nonsupport.get(confKey);
581
- report(advise);
582
- }
583
- const confValue = options[confKey];
584
- switch (confKey) {
585
- case 'behaviors':
586
- break;
587
- case 'data':
588
- {
589
- if (isApp) {
590
- this[confKey] = confValue;
591
- if (!appOptions.includes(confKey)) {
592
- this.defineProperty(this.taroGlobalData, confKey, this);
593
- }
594
- } else {
595
- this.state = Object.assign(Object.assign({}, confValue), this.state);
567
+ initProps(props) {
568
+ const properties = {};
569
+ for (const propKey in props) {
570
+ if (props.hasOwnProperty(propKey)) {
571
+ const propValue = props[propKey];
572
+ // propValue 可能是 null, 构造函数, 对象
573
+ const observers = [propToState];
574
+ if (propValue === null || propValue === undefined) { // propValue为null、undefined情况
575
+ properties[propKey] = null;
576
+ }
577
+ else if (isFunction(propValue)) { // propValue为Function,即Array、String、Boolean等情况时
578
+ if (propValue.name === 'Array') {
579
+ properties[propKey] = [];
580
+ }
581
+ else if (propValue.name === 'String') {
582
+ properties[propKey] = '';
583
+ }
584
+ else if (propValue.name === 'Boolean') {
585
+ properties[propKey] = false;
586
+ }
587
+ else if (propValue.name === 'Number') {
588
+ properties[propKey] = 0;
589
+ }
590
+ else {
591
+ properties[propKey] = null;
592
+ }
593
+ }
594
+ else if (typeof propValue === 'object') { // propValue为对象时
595
+ properties[propKey] = propValue.value;
596
+ if (propValue.observer) {
597
+ observers.push(propValue.observer);
598
+ }
599
+ }
600
+ else {
601
+ properties[propKey] = null;
602
+ }
603
+ this._observeProps.push({
604
+ name: propKey,
605
+ observers: observers
606
+ });
607
+ }
596
608
  }
597
- break;
598
- }
599
- case 'properties':
600
- this.initProps(Object.assign(behaviorProperties, confValue));
601
- break;
602
- case 'methods':
603
- this.methods = confValue;
604
- for (const key in confValue) {
605
- const method = confValue[key];
606
- this[key] = bind(method, this);
607
- }
608
- break;
609
- case 'lifetimes':
610
- for (const key in confValue) {
611
- this.initLifeCycles(key, confValue[key]);
612
- }
613
- break;
614
- case 'pageLifetimes':
615
- for (const key in confValue) {
616
- const cb = confValue[key];
617
- switch (key) {
618
- case 'show':
619
- {
620
- this.initLifeCycleListener('show', cb);
621
- break;
609
+ this.state = Object.assign(Object.assign({}, properties), this.state);
610
+ }
611
+ init(options) {
612
+ var _a, _b, _c;
613
+ // 处理 Behaviors
614
+ if ((_a = options.behaviors) === null || _a === void 0 ? void 0 : _a.length) {
615
+ for (const [key, list] of behaviorMap.entries()) {
616
+ switch (key) {
617
+ case 'created':
618
+ case 'attached':
619
+ case 'detached':
620
+ case 'ready':
621
+ list.forEach(fn => this.initLifeCycles(key, fn));
622
+ break;
623
+ }
622
624
  }
623
- case 'hide':
624
- {
625
- this.initLifeCycleListener('hide', cb);
626
- break;
625
+ }
626
+ for (const confKey in options) {
627
+ // 不支持的属性
628
+ if (nonsupport.has(confKey)) {
629
+ const advise = nonsupport.get(confKey);
630
+ report(advise);
627
631
  }
628
- case 'resize':
629
- {
630
- report('不支持组件所在页面的生命周期 pageLifetimes.resize。');
631
- break;
632
+ const confValue = options[confKey];
633
+ switch (confKey) {
634
+ case 'behaviors':
635
+ break;
636
+ case 'data': {
637
+ if (isApp) {
638
+ this[confKey] = confValue;
639
+ if (!appOptions.includes(confKey)) {
640
+ this.defineProperty(this.taroGlobalData, confKey, this);
641
+ }
642
+ }
643
+ else {
644
+ this.state = Object.assign(Object.assign({}, confValue), this.state);
645
+ }
646
+ break;
647
+ }
648
+ case 'properties':
649
+ this.initProps(Object.assign(behaviorProperties, confValue));
650
+ break;
651
+ case 'methods':
652
+ this.methods = confValue;
653
+ for (const key in confValue) {
654
+ const method = confValue[key];
655
+ this[key] = bind(method, this);
656
+ }
657
+ break;
658
+ case 'lifetimes':
659
+ for (const key in confValue) {
660
+ this.initLifeCycles(key, confValue[key]);
661
+ }
662
+ break;
663
+ case 'pageLifetimes':
664
+ for (const key in confValue) {
665
+ const cb = confValue[key];
666
+ switch (key) {
667
+ case 'show': {
668
+ this.initLifeCycleListener('show', cb);
669
+ break;
670
+ }
671
+ case 'hide': {
672
+ this.initLifeCycleListener('hide', cb);
673
+ break;
674
+ }
675
+ case 'resize': {
676
+ report('不支持组件所在页面的生命周期 pageLifetimes.resize。');
677
+ break;
678
+ }
679
+ }
680
+ }
681
+ break;
682
+ default:
683
+ if (lifecycles.has(confKey)) {
684
+ // 优先使用 lifetimes 中定义的生命周期
685
+ if ((_b = options.lifetimes) === null || _b === void 0 ? void 0 : _b[confKey]) {
686
+ break;
687
+ }
688
+ const lifecycle = options[confKey];
689
+ this.initLifeCycles(confKey, lifecycle);
690
+ }
691
+ else if (isFunction(confValue)) {
692
+ this[confKey] = bind(confValue, this);
693
+ if (isApp && !appOptions.includes(confKey)) {
694
+ this.defineProperty(this.taroGlobalData, confKey, this);
695
+ }
696
+ // 原生页面和 Taro 页面中共计只能定义一次的生命周期
697
+ if (uniquePageLifecycle.includes(confKey) && ConnectComponent.prototype[confKey]) {
698
+ report(`生命周期 ${confKey} 已在原生部分进行定义,React 部分的定义将不会被执行。`);
699
+ }
700
+ }
701
+ else {
702
+ this[confKey] = confValue;
703
+ if (isApp && !appOptions.includes(confKey)) {
704
+ this.defineProperty(this.taroGlobalData, confKey, this);
705
+ }
706
+ }
707
+ break;
632
708
  }
633
709
  }
634
- }
635
- break;
636
- default:
637
- if (lifecycles.has(confKey)) {
638
- // 优先使用 lifetimes 中定义的生命周期
639
- if ((_b = options.lifetimes) === null || _b === void 0 ? void 0 : _b[confKey]) {
640
- break;
710
+ // 处理 Behaviors
711
+ if ((_c = options.behaviors) === null || _c === void 0 ? void 0 : _c.length) {
712
+ const behaviorData = {};
713
+ const methods = {};
714
+ for (const [key, list] of behaviorMap.entries()) {
715
+ switch (key) {
716
+ case 'data':
717
+ [...list, this.state].forEach((dataObject, index) => {
718
+ Object.keys(dataObject).forEach(dataKey => {
719
+ const value = dataObject[dataKey];
720
+ const preValue = behaviorData[dataKey];
721
+ const valueType = typeof value;
722
+ const preValueType = typeof preValue;
723
+ if (valueType === 'object') {
724
+ if (!value) {
725
+ behaviorData[dataKey] = value;
726
+ }
727
+ else if (preValueType !== 'object' || !preValueType || Array.isArray(value)) {
728
+ behaviorData[dataKey] = index === list.length ? value : clone(value);
729
+ }
730
+ else {
731
+ const newVal = Object.assign({}, preValue, value);
732
+ behaviorData[dataKey] = index === list.length ? newVal : clone(newVal);
733
+ }
734
+ }
735
+ else {
736
+ behaviorData[dataKey] = value;
737
+ }
738
+ });
739
+ });
740
+ this.state = behaviorData;
741
+ break;
742
+ case 'methods':
743
+ list.forEach(methodsObject => {
744
+ Object.assign(methods, methodsObject);
745
+ });
746
+ Object.keys(methods).forEach(methodName => {
747
+ if (!this[methodName]) {
748
+ const method = methods[methodName];
749
+ this[methodName] = bind(method, this);
750
+ }
751
+ });
752
+ break;
753
+ case 'lifetimes':
754
+ list.forEach(lifetimesObject => {
755
+ for (const key in lifetimesObject) {
756
+ this.initLifeCycles(key, lifetimesObject[key]);
757
+ }
758
+ });
759
+ break;
760
+ }
761
+ }
641
762
  }
642
- const lifecycle = options[confKey];
643
- this.initLifeCycles(confKey, lifecycle);
644
- } else if (isFunction(confValue)) {
645
- this[confKey] = bind(confValue, this);
646
- if (isApp && !appOptions.includes(confKey)) {
647
- this.defineProperty(this.taroGlobalData, confKey, this);
763
+ }
764
+ initComputed(weappConf) {
765
+ // 处理 computed
766
+ if (weappConf.computed) {
767
+ const computed = weappConf.computed;
768
+ for (const key in computed) {
769
+ const getter = computed[key];
770
+ if (isFunction(getter)) {
771
+ Object.defineProperty(this.data, key, {
772
+ get: () => {
773
+ // 每次访问 this.object.data[name] 时,都执行 computed[name]()
774
+ return getter.call(Object.assign(Object.assign({}, this.state), this.methods));
775
+ },
776
+ enumerable: true, // 这将确保属性是可枚举的,如果你希望它出现在 for...in 循环中
777
+ configurable: true // 这将确保属性是可配置的,比如可以被删除
778
+ });
779
+ }
780
+ else {
781
+ report('computed 属性值必须是函数。');
782
+ }
783
+ }
648
784
  }
649
- // 原生页面和 Taro 页面中共计只能定义一次的生命周期
650
- if (uniquePageLifecycle.includes(confKey) && ConnectComponent.prototype[confKey]) {
651
- report(`生命周期 ${confKey} 已在原生部分进行定义,React 部分的定义将不会被执行。`);
785
+ }
786
+ initLifeCycles(lifecycleName, lifecycle) {
787
+ // 不支持的生命周期
788
+ if (nonsupport.has(lifecycleName)) {
789
+ const advise = nonsupport.get(lifecycleName);
790
+ return report(advise);
652
791
  }
653
- } else {
654
- this[confKey] = confValue;
655
- if (isApp && !appOptions.includes(confKey)) {
656
- this.defineProperty(this.taroGlobalData, confKey, this);
792
+ if (lifecycleName === 'ready') {
793
+ // 如果组件是延时渲染的,页面 onReady 的事件已经 emit 了,因此使用 componentDidMount + nextTick 模拟
794
+ if (this.current.page.onReady.called) {
795
+ this.didMounts.push(function (...args) {
796
+ taro.nextTick(() => {
797
+ if (isFunction(lifecycle)) {
798
+ lifecycle.apply(this, args);
799
+ }
800
+ });
801
+ });
802
+ }
803
+ else {
804
+ this.initLifeCycleListener('ready', lifecycle);
805
+ }
657
806
  }
658
- }
659
- break;
660
- }
661
- }
662
- // 处理 Behaviors
663
- if ((_c = options.behaviors) === null || _c === void 0 ? void 0 : _c.length) {
664
- const behaviorData = {};
665
- const methods = {};
666
- for (const [key, list] of behaviorMap.entries()) {
667
- switch (key) {
668
- case 'data':
669
- [...list, this.state].forEach((dataObject, index) => {
670
- Object.keys(dataObject).forEach(dataKey => {
671
- const value = dataObject[dataKey];
672
- const preValue = behaviorData[dataKey];
673
- const valueType = typeof value;
674
- const preValueType = typeof preValue;
675
- if (valueType === 'object') {
676
- if (!value) {
677
- behaviorData[dataKey] = value;
678
- } else if (preValueType !== 'object' || !preValueType || Array.isArray(value)) {
679
- behaviorData[dataKey] = index === list.length ? value : clone(value);
680
- } else {
681
- const newVal = Object.assign({}, preValue, value);
682
- behaviorData[dataKey] = index === list.length ? newVal : clone(newVal);
683
- }
684
- } else {
685
- behaviorData[dataKey] = value;
807
+ else {
808
+ for (const lifecycleKey in lifecycleMap) {
809
+ const cycleNames = lifecycleMap[lifecycleKey];
810
+ if (cycleNames.indexOf(lifecycleName) !== -1) {
811
+ switch (lifecycleKey) {
812
+ case TaroLifeCycles.DidHide:
813
+ this.didHides.push(lifecycle);
814
+ break;
815
+ case TaroLifeCycles.DidMount:
816
+ this.didMounts.push(lifecycle);
817
+ break;
818
+ case TaroLifeCycles.DidShow:
819
+ this.didShows.push(lifecycle);
820
+ break;
821
+ case TaroLifeCycles.WillMount:
822
+ this.willMounts.push(lifecycle);
823
+ break;
824
+ case TaroLifeCycles.WillUnmount:
825
+ this.willUnmounts.push(lifecycle);
826
+ break;
827
+ }
828
+ }
829
+ }
830
+ }
831
+ // mixins 不会覆盖已经设置的生命周期,加入到 this 是为了形如 this.created() 的调用
832
+ if (!isFunction(this[lifecycleName])) {
833
+ this[lifecycleName] = lifecycle;
834
+ }
835
+ }
836
+ initLifeCycleListener(name, cb) {
837
+ // 组件的 ready、show、hide 需要利用页面事件触发
838
+ const { router } = this.current;
839
+ const lifecycleName = `on${name[0].toUpperCase()}${name.slice(1)}`;
840
+ cb = cb.bind(this);
841
+ (router === null || router === void 0 ? void 0 : router[lifecycleName]) && taro.eventCenter.on(router[lifecycleName], cb);
842
+ // unMount 时需要取消事件监听
843
+ this.eventDestroyList.push(() => taro.eventCenter.off(router[lifecycleName], cb));
844
+ }
845
+ executeLifeCycles(funcs, ...args) {
846
+ for (let i = 0; i < funcs.length; i++) {
847
+ const func = funcs[i];
848
+ this.safeExecute(func, ...args);
849
+ }
850
+ }
851
+ triggerPropertiesObservers(prevProps, nextProps) {
852
+ this._observeProps.forEach(({ name: key, observers }) => {
853
+ const prop = prevProps === null || prevProps === void 0 ? void 0 : prevProps[key];
854
+ const nextProp = nextProps[key];
855
+ // 小程序是深比较不同之后才 trigger observer
856
+ if (!isEqual(prop, nextProp)) {
857
+ observers.forEach((observer) => {
858
+ if (typeof observer === 'string') {
859
+ const ob = this[observer];
860
+ if (isFunction(ob)) {
861
+ ob.call(this, nextProp, prop, key);
862
+ }
863
+ }
864
+ else if (isFunction(observer)) {
865
+ observer.call(this, nextProp, prop, key);
866
+ }
867
+ });
686
868
  }
687
- });
688
- });
689
- this.state = behaviorData;
690
- break;
691
- case 'methods':
692
- list.forEach(methodsObject => {
693
- Object.assign(methods, methodsObject);
694
- });
695
- Object.keys(methods).forEach(methodName => {
696
- if (!this[methodName]) {
697
- const method = methods[methodName];
698
- this[methodName] = bind(method, this);
699
- }
700
- });
701
- break;
702
- case 'lifetimes':
703
- list.forEach(lifetimesObject => {
704
- for (const key in lifetimesObject) {
705
- this.initLifeCycles(key, lifetimesObject[key]);
706
- }
707
869
  });
708
- break;
709
870
  }
710
- }
711
- }
712
- }
713
- initComputed(weappConf) {
714
- // 处理 computed
715
- if (weappConf.computed) {
716
- const computed = weappConf.computed;
717
- for (const key in computed) {
718
- const getter = computed[key];
719
- if (isFunction(getter)) {
720
- Object.defineProperty(this.data, key, {
721
- get: () => {
722
- // 每次访问 this.object.data[name] 时,都执行 computed[name]()
723
- return getter.call(Object.assign(Object.assign({}, this.state), this.methods));
724
- },
725
- enumerable: true,
726
- configurable: true // 这将确保属性是可配置的,比如可以被删除
727
- });
728
- } else {
729
- report('computed 属性值必须是函数。');
871
+ triggerObservers(current, prev) {
872
+ const observers = this.observers;
873
+ if (observers == null) {
874
+ return;
875
+ }
876
+ if (Object.keys(observers).length === 0) {
877
+ return;
878
+ }
879
+ const result = diff(current, prev);
880
+ const resultKeys = Object.keys(result);
881
+ if (resultKeys.length === 0) {
882
+ return;
883
+ }
884
+ for (const observerKey in observers) {
885
+ if (/\*\*/.test(observerKey)) {
886
+ report('数据监听器 observers 不支持使用通配符 **。');
887
+ continue;
888
+ }
889
+ const keys = observerKey.split(',').map(k => k.trim());
890
+ let isModified = false;
891
+ for (let i = 0; i < keys.length; i++) {
892
+ const key = keys[i];
893
+ for (let j = 0; j < resultKeys.length; j++) {
894
+ const resultKey = resultKeys[j];
895
+ if (resultKey.startsWith(key) ||
896
+ (key.startsWith(resultKey) && key.endsWith(']'))) {
897
+ isModified = true;
898
+ }
899
+ }
900
+ }
901
+ if (isModified) {
902
+ observers[observerKey].apply(this, keys.map(key => safeGet(current, key)));
903
+ }
904
+ }
730
905
  }
731
- }
732
- }
733
- }
734
- initLifeCycles(lifecycleName, lifecycle) {
735
- // 不支持的生命周期
736
- if (nonsupport.has(lifecycleName)) {
737
- const advise = nonsupport.get(lifecycleName);
738
- return report(advise);
739
- }
740
- if (lifecycleName === 'ready') {
741
- // 如果组件是延时渲染的,页面 onReady 的事件已经 emit 了,因此使用 componentDidMount + nextTick 模拟
742
- if (this.current.page.onReady.called) {
743
- this.didMounts.push(function (...args) {
744
- taro.nextTick(() => {
745
- if (isFunction(lifecycle)) {
746
- lifecycle.apply(this, args);
906
+ defineProperty(target, key, data) {
907
+ Object.defineProperty(target, key, {
908
+ configurable: true,
909
+ enumerable: true,
910
+ set(value) {
911
+ data[key] = value;
912
+ },
913
+ get() {
914
+ return data[key];
915
+ }
916
+ });
917
+ }
918
+ privateStopNoop(...args) {
919
+ let e;
920
+ let fn;
921
+ if (args.length === 2) {
922
+ fn = args[0];
923
+ e = args[1];
747
924
  }
748
- });
749
- });
750
- } else {
751
- this.initLifeCycleListener('ready', lifecycle);
752
- }
753
- } else {
754
- for (const lifecycleKey in lifecycleMap) {
755
- const cycleNames = lifecycleMap[lifecycleKey];
756
- if (cycleNames.indexOf(lifecycleName) !== -1) {
757
- switch (lifecycleKey) {
758
- case TaroLifeCycles.DidHide:
759
- this.didHides.push(lifecycle);
760
- break;
761
- case TaroLifeCycles.DidMount:
762
- this.didMounts.push(lifecycle);
763
- break;
764
- case TaroLifeCycles.DidShow:
765
- this.didShows.push(lifecycle);
766
- break;
767
- case TaroLifeCycles.WillMount:
768
- this.willMounts.push(lifecycle);
769
- break;
770
- case TaroLifeCycles.WillUnmount:
771
- this.willUnmounts.push(lifecycle);
772
- break;
773
- }
925
+ else if (args.length === 1) {
926
+ e = args[0];
927
+ }
928
+ if (e.type === 'touchmove') {
929
+ report('catchtouchmove 转换后只能停止回调函数的冒泡,不能阻止滚动穿透。如要阻止滚动穿透,可以手动给编译后的 View 组件加上 catchMove 属性');
930
+ }
931
+ e.stopPropagation();
932
+ isFunction(fn) && fn(e);
933
+ }
934
+ // ================ React 生命周期 ================
935
+ componentWillMount() {
936
+ this.safeExecute(super.componentWillMount);
937
+ this.executeLifeCycles(this.willMounts, this.current.router || {});
938
+ this.triggerObservers(this.data, BaseComponent.defaultProps);
939
+ this.triggerPropertiesObservers(BaseComponent.defaultProps, this.props);
940
+ }
941
+ componentDidMount() {
942
+ this.safeExecute(super.componentDidMount);
943
+ this.executeLifeCycles(this.didMounts);
944
+ }
945
+ componentWillUnmount() {
946
+ this.eventDestroyList.forEach(fn => fn());
947
+ this.safeExecute(super.componentWillUnmount);
948
+ this.executeLifeCycles(this.willUnmounts);
949
+ }
950
+ componentDidHide() {
951
+ this.safeExecute(super.componentDidHide);
952
+ this.executeLifeCycles(this.didHides);
953
+ }
954
+ componentDidShow() {
955
+ this.safeExecute(super.componentDidShow, this.current.router || {});
956
+ this.executeLifeCycles(this.didShows, this.current.router || {});
957
+ }
958
+ componentWillReceiveProps(nextProps) {
959
+ this.triggerObservers(nextProps, this.props);
960
+ this.triggerPropertiesObservers(this.props, nextProps);
961
+ this.safeExecute(super.componentWillReceiveProps);
962
+ }
963
+ // ================ 小程序 App, Page, Component 实例属性与方法 ================
964
+ get is() {
965
+ return this.current.page.is;
966
+ }
967
+ get id() {
968
+ return this.current.page.id;
969
+ }
970
+ get dataset() {
971
+ return this.current.page.dataset;
972
+ }
973
+ componentMethodsProxy(method) {
974
+ return (...args) => {
975
+ const page = this.current.page;
976
+ if (page === null || page === void 0 ? void 0 : page[method]) {
977
+ return page[method](...args);
978
+ }
979
+ else if (method === 'createSelectorQuery') {
980
+ return taro.createSelectorQuery();
981
+ }
982
+ else if (method === 'createIntersectionObserver') {
983
+ // @ts-ignore
984
+ return taro.createIntersectionObserver(...args);
985
+ }
986
+ else if (method === 'createMediaQueryObserver') {
987
+ return taro.createMediaQueryObserver();
988
+ }
989
+ else {
990
+ console.error(`page 下没有 ${method} 方法`);
991
+ }
992
+ };
993
+ }
994
+ selectComponent() {
995
+ report(nonsupport.get('selectComponent'));
996
+ }
997
+ selectAllComponents() {
998
+ report(nonsupport.get('selectAllComponents'));
999
+ }
1000
+ selectOwnerComponent() {
1001
+ report(nonsupport.get('selectOwnerComponent'));
1002
+ }
1003
+ groupSetData() {
1004
+ report(nonsupport.get('groupSetData'));
774
1005
  }
775
- }
776
- }
777
- // mixins 不会覆盖已经设置的生命周期,加入到 this 是为了形如 this.created() 的调用
778
- if (!isFunction(this[lifecycleName])) {
779
- this[lifecycleName] = lifecycle;
780
- }
781
- }
782
- initLifeCycleListener(name, cb) {
783
- // 组件的 ready、show、hide 需要利用页面事件触发
784
- const {
785
- router
786
- } = this.current;
787
- const lifecycleName = `on${name[0].toUpperCase()}${name.slice(1)}`;
788
- cb = cb.bind(this);
789
- (router === null || router === void 0 ? void 0 : router[lifecycleName]) && taro.eventCenter.on(router[lifecycleName], cb);
790
- // unMount 时需要取消事件监听
791
- this.eventDestroyList.push(() => taro.eventCenter.off(router[lifecycleName], cb));
792
- }
793
- executeLifeCycles(funcs, ...args) {
794
- for (let i = 0; i < funcs.length; i++) {
795
- const func = funcs[i];
796
- this.safeExecute(func, ...args);
797
1006
  }
798
- }
799
- triggerPropertiesObservers(prevProps, nextProps) {
800
- this._observeProps.forEach(({
801
- name: key,
802
- observers
803
- }) => {
804
- const prop = prevProps === null || prevProps === void 0 ? void 0 : prevProps[key];
805
- const nextProp = nextProps[key];
806
- // 小程序是深比较不同之后才 trigger observer
807
- if (!isEqual(prop, nextProp)) {
808
- observers.forEach(observer => {
809
- if (typeof observer === 'string') {
810
- const ob = this[observer];
811
- if (isFunction(ob)) {
812
- ob.call(this, nextProp, prop, key);
1007
+ const props = weappConf.properties;
1008
+ if (props) {
1009
+ for (const propKey in props) {
1010
+ const propValue = props[propKey];
1011
+ if (propValue != null && !isFunction(propValue)) {
1012
+ if (propValue.value !== undefined) { // 如果是 null 也赋值到 defaultProps
1013
+ BaseComponent.defaultProps = Object.assign({ [propKey]: propValue.value }, BaseComponent.defaultProps);
1014
+ }
813
1015
  }
814
- } else if (isFunction(observer)) {
815
- observer.call(this, nextProp, prop, key);
816
- }
817
- });
818
- }
819
- });
820
- }
821
- triggerObservers(current, prev) {
822
- const observers = this.observers;
823
- if (observers == null) {
824
- return;
825
- }
826
- if (Object.keys(observers).length === 0) {
827
- return;
828
- }
829
- const result = diff(current, prev);
830
- const resultKeys = Object.keys(result);
831
- if (resultKeys.length === 0) {
832
- return;
833
- }
834
- for (const observerKey in observers) {
835
- if (/\*\*/.test(observerKey)) {
836
- report('数据监听器 observers 不支持使用通配符 **。');
837
- continue;
838
- }
839
- const keys = observerKey.split(',').map(k => k.trim());
840
- let isModified = false;
841
- for (let i = 0; i < keys.length; i++) {
842
- const key = keys[i];
843
- for (let j = 0; j < resultKeys.length; j++) {
844
- const resultKey = resultKeys[j];
845
- if (resultKey.startsWith(key) || key.startsWith(resultKey) && key.endsWith(']')) {
846
- isModified = true;
847
- }
848
1016
  }
849
- }
850
- if (isModified) {
851
- observers[observerKey].apply(this, keys.map(key => safeGet(current, key)));
852
- }
853
1017
  }
854
- }
855
- defineProperty(target, key, data) {
856
- Object.defineProperty(target, key, {
857
- configurable: true,
858
- enumerable: true,
859
- set(value) {
860
- data[key] = value;
861
- },
862
- get() {
863
- return data[key];
864
- }
1018
+ const staticOptions = ['externalClasses', 'relations', 'options'];
1019
+ staticOptions.forEach(option => {
1020
+ const value = weappConf[option];
1021
+ if (value != null) {
1022
+ BaseComponent[option] = value;
1023
+ }
865
1024
  });
866
- }
867
- privateStopNoop(...args) {
868
- let e;
869
- let fn;
870
- if (args.length === 2) {
871
- fn = args[0];
872
- e = args[1];
873
- } else if (args.length === 1) {
874
- e = args[0];
875
- }
876
- if (e.type === 'touchmove') {
877
- report('catchtouchmove 转换后只能停止回调函数的冒泡,不能阻止滚动穿透。如要阻止滚动穿透,可以手动给编译后的 View 组件加上 catchMove 属性');
878
- }
879
- e.stopPropagation();
880
- isFunction(fn) && fn(e);
881
- }
882
- // ================ React 生命周期 ================
883
- componentWillMount() {
884
- this.safeExecute(super.componentWillMount);
885
- this.executeLifeCycles(this.willMounts, this.current.router || {});
886
- this.triggerObservers(this.data, BaseComponent.defaultProps);
887
- this.triggerPropertiesObservers(BaseComponent.defaultProps, this.props);
888
- }
889
- componentDidMount() {
890
- this.safeExecute(super.componentDidMount);
891
- this.executeLifeCycles(this.didMounts);
892
- }
893
- componentWillUnmount() {
894
- this.eventDestroyList.forEach(fn => fn());
895
- this.safeExecute(super.componentWillUnmount);
896
- this.executeLifeCycles(this.willUnmounts);
897
- }
898
- componentDidHide() {
899
- this.safeExecute(super.componentDidHide);
900
- this.executeLifeCycles(this.didHides);
901
- }
902
- componentDidShow() {
903
- this.safeExecute(super.componentDidShow, this.current.router || {});
904
- this.executeLifeCycles(this.didShows, this.current.router || {});
905
- }
906
- componentWillReceiveProps(nextProps) {
907
- this.triggerObservers(nextProps, this.props);
908
- this.triggerPropertiesObservers(this.props, nextProps);
909
- this.safeExecute(super.componentWillReceiveProps);
910
- }
911
- // ================ 小程序 App, Page, Component 实例属性与方法 ================
912
- get is() {
913
- return this.current.page.is;
914
- }
915
- get id() {
916
- return this.current.page.id;
917
- }
918
- get dataset() {
919
- return this.current.page.dataset;
920
- }
921
- componentMethodsProxy(method) {
922
- return (...args) => {
923
- const page = this.current.page;
924
- if (page === null || page === void 0 ? void 0 : page[method]) {
925
- return page[method](...args);
926
- } else if (method === 'createSelectorQuery') {
927
- return taro.createSelectorQuery();
928
- } else if (method === 'createIntersectionObserver') {
929
- // @ts-ignore
930
- return taro.createIntersectionObserver(...args);
931
- } else if (method === 'createMediaQueryObserver') {
932
- return taro.createMediaQueryObserver();
933
- } else {
934
- console.error(`page 下没有 ${method} 方法`);
935
- }
936
- };
937
- }
938
- selectComponent() {
939
- report(nonsupport.get('selectComponent'));
940
- }
941
- selectAllComponents() {
942
- report(nonsupport.get('selectAllComponents'));
943
- }
944
- selectOwnerComponent() {
945
- report(nonsupport.get('selectOwnerComponent'));
946
- }
947
- groupSetData() {
948
- report(nonsupport.get('groupSetData'));
949
- }
950
- }
951
- const props = weappConf.properties;
952
- if (props) {
953
- for (const propKey in props) {
954
- const propValue = props[propKey];
955
- if (propValue != null && !isFunction(propValue)) {
956
- if (propValue.value !== undefined) {
957
- // 如果是 null 也赋值到 defaultProps
958
- BaseComponent.defaultProps = Object.assign({
959
- [propKey]: propValue.value
960
- }, BaseComponent.defaultProps);
961
- }
962
- }
963
- }
964
- }
965
- const staticOptions = ['externalClasses', 'relations', 'options'];
966
- staticOptions.forEach(option => {
967
- const value = weappConf[option];
968
- if (value != null) {
969
- BaseComponent[option] = value;
970
- }
971
- });
972
- return BaseComponent;
973
- };
1025
+ return BaseComponent;
1026
+ };
974
1027
  }
975
1028
 
976
1029
  exports.cacheOptions = cacheOptions;
977
1030
  exports.convertToArray = convertToArray;
978
- exports["default"] = withWeapp;
1031
+ exports.default = withWeapp;
979
1032
  exports.getTarget = getTarget;
980
1033
 
981
1034
  Object.defineProperty(exports, '__esModule', { value: true });