@tarojs/with-weapp 4.0.0-beta.87 → 4.0.0-beta.89

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