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

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