UNPKG

31.9 kBJavaScriptView Raw
1import*as React from'react';import {cloneElement,isValidElement,createRef,PureComponent,Component,forwardRef,useRef,useState,useEffect,useLayoutEffect}from'react';import {findDOMNode}from'react-dom';/*! *****************************************************************************
2Copyright (c) Microsoft Corporation.
3
4Permission to use, copy, modify, and/or distribute this software for any
5purpose with or without fee is hereby granted.
6
7THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
8REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
9AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
10INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
11LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13PERFORMANCE OF THIS SOFTWARE.
14***************************************************************************** */
15/* global Reflect, Promise */
16
17var extendStatics = function(d, b) {
18 extendStatics = Object.setPrototypeOf ||
19 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
21 return extendStatics(d, b);
22};
23
24function __extends(d, b) {
25 if (typeof b !== "function" && b !== null)
26 throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
27 extendStatics(d, b);
28 function __() { this.constructor = d; }
29 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30}
31
32var __assign = function() {
33 __assign = Object.assign || function __assign(t) {
34 for (var s, i = 1, n = arguments.length; i < n; i++) {
35 s = arguments[i];
36 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
37 }
38 return t;
39 };
40 return __assign.apply(this, arguments);
41};
42
43function __rest(s, e) {
44 var t = {};
45 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
46 t[p] = s[p];
47 if (s != null && typeof Object.getOwnPropertySymbols === "function")
48 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
49 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
50 t[p[i]] = s[p[i]];
51 }
52 return t;
53}var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};/**
54 * Checks if `value` is the
55 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
56 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
57 *
58 * @static
59 * @memberOf _
60 * @since 0.1.0
61 * @category Lang
62 * @param {*} value The value to check.
63 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
64 * @example
65 *
66 * _.isObject({});
67 * // => true
68 *
69 * _.isObject([1, 2, 3]);
70 * // => true
71 *
72 * _.isObject(_.noop);
73 * // => true
74 *
75 * _.isObject(null);
76 * // => false
77 */
78
79function isObject$3(value) {
80 var type = typeof value;
81 return value != null && (type == 'object' || type == 'function');
82}
83
84var isObject_1 = isObject$3;/** Detect free variable `global` from Node.js. */
85
86var freeGlobal$1 = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
87
88var _freeGlobal = freeGlobal$1;var freeGlobal = _freeGlobal;
89
90/** Detect free variable `self`. */
91var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
92
93/** Used as a reference to the global object. */
94var root$2 = freeGlobal || freeSelf || Function('return this')();
95
96var _root = root$2;var root$1 = _root;
97
98/**
99 * Gets the timestamp of the number of milliseconds that have elapsed since
100 * the Unix epoch (1 January 1970 00:00:00 UTC).
101 *
102 * @static
103 * @memberOf _
104 * @since 2.4.0
105 * @category Date
106 * @returns {number} Returns the timestamp.
107 * @example
108 *
109 * _.defer(function(stamp) {
110 * console.log(_.now() - stamp);
111 * }, _.now());
112 * // => Logs the number of milliseconds it took for the deferred invocation.
113 */
114var now$1 = function() {
115 return root$1.Date.now();
116};
117
118var now_1 = now$1;/** Used to match a single whitespace character. */
119
120var reWhitespace = /\s/;
121
122/**
123 * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
124 * character of `string`.
125 *
126 * @private
127 * @param {string} string The string to inspect.
128 * @returns {number} Returns the index of the last non-whitespace character.
129 */
130function trimmedEndIndex$1(string) {
131 var index = string.length;
132
133 while (index-- && reWhitespace.test(string.charAt(index))) {}
134 return index;
135}
136
137var _trimmedEndIndex = trimmedEndIndex$1;var trimmedEndIndex = _trimmedEndIndex;
138
139/** Used to match leading whitespace. */
140var reTrimStart = /^\s+/;
141
142/**
143 * The base implementation of `_.trim`.
144 *
145 * @private
146 * @param {string} string The string to trim.
147 * @returns {string} Returns the trimmed string.
148 */
149function baseTrim$1(string) {
150 return string
151 ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')
152 : string;
153}
154
155var _baseTrim = baseTrim$1;var root = _root;
156
157/** Built-in value references. */
158var Symbol$2 = root.Symbol;
159
160var _Symbol = Symbol$2;var Symbol$1 = _Symbol;
161
162/** Used for built-in method references. */
163var objectProto$1 = Object.prototype;
164
165/** Used to check objects for own properties. */
166var hasOwnProperty = objectProto$1.hasOwnProperty;
167
168/**
169 * Used to resolve the
170 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
171 * of values.
172 */
173var nativeObjectToString$1 = objectProto$1.toString;
174
175/** Built-in value references. */
176var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined;
177
178/**
179 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
180 *
181 * @private
182 * @param {*} value The value to query.
183 * @returns {string} Returns the raw `toStringTag`.
184 */
185function getRawTag$1(value) {
186 var isOwn = hasOwnProperty.call(value, symToStringTag$1),
187 tag = value[symToStringTag$1];
188
189 try {
190 value[symToStringTag$1] = undefined;
191 var unmasked = true;
192 } catch (e) {}
193
194 var result = nativeObjectToString$1.call(value);
195 if (unmasked) {
196 if (isOwn) {
197 value[symToStringTag$1] = tag;
198 } else {
199 delete value[symToStringTag$1];
200 }
201 }
202 return result;
203}
204
205var _getRawTag = getRawTag$1;/** Used for built-in method references. */
206
207var objectProto = Object.prototype;
208
209/**
210 * Used to resolve the
211 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
212 * of values.
213 */
214var nativeObjectToString = objectProto.toString;
215
216/**
217 * Converts `value` to a string using `Object.prototype.toString`.
218 *
219 * @private
220 * @param {*} value The value to convert.
221 * @returns {string} Returns the converted string.
222 */
223function objectToString$1(value) {
224 return nativeObjectToString.call(value);
225}
226
227var _objectToString = objectToString$1;var Symbol = _Symbol,
228 getRawTag = _getRawTag,
229 objectToString = _objectToString;
230
231/** `Object#toString` result references. */
232var nullTag = '[object Null]',
233 undefinedTag = '[object Undefined]';
234
235/** Built-in value references. */
236var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
237
238/**
239 * The base implementation of `getTag` without fallbacks for buggy environments.
240 *
241 * @private
242 * @param {*} value The value to query.
243 * @returns {string} Returns the `toStringTag`.
244 */
245function baseGetTag$1(value) {
246 if (value == null) {
247 return value === undefined ? undefinedTag : nullTag;
248 }
249 return (symToStringTag && symToStringTag in Object(value))
250 ? getRawTag(value)
251 : objectToString(value);
252}
253
254var _baseGetTag = baseGetTag$1;/**
255 * Checks if `value` is object-like. A value is object-like if it's not `null`
256 * and has a `typeof` result of "object".
257 *
258 * @static
259 * @memberOf _
260 * @since 4.0.0
261 * @category Lang
262 * @param {*} value The value to check.
263 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
264 * @example
265 *
266 * _.isObjectLike({});
267 * // => true
268 *
269 * _.isObjectLike([1, 2, 3]);
270 * // => true
271 *
272 * _.isObjectLike(_.noop);
273 * // => false
274 *
275 * _.isObjectLike(null);
276 * // => false
277 */
278
279function isObjectLike$1(value) {
280 return value != null && typeof value == 'object';
281}
282
283var isObjectLike_1 = isObjectLike$1;var baseGetTag = _baseGetTag,
284 isObjectLike = isObjectLike_1;
285
286/** `Object#toString` result references. */
287var symbolTag = '[object Symbol]';
288
289/**
290 * Checks if `value` is classified as a `Symbol` primitive or object.
291 *
292 * @static
293 * @memberOf _
294 * @since 4.0.0
295 * @category Lang
296 * @param {*} value The value to check.
297 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
298 * @example
299 *
300 * _.isSymbol(Symbol.iterator);
301 * // => true
302 *
303 * _.isSymbol('abc');
304 * // => false
305 */
306function isSymbol$1(value) {
307 return typeof value == 'symbol' ||
308 (isObjectLike(value) && baseGetTag(value) == symbolTag);
309}
310
311var isSymbol_1 = isSymbol$1;var baseTrim = _baseTrim,
312 isObject$2 = isObject_1,
313 isSymbol = isSymbol_1;
314
315/** Used as references for various `Number` constants. */
316var NAN = 0 / 0;
317
318/** Used to detect bad signed hexadecimal string values. */
319var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
320
321/** Used to detect binary string values. */
322var reIsBinary = /^0b[01]+$/i;
323
324/** Used to detect octal string values. */
325var reIsOctal = /^0o[0-7]+$/i;
326
327/** Built-in method references without a dependency on `root`. */
328var freeParseInt = parseInt;
329
330/**
331 * Converts `value` to a number.
332 *
333 * @static
334 * @memberOf _
335 * @since 4.0.0
336 * @category Lang
337 * @param {*} value The value to process.
338 * @returns {number} Returns the number.
339 * @example
340 *
341 * _.toNumber(3.2);
342 * // => 3.2
343 *
344 * _.toNumber(Number.MIN_VALUE);
345 * // => 5e-324
346 *
347 * _.toNumber(Infinity);
348 * // => Infinity
349 *
350 * _.toNumber('3.2');
351 * // => 3.2
352 */
353function toNumber$1(value) {
354 if (typeof value == 'number') {
355 return value;
356 }
357 if (isSymbol(value)) {
358 return NAN;
359 }
360 if (isObject$2(value)) {
361 var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
362 value = isObject$2(other) ? (other + '') : other;
363 }
364 if (typeof value != 'string') {
365 return value === 0 ? value : +value;
366 }
367 value = baseTrim(value);
368 var isBinary = reIsBinary.test(value);
369 return (isBinary || reIsOctal.test(value))
370 ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
371 : (reIsBadHex.test(value) ? NAN : +value);
372}
373
374var toNumber_1 = toNumber$1;var isObject$1 = isObject_1,
375 now = now_1,
376 toNumber = toNumber_1;
377
378/** Error message constants. */
379var FUNC_ERROR_TEXT$1 = 'Expected a function';
380
381/* Built-in method references for those with the same name as other `lodash` methods. */
382var nativeMax = Math.max,
383 nativeMin = Math.min;
384
385/**
386 * Creates a debounced function that delays invoking `func` until after `wait`
387 * milliseconds have elapsed since the last time the debounced function was
388 * invoked. The debounced function comes with a `cancel` method to cancel
389 * delayed `func` invocations and a `flush` method to immediately invoke them.
390 * Provide `options` to indicate whether `func` should be invoked on the
391 * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
392 * with the last arguments provided to the debounced function. Subsequent
393 * calls to the debounced function return the result of the last `func`
394 * invocation.
395 *
396 * **Note:** If `leading` and `trailing` options are `true`, `func` is
397 * invoked on the trailing edge of the timeout only if the debounced function
398 * is invoked more than once during the `wait` timeout.
399 *
400 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
401 * until to the next tick, similar to `setTimeout` with a timeout of `0`.
402 *
403 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
404 * for details over the differences between `_.debounce` and `_.throttle`.
405 *
406 * @static
407 * @memberOf _
408 * @since 0.1.0
409 * @category Function
410 * @param {Function} func The function to debounce.
411 * @param {number} [wait=0] The number of milliseconds to delay.
412 * @param {Object} [options={}] The options object.
413 * @param {boolean} [options.leading=false]
414 * Specify invoking on the leading edge of the timeout.
415 * @param {number} [options.maxWait]
416 * The maximum time `func` is allowed to be delayed before it's invoked.
417 * @param {boolean} [options.trailing=true]
418 * Specify invoking on the trailing edge of the timeout.
419 * @returns {Function} Returns the new debounced function.
420 * @example
421 *
422 * // Avoid costly calculations while the window size is in flux.
423 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
424 *
425 * // Invoke `sendMail` when clicked, debouncing subsequent calls.
426 * jQuery(element).on('click', _.debounce(sendMail, 300, {
427 * 'leading': true,
428 * 'trailing': false
429 * }));
430 *
431 * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
432 * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
433 * var source = new EventSource('/stream');
434 * jQuery(source).on('message', debounced);
435 *
436 * // Cancel the trailing debounced invocation.
437 * jQuery(window).on('popstate', debounced.cancel);
438 */
439function debounce$1(func, wait, options) {
440 var lastArgs,
441 lastThis,
442 maxWait,
443 result,
444 timerId,
445 lastCallTime,
446 lastInvokeTime = 0,
447 leading = false,
448 maxing = false,
449 trailing = true;
450
451 if (typeof func != 'function') {
452 throw new TypeError(FUNC_ERROR_TEXT$1);
453 }
454 wait = toNumber(wait) || 0;
455 if (isObject$1(options)) {
456 leading = !!options.leading;
457 maxing = 'maxWait' in options;
458 maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
459 trailing = 'trailing' in options ? !!options.trailing : trailing;
460 }
461
462 function invokeFunc(time) {
463 var args = lastArgs,
464 thisArg = lastThis;
465
466 lastArgs = lastThis = undefined;
467 lastInvokeTime = time;
468 result = func.apply(thisArg, args);
469 return result;
470 }
471
472 function leadingEdge(time) {
473 // Reset any `maxWait` timer.
474 lastInvokeTime = time;
475 // Start the timer for the trailing edge.
476 timerId = setTimeout(timerExpired, wait);
477 // Invoke the leading edge.
478 return leading ? invokeFunc(time) : result;
479 }
480
481 function remainingWait(time) {
482 var timeSinceLastCall = time - lastCallTime,
483 timeSinceLastInvoke = time - lastInvokeTime,
484 timeWaiting = wait - timeSinceLastCall;
485
486 return maxing
487 ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
488 : timeWaiting;
489 }
490
491 function shouldInvoke(time) {
492 var timeSinceLastCall = time - lastCallTime,
493 timeSinceLastInvoke = time - lastInvokeTime;
494
495 // Either this is the first call, activity has stopped and we're at the
496 // trailing edge, the system time has gone backwards and we're treating
497 // it as the trailing edge, or we've hit the `maxWait` limit.
498 return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
499 (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
500 }
501
502 function timerExpired() {
503 var time = now();
504 if (shouldInvoke(time)) {
505 return trailingEdge(time);
506 }
507 // Restart the timer.
508 timerId = setTimeout(timerExpired, remainingWait(time));
509 }
510
511 function trailingEdge(time) {
512 timerId = undefined;
513
514 // Only invoke if we have `lastArgs` which means `func` has been
515 // debounced at least once.
516 if (trailing && lastArgs) {
517 return invokeFunc(time);
518 }
519 lastArgs = lastThis = undefined;
520 return result;
521 }
522
523 function cancel() {
524 if (timerId !== undefined) {
525 clearTimeout(timerId);
526 }
527 lastInvokeTime = 0;
528 lastArgs = lastCallTime = lastThis = timerId = undefined;
529 }
530
531 function flush() {
532 return timerId === undefined ? result : trailingEdge(now());
533 }
534
535 function debounced() {
536 var time = now(),
537 isInvoking = shouldInvoke(time);
538
539 lastArgs = arguments;
540 lastThis = this;
541 lastCallTime = time;
542
543 if (isInvoking) {
544 if (timerId === undefined) {
545 return leadingEdge(lastCallTime);
546 }
547 if (maxing) {
548 // Handle invocations in a tight loop.
549 clearTimeout(timerId);
550 timerId = setTimeout(timerExpired, wait);
551 return invokeFunc(lastCallTime);
552 }
553 }
554 if (timerId === undefined) {
555 timerId = setTimeout(timerExpired, wait);
556 }
557 return result;
558 }
559 debounced.cancel = cancel;
560 debounced.flush = flush;
561 return debounced;
562}
563
564var debounce_1 = debounce$1;var debounce = debounce_1,
565 isObject = isObject_1;
566
567/** Error message constants. */
568var FUNC_ERROR_TEXT = 'Expected a function';
569
570/**
571 * Creates a throttled function that only invokes `func` at most once per
572 * every `wait` milliseconds. The throttled function comes with a `cancel`
573 * method to cancel delayed `func` invocations and a `flush` method to
574 * immediately invoke them. Provide `options` to indicate whether `func`
575 * should be invoked on the leading and/or trailing edge of the `wait`
576 * timeout. The `func` is invoked with the last arguments provided to the
577 * throttled function. Subsequent calls to the throttled function return the
578 * result of the last `func` invocation.
579 *
580 * **Note:** If `leading` and `trailing` options are `true`, `func` is
581 * invoked on the trailing edge of the timeout only if the throttled function
582 * is invoked more than once during the `wait` timeout.
583 *
584 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
585 * until to the next tick, similar to `setTimeout` with a timeout of `0`.
586 *
587 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
588 * for details over the differences between `_.throttle` and `_.debounce`.
589 *
590 * @static
591 * @memberOf _
592 * @since 0.1.0
593 * @category Function
594 * @param {Function} func The function to throttle.
595 * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
596 * @param {Object} [options={}] The options object.
597 * @param {boolean} [options.leading=true]
598 * Specify invoking on the leading edge of the timeout.
599 * @param {boolean} [options.trailing=true]
600 * Specify invoking on the trailing edge of the timeout.
601 * @returns {Function} Returns the new throttled function.
602 * @example
603 *
604 * // Avoid excessively updating the position while scrolling.
605 * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
606 *
607 * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
608 * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
609 * jQuery(element).on('click', throttled);
610 *
611 * // Cancel the trailing throttled invocation.
612 * jQuery(window).on('popstate', throttled.cancel);
613 */
614function throttle(func, wait, options) {
615 var leading = true,
616 trailing = true;
617
618 if (typeof func != 'function') {
619 throw new TypeError(FUNC_ERROR_TEXT);
620 }
621 if (isObject(options)) {
622 leading = 'leading' in options ? !!options.leading : leading;
623 trailing = 'trailing' in options ? !!options.trailing : trailing;
624 }
625 return debounce(func, wait, {
626 'leading': leading,
627 'maxWait': wait,
628 'trailing': trailing
629 });
630}
631
632var throttle_1 = throttle;var patchResizeHandler = function (resizeCallback, refreshMode, refreshRate, refreshOptions) {
633 switch (refreshMode) {
634 case 'debounce':
635 return debounce_1(resizeCallback, refreshRate, refreshOptions);
636 case 'throttle':
637 return throttle_1(resizeCallback, refreshRate, refreshOptions);
638 default:
639 return resizeCallback;
640 }
641};
642var isFunction = function (fn) { return typeof fn === 'function'; };
643var isSSR = function () { return typeof window === 'undefined'; };
644var isDOMElement = function (element) { return element instanceof Element || element instanceof HTMLDocument; };
645var createNotifier = function (onResize, setSize, handleWidth, handleHeight) {
646 return function (_a) {
647 var width = _a.width, height = _a.height;
648 setSize(function (prev) {
649 if (prev.width === width && prev.height === height) {
650 // skip if dimensions haven't changed
651 return prev;
652 }
653 if ((prev.width === width && !handleHeight) || (prev.height === height && !handleWidth)) {
654 // process `handleHeight/handleWidth` props
655 return prev;
656 }
657 if (onResize && isFunction(onResize)) {
658 onResize(width, height);
659 }
660 return { width: width, height: height };
661 });
662 };
663};var ResizeDetector = /** @class */ (function (_super) {
664 __extends(ResizeDetector, _super);
665 function ResizeDetector(props) {
666 var _this = _super.call(this, props) || this;
667 _this.cancelHandler = function () {
668 if (_this.resizeHandler && _this.resizeHandler.cancel) {
669 // cancel debounced handler
670 _this.resizeHandler.cancel();
671 _this.resizeHandler = null;
672 }
673 };
674 _this.attachObserver = function () {
675 var _a = _this.props, targetRef = _a.targetRef, observerOptions = _a.observerOptions;
676 if (isSSR()) {
677 return;
678 }
679 if (targetRef && targetRef.current) {
680 _this.targetRef.current = targetRef.current;
681 }
682 var element = _this.getElement();
683 if (!element) {
684 // can't find element to observe
685 return;
686 }
687 if (_this.observableElement && _this.observableElement === element) {
688 // element is already observed
689 return;
690 }
691 _this.observableElement = element;
692 _this.resizeObserver.observe(element, observerOptions);
693 };
694 _this.getElement = function () {
695 var _a = _this.props, querySelector = _a.querySelector, targetDomEl = _a.targetDomEl;
696 if (isSSR())
697 return null;
698 // in case we pass a querySelector
699 if (querySelector)
700 return document.querySelector(querySelector);
701 // in case we pass a DOM element
702 if (targetDomEl && isDOMElement(targetDomEl))
703 return targetDomEl;
704 // in case we pass a React ref using React.createRef()
705 if (_this.targetRef && isDOMElement(_this.targetRef.current))
706 return _this.targetRef.current;
707 // the worse case when we don't receive any information from the parent and the library doesn't add any wrappers
708 // we have to use a deprecated `findDOMNode` method in order to find a DOM element to attach to
709 var currentElement = findDOMNode(_this);
710 if (!currentElement)
711 return null;
712 var renderType = _this.getRenderType();
713 switch (renderType) {
714 case 'renderProp':
715 return currentElement;
716 case 'childFunction':
717 return currentElement;
718 case 'child':
719 return currentElement;
720 case 'childArray':
721 return currentElement;
722 default:
723 return currentElement.parentElement;
724 }
725 };
726 _this.createResizeHandler = function (entries) {
727 var _a = _this.props, _b = _a.handleWidth, handleWidth = _b === void 0 ? true : _b, _c = _a.handleHeight, handleHeight = _c === void 0 ? true : _c, onResize = _a.onResize;
728 if (!handleWidth && !handleHeight)
729 return;
730 var notifyResize = createNotifier(onResize, _this.setState.bind(_this), handleWidth, handleHeight);
731 entries.forEach(function (entry) {
732 var _a = (entry && entry.contentRect) || {}, width = _a.width, height = _a.height;
733 var shouldSetSize = !_this.skipOnMount && !isSSR();
734 if (shouldSetSize) {
735 notifyResize({ width: width, height: height });
736 }
737 _this.skipOnMount = false;
738 });
739 };
740 _this.getRenderType = function () {
741 var _a = _this.props, render = _a.render, children = _a.children;
742 if (isFunction(render)) {
743 // DEPRECATED. Use `Child Function Pattern` instead
744 return 'renderProp';
745 }
746 if (isFunction(children)) {
747 return 'childFunction';
748 }
749 if (isValidElement(children)) {
750 return 'child';
751 }
752 if (Array.isArray(children)) {
753 // DEPRECATED. Wrap children with a single parent
754 return 'childArray';
755 }
756 // DEPRECATED. Use `Child Function Pattern` instead
757 return 'parent';
758 };
759 var skipOnMount = props.skipOnMount, refreshMode = props.refreshMode, _a = props.refreshRate, refreshRate = _a === void 0 ? 1000 : _a, refreshOptions = props.refreshOptions;
760 _this.state = {
761 width: undefined,
762 height: undefined
763 };
764 _this.skipOnMount = skipOnMount;
765 _this.targetRef = createRef();
766 _this.observableElement = null;
767 if (isSSR()) {
768 return _this;
769 }
770 _this.resizeHandler = patchResizeHandler(_this.createResizeHandler, refreshMode, refreshRate, refreshOptions);
771 _this.resizeObserver = new window.ResizeObserver(_this.resizeHandler);
772 return _this;
773 }
774 ResizeDetector.prototype.componentDidMount = function () {
775 this.attachObserver();
776 };
777 ResizeDetector.prototype.componentDidUpdate = function () {
778 this.attachObserver();
779 };
780 ResizeDetector.prototype.componentWillUnmount = function () {
781 if (isSSR()) {
782 return;
783 }
784 this.resizeObserver.disconnect();
785 this.cancelHandler();
786 };
787 ResizeDetector.prototype.render = function () {
788 var _a = this.props, render = _a.render, children = _a.children, _b = _a.nodeType, WrapperTag = _b === void 0 ? 'div' : _b;
789 var _c = this.state, width = _c.width, height = _c.height;
790 var childProps = { width: width, height: height, targetRef: this.targetRef };
791 var renderType = this.getRenderType();
792 var typedChildren;
793 switch (renderType) {
794 case 'renderProp':
795 return render && render(childProps);
796 case 'childFunction':
797 typedChildren = children;
798 return typedChildren(childProps);
799 case 'child':
800 // @TODO bug prone logic
801 typedChildren = children;
802 if (typedChildren.type && typeof typedChildren.type === 'string') {
803 // child is a native DOM elements such as div, span etc
804 childProps.targetRef; var nativeProps = __rest(childProps, ["targetRef"]);
805 return cloneElement(typedChildren, nativeProps);
806 }
807 // class or functional component otherwise
808 return cloneElement(typedChildren, childProps);
809 case 'childArray':
810 typedChildren = children;
811 return typedChildren.map(function (el) { return !!el && cloneElement(el, childProps); });
812 default:
813 return React.createElement(WrapperTag, null);
814 }
815 };
816 return ResizeDetector;
817}(PureComponent));function withResizeDetector(ComponentInner, options) {
818 if (options === void 0) { options = {}; }
819 var ResizeDetectorHOC = /** @class */ (function (_super) {
820 __extends(ResizeDetectorHOC, _super);
821 function ResizeDetectorHOC() {
822 var _this = _super !== null && _super.apply(this, arguments) || this;
823 _this.ref = createRef();
824 return _this;
825 }
826 ResizeDetectorHOC.prototype.render = function () {
827 var _a = this.props, forwardedRef = _a.forwardedRef, rest = __rest(_a, ["forwardedRef"]);
828 var targetRef = forwardedRef !== null && forwardedRef !== void 0 ? forwardedRef : this.ref;
829 return (React.createElement(ResizeDetector, __assign({}, options, { targetRef: targetRef }),
830 React.createElement(ComponentInner, __assign({ targetRef: targetRef }, rest))));
831 };
832 return ResizeDetectorHOC;
833 }(Component));
834 function forwardRefWrapper(props, ref) {
835 return React.createElement(ResizeDetectorHOC, __assign({}, props, { forwardedRef: ref }));
836 }
837 var name = ComponentInner.displayName || ComponentInner.name;
838 forwardRefWrapper.displayName = "withResizeDetector(".concat(name, ")");
839 return forwardRef(forwardRefWrapper);
840}var useEnhancedEffect = isSSR() ? useEffect : useLayoutEffect;
841function useResizeDetector(props) {
842 if (props === void 0) { props = {}; }
843 var _a = props.skipOnMount, skipOnMount = _a === void 0 ? false : _a, refreshMode = props.refreshMode, _b = props.refreshRate, refreshRate = _b === void 0 ? 1000 : _b, refreshOptions = props.refreshOptions, _c = props.handleWidth, handleWidth = _c === void 0 ? true : _c, _d = props.handleHeight, handleHeight = _d === void 0 ? true : _d, targetRef = props.targetRef, observerOptions = props.observerOptions, onResize = props.onResize;
844 var skipResize = useRef(skipOnMount);
845 var localRef = useRef(null);
846 var ref = (targetRef !== null && targetRef !== void 0 ? targetRef : localRef);
847 var resizeHandler = useRef();
848 var _e = useState({
849 width: undefined,
850 height: undefined
851 }), size = _e[0], setSize = _e[1];
852 useEnhancedEffect(function () {
853 if (isSSR()) {
854 return;
855 }
856 var notifyResize = createNotifier(onResize, setSize, handleWidth, handleHeight);
857 var resizeCallback = function (entries) {
858 if (!handleWidth && !handleHeight)
859 return;
860 entries.forEach(function (entry) {
861 var _a = (entry && entry.contentRect) || {}, width = _a.width, height = _a.height;
862 var shouldSetSize = !skipResize.current && !isSSR();
863 if (shouldSetSize) {
864 notifyResize({ width: width, height: height });
865 }
866 skipResize.current = false;
867 });
868 };
869 resizeHandler.current = patchResizeHandler(resizeCallback, refreshMode, refreshRate, refreshOptions);
870 var resizeObserver = new window.ResizeObserver(resizeHandler.current);
871 if (ref.current) {
872 // Something wrong with typings here...
873 resizeObserver.observe(ref.current, observerOptions);
874 }
875 return function () {
876 resizeObserver.disconnect();
877 var patchedResizeHandler = resizeHandler.current;
878 if (patchedResizeHandler && patchedResizeHandler.cancel) {
879 patchedResizeHandler.cancel();
880 }
881 };
882 }, [refreshMode, refreshRate, refreshOptions, handleWidth, handleHeight, onResize, observerOptions, ref.current]);
883 return __assign({ ref: ref }, size);
884}export{ResizeDetector as default,useResizeDetector,withResizeDetector};//# sourceMappingURL=index.esm.js.map