@tarojs/api 3.6.22-nightly.0 → 3.6.22-nightly.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,945 @@
1
+ 'use strict';
2
+
3
+ var shared = require('@tarojs/shared');
4
+ var runtime = require('@tarojs/runtime');
5
+
6
+ function throttle(fn, threshold = 250, scope) {
7
+ let lastTime = 0;
8
+ let deferTimer;
9
+ return function (...args) {
10
+ const context = scope || this;
11
+ const now = Date.now();
12
+ if (now - lastTime > threshold) {
13
+ fn.apply(this, args);
14
+ lastTime = now;
15
+ }
16
+ else {
17
+ clearTimeout(deferTimer);
18
+ deferTimer = setTimeout(() => {
19
+ lastTime = now;
20
+ fn.apply(context, args);
21
+ }, threshold);
22
+ }
23
+ };
24
+ }
25
+
26
+ /* eslint-disable eqeqeq */
27
+ function handleIntersectionObserverPolyfill() {
28
+ // Exit early if all IntersectionObserver and IntersectionObserverEntry
29
+ // features are natively supported.
30
+ if ('IntersectionObserver' in window &&
31
+ 'IntersectionObserverEntry' in window &&
32
+ 'intersectionRatio' in window.IntersectionObserverEntry.prototype) {
33
+ if (!('isIntersecting' in window.IntersectionObserverEntry.prototype)) {
34
+ // Minimal polyfill for Edge 15's lack of `isIntersecting`
35
+ // See: https://github.com/w3c/IntersectionObserver/issues/211
36
+ Object.defineProperty(window.IntersectionObserverEntry.prototype, 'isIntersecting', {
37
+ get: function () {
38
+ return this.intersectionRatio > 0;
39
+ }
40
+ });
41
+ }
42
+ }
43
+ else {
44
+ handleIntersectionObserverObjectPolyfill();
45
+ }
46
+ }
47
+ function handleIntersectionObserverObjectPolyfill() {
48
+ const document = window.document;
49
+ /**
50
+ * Creates the global IntersectionObserverEntry constructor.
51
+ * https://w3c.github.io/IntersectionObserver/#intersection-observer-entry
52
+ * @param {Object} entry A dictionary of instance properties.
53
+ * @constructor
54
+ */
55
+ function IntersectionObserverEntry(entry) {
56
+ this.time = entry.time;
57
+ this.target = entry.target;
58
+ this.rootBounds = entry.rootBounds;
59
+ this.boundingClientRect = entry.boundingClientRect;
60
+ this.intersectionRect = entry.intersectionRect || getEmptyRect();
61
+ this.isIntersecting = !!entry.intersectionRect;
62
+ // Calculates the intersection ratio.
63
+ const targetRect = this.boundingClientRect;
64
+ const targetArea = targetRect.width * targetRect.height;
65
+ const intersectionRect = this.intersectionRect;
66
+ const intersectionArea = intersectionRect.width * intersectionRect.height;
67
+ // Sets intersection ratio.
68
+ if (targetArea) {
69
+ // Round the intersection ratio to avoid floating point math issues:
70
+ // https://github.com/w3c/IntersectionObserver/issues/324
71
+ this.intersectionRatio = Number((intersectionArea / targetArea).toFixed(4));
72
+ }
73
+ else {
74
+ // If area is zero and is intersecting, sets to 1, otherwise to 0
75
+ this.intersectionRatio = this.isIntersecting ? 1 : 0;
76
+ }
77
+ }
78
+ /**
79
+ * Creates the global IntersectionObserver constructor.
80
+ * https://w3c.github.io/IntersectionObserver/#intersection-observer-interface
81
+ * @param {Function} callback The function to be invoked after intersection
82
+ * changes have queued. The function is not invoked if the queue has
83
+ * been emptied by calling the `takeRecords` method.
84
+ * @param {Object=} opt_options Optional configuration options.
85
+ * @constructor
86
+ */
87
+ function IntersectionObserver(callback, options = {}) {
88
+ if (!shared.isFunction(callback)) {
89
+ throw new Error('callback must be a function');
90
+ }
91
+ if (options.root && options.root.nodeType != 1) {
92
+ throw new Error('root must be an Element');
93
+ }
94
+ // Binds and throttles `this._checkForIntersections`.
95
+ this._checkForIntersections = throttle(this._checkForIntersections.bind(this), this.THROTTLE_TIMEOUT);
96
+ // Private properties.
97
+ this._callback = callback;
98
+ this._observationTargets = [];
99
+ this._queuedEntries = [];
100
+ this._rootMarginValues = this._parseRootMargin(options.rootMargin);
101
+ // Public properties.
102
+ this.thresholds = this._initThresholds(options.threshold);
103
+ this.root = options.root || null;
104
+ this.rootMargin = this._rootMarginValues.map(function (margin) {
105
+ return margin.value + margin.unit;
106
+ }).join(' ');
107
+ }
108
+ /**
109
+ * The minimum interval within which the document will be checked for
110
+ * intersection changes.
111
+ */
112
+ IntersectionObserver.prototype.THROTTLE_TIMEOUT = 100;
113
+ /**
114
+ * The frequency in which the polyfill polls for intersection changes.
115
+ * this can be updated on a per instance basis and must be set prior to
116
+ * calling `observe` on the first target.
117
+ */
118
+ IntersectionObserver.prototype.POLL_INTERVAL = null;
119
+ /**
120
+ * Use a mutation observer on the root element
121
+ * to detect intersection changes.
122
+ */
123
+ IntersectionObserver.prototype.USE_MUTATION_OBSERVER = true;
124
+ /**
125
+ * Starts observing a target element for intersection changes based on
126
+ * the thresholds values.
127
+ * @param {Element} target The DOM element to observe.
128
+ */
129
+ IntersectionObserver.prototype.observe = function (target) {
130
+ const isTargetAlreadyObserved = this._observationTargets.some(function (item) {
131
+ return item.element == target;
132
+ });
133
+ if (isTargetAlreadyObserved)
134
+ return;
135
+ if (!(target && target.nodeType == 1)) {
136
+ throw new Error('target must be an Element');
137
+ }
138
+ this._registerInstance();
139
+ this._observationTargets.push({ element: target, entry: null });
140
+ this._monitorIntersections();
141
+ this._checkForIntersections();
142
+ };
143
+ /**
144
+ * Stops observing a target element for intersection changes.
145
+ * @param {Element} target The DOM element to observe.
146
+ */
147
+ IntersectionObserver.prototype.unobserve = function (target) {
148
+ this._observationTargets =
149
+ this._observationTargets.filter(function (item) {
150
+ return item.element != target;
151
+ });
152
+ if (!this._observationTargets.length) {
153
+ this._unmonitorIntersections();
154
+ this._unregisterInstance();
155
+ }
156
+ };
157
+ /**
158
+ * Stops observing all target elements for intersection changes.
159
+ */
160
+ IntersectionObserver.prototype.disconnect = function () {
161
+ this._observationTargets = [];
162
+ this._unmonitorIntersections();
163
+ this._unregisterInstance();
164
+ };
165
+ /**
166
+ * Returns any queue entries that have not yet been reported to the
167
+ * callback and clears the queue. This can be used in conjunction with the
168
+ * callback to obtain the absolute most up-to-date intersection information.
169
+ * @return {Array} The currently queued entries.
170
+ */
171
+ IntersectionObserver.prototype.takeRecords = function () {
172
+ const records = this._queuedEntries.slice();
173
+ this._queuedEntries = [];
174
+ return records;
175
+ };
176
+ /**
177
+ * Accepts the threshold value from the user configuration object and
178
+ * returns a sorted array of unique threshold values. If a value is not
179
+ * between 0 and 1 and error is thrown.
180
+ * @private
181
+ * @param {Array|number=} opt_threshold An optional threshold value or
182
+ * a list of threshold values, defaulting to [0].
183
+ * @return {Array} A sorted list of unique and valid threshold values.
184
+ */
185
+ IntersectionObserver.prototype._initThresholds = function (opt_threshold) {
186
+ let threshold = opt_threshold || [0];
187
+ if (!Array.isArray(threshold))
188
+ threshold = [threshold];
189
+ return threshold.sort().filter(function (t, i, a) {
190
+ if (!shared.isNumber(t) || isNaN(t) || t < 0 || t > 1) {
191
+ throw new Error('threshold must be a number between 0 and 1 inclusively');
192
+ }
193
+ return t !== a[i - 1];
194
+ });
195
+ };
196
+ /**
197
+ * Accepts the rootMargin value from the user configuration object
198
+ * and returns an array of the four margin values as an object containing
199
+ * the value and unit properties. If any of the values are not properly
200
+ * formatted or use a unit other than px or %, and error is thrown.
201
+ * @private
202
+ * @param {string=} opt_rootMargin An optional rootMargin value,
203
+ * defaulting to '0px'.
204
+ * @return {Array<Object>} An array of margin objects with the keys
205
+ * value and unit.
206
+ */
207
+ IntersectionObserver.prototype._parseRootMargin = function (opt_rootMargin) {
208
+ const marginString = opt_rootMargin || '0px';
209
+ const margins = marginString.split(/\s+/).map(function (margin) {
210
+ const parts = /^(-?\d*\.?\d+)(px|%)$/.exec(margin);
211
+ if (!parts) {
212
+ throw new Error('rootMargin must be specified in pixels or percent');
213
+ }
214
+ return { value: parseFloat(parts[1]), unit: parts[2] };
215
+ });
216
+ // Handles shorthand.
217
+ margins[1] = margins[1] || margins[0];
218
+ margins[2] = margins[2] || margins[0];
219
+ margins[3] = margins[3] || margins[1];
220
+ return margins;
221
+ };
222
+ /**
223
+ * Starts polling for intersection changes if the polling is not already
224
+ * happening, and if the page's visibility state is visible.
225
+ * @private
226
+ */
227
+ IntersectionObserver.prototype._monitorIntersections = function () {
228
+ if (!this._monitoringIntersections) {
229
+ this._monitoringIntersections = true;
230
+ // If a poll interval is set, use polling instead of listening to
231
+ // resize and scroll events or DOM mutations.
232
+ if (this.POLL_INTERVAL) {
233
+ this._monitoringInterval = setInterval(this._checkForIntersections, this.POLL_INTERVAL);
234
+ }
235
+ else {
236
+ addEvent(window, 'resize', this._checkForIntersections, true);
237
+ addEvent(document, 'scroll', this._checkForIntersections, true);
238
+ if (this.USE_MUTATION_OBSERVER && 'MutationObserver' in window) {
239
+ this._domObserver = new MutationObserver(this._checkForIntersections);
240
+ this._domObserver.observe(document, {
241
+ attributes: true,
242
+ childList: true,
243
+ characterData: true,
244
+ subtree: true
245
+ });
246
+ }
247
+ }
248
+ }
249
+ };
250
+ /**
251
+ * Stops polling for intersection changes.
252
+ * @private
253
+ */
254
+ IntersectionObserver.prototype._unmonitorIntersections = function () {
255
+ if (this._monitoringIntersections) {
256
+ this._monitoringIntersections = false;
257
+ clearInterval(this._monitoringInterval);
258
+ this._monitoringInterval = null;
259
+ removeEvent(window, 'resize', this._checkForIntersections, true);
260
+ removeEvent(document, 'scroll', this._checkForIntersections, true);
261
+ if (this._domObserver) {
262
+ this._domObserver.disconnect();
263
+ this._domObserver = null;
264
+ }
265
+ }
266
+ };
267
+ /**
268
+ * Scans each observation target for intersection changes and adds them
269
+ * to the internal entries queue. If new entries are found, it
270
+ * schedules the callback to be invoked.
271
+ * @private
272
+ */
273
+ IntersectionObserver.prototype._checkForIntersections = function () {
274
+ const rootIsInDom = this._rootIsInDom();
275
+ const rootRect = rootIsInDom ? this._getRootRect() : getEmptyRect();
276
+ this._observationTargets.forEach(function (item) {
277
+ const target = item.element;
278
+ const targetRect = getBoundingClientRect(target);
279
+ const rootContainsTarget = this._rootContainsTarget(target);
280
+ const oldEntry = item.entry;
281
+ const intersectionRect = rootIsInDom && rootContainsTarget &&
282
+ this._computeTargetAndRootIntersection(target, rootRect);
283
+ const newEntry = item.entry = new IntersectionObserverEntry({
284
+ time: now(),
285
+ target: target,
286
+ boundingClientRect: targetRect,
287
+ rootBounds: rootRect,
288
+ intersectionRect: intersectionRect,
289
+ intersectionRatio: -1,
290
+ isIntersecting: false,
291
+ });
292
+ if (!oldEntry) {
293
+ this._queuedEntries.push(newEntry);
294
+ }
295
+ else if (rootIsInDom && rootContainsTarget) {
296
+ // If the new entry intersection ratio has crossed any of the
297
+ // thresholds, add a new entry.
298
+ if (this._hasCrossedThreshold(oldEntry, newEntry)) {
299
+ this._queuedEntries.push(newEntry);
300
+ }
301
+ }
302
+ else {
303
+ // If the root is not in the DOM or target is not contained within
304
+ // root but the previous entry for this target had an intersection,
305
+ // add a new record indicating removal.
306
+ if (oldEntry && oldEntry.isIntersecting) {
307
+ this._queuedEntries.push(newEntry);
308
+ }
309
+ }
310
+ }, this);
311
+ if (this._queuedEntries.length) {
312
+ this._callback(this.takeRecords(), this);
313
+ }
314
+ };
315
+ /**
316
+ * Accepts a target and root rect computes the intersection between then
317
+ * following the algorithm in the spec.
318
+ * TODO(philipwalton): at this time clip-path is not considered.
319
+ * https://w3c.github.io/IntersectionObserver/#calculate-intersection-rect-algo
320
+ * @param {Element} target The target DOM element
321
+ * @param {Object} rootRect The bounding rect of the root after being
322
+ * expanded by the rootMargin value.
323
+ * @return {?Object} The final intersection rect object or undefined if no
324
+ * intersection is found.
325
+ * @private
326
+ */
327
+ IntersectionObserver.prototype._computeTargetAndRootIntersection = function (target, rootRect) {
328
+ // If the element isn't displayed, an intersection can't happen.
329
+ if (window.getComputedStyle(target).display === 'none')
330
+ return;
331
+ const targetRect = getBoundingClientRect(target);
332
+ let intersectionRect = targetRect;
333
+ let parent = getParentNode(target);
334
+ let atRoot = false;
335
+ while (!atRoot) {
336
+ let parentRect = null;
337
+ const parentComputedStyle = parent.nodeType == 1 ?
338
+ window.getComputedStyle(parent) : {};
339
+ // If the parent isn't displayed, an intersection can't happen.
340
+ if (parentComputedStyle.display === 'none')
341
+ return;
342
+ if (parent == this.root || parent == document) {
343
+ atRoot = true;
344
+ parentRect = rootRect;
345
+ }
346
+ else {
347
+ // If the element has a non-visible overflow, and it's not the <body>
348
+ // or <html> element, update the intersection rect.
349
+ // Note: <body> and <html> cannot be clipped to a rect that's not also
350
+ // the document rect, so no need to compute a new intersection.
351
+ if (parent != document.body &&
352
+ parent != document.documentElement &&
353
+ parentComputedStyle.overflow != 'visible') {
354
+ parentRect = getBoundingClientRect(parent);
355
+ }
356
+ }
357
+ // If either of the above conditionals set a new parentRect,
358
+ // calculate new intersection data.
359
+ if (parentRect) {
360
+ intersectionRect = computeRectIntersection(parentRect, intersectionRect);
361
+ if (!intersectionRect)
362
+ break;
363
+ }
364
+ parent = getParentNode(parent);
365
+ }
366
+ return intersectionRect;
367
+ };
368
+ /**
369
+ * Returns the root rect after being expanded by the rootMargin value.
370
+ * @return {Object} The expanded root rect.
371
+ * @private
372
+ */
373
+ IntersectionObserver.prototype._getRootRect = function () {
374
+ let rootRect;
375
+ if (this.root) {
376
+ rootRect = getBoundingClientRect(this.root);
377
+ }
378
+ else {
379
+ // Use <html>/<body> instead of window since scroll bars affect size.
380
+ const html = document.documentElement;
381
+ const body = document.body;
382
+ rootRect = {
383
+ top: 0,
384
+ left: 0,
385
+ right: html.clientWidth || body.clientWidth,
386
+ width: html.clientWidth || body.clientWidth,
387
+ bottom: html.clientHeight || body.clientHeight,
388
+ height: html.clientHeight || body.clientHeight
389
+ };
390
+ }
391
+ return this._expandRectByRootMargin(rootRect);
392
+ };
393
+ /**
394
+ * Accepts a rect and expands it by the rootMargin value.
395
+ * @param {Object} rect The rect object to expand.
396
+ * @return {Object} The expanded rect.
397
+ * @private
398
+ */
399
+ IntersectionObserver.prototype._expandRectByRootMargin = function (rect) {
400
+ const margins = this._rootMarginValues.map(function (margin, i) {
401
+ return margin.unit === 'px' ? margin.value :
402
+ margin.value * (i % 2 ? rect.width : rect.height) / 100;
403
+ });
404
+ const newRect = {
405
+ top: rect.top - margins[0],
406
+ right: rect.right + margins[1],
407
+ bottom: rect.bottom + margins[2],
408
+ left: rect.left - margins[3]
409
+ };
410
+ newRect.width = newRect.right - newRect.left;
411
+ newRect.height = newRect.bottom - newRect.top;
412
+ return newRect;
413
+ };
414
+ /**
415
+ * Accepts an old and new entry and returns true if at least one of the
416
+ * threshold values has been crossed.
417
+ * @param {?IntersectionObserverEntry} oldEntry The previous entry for a
418
+ * particular target element or null if no previous entry exists.
419
+ * @param {IntersectionObserverEntry} newEntry The current entry for a
420
+ * particular target element.
421
+ * @return {boolean} Returns true if a any threshold has been crossed.
422
+ * @private
423
+ */
424
+ IntersectionObserver.prototype._hasCrossedThreshold =
425
+ function (oldEntry, newEntry) {
426
+ // To make comparing easier, an entry that has a ratio of 0
427
+ // but does not actually intersect is given a value of -1
428
+ const oldRatio = oldEntry && oldEntry.isIntersecting ? oldEntry.intersectionRatio || 0 : -1;
429
+ const newRatio = newEntry.isIntersecting ? newEntry.intersectionRatio || 0 : -1;
430
+ // Ignore unchanged ratios
431
+ if (oldRatio === newRatio)
432
+ return;
433
+ for (let i = 0; i < this.thresholds.length; i++) {
434
+ const threshold = this.thresholds[i];
435
+ // Return true if an entry matches a threshold or if the new ratio
436
+ // and the old ratio are on the opposite sides of a threshold.
437
+ if (threshold == oldRatio || threshold == newRatio ||
438
+ threshold < oldRatio !== threshold < newRatio) {
439
+ return true;
440
+ }
441
+ }
442
+ };
443
+ /**
444
+ * Returns whether or not the root element is an element and is in the DOM.
445
+ * @return {boolean} True if the root element is an element and is in the DOM.
446
+ * @private
447
+ */
448
+ IntersectionObserver.prototype._rootIsInDom = function () {
449
+ return !this.root || containsDeep(document, this.root);
450
+ };
451
+ /**
452
+ * Returns whether or not the target element is a child of root.
453
+ * @param {Element} target The target element to check.
454
+ * @return {boolean} True if the target element is a child of root.
455
+ * @private
456
+ */
457
+ IntersectionObserver.prototype._rootContainsTarget = function (target) {
458
+ return containsDeep(this.root || document, target);
459
+ };
460
+ /**
461
+ * Adds the instance to the global IntersectionObserver registry if it isn't
462
+ * already present.
463
+ * @private
464
+ */
465
+ IntersectionObserver.prototype._registerInstance = function () {
466
+ };
467
+ /**
468
+ * Removes the instance from the global IntersectionObserver registry.
469
+ * @private
470
+ */
471
+ IntersectionObserver.prototype._unregisterInstance = function () {
472
+ };
473
+ /**
474
+ * Returns the result of the performance.now() method or null in browsers
475
+ * that don't support the API.
476
+ * @return {number} The elapsed time since the page was requested.
477
+ */
478
+ function now() {
479
+ return window.performance && performance.now && performance.now();
480
+ }
481
+ /**
482
+ * Adds an event handler to a DOM node ensuring cross-browser compatibility.
483
+ * @param {Node} node The DOM node to add the event handler to.
484
+ * @param {string} event The event name.
485
+ * @param {Function} fn The event handler to add.
486
+ * @param {boolean} opt_useCapture Optionally adds the even to the capture
487
+ * phase. Note: this only works in modern browsers.
488
+ */
489
+ function addEvent(node, event, fn, opt_useCapture) {
490
+ if (shared.isFunction(node.addEventListener)) {
491
+ node.addEventListener(event, fn, opt_useCapture || false);
492
+ }
493
+ else if (shared.isFunction(node.attachEvent)) {
494
+ node.attachEvent('on' + event, fn);
495
+ }
496
+ }
497
+ /**
498
+ * Removes a previously added event handler from a DOM node.
499
+ * @param {Node} node The DOM node to remove the event handler from.
500
+ * @param {string} event The event name.
501
+ * @param {Function} fn The event handler to remove.
502
+ * @param {boolean} opt_useCapture If the event handler was added with this
503
+ * flag set to true, it should be set to true here in order to remove it.
504
+ */
505
+ function removeEvent(node, event, fn, opt_useCapture) {
506
+ if (shared.isFunction(node.removeEventListener)) {
507
+ node.removeEventListener(event, fn, opt_useCapture || false);
508
+ }
509
+ else if (shared.isFunction(node.detatchEvent)) {
510
+ node.detatchEvent('on' + event, fn);
511
+ }
512
+ }
513
+ /**
514
+ * Returns the intersection between two rect objects.
515
+ * @param {Object} rect1 The first rect.
516
+ * @param {Object} rect2 The second rect.
517
+ * @return {?Object} The intersection rect or undefined if no intersection
518
+ * is found.
519
+ */
520
+ function computeRectIntersection(rect1, rect2) {
521
+ const top = Math.max(rect1.top, rect2.top);
522
+ const bottom = Math.min(rect1.bottom, rect2.bottom);
523
+ const left = Math.max(rect1.left, rect2.left);
524
+ const right = Math.min(rect1.right, rect2.right);
525
+ const width = right - left;
526
+ const height = bottom - top;
527
+ return (width >= 0 && height >= 0) && {
528
+ top: top,
529
+ bottom: bottom,
530
+ left: left,
531
+ right: right,
532
+ width: width,
533
+ height: height
534
+ };
535
+ }
536
+ /**
537
+ * Shims the native getBoundingClientRect for compatibility with older IE.
538
+ * @param {Element} el The element whose bounding rect to get.
539
+ * @return {Object} The (possibly shimmed) rect of the element.
540
+ */
541
+ function getBoundingClientRect(el) {
542
+ let rect;
543
+ try {
544
+ rect = el.getBoundingClientRect();
545
+ }
546
+ catch (err) {
547
+ // Ignore Windows 7 IE11 "Unspecified error"
548
+ // https://github.com/w3c/IntersectionObserver/pull/205
549
+ }
550
+ if (!rect)
551
+ return getEmptyRect();
552
+ // Older IE
553
+ if (!(rect.width && rect.height)) {
554
+ rect = {
555
+ top: rect.top,
556
+ right: rect.right,
557
+ bottom: rect.bottom,
558
+ left: rect.left,
559
+ width: rect.right - rect.left,
560
+ height: rect.bottom - rect.top
561
+ };
562
+ }
563
+ return rect;
564
+ }
565
+ /**
566
+ * Returns an empty rect object. An empty rect is returned when an element
567
+ * is not in the DOM.
568
+ * @return {Object} The empty rect.
569
+ */
570
+ function getEmptyRect() {
571
+ return {
572
+ top: 0,
573
+ bottom: 0,
574
+ left: 0,
575
+ right: 0,
576
+ width: 0,
577
+ height: 0
578
+ };
579
+ }
580
+ /**
581
+ * Checks to see if a parent element contains a child element (including inside
582
+ * shadow DOM).
583
+ * @param {Node} parent The parent element.
584
+ * @param {Node} child The child element.
585
+ * @return {boolean} True if the parent node contains the child node.
586
+ */
587
+ function containsDeep(parent, child) {
588
+ let node = child;
589
+ while (node) {
590
+ if (node == parent)
591
+ return true;
592
+ node = getParentNode(node);
593
+ }
594
+ return false;
595
+ }
596
+ /**
597
+ * Gets the parent node of an element or its host element if the parent node
598
+ * is a shadow root.
599
+ * @param {Node} node The node whose parent to get.
600
+ * @return {Node|null} The parent node or null if no parent exists.
601
+ */
602
+ function getParentNode(node) {
603
+ const parent = node.parentNode;
604
+ if (parent && parent.nodeType == 11 && parent.host) {
605
+ // If the parent is a shadow root, return the host element.
606
+ return parent.host;
607
+ }
608
+ if (parent && parent.assignedSlot) {
609
+ // If the parent is distributed in a <slot>, return the parent of a slot.
610
+ return parent.assignedSlot.parentNode;
611
+ }
612
+ return parent;
613
+ }
614
+ // Exposes the constructors globally.
615
+ window.IntersectionObserver = IntersectionObserver;
616
+ window.IntersectionObserverEntry = IntersectionObserverEntry;
617
+ }
618
+
619
+ function handleObjectAssignPolyfill() {
620
+ if (!shared.isFunction(Object.assign)) {
621
+ // Must be writable: true, enumerable: false, configurable: true
622
+ Object.assign = function (target) {
623
+ if (target == null) { // TypeError if undefined or null
624
+ throw new TypeError('Cannot convert undefined or null to object');
625
+ }
626
+ const to = Object(target);
627
+ for (let index = 1; index < arguments.length; index++) {
628
+ const nextSource = arguments[index];
629
+ if (nextSource != null) { // Skip over if undefined or null
630
+ for (const nextKey in nextSource) {
631
+ // Avoid bugs when hasOwnProperty is shadowed
632
+ if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
633
+ to[nextKey] = nextSource[nextKey];
634
+ }
635
+ }
636
+ }
637
+ }
638
+ return to;
639
+ };
640
+ }
641
+ }
642
+ function handleObjectDefinePropertyPolyfill() {
643
+ if (!shared.isFunction(Object.defineProperties)) {
644
+ Object.defineProperties = function (obj, properties) {
645
+ function convertToDescriptor(desc) {
646
+ function hasProperty(obj, prop) {
647
+ return Object.prototype.hasOwnProperty.call(obj, prop);
648
+ }
649
+ if (!shared.isObject(desc)) {
650
+ throw new TypeError('bad desc');
651
+ }
652
+ const d = {};
653
+ if (hasProperty(desc, 'enumerable'))
654
+ d.enumerable = !!desc.enumerable;
655
+ if (hasProperty(desc, 'configurable')) {
656
+ d.configurable = !!desc.configurable;
657
+ }
658
+ if (hasProperty(desc, 'value'))
659
+ d.value = desc.value;
660
+ if (hasProperty(desc, 'writable'))
661
+ d.writable = !!desc.writable;
662
+ if (hasProperty(desc, 'get')) {
663
+ const g = desc.get;
664
+ if (!shared.isFunction(g) && !shared.isUndefined(g)) {
665
+ throw new TypeError('bad get');
666
+ }
667
+ d.get = g;
668
+ }
669
+ if (hasProperty(desc, 'set')) {
670
+ const s = desc.set;
671
+ if (!shared.isFunction(s) && !shared.isUndefined(s)) {
672
+ throw new TypeError('bad set');
673
+ }
674
+ d.set = s;
675
+ }
676
+ if (('get' in d || 'set' in d) && ('value' in d || 'writable' in d)) {
677
+ throw new TypeError('identity-confused descriptor');
678
+ }
679
+ return d;
680
+ }
681
+ if (!shared.isObject(obj))
682
+ throw new TypeError('bad obj');
683
+ properties = Object(properties);
684
+ const keys = Object.keys(properties);
685
+ const descs = [];
686
+ for (let i = 0; i < keys.length; i++) {
687
+ descs.push([keys[i], convertToDescriptor(properties[keys[i]])]);
688
+ }
689
+ for (let i = 0; i < descs.length; i++) {
690
+ Object.defineProperty(obj, descs[i][0], descs[i][1]);
691
+ }
692
+ return obj;
693
+ };
694
+ }
695
+ }
696
+
697
+ if (process.env.SUPPORT_TARO_POLYFILL !== 'disabled') {
698
+ if (process.env.SUPPORT_TARO_POLYFILL === 'enabled' || process.env.SUPPORT_TARO_POLYFILL === 'Object' || process.env.SUPPORT_TARO_POLYFILL === 'Object.assign') {
699
+ handleObjectAssignPolyfill();
700
+ }
701
+ if (process.env.SUPPORT_TARO_POLYFILL === 'enabled' || process.env.SUPPORT_TARO_POLYFILL === 'Object' || process.env.SUPPORT_TARO_POLYFILL === 'Object.defineProperty') {
702
+ handleObjectDefinePropertyPolyfill();
703
+ }
704
+ // Exit early if we're not running in a browser.
705
+ if (process.env.TARO_PLATFORM === 'web' && shared.isObject(window)) {
706
+ if (process.env.SUPPORT_TARO_POLYFILL === 'enabled' || process.env.SUPPORT_TARO_POLYFILL === 'IntersectionObserver') {
707
+ handleIntersectionObserverPolyfill();
708
+ }
709
+ }
710
+ }
711
+
712
+ const ENV_TYPE = {
713
+ WEAPP: 'WEAPP',
714
+ SWAN: 'SWAN',
715
+ ALIPAY: 'ALIPAY',
716
+ TT: 'TT',
717
+ QQ: 'QQ',
718
+ JD: 'JD',
719
+ WEB: 'WEB',
720
+ RN: 'RN',
721
+ HARMONY: 'HARMONY',
722
+ QUICKAPP: 'QUICKAPP'
723
+ };
724
+ function getEnv() {
725
+ if (process.env.TARO_ENV === 'weapp') {
726
+ return ENV_TYPE.WEAPP;
727
+ }
728
+ else if (process.env.TARO_ENV === 'alipay') {
729
+ return ENV_TYPE.ALIPAY;
730
+ }
731
+ else if (process.env.TARO_ENV === 'swan') {
732
+ return ENV_TYPE.SWAN;
733
+ }
734
+ else if (process.env.TARO_ENV === 'tt') {
735
+ return ENV_TYPE.TT;
736
+ }
737
+ else if (process.env.TARO_ENV === 'jd') {
738
+ return ENV_TYPE.JD;
739
+ }
740
+ else if (process.env.TARO_ENV === 'qq') {
741
+ return ENV_TYPE.QQ;
742
+ }
743
+ else if (process.env.TARO_ENV === 'h5' || process.env.TARO_PLATFORM === 'web') {
744
+ return ENV_TYPE.WEB;
745
+ }
746
+ else if (process.env.TARO_ENV === 'rn') {
747
+ return ENV_TYPE.RN;
748
+ }
749
+ else if (process.env.TARO_ENV === 'harmony' || process.env.TARO_PLATFORM === 'harmony') {
750
+ return ENV_TYPE.HARMONY;
751
+ }
752
+ else if (process.env.TARO_ENV === 'quickapp') {
753
+ return ENV_TYPE.QUICKAPP;
754
+ }
755
+ else {
756
+ return process.env.TARO_ENV || 'Unknown';
757
+ }
758
+ }
759
+
760
+ class Chain {
761
+ constructor(requestParams, interceptors, index) {
762
+ this.index = index || 0;
763
+ this.requestParams = requestParams || {};
764
+ this.interceptors = interceptors || [];
765
+ }
766
+ proceed(requestParams = {}) {
767
+ this.requestParams = requestParams;
768
+ if (this.index >= this.interceptors.length) {
769
+ throw new Error('chain 参数错误, 请勿直接修改 request.chain');
770
+ }
771
+ const nextInterceptor = this._getNextInterceptor();
772
+ const nextChain = this._getNextChain();
773
+ const p = nextInterceptor(nextChain);
774
+ const res = p.catch(err => Promise.reject(err));
775
+ Object.keys(p).forEach(k => shared.isFunction(p[k]) && (res[k] = p[k]));
776
+ return res;
777
+ }
778
+ _getNextInterceptor() {
779
+ return this.interceptors[this.index];
780
+ }
781
+ _getNextChain() {
782
+ return new Chain(this.requestParams, this.interceptors, this.index + 1);
783
+ }
784
+ }
785
+
786
+ class Link {
787
+ constructor(interceptor) {
788
+ this.taroInterceptor = interceptor;
789
+ this.chain = new Chain();
790
+ }
791
+ request(requestParams) {
792
+ const chain = this.chain;
793
+ const taroInterceptor = this.taroInterceptor;
794
+ chain.interceptors = chain.interceptors
795
+ .filter(interceptor => interceptor !== taroInterceptor)
796
+ .concat(taroInterceptor);
797
+ return chain.proceed(Object.assign({}, requestParams));
798
+ }
799
+ addInterceptor(interceptor) {
800
+ this.chain.interceptors.push(interceptor);
801
+ }
802
+ cleanInterceptors() {
803
+ this.chain = new Chain();
804
+ }
805
+ }
806
+ function interceptorify(promiseifyApi) {
807
+ return new Link(function (chain) {
808
+ return promiseifyApi(chain.requestParams);
809
+ });
810
+ }
811
+
812
+ function timeoutInterceptor(chain) {
813
+ const requestParams = chain.requestParams;
814
+ let p;
815
+ const res = new Promise((resolve, reject) => {
816
+ const timeout = setTimeout(() => {
817
+ clearTimeout(timeout);
818
+ reject(new Error('网络链接超时,请稍后再试!'));
819
+ }, (requestParams && requestParams.timeout) || 60000);
820
+ p = chain.proceed(requestParams);
821
+ p
822
+ .then(res => {
823
+ if (!timeout)
824
+ return;
825
+ clearTimeout(timeout);
826
+ resolve(res);
827
+ })
828
+ .catch(err => {
829
+ timeout && clearTimeout(timeout);
830
+ reject(err);
831
+ });
832
+ });
833
+ // @ts-ignore
834
+ if (!shared.isUndefined(p) && shared.isFunction(p.abort))
835
+ res.abort = p.abort;
836
+ return res;
837
+ }
838
+ function logInterceptor(chain) {
839
+ const requestParams = chain.requestParams;
840
+ const { method, data, url } = requestParams;
841
+ // eslint-disable-next-line no-console
842
+ console.log(`http ${method || 'GET'} --> ${url} data: `, data);
843
+ const p = chain.proceed(requestParams);
844
+ const res = p
845
+ .then(res => {
846
+ // eslint-disable-next-line no-console
847
+ console.log(`http <-- ${url} result:`, res);
848
+ return res;
849
+ });
850
+ // @ts-ignore
851
+ if (shared.isFunction(p.abort))
852
+ res.abort = p.abort;
853
+ return res;
854
+ }
855
+
856
+ var interceptors = /*#__PURE__*/Object.freeze({
857
+ __proto__: null,
858
+ logInterceptor: logInterceptor,
859
+ timeoutInterceptor: timeoutInterceptor
860
+ });
861
+
862
+ function Behavior(options) {
863
+ return options;
864
+ }
865
+ function getPreload(current) {
866
+ return function (key, val) {
867
+ current.preloadData = shared.isObject(key)
868
+ ? key
869
+ : {
870
+ [key]: val
871
+ };
872
+ };
873
+ }
874
+ const defaultDesignWidth = 750;
875
+ const defaultDesignRatio = {
876
+ 640: 2.34 / 2,
877
+ 750: 1,
878
+ 828: 1.81 / 2
879
+ };
880
+ const defaultBaseFontSize = 20;
881
+ const defaultUnitPrecision = 5;
882
+ const defaultTargetUnit = 'rpx';
883
+ function getInitPxTransform(taro) {
884
+ return function (config) {
885
+ const { designWidth = defaultDesignWidth, deviceRatio = defaultDesignRatio, baseFontSize = defaultBaseFontSize, targetUnit = defaultTargetUnit, unitPrecision = defaultUnitPrecision, } = config;
886
+ taro.config = taro.config || {};
887
+ taro.config.designWidth = designWidth;
888
+ taro.config.deviceRatio = deviceRatio;
889
+ taro.config.baseFontSize = baseFontSize;
890
+ taro.config.targetUnit = targetUnit;
891
+ taro.config.unitPrecision = unitPrecision;
892
+ };
893
+ }
894
+ function getPxTransform(taro) {
895
+ return function (size) {
896
+ const config = taro.config || {};
897
+ const baseFontSize = config.baseFontSize;
898
+ const deviceRatio = config.deviceRatio || defaultDesignRatio;
899
+ const designWidth = (((input = 0) => shared.isFunction(config.designWidth)
900
+ ? config.designWidth(input)
901
+ : config.designWidth || defaultDesignWidth))(size);
902
+ if (!(designWidth in deviceRatio)) {
903
+ throw new Error(`deviceRatio 配置中不存在 ${designWidth} 的设置!`);
904
+ }
905
+ const targetUnit = config.targetUnit || defaultTargetUnit;
906
+ const unitPrecision = config.unitPrecision || defaultUnitPrecision;
907
+ const formatSize = ~~size;
908
+ let rootValue = 1 / deviceRatio[designWidth];
909
+ switch (targetUnit) {
910
+ case 'rem':
911
+ rootValue *= baseFontSize * 2;
912
+ break;
913
+ case 'px':
914
+ rootValue *= 2;
915
+ break;
916
+ }
917
+ let val = formatSize / rootValue;
918
+ if (unitPrecision >= 0 && unitPrecision <= 100) {
919
+ val = Number(val.toFixed(unitPrecision));
920
+ }
921
+ return val + targetUnit;
922
+ };
923
+ }
924
+
925
+ /* eslint-disable camelcase */
926
+ const Taro = {
927
+ Behavior,
928
+ getEnv,
929
+ ENV_TYPE,
930
+ Link,
931
+ interceptors,
932
+ Current: runtime.Current,
933
+ getCurrentInstance: runtime.getCurrentInstance,
934
+ options: runtime.options,
935
+ nextTick: runtime.nextTick,
936
+ eventCenter: runtime.eventCenter,
937
+ Events: runtime.Events,
938
+ getInitPxTransform,
939
+ interceptorify
940
+ };
941
+ Taro.initPxTransform = getInitPxTransform(Taro);
942
+ Taro.preload = getPreload(runtime.Current);
943
+ Taro.pxTransform = getPxTransform(Taro);
944
+
945
+ module.exports = Taro;