(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('react-dom')) :
typeof define === 'function' && define.amd ? define(['exports', 'react', 'react-dom'], factory) :
(global = global || self, factory(global.ReactBootstrapTypeahead = {}, global.React, global.ReactDOM));
}(this, function (exports, React, reactDom) { 'use strict';
var React__default = 'default' in React ? React['default'] : React;
var reactDom__default = 'default' in reactDom ? reactDom['default'] : reactDom;
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x.default : x;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
/**
* lodash (Custom Build)
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors
* Released under MIT license
* Based on Underscore.js 1.8.3
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
nativeMin = Math.min;
/**
* Gets the timestamp of the number of milliseconds that have elapsed since
* the Unix epoch (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Date
* @returns {number} Returns the timestamp.
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => Logs the number of milliseconds it took for the deferred invocation.
*/
var now = function() {
return root.Date.now();
};
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed `func` invocations and a `flush` method to immediately invoke them.
* Provide `options` to indicate whether `func` should be invoked on the
* leading and/or trailing edge of the `wait` timeout. The `func` is invoked
* with the last arguments provided to the debounced function. Subsequent
* calls to the debounced function return the result of the last `func`
* invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the debounced function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=false]
* Specify invoking on the leading edge of the timeout.
* @param {number} [options.maxWait]
* The maximum time `func` is allowed to be delayed before it's invoked.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // Avoid costly calculations while the window size is in flux.
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // Invoke `sendMail` when clicked, debouncing subsequent calls.
* jQuery(element).on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // Ensure `batchLog` is invoked once after 1 second of debounced calls.
* var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
* var source = new EventSource('/stream');
* jQuery(source).on('message', debounced);
*
* // Cancel the trailing debounced invocation.
* jQuery(window).on('popstate', debounced.cancel);
*/
function debounce(func, wait, options) {
var lastArgs,
lastThis,
maxWait,
result,
timerId,
lastCallTime,
lastInvokeTime = 0,
leading = false,
maxing = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = toNumber(wait) || 0;
if (isObject(options)) {
leading = !!options.leading;
maxing = 'maxWait' in options;
maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs,
thisArg = lastThis;
lastArgs = lastThis = undefined;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time;
// Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait);
// Invoke the leading edge.
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime,
result = wait - timeSinceLastCall;
return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime;
// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
(timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
}
function timerExpired() {
var time = now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
// Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
timerId = undefined;
// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = undefined;
return result;
}
function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = undefined;
}
function flush() {
return timerId === undefined ? result : trailingEdge(now());
}
function debounced() {
var time = now(),
isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && objectToString.call(value) == symbolTag);
}
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
var lodash_debounce = debounce;
var reactIs_production_min = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports,"__esModule",{value:!0});
var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.concurrent_mode"):60111,n=b?Symbol.for("react.forward_ref"):60112,p=b?Symbol.for("react.suspense"):60113,q=b?Symbol.for("react.memo"):
60115,r=b?Symbol.for("react.lazy"):60116;function t(a){if("object"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case h:return a;default:return u}}case r:case q:case d:return u}}}function v(a){return t(a)===m}exports.typeOf=t;exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;
exports.Fragment=e;exports.Lazy=r;exports.Memo=q;exports.Portal=d;exports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===e||a===m||a===g||a===f||a===p||"object"===typeof a&&null!==a&&(a.$$typeof===r||a.$$typeof===q||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n)};exports.isAsyncMode=function(a){return v(a)||t(a)===l};exports.isConcurrentMode=v;exports.isContextConsumer=function(a){return t(a)===k};
exports.isContextProvider=function(a){return t(a)===h};exports.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return t(a)===n};exports.isFragment=function(a){return t(a)===e};exports.isLazy=function(a){return t(a)===r};exports.isMemo=function(a){return t(a)===q};exports.isPortal=function(a){return t(a)===d};exports.isProfiler=function(a){return t(a)===g};exports.isStrictMode=function(a){return t(a)===f};
exports.isSuspense=function(a){return t(a)===p};
});
unwrapExports(reactIs_production_min);
var reactIs_production_min_1 = reactIs_production_min.typeOf;
var reactIs_production_min_2 = reactIs_production_min.AsyncMode;
var reactIs_production_min_3 = reactIs_production_min.ConcurrentMode;
var reactIs_production_min_4 = reactIs_production_min.ContextConsumer;
var reactIs_production_min_5 = reactIs_production_min.ContextProvider;
var reactIs_production_min_6 = reactIs_production_min.Element;
var reactIs_production_min_7 = reactIs_production_min.ForwardRef;
var reactIs_production_min_8 = reactIs_production_min.Fragment;
var reactIs_production_min_9 = reactIs_production_min.Lazy;
var reactIs_production_min_10 = reactIs_production_min.Memo;
var reactIs_production_min_11 = reactIs_production_min.Portal;
var reactIs_production_min_12 = reactIs_production_min.Profiler;
var reactIs_production_min_13 = reactIs_production_min.StrictMode;
var reactIs_production_min_14 = reactIs_production_min.Suspense;
var reactIs_production_min_15 = reactIs_production_min.isValidElementType;
var reactIs_production_min_16 = reactIs_production_min.isAsyncMode;
var reactIs_production_min_17 = reactIs_production_min.isConcurrentMode;
var reactIs_production_min_18 = reactIs_production_min.isContextConsumer;
var reactIs_production_min_19 = reactIs_production_min.isContextProvider;
var reactIs_production_min_20 = reactIs_production_min.isElement;
var reactIs_production_min_21 = reactIs_production_min.isForwardRef;
var reactIs_production_min_22 = reactIs_production_min.isFragment;
var reactIs_production_min_23 = reactIs_production_min.isLazy;
var reactIs_production_min_24 = reactIs_production_min.isMemo;
var reactIs_production_min_25 = reactIs_production_min.isPortal;
var reactIs_production_min_26 = reactIs_production_min.isProfiler;
var reactIs_production_min_27 = reactIs_production_min.isStrictMode;
var reactIs_production_min_28 = reactIs_production_min.isSuspense;
var reactIs_development = createCommonjsModule(function (module, exports) {
{
(function() {
Object.defineProperty(exports, '__esModule', { value: true });
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var hasSymbol = typeof Symbol === 'function' && Symbol.for;
var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
function isValidElementType(type) {
return typeof type === 'string' || typeof type === 'function' ||
// Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE);
}
/**
* Forked from fbjs/warning:
* https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
*
* Only change is we use console.warn instead of console.error,
* and do nothing when 'console' is not supported.
* This really simplifies the code.
* ---
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var lowPriorityWarning = function () {};
{
var printWarning = function (format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.warn(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
lowPriorityWarning = function (condition, format) {
if (format === undefined) {
throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
}
var lowPriorityWarning$1 = lowPriorityWarning;
function typeOf(object) {
if (typeof object === 'object' && object !== null) {
var $$typeof = object.$$typeof;
switch ($$typeof) {
case REACT_ELEMENT_TYPE:
var type = object.type;
switch (type) {
case REACT_ASYNC_MODE_TYPE:
case REACT_CONCURRENT_MODE_TYPE:
case REACT_FRAGMENT_TYPE:
case REACT_PROFILER_TYPE:
case REACT_STRICT_MODE_TYPE:
case REACT_SUSPENSE_TYPE:
return type;
default:
var $$typeofType = type && type.$$typeof;
switch ($$typeofType) {
case REACT_CONTEXT_TYPE:
case REACT_FORWARD_REF_TYPE:
case REACT_PROVIDER_TYPE:
return $$typeofType;
default:
return $$typeof;
}
}
case REACT_LAZY_TYPE:
case REACT_MEMO_TYPE:
case REACT_PORTAL_TYPE:
return $$typeof;
}
}
return undefined;
}
// AsyncMode is deprecated along with isAsyncMode
var AsyncMode = REACT_ASYNC_MODE_TYPE;
var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
var ContextConsumer = REACT_CONTEXT_TYPE;
var ContextProvider = REACT_PROVIDER_TYPE;
var Element = REACT_ELEMENT_TYPE;
var ForwardRef = REACT_FORWARD_REF_TYPE;
var Fragment = REACT_FRAGMENT_TYPE;
var Lazy = REACT_LAZY_TYPE;
var Memo = REACT_MEMO_TYPE;
var Portal = REACT_PORTAL_TYPE;
var Profiler = REACT_PROFILER_TYPE;
var StrictMode = REACT_STRICT_MODE_TYPE;
var Suspense = REACT_SUSPENSE_TYPE;
var hasWarnedAboutDeprecatedIsAsyncMode = false;
// AsyncMode should be deprecated
function isAsyncMode(object) {
{
if (!hasWarnedAboutDeprecatedIsAsyncMode) {
hasWarnedAboutDeprecatedIsAsyncMode = true;
lowPriorityWarning$1(false, 'The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');
}
}
return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
}
function isConcurrentMode(object) {
return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
}
function isContextConsumer(object) {
return typeOf(object) === REACT_CONTEXT_TYPE;
}
function isContextProvider(object) {
return typeOf(object) === REACT_PROVIDER_TYPE;
}
function isElement(object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
function isForwardRef(object) {
return typeOf(object) === REACT_FORWARD_REF_TYPE;
}
function isFragment(object) {
return typeOf(object) === REACT_FRAGMENT_TYPE;
}
function isLazy(object) {
return typeOf(object) === REACT_LAZY_TYPE;
}
function isMemo(object) {
return typeOf(object) === REACT_MEMO_TYPE;
}
function isPortal(object) {
return typeOf(object) === REACT_PORTAL_TYPE;
}
function isProfiler(object) {
return typeOf(object) === REACT_PROFILER_TYPE;
}
function isStrictMode(object) {
return typeOf(object) === REACT_STRICT_MODE_TYPE;
}
function isSuspense(object) {
return typeOf(object) === REACT_SUSPENSE_TYPE;
}
exports.typeOf = typeOf;
exports.AsyncMode = AsyncMode;
exports.ConcurrentMode = ConcurrentMode;
exports.ContextConsumer = ContextConsumer;
exports.ContextProvider = ContextProvider;
exports.Element = Element;
exports.ForwardRef = ForwardRef;
exports.Fragment = Fragment;
exports.Lazy = Lazy;
exports.Memo = Memo;
exports.Portal = Portal;
exports.Profiler = Profiler;
exports.StrictMode = StrictMode;
exports.Suspense = Suspense;
exports.isValidElementType = isValidElementType;
exports.isAsyncMode = isAsyncMode;
exports.isConcurrentMode = isConcurrentMode;
exports.isContextConsumer = isContextConsumer;
exports.isContextProvider = isContextProvider;
exports.isElement = isElement;
exports.isForwardRef = isForwardRef;
exports.isFragment = isFragment;
exports.isLazy = isLazy;
exports.isMemo = isMemo;
exports.isPortal = isPortal;
exports.isProfiler = isProfiler;
exports.isStrictMode = isStrictMode;
exports.isSuspense = isSuspense;
})();
}
});
unwrapExports(reactIs_development);
var reactIs_development_1 = reactIs_development.typeOf;
var reactIs_development_2 = reactIs_development.AsyncMode;
var reactIs_development_3 = reactIs_development.ConcurrentMode;
var reactIs_development_4 = reactIs_development.ContextConsumer;
var reactIs_development_5 = reactIs_development.ContextProvider;
var reactIs_development_6 = reactIs_development.Element;
var reactIs_development_7 = reactIs_development.ForwardRef;
var reactIs_development_8 = reactIs_development.Fragment;
var reactIs_development_9 = reactIs_development.Lazy;
var reactIs_development_10 = reactIs_development.Memo;
var reactIs_development_11 = reactIs_development.Portal;
var reactIs_development_12 = reactIs_development.Profiler;
var reactIs_development_13 = reactIs_development.StrictMode;
var reactIs_development_14 = reactIs_development.Suspense;
var reactIs_development_15 = reactIs_development.isValidElementType;
var reactIs_development_16 = reactIs_development.isAsyncMode;
var reactIs_development_17 = reactIs_development.isConcurrentMode;
var reactIs_development_18 = reactIs_development.isContextConsumer;
var reactIs_development_19 = reactIs_development.isContextProvider;
var reactIs_development_20 = reactIs_development.isElement;
var reactIs_development_21 = reactIs_development.isForwardRef;
var reactIs_development_22 = reactIs_development.isFragment;
var reactIs_development_23 = reactIs_development.isLazy;
var reactIs_development_24 = reactIs_development.isMemo;
var reactIs_development_25 = reactIs_development.isPortal;
var reactIs_development_26 = reactIs_development.isProfiler;
var reactIs_development_27 = reactIs_development.isStrictMode;
var reactIs_development_28 = reactIs_development.isSuspense;
var reactIs = createCommonjsModule(function (module) {
{
module.exports = reactIs_development;
}
});
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret;
var printWarning = function() {};
{
var ReactPropTypesSecret$1 = ReactPropTypesSecret_1;
var loggedTypeFailures = {};
var has = Function.call.bind(Object.prototype.hasOwnProperty);
printWarning = function(text) {
var message = 'Warning: ' + text;
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
}
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?Function} getStack Returns the component stack.
* @private
*/
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
{
for (var typeSpecName in typeSpecs) {
if (has(typeSpecs, typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if (typeof typeSpecs[typeSpecName] !== 'function') {
var err = Error(
(componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
);
err.name = 'Invariant Violation';
throw err;
}
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1);
} catch (ex) {
error = ex;
}
if (error && !(error instanceof Error)) {
printWarning(
(componentName || 'React class') + ': type specification of ' +
location + ' `' + typeSpecName + '` is invalid; the type checker ' +
'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
'You may have forgotten to pass an argument to the type checker ' +
'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
'shape all require an argument).'
);
}
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var stack = getStack ? getStack() : '';
printWarning(
'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
);
}
}
}
}
}
/**
* Resets warning cache when testing.
*
* @private
*/
checkPropTypes.resetWarningCache = function() {
{
loggedTypeFailures = {};
}
};
var checkPropTypes_1 = checkPropTypes;
var has$1 = Function.call.bind(Object.prototype.hasOwnProperty);
var printWarning$1 = function() {};
{
printWarning$1 = function(text) {
var message = 'Warning: ' + text;
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
}
function emptyFunctionThatReturnsNull() {
return null;
}
var factoryWithTypeCheckers = function(isValidElement, throwOnDirectAccess) {
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<>';
// Important!
// Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
symbol: createPrimitiveTypeChecker('symbol'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
elementType: createElementTypeTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker,
exact: createStrictShapeTypeChecker,
};
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/*eslint-enable no-self-compare*/
/**
* We use an Error-like object for backward compatibility as people may call
* PropTypes directly and inspect their output. However, we don't use real
* Errors anymore. We don't inspect their stack anyway, and creating them
* is prohibitively expensive if they are created too often, such as what
* happens in oneOfType() for any type before the one that matched.
*/
function PropTypeError(message) {
this.message = message;
this.stack = '';
}
// Make `instanceof Error` still work for returned errors.
PropTypeError.prototype = Error.prototype;
function createChainableTypeChecker(validate) {
{
var manualPropTypeCallCache = {};
var manualPropTypeWarningCount = 0;
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (secret !== ReactPropTypesSecret_1) {
if (throwOnDirectAccess) {
// New behavior only for users of `prop-types` package
var err = new Error(
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use `PropTypes.checkPropTypes()` to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
err.name = 'Invariant Violation';
throw err;
} else if (typeof console !== 'undefined') {
// Old behavior for people using React.PropTypes
var cacheKey = componentName + ':' + propName;
if (
!manualPropTypeCallCache[cacheKey] &&
// Avoid spamming the console because they are often not actionable except for lib authors
manualPropTypeWarningCount < 3
) {
printWarning$1(
'You are manually calling a React.PropTypes validation ' +
'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' +
'and will throw in the standalone `prop-types` package. ' +
'You may be seeing this warning due to a third-party PropTypes ' +
'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.'
);
manualPropTypeCallCache[cacheKey] = true;
manualPropTypeWarningCount++;
}
}
}
if (props[propName] == null) {
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
}
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName, secret) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunctionThatReturnsNull);
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret_1);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!isValidElement(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!reactIs.isValidElementType(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
{
if (arguments.length > 1) {
printWarning$1(
'Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' +
'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).'
);
} else {
printWarning$1('Invalid argument supplied to oneOf, expected an array.');
}
}
return emptyFunctionThatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (is(propValue, expectedValues[i])) {
return null;
}
}
var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {
var type = getPreciseType(value);
if (type === 'symbol') {
return String(value);
}
return value;
});
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (has$1(propValue, key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
printWarning$1('Invalid argument supplied to oneOfType, expected an instance of array.');
return emptyFunctionThatReturnsNull;
}
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (typeof checker !== 'function') {
printWarning$1(
'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +
'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.'
);
return emptyFunctionThatReturnsNull;
}
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret_1) == null) {
return null;
}
}
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createStrictShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
// We need to check all keys in case some are required but missing from
// props.
var allKeys = objectAssign({}, props[propName], shapeTypes);
for (var key in allKeys) {
var checker = shapeTypes[key];
if (!checker) {
return new PropTypeError(
'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +
'\nBad object: ' + JSON.stringify(props[propName], null, ' ') +
'\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')
);
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === 'symbol') {
return true;
}
// falsy value can't be a Symbol
if (!propValue) {
return false;
}
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue['@@toStringTag'] === 'Symbol') {
return true;
}
// Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === 'function' && propValue instanceof Symbol) {
return true;
}
return false;
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
if (isSymbol(propType, propValue)) {
return 'symbol';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
if (typeof propValue === 'undefined' || propValue === null) {
return '' + propValue;
}
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
// Returns a string that is postfixed to a warning about an invalid type.
// For example, "undefined" or "of type array"
function getPostfixForTypeWarning(value) {
var type = getPreciseType(value);
switch (type) {
case 'array':
case 'object':
return 'an ' + type;
case 'boolean':
case 'date':
case 'regexp':
return 'a ' + type;
default:
return type;
}
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
ReactPropTypes.checkPropTypes = checkPropTypes_1;
ReactPropTypes.resetWarningCache = checkPropTypes_1.resetWarningCache;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
var propTypes = createCommonjsModule(function (module) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
{
var ReactIs = reactIs;
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
module.exports = factoryWithTypeCheckers(ReactIs.isElement, throwOnDirectAccess);
}
});
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var invariant = function(condition, format, a, b, c, d, e, f) {
{
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
format.replace(/%s/g, function() { return args[argIndex++]; })
);
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
var invariant_1 = invariant;
/**
* Common (non-printable) keycodes for `keydown` and `keyup` events. Note that
* `keypress` handles things differently and may not return the same values.
*/
var BACKSPACE = 8;
var TAB = 9;
var RETURN = 13;
var ESC = 27;
var UP = 38;
var RIGHT = 39;
var DOWN = 40;
var DEFAULT_LABELKEY = 'label';
function getStringLabelKey(labelKey) {
return typeof labelKey === 'string' ? labelKey : DEFAULT_LABELKEY;
}
var idCounter = 0;
function head(arr) {
return Array.isArray(arr) && arr.length ? arr[0] : undefined;
}
function isFunction(value) {
return typeof value === 'function';
}
function isString(value) {
return typeof value === 'string';
}
function noop() {}
function pick(obj, keys) {
var result = {};
keys.forEach(function (k) {
if (Object.prototype.hasOwnProperty.call(obj, k)) {
result[k] = obj[k];
}
});
return result;
}
function uniqueId(prefix) {
idCounter += 1;
return (prefix == null ? '' : String(prefix)) + idCounter;
}
/**
* Retrieves the display string from an option. Options can be the string
* themselves, or an object with a defined display string. Anything else throws
* an error.
*/
function getOptionLabel(option, labelKey) {
// Handle internally created options first.
if (!isString(option) && (option.paginationOption || option.customOption)) {
return option[getStringLabelKey(labelKey)];
}
var optionLabel;
if (isFunction(labelKey)) {
optionLabel = labelKey(option);
} else if (isString(option)) {
optionLabel = option;
} else {
// `option` is an object and `labelKey` is a string.
optionLabel = option[labelKey];
}
!isString(optionLabel) ? invariant_1(false, 'One or more options does not have a valid label string. Check the ' + '`labelKey` prop to ensure that it matches the correct option key and ' + 'provides a string for filtering and display.') : void 0;
return optionLabel;
}
function addCustomOption(results, props) {
var allowNew = props.allowNew,
labelKey = props.labelKey,
text = props.text;
if (!allowNew || !text.trim()) {
return false;
} // If the consumer has provided a callback, use that to determine whether or
// not to add the custom option.
if (typeof allowNew === 'function') {
return allowNew(results, props);
} // By default, don't add the custom option if there is an exact text match
// with an existing option.
return !results.some(function (o) {
return getOptionLabel(o, labelKey) === text;
});
}
var lodash_isequal = createCommonjsModule(function (module, exports) {
/**
* Lodash (Custom Build)
* Build: `lodash modularize exports="npm" -o ./`
* Copyright JS Foundation and other contributors
* Released under MIT license
* Based on Underscore.js 1.8.3
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
asyncTag = '[object AsyncFunction]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
nullTag = '[object Null]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
proxyTag = '[object Proxy]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
undefinedTag = '[object Undefined]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
/** Detect free variable `exports`. */
var freeExports = exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
/* Node.js helper references. */
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
/** Used for built-in method references. */
var arrayProto = Array.prototype,
funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
Symbol = root.Symbol,
Uint8Array = root.Uint8Array,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
splice = arrayProto.splice,
symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols,
nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
nativeKeys = overArg(Object.keys, Object);
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView'),
Map = getNative(root, 'Map'),
Promise = getNative(root, 'Promise'),
Set = getNative(root, 'Set'),
WeakMap = getNative(root, 'WeakMap'),
nativeCreate = getNative(Object, 'create');
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
}
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
return this;
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new Hash,
'map': new (Map || ListCache),
'string': new Hash
};
}
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
/**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var index = -1,
length = values == null ? 0 : values.length;
this.__data__ = new MapCache;
while (++index < length) {
this.add(values[index]);
}
}
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED);
return this;
}
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
this.size = 0;
}
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray(value),
isArg = !isArr && isArguments(value),
isBuff = !isArr && !isArg && isBuffer(value),
isType = !isArr && !isArg && !isBuff && isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag && symToStringTag in Object(value))
? getRawTag(value)
: objectToString(value);
}
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = objIsArr ? arrayTag : getTag(object),
othTag = othIsArr ? arrayTag : getTag(other);
objTag = objTag == argsTag ? objectTag : objTag;
othTag = othTag == argsTag ? objectTag : othTag;
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(array);
if (stacked && stack.get(other)) {
return stacked == other;
}
var index = -1,
result = true,
seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!arraySome(other, function(othValue, othIndex) {
if (!cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, bitmask, customizer, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
case numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= COMPARE_UNORDERED_FLAG;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack['delete'](object);
return result;
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
objProps = getAllKeys(object),
objLength = objProps.length,
othProps = getAllKeys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked && stack.get(other)) {
return stacked == other;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable.call(object, symbol);
});
};
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = baseGetTag(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString.call(value);
}
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are compared by strict equality, i.e. `===`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value, other) {
return baseIsEqual(value, other);
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
module.exports = isEqual;
});
function getOptionProperty(option, key) {
if (isString(option)) {
return undefined;
}
return option[key];
}
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Taken from: http://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript/18391901#18391901
*/
/* eslint-disable max-len */
var map = [{
base: 'A',
letters: "A\u24B6\uFF21\xC0\xC1\xC2\u1EA6\u1EA4\u1EAA\u1EA8\xC3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\xC4\u01DE\u1EA2\xC5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F"
}, {
base: 'AA',
letters: "\uA732"
}, {
base: 'AE',
letters: "\xC6\u01FC\u01E2"
}, {
base: 'AO',
letters: "\uA734"
}, {
base: 'AU',
letters: "\uA736"
}, {
base: 'AV',
letters: "\uA738\uA73A"
}, {
base: 'AY',
letters: "\uA73C"
}, {
base: 'B',
letters: "B\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181"
}, {
base: 'C',
letters: "C\u24B8\uFF23\u0106\u0108\u010A\u010C\xC7\u1E08\u0187\u023B\uA73E"
}, {
base: 'D',
letters: "D\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779\xD0"
}, {
base: 'DZ',
letters: "\u01F1\u01C4"
}, {
base: 'Dz',
letters: "\u01F2\u01C5"
}, {
base: 'E',
letters: "E\u24BA\uFF25\xC8\xC9\xCA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\xCB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E"
}, {
base: 'F',
letters: "F\u24BB\uFF26\u1E1E\u0191\uA77B"
}, {
base: 'G',
letters: "G\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E"
}, {
base: 'H',
letters: "H\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D"
}, {
base: 'I',
letters: "I\u24BE\uFF29\xCC\xCD\xCE\u0128\u012A\u012C\u0130\xCF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197"
}, {
base: 'J',
letters: "J\u24BF\uFF2A\u0134\u0248"
}, {
base: 'K',
letters: "K\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2"
}, {
base: 'L',
letters: "L\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780"
}, {
base: 'LJ',
letters: "\u01C7"
}, {
base: 'Lj',
letters: "\u01C8"
}, {
base: 'M',
letters: "M\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C"
}, {
base: 'N',
letters: "N\u24C3\uFF2E\u01F8\u0143\xD1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4"
}, {
base: 'NJ',
letters: "\u01CA"
}, {
base: 'Nj',
letters: "\u01CB"
}, {
base: 'O',
letters: "O\u24C4\uFF2F\xD2\xD3\xD4\u1ED2\u1ED0\u1ED6\u1ED4\xD5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\xD6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\xD8\u01FE\u0186\u019F\uA74A\uA74C"
}, {
base: 'OI',
letters: "\u01A2"
}, {
base: 'OO',
letters: "\uA74E"
}, {
base: 'OU',
letters: "\u0222"
}, {
base: 'OE',
letters: "\x8C\u0152"
}, {
base: 'oe',
letters: "\x9C\u0153"
}, {
base: 'P',
letters: "P\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754"
}, {
base: 'Q',
letters: "Q\u24C6\uFF31\uA756\uA758\u024A"
}, {
base: 'R',
letters: "R\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782"
}, {
base: 'S',
letters: "S\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784"
}, {
base: 'T',
letters: "T\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786"
}, {
base: 'TZ',
letters: "\uA728"
}, {
base: 'U',
letters: "U\u24CA\uFF35\xD9\xDA\xDB\u0168\u1E78\u016A\u1E7A\u016C\xDC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244"
}, {
base: 'V',
letters: "V\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245"
}, {
base: 'VY',
letters: "\uA760"
}, {
base: 'W',
letters: "W\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72"
}, {
base: 'X',
letters: "X\u24CD\uFF38\u1E8A\u1E8C"
}, {
base: 'Y',
letters: "Y\u24CE\uFF39\u1EF2\xDD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE"
}, {
base: 'Z',
letters: "Z\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762"
}, {
base: 'a',
letters: "a\u24D0\uFF41\u1E9A\xE0\xE1\xE2\u1EA7\u1EA5\u1EAB\u1EA9\xE3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\xE4\u01DF\u1EA3\xE5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250"
}, {
base: 'aa',
letters: "\uA733"
}, {
base: 'ae',
letters: "\xE6\u01FD\u01E3"
}, {
base: 'ao',
letters: "\uA735"
}, {
base: 'au',
letters: "\uA737"
}, {
base: 'av',
letters: "\uA739\uA73B"
}, {
base: 'ay',
letters: "\uA73D"
}, {
base: 'b',
letters: "b\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253"
}, {
base: 'c',
letters: "c\u24D2\uFF43\u0107\u0109\u010B\u010D\xE7\u1E09\u0188\u023C\uA73F\u2184"
}, {
base: 'd',
letters: "d\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A"
}, {
base: 'dz',
letters: "\u01F3\u01C6"
}, {
base: 'e',
letters: "e\u24D4\uFF45\xE8\xE9\xEA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\xEB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD"
}, {
base: 'f',
letters: "f\u24D5\uFF46\u1E1F\u0192\uA77C"
}, {
base: 'g',
letters: "g\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F"
}, {
base: 'h',
letters: "h\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265"
}, {
base: 'hv',
letters: "\u0195"
}, {
base: 'i',
letters: "i\u24D8\uFF49\xEC\xED\xEE\u0129\u012B\u012D\xEF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131"
}, {
base: 'j',
letters: "j\u24D9\uFF4A\u0135\u01F0\u0249"
}, {
base: 'k',
letters: "k\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3"
}, {
base: 'l',
letters: "l\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747"
}, {
base: 'lj',
letters: "\u01C9"
}, {
base: 'm',
letters: "m\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F"
}, {
base: 'n',
letters: "n\u24DD\uFF4E\u01F9\u0144\xF1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5"
}, {
base: 'nj',
letters: "\u01CC"
}, {
base: 'o',
letters: "o\u24DE\uFF4F\xF2\xF3\xF4\u1ED3\u1ED1\u1ED7\u1ED5\xF5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\xF6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\xF8\u01FF\u0254\uA74B\uA74D\u0275"
}, {
base: 'oi',
letters: "\u01A3"
}, {
base: 'ou',
letters: "\u0223"
}, {
base: 'oo',
letters: "\uA74F"
}, {
base: 'p',
letters: "p\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755"
}, {
base: 'q',
letters: "q\u24E0\uFF51\u024B\uA757\uA759"
}, {
base: 'r',
letters: "r\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783"
}, {
base: 's',
letters: "s\u24E2\uFF53\xDF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B"
}, {
base: 't',
letters: "t\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787"
}, {
base: 'tz',
letters: "\uA729"
}, {
base: 'u',
letters: "u\u24E4\uFF55\xF9\xFA\xFB\u0169\u1E79\u016B\u1E7B\u016D\xFC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289"
}, {
base: 'v',
letters: "v\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C"
}, {
base: 'vy',
letters: "\uA761"
}, {
base: 'w',
letters: "w\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73"
}, {
base: 'x',
letters: "x\u24E7\uFF58\u1E8B\u1E8D"
}, {
base: 'y',
letters: "y\u24E8\uFF59\u1EF3\xFD\u0177\u1EF9\u0233\u1E8F\xFF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF"
}, {
base: 'z',
letters: "z\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763"
}];
/* eslint-enable max-len */
var diacriticsMap = {};
for (var ii = 0; ii < map.length; ii++) {
var letters = map[ii].letters;
for (var jj = 0; jj < letters.length; jj++) {
diacriticsMap[letters[jj]] = map[ii].base;
}
} // "what?" version ... http://jsperf.com/diacritics/12
function stripDiacritics(str) {
return str.replace(/[\u0300-\u036F]/g, '') // Remove combining diacritics
/* eslint-disable-next-line no-control-regex */
.replace(/[^\u0000-\u007E]/g, function (a) {
return diacriticsMap[a] || a;
});
}
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var warning = function() {};
{
var printWarning$2 = function printWarning(format, args) {
var len = arguments.length;
args = new Array(len > 1 ? len - 1 : 0);
for (var key = 1; key < len; key++) {
args[key - 1] = arguments[key];
}
var argIndex = 0;
var message = 'Warning: ' +
format.replace(/%s/g, function() {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
warning = function(condition, format, args) {
var len = arguments.length;
args = new Array(len > 2 ? len - 2 : 0);
for (var key = 2; key < len; key++) {
args[key - 2] = arguments[key];
}
if (format === undefined) {
throw new Error(
'`warning(condition, format, ...args)` requires a warning ' +
'message argument'
);
}
if (!condition) {
printWarning$2.apply(null, [format].concat(args));
}
};
}
var warning_1 = warning;
var warned = {};
/**
* Copied from: https://github.com/ReactTraining/react-router/blob/master/modules/routerWarning.js
*/
function warn(falseToWarn, message) {
// Only issue deprecation warnings once.
if (!falseToWarn && message.indexOf('deprecated') !== -1) {
if (warned[message]) {
return;
}
warned[message] = true;
}
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
warning_1.apply(void 0, [falseToWarn, "[react-bootstrap-typeahead] " + message].concat(args));
}
function isMatch(input, string, props) {
var searchStr = input;
var str = string;
if (!props.caseSensitive) {
searchStr = searchStr.toLowerCase();
str = str.toLowerCase();
}
if (props.ignoreDiacritics) {
searchStr = stripDiacritics(searchStr);
str = stripDiacritics(str);
}
return str.indexOf(searchStr) !== -1;
}
/**
* Default algorithm for filtering results.
*/
function defaultFilterBy(option, props) {
var filterBy = props.filterBy,
labelKey = props.labelKey,
multiple = props.multiple,
selected = props.selected,
text = props.text; // Don't show selected options in the menu for the multi-select case.
if (multiple && selected.some(function (o) {
return lodash_isequal(o, option);
})) {
return false;
}
if (isFunction(labelKey) && isMatch(text, labelKey(option), props)) {
return true;
}
var fields = filterBy.slice();
if (isString(labelKey)) {
// Add the `labelKey` field to the list of fields if it isn't already there.
if (fields.indexOf(labelKey) === -1) {
fields.unshift(labelKey);
}
}
if (isString(option)) {
warn(fields.length <= 1, 'You cannot filter by properties when `option` is a string.');
return isMatch(text, option, props);
}
return fields.some(function (field) {
var value = getOptionProperty(option, field);
if (!isString(value)) {
warn(false, 'Fields passed to `filterBy` should have string values. Value will ' + 'be converted to a string; results may be unexpected.');
value = String(value);
}
return isMatch(text, value, props);
});
}
function getDisplayName(Component) {
return Component.displayName || Component.name || 'Component';
}
var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
var escapeStringRegexp = function (str) {
if (typeof str !== 'string') {
throw new TypeError('Expected a string');
}
return str.replace(matchOperatorsRe, '\\$&');
};
var CASE_INSENSITIVE = 'i';
var COMBINING_MARKS = /[\u0300-\u036F]/;
function getMatchBounds(subject, str) {
var search = new RegExp(escapeStringRegexp(stripDiacritics(str)), CASE_INSENSITIVE);
var matches = search.exec(stripDiacritics(subject));
if (!matches) {
return null;
}
var start = matches.index;
var matchLength = matches[0].length; // Account for combining marks, which changes the indices.
if (COMBINING_MARKS.test(subject)) {
// Starting at the beginning of the subject string, check for the number of
// combining marks and increment the start index whenever one is found.
for (var ii = 0; ii <= start; ii++) {
if (COMBINING_MARKS.test(subject[ii])) {
start += 1;
}
} // Similarly, increment the length of the match string if it contains a
// combining mark.
for (var _ii = start; _ii <= start + matchLength; _ii++) {
if (COMBINING_MARKS.test(subject[_ii])) {
matchLength += 1;
}
}
}
return {
end: start + matchLength,
start: start
};
}
function getHintText(props) {
var activeItem = props.activeItem,
initialItem = props.initialItem,
isFocused = props.isFocused,
isMenuShown = props.isMenuShown,
labelKey = props.labelKey,
multiple = props.multiple,
selected = props.selected,
text = props.text; // Don't display a hint under the following conditions:
if ( // No text entered.
!text || // The input is not focused.
!isFocused || // The menu is hidden.
!isMenuShown || // No item in the menu.
!initialItem || // The initial item is a custom option.
initialItem.customOption || // One of the menu items is active.
activeItem || // There's already a selection in single-select mode.
!!selected.length && !multiple) {
return '';
}
var initialItemStr = getOptionLabel(initialItem, labelKey);
var bounds = getMatchBounds(initialItemStr.toLowerCase(), text.toLowerCase());
if (!(bounds && bounds.start === 0)) {
return '';
} // Text matching is case- and accent-insensitive, so to display the hint
// correctly, splice the input string with the hint string.
return text + initialItemStr.slice(bounds.end, initialItemStr.length);
}
var classnames = createCommonjsModule(function (module) {
/*!
Copyright (c) 2017 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg) && arg.length) {
var inner = classNames.apply(null, arg);
if (inner) {
classes.push(inner);
}
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if (module.exports) {
classNames.default = classNames;
module.exports = classNames;
} else {
window.classNames = classNames;
}
}());
});
function getMenuItemId(id, position) {
return (id || '') + "-item-" + position;
}
var getInputProps = function getInputProps(_ref) {
var activeIndex = _ref.activeIndex,
getReferenceElement = _ref.getReferenceElement,
id = _ref.id,
isFocused = _ref.isFocused,
isMenuShown = _ref.isMenuShown,
labelKey = _ref.labelKey,
multiple = _ref.multiple,
onFocus = _ref.onFocus,
onRemove = _ref.onRemove,
placeholder = _ref.placeholder,
rest = _objectWithoutPropertiesLoose(_ref, ["activeIndex", "getReferenceElement", "id", "isFocused", "isMenuShown", "labelKey", "multiple", "onFocus", "onRemove", "placeholder"]);
return function (_temp) {
var _cx;
var _ref2 = _temp === void 0 ? {} : _temp,
className = _ref2.className,
inputProps = _objectWithoutPropertiesLoose(_ref2, ["className"]);
var props = _extends({
/* eslint-disable sort-keys */
// These props can be overridden by values in `inputProps`.
autoComplete: 'off',
placeholder: placeholder,
type: 'text'
}, inputProps, rest, {
'aria-activedescendant': activeIndex >= 0 ? getMenuItemId(id, activeIndex) : '',
'aria-autocomplete': 'both',
'aria-expanded': isMenuShown,
'aria-haspopup': 'listbox',
'aria-owns': isMenuShown ? id : '',
className: classnames((_cx = {}, _cx[className || ''] = !multiple, _cx.focus = isFocused, _cx)),
// Re-open the menu, eg: if it's closed via ESC.
onClick: onFocus,
onFocus: onFocus,
// Comboboxes are single-select by definition:
// https://www.w3.org/TR/wai-aria-practices-1.1/#combobox
role: 'combobox'
/* eslint-enable sort-keys */
});
if (!multiple) {
return props;
}
return _extends({}, props, {
'aria-autocomplete': 'list',
'aria-expanded': undefined,
inputClassName: className,
onRemove: onRemove,
role: undefined
});
};
};
function getInputText(props) {
var activeItem = props.activeItem,
labelKey = props.labelKey,
multiple = props.multiple,
selected = props.selected,
text = props.text;
if (activeItem) {
// Display the input value if the pagination item is active.
return activeItem.paginationOption ? text : getOptionLabel(activeItem, labelKey);
}
var selectedItem = !multiple && !!selected.length && head(selected);
if (selectedItem) {
return getOptionLabel(selectedItem, labelKey);
}
return text;
}
function getIsOnlyResult(props) {
var allowNew = props.allowNew,
highlightOnlyResult = props.highlightOnlyResult,
results = props.results;
if (!highlightOnlyResult || allowNew) {
return false;
}
return results.length === 1 && !getOptionProperty(head(results), 'disabled');
}
/**
* Truncates the result set based on `maxResults` and returns the new set.
*/
function getTruncatedOptions(options, maxResults) {
if (!maxResults || maxResults >= options.length) {
return options;
}
return options.slice(0, maxResults);
}
function skipDisabledOptions(currentIndex, keyCode, results) {
var newIndex = currentIndex;
while (results[newIndex] && results[newIndex].disabled) {
newIndex += keyCode === UP ? -1 : 1;
}
return newIndex;
}
function getUpdatedActiveIndex(currentIndex, keyCode, results) {
var newIndex = currentIndex; // Increment or decrement index based on user keystroke.
newIndex += keyCode === UP ? -1 : 1; // Skip over any disabled options.
newIndex = skipDisabledOptions(newIndex, keyCode, results); // If we've reached the end, go back to the beginning or vice-versa.
if (newIndex === results.length) {
newIndex = -1;
} else if (newIndex === -2) {
newIndex = results.length - 1; // Skip over any disabled options.
newIndex = skipDisabledOptions(newIndex, keyCode, results);
}
return newIndex;
}
/**
* Check if an input type is selectable, based on WHATWG spec.
*
* See:
* - https://stackoverflow.com/questions/21177489/selectionstart-selectionend-on-input-type-number-no-longer-allowed-in-chrome/24175357
* - https://html.spec.whatwg.org/multipage/input.html#do-not-apply
*/
function isSelectable(inputNode) {
return inputNode.selectionStart != null;
}
function isShown(props) {
var open = props.open,
minLength = props.minLength,
showMenu = props.showMenu,
text = props.text; // If menu visibility is controlled via props, that value takes precedence.
if (open || open === false) {
return open;
}
if (text.length < minLength) {
return false;
}
return showMenu;
}
/**
* Prevent the main input from blurring when a menu item or the clear button is
* clicked. (#226 & #310)
*/
function preventInputBlur(e) {
e.preventDefault();
}
function shouldSelectHint(_ref, _ref2) {
var currentTarget = _ref.currentTarget,
keyCode = _ref.keyCode;
var hintText = _ref2.hintText,
selectHintOnEnter = _ref2.selectHintOnEnter,
value = _ref2.value;
if (!hintText) {
return false;
}
if (keyCode === RIGHT) {
// For selectable input types ("text", "search"), only select the hint if
// it's at the end of the input value. For non-selectable types ("email",
// "number"), always select the hint.
return isSelectable(currentTarget) ? currentTarget.selectionStart === value.length : true;
}
if (keyCode === TAB) {
return true;
}
if (keyCode === RETURN && selectHintOnEnter) {
return true;
}
return false;
}
function validateSelectedPropChange(prevSelected, selected) {
var uncontrolledToControlled = !prevSelected && selected;
var controlledToUncontrolled = prevSelected && !selected;
var from, to, precedent;
if (uncontrolledToControlled) {
from = 'uncontrolled';
to = 'controlled';
precedent = 'an';
} else {
from = 'controlled';
to = 'uncontrolled';
precedent = 'a';
}
var message = "You are changing " + precedent + " " + from + " typeahead to be " + to + ". " + ("Input elements should not switch from " + from + " to " + to + " (or vice versa). ") + 'Decide between using a controlled or uncontrolled element for the ' + 'lifetime of the component.';
warn(!(uncontrolledToControlled || controlledToUncontrolled), message);
}
var INPUT_PROPS_BLACKLIST = [{
alt: 'onBlur',
prop: 'onBlur'
}, {
alt: 'onInputChange',
prop: 'onChange'
}, {
alt: 'onFocus',
prop: 'onFocus'
}, {
alt: 'onKeyDown',
prop: 'onKeyDown'
}];
/**
* Allows additional warnings or messaging related to prop validation.
*/
function checkPropType(validator, callback) {
return function (props, propName, componentName) {
var _PropTypes$checkPropT;
propTypes.checkPropTypes((_PropTypes$checkPropT = {}, _PropTypes$checkPropT[propName] = validator, _PropTypes$checkPropT), props, 'prop', componentName);
isFunction(callback) && callback(props, propName, componentName);
};
}
function caseSensitiveType(props, propName, componentName) {
var caseSensitive = props.caseSensitive,
filterBy = props.filterBy;
warn(!caseSensitive || typeof filterBy !== 'function', 'Your `filterBy` function will override the `caseSensitive` prop.');
}
function defaultInputValueType(props, propName, componentName) {
var defaultInputValue = props.defaultInputValue,
defaultSelected = props.defaultSelected,
multiple = props.multiple,
selected = props.selected;
var name = defaultSelected.length ? 'defaultSelected' : 'selected';
warn(!(!multiple && defaultInputValue && (defaultSelected.length || selected && selected.length)), "`defaultInputValue` will be overridden by the value from `" + name + "`.");
}
function highlightOnlyResultType(props, propName, componentName) {
var allowNew = props.allowNew,
highlightOnlyResult = props.highlightOnlyResult;
warn(!(highlightOnlyResult && allowNew), '`highlightOnlyResult` will not work with `allowNew`.');
}
function ignoreDiacriticsType(props, propName, componentName) {
var filterBy = props.filterBy,
ignoreDiacritics = props.ignoreDiacritics;
warn(ignoreDiacritics || typeof filterBy !== 'function', 'Your `filterBy` function will override the `ignoreDiacritics` prop.');
}
function inputPropsType(props, propName, componentName) {
var inputProps = props.inputProps;
if (!(inputProps && Object.prototype.toString.call(inputProps) === '[object Object]')) {
return;
} // Blacklisted properties.
INPUT_PROPS_BLACKLIST.forEach(function (_ref) {
var alt = _ref.alt,
prop = _ref.prop;
var msg = alt ? " Use the top-level `" + alt + "` prop instead." : null;
warn(!inputProps[prop], "The `" + prop + "` property of `inputProps` will be ignored." + msg);
});
}
function isRequiredForA11y(props, propName, componentName) {
warn(props[propName] != null, "The prop `" + propName + "` is required to make `" + componentName + "` " + 'accessible for users of assistive technologies such as screen readers.');
}
function labelKeyType(props, propName, componentName) {
var allowNew = props.allowNew,
labelKey = props.labelKey;
warn(!(isFunction(labelKey) && allowNew), '`labelKey` must be a string when `allowNew={true}`.');
}
var optionType = propTypes.oneOfType([propTypes.object, propTypes.string]).isRequired;
function selectedType(props, propName, componentName) {
var onChange = props.onChange,
selected = props.selected;
warn(!selected || selected && isFunction(onChange), 'You provided a `selected` prop without an `onChange` handler. If you ' + 'want the typeahead to be uncontrolled, use `defaultSelected`. ' + 'Otherwise, set `onChange`.');
}
var propTypes$1 = {
/**
* Delay, in milliseconds, before performing search.
*/
delay: propTypes.number,
/**
* Whether or not a request is currently pending. Necessary for the
* container to know when new results are available.
*/
isLoading: propTypes.bool.isRequired,
/**
* Number of input characters that must be entered before showing results.
*/
minLength: propTypes.number,
/**
* Callback to perform when the search is executed.
*/
onSearch: propTypes.func.isRequired,
/**
* Options to be passed to the typeahead. Will typically be the query
* results, but can also be initial default options.
*/
options: propTypes.arrayOf(optionType),
/**
* Message displayed in the menu when there is no user input.
*/
promptText: propTypes.node,
/**
* Message displayed in the menu while the request is pending.
*/
searchText: propTypes.node,
/**
* Whether or not the component should cache query results.
*/
useCache: propTypes.bool
};
var defaultProps = {
delay: 200,
minLength: 2,
options: [],
promptText: 'Type to search...',
searchText: 'Searching...',
useCache: true
};
/**
* HoC that encapsulates common behavior and functionality for doing
* asynchronous searches, including:
*
* - Debouncing user input
* - Optional query caching
* - Search prompt and empty results behaviors
*/
var asyncContainer = function asyncContainer(Typeahead) {
var _class, _temp;
return _temp = _class =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(_class, _React$Component);
function _class() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_defineProperty(_assertThisInitialized(_this), "_cache", {});
_defineProperty(_assertThisInitialized(_this), "_handleSearchDebounced", undefined);
_defineProperty(_assertThisInitialized(_this), "_instance", undefined);
_defineProperty(_assertThisInitialized(_this), "_query", '');
_defineProperty(_assertThisInitialized(_this), "_getEmptyLabel", function () {
var _this$props = _this.props,
emptyLabel = _this$props.emptyLabel,
isLoading = _this$props.isLoading,
promptText = _this$props.promptText,
searchText = _this$props.searchText;
if (!_this._query.length) {
return promptText;
}
if (isLoading) {
return searchText;
}
return emptyLabel;
});
_defineProperty(_assertThisInitialized(_this), "_handleInputChange", function (query, e) {
_this.props.onInputChange && _this.props.onInputChange(query, e);
_this._handleSearchDebounced(query);
});
_defineProperty(_assertThisInitialized(_this), "_handleSearch", function (query) {
_this._query = query;
var _this$props2 = _this.props,
minLength = _this$props2.minLength,
onSearch = _this$props2.onSearch,
useCache = _this$props2.useCache;
if (!query || minLength && query.length < minLength) {
return;
} // Use cached results, if applicable.
if (useCache && _this._cache[query]) {
// Re-render the component with the cached results.
_this.forceUpdate();
return;
} // Perform the search.
onSearch(query);
});
return _this;
}
var _proto = _class.prototype;
_proto.componentDidMount = function componentDidMount() {
this._handleSearchDebounced = lodash_debounce(this._handleSearch, this.props.delay);
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
if (prevProps.isLoading && this.props.useCache) {
this._cache[this._query] = this.props.options;
}
};
_proto.componentWillUnmount = function componentWillUnmount() {
this._cache = {};
this._query = '';
this._handleSearchDebounced && this._handleSearchDebounced.cancel();
};
_proto.render = function render() {
var _this2 = this;
var _this$props3 = this.props,
allowNew = _this$props3.allowNew,
isLoading = _this$props3.isLoading,
options = _this$props3.options,
useCache = _this$props3.useCache,
props = _objectWithoutPropertiesLoose(_this$props3, ["allowNew", "isLoading", "options", "useCache"]);
var cachedQuery = this._cache[this._query];
return React__default.createElement(Typeahead, _extends({}, props, {
allowNew: // Disable custom selections during a search unless
// `allowNew` is a function.
isFunction(allowNew) ? allowNew : allowNew && !isLoading,
emptyLabel: this._getEmptyLabel(),
isLoading: isLoading,
onInputChange: this._handleInputChange,
options: useCache && cachedQuery ? cachedQuery : options,
ref: function ref(instance) {
return _this2._instance = instance;
}
}));
}
/**
* Make the component instance available.
*/
;
_proto.getInstance = function getInstance() {
return this._instance.getInstance();
};
return _class;
}(React__default.Component), _defineProperty(_class, "displayName", "asyncContainer(" + getDisplayName(Typeahead) + ")"), _defineProperty(_class, "propTypes", propTypes$1), _defineProperty(_class, "defaultProps", defaultProps), _temp;
};
function _objectWithoutPropertiesLoose$1(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
var objectWithoutPropertiesLoose = _objectWithoutPropertiesLoose$1;
var _extends_1 = createCommonjsModule(function (module) {
function _extends() {
module.exports = _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
module.exports = _extends;
});
function _inheritsLoose$1(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
var inheritsLoose = _inheritsLoose$1;
function _assertThisInitialized$1(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
var assertThisInitialized = _assertThisInitialized$1;
function _defineProperty$1(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var defineProperty = _defineProperty$1;
/**!
* @fileOverview Kickass library to create and place poppers near their reference elements.
* @version 1.14.7
* @license
* Copyright (c) 2016 Federico Zivolo and contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined';
var longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox'];
var timeoutDuration = 0;
for (var i = 0; i < longerTimeoutBrowsers.length; i += 1) {
if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) {
timeoutDuration = 1;
break;
}
}
function microtaskDebounce(fn) {
var called = false;
return function () {
if (called) {
return;
}
called = true;
window.Promise.resolve().then(function () {
called = false;
fn();
});
};
}
function taskDebounce(fn) {
var scheduled = false;
return function () {
if (!scheduled) {
scheduled = true;
setTimeout(function () {
scheduled = false;
fn();
}, timeoutDuration);
}
};
}
var supportsMicroTasks = isBrowser && window.Promise;
/**
* Create a debounced version of a method, that's asynchronously deferred
* but called in the minimum time possible.
*
* @method
* @memberof Popper.Utils
* @argument {Function} fn
* @returns {Function}
*/
var debounce$1 = supportsMicroTasks ? microtaskDebounce : taskDebounce;
/**
* Check if the given variable is a function
* @method
* @memberof Popper.Utils
* @argument {Any} functionToCheck - variable to check
* @returns {Boolean} answer to: is a function?
*/
function isFunction$1(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
/**
* Get CSS computed property of the given element
* @method
* @memberof Popper.Utils
* @argument {Eement} element
* @argument {String} property
*/
function getStyleComputedProperty(element, property) {
if (element.nodeType !== 1) {
return [];
}
// NOTE: 1 DOM access here
var window = element.ownerDocument.defaultView;
var css = window.getComputedStyle(element, null);
return property ? css[property] : css;
}
/**
* Returns the parentNode or the host of the element
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} parent
*/
function getParentNode(element) {
if (element.nodeName === 'HTML') {
return element;
}
return element.parentNode || element.host;
}
/**
* Returns the scrolling parent of the given element
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} scroll parent
*/
function getScrollParent(element) {
// Return body, `getScroll` will take care to get the correct `scrollTop` from it
if (!element) {
return document.body;
}
switch (element.nodeName) {
case 'HTML':
case 'BODY':
return element.ownerDocument.body;
case '#document':
return element.body;
}
// Firefox want us to check `-x` and `-y` variations as well
var _getStyleComputedProp = getStyleComputedProperty(element),
overflow = _getStyleComputedProp.overflow,
overflowX = _getStyleComputedProp.overflowX,
overflowY = _getStyleComputedProp.overflowY;
if (/(auto|scroll|overlay)/.test(overflow + overflowY + overflowX)) {
return element;
}
return getScrollParent(getParentNode(element));
}
var isIE11 = isBrowser && !!(window.MSInputMethodContext && document.documentMode);
var isIE10 = isBrowser && /MSIE 10/.test(navigator.userAgent);
/**
* Determines if the browser is Internet Explorer
* @method
* @memberof Popper.Utils
* @param {Number} version to check
* @returns {Boolean} isIE
*/
function isIE(version) {
if (version === 11) {
return isIE11;
}
if (version === 10) {
return isIE10;
}
return isIE11 || isIE10;
}
/**
* Returns the offset parent of the given element
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} offset parent
*/
function getOffsetParent(element) {
if (!element) {
return document.documentElement;
}
var noOffsetParent = isIE(10) ? document.body : null;
// NOTE: 1 DOM access here
var offsetParent = element.offsetParent || null;
// Skip hidden elements which don't have an offsetParent
while (offsetParent === noOffsetParent && element.nextElementSibling) {
offsetParent = (element = element.nextElementSibling).offsetParent;
}
var nodeName = offsetParent && offsetParent.nodeName;
if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') {
return element ? element.ownerDocument.documentElement : document.documentElement;
}
// .offsetParent will return the closest TH, TD or TABLE in case
// no offsetParent is present, I hate this job...
if (['TH', 'TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') {
return getOffsetParent(offsetParent);
}
return offsetParent;
}
function isOffsetContainer(element) {
var nodeName = element.nodeName;
if (nodeName === 'BODY') {
return false;
}
return nodeName === 'HTML' || getOffsetParent(element.firstElementChild) === element;
}
/**
* Finds the root node (document, shadowDOM root) of the given element
* @method
* @memberof Popper.Utils
* @argument {Element} node
* @returns {Element} root node
*/
function getRoot(node) {
if (node.parentNode !== null) {
return getRoot(node.parentNode);
}
return node;
}
/**
* Finds the offset parent common to the two provided nodes
* @method
* @memberof Popper.Utils
* @argument {Element} element1
* @argument {Element} element2
* @returns {Element} common offset parent
*/
function findCommonOffsetParent(element1, element2) {
// This check is needed to avoid errors in case one of the elements isn't defined for any reason
if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) {
return document.documentElement;
}
// Here we make sure to give as "start" the element that comes first in the DOM
var order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING;
var start = order ? element1 : element2;
var end = order ? element2 : element1;
// Get common ancestor container
var range = document.createRange();
range.setStart(start, 0);
range.setEnd(end, 0);
var commonAncestorContainer = range.commonAncestorContainer;
// Both nodes are inside #document
if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) {
if (isOffsetContainer(commonAncestorContainer)) {
return commonAncestorContainer;
}
return getOffsetParent(commonAncestorContainer);
}
// one of the nodes is inside shadowDOM, find which one
var element1root = getRoot(element1);
if (element1root.host) {
return findCommonOffsetParent(element1root.host, element2);
} else {
return findCommonOffsetParent(element1, getRoot(element2).host);
}
}
/**
* Gets the scroll value of the given element in the given side (top and left)
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @argument {String} side `top` or `left`
* @returns {number} amount of scrolled pixels
*/
function getScroll(element) {
var side = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'top';
var upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft';
var nodeName = element.nodeName;
if (nodeName === 'BODY' || nodeName === 'HTML') {
var html = element.ownerDocument.documentElement;
var scrollingElement = element.ownerDocument.scrollingElement || html;
return scrollingElement[upperSide];
}
return element[upperSide];
}
/*
* Sum or subtract the element scroll values (left and top) from a given rect object
* @method
* @memberof Popper.Utils
* @param {Object} rect - Rect object you want to change
* @param {HTMLElement} element - The element from the function reads the scroll values
* @param {Boolean} subtract - set to true if you want to subtract the scroll values
* @return {Object} rect - The modifier rect object
*/
function includeScroll(rect, element) {
var subtract = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var scrollTop = getScroll(element, 'top');
var scrollLeft = getScroll(element, 'left');
var modifier = subtract ? -1 : 1;
rect.top += scrollTop * modifier;
rect.bottom += scrollTop * modifier;
rect.left += scrollLeft * modifier;
rect.right += scrollLeft * modifier;
return rect;
}
/*
* Helper to detect borders of a given element
* @method
* @memberof Popper.Utils
* @param {CSSStyleDeclaration} styles
* Result of `getStyleComputedProperty` on the given element
* @param {String} axis - `x` or `y`
* @return {number} borders - The borders size of the given axis
*/
function getBordersSize(styles, axis) {
var sideA = axis === 'x' ? 'Left' : 'Top';
var sideB = sideA === 'Left' ? 'Right' : 'Bottom';
return parseFloat(styles['border' + sideA + 'Width'], 10) + parseFloat(styles['border' + sideB + 'Width'], 10);
}
function getSize(axis, body, html, computedStyle) {
return Math.max(body['offset' + axis], body['scroll' + axis], html['client' + axis], html['offset' + axis], html['scroll' + axis], isIE(10) ? parseInt(html['offset' + axis]) + parseInt(computedStyle['margin' + (axis === 'Height' ? 'Top' : 'Left')]) + parseInt(computedStyle['margin' + (axis === 'Height' ? 'Bottom' : 'Right')]) : 0);
}
function getWindowSizes(document) {
var body = document.body;
var html = document.documentElement;
var computedStyle = isIE(10) && getComputedStyle(html);
return {
height: getSize('Height', body, html, computedStyle),
width: getSize('Width', body, html, computedStyle)
};
}
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var defineProperty$1 = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
var _extends$1 = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
/**
* Given element offsets, generate an output similar to getBoundingClientRect
* @method
* @memberof Popper.Utils
* @argument {Object} offsets
* @returns {Object} ClientRect like output
*/
function getClientRect(offsets) {
return _extends$1({}, offsets, {
right: offsets.left + offsets.width,
bottom: offsets.top + offsets.height
});
}
/**
* Get bounding client rect of given element
* @method
* @memberof Popper.Utils
* @param {HTMLElement} element
* @return {Object} client rect
*/
function getBoundingClientRect(element) {
var rect = {};
// IE10 10 FIX: Please, don't ask, the element isn't
// considered in DOM in some circumstances...
// This isn't reproducible in IE10 compatibility mode of IE11
try {
if (isIE(10)) {
rect = element.getBoundingClientRect();
var scrollTop = getScroll(element, 'top');
var scrollLeft = getScroll(element, 'left');
rect.top += scrollTop;
rect.left += scrollLeft;
rect.bottom += scrollTop;
rect.right += scrollLeft;
} else {
rect = element.getBoundingClientRect();
}
} catch (e) {}
var result = {
left: rect.left,
top: rect.top,
width: rect.right - rect.left,
height: rect.bottom - rect.top
};
// subtract scrollbar size from sizes
var sizes = element.nodeName === 'HTML' ? getWindowSizes(element.ownerDocument) : {};
var width = sizes.width || element.clientWidth || result.right - result.left;
var height = sizes.height || element.clientHeight || result.bottom - result.top;
var horizScrollbar = element.offsetWidth - width;
var vertScrollbar = element.offsetHeight - height;
// if an hypothetical scrollbar is detected, we must be sure it's not a `border`
// we make this check conditional for performance reasons
if (horizScrollbar || vertScrollbar) {
var styles = getStyleComputedProperty(element);
horizScrollbar -= getBordersSize(styles, 'x');
vertScrollbar -= getBordersSize(styles, 'y');
result.width -= horizScrollbar;
result.height -= vertScrollbar;
}
return getClientRect(result);
}
function getOffsetRectRelativeToArbitraryNode(children, parent) {
var fixedPosition = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var isIE10 = isIE(10);
var isHTML = parent.nodeName === 'HTML';
var childrenRect = getBoundingClientRect(children);
var parentRect = getBoundingClientRect(parent);
var scrollParent = getScrollParent(children);
var styles = getStyleComputedProperty(parent);
var borderTopWidth = parseFloat(styles.borderTopWidth, 10);
var borderLeftWidth = parseFloat(styles.borderLeftWidth, 10);
// In cases where the parent is fixed, we must ignore negative scroll in offset calc
if (fixedPosition && isHTML) {
parentRect.top = Math.max(parentRect.top, 0);
parentRect.left = Math.max(parentRect.left, 0);
}
var offsets = getClientRect({
top: childrenRect.top - parentRect.top - borderTopWidth,
left: childrenRect.left - parentRect.left - borderLeftWidth,
width: childrenRect.width,
height: childrenRect.height
});
offsets.marginTop = 0;
offsets.marginLeft = 0;
// Subtract margins of documentElement in case it's being used as parent
// we do this only on HTML because it's the only element that behaves
// differently when margins are applied to it. The margins are included in
// the box of the documentElement, in the other cases not.
if (!isIE10 && isHTML) {
var marginTop = parseFloat(styles.marginTop, 10);
var marginLeft = parseFloat(styles.marginLeft, 10);
offsets.top -= borderTopWidth - marginTop;
offsets.bottom -= borderTopWidth - marginTop;
offsets.left -= borderLeftWidth - marginLeft;
offsets.right -= borderLeftWidth - marginLeft;
// Attach marginTop and marginLeft because in some circumstances we may need them
offsets.marginTop = marginTop;
offsets.marginLeft = marginLeft;
}
if (isIE10 && !fixedPosition ? parent.contains(scrollParent) : parent === scrollParent && scrollParent.nodeName !== 'BODY') {
offsets = includeScroll(offsets, parent);
}
return offsets;
}
function getViewportOffsetRectRelativeToArtbitraryNode(element) {
var excludeScroll = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var html = element.ownerDocument.documentElement;
var relativeOffset = getOffsetRectRelativeToArbitraryNode(element, html);
var width = Math.max(html.clientWidth, window.innerWidth || 0);
var height = Math.max(html.clientHeight, window.innerHeight || 0);
var scrollTop = !excludeScroll ? getScroll(html) : 0;
var scrollLeft = !excludeScroll ? getScroll(html, 'left') : 0;
var offset = {
top: scrollTop - relativeOffset.top + relativeOffset.marginTop,
left: scrollLeft - relativeOffset.left + relativeOffset.marginLeft,
width: width,
height: height
};
return getClientRect(offset);
}
/**
* Check if the given element is fixed or is inside a fixed parent
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @argument {Element} customContainer
* @returns {Boolean} answer to "isFixed?"
*/
function isFixed(element) {
var nodeName = element.nodeName;
if (nodeName === 'BODY' || nodeName === 'HTML') {
return false;
}
if (getStyleComputedProperty(element, 'position') === 'fixed') {
return true;
}
var parentNode = getParentNode(element);
if (!parentNode) {
return false;
}
return isFixed(parentNode);
}
/**
* Finds the first parent of an element that has a transformed property defined
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} first transformed parent or documentElement
*/
function getFixedPositionOffsetParent(element) {
// This check is needed to avoid errors in case one of the elements isn't defined for any reason
if (!element || !element.parentElement || isIE()) {
return document.documentElement;
}
var el = element.parentElement;
while (el && getStyleComputedProperty(el, 'transform') === 'none') {
el = el.parentElement;
}
return el || document.documentElement;
}
/**
* Computed the boundaries limits and return them
* @method
* @memberof Popper.Utils
* @param {HTMLElement} popper
* @param {HTMLElement} reference
* @param {number} padding
* @param {HTMLElement} boundariesElement - Element used to define the boundaries
* @param {Boolean} fixedPosition - Is in fixed position mode
* @returns {Object} Coordinates of the boundaries
*/
function getBoundaries(popper, reference, padding, boundariesElement) {
var fixedPosition = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
// NOTE: 1 DOM access here
var boundaries = { top: 0, left: 0 };
var offsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, reference);
// Handle viewport case
if (boundariesElement === 'viewport') {
boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent, fixedPosition);
} else {
// Handle other cases based on DOM element used as boundaries
var boundariesNode = void 0;
if (boundariesElement === 'scrollParent') {
boundariesNode = getScrollParent(getParentNode(reference));
if (boundariesNode.nodeName === 'BODY') {
boundariesNode = popper.ownerDocument.documentElement;
}
} else if (boundariesElement === 'window') {
boundariesNode = popper.ownerDocument.documentElement;
} else {
boundariesNode = boundariesElement;
}
var offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent, fixedPosition);
// In case of HTML, we need a different computation
if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) {
var _getWindowSizes = getWindowSizes(popper.ownerDocument),
height = _getWindowSizes.height,
width = _getWindowSizes.width;
boundaries.top += offsets.top - offsets.marginTop;
boundaries.bottom = height + offsets.top;
boundaries.left += offsets.left - offsets.marginLeft;
boundaries.right = width + offsets.left;
} else {
// for all the other DOM elements, this one is good
boundaries = offsets;
}
}
// Add paddings
padding = padding || 0;
var isPaddingNumber = typeof padding === 'number';
boundaries.left += isPaddingNumber ? padding : padding.left || 0;
boundaries.top += isPaddingNumber ? padding : padding.top || 0;
boundaries.right -= isPaddingNumber ? padding : padding.right || 0;
boundaries.bottom -= isPaddingNumber ? padding : padding.bottom || 0;
return boundaries;
}
function getArea(_ref) {
var width = _ref.width,
height = _ref.height;
return width * height;
}
/**
* Utility used to transform the `auto` placement to the placement with more
* available space.
* @method
* @memberof Popper.Utils
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement) {
var padding = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;
if (placement.indexOf('auto') === -1) {
return placement;
}
var boundaries = getBoundaries(popper, reference, padding, boundariesElement);
var rects = {
top: {
width: boundaries.width,
height: refRect.top - boundaries.top
},
right: {
width: boundaries.right - refRect.right,
height: boundaries.height
},
bottom: {
width: boundaries.width,
height: boundaries.bottom - refRect.bottom
},
left: {
width: refRect.left - boundaries.left,
height: boundaries.height
}
};
var sortedAreas = Object.keys(rects).map(function (key) {
return _extends$1({
key: key
}, rects[key], {
area: getArea(rects[key])
});
}).sort(function (a, b) {
return b.area - a.area;
});
var filteredAreas = sortedAreas.filter(function (_ref2) {
var width = _ref2.width,
height = _ref2.height;
return width >= popper.clientWidth && height >= popper.clientHeight;
});
var computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key;
var variation = placement.split('-')[1];
return computedPlacement + (variation ? '-' + variation : '');
}
/**
* Get offsets to the reference element
* @method
* @memberof Popper.Utils
* @param {Object} state
* @param {Element} popper - the popper element
* @param {Element} reference - the reference element (the popper will be relative to this)
* @param {Element} fixedPosition - is in fixed position mode
* @returns {Object} An object containing the offsets which will be applied to the popper
*/
function getReferenceOffsets(state, popper, reference) {
var fixedPosition = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var commonOffsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, reference);
return getOffsetRectRelativeToArbitraryNode(reference, commonOffsetParent, fixedPosition);
}
/**
* Get the outer sizes of the given element (offset size + margins)
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Object} object containing width and height properties
*/
function getOuterSizes(element) {
var window = element.ownerDocument.defaultView;
var styles = window.getComputedStyle(element);
var x = parseFloat(styles.marginTop || 0) + parseFloat(styles.marginBottom || 0);
var y = parseFloat(styles.marginLeft || 0) + parseFloat(styles.marginRight || 0);
var result = {
width: element.offsetWidth + y,
height: element.offsetHeight + x
};
return result;
}
/**
* Get the opposite placement of the given one
* @method
* @memberof Popper.Utils
* @argument {String} placement
* @returns {String} flipped placement
*/
function getOppositePlacement(placement) {
var hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' };
return placement.replace(/left|right|bottom|top/g, function (matched) {
return hash[matched];
});
}
/**
* Get offsets to the popper
* @method
* @memberof Popper.Utils
* @param {Object} position - CSS position the Popper will get applied
* @param {HTMLElement} popper - the popper element
* @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this)
* @param {String} placement - one of the valid placement options
* @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper
*/
function getPopperOffsets(popper, referenceOffsets, placement) {
placement = placement.split('-')[0];
// Get popper node sizes
var popperRect = getOuterSizes(popper);
// Add position, width and height to our offsets object
var popperOffsets = {
width: popperRect.width,
height: popperRect.height
};
// depending by the popper placement we have to compute its offsets slightly differently
var isHoriz = ['right', 'left'].indexOf(placement) !== -1;
var mainSide = isHoriz ? 'top' : 'left';
var secondarySide = isHoriz ? 'left' : 'top';
var measurement = isHoriz ? 'height' : 'width';
var secondaryMeasurement = !isHoriz ? 'height' : 'width';
popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2;
if (placement === secondarySide) {
popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement];
} else {
popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)];
}
return popperOffsets;
}
/**
* Mimics the `find` method of Array
* @method
* @memberof Popper.Utils
* @argument {Array} arr
* @argument prop
* @argument value
* @returns index or -1
*/
function find(arr, check) {
// use native find if supported
if (Array.prototype.find) {
return arr.find(check);
}
// use `filter` to obtain the same behavior of `find`
return arr.filter(check)[0];
}
/**
* Return the index of the matching object
* @method
* @memberof Popper.Utils
* @argument {Array} arr
* @argument prop
* @argument value
* @returns index or -1
*/
function findIndex(arr, prop, value) {
// use native findIndex if supported
if (Array.prototype.findIndex) {
return arr.findIndex(function (cur) {
return cur[prop] === value;
});
}
// use `find` + `indexOf` if `findIndex` isn't supported
var match = find(arr, function (obj) {
return obj[prop] === value;
});
return arr.indexOf(match);
}
/**
* Loop trough the list of modifiers and run them in order,
* each of them will then edit the data object.
* @method
* @memberof Popper.Utils
* @param {dataObject} data
* @param {Array} modifiers
* @param {String} ends - Optional modifier name used as stopper
* @returns {dataObject}
*/
function runModifiers(modifiers, data, ends) {
var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends));
modifiersToRun.forEach(function (modifier) {
if (modifier['function']) {
// eslint-disable-line dot-notation
console.warn('`modifier.function` is deprecated, use `modifier.fn`!');
}
var fn = modifier['function'] || modifier.fn; // eslint-disable-line dot-notation
if (modifier.enabled && isFunction$1(fn)) {
// Add properties to offsets to make them a complete clientRect object
// we do this before each modifier to make sure the previous one doesn't
// mess with these values
data.offsets.popper = getClientRect(data.offsets.popper);
data.offsets.reference = getClientRect(data.offsets.reference);
data = fn(data, modifier);
}
});
return data;
}
/**
* Updates the position of the popper, computing the new offsets and applying
* the new style.
* Prefer `scheduleUpdate` over `update` because of performance reasons.
* @method
* @memberof Popper
*/
function update() {
// if popper is destroyed, don't perform any further update
if (this.state.isDestroyed) {
return;
}
var data = {
instance: this,
styles: {},
arrowStyles: {},
attributes: {},
flipped: false,
offsets: {}
};
// compute reference element offsets
data.offsets.reference = getReferenceOffsets(this.state, this.popper, this.reference, this.options.positionFixed);
// compute auto placement, store placement inside the data object,
// modifiers will be able to edit `placement` if needed
// and refer to originalPlacement to know the original value
data.placement = computeAutoPlacement(this.options.placement, data.offsets.reference, this.popper, this.reference, this.options.modifiers.flip.boundariesElement, this.options.modifiers.flip.padding);
// store the computed placement inside `originalPlacement`
data.originalPlacement = data.placement;
data.positionFixed = this.options.positionFixed;
// compute the popper offsets
data.offsets.popper = getPopperOffsets(this.popper, data.offsets.reference, data.placement);
data.offsets.popper.position = this.options.positionFixed ? 'fixed' : 'absolute';
// run the modifiers
data = runModifiers(this.modifiers, data);
// the first `update` will call `onCreate` callback
// the other ones will call `onUpdate` callback
if (!this.state.isCreated) {
this.state.isCreated = true;
this.options.onCreate(data);
} else {
this.options.onUpdate(data);
}
}
/**
* Helper used to know if the given modifier is enabled.
* @method
* @memberof Popper.Utils
* @returns {Boolean}
*/
function isModifierEnabled(modifiers, modifierName) {
return modifiers.some(function (_ref) {
var name = _ref.name,
enabled = _ref.enabled;
return enabled && name === modifierName;
});
}
/**
* Get the prefixed supported property name
* @method
* @memberof Popper.Utils
* @argument {String} property (camelCase)
* @returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix)
*/
function getSupportedPropertyName(property) {
var prefixes = [false, 'ms', 'Webkit', 'Moz', 'O'];
var upperProp = property.charAt(0).toUpperCase() + property.slice(1);
for (var i = 0; i < prefixes.length; i++) {
var prefix = prefixes[i];
var toCheck = prefix ? '' + prefix + upperProp : property;
if (typeof document.body.style[toCheck] !== 'undefined') {
return toCheck;
}
}
return null;
}
/**
* Destroys the popper.
* @method
* @memberof Popper
*/
function destroy() {
this.state.isDestroyed = true;
// touch DOM only if `applyStyle` modifier is enabled
if (isModifierEnabled(this.modifiers, 'applyStyle')) {
this.popper.removeAttribute('x-placement');
this.popper.style.position = '';
this.popper.style.top = '';
this.popper.style.left = '';
this.popper.style.right = '';
this.popper.style.bottom = '';
this.popper.style.willChange = '';
this.popper.style[getSupportedPropertyName('transform')] = '';
}
this.disableEventListeners();
// remove the popper if user explicity asked for the deletion on destroy
// do not use `remove` because IE11 doesn't support it
if (this.options.removeOnDestroy) {
this.popper.parentNode.removeChild(this.popper);
}
return this;
}
/**
* Get the window associated with the element
* @argument {Element} element
* @returns {Window}
*/
function getWindow(element) {
var ownerDocument = element.ownerDocument;
return ownerDocument ? ownerDocument.defaultView : window;
}
function attachToScrollParents(scrollParent, event, callback, scrollParents) {
var isBody = scrollParent.nodeName === 'BODY';
var target = isBody ? scrollParent.ownerDocument.defaultView : scrollParent;
target.addEventListener(event, callback, { passive: true });
if (!isBody) {
attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents);
}
scrollParents.push(target);
}
/**
* Setup needed event listeners used to update the popper position
* @method
* @memberof Popper.Utils
* @private
*/
function setupEventListeners(reference, options, state, updateBound) {
// Resize event listener on window
state.updateBound = updateBound;
getWindow(reference).addEventListener('resize', state.updateBound, { passive: true });
// Scroll event listener on scroll parents
var scrollElement = getScrollParent(reference);
attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents);
state.scrollElement = scrollElement;
state.eventsEnabled = true;
return state;
}
/**
* It will add resize/scroll events and start recalculating
* position of the popper element when they are triggered.
* @method
* @memberof Popper
*/
function enableEventListeners() {
if (!this.state.eventsEnabled) {
this.state = setupEventListeners(this.reference, this.options, this.state, this.scheduleUpdate);
}
}
/**
* Remove event listeners used to update the popper position
* @method
* @memberof Popper.Utils
* @private
*/
function removeEventListeners(reference, state) {
// Remove resize event listener on window
getWindow(reference).removeEventListener('resize', state.updateBound);
// Remove scroll event listener on scroll parents
state.scrollParents.forEach(function (target) {
target.removeEventListener('scroll', state.updateBound);
});
// Reset state
state.updateBound = null;
state.scrollParents = [];
state.scrollElement = null;
state.eventsEnabled = false;
return state;
}
/**
* It will remove resize/scroll events and won't recalculate popper position
* when they are triggered. It also won't trigger `onUpdate` callback anymore,
* unless you call `update` method manually.
* @method
* @memberof Popper
*/
function disableEventListeners() {
if (this.state.eventsEnabled) {
cancelAnimationFrame(this.scheduleUpdate);
this.state = removeEventListeners(this.reference, this.state);
}
}
/**
* Tells if a given input is a number
* @method
* @memberof Popper.Utils
* @param {*} input to check
* @return {Boolean}
*/
function isNumeric(n) {
return n !== '' && !isNaN(parseFloat(n)) && isFinite(n);
}
/**
* Set the style to the given popper
* @method
* @memberof Popper.Utils
* @argument {Element} element - Element to apply the style to
* @argument {Object} styles
* Object with a list of properties and values which will be applied to the element
*/
function setStyles(element, styles) {
Object.keys(styles).forEach(function (prop) {
var unit = '';
// add unit if the value is numeric and is one of the following
if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) {
unit = 'px';
}
element.style[prop] = styles[prop] + unit;
});
}
/**
* Set the attributes to the given popper
* @method
* @memberof Popper.Utils
* @argument {Element} element - Element to apply the attributes to
* @argument {Object} styles
* Object with a list of properties and values which will be applied to the element
*/
function setAttributes(element, attributes) {
Object.keys(attributes).forEach(function (prop) {
var value = attributes[prop];
if (value !== false) {
element.setAttribute(prop, attributes[prop]);
} else {
element.removeAttribute(prop);
}
});
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} data.styles - List of style properties - values to apply to popper element
* @argument {Object} data.attributes - List of attribute properties - values to apply to popper element
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The same data object
*/
function applyStyle(data) {
// any property present in `data.styles` will be applied to the popper,
// in this way we can make the 3rd party modifiers add custom styles to it
// Be aware, modifiers could override the properties defined in the previous
// lines of this modifier!
setStyles(data.instance.popper, data.styles);
// any property present in `data.attributes` will be applied to the popper,
// they will be set as HTML attributes of the element
setAttributes(data.instance.popper, data.attributes);
// if arrowElement is defined and arrowStyles has some properties
if (data.arrowElement && Object.keys(data.arrowStyles).length) {
setStyles(data.arrowElement, data.arrowStyles);
}
return data;
}
/**
* Set the x-placement attribute before everything else because it could be used
* to add margins to the popper margins needs to be calculated to get the
* correct popper offsets.
* @method
* @memberof Popper.modifiers
* @param {HTMLElement} reference - The reference element used to position the popper
* @param {HTMLElement} popper - The HTML element used as popper
* @param {Object} options - Popper.js options
*/
function applyStyleOnLoad(reference, popper, options, modifierOptions, state) {
// compute reference element offsets
var referenceOffsets = getReferenceOffsets(state, popper, reference, options.positionFixed);
// compute auto placement, store placement inside the data object,
// modifiers will be able to edit `placement` if needed
// and refer to originalPlacement to know the original value
var placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding);
popper.setAttribute('x-placement', placement);
// Apply `position` to popper before anything else because
// without the position applied we can't guarantee correct computations
setStyles(popper, { position: options.positionFixed ? 'fixed' : 'absolute' });
return options;
}
/**
* @function
* @memberof Popper.Utils
* @argument {Object} data - The data object generated by `update` method
* @argument {Boolean} shouldRound - If the offsets should be rounded at all
* @returns {Object} The popper's position offsets rounded
*
* The tale of pixel-perfect positioning. It's still not 100% perfect, but as
* good as it can be within reason.
* Discussion here: https://github.com/FezVrasta/popper.js/pull/715
*
* Low DPI screens cause a popper to be blurry if not using full pixels (Safari
* as well on High DPI screens).
*
* Firefox prefers no rounding for positioning and does not have blurriness on
* high DPI screens.
*
* Only horizontal placement and left/right values need to be considered.
*/
function getRoundedOffsets(data, shouldRound) {
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var round = Math.round,
floor = Math.floor;
var noRound = function noRound(v) {
return v;
};
var referenceWidth = round(reference.width);
var popperWidth = round(popper.width);
var isVertical = ['left', 'right'].indexOf(data.placement) !== -1;
var isVariation = data.placement.indexOf('-') !== -1;
var sameWidthParity = referenceWidth % 2 === popperWidth % 2;
var bothOddWidth = referenceWidth % 2 === 1 && popperWidth % 2 === 1;
var horizontalToInteger = !shouldRound ? noRound : isVertical || isVariation || sameWidthParity ? round : floor;
var verticalToInteger = !shouldRound ? noRound : round;
return {
left: horizontalToInteger(bothOddWidth && !isVariation && shouldRound ? popper.left - 1 : popper.left),
top: verticalToInteger(popper.top),
bottom: verticalToInteger(popper.bottom),
right: horizontalToInteger(popper.right)
};
}
var isFirefox = isBrowser && /Firefox/i.test(navigator.userAgent);
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function computeStyle(data, options) {
var x = options.x,
y = options.y;
var popper = data.offsets.popper;
// Remove this legacy support in Popper.js v2
var legacyGpuAccelerationOption = find(data.instance.modifiers, function (modifier) {
return modifier.name === 'applyStyle';
}).gpuAcceleration;
if (legacyGpuAccelerationOption !== undefined) {
console.warn('WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!');
}
var gpuAcceleration = legacyGpuAccelerationOption !== undefined ? legacyGpuAccelerationOption : options.gpuAcceleration;
var offsetParent = getOffsetParent(data.instance.popper);
var offsetParentRect = getBoundingClientRect(offsetParent);
// Styles
var styles = {
position: popper.position
};
var offsets = getRoundedOffsets(data, window.devicePixelRatio < 2 || !isFirefox);
var sideA = x === 'bottom' ? 'top' : 'bottom';
var sideB = y === 'right' ? 'left' : 'right';
// if gpuAcceleration is set to `true` and transform is supported,
// we use `translate3d` to apply the position to the popper we
// automatically use the supported prefixed version if needed
var prefixedProperty = getSupportedPropertyName('transform');
// now, let's make a step back and look at this code closely (wtf?)
// If the content of the popper grows once it's been positioned, it
// may happen that the popper gets misplaced because of the new content
// overflowing its reference element
// To avoid this problem, we provide two options (x and y), which allow
// the consumer to define the offset origin.
// If we position a popper on top of a reference element, we can set
// `x` to `top` to make the popper grow towards its top instead of
// its bottom.
var left = void 0,
top = void 0;
if (sideA === 'bottom') {
// when offsetParent is the positioning is relative to the bottom of the screen (excluding the scrollbar)
// and not the bottom of the html element
if (offsetParent.nodeName === 'HTML') {
top = -offsetParent.clientHeight + offsets.bottom;
} else {
top = -offsetParentRect.height + offsets.bottom;
}
} else {
top = offsets.top;
}
if (sideB === 'right') {
if (offsetParent.nodeName === 'HTML') {
left = -offsetParent.clientWidth + offsets.right;
} else {
left = -offsetParentRect.width + offsets.right;
}
} else {
left = offsets.left;
}
if (gpuAcceleration && prefixedProperty) {
styles[prefixedProperty] = 'translate3d(' + left + 'px, ' + top + 'px, 0)';
styles[sideA] = 0;
styles[sideB] = 0;
styles.willChange = 'transform';
} else {
// othwerise, we use the standard `top`, `left`, `bottom` and `right` properties
var invertTop = sideA === 'bottom' ? -1 : 1;
var invertLeft = sideB === 'right' ? -1 : 1;
styles[sideA] = top * invertTop;
styles[sideB] = left * invertLeft;
styles.willChange = sideA + ', ' + sideB;
}
// Attributes
var attributes = {
'x-placement': data.placement
};
// Update `data` attributes, styles and arrowStyles
data.attributes = _extends$1({}, attributes, data.attributes);
data.styles = _extends$1({}, styles, data.styles);
data.arrowStyles = _extends$1({}, data.offsets.arrow, data.arrowStyles);
return data;
}
/**
* Helper used to know if the given modifier depends from another one.
* It checks if the needed modifier is listed and enabled.
* @method
* @memberof Popper.Utils
* @param {Array} modifiers - list of modifiers
* @param {String} requestingName - name of requesting modifier
* @param {String} requestedName - name of requested modifier
* @returns {Boolean}
*/
function isModifierRequired(modifiers, requestingName, requestedName) {
var requesting = find(modifiers, function (_ref) {
var name = _ref.name;
return name === requestingName;
});
var isRequired = !!requesting && modifiers.some(function (modifier) {
return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order;
});
if (!isRequired) {
var _requesting = '`' + requestingName + '`';
var requested = '`' + requestedName + '`';
console.warn(requested + ' modifier is required by ' + _requesting + ' modifier in order to work, be sure to include it before ' + _requesting + '!');
}
return isRequired;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function arrow(data, options) {
var _data$offsets$arrow;
// arrow depends on keepTogether in order to work
if (!isModifierRequired(data.instance.modifiers, 'arrow', 'keepTogether')) {
return data;
}
var arrowElement = options.element;
// if arrowElement is a string, suppose it's a CSS selector
if (typeof arrowElement === 'string') {
arrowElement = data.instance.popper.querySelector(arrowElement);
// if arrowElement is not found, don't run the modifier
if (!arrowElement) {
return data;
}
} else {
// if the arrowElement isn't a query selector we must check that the
// provided DOM node is child of its popper node
if (!data.instance.popper.contains(arrowElement)) {
console.warn('WARNING: `arrow.element` must be child of its popper element!');
return data;
}
}
var placement = data.placement.split('-')[0];
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var isVertical = ['left', 'right'].indexOf(placement) !== -1;
var len = isVertical ? 'height' : 'width';
var sideCapitalized = isVertical ? 'Top' : 'Left';
var side = sideCapitalized.toLowerCase();
var altSide = isVertical ? 'left' : 'top';
var opSide = isVertical ? 'bottom' : 'right';
var arrowElementSize = getOuterSizes(arrowElement)[len];
//
// extends keepTogether behavior making sure the popper and its
// reference have enough pixels in conjunction
//
// top/left side
if (reference[opSide] - arrowElementSize < popper[side]) {
data.offsets.popper[side] -= popper[side] - (reference[opSide] - arrowElementSize);
}
// bottom/right side
if (reference[side] + arrowElementSize > popper[opSide]) {
data.offsets.popper[side] += reference[side] + arrowElementSize - popper[opSide];
}
data.offsets.popper = getClientRect(data.offsets.popper);
// compute center of the popper
var center = reference[side] + reference[len] / 2 - arrowElementSize / 2;
// Compute the sideValue using the updated popper offsets
// take popper margin in account because we don't have this info available
var css = getStyleComputedProperty(data.instance.popper);
var popperMarginSide = parseFloat(css['margin' + sideCapitalized], 10);
var popperBorderSide = parseFloat(css['border' + sideCapitalized + 'Width'], 10);
var sideValue = center - data.offsets.popper[side] - popperMarginSide - popperBorderSide;
// prevent arrowElement from being placed not contiguously to its popper
sideValue = Math.max(Math.min(popper[len] - arrowElementSize, sideValue), 0);
data.arrowElement = arrowElement;
data.offsets.arrow = (_data$offsets$arrow = {}, defineProperty$1(_data$offsets$arrow, side, Math.round(sideValue)), defineProperty$1(_data$offsets$arrow, altSide, ''), _data$offsets$arrow);
return data;
}
/**
* Get the opposite placement variation of the given one
* @method
* @memberof Popper.Utils
* @argument {String} placement variation
* @returns {String} flipped placement variation
*/
function getOppositeVariation(variation) {
if (variation === 'end') {
return 'start';
} else if (variation === 'start') {
return 'end';
}
return variation;
}
/**
* List of accepted placements to use as values of the `placement` option.
* Valid placements are:
* - `auto`
* - `top`
* - `right`
* - `bottom`
* - `left`
*
* Each placement can have a variation from this list:
* - `-start`
* - `-end`
*
* Variations are interpreted easily if you think of them as the left to right
* written languages. Horizontally (`top` and `bottom`), `start` is left and `end`
* is right.
* Vertically (`left` and `right`), `start` is top and `end` is bottom.
*
* Some valid examples are:
* - `top-end` (on top of reference, right aligned)
* - `right-start` (on right of reference, top aligned)
* - `bottom` (on bottom, centered)
* - `auto-end` (on the side with more space available, alignment depends by placement)
*
* @static
* @type {Array}
* @enum {String}
* @readonly
* @method placements
* @memberof Popper
*/
var placements = ['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start'];
// Get rid of `auto` `auto-start` and `auto-end`
var validPlacements = placements.slice(3);
/**
* Given an initial placement, returns all the subsequent placements
* clockwise (or counter-clockwise).
*
* @method
* @memberof Popper.Utils
* @argument {String} placement - A valid placement (it accepts variations)
* @argument {Boolean} counter - Set to true to walk the placements counterclockwise
* @returns {Array} placements including their variations
*/
function clockwise(placement) {
var counter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var index = validPlacements.indexOf(placement);
var arr = validPlacements.slice(index + 1).concat(validPlacements.slice(0, index));
return counter ? arr.reverse() : arr;
}
var BEHAVIORS = {
FLIP: 'flip',
CLOCKWISE: 'clockwise',
COUNTERCLOCKWISE: 'counterclockwise'
};
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function flip(data, options) {
// if `inner` modifier is enabled, we can't use the `flip` modifier
if (isModifierEnabled(data.instance.modifiers, 'inner')) {
return data;
}
if (data.flipped && data.placement === data.originalPlacement) {
// seems like flip is trying to loop, probably there's not enough space on any of the flippable sides
return data;
}
var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, options.boundariesElement, data.positionFixed);
var placement = data.placement.split('-')[0];
var placementOpposite = getOppositePlacement(placement);
var variation = data.placement.split('-')[1] || '';
var flipOrder = [];
switch (options.behavior) {
case BEHAVIORS.FLIP:
flipOrder = [placement, placementOpposite];
break;
case BEHAVIORS.CLOCKWISE:
flipOrder = clockwise(placement);
break;
case BEHAVIORS.COUNTERCLOCKWISE:
flipOrder = clockwise(placement, true);
break;
default:
flipOrder = options.behavior;
}
flipOrder.forEach(function (step, index) {
if (placement !== step || flipOrder.length === index + 1) {
return data;
}
placement = data.placement.split('-')[0];
placementOpposite = getOppositePlacement(placement);
var popperOffsets = data.offsets.popper;
var refOffsets = data.offsets.reference;
// using floor because the reference offsets may contain decimals we are not going to consider here
var floor = Math.floor;
var overlapsRef = placement === 'left' && floor(popperOffsets.right) > floor(refOffsets.left) || placement === 'right' && floor(popperOffsets.left) < floor(refOffsets.right) || placement === 'top' && floor(popperOffsets.bottom) > floor(refOffsets.top) || placement === 'bottom' && floor(popperOffsets.top) < floor(refOffsets.bottom);
var overflowsLeft = floor(popperOffsets.left) < floor(boundaries.left);
var overflowsRight = floor(popperOffsets.right) > floor(boundaries.right);
var overflowsTop = floor(popperOffsets.top) < floor(boundaries.top);
var overflowsBottom = floor(popperOffsets.bottom) > floor(boundaries.bottom);
var overflowsBoundaries = placement === 'left' && overflowsLeft || placement === 'right' && overflowsRight || placement === 'top' && overflowsTop || placement === 'bottom' && overflowsBottom;
// flip the variation if required
var isVertical = ['top', 'bottom'].indexOf(placement) !== -1;
var flippedVariation = !!options.flipVariations && (isVertical && variation === 'start' && overflowsLeft || isVertical && variation === 'end' && overflowsRight || !isVertical && variation === 'start' && overflowsTop || !isVertical && variation === 'end' && overflowsBottom);
if (overlapsRef || overflowsBoundaries || flippedVariation) {
// this boolean to detect any flip loop
data.flipped = true;
if (overlapsRef || overflowsBoundaries) {
placement = flipOrder[index + 1];
}
if (flippedVariation) {
variation = getOppositeVariation(variation);
}
data.placement = placement + (variation ? '-' + variation : '');
// this object contains `position`, we want to preserve it along with
// any additional property we may add in the future
data.offsets.popper = _extends$1({}, data.offsets.popper, getPopperOffsets(data.instance.popper, data.offsets.reference, data.placement));
data = runModifiers(data.instance.modifiers, data, 'flip');
}
});
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function keepTogether(data) {
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var placement = data.placement.split('-')[0];
var floor = Math.floor;
var isVertical = ['top', 'bottom'].indexOf(placement) !== -1;
var side = isVertical ? 'right' : 'bottom';
var opSide = isVertical ? 'left' : 'top';
var measurement = isVertical ? 'width' : 'height';
if (popper[side] < floor(reference[opSide])) {
data.offsets.popper[opSide] = floor(reference[opSide]) - popper[measurement];
}
if (popper[opSide] > floor(reference[side])) {
data.offsets.popper[opSide] = floor(reference[side]);
}
return data;
}
/**
* Converts a string containing value + unit into a px value number
* @function
* @memberof {modifiers~offset}
* @private
* @argument {String} str - Value + unit string
* @argument {String} measurement - `height` or `width`
* @argument {Object} popperOffsets
* @argument {Object} referenceOffsets
* @returns {Number|String}
* Value in pixels, or original string if no values were extracted
*/
function toValue(str, measurement, popperOffsets, referenceOffsets) {
// separate value from unit
var split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/);
var value = +split[1];
var unit = split[2];
// If it's not a number it's an operator, I guess
if (!value) {
return str;
}
if (unit.indexOf('%') === 0) {
var element = void 0;
switch (unit) {
case '%p':
element = popperOffsets;
break;
case '%':
case '%r':
default:
element = referenceOffsets;
}
var rect = getClientRect(element);
return rect[measurement] / 100 * value;
} else if (unit === 'vh' || unit === 'vw') {
// if is a vh or vw, we calculate the size based on the viewport
var size = void 0;
if (unit === 'vh') {
size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
} else {
size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
}
return size / 100 * value;
} else {
// if is an explicit pixel unit, we get rid of the unit and keep the value
// if is an implicit unit, it's px, and we return just the value
return value;
}
}
/**
* Parse an `offset` string to extrapolate `x` and `y` numeric offsets.
* @function
* @memberof {modifiers~offset}
* @private
* @argument {String} offset
* @argument {Object} popperOffsets
* @argument {Object} referenceOffsets
* @argument {String} basePlacement
* @returns {Array} a two cells array with x and y offsets in numbers
*/
function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) {
var offsets = [0, 0];
// Use height if placement is left or right and index is 0 otherwise use width
// in this way the first offset will use an axis and the second one
// will use the other one
var useHeight = ['right', 'left'].indexOf(basePlacement) !== -1;
// Split the offset string to obtain a list of values and operands
// The regex addresses values with the plus or minus sign in front (+10, -20, etc)
var fragments = offset.split(/(\+|\-)/).map(function (frag) {
return frag.trim();
});
// Detect if the offset string contains a pair of values or a single one
// they could be separated by comma or space
var divider = fragments.indexOf(find(fragments, function (frag) {
return frag.search(/,|\s/) !== -1;
}));
if (fragments[divider] && fragments[divider].indexOf(',') === -1) {
console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.');
}
// If divider is found, we divide the list of values and operands to divide
// them by ofset X and Y.
var splitRegex = /\s*,\s*|\s+/;
var ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments];
// Convert the values with units to absolute pixels to allow our computations
ops = ops.map(function (op, index) {
// Most of the units rely on the orientation of the popper
var measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width';
var mergeWithPrevious = false;
return op
// This aggregates any `+` or `-` sign that aren't considered operators
// e.g.: 10 + +5 => [10, +, +5]
.reduce(function (a, b) {
if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) {
a[a.length - 1] = b;
mergeWithPrevious = true;
return a;
} else if (mergeWithPrevious) {
a[a.length - 1] += b;
mergeWithPrevious = false;
return a;
} else {
return a.concat(b);
}
}, [])
// Here we convert the string values into number values (in px)
.map(function (str) {
return toValue(str, measurement, popperOffsets, referenceOffsets);
});
});
// Loop trough the offsets arrays and execute the operations
ops.forEach(function (op, index) {
op.forEach(function (frag, index2) {
if (isNumeric(frag)) {
offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1);
}
});
});
return offsets;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @argument {Number|String} options.offset=0
* The offset value as described in the modifier description
* @returns {Object} The data object, properly modified
*/
function offset(data, _ref) {
var offset = _ref.offset;
var placement = data.placement,
_data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var basePlacement = placement.split('-')[0];
var offsets = void 0;
if (isNumeric(+offset)) {
offsets = [+offset, 0];
} else {
offsets = parseOffset(offset, popper, reference, basePlacement);
}
if (basePlacement === 'left') {
popper.top += offsets[0];
popper.left -= offsets[1];
} else if (basePlacement === 'right') {
popper.top += offsets[0];
popper.left += offsets[1];
} else if (basePlacement === 'top') {
popper.left += offsets[0];
popper.top -= offsets[1];
} else if (basePlacement === 'bottom') {
popper.left += offsets[0];
popper.top += offsets[1];
}
data.popper = popper;
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function preventOverflow(data, options) {
var boundariesElement = options.boundariesElement || getOffsetParent(data.instance.popper);
// If offsetParent is the reference element, we really want to
// go one step up and use the next offsetParent as reference to
// avoid to make this modifier completely useless and look like broken
if (data.instance.reference === boundariesElement) {
boundariesElement = getOffsetParent(boundariesElement);
}
// NOTE: DOM access here
// resets the popper's position so that the document size can be calculated excluding
// the size of the popper element itself
var transformProp = getSupportedPropertyName('transform');
var popperStyles = data.instance.popper.style; // assignment to help minification
var top = popperStyles.top,
left = popperStyles.left,
transform = popperStyles[transformProp];
popperStyles.top = '';
popperStyles.left = '';
popperStyles[transformProp] = '';
var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, boundariesElement, data.positionFixed);
// NOTE: DOM access here
// restores the original style properties after the offsets have been computed
popperStyles.top = top;
popperStyles.left = left;
popperStyles[transformProp] = transform;
options.boundaries = boundaries;
var order = options.priority;
var popper = data.offsets.popper;
var check = {
primary: function primary(placement) {
var value = popper[placement];
if (popper[placement] < boundaries[placement] && !options.escapeWithReference) {
value = Math.max(popper[placement], boundaries[placement]);
}
return defineProperty$1({}, placement, value);
},
secondary: function secondary(placement) {
var mainSide = placement === 'right' ? 'left' : 'top';
var value = popper[mainSide];
if (popper[placement] > boundaries[placement] && !options.escapeWithReference) {
value = Math.min(popper[mainSide], boundaries[placement] - (placement === 'right' ? popper.width : popper.height));
}
return defineProperty$1({}, mainSide, value);
}
};
order.forEach(function (placement) {
var side = ['left', 'top'].indexOf(placement) !== -1 ? 'primary' : 'secondary';
popper = _extends$1({}, popper, check[side](placement));
});
data.offsets.popper = popper;
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function shift(data) {
var placement = data.placement;
var basePlacement = placement.split('-')[0];
var shiftvariation = placement.split('-')[1];
// if shift shiftvariation is specified, run the modifier
if (shiftvariation) {
var _data$offsets = data.offsets,
reference = _data$offsets.reference,
popper = _data$offsets.popper;
var isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1;
var side = isVertical ? 'left' : 'top';
var measurement = isVertical ? 'width' : 'height';
var shiftOffsets = {
start: defineProperty$1({}, side, reference[side]),
end: defineProperty$1({}, side, reference[side] + reference[measurement] - popper[measurement])
};
data.offsets.popper = _extends$1({}, popper, shiftOffsets[shiftvariation]);
}
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function hide(data) {
if (!isModifierRequired(data.instance.modifiers, 'hide', 'preventOverflow')) {
return data;
}
var refRect = data.offsets.reference;
var bound = find(data.instance.modifiers, function (modifier) {
return modifier.name === 'preventOverflow';
}).boundaries;
if (refRect.bottom < bound.top || refRect.left > bound.right || refRect.top > bound.bottom || refRect.right < bound.left) {
// Avoid unnecessary DOM access if visibility hasn't changed
if (data.hide === true) {
return data;
}
data.hide = true;
data.attributes['x-out-of-boundaries'] = '';
} else {
// Avoid unnecessary DOM access if visibility hasn't changed
if (data.hide === false) {
return data;
}
data.hide = false;
data.attributes['x-out-of-boundaries'] = false;
}
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function inner(data) {
var placement = data.placement;
var basePlacement = placement.split('-')[0];
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var isHoriz = ['left', 'right'].indexOf(basePlacement) !== -1;
var subtractLength = ['top', 'left'].indexOf(basePlacement) === -1;
popper[isHoriz ? 'left' : 'top'] = reference[basePlacement] - (subtractLength ? popper[isHoriz ? 'width' : 'height'] : 0);
data.placement = getOppositePlacement(placement);
data.offsets.popper = getClientRect(popper);
return data;
}
/**
* Modifier function, each modifier can have a function of this type assigned
* to its `fn` property.
* These functions will be called on each update, this means that you must
* make sure they are performant enough to avoid performance bottlenecks.
*
* @function ModifierFn
* @argument {dataObject} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {dataObject} The data object, properly modified
*/
/**
* Modifiers are plugins used to alter the behavior of your poppers.
* Popper.js uses a set of 9 modifiers to provide all the basic functionalities
* needed by the library.
*
* Usually you don't want to override the `order`, `fn` and `onLoad` props.
* All the other properties are configurations that could be tweaked.
* @namespace modifiers
*/
var modifiers = {
/**
* Modifier used to shift the popper on the start or end of its reference
* element.
* It will read the variation of the `placement` property.
* It can be one either `-end` or `-start`.
* @memberof modifiers
* @inner
*/
shift: {
/** @prop {number} order=100 - Index used to define the order of execution */
order: 100,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: shift
},
/**
* The `offset` modifier can shift your popper on both its axis.
*
* It accepts the following units:
* - `px` or unit-less, interpreted as pixels
* - `%` or `%r`, percentage relative to the length of the reference element
* - `%p`, percentage relative to the length of the popper element
* - `vw`, CSS viewport width unit
* - `vh`, CSS viewport height unit
*
* For length is intended the main axis relative to the placement of the popper.
* This means that if the placement is `top` or `bottom`, the length will be the
* `width`. In case of `left` or `right`, it will be the `height`.
*
* You can provide a single value (as `Number` or `String`), or a pair of values
* as `String` divided by a comma or one (or more) white spaces.
* The latter is a deprecated method because it leads to confusion and will be
* removed in v2.
* Additionally, it accepts additions and subtractions between different units.
* Note that multiplications and divisions aren't supported.
*
* Valid examples are:
* ```
* 10
* '10%'
* '10, 10'
* '10%, 10'
* '10 + 10%'
* '10 - 5vh + 3%'
* '-10px + 5vh, 5px - 6%'
* ```
* > **NB**: If you desire to apply offsets to your poppers in a way that may make them overlap
* > with their reference element, unfortunately, you will have to disable the `flip` modifier.
* > You can read more on this at this [issue](https://github.com/FezVrasta/popper.js/issues/373).
*
* @memberof modifiers
* @inner
*/
offset: {
/** @prop {number} order=200 - Index used to define the order of execution */
order: 200,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: offset,
/** @prop {Number|String} offset=0
* The offset value as described in the modifier description
*/
offset: 0
},
/**
* Modifier used to prevent the popper from being positioned outside the boundary.
*
* A scenario exists where the reference itself is not within the boundaries.
* We can say it has "escaped the boundaries" — or just "escaped".
* In this case we need to decide whether the popper should either:
*
* - detach from the reference and remain "trapped" in the boundaries, or
* - if it should ignore the boundary and "escape with its reference"
*
* When `escapeWithReference` is set to`true` and reference is completely
* outside its boundaries, the popper will overflow (or completely leave)
* the boundaries in order to remain attached to the edge of the reference.
*
* @memberof modifiers
* @inner
*/
preventOverflow: {
/** @prop {number} order=300 - Index used to define the order of execution */
order: 300,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: preventOverflow,
/**
* @prop {Array} [priority=['left','right','top','bottom']]
* Popper will try to prevent overflow following these priorities by default,
* then, it could overflow on the left and on top of the `boundariesElement`
*/
priority: ['left', 'right', 'top', 'bottom'],
/**
* @prop {number} padding=5
* Amount of pixel used to define a minimum distance between the boundaries
* and the popper. This makes sure the popper always has a little padding
* between the edges of its container
*/
padding: 5,
/**
* @prop {String|HTMLElement} boundariesElement='scrollParent'
* Boundaries used by the modifier. Can be `scrollParent`, `window`,
* `viewport` or any DOM element.
*/
boundariesElement: 'scrollParent'
},
/**
* Modifier used to make sure the reference and its popper stay near each other
* without leaving any gap between the two. Especially useful when the arrow is
* enabled and you want to ensure that it points to its reference element.
* It cares only about the first axis. You can still have poppers with margin
* between the popper and its reference element.
* @memberof modifiers
* @inner
*/
keepTogether: {
/** @prop {number} order=400 - Index used to define the order of execution */
order: 400,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: keepTogether
},
/**
* This modifier is used to move the `arrowElement` of the popper to make
* sure it is positioned between the reference element and its popper element.
* It will read the outer size of the `arrowElement` node to detect how many
* pixels of conjunction are needed.
*
* It has no effect if no `arrowElement` is provided.
* @memberof modifiers
* @inner
*/
arrow: {
/** @prop {number} order=500 - Index used to define the order of execution */
order: 500,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: arrow,
/** @prop {String|HTMLElement} element='[x-arrow]' - Selector or node used as arrow */
element: '[x-arrow]'
},
/**
* Modifier used to flip the popper's placement when it starts to overlap its
* reference element.
*
* Requires the `preventOverflow` modifier before it in order to work.
*
* **NOTE:** this modifier will interrupt the current update cycle and will
* restart it if it detects the need to flip the placement.
* @memberof modifiers
* @inner
*/
flip: {
/** @prop {number} order=600 - Index used to define the order of execution */
order: 600,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: flip,
/**
* @prop {String|Array} behavior='flip'
* The behavior used to change the popper's placement. It can be one of
* `flip`, `clockwise`, `counterclockwise` or an array with a list of valid
* placements (with optional variations)
*/
behavior: 'flip',
/**
* @prop {number} padding=5
* The popper will flip if it hits the edges of the `boundariesElement`
*/
padding: 5,
/**
* @prop {String|HTMLElement} boundariesElement='viewport'
* The element which will define the boundaries of the popper position.
* The popper will never be placed outside of the defined boundaries
* (except if `keepTogether` is enabled)
*/
boundariesElement: 'viewport'
},
/**
* Modifier used to make the popper flow toward the inner of the reference element.
* By default, when this modifier is disabled, the popper will be placed outside
* the reference element.
* @memberof modifiers
* @inner
*/
inner: {
/** @prop {number} order=700 - Index used to define the order of execution */
order: 700,
/** @prop {Boolean} enabled=false - Whether the modifier is enabled or not */
enabled: false,
/** @prop {ModifierFn} */
fn: inner
},
/**
* Modifier used to hide the popper when its reference element is outside of the
* popper boundaries. It will set a `x-out-of-boundaries` attribute which can
* be used to hide with a CSS selector the popper when its reference is
* out of boundaries.
*
* Requires the `preventOverflow` modifier before it in order to work.
* @memberof modifiers
* @inner
*/
hide: {
/** @prop {number} order=800 - Index used to define the order of execution */
order: 800,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: hide
},
/**
* Computes the style that will be applied to the popper element to gets
* properly positioned.
*
* Note that this modifier will not touch the DOM, it just prepares the styles
* so that `applyStyle` modifier can apply it. This separation is useful
* in case you need to replace `applyStyle` with a custom implementation.
*
* This modifier has `850` as `order` value to maintain backward compatibility
* with previous versions of Popper.js. Expect the modifiers ordering method
* to change in future major versions of the library.
*
* @memberof modifiers
* @inner
*/
computeStyle: {
/** @prop {number} order=850 - Index used to define the order of execution */
order: 850,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: computeStyle,
/**
* @prop {Boolean} gpuAcceleration=true
* If true, it uses the CSS 3D transformation to position the popper.
* Otherwise, it will use the `top` and `left` properties
*/
gpuAcceleration: true,
/**
* @prop {string} [x='bottom']
* Where to anchor the X axis (`bottom` or `top`). AKA X offset origin.
* Change this if your popper should grow in a direction different from `bottom`
*/
x: 'bottom',
/**
* @prop {string} [x='left']
* Where to anchor the Y axis (`left` or `right`). AKA Y offset origin.
* Change this if your popper should grow in a direction different from `right`
*/
y: 'right'
},
/**
* Applies the computed styles to the popper element.
*
* All the DOM manipulations are limited to this modifier. This is useful in case
* you want to integrate Popper.js inside a framework or view library and you
* want to delegate all the DOM manipulations to it.
*
* Note that if you disable this modifier, you must make sure the popper element
* has its position set to `absolute` before Popper.js can do its work!
*
* Just disable this modifier and define your own to achieve the desired effect.
*
* @memberof modifiers
* @inner
*/
applyStyle: {
/** @prop {number} order=900 - Index used to define the order of execution */
order: 900,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: applyStyle,
/** @prop {Function} */
onLoad: applyStyleOnLoad,
/**
* @deprecated since version 1.10.0, the property moved to `computeStyle` modifier
* @prop {Boolean} gpuAcceleration=true
* If true, it uses the CSS 3D transformation to position the popper.
* Otherwise, it will use the `top` and `left` properties
*/
gpuAcceleration: undefined
}
};
/**
* The `dataObject` is an object containing all the information used by Popper.js.
* This object is passed to modifiers and to the `onCreate` and `onUpdate` callbacks.
* @name dataObject
* @property {Object} data.instance The Popper.js instance
* @property {String} data.placement Placement applied to popper
* @property {String} data.originalPlacement Placement originally defined on init
* @property {Boolean} data.flipped True if popper has been flipped by flip modifier
* @property {Boolean} data.hide True if the reference element is out of boundaries, useful to know when to hide the popper
* @property {HTMLElement} data.arrowElement Node used as arrow by arrow modifier
* @property {Object} data.styles Any CSS property defined here will be applied to the popper. It expects the JavaScript nomenclature (eg. `marginBottom`)
* @property {Object} data.arrowStyles Any CSS property defined here will be applied to the popper arrow. It expects the JavaScript nomenclature (eg. `marginBottom`)
* @property {Object} data.boundaries Offsets of the popper boundaries
* @property {Object} data.offsets The measurements of popper, reference and arrow elements
* @property {Object} data.offsets.popper `top`, `left`, `width`, `height` values
* @property {Object} data.offsets.reference `top`, `left`, `width`, `height` values
* @property {Object} data.offsets.arrow] `top` and `left` offsets, only one of them will be different from 0
*/
/**
* Default options provided to Popper.js constructor.
* These can be overridden using the `options` argument of Popper.js.
* To override an option, simply pass an object with the same
* structure of the `options` object, as the 3rd argument. For example:
* ```
* new Popper(ref, pop, {
* modifiers: {
* preventOverflow: { enabled: false }
* }
* })
* ```
* @type {Object}
* @static
* @memberof Popper
*/
var Defaults = {
/**
* Popper's placement.
* @prop {Popper.placements} placement='bottom'
*/
placement: 'bottom',
/**
* Set this to true if you want popper to position it self in 'fixed' mode
* @prop {Boolean} positionFixed=false
*/
positionFixed: false,
/**
* Whether events (resize, scroll) are initially enabled.
* @prop {Boolean} eventsEnabled=true
*/
eventsEnabled: true,
/**
* Set to true if you want to automatically remove the popper when
* you call the `destroy` method.
* @prop {Boolean} removeOnDestroy=false
*/
removeOnDestroy: false,
/**
* Callback called when the popper is created.
* By default, it is set to no-op.
* Access Popper.js instance with `data.instance`.
* @prop {onCreate}
*/
onCreate: function onCreate() {},
/**
* Callback called when the popper is updated. This callback is not called
* on the initialization/creation of the popper, but only on subsequent
* updates.
* By default, it is set to no-op.
* Access Popper.js instance with `data.instance`.
* @prop {onUpdate}
*/
onUpdate: function onUpdate() {},
/**
* List of modifiers used to modify the offsets before they are applied to the popper.
* They provide most of the functionalities of Popper.js.
* @prop {modifiers}
*/
modifiers: modifiers
};
/**
* @callback onCreate
* @param {dataObject} data
*/
/**
* @callback onUpdate
* @param {dataObject} data
*/
// Utils
// Methods
var Popper = function () {
/**
* Creates a new Popper.js instance.
* @class Popper
* @param {HTMLElement|referenceObject} reference - The reference element used to position the popper
* @param {HTMLElement} popper - The HTML element used as the popper
* @param {Object} options - Your custom options to override the ones defined in [Defaults](#defaults)
* @return {Object} instance - The generated Popper.js instance
*/
function Popper(reference, popper) {
var _this = this;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
classCallCheck(this, Popper);
this.scheduleUpdate = function () {
return requestAnimationFrame(_this.update);
};
// make update() debounced, so that it only runs at most once-per-tick
this.update = debounce$1(this.update.bind(this));
// with {} we create a new object with the options inside it
this.options = _extends$1({}, Popper.Defaults, options);
// init state
this.state = {
isDestroyed: false,
isCreated: false,
scrollParents: []
};
// get reference and popper elements (allow jQuery wrappers)
this.reference = reference && reference.jquery ? reference[0] : reference;
this.popper = popper && popper.jquery ? popper[0] : popper;
// Deep merge modifiers options
this.options.modifiers = {};
Object.keys(_extends$1({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) {
_this.options.modifiers[name] = _extends$1({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {});
});
// Refactoring modifiers' list (Object => Array)
this.modifiers = Object.keys(this.options.modifiers).map(function (name) {
return _extends$1({
name: name
}, _this.options.modifiers[name]);
})
// sort the modifiers by order
.sort(function (a, b) {
return a.order - b.order;
});
// modifiers have the ability to execute arbitrary code when Popper.js get inited
// such code is executed in the same order of its modifier
// they could add new properties to their options configuration
// BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`!
this.modifiers.forEach(function (modifierOptions) {
if (modifierOptions.enabled && isFunction$1(modifierOptions.onLoad)) {
modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state);
}
});
// fire the first update to position the popper in the right place
this.update();
var eventsEnabled = this.options.eventsEnabled;
if (eventsEnabled) {
// setup event listeners, they will take care of update the position in specific situations
this.enableEventListeners();
}
this.state.eventsEnabled = eventsEnabled;
}
// We can't use class properties because they don't get listed in the
// class prototype and break stuff like Sinon stubs
createClass(Popper, [{
key: 'update',
value: function update$$1() {
return update.call(this);
}
}, {
key: 'destroy',
value: function destroy$$1() {
return destroy.call(this);
}
}, {
key: 'enableEventListeners',
value: function enableEventListeners$$1() {
return enableEventListeners.call(this);
}
}, {
key: 'disableEventListeners',
value: function disableEventListeners$$1() {
return disableEventListeners.call(this);
}
/**
* Schedules an update. It will run on the next UI update available.
* @method scheduleUpdate
* @memberof Popper
*/
/**
* Collection of utilities useful when writing custom modifiers.
* Starting from version 1.7, this method is available only if you
* include `popper-utils.js` before `popper.js`.
*
* **DEPRECATION**: This way to access PopperUtils is deprecated
* and will be removed in v2! Use the PopperUtils module directly instead.
* Due to the high instability of the methods contained in Utils, we can't
* guarantee them to follow semver. Use them at your own risk!
* @static
* @private
* @type {Object}
* @deprecated since version 1.8
* @member Utils
* @memberof Popper
*/
}]);
return Popper;
}();
/**
* The `referenceObject` is an object that provides an interface compatible with Popper.js
* and lets you use it as replacement of a real DOM node.
* You can use this method to position a popper relatively to a set of coordinates
* in case you don't have a DOM node to use as reference.
*
* ```
* new Popper(referenceObject, popperNode);
* ```
*
* NB: This feature isn't supported in Internet Explorer 10.
* @name referenceObject
* @property {Function} data.getBoundingClientRect
* A function that returns a set of coordinates compatible with the native `getBoundingClientRect` method.
* @property {number} data.clientWidth
* An ES6 getter that will return the width of the virtual reference element.
* @property {number} data.clientHeight
* An ES6 getter that will return the height of the virtual reference element.
*/
Popper.Utils = (typeof window !== 'undefined' ? window : global).PopperUtils;
Popper.placements = placements;
Popper.Defaults = Defaults;
var key = '__global_unique_id__';
var gud = function() {
return commonjsGlobal[key] = (commonjsGlobal[key] || 0) + 1;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
var emptyFunction_1 = emptyFunction;
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning$1 = emptyFunction_1;
{
var printWarning$3 = function printWarning(format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
warning$1 = function warning(condition, format) {
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning$3.apply(undefined, [format].concat(args));
}
};
}
var warning_1$1 = warning$1;
var implementation = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
var _react2 = _interopRequireDefault(React__default);
var _propTypes2 = _interopRequireDefault(propTypes);
var _gud2 = _interopRequireDefault(gud);
var _warning2 = _interopRequireDefault(warning_1$1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var MAX_SIGNED_31_BIT_INT = 1073741823;
// Inlined Object.is polyfill.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
function objectIs(x, y) {
if (x === y) {
return x !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
function createEventEmitter(value) {
var handlers = [];
return {
on: function on(handler) {
handlers.push(handler);
},
off: function off(handler) {
handlers = handlers.filter(function (h) {
return h !== handler;
});
},
get: function get() {
return value;
},
set: function set(newValue, changedBits) {
value = newValue;
handlers.forEach(function (handler) {
return handler(value, changedBits);
});
}
};
}
function onlyChild(children) {
return Array.isArray(children) ? children[0] : children;
}
function createReactContext(defaultValue, calculateChangedBits) {
var _Provider$childContex, _Consumer$contextType;
var contextProp = '__create-react-context-' + (0, _gud2.default)() + '__';
var Provider = function (_Component) {
_inherits(Provider, _Component);
function Provider() {
var _temp, _this, _ret;
_classCallCheck(this, Provider);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.emitter = createEventEmitter(_this.props.value), _temp), _possibleConstructorReturn(_this, _ret);
}
Provider.prototype.getChildContext = function getChildContext() {
var _ref;
return _ref = {}, _ref[contextProp] = this.emitter, _ref;
};
Provider.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.props.value !== nextProps.value) {
var oldValue = this.props.value;
var newValue = nextProps.value;
var changedBits = void 0;
if (objectIs(oldValue, newValue)) {
changedBits = 0; // No change
} else {
changedBits = typeof calculateChangedBits === 'function' ? calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;
{
(0, _warning2.default)((changedBits & MAX_SIGNED_31_BIT_INT) === changedBits, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits);
}
changedBits |= 0;
if (changedBits !== 0) {
this.emitter.set(nextProps.value, changedBits);
}
}
}
};
Provider.prototype.render = function render() {
return this.props.children;
};
return Provider;
}(React__default.Component);
Provider.childContextTypes = (_Provider$childContex = {}, _Provider$childContex[contextProp] = _propTypes2.default.object.isRequired, _Provider$childContex);
var Consumer = function (_Component2) {
_inherits(Consumer, _Component2);
function Consumer() {
var _temp2, _this2, _ret2;
_classCallCheck(this, Consumer);
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return _ret2 = (_temp2 = (_this2 = _possibleConstructorReturn(this, _Component2.call.apply(_Component2, [this].concat(args))), _this2), _this2.state = {
value: _this2.getValue()
}, _this2.onUpdate = function (newValue, changedBits) {
var observedBits = _this2.observedBits | 0;
if ((observedBits & changedBits) !== 0) {
_this2.setState({ value: _this2.getValue() });
}
}, _temp2), _possibleConstructorReturn(_this2, _ret2);
}
Consumer.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var observedBits = nextProps.observedBits;
this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT // Subscribe to all changes by default
: observedBits;
};
Consumer.prototype.componentDidMount = function componentDidMount() {
if (this.context[contextProp]) {
this.context[contextProp].on(this.onUpdate);
}
var observedBits = this.props.observedBits;
this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT // Subscribe to all changes by default
: observedBits;
};
Consumer.prototype.componentWillUnmount = function componentWillUnmount() {
if (this.context[contextProp]) {
this.context[contextProp].off(this.onUpdate);
}
};
Consumer.prototype.getValue = function getValue() {
if (this.context[contextProp]) {
return this.context[contextProp].get();
} else {
return defaultValue;
}
};
Consumer.prototype.render = function render() {
return onlyChild(this.props.children)(this.state.value);
};
return Consumer;
}(React__default.Component);
Consumer.contextTypes = (_Consumer$contextType = {}, _Consumer$contextType[contextProp] = _propTypes2.default.object, _Consumer$contextType);
return {
Provider: Provider,
Consumer: Consumer
};
}
exports.default = createReactContext;
module.exports = exports['default'];
});
unwrapExports(implementation);
var lib = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
var _react2 = _interopRequireDefault(React__default);
var _implementation2 = _interopRequireDefault(implementation);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _react2.default.createContext || _implementation2.default;
module.exports = exports['default'];
});
var createContext = unwrapExports(lib);
var ManagerContext = createContext({
setReferenceNode: undefined,
referenceNode: undefined
});
/**
* Takes an argument and if it's an array, returns the first item in the array,
* otherwise returns the argument. Used for Preact compatibility.
*/
var unwrapArray = function unwrapArray(arg) {
return Array.isArray(arg) ? arg[0] : arg;
};
/**
* Takes a maybe-undefined function and arbitrary args and invokes the function
* only if it is defined.
*/
var safeInvoke = function safeInvoke(fn) {
if (typeof fn === "function") {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return fn.apply(void 0, args);
}
};
var initialStyle = {
position: 'absolute',
top: 0,
left: 0,
opacity: 0,
pointerEvents: 'none'
};
var initialArrowStyle = {};
var InnerPopper =
/*#__PURE__*/
function (_React$Component) {
inheritsLoose(InnerPopper, _React$Component);
function InnerPopper() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
defineProperty(assertThisInitialized(assertThisInitialized(_this)), "state", {
data: undefined,
placement: undefined
});
defineProperty(assertThisInitialized(assertThisInitialized(_this)), "popperInstance", void 0);
defineProperty(assertThisInitialized(assertThisInitialized(_this)), "popperNode", null);
defineProperty(assertThisInitialized(assertThisInitialized(_this)), "arrowNode", null);
defineProperty(assertThisInitialized(assertThisInitialized(_this)), "setPopperNode", function (popperNode) {
if (!popperNode || _this.popperNode === popperNode) return;
safeInvoke(_this.props.innerRef, popperNode);
_this.popperNode = popperNode;
_this.updatePopperInstance();
});
defineProperty(assertThisInitialized(assertThisInitialized(_this)), "setArrowNode", function (arrowNode) {
_this.arrowNode = arrowNode;
});
defineProperty(assertThisInitialized(assertThisInitialized(_this)), "updateStateModifier", {
enabled: true,
order: 900,
fn: function fn(data) {
var placement = data.placement;
_this.setState({
data: data,
placement: placement
});
return data;
}
});
defineProperty(assertThisInitialized(assertThisInitialized(_this)), "getOptions", function () {
return {
placement: _this.props.placement,
eventsEnabled: _this.props.eventsEnabled,
positionFixed: _this.props.positionFixed,
modifiers: _extends_1({}, _this.props.modifiers, {
arrow: _extends_1({}, _this.props.modifiers && _this.props.modifiers.arrow, {
enabled: !!_this.arrowNode,
element: _this.arrowNode
}),
applyStyle: {
enabled: false
},
updateStateModifier: _this.updateStateModifier
})
};
});
defineProperty(assertThisInitialized(assertThisInitialized(_this)), "getPopperStyle", function () {
return !_this.popperNode || !_this.state.data ? initialStyle : _extends_1({
position: _this.state.data.offsets.popper.position
}, _this.state.data.styles);
});
defineProperty(assertThisInitialized(assertThisInitialized(_this)), "getPopperPlacement", function () {
return !_this.state.data ? undefined : _this.state.placement;
});
defineProperty(assertThisInitialized(assertThisInitialized(_this)), "getArrowStyle", function () {
return !_this.arrowNode || !_this.state.data ? initialArrowStyle : _this.state.data.arrowStyles;
});
defineProperty(assertThisInitialized(assertThisInitialized(_this)), "getOutOfBoundariesState", function () {
return _this.state.data ? _this.state.data.hide : undefined;
});
defineProperty(assertThisInitialized(assertThisInitialized(_this)), "destroyPopperInstance", function () {
if (!_this.popperInstance) return;
_this.popperInstance.destroy();
_this.popperInstance = null;
});
defineProperty(assertThisInitialized(assertThisInitialized(_this)), "updatePopperInstance", function () {
_this.destroyPopperInstance();
var _assertThisInitialize = assertThisInitialized(assertThisInitialized(_this)),
popperNode = _assertThisInitialize.popperNode;
var referenceElement = _this.props.referenceElement;
if (!referenceElement || !popperNode) return;
_this.popperInstance = new Popper(referenceElement, popperNode, _this.getOptions());
});
defineProperty(assertThisInitialized(assertThisInitialized(_this)), "scheduleUpdate", function () {
if (_this.popperInstance) {
_this.popperInstance.scheduleUpdate();
}
});
return _this;
}
var _proto = InnerPopper.prototype;
_proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
// If the Popper.js options have changed, update the instance (destroy + create)
if (this.props.placement !== prevProps.placement || this.props.referenceElement !== prevProps.referenceElement || this.props.positionFixed !== prevProps.positionFixed) {
this.updatePopperInstance();
} else if (this.props.eventsEnabled !== prevProps.eventsEnabled && this.popperInstance) {
this.props.eventsEnabled ? this.popperInstance.enableEventListeners() : this.popperInstance.disableEventListeners();
} // A placement difference in state means popper determined a new placement
// apart from the props value. By the time the popper element is rendered with
// the new position Popper has already measured it, if the place change triggers
// a size change it will result in a misaligned popper. So we schedule an update to be sure.
if (prevState.placement !== this.state.placement) {
this.scheduleUpdate();
}
};
_proto.componentWillUnmount = function componentWillUnmount() {
safeInvoke(this.props.innerRef, null);
this.destroyPopperInstance();
};
_proto.render = function render() {
return unwrapArray(this.props.children)({
ref: this.setPopperNode,
style: this.getPopperStyle(),
placement: this.getPopperPlacement(),
outOfBoundaries: this.getOutOfBoundariesState(),
scheduleUpdate: this.scheduleUpdate,
arrowProps: {
ref: this.setArrowNode,
style: this.getArrowStyle()
}
});
};
return InnerPopper;
}(React.Component);
defineProperty(InnerPopper, "defaultProps", {
placement: 'bottom',
eventsEnabled: true,
referenceElement: undefined,
positionFixed: false
});
function Popper$1(_ref) {
var referenceElement = _ref.referenceElement,
props = objectWithoutPropertiesLoose(_ref, ["referenceElement"]);
return React.createElement(ManagerContext.Consumer, null, function (_ref2) {
var referenceNode = _ref2.referenceNode;
return React.createElement(InnerPopper, _extends_1({
referenceElement: referenceElement !== undefined ? referenceElement : referenceNode
}, props));
});
}
// Public components
// Public types
var propTypes$2 = {
/**
* Specify menu alignment. The default value is `justify`, which makes the
* menu as wide as the input and truncates long values. Specifying `left`
* or `right` will align the menu to that side and the width will be
* determined by the length of menu item values.
*/
align: propTypes.oneOf(['justify', 'left', 'right']),
children: propTypes.func.isRequired,
/**
* Specify whether the menu should appear above the input.
*/
dropup: propTypes.bool,
/**
* Whether or not to automatically adjust the position of the menu when it
* reaches the viewport boundaries.
*/
flip: propTypes.bool,
/* eslint-disable-line react/no-unused-prop-types */
isMenuShown: propTypes.bool,
/**
* Invoked when menu visibility changes.
*/
onMenuToggle: propTypes.func,
positionFixed: propTypes.bool,
/* eslint-disable-next-line react/forbid-prop-types */
referenceElement: propTypes.object
};
var defaultProps$1 = {
align: 'justify',
dropup: false,
flip: false,
isMenuShown: false,
onMenuToggle: noop,
positionFixed: false
};
function getModifiers(_ref) {
var align = _ref.align,
flip = _ref.flip;
return {
computeStyles: {
enabled: true,
fn: function fn(data) {
// Use the following condition instead of `align === 'justify'` since
// it allows the component to fall back to justifying the menu width
// even when `align` is undefined.
if (align !== 'right' && align !== 'left') {
// Set the popper width to match the target width.
/* eslint-disable-next-line no-param-reassign */
data.styles.width = data.offsets.reference.width;
}
return data;
}
},
flip: {
enabled: flip
},
preventOverflow: {
escapeWithReference: true
}
};
}
var Overlay =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Overlay, _React$Component);
function Overlay() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = Overlay.prototype;
_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
var _this$props = this.props,
isMenuShown = _this$props.isMenuShown,
onMenuToggle = _this$props.onMenuToggle;
if (isMenuShown !== prevProps.isMenuShown) {
onMenuToggle(isMenuShown);
}
};
_proto.render = function render() {
var _this$props2 = this.props,
align = _this$props2.align,
children = _this$props2.children,
dropup = _this$props2.dropup,
isMenuShown = _this$props2.isMenuShown,
positionFixed = _this$props2.positionFixed,
referenceElement = _this$props2.referenceElement;
if (!isMenuShown) {
return null;
}
var xPlacement = align === 'right' ? 'end' : 'start';
var yPlacement = dropup ? 'top' : 'bottom';
return React__default.createElement(Popper$1, {
modifiers: getModifiers(this.props),
placement: yPlacement + "-" + xPlacement,
positionFixed: positionFixed,
referenceElement: referenceElement
}, function (_ref2) {
var ref = _ref2.ref,
props = _objectWithoutPropertiesLoose(_ref2, ["ref"]);
return children(_extends({}, props, {
innerRef: ref,
inputHeight: referenceElement ? referenceElement.offsetHeight : 0
}));
});
};
return Overlay;
}(React__default.Component);
_defineProperty(Overlay, "propTypes", propTypes$2);
_defineProperty(Overlay, "defaultProps", defaultProps$1);
var interopRequireDefault = createCommonjsModule(function (module) {
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
module.exports = _interopRequireDefault;
});
unwrapExports(interopRequireDefault);
var inDOM = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _default = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(inDOM);
var contains = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _inDOM = interopRequireDefault(inDOM);
var _default = function () {
// HTML DOM and SVG DOM may have different support levels,
// so we need to check on context instead of a document root element.
return _inDOM.default ? function (context, node) {
if (context.contains) {
return context.contains(node);
} else if (context.compareDocumentPosition) {
return context === node || !!(context.compareDocumentPosition(node) & 16);
} else {
return fallback(context, node);
}
} : fallback;
}();
exports.default = _default;
function fallback(context, node) {
if (node) do {
if (node === context) return true;
} while (node = node.parentNode);
return false;
}
module.exports = exports["default"];
});
unwrapExports(contains);
var on_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _inDOM = interopRequireDefault(inDOM);
var on = function on() {};
if (_inDOM.default) {
on = function () {
if (document.addEventListener) return function (node, eventName, handler, capture) {
return node.addEventListener(eventName, handler, capture || false);
};else if (document.attachEvent) return function (node, eventName, handler) {
return node.attachEvent('on' + eventName, function (e) {
e = e || window.event;
e.target = e.target || e.srcElement;
e.currentTarget = node;
handler.call(node, e);
});
};
}();
}
var _default = on;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(on_1);
var off_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _inDOM = interopRequireDefault(inDOM);
var off = function off() {};
if (_inDOM.default) {
off = function () {
if (document.addEventListener) return function (node, eventName, handler, capture) {
return node.removeEventListener(eventName, handler, capture || false);
};else if (document.attachEvent) return function (node, eventName, handler) {
return node.detachEvent('on' + eventName, handler);
};
}();
}
var _default = off;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(off_1);
var addEventListener = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = function (node, event, handler, capture) {
(0, _on2.default)(node, event, handler, capture);
return {
remove: function remove() {
(0, _off2.default)(node, event, handler, capture);
}
};
};
var _on2 = _interopRequireDefault(on_1);
var _off2 = _interopRequireDefault(off_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = exports['default'];
});
unwrapExports(addEventListener);
var ownerDocument_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = ownerDocument;
function ownerDocument(node) {
return node && node.ownerDocument || document;
}
module.exports = exports["default"];
});
unwrapExports(ownerDocument_1);
var ownerDocument = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = function (componentOrElement) {
return (0, _ownerDocument2.default)(_reactDom2.default.findDOMNode(componentOrElement));
};
var _reactDom2 = _interopRequireDefault(reactDom__default);
var _ownerDocument2 = _interopRequireDefault(ownerDocument_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = exports['default'];
});
unwrapExports(ownerDocument);
var RootCloseWrapper_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
var _contains2 = _interopRequireDefault(contains);
var _propTypes2 = _interopRequireDefault(propTypes);
var _react2 = _interopRequireDefault(React__default);
var _reactDom2 = _interopRequireDefault(reactDom__default);
var _addEventListener2 = _interopRequireDefault(addEventListener);
var _ownerDocument2 = _interopRequireDefault(ownerDocument);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var escapeKeyCode = 27;
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
/**
* The `` component registers your callback on the document
* when rendered. Powers the `` component. This is used achieve modal
* style behavior where your callback is triggered when the user tries to
* interact with the rest of the document or hits the `esc` key.
*/
var RootCloseWrapper = function (_React$Component) {
_inherits(RootCloseWrapper, _React$Component);
function RootCloseWrapper(props, context) {
_classCallCheck(this, RootCloseWrapper);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.addEventListeners = function () {
var event = _this.props.event;
var doc = (0, _ownerDocument2.default)(_this);
// Use capture for this listener so it fires before React's listener, to
// avoid false positives in the contains() check below if the target DOM
// element is removed in the React mouse callback.
_this.documentMouseCaptureListener = (0, _addEventListener2.default)(doc, event, _this.handleMouseCapture, true);
_this.documentMouseListener = (0, _addEventListener2.default)(doc, event, _this.handleMouse);
_this.documentKeyupListener = (0, _addEventListener2.default)(doc, 'keyup', _this.handleKeyUp);
};
_this.removeEventListeners = function () {
if (_this.documentMouseCaptureListener) {
_this.documentMouseCaptureListener.remove();
}
if (_this.documentMouseListener) {
_this.documentMouseListener.remove();
}
if (_this.documentKeyupListener) {
_this.documentKeyupListener.remove();
}
};
_this.handleMouseCapture = function (e) {
_this.preventMouseRootClose = isModifiedEvent(e) || !isLeftClickEvent(e) || (0, _contains2.default)(_reactDom2.default.findDOMNode(_this), e.target);
};
_this.handleMouse = function (e) {
if (!_this.preventMouseRootClose && _this.props.onRootClose) {
_this.props.onRootClose(e);
}
};
_this.handleKeyUp = function (e) {
if (e.keyCode === escapeKeyCode && _this.props.onRootClose) {
_this.props.onRootClose(e);
}
};
_this.preventMouseRootClose = false;
return _this;
}
RootCloseWrapper.prototype.componentDidMount = function componentDidMount() {
if (!this.props.disabled) {
this.addEventListeners();
}
};
RootCloseWrapper.prototype.componentDidUpdate = function componentDidUpdate(prevProps) {
if (!this.props.disabled && prevProps.disabled) {
this.addEventListeners();
} else if (this.props.disabled && !prevProps.disabled) {
this.removeEventListeners();
}
};
RootCloseWrapper.prototype.componentWillUnmount = function componentWillUnmount() {
if (!this.props.disabled) {
this.removeEventListeners();
}
};
RootCloseWrapper.prototype.render = function render() {
return this.props.children;
};
return RootCloseWrapper;
}(_react2.default.Component);
RootCloseWrapper.displayName = 'RootCloseWrapper';
RootCloseWrapper.propTypes = {
/**
* Callback fired after click or mousedown. Also triggers when user hits `esc`.
*/
onRootClose: _propTypes2.default.func,
/**
* Children to render.
*/
children: _propTypes2.default.element,
/**
* Disable the the RootCloseWrapper, preventing it from triggering `onRootClose`.
*/
disabled: _propTypes2.default.bool,
/**
* Choose which document mouse event to bind to.
*/
event: _propTypes2.default.oneOf(['click', 'mousedown'])
};
RootCloseWrapper.defaultProps = {
event: 'click'
};
exports.default = RootCloseWrapper;
module.exports = exports['default'];
});
var RootCloseWrapper = unwrapExports(RootCloseWrapper_1);
var implementation$1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
var _react2 = _interopRequireDefault(React__default);
var _propTypes2 = _interopRequireDefault(propTypes);
var _gud2 = _interopRequireDefault(gud);
var _warning2 = _interopRequireDefault(warning_1$1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var MAX_SIGNED_31_BIT_INT = 1073741823;
// Inlined Object.is polyfill.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
function objectIs(x, y) {
if (x === y) {
return x !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
function createEventEmitter(value) {
var handlers = [];
return {
on: function on(handler) {
handlers.push(handler);
},
off: function off(handler) {
handlers = handlers.filter(function (h) {
return h !== handler;
});
},
get: function get() {
return value;
},
set: function set(newValue, changedBits) {
value = newValue;
handlers.forEach(function (handler) {
return handler(value, changedBits);
});
}
};
}
function onlyChild(children) {
return Array.isArray(children) ? children[0] : children;
}
function createReactContext(defaultValue, calculateChangedBits) {
var _Provider$childContex, _Consumer$contextType;
var contextProp = '__create-react-context-' + (0, _gud2.default)() + '__';
var Provider = function (_Component) {
_inherits(Provider, _Component);
function Provider() {
var _temp, _this, _ret;
_classCallCheck(this, Provider);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.emitter = createEventEmitter(_this.props.value), _temp), _possibleConstructorReturn(_this, _ret);
}
Provider.prototype.getChildContext = function getChildContext() {
var _ref;
return _ref = {}, _ref[contextProp] = this.emitter, _ref;
};
Provider.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.props.value !== nextProps.value) {
var oldValue = this.props.value;
var newValue = nextProps.value;
var changedBits = void 0;
if (objectIs(oldValue, newValue)) {
changedBits = 0; // No change
} else {
changedBits = typeof calculateChangedBits === 'function' ? calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;
{
(0, _warning2.default)((changedBits & MAX_SIGNED_31_BIT_INT) === changedBits, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits);
}
changedBits |= 0;
if (changedBits !== 0) {
this.emitter.set(nextProps.value, changedBits);
}
}
}
};
Provider.prototype.render = function render() {
return this.props.children;
};
return Provider;
}(React__default.Component);
Provider.childContextTypes = (_Provider$childContex = {}, _Provider$childContex[contextProp] = _propTypes2.default.object.isRequired, _Provider$childContex);
var Consumer = function (_Component2) {
_inherits(Consumer, _Component2);
function Consumer() {
var _temp2, _this2, _ret2;
_classCallCheck(this, Consumer);
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return _ret2 = (_temp2 = (_this2 = _possibleConstructorReturn(this, _Component2.call.apply(_Component2, [this].concat(args))), _this2), _this2.state = {
value: _this2.getValue()
}, _this2.onUpdate = function (newValue, changedBits) {
var observedBits = _this2.observedBits | 0;
if ((observedBits & changedBits) !== 0) {
_this2.setState({ value: _this2.getValue() });
}
}, _temp2), _possibleConstructorReturn(_this2, _ret2);
}
Consumer.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var observedBits = nextProps.observedBits;
this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT // Subscribe to all changes by default
: observedBits;
};
Consumer.prototype.componentDidMount = function componentDidMount() {
if (this.context[contextProp]) {
this.context[contextProp].on(this.onUpdate);
}
var observedBits = this.props.observedBits;
this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT // Subscribe to all changes by default
: observedBits;
};
Consumer.prototype.componentWillUnmount = function componentWillUnmount() {
if (this.context[contextProp]) {
this.context[contextProp].off(this.onUpdate);
}
};
Consumer.prototype.getValue = function getValue() {
if (this.context[contextProp]) {
return this.context[contextProp].get();
} else {
return defaultValue;
}
};
Consumer.prototype.render = function render() {
return onlyChild(this.props.children)(this.state.value);
};
return Consumer;
}(React__default.Component);
Consumer.contextTypes = (_Consumer$contextType = {}, _Consumer$contextType[contextProp] = _propTypes2.default.object, _Consumer$contextType);
return {
Provider: Provider,
Consumer: Consumer
};
}
exports.default = createReactContext;
module.exports = exports['default'];
});
unwrapExports(implementation$1);
var lib$1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
var _react2 = _interopRequireDefault(React__default);
var _implementation2 = _interopRequireDefault(implementation$1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _react2.default.createContext || _implementation2.default;
module.exports = exports['default'];
});
var createReactContext = unwrapExports(lib$1);
var TypeaheadContext = createReactContext({});
var withContext = function withContext(Component, values) {
// Note: Use a class instead of function component to support refs.
/* eslint-disable-next-line react/prefer-stateless-function */
return (
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(_class, _React$Component);
function _class() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = _class.prototype;
_proto.render = function render() {
var _this = this;
return React__default.createElement(TypeaheadContext.Consumer, null, function (context) {
return React__default.createElement(Component, _extends({}, _this.props, pick(context, values)));
});
};
return _class;
}(React__default.Component)
);
};
var inputPropKeys = ['activeIndex', 'disabled', 'id', 'inputRef', 'isFocused', 'isMenuShown', 'labelKey', 'multiple', 'onBlur', 'onChange', 'onFocus', 'onKeyDown', 'onRemove', 'placeholder', 'selected'];
var overlayPropKeys = ['align', 'dropup', 'flip', 'onMenuToggle', 'positionFixed'];
var stateKeys = ['activeIndex', 'isMenuShown', 'labelKey', 'onClear', 'results', 'selected', 'text'];
var typeaheadContextKeys = ['activeIndex', 'id', 'initialItem', 'onActiveItemChange', 'onAdd', 'onInitialItemChange', 'onMenuItemClick', 'selectHintOnEnter'];
var getOverlayProps = function getOverlayProps(_ref) {
var isMenuShown = _ref.isMenuShown,
referenceElement = _ref.referenceElement;
return function (props) {
return _extends({}, pick(props, overlayPropKeys), {
isMenuShown: isMenuShown,
referenceElement: referenceElement
});
};
};
function getTypeaheadContextValue(props) {
return _extends({}, pick(props, typeaheadContextKeys), {
hintText: getHintText(props),
isOnlyResult: getIsOnlyResult(props)
});
}
var TypeaheadInnerManager =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(TypeaheadInnerManager, _React$Component);
function TypeaheadInnerManager() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_defineProperty(_assertThisInitialized(_this), "_handleKeyDown", function (e) {
var _this$props = _this.props,
initialItem = _this$props.initialItem,
onKeyDown = _this$props.onKeyDown,
onAdd = _this$props.onAdd;
switch (e.keyCode) {
case RETURN:
if (initialItem && getIsOnlyResult(_this.props)) {
onAdd(initialItem);
}
break;
default:
break;
}
onKeyDown(e);
});
return _this;
}
var _proto = TypeaheadInnerManager.prototype;
_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
var _this$props2 = this.props,
allowNew = _this$props2.allowNew,
onInitialItemChange = _this$props2.onInitialItemChange,
results = _this$props2.results; // Clear the initial item when there are no results.
if (!(allowNew || results.length)) {
onInitialItemChange(null);
}
};
_proto.render = function render() {
var childProps = {
getInputProps: getInputProps(_extends({}, pick(this.props, inputPropKeys), {
onKeyDown: this._handleKeyDown,
ref: this.props.getReferenceElement,
value: getInputText(this.props)
})),
getOverlayProps: getOverlayProps(this.props),
state: pick(this.props, stateKeys)
};
return React__default.createElement(TypeaheadContext.Provider, {
value: getTypeaheadContextValue(this.props)
}, this.props.children(childProps));
};
return TypeaheadInnerManager;
}(React__default.Component);
var propTypes$3 = {
/**
* Allows the creation of new selections on the fly. Note that any new items
* will be added to the list of selections, but not the list of original
* options unless handled as such by `Typeahead`'s parent.
*
* If a function is specified, it will be used to determine whether a custom
* option should be included. The return value should be true or false.
*/
allowNew: propTypes.oneOfType([propTypes.bool, propTypes.func]),
/**
* Autofocus the input when the component initially mounts.
*/
autoFocus: propTypes.bool,
/**
* Whether or not filtering should be case-sensitive.
*/
caseSensitive: checkPropType(propTypes.bool, caseSensitiveType),
/**
* The initial value displayed in the text input.
*/
defaultInputValue: checkPropType(propTypes.string, defaultInputValueType),
/**
* Whether or not the menu is displayed upon initial render.
*/
defaultOpen: propTypes.bool,
/**
* Specify any pre-selected options. Use only if you want the component to
* be uncontrolled.
*/
defaultSelected: propTypes.arrayOf(optionType),
/**
* Either an array of fields in `option` to search, or a custom filtering
* callback.
*/
filterBy: propTypes.oneOfType([propTypes.arrayOf(propTypes.string.isRequired), propTypes.func]),
/**
* Highlights the menu item if there is only one result and allows selecting
* that item by hitting enter. Does not work with `allowNew`.
*/
highlightOnlyResult: checkPropType(propTypes.bool, highlightOnlyResultType),
/**
* An html id attribute, required for assistive technologies such as screen
* readers.
*/
id: checkPropType(propTypes.oneOfType([propTypes.number, propTypes.string]), isRequiredForA11y),
/**
* Whether the filter should ignore accents and other diacritical marks.
*/
ignoreDiacritics: checkPropType(propTypes.bool, ignoreDiacriticsType),
/**
* Specify the option key to use for display or a function returning the
* display string. By default, the selector will use the `label` key.
*/
labelKey: checkPropType(propTypes.oneOfType([propTypes.string, propTypes.func]), labelKeyType),
/**
* Maximum number of results to display by default. Mostly done for
* performance reasons so as not to render too many DOM nodes in the case of
* large data sets.
*/
maxResults: propTypes.number,
/**
* Number of input characters that must be entered before showing results.
*/
minLength: propTypes.number,
/**
* Whether or not multiple selections are allowed.
*/
multiple: propTypes.bool,
/**
* Invoked when the input is blurred. Receives an event.
*/
onBlur: propTypes.func,
/**
* Invoked whenever items are added or removed. Receives an array of the
* selected options.
*/
onChange: propTypes.func,
/**
* Invoked when the input is focused. Receives an event.
*/
onFocus: propTypes.func,
/**
* Invoked when the input value changes. Receives the string value of the
* input.
*/
onInputChange: propTypes.func,
/**
* Invoked when a key is pressed. Receives an event.
*/
onKeyDown: propTypes.func,
/**
* Invoked when the pagination menu item is clicked. Receives an event.
*/
onPaginate: propTypes.func,
/**
* Whether or not the menu should be displayed. `undefined` allows the
* component to control visibility, while `true` and `false` show and hide
* the menu, respectively.
*/
open: propTypes.bool,
/**
* Full set of options, including pre-selected options. Must either be an
* array of objects (recommended) or strings.
*/
options: propTypes.arrayOf(optionType).isRequired,
/**
* Give user the ability to display additional results if the number of
* results exceeds `maxResults`.
*/
paginate: propTypes.bool,
/**
* Prompt displayed when large data sets are paginated.
*/
paginationText: propTypes.string,
/**
* The selected option(s) displayed in the input. Use this prop if you want
* to control the component via its parent.
*/
selected: checkPropType(propTypes.arrayOf(optionType), selectedType),
/**
* Allows selecting the hinted result by pressing enter.
*/
selectHintOnEnter: propTypes.bool
};
var defaultProps$2 = {
allowNew: false,
autoFocus: false,
caseSensitive: false,
defaultInputValue: '',
defaultOpen: false,
defaultSelected: [],
filterBy: [],
highlightOnlyResult: false,
ignoreDiacritics: true,
labelKey: DEFAULT_LABELKEY,
maxResults: 100,
minLength: 0,
multiple: false,
onBlur: noop,
onFocus: noop,
onInputChange: noop,
onKeyDown: noop,
onPaginate: noop,
paginate: true,
paginationText: 'Display additional results...',
selectHintOnEnter: false
};
function getInitialState(props) {
var defaultInputValue = props.defaultInputValue,
defaultOpen = props.defaultOpen,
defaultSelected = props.defaultSelected,
maxResults = props.maxResults,
multiple = props.multiple;
var selected = props.selected ? props.selected.slice() : defaultSelected.slice();
var text = defaultInputValue;
if (!multiple && selected.length) {
// Set the text if an initial selection is passed in.
text = getOptionLabel(head(selected), props.labelKey);
if (selected.length > 1) {
// Limit to 1 selection in single-select mode.
selected = selected.slice(0, 1);
}
}
return {
activeIndex: -1,
activeItem: null,
initialItem: null,
isFocused: false,
selected: selected,
showMenu: defaultOpen,
shownResults: maxResults,
text: text
};
}
var Typeahead =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Typeahead, _React$Component);
function Typeahead() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_defineProperty(_assertThisInitialized(_this), "state", getInitialState(_this.props));
_defineProperty(_assertThisInitialized(_this), "_input", undefined);
_defineProperty(_assertThisInitialized(_this), "_referenceElement", undefined);
_defineProperty(_assertThisInitialized(_this), "blur", function () {
_this.getInput().blur();
_this._hideMenu();
});
_defineProperty(_assertThisInitialized(_this), "clear", function () {
_this.setState(function (state, props) {
return _extends({}, getInitialState(props), {
isFocused: state.isFocused,
selected: [],
text: ''
});
});
});
_defineProperty(_assertThisInitialized(_this), "focus", function () {
_this.getInput().focus();
});
_defineProperty(_assertThisInitialized(_this), "getInput", function () {
!(_this._input instanceof HTMLInputElement) ? invariant_1(false, '`this._input` is not an input element. Be sure to correctly pass the ' + '`inputRef` prop to your input node.') : void 0;
return _this._input;
});
_defineProperty(_assertThisInitialized(_this), "_handleActiveIndexChange", function (activeIndex) {
_this.setState(function (state) {
return {
activeIndex: activeIndex,
activeItem: activeIndex === -1 ? null : state.activeItem
};
});
});
_defineProperty(_assertThisInitialized(_this), "_handleActiveItemChange", function (activeItem) {
// Don't update the active item if it hasn't changed.
if (!lodash_isequal(activeItem, _this.state.activeItem)) {
_this.setState({
activeItem: activeItem
});
}
});
_defineProperty(_assertThisInitialized(_this), "_handleBlur", function (e) {
e.persist();
_this.setState({
isFocused: false
}, function () {
return _this.props.onBlur(e);
});
});
_defineProperty(_assertThisInitialized(_this), "_handleClear", function () {
_this.clear();
_this._updateSelected([]);
});
_defineProperty(_assertThisInitialized(_this), "_handleFocus", function (e) {
e.persist();
_this.setState({
isFocused: true,
showMenu: true
}, function () {
return _this.props.onFocus(e);
});
});
_defineProperty(_assertThisInitialized(_this), "_handleInitialItemChange", function (initialItem) {
// Don't update the initial item if it hasn't changed.
if (!lodash_isequal(initialItem, _this.state.initialItem)) {
_this.setState({
initialItem: initialItem
});
}
});
_defineProperty(_assertThisInitialized(_this), "_handleInputChange", function (e) {
e.persist();
var text = e.currentTarget.value;
var _getInitialState = getInitialState(_this.props),
activeIndex = _getInitialState.activeIndex,
activeItem = _getInitialState.activeItem,
shownResults = _getInitialState.shownResults;
var _this$props = _this.props,
multiple = _this$props.multiple,
onInputChange = _this$props.onInputChange;
_this.setState({
activeIndex: activeIndex,
activeItem: activeItem,
showMenu: true,
shownResults: shownResults,
text: text
}, function () {
return onInputChange(text, e);
}); // Clear any selections if text is entered in single-select mode.
if (_this.state.selected.length && !multiple) {
_this._updateSelected([]);
}
});
_defineProperty(_assertThisInitialized(_this), "_handleKeyDown", function (e, results, isMenuShown) {
var activeItem = _this.state.activeItem; // Skip most actions when the menu is hidden.
if (!isMenuShown) {
if (e.keyCode === UP || e.keyCode === DOWN) {
_this.setState({
showMenu: true
});
}
_this.props.onKeyDown(e);
return;
}
switch (e.keyCode) {
case UP:
case DOWN:
// Prevent input cursor from going to the beginning when pressing up.
e.preventDefault();
_this._handleActiveIndexChange(getUpdatedActiveIndex(_this.state.activeIndex, e.keyCode, results));
break;
case ESC:
_this._hideMenu();
break;
case RETURN:
// Prevent form submission while menu is open.
e.preventDefault();
activeItem && _this._handleMenuItemSelect(activeItem, e);
break;
case TAB:
// Don't blur the input when the menu is open.
e.preventDefault();
break;
default:
break;
}
_this.props.onKeyDown(e);
});
_defineProperty(_assertThisInitialized(_this), "_handleMenuItemSelect", function (option, e) {
if (option.paginationOption) {
_this._handlePaginate(e);
} else {
_this._handleSelectionAdd(option);
}
});
_defineProperty(_assertThisInitialized(_this), "_handlePaginate", function (e) {
e.persist();
_this.setState(function (_ref, _ref2) {
var shownResults = _ref.shownResults;
var maxResults = _ref2.maxResults;
return {
shownResults: shownResults + maxResults
};
}, function () {
return _this.props.onPaginate(e, _this.state.shownResults);
});
});
_defineProperty(_assertThisInitialized(_this), "_handleSelectionAdd", function (option) {
var _this$props2 = _this.props,
multiple = _this$props2.multiple,
labelKey = _this$props2.labelKey;
var selected;
var selection = option;
var text; // Add a unique id to the custom selection. Avoid doing this in `render` so
// the id doesn't increment every time.
if (!isString(selection) && selection.customOption) {
// $FlowFixMe: Option is an object here...
selection = _extends({}, selection, {
id: uniqueId('new-id-')
});
}
if (multiple) {
// If multiple selections are allowed, add the new selection to the
// existing selections.
selected = _this.state.selected.concat(selection);
text = '';
} else {
// If only a single selection is allowed, replace the existing selection
// with the new one.
selected = [selection];
text = getOptionLabel(selection, labelKey);
}
_this._hideMenu();
_this.setState({
initialItem: selection,
text: text
}); // Text must be updated before the selection to fix #211.
// TODO: Find a more robust way of solving the issue.
_this._updateSelected(selected);
});
_defineProperty(_assertThisInitialized(_this), "_handleSelectionRemove", function (selection) {
var selected = _this.state.selected.filter(function (option) {
return !lodash_isequal(option, selection);
}); // Make sure the input stays focused after the item is removed.
_this.focus();
_this._hideMenu();
_this._updateSelected(selected);
});
_defineProperty(_assertThisInitialized(_this), "_hideMenu", function () {
var _getInitialState2 = getInitialState(_this.props),
activeIndex = _getInitialState2.activeIndex,
activeItem = _getInitialState2.activeItem,
shownResults = _getInitialState2.shownResults;
_this.setState({
activeIndex: activeIndex,
activeItem: activeItem,
showMenu: false,
shownResults: shownResults
});
});
_defineProperty(_assertThisInitialized(_this), "_updateSelected", function (selected) {
_this.setState({
selected: selected
}, function () {
_this.props.onChange && _this.props.onChange(selected);
});
});
return _this;
}
Typeahead.getDerivedStateFromProps = function getDerivedStateFromProps(props, state) {
var labelKey = props.labelKey,
multiple = props.multiple; // Truncate selections when in single-select mode.
var prevSelected = props.selected || state.selected;
if (!multiple && prevSelected.length > 1) {
var selected = prevSelected.slice(0, 1);
return {
selected: selected,
text: getOptionLabel(head(selected), labelKey)
};
}
return null;
};
var _proto = Typeahead.prototype;
_proto.componentDidMount = function componentDidMount() {
this.props.autoFocus && this.focus();
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
var _this$props3 = this.props,
labelKey = _this$props3.labelKey,
multiple = _this$props3.multiple,
selected = _this$props3.selected;
validateSelectedPropChange(prevProps.selected, selected); // Keep `selected` state and props in sync. Use `componentDidUpdate`
// rather than `getDerivedStateFromProps` to compare with previous
// props and differentiate between externally changed selections and
// internally changed ones that trigger `onChange` in a controlled
// component, eg. passing an empty array vs. clearing a selection by
// deleting part of the input value.
if (lodash_isequal(prevProps.selected, this.state.selected) && !lodash_isequal(prevProps.selected, selected)) {
// Selections were changed externally, update state accordingly.
var text = selected && selected.length && !multiple ? getOptionLabel(head(selected), labelKey) : '';
this.setState({
selected: selected,
text: text
});
}
if (prevProps.multiple !== multiple) {
this.setState({
text: ''
});
}
};
_proto.render = function render() {
var _this2 = this;
// Omit `onChange` so Flow doesn't complain.
var _this$props4 = this.props,
onChange = _this$props4.onChange,
otherProps = _objectWithoutPropertiesLoose(_this$props4, ["onChange"]);
var mergedPropsAndState = _extends({}, otherProps, this.state);
var filterBy = mergedPropsAndState.filterBy,
labelKey = mergedPropsAndState.labelKey,
options = mergedPropsAndState.options,
paginate = mergedPropsAndState.paginate,
paginationText = mergedPropsAndState.paginationText,
shownResults = mergedPropsAndState.shownResults,
text = mergedPropsAndState.text;
var isMenuShown = isShown(mergedPropsAndState);
var results = [];
if (isMenuShown) {
var cb = isFunction(filterBy) ? filterBy : defaultFilterBy;
results = options.filter(function (option) {
return cb(option, mergedPropsAndState);
});
} // This must come before results are truncated.
var shouldPaginate = paginate && results.length > shownResults; // Truncate results if necessary.
results = getTruncatedOptions(results, shownResults); // Add the custom option if necessary.
if (addCustomOption(results, mergedPropsAndState)) {
var _results$push;
results.push((_results$push = {
customOption: true
}, _results$push[getStringLabelKey(labelKey)] = text, _results$push));
} // Add the pagination item if necessary.
if (shouldPaginate) {
var _results$push2;
results.push((_results$push2 = {}, _results$push2[getStringLabelKey(labelKey)] = paginationText, _results$push2.paginationOption = true, _results$push2));
}
var props = _extends({}, mergedPropsAndState, {
getReferenceElement: function getReferenceElement(element) {
// Use `findDOMNode` here because it's easier and less fragile than
// forwarding refs to the input's container.
/* eslint-disable-next-line react/no-find-dom-node */
_this2._referenceElement = reactDom.findDOMNode(element);
},
inputRef: function inputRef(input) {
_this2._input = input;
},
isMenuShown: isMenuShown,
onActiveItemChange: this._handleActiveItemChange,
onAdd: this._handleSelectionAdd,
onBlur: this._handleBlur,
onChange: this._handleInputChange,
onClear: this._handleClear,
onFocus: this._handleFocus,
onInitialItemChange: this._handleInitialItemChange,
onKeyDown: function onKeyDown(e) {
return _this2._handleKeyDown(e, results, isMenuShown);
},
onMenuItemClick: this._handleMenuItemSelect,
onRemove: this._handleSelectionRemove,
referenceElement: this._referenceElement,
results: results
});
return React__default.createElement(RootCloseWrapper, {
disabled: this.props.open || !isMenuShown,
onRootClose: this._hideMenu
}, React__default.createElement(TypeaheadInnerManager, props));
};
return Typeahead;
}(React__default.Component);
_defineProperty(Typeahead, "propTypes", propTypes$3);
_defineProperty(Typeahead, "defaultProps", defaultProps$2);
var propTypes$4 = {
bsSize: propTypes.oneOf(['large', 'lg', 'small', 'sm']),
label: propTypes.string,
onClick: propTypes.func.isRequired
};
var defaultProps$3 = {
label: 'Clear'
};
/**
* ClearButton
*
* http://getbootstrap.com/css/#helper-classes-close
*/
var ClearButton = function ClearButton(_ref) {
var bsSize = _ref.bsSize,
className = _ref.className,
label = _ref.label,
_onClick = _ref.onClick,
props = _objectWithoutPropertiesLoose(_ref, ["bsSize", "className", "label", "onClick"]);
return React__default.createElement("button", _extends({}, props, {
"aria-label": label,
className: classnames('close', 'rbt-close', {
'rbt-close-lg': bsSize === 'large' || bsSize === 'lg'
}, className),
onClick: function onClick(e) {
e.stopPropagation();
_onClick(e);
},
type: "button"
}), React__default.createElement("span", {
"aria-hidden": "true"
}, "\xD7"), React__default.createElement("span", {
className: "sr-only"
}, label));
};
ClearButton.propTypes = propTypes$4;
ClearButton.defaultProps = defaultProps$3;
var Loader = function Loader(_ref) {
var bsSize = _ref.bsSize;
return React__default.createElement("div", {
className: classnames('rbt-loader', {
'rbt-loader-lg': bsSize === 'large' || bsSize === 'lg',
'rbt-loader-sm': bsSize === 'small' || bsSize === 'sm'
})
});
};
Loader.propTypes = {
bsSize: propTypes.oneOf(['large', 'lg', 'small', 'sm'])
};
var Input =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Input, _React$Component);
function Input() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = Input.prototype;
_proto.render = function render() {
var _this$props = this.props,
className = _this$props.className,
inputRef = _this$props.inputRef,
props = _objectWithoutPropertiesLoose(_this$props, ["className", "inputRef"]);
return React__default.createElement("input", _extends({}, props, {
className: classnames('rbt-input-main', className),
ref: inputRef
}));
};
return Input;
}(React__default.Component);
/**
* Higher-order component to encapsulate Token behaviors.
*/
var tokenContainer = function tokenContainer(Component) {
var WrappedComponent =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(WrappedComponent, _React$Component);
function WrappedComponent() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_defineProperty(_assertThisInitialized(_this), "state", {
active: false
});
_defineProperty(_assertThisInitialized(_this), "_handleBlur", function (e) {
_this.setState({
active: false
});
});
_defineProperty(_assertThisInitialized(_this), "_handleKeyDown", function (e) {
switch (e.keyCode) {
case BACKSPACE:
if (_this.state.active) {
// Prevent backspace keypress from triggering the browser "back"
// action.
e.preventDefault();
_this.props.onRemove();
}
break;
default:
break;
}
});
_defineProperty(_assertThisInitialized(_this), "_handleActive", function (e) {
e.stopPropagation();
_this.setState({
active: true
});
});
return _this;
}
var _proto = WrappedComponent.prototype;
_proto.render = function render() {
return React__default.createElement(RootCloseWrapper, {
onRootClose: this._handleBlur
}, React__default.createElement(Component, _extends({}, this.props, this.state, {
onBlur: this._handleBlur,
onClick: this._handleActive,
onFocus: this._handleActive,
onKeyDown: this._handleKeyDown
})));
};
return WrappedComponent;
}(React__default.Component);
_defineProperty(WrappedComponent, "displayName", "tokenContainer(" + getDisplayName(Component) + ")");
return WrappedComponent;
};
var propTypes$5 = {
active: propTypes.bool,
/**
* Handler for removing/deleting the token. If not defined, the token will
* be rendered in a read-only state.
*/
onRemove: propTypes.func,
tabIndex: propTypes.number
};
var defaultProps$4 = {
active: false,
tabIndex: 0
};
/**
* Token
*
* Individual token component, generally displayed within the TokenizerInput
* component, but can also be rendered on its own.
*/
var Token =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Token, _React$Component);
function Token() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_defineProperty(_assertThisInitialized(_this), "_renderRemoveableToken", function () {
var _this$props = _this.props,
active = _this$props.active,
children = _this$props.children,
className = _this$props.className,
onRemove = _this$props.onRemove,
props = _objectWithoutPropertiesLoose(_this$props, ["active", "children", "className", "onRemove"]);
return React__default.createElement("div", _extends({}, props, {
className: classnames('rbt-token', 'rbt-token-removeable', {
'rbt-token-active': active
}, className)
}), children, React__default.createElement(ClearButton, {
className: "rbt-token-remove-button",
label: "Remove",
onClick: onRemove,
tabIndex: -1
}));
});
_defineProperty(_assertThisInitialized(_this), "_renderToken", function () {
var _this$props2 = _this.props,
children = _this$props2.children,
className = _this$props2.className,
disabled = _this$props2.disabled,
href = _this$props2.href;
var classnames$1 = classnames('rbt-token', {
'rbt-token-disabled': disabled
}, className);
if (href) {
return React__default.createElement("a", {
className: classnames$1,
href: href
}, children);
}
return React__default.createElement("div", {
className: classnames$1
}, children);
});
return _this;
}
var _proto = Token.prototype;
_proto.render = function render() {
return this.props.onRemove && !this.props.disabled ? this._renderRemoveableToken() : this._renderToken();
};
return Token;
}(React__default.Component);
_defineProperty(Token, "propTypes", propTypes$5);
_defineProperty(Token, "defaultProps", defaultProps$4);
var Token$1 = tokenContainer(Token);
// 'borderStyle', etc.), so generate these from the individual values.
function interpolateStyle(styles, attr, subattr) {
if (subattr === void 0) {
subattr = '';
}
// Title-case the sub-attribute.
if (subattr) {
/* eslint-disable-next-line no-param-reassign */
subattr = subattr.replace(subattr[0], subattr[0].toUpperCase());
}
return ['Top', 'Right', 'Bottom', 'Left'].map(function (dir) {
return styles[attr + dir + subattr];
}).join(' ');
}
function copyStyles(inputNode, hintNode) {
var inputStyle = window.getComputedStyle(inputNode);
/* eslint-disable no-param-reassign */
hintNode.style.borderStyle = interpolateStyle(inputStyle, 'border', 'style');
hintNode.style.borderWidth = interpolateStyle(inputStyle, 'border', 'width');
hintNode.style.fontSize = inputStyle.fontSize;
hintNode.style.lineHeight = inputStyle.lineHeight;
hintNode.style.margin = interpolateStyle(inputStyle, 'margin');
hintNode.style.padding = interpolateStyle(inputStyle, 'padding');
/* eslint-enable no-param-reassign */
}
function hintContainer(Input) {
var HintedInput =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(HintedInput, _React$Component);
function HintedInput() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_defineProperty(_assertThisInitialized(_this), "_hint", undefined);
_defineProperty(_assertThisInitialized(_this), "_input", undefined);
_defineProperty(_assertThisInitialized(_this), "_handleKeyDown", function (e) {
var _this$props = _this.props,
initialItem = _this$props.initialItem,
onAdd = _this$props.onAdd,
onKeyDown = _this$props.onKeyDown;
if (shouldSelectHint(e, _this.props)) {
e.preventDefault(); // Prevent input from blurring on TAB.
onAdd(initialItem);
}
onKeyDown(e);
});
return _this;
}
var _proto = HintedInput.prototype;
_proto.componentDidMount = function componentDidMount() {
copyStyles(this._input, this._hint);
};
_proto.componentDidUpdate = function componentDidUpdate() {
copyStyles(this._input, this._hint);
};
_proto.render = function render() {
var _this2 = this;
var _this$props2 = this.props,
hintText = _this$props2.hintText,
initialItem = _this$props2.initialItem,
_inputRef = _this$props2.inputRef,
onAdd = _this$props2.onAdd,
selectHintOnEnter = _this$props2.selectHintOnEnter,
props = _objectWithoutPropertiesLoose(_this$props2, ["hintText", "initialItem", "inputRef", "onAdd", "selectHintOnEnter"]);
return React__default.createElement("div", {
style: {
display: 'flex',
flex: 1,
height: '100%',
position: 'relative'
}
}, React__default.createElement(Input, _extends({}, props, {
inputRef: function inputRef(input) {
_this2._input = input;
_inputRef(input);
},
onKeyDown: this._handleKeyDown
})), React__default.createElement("input", {
"aria-hidden": true,
className: "rbt-input-hint",
ref: function ref(hint) {
return _this2._hint = hint;
},
readOnly: true,
style: {
backgroundColor: 'transparent',
borderColor: 'transparent',
boxShadow: 'none',
color: 'rgba(0, 0, 0, 0.35)',
left: 0,
pointerEvents: 'none',
position: 'absolute',
top: 0,
width: '100%'
},
tabIndex: -1,
value: hintText
}));
};
return HintedInput;
}(React__default.Component);
_defineProperty(HintedInput, "displayName", "hintContainer(" + getDisplayName(Input) + ")");
return withContext(HintedInput, ['hintText', 'initialItem', 'onAdd', 'selectHintOnEnter']);
}
function withClassNames(Component) {
// Use a class instead of function component to support refs.
/* eslint-disable-next-line react/prefer-stateless-function */
var WrappedComponent =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(WrappedComponent, _React$Component);
function WrappedComponent() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = WrappedComponent.prototype;
_proto.render = function render() {
var _this$props = this.props,
bsSize = _this$props.bsSize,
className = _this$props.className,
isInvalid = _this$props.isInvalid,
isValid = _this$props.isValid,
props = _objectWithoutPropertiesLoose(_this$props, ["bsSize", "className", "isInvalid", "isValid"]);
return React__default.createElement(Component, _extends({}, props, {
className: classnames('form-control', 'rbt-input', {
'input-lg form-control-lg': bsSize === 'large' || bsSize === 'lg',
'input-sm form-control-sm': bsSize === 'small' || bsSize === 'sm',
'is-invalid': isInvalid,
'is-valid': isValid
}, className)
}));
};
return WrappedComponent;
}(React__default.Component);
_defineProperty(WrappedComponent, "displayName", "withClassNames(" + getDisplayName(Component) + ")");
return WrappedComponent;
}
var HintedInput = hintContainer(Input);
var propTypes$6 = {
/**
* Provides a hook for customized rendering of tokens when multiple
* selections are enabled.
*/
renderToken: propTypes.func
};
var defaultProps$5 = {
renderToken: function renderToken(option, props, idx) {
return React__default.createElement(Token$1, {
disabled: props.disabled,
key: idx,
onRemove: props.onRemove,
tabIndex: props.tabIndex
}, getOptionLabel(option, props.labelKey));
}
};
var TypeaheadInputMulti =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(TypeaheadInputMulti, _React$Component);
function TypeaheadInputMulti() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_defineProperty(_assertThisInitialized(_this), "_input", null);
_defineProperty(_assertThisInitialized(_this), "_wrapper", null);
_defineProperty(_assertThisInitialized(_this), "_renderToken", function (option, idx) {
var _this$props = _this.props,
_onRemove = _this$props.onRemove,
renderToken = _this$props.renderToken;
var props = _extends({}, _this.props, {
onRemove: function onRemove() {
return _onRemove(option);
}
});
return renderToken(option, props, idx);
});
_defineProperty(_assertThisInitialized(_this), "_handleContainerClickOrFocus", function (e) {
// Don't focus the input if it's disabled.
if (_this.props.disabled) {
e.currentTarget.blur();
return;
} // Move cursor to the end if the user clicks outside the actual input.
var inputNode = _this._input;
if (e.currentTarget !== inputNode && isSelectable(inputNode)) {
inputNode.selectionStart = inputNode.value.length;
}
inputNode.focus();
});
_defineProperty(_assertThisInitialized(_this), "_handleKeyDown", function (e) {
var _this$props2 = _this.props,
onKeyDown = _this$props2.onKeyDown,
selected = _this$props2.selected,
value = _this$props2.value;
switch (e.keyCode) {
case BACKSPACE:
if (e.currentTarget === _this._input && selected.length && !value) {
// If the input is selected and there is no text, focus the last
// token when the user hits backspace.
var children = _this._wrapper.children;
var lastToken = children[children.length - 2];
lastToken && lastToken.focus();
}
break;
default:
break;
}
onKeyDown(e);
});
return _this;
}
var _proto = TypeaheadInputMulti.prototype;
_proto.render = function render() {
var _this2 = this;
var _this$props3 = this.props,
className = _this$props3.className,
inputClassName = _this$props3.inputClassName,
labelKey = _this$props3.labelKey,
onRemove = _this$props3.onRemove,
placeholder = _this$props3.placeholder,
renderToken = _this$props3.renderToken,
selected = _this$props3.selected,
props = _objectWithoutPropertiesLoose(_this$props3, ["className", "inputClassName", "labelKey", "onRemove", "placeholder", "renderToken", "selected"]);
return (
/* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable jsx-a11y/click-events-have-key-events */
React__default.createElement("div", {
className: classnames('rbt-input-multi', className),
disabled: props.disabled,
onClick: this._handleContainerClickOrFocus,
onFocus: this._handleContainerClickOrFocus,
tabIndex: -1
}, React__default.createElement("div", {
className: "rbt-input-wrapper",
ref: function ref(el) {
return _this2._wrapper = el;
}
}, selected.map(this._renderToken), React__default.createElement(HintedInput, _extends({}, props, {
className: inputClassName,
inputRef: function inputRef(input) {
_this2._input = input;
_this2.props.inputRef(input);
},
onKeyDown: this._handleKeyDown,
placeholder: selected.length ? '' : placeholder,
style: {
backgroundColor: 'transparent',
border: 0,
boxShadow: 'none',
cursor: 'inherit',
outline: 'none',
padding: 0,
width: '100%',
zIndex: 1
}
}))))
/* eslint-enable jsx-a11y/no-static-element-interactions */
/* eslint-enable jsx-a11y/click-events-have-key-events */
);
};
return TypeaheadInputMulti;
}(React__default.Component);
_defineProperty(TypeaheadInputMulti, "propTypes", propTypes$6);
_defineProperty(TypeaheadInputMulti, "defaultProps", defaultProps$5);
var TypeaheadInputMulti$1 = withClassNames(TypeaheadInputMulti);
var TypeaheadInputSingle = withClassNames(hintContainer(Input));
var propTypes$7 = {
children: propTypes.string.isRequired,
highlightClassName: propTypes.string,
search: propTypes.string.isRequired
};
var defaultProps$6 = {
highlightClassName: 'rbt-highlight-text'
};
// React 16.0 added support for returning arrays and strings from components.
// TODO: Get rid of this once support for React < 16 is dropped.
function wrapChildren(children) {
/* istanbul ignore next */
return React__default.version >= '16' ? children : React__default.createElement("span", null, children);
}
/**
* Stripped-down version of https://github.com/helior/react-highlighter
*
* Results are already filtered by the time the component is used internally so
* we can safely ignore case and diacritical marks for the purposes of matching.
*/
var Highlighter =
/*#__PURE__*/
function (_React$PureComponent) {
_inheritsLoose(Highlighter, _React$PureComponent);
function Highlighter() {
return _React$PureComponent.apply(this, arguments) || this;
}
var _proto = Highlighter.prototype;
_proto.render = function render() {
var _this$props = this.props,
children = _this$props.children,
highlightClassName = _this$props.highlightClassName,
search = _this$props.search;
if (!search || !children) {
return wrapChildren(children);
}
var matchCount = 0;
var remaining = children;
var highlighterChildren = [];
while (remaining) {
var bounds = getMatchBounds(remaining, search); // No match anywhere in the remaining string, stop.
if (!bounds) {
highlighterChildren.push(remaining);
break;
} // Capture the string that leads up to a match.
var nonMatch = remaining.slice(0, bounds.start);
if (nonMatch) {
highlighterChildren.push(nonMatch);
} // Capture the matching string.
var match = remaining.slice(bounds.start, bounds.end);
highlighterChildren.push(React__default.createElement("mark", {
className: highlightClassName,
key: matchCount
}, match));
matchCount += 1; // And if there's anything left over, continue the loop.
remaining = remaining.slice(bounds.end);
}
return wrapChildren(highlighterChildren);
};
return Highlighter;
}(React__default.PureComponent);
_defineProperty(Highlighter, "propTypes", propTypes$7);
_defineProperty(Highlighter, "defaultProps", defaultProps$6);
function isElement(el) {
return el != null && typeof el === 'object' && el.nodeType === 1;
}
function canOverflow(overflow, skipOverflowHiddenElements) {
if (skipOverflowHiddenElements && overflow === 'hidden') {
return false;
}
return overflow !== 'visible' && overflow !== 'clip';
}
function isScrollable(el, skipOverflowHiddenElements) {
if (el.clientHeight < el.scrollHeight || el.clientWidth < el.scrollWidth) {
var style = getComputedStyle(el, null);
return canOverflow(style.overflowY, skipOverflowHiddenElements) || canOverflow(style.overflowX, skipOverflowHiddenElements);
}
return false;
}
function alignNearest(scrollingEdgeStart, scrollingEdgeEnd, scrollingSize, scrollingBorderStart, scrollingBorderEnd, elementEdgeStart, elementEdgeEnd, elementSize) {
if (elementEdgeStart < scrollingEdgeStart && elementEdgeEnd > scrollingEdgeEnd || elementEdgeStart > scrollingEdgeStart && elementEdgeEnd < scrollingEdgeEnd) {
return 0;
}
if (elementEdgeStart <= scrollingEdgeStart && elementSize <= scrollingSize || elementEdgeEnd >= scrollingEdgeEnd && elementSize >= scrollingSize) {
return elementEdgeStart - scrollingEdgeStart - scrollingBorderStart;
}
if (elementEdgeEnd > scrollingEdgeEnd && elementSize < scrollingSize || elementEdgeStart < scrollingEdgeStart && elementSize > scrollingSize) {
return elementEdgeEnd - scrollingEdgeEnd + scrollingBorderEnd;
}
return 0;
}
var compute = (function (target, options) {
var scrollMode = options.scrollMode,
block = options.block,
inline = options.inline,
boundary = options.boundary,
skipOverflowHiddenElements = options.skipOverflowHiddenElements;
var checkBoundary = typeof boundary === 'function' ? boundary : function (node) {
return node !== boundary;
};
if (!isElement(target)) {
throw new TypeError('Invalid target');
}
var scrollingElement = document.scrollingElement || document.documentElement;
var frames = [];
var cursor = target;
while (isElement(cursor) && checkBoundary(cursor)) {
cursor = cursor.parentNode;
if (cursor === scrollingElement) {
frames.push(cursor);
break;
}
if (cursor === document.body && isScrollable(cursor) && !isScrollable(document.documentElement)) {
continue;
}
if (isScrollable(cursor, skipOverflowHiddenElements)) {
frames.push(cursor);
}
}
var viewportWidth = window.visualViewport ? visualViewport.width : innerWidth;
var viewportHeight = window.visualViewport ? visualViewport.height : innerHeight;
var viewportX = window.scrollX || pageXOffset;
var viewportY = window.scrollY || pageYOffset;
var _target$getBoundingCl = target.getBoundingClientRect(),
targetHeight = _target$getBoundingCl.height,
targetWidth = _target$getBoundingCl.width,
targetTop = _target$getBoundingCl.top,
targetRight = _target$getBoundingCl.right,
targetBottom = _target$getBoundingCl.bottom,
targetLeft = _target$getBoundingCl.left;
var targetBlock = block === 'start' || block === 'nearest' ? targetTop : block === 'end' ? targetBottom : targetTop + targetHeight / 2;
var targetInline = inline === 'center' ? targetLeft + targetWidth / 2 : inline === 'end' ? targetRight : targetLeft;
var computations = [];
for (var index = 0; index < frames.length; index++) {
var frame = frames[index];
var _frame$getBoundingCli = frame.getBoundingClientRect(),
_height = _frame$getBoundingCli.height,
_width = _frame$getBoundingCli.width,
_top = _frame$getBoundingCli.top,
right = _frame$getBoundingCli.right,
bottom = _frame$getBoundingCli.bottom,
_left = _frame$getBoundingCli.left;
if (scrollMode === 'if-needed' && targetTop >= 0 && targetLeft >= 0 && targetBottom <= viewportHeight && targetRight <= viewportWidth && targetTop >= _top && targetBottom <= bottom && targetLeft >= _left && targetRight <= right) {
return computations;
}
var frameStyle = getComputedStyle(frame);
var borderLeft = parseInt(frameStyle.borderLeftWidth, 10);
var borderTop = parseInt(frameStyle.borderTopWidth, 10);
var borderRight = parseInt(frameStyle.borderRightWidth, 10);
var borderBottom = parseInt(frameStyle.borderBottomWidth, 10);
var blockScroll = 0;
var inlineScroll = 0;
var scrollbarWidth = 'offsetWidth' in frame ? frame.offsetWidth - frame.clientWidth - borderLeft - borderRight : 0;
var scrollbarHeight = 'offsetHeight' in frame ? frame.offsetHeight - frame.clientHeight - borderTop - borderBottom : 0;
if (scrollingElement === frame) {
if (block === 'start') {
blockScroll = targetBlock;
} else if (block === 'end') {
blockScroll = targetBlock - viewportHeight;
} else if (block === 'nearest') {
blockScroll = alignNearest(viewportY, viewportY + viewportHeight, viewportHeight, borderTop, borderBottom, viewportY + targetBlock, viewportY + targetBlock + targetHeight, targetHeight);
} else {
blockScroll = targetBlock - viewportHeight / 2;
}
if (inline === 'start') {
inlineScroll = targetInline;
} else if (inline === 'center') {
inlineScroll = targetInline - viewportWidth / 2;
} else if (inline === 'end') {
inlineScroll = targetInline - viewportWidth;
} else {
inlineScroll = alignNearest(viewportX, viewportX + viewportWidth, viewportWidth, borderLeft, borderRight, viewportX + targetInline, viewportX + targetInline + targetWidth, targetWidth);
}
blockScroll = Math.max(0, blockScroll + viewportY);
inlineScroll = Math.max(0, inlineScroll + viewportX);
} else {
if (block === 'start') {
blockScroll = targetBlock - _top - borderTop;
} else if (block === 'end') {
blockScroll = targetBlock - bottom + borderBottom + scrollbarHeight;
} else if (block === 'nearest') {
blockScroll = alignNearest(_top, bottom, _height, borderTop, borderBottom + scrollbarHeight, targetBlock, targetBlock + targetHeight, targetHeight);
} else {
blockScroll = targetBlock - (_top + _height / 2) + scrollbarHeight / 2;
}
if (inline === 'start') {
inlineScroll = targetInline - _left - borderLeft;
} else if (inline === 'center') {
inlineScroll = targetInline - (_left + _width / 2) + scrollbarWidth / 2;
} else if (inline === 'end') {
inlineScroll = targetInline - right + borderRight + scrollbarWidth;
} else {
inlineScroll = alignNearest(_left, right, _width, borderLeft, borderRight + scrollbarWidth, targetInline, targetInline + targetWidth, targetWidth);
}
var scrollLeft = frame.scrollLeft,
scrollTop = frame.scrollTop;
blockScroll = Math.max(0, Math.min(scrollTop + blockScroll, frame.scrollHeight - _height + scrollbarHeight));
inlineScroll = Math.max(0, Math.min(scrollLeft + inlineScroll, frame.scrollWidth - _width + scrollbarWidth));
targetBlock += scrollTop - blockScroll;
targetInline += scrollLeft - inlineScroll;
}
computations.push({
el: frame,
top: blockScroll,
left: inlineScroll
});
}
return computations;
});
function isOptionsObject(options) {
return options === Object(options) && Object.keys(options).length !== 0;
}
function defaultBehavior(actions, behavior) {
if (behavior === void 0) {
behavior = 'auto';
}
var canSmoothScroll = 'scrollBehavior' in document.body.style;
actions.forEach(function (_ref) {
var el = _ref.el,
top = _ref.top,
left = _ref.left;
if (el.scroll && canSmoothScroll) {
el.scroll({
top: top,
left: left,
behavior: behavior
});
} else {
el.scrollTop = top;
el.scrollLeft = left;
}
});
}
function getOptions(options) {
if (options === false) {
return {
block: 'end',
inline: 'nearest'
};
}
if (isOptionsObject(options)) {
return options;
}
return {
block: 'start',
inline: 'nearest'
};
}
function scrollIntoView(target, options) {
var targetIsDetached = !target.ownerDocument.documentElement.contains(target);
if (isOptionsObject(options) && typeof options.behavior === 'function') {
return options.behavior(targetIsDetached ? [] : compute(target, options));
}
if (targetIsDetached) {
return;
}
var computeOptions = getOptions(options);
return defaultBehavior(compute(target, computeOptions), computeOptions.behavior);
}
var propTypes$8 = {
option: propTypes.oneOfType([propTypes.object, propTypes.string]).isRequired,
position: propTypes.number
};
var menuItemContainer = function menuItemContainer(Component) {
var WrappedMenuItem =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(WrappedMenuItem, _React$Component);
function WrappedMenuItem() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_defineProperty(_assertThisInitialized(_this), "_handleClick", function (e) {
var _this$props = _this.props,
onMenuItemClick = _this$props.onMenuItemClick,
option = _this$props.option,
onClick = _this$props.onClick;
onMenuItemClick(option, e);
onClick && onClick(e);
});
_defineProperty(_assertThisInitialized(_this), "_maybeUpdateItem", function () {
var _this$props2 = _this.props,
activeIndex = _this$props2.activeIndex,
onActiveItemChange = _this$props2.onActiveItemChange,
onInitialItemChange = _this$props2.onInitialItemChange,
option = _this$props2.option,
position = _this$props2.position;
if (position === 0) {
onInitialItemChange(option);
}
if (position === activeIndex) {
onActiveItemChange(option); // Automatically scroll the menu as the user keys through it.
/* eslint-disable-next-line react/no-find-dom-node */
var node = reactDom.findDOMNode(_assertThisInitialized(_this));
node && scrollIntoView(node, {
block: 'nearest',
boundary: node.parentNode,
inline: 'nearest',
scrollMode: 'if-needed'
});
}
});
return _this;
}
var _proto = WrappedMenuItem.prototype;
_proto.componentDidMount = function componentDidMount() {
this._maybeUpdateItem();
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
this._maybeUpdateItem();
};
_proto.render = function render() {
var _this$props3 = this.props,
activeIndex = _this$props3.activeIndex,
id = _this$props3.id,
isOnlyResult = _this$props3.isOnlyResult,
label = _this$props3.label,
onActiveItemChange = _this$props3.onActiveItemChange,
onInitialItemChange = _this$props3.onInitialItemChange,
onMenuItemClick = _this$props3.onMenuItemClick,
option = _this$props3.option,
position = _this$props3.position,
props = _objectWithoutPropertiesLoose(_this$props3, ["activeIndex", "id", "isOnlyResult", "label", "onActiveItemChange", "onInitialItemChange", "onMenuItemClick", "option", "position"]);
var active = isOnlyResult || activeIndex === position;
return React__default.createElement(Component, _extends({}, props, {
active: active,
"aria-label": label,
"aria-selected": active,
id: getMenuItemId(id, position),
onClick: this._handleClick,
onMouseDown: preventInputBlur,
role: "option"
}));
};
return WrappedMenuItem;
}(React__default.Component);
_defineProperty(WrappedMenuItem, "displayName", "menuItemContainer(" + getDisplayName(Component) + ")");
WrappedMenuItem.propTypes = propTypes$8;
return withContext(WrappedMenuItem, ['activeIndex', 'id', 'isOnlyResult', 'onActiveItemChange', 'onInitialItemChange', 'onMenuItemClick']);
};
var propTypes$9 = {
onClick: propTypes.func
};
var defaultProps$7 = {
onClick: noop
};
var BaseMenuItem =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(BaseMenuItem, _React$Component);
function BaseMenuItem() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_defineProperty(_assertThisInitialized(_this), "_handleClick", function (e) {
var _this$props = _this.props,
disabled = _this$props.disabled,
onClick = _this$props.onClick;
e.preventDefault();
!disabled && onClick(e);
});
return _this;
}
var _proto = BaseMenuItem.prototype;
_proto.render = function render() {
var _this$props2 = this.props,
active = _this$props2.active,
children = _this$props2.children,
className = _this$props2.className,
disabled = _this$props2.disabled,
onClick = _this$props2.onClick,
onMouseDown = _this$props2.onMouseDown,
props = _objectWithoutPropertiesLoose(_this$props2, ["active", "children", "className", "disabled", "onClick", "onMouseDown"]);
var conditionalClassNames = {
active: active,
disabled: disabled
};
return (
/* eslint-disable jsx-a11y/anchor-is-valid */
React__default.createElement("li", _extends({}, props, {
className: classnames(conditionalClassNames, className)
}), React__default.createElement("a", {
className: classnames('dropdown-item', conditionalClassNames),
href: "#",
onClick: this._handleClick,
onMouseDown: onMouseDown
}, children))
/* eslint-enable jsx-a11y/anchor-is-valid */
);
};
return BaseMenuItem;
}(React__default.Component);
_defineProperty(BaseMenuItem, "propTypes", propTypes$9);
_defineProperty(BaseMenuItem, "defaultProps", defaultProps$7);
var MenuItem = menuItemContainer(BaseMenuItem);
var MenuDivider = function MenuDivider(props) {
return React__default.createElement("li", {
className: "divider dropdown-divider",
role: "separator"
});
};
var MenuHeader = function MenuHeader(props) {
return React__default.createElement("li", _extends({}, props, {
className: "dropdown-header"
}));
};
var propTypes$a = {
/**
* Message to display in the menu if there are no valid results.
*/
emptyLabel: propTypes.node,
/**
* Needed for accessibility.
*/
id: checkPropType(propTypes.oneOfType([propTypes.number, propTypes.string]), isRequiredForA11y),
/**
* Maximum height of the dropdown menu.
*/
maxHeight: propTypes.string
};
var defaultProps$8 = {
emptyLabel: 'No matches found.',
maxHeight: '300px'
};
/**
* Menu component that handles empty state when passed a set of results.
*/
var Menu =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Menu, _React$Component);
function Menu() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = Menu.prototype;
_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
var _this$props = this.props,
inputHeight = _this$props.inputHeight,
scheduleUpdate = _this$props.scheduleUpdate; // Update the menu position if the height of the input changes.
if (inputHeight !== prevProps.inputHeight) {
scheduleUpdate();
}
};
_proto.render = function render() {
var _this$props2 = this.props,
children = _this$props2.children,
className = _this$props2.className,
emptyLabel = _this$props2.emptyLabel,
id = _this$props2.id,
innerRef = _this$props2.innerRef,
maxHeight = _this$props2.maxHeight,
style = _this$props2.style,
text = _this$props2.text;
var contents = React.Children.count(children) === 0 ? React__default.createElement(BaseMenuItem, {
disabled: true
}, emptyLabel) : children;
return React__default.createElement("ul", {
className: classnames('rbt-menu', 'dropdown-menu', 'show', className),
id: id,
key: // Force a re-render if the text changes to ensure that menu
// positioning updates correctly.
text,
ref: innerRef,
role: "listbox",
style: _extends({}, style, {
display: 'block',
maxHeight: maxHeight,
overflow: 'auto'
})
}, contents);
};
return Menu;
}(React__default.Component);
_defineProperty(Menu, "propTypes", propTypes$a);
_defineProperty(Menu, "defaultProps", defaultProps$8);
_defineProperty(Menu, "Divider", MenuDivider);
_defineProperty(Menu, "Header", MenuHeader);
var propTypes$b = {
/**
* Provides the ability to specify a prefix before the user-entered text to
* indicate that the selection will be new. No-op unless `allowNew={true}`.
*/
newSelectionPrefix: propTypes.string,
/**
* Provides a hook for customized rendering of menu item contents.
*/
renderMenuItemChildren: propTypes.func
};
var defaultProps$9 = {
newSelectionPrefix: 'New selection: ',
renderMenuItemChildren: function renderMenuItemChildren(option, props, idx) {
return React__default.createElement(Highlighter, {
search: props.text
}, getOptionLabel(option, props.labelKey));
}
};
var TypeaheadMenu =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(TypeaheadMenu, _React$Component);
function TypeaheadMenu() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_defineProperty(_assertThisInitialized(_this), "_renderMenuItem", function (option, idx) {
var _this$props = _this.props,
labelKey = _this$props.labelKey,
newSelectionPrefix = _this$props.newSelectionPrefix,
renderMenuItemChildren = _this$props.renderMenuItemChildren,
text = _this$props.text;
var label = getOptionLabel(option, labelKey);
var menuItemProps = {
disabled: getOptionProperty(option, 'disabled'),
key: idx,
label: label,
option: option,
position: idx
};
if (option.customOption) {
return React__default.createElement(MenuItem, _extends({}, menuItemProps, {
className: "rbt-menu-custom-option",
label: newSelectionPrefix + label
}), newSelectionPrefix, React__default.createElement(Highlighter, {
search: text
}, label));
}
if (option.paginationOption) {
return [React__default.createElement(Menu.Divider, {
key: "pagination-item-divider"
}), React__default.createElement(MenuItem, _extends({}, menuItemProps, {
className: "rbt-menu-pagination-option",
key: "pagination-item"
}), label)];
}
return React__default.createElement(MenuItem, menuItemProps, renderMenuItemChildren(option, _this.props, idx));
});
return _this;
}
var _proto = TypeaheadMenu.prototype;
_proto.render = function render() {
var _this$props2 = this.props,
labelKey = _this$props2.labelKey,
newSelectionPrefix = _this$props2.newSelectionPrefix,
options = _this$props2.options,
renderMenuItemChildren = _this$props2.renderMenuItemChildren,
menuProps = _objectWithoutPropertiesLoose(_this$props2, ["labelKey", "newSelectionPrefix", "options", "renderMenuItemChildren"]);
return (// $FlowFixMe: Improve typing for spread props.
React__default.createElement(Menu, menuProps, options.map(this._renderMenuItem))
);
};
return TypeaheadMenu;
}(React__default.Component);
_defineProperty(TypeaheadMenu, "propTypes", propTypes$b);
_defineProperty(TypeaheadMenu, "defaultProps", defaultProps$9);
var propTypes$c = {
/**
* Specifies the size of the input.
*/
bsSize: propTypes.oneOf(['large', 'lg', 'small', 'sm']),
/**
* Displays a button to clear the input when there are selections.
*/
clearButton: propTypes.bool,
/**
* Props to be applied directly to the input. `onBlur`, `onChange`,
* `onFocus`, and `onKeyDown` are ignored.
*/
inputProps: checkPropType(propTypes.object, inputPropsType),
/**
* Bootstrap 4 only. Adds the `is-invalid` classname to the `form-control`.
*/
isInvalid: propTypes.bool,
/**
* Indicate whether an asynchronous data fetch is happening.
*/
isLoading: propTypes.bool,
/**
* Bootstrap 4 only. Adds the `is-valid` classname to the `form-control`.
*/
isValid: propTypes.bool,
/**
* Callback for custom input rendering.
*/
renderInput: propTypes.func,
/**
* Callback for custom menu rendering.
*/
renderMenu: propTypes.func
};
var defaultProps$a = {
clearButton: false,
inputProps: {},
isInvalid: false,
isLoading: false,
isValid: false,
renderMenu: function renderMenu(results, menuProps, state) {
return (// TODO: Merged props not registering correctly.
// $FlowFixMe
React__default.createElement(TypeaheadMenu, _extends({}, menuProps, {
labelKey: state.labelKey,
options: results,
text: state.text
}))
);
}
};
var TypeaheadComponent =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(TypeaheadComponent, _React$Component);
function TypeaheadComponent() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_defineProperty(_assertThisInitialized(_this), "_instance", null);
_defineProperty(_assertThisInitialized(_this), "getInstance", function () {
return _this._instance;
});
_defineProperty(_assertThisInitialized(_this), "_renderInput", function (inputProps, state) {
var _this$props = _this.props,
bsSize = _this$props.bsSize,
isInvalid = _this$props.isInvalid,
isValid = _this$props.isValid,
multiple = _this$props.multiple,
renderInput = _this$props.renderInput,
renderToken = _this$props.renderToken;
if (isFunction(renderInput)) {
return renderInput(inputProps, state);
}
var props = _extends({}, inputProps, {
bsSize: bsSize,
isInvalid: isInvalid,
isValid: isValid
});
return multiple ? React__default.createElement(TypeaheadInputMulti$1, _extends({}, props, {
labelKey: state.labelKey,
renderToken: renderToken,
selected: state.selected
})) : React__default.createElement(TypeaheadInputSingle, props);
});
_defineProperty(_assertThisInitialized(_this), "_renderMenu", function (results, menuProps, state) {
var _this$props2 = _this.props,
emptyLabel = _this$props2.emptyLabel,
id = _this$props2.id,
maxHeight = _this$props2.maxHeight,
newSelectionPrefix = _this$props2.newSelectionPrefix,
renderMenu = _this$props2.renderMenu,
renderMenuItemChildren = _this$props2.renderMenuItemChildren;
return renderMenu(results, _extends({}, menuProps, {
emptyLabel: emptyLabel,
id: id,
maxHeight: maxHeight,
newSelectionPrefix: newSelectionPrefix,
renderMenuItemChildren: renderMenuItemChildren
}), state);
});
_defineProperty(_assertThisInitialized(_this), "_renderAux", function (state) {
var _this$props3 = _this.props,
bsSize = _this$props3.bsSize,
clearButton = _this$props3.clearButton,
disabled = _this$props3.disabled,
isLoading = _this$props3.isLoading;
var onClear = state.onClear,
selected = state.selected;
var content;
if (isLoading) {
content = React__default.createElement(Loader, {
bsSize: bsSize
});
} else if (clearButton && !disabled && selected.length) {
content = React__default.createElement(ClearButton, {
bsSize: bsSize,
onClick: onClear,
onFocus: function onFocus(e) {
// Prevent the main input from auto-focusing again.
e.stopPropagation();
},
onMouseDown: preventInputBlur
});
}
return content ? React__default.createElement("div", {
className: classnames('rbt-aux', {
'rbt-aux-lg': bsSize === 'large' || bsSize === 'lg'
})
}, content) : null;
});
return _this;
}
var _proto = TypeaheadComponent.prototype;
_proto.render = function render() {
var _this2 = this;
var _this$props4 = this.props,
children = _this$props4.children,
className = _this$props4.className,
style = _this$props4.style;
return React__default.createElement(Typeahead, _extends({}, this.props, {
ref: function ref(instance) {
return _this2._instance = instance;
}
}), function (_ref) {
var getInputProps = _ref.getInputProps,
getOverlayProps = _ref.getOverlayProps,
state = _ref.state;
var auxContent = _this2._renderAux(state);
return React__default.createElement("div", {
className: classnames('rbt', {
'has-aux': !!auxContent
}, className),
style: _extends({
outline: 'none',
position: 'relative'
}, style),
tabIndex: -1
}, _this2._renderInput(getInputProps(_this2.props.inputProps), state), React__default.createElement(Overlay, getOverlayProps(_this2.props), function (menuProps) {
return _this2._renderMenu(state.results, menuProps, state);
}), auxContent, isFunction(children) ? children(state) : children);
});
};
return TypeaheadComponent;
}(React__default.Component);
_defineProperty(TypeaheadComponent, "propTypes", propTypes$c);
_defineProperty(TypeaheadComponent, "defaultProps", defaultProps$a);
var AsyncTypeahead_react = asyncContainer(TypeaheadComponent);
// Components
exports.AsyncTypeahead = AsyncTypeahead_react;
exports.Highlighter = Highlighter;
exports.Menu = Menu;
exports.MenuItem = MenuItem;
exports.Token = Token$1;
exports.Typeahead = TypeaheadComponent;
exports.TypeaheadMenu = TypeaheadMenu;
exports.asyncContainer = asyncContainer;
exports.hintContainer = hintContainer;
exports.menuItemContainer = menuItemContainer;
exports.tokenContainer = tokenContainer;
Object.defineProperty(exports, '__esModule', { value: true });
}));