UNPKG

19.4 kBJavaScriptView Raw
1'use strict';
2
3function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
4
5require('./slicedToArray-ef426d0f.js');
6require('./unsupportedIterableToArray-8a00e599.js');
7var React = require('react');
8var React__default = _interopDefault(React);
9var index = require('./index-b0606964.js');
10var defineProperty = require('./defineProperty-0921a47c.js');
11require('styled-components');
12var getPrototypeOf = require('./getPrototypeOf-e2d1e599.js');
13require('./miscellaneous.js');
14require('./environment.js');
15require('./font.js');
16require('./constants.js');
17var breakpoints = require('./breakpoints.js');
18require('./springs.js');
19require('./text-styles.js');
20var isObject = require('./isObject-52908731.js');
21
22/**
23 * Gets the timestamp of the number of milliseconds that have elapsed since
24 * the Unix epoch (1 January 1970 00:00:00 UTC).
25 *
26 * @static
27 * @memberOf _
28 * @since 2.4.0
29 * @category Date
30 * @returns {number} Returns the timestamp.
31 * @example
32 *
33 * _.defer(function(stamp) {
34 * console.log(_.now() - stamp);
35 * }, _.now());
36 * // => Logs the number of milliseconds it took for the deferred invocation.
37 */
38var now = function() {
39 return isObject.root.Date.now();
40};
41
42var now_1 = now;
43
44/**
45 * Checks if `value` is object-like. A value is object-like if it's not `null`
46 * and has a `typeof` result of "object".
47 *
48 * @static
49 * @memberOf _
50 * @since 4.0.0
51 * @category Lang
52 * @param {*} value The value to check.
53 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
54 * @example
55 *
56 * _.isObjectLike({});
57 * // => true
58 *
59 * _.isObjectLike([1, 2, 3]);
60 * // => true
61 *
62 * _.isObjectLike(_.noop);
63 * // => false
64 *
65 * _.isObjectLike(null);
66 * // => false
67 */
68function isObjectLike(value) {
69 return value != null && typeof value == 'object';
70}
71
72var isObjectLike_1 = isObjectLike;
73
74/** `Object#toString` result references. */
75var symbolTag = '[object Symbol]';
76
77/**
78 * Checks if `value` is classified as a `Symbol` primitive or object.
79 *
80 * @static
81 * @memberOf _
82 * @since 4.0.0
83 * @category Lang
84 * @param {*} value The value to check.
85 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
86 * @example
87 *
88 * _.isSymbol(Symbol.iterator);
89 * // => true
90 *
91 * _.isSymbol('abc');
92 * // => false
93 */
94function isSymbol(value) {
95 return typeof value == 'symbol' ||
96 (isObjectLike_1(value) && isObject.baseGetTag(value) == symbolTag);
97}
98
99var isSymbol_1 = isSymbol;
100
101/** Used as references for various `Number` constants. */
102var NAN = 0 / 0;
103
104/** Used to match leading and trailing whitespace. */
105var reTrim = /^\s+|\s+$/g;
106
107/** Used to detect bad signed hexadecimal string values. */
108var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
109
110/** Used to detect binary string values. */
111var reIsBinary = /^0b[01]+$/i;
112
113/** Used to detect octal string values. */
114var reIsOctal = /^0o[0-7]+$/i;
115
116/** Built-in method references without a dependency on `root`. */
117var freeParseInt = parseInt;
118
119/**
120 * Converts `value` to a number.
121 *
122 * @static
123 * @memberOf _
124 * @since 4.0.0
125 * @category Lang
126 * @param {*} value The value to process.
127 * @returns {number} Returns the number.
128 * @example
129 *
130 * _.toNumber(3.2);
131 * // => 3.2
132 *
133 * _.toNumber(Number.MIN_VALUE);
134 * // => 5e-324
135 *
136 * _.toNumber(Infinity);
137 * // => Infinity
138 *
139 * _.toNumber('3.2');
140 * // => 3.2
141 */
142function toNumber(value) {
143 if (typeof value == 'number') {
144 return value;
145 }
146 if (isSymbol_1(value)) {
147 return NAN;
148 }
149 if (isObject.isObject(value)) {
150 var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
151 value = isObject.isObject(other) ? (other + '') : other;
152 }
153 if (typeof value != 'string') {
154 return value === 0 ? value : +value;
155 }
156 value = value.replace(reTrim, '');
157 var isBinary = reIsBinary.test(value);
158 return (isBinary || reIsOctal.test(value))
159 ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
160 : (reIsBadHex.test(value) ? NAN : +value);
161}
162
163var toNumber_1 = toNumber;
164
165/** Error message constants. */
166var FUNC_ERROR_TEXT = 'Expected a function';
167
168/* Built-in method references for those with the same name as other `lodash` methods. */
169var nativeMax = Math.max,
170 nativeMin = Math.min;
171
172/**
173 * Creates a debounced function that delays invoking `func` until after `wait`
174 * milliseconds have elapsed since the last time the debounced function was
175 * invoked. The debounced function comes with a `cancel` method to cancel
176 * delayed `func` invocations and a `flush` method to immediately invoke them.
177 * Provide `options` to indicate whether `func` should be invoked on the
178 * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
179 * with the last arguments provided to the debounced function. Subsequent
180 * calls to the debounced function return the result of the last `func`
181 * invocation.
182 *
183 * **Note:** If `leading` and `trailing` options are `true`, `func` is
184 * invoked on the trailing edge of the timeout only if the debounced function
185 * is invoked more than once during the `wait` timeout.
186 *
187 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
188 * until to the next tick, similar to `setTimeout` with a timeout of `0`.
189 *
190 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
191 * for details over the differences between `_.debounce` and `_.throttle`.
192 *
193 * @static
194 * @memberOf _
195 * @since 0.1.0
196 * @category Function
197 * @param {Function} func The function to debounce.
198 * @param {number} [wait=0] The number of milliseconds to delay.
199 * @param {Object} [options={}] The options object.
200 * @param {boolean} [options.leading=false]
201 * Specify invoking on the leading edge of the timeout.
202 * @param {number} [options.maxWait]
203 * The maximum time `func` is allowed to be delayed before it's invoked.
204 * @param {boolean} [options.trailing=true]
205 * Specify invoking on the trailing edge of the timeout.
206 * @returns {Function} Returns the new debounced function.
207 * @example
208 *
209 * // Avoid costly calculations while the window size is in flux.
210 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
211 *
212 * // Invoke `sendMail` when clicked, debouncing subsequent calls.
213 * jQuery(element).on('click', _.debounce(sendMail, 300, {
214 * 'leading': true,
215 * 'trailing': false
216 * }));
217 *
218 * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
219 * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
220 * var source = new EventSource('/stream');
221 * jQuery(source).on('message', debounced);
222 *
223 * // Cancel the trailing debounced invocation.
224 * jQuery(window).on('popstate', debounced.cancel);
225 */
226function debounce(func, wait, options) {
227 var lastArgs,
228 lastThis,
229 maxWait,
230 result,
231 timerId,
232 lastCallTime,
233 lastInvokeTime = 0,
234 leading = false,
235 maxing = false,
236 trailing = true;
237
238 if (typeof func != 'function') {
239 throw new TypeError(FUNC_ERROR_TEXT);
240 }
241 wait = toNumber_1(wait) || 0;
242 if (isObject.isObject(options)) {
243 leading = !!options.leading;
244 maxing = 'maxWait' in options;
245 maxWait = maxing ? nativeMax(toNumber_1(options.maxWait) || 0, wait) : maxWait;
246 trailing = 'trailing' in options ? !!options.trailing : trailing;
247 }
248
249 function invokeFunc(time) {
250 var args = lastArgs,
251 thisArg = lastThis;
252
253 lastArgs = lastThis = undefined;
254 lastInvokeTime = time;
255 result = func.apply(thisArg, args);
256 return result;
257 }
258
259 function leadingEdge(time) {
260 // Reset any `maxWait` timer.
261 lastInvokeTime = time;
262 // Start the timer for the trailing edge.
263 timerId = setTimeout(timerExpired, wait);
264 // Invoke the leading edge.
265 return leading ? invokeFunc(time) : result;
266 }
267
268 function remainingWait(time) {
269 var timeSinceLastCall = time - lastCallTime,
270 timeSinceLastInvoke = time - lastInvokeTime,
271 timeWaiting = wait - timeSinceLastCall;
272
273 return maxing
274 ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
275 : timeWaiting;
276 }
277
278 function shouldInvoke(time) {
279 var timeSinceLastCall = time - lastCallTime,
280 timeSinceLastInvoke = time - lastInvokeTime;
281
282 // Either this is the first call, activity has stopped and we're at the
283 // trailing edge, the system time has gone backwards and we're treating
284 // it as the trailing edge, or we've hit the `maxWait` limit.
285 return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
286 (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
287 }
288
289 function timerExpired() {
290 var time = now_1();
291 if (shouldInvoke(time)) {
292 return trailingEdge(time);
293 }
294 // Restart the timer.
295 timerId = setTimeout(timerExpired, remainingWait(time));
296 }
297
298 function trailingEdge(time) {
299 timerId = undefined;
300
301 // Only invoke if we have `lastArgs` which means `func` has been
302 // debounced at least once.
303 if (trailing && lastArgs) {
304 return invokeFunc(time);
305 }
306 lastArgs = lastThis = undefined;
307 return result;
308 }
309
310 function cancel() {
311 if (timerId !== undefined) {
312 clearTimeout(timerId);
313 }
314 lastInvokeTime = 0;
315 lastArgs = lastCallTime = lastThis = timerId = undefined;
316 }
317
318 function flush() {
319 return timerId === undefined ? result : trailingEdge(now_1());
320 }
321
322 function debounced() {
323 var time = now_1(),
324 isInvoking = shouldInvoke(time);
325
326 lastArgs = arguments;
327 lastThis = this;
328 lastCallTime = time;
329
330 if (isInvoking) {
331 if (timerId === undefined) {
332 return leadingEdge(lastCallTime);
333 }
334 if (maxing) {
335 // Handle invocations in a tight loop.
336 clearTimeout(timerId);
337 timerId = setTimeout(timerExpired, wait);
338 return invokeFunc(lastCallTime);
339 }
340 }
341 if (timerId === undefined) {
342 timerId = setTimeout(timerExpired, wait);
343 }
344 return result;
345 }
346 debounced.cancel = cancel;
347 debounced.flush = flush;
348 return debounced;
349}
350
351var debounce_1 = debounce;
352
353/** Error message constants. */
354var FUNC_ERROR_TEXT$1 = 'Expected a function';
355
356/**
357 * Creates a throttled function that only invokes `func` at most once per
358 * every `wait` milliseconds. The throttled function comes with a `cancel`
359 * method to cancel delayed `func` invocations and a `flush` method to
360 * immediately invoke them. Provide `options` to indicate whether `func`
361 * should be invoked on the leading and/or trailing edge of the `wait`
362 * timeout. The `func` is invoked with the last arguments provided to the
363 * throttled function. Subsequent calls to the throttled function return the
364 * result of the last `func` invocation.
365 *
366 * **Note:** If `leading` and `trailing` options are `true`, `func` is
367 * invoked on the trailing edge of the timeout only if the throttled function
368 * is invoked more than once during the `wait` timeout.
369 *
370 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
371 * until to the next tick, similar to `setTimeout` with a timeout of `0`.
372 *
373 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
374 * for details over the differences between `_.throttle` and `_.debounce`.
375 *
376 * @static
377 * @memberOf _
378 * @since 0.1.0
379 * @category Function
380 * @param {Function} func The function to throttle.
381 * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
382 * @param {Object} [options={}] The options object.
383 * @param {boolean} [options.leading=true]
384 * Specify invoking on the leading edge of the timeout.
385 * @param {boolean} [options.trailing=true]
386 * Specify invoking on the trailing edge of the timeout.
387 * @returns {Function} Returns the new throttled function.
388 * @example
389 *
390 * // Avoid excessively updating the position while scrolling.
391 * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
392 *
393 * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
394 * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
395 * jQuery(element).on('click', throttled);
396 *
397 * // Cancel the trailing throttled invocation.
398 * jQuery(window).on('popstate', throttled.cancel);
399 */
400function throttle(func, wait, options) {
401 var leading = true,
402 trailing = true;
403
404 if (typeof func != 'function') {
405 throw new TypeError(FUNC_ERROR_TEXT$1);
406 }
407 if (isObject.isObject(options)) {
408 leading = 'leading' in options ? !!options.leading : leading;
409 trailing = 'trailing' in options ? !!options.trailing : trailing;
410 }
411 return debounce_1(func, wait, {
412 'leading': leading,
413 'maxWait': wait,
414 'trailing': trailing
415 });
416}
417
418var throttle_1 = throttle;
419
420function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = getPrototypeOf._getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf._getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return getPrototypeOf._possibleConstructorReturn(this, result); }; }
421
422function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
423
424function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
425
426function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { defineProperty._defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
427var NO_DOM_WINDOW_SIZE = {
428 width: 0,
429 height: 0
430};
431
432var WINDOW_SIZE_BASE = _objectSpread({
433 breakpoints: breakpoints.BREAKPOINTS
434}, getCurrentWindowSize());
435
436var ViewportContext = React__default.createContext(WINDOW_SIZE_BASE);
437
438function getCurrentWindowSize() {
439 return typeof window === 'undefined' ? NO_DOM_WINDOW_SIZE : {
440 width: window.innerWidth,
441 height: window.innerHeight
442 };
443}
444
445var ViewportProvider = /*#__PURE__*/function (_React$Component) {
446 getPrototypeOf._inherits(ViewportProvider, _React$Component);
447
448 var _super = _createSuper(ViewportProvider);
449
450 function ViewportProvider() {
451 var _this;
452
453 getPrototypeOf._classCallCheck(this, ViewportProvider);
454
455 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
456 args[_key] = arguments[_key];
457 }
458
459 _this = _super.call.apply(_super, [this].concat(args));
460
461 defineProperty._defineProperty(getPrototypeOf._assertThisInitialized(_this), "state", {
462 windowSize: _this.getWindowSize()
463 });
464
465 defineProperty._defineProperty(getPrototypeOf._assertThisInitialized(_this), "updateWindowSize", function () {
466 _this.setState({
467 windowSize: _this.getWindowSize()
468 });
469 });
470
471 defineProperty._defineProperty(getPrototypeOf._assertThisInitialized(_this), "within", function (min, max) {
472 var width = _this.state.windowSize.width; // Accept "" or -1 indifferently
473
474 if (min === '') min = -1;
475 if (max === '') max = -1; // Convert breakpoints into numbers
476
477 if (typeof min === 'string') min = breakpoints.BREAKPOINTS[min];
478 if (typeof max === 'string') max = breakpoints.BREAKPOINTS[max];
479
480 if (typeof min !== 'number') {
481 throw new Error("Viewport: invalid minimum value (".concat(min, ")."));
482 }
483
484 if (typeof max !== 'number') {
485 throw new Error("Viewport: invalid maximum value (".concat(max, ")."));
486 }
487
488 return (min === -1 || width >= min) && (max === -1 || width < max);
489 });
490
491 defineProperty._defineProperty(getPrototypeOf._assertThisInitialized(_this), "above", function (value) {
492 return _this.within(value, -1);
493 });
494
495 defineProperty._defineProperty(getPrototypeOf._assertThisInitialized(_this), "below", function (value) {
496 return _this.within(-1, value);
497 });
498
499 return _this;
500 }
501
502 getPrototypeOf._createClass(ViewportProvider, [{
503 key: "componentDidMount",
504 value: function componentDidMount() {
505 this.resizeStart();
506 }
507 }, {
508 key: "componentWillUnmount",
509 value: function componentWillUnmount() {
510 this.resizeStop();
511 }
512 }, {
513 key: "componentDidUpdate",
514 value: function componentDidUpdate(prevProps) {
515 var throttle = this.props.throttle;
516
517 if (prevProps.throttle !== throttle) {
518 this.resizeStop();
519 this.resizeStart();
520 }
521 }
522 }, {
523 key: "resizeStart",
524 value: function resizeStart() {
525 this._handleResize = throttle_1(this.updateWindowSize, this.props.throttle);
526 this.updateWindowSize();
527
528 if (typeof window !== 'undefined') {
529 window.addEventListener('resize', this._handleResize);
530 }
531 }
532 }, {
533 key: "resizeStop",
534 value: function resizeStop() {
535 if (!this._handleResize) {
536 return;
537 }
538
539 if (typeof window !== 'undefined') {
540 window.removeEventListener('resize', this._handleResize);
541 }
542
543 this._handleResize.cancel();
544
545 delete this._handleResize;
546 }
547 }, {
548 key: "getWindowSize",
549 value: function getWindowSize() {
550 return _objectSpread(_objectSpread({}, WINDOW_SIZE_BASE), getCurrentWindowSize());
551 } // Check if the current width is between two points.
552 // Accepts a breakpoint string ('small', 'large') or numbers (width in pixels).
553 // `min` is inclusive and `max` is exclusive.
554
555 }, {
556 key: "render",
557 value: function render() {
558 var windowSize = this.state.windowSize;
559 var children = this.props.children;
560 var within = this.within,
561 above = this.above,
562 below = this.below;
563 return /*#__PURE__*/React__default.createElement(ViewportContext.Provider, {
564 value: _objectSpread(_objectSpread({}, windowSize), {}, {
565 within: within,
566 above: above,
567 below: below
568 })
569 }, children);
570 }
571 }]);
572
573 return ViewportProvider;
574}(React__default.Component); // React emits a warning message if `Provider` is attached to `Consumer`, this
575// is only to prevent it.
576
577
578defineProperty._defineProperty(ViewportProvider, "propTypes", {
579 children: index.PropTypes.node,
580 throttle: index.PropTypes.number
581});
582
583defineProperty._defineProperty(ViewportProvider, "defaultProps", {
584 throttle: 100
585});
586
587var Viewport = function Viewport(props) {
588 return /*#__PURE__*/React__default.createElement(ViewportContext.Consumer, props);
589};
590
591Viewport.Provider = ViewportProvider;
592var useViewport = function useViewport() {
593 return React__default.useContext(ViewportContext);
594};
595
596exports.Viewport = Viewport;
597exports.useViewport = useViewport;
598//# sourceMappingURL=Viewport-fe2db97a.js.map