UNPKG

199 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
3 typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
4 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Downshift = {}, global.React));
5}(this, (function (exports, react) { 'use strict';
6
7 function _objectWithoutPropertiesLoose(source, excluded) {
8 if (source == null) return {};
9 var target = {};
10 var sourceKeys = Object.keys(source);
11 var key, i;
12
13 for (i = 0; i < sourceKeys.length; i++) {
14 key = sourceKeys[i];
15 if (excluded.indexOf(key) >= 0) continue;
16 target[key] = source[key];
17 }
18
19 return target;
20 }
21
22 function _extends() {
23 _extends = Object.assign || function (target) {
24 for (var i = 1; i < arguments.length; i++) {
25 var source = arguments[i];
26
27 for (var key in source) {
28 if (Object.prototype.hasOwnProperty.call(source, key)) {
29 target[key] = source[key];
30 }
31 }
32 }
33
34 return target;
35 };
36
37 return _extends.apply(this, arguments);
38 }
39
40 function _assertThisInitialized(self) {
41 if (self === void 0) {
42 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
43 }
44
45 return self;
46 }
47
48 function _inheritsLoose(subClass, superClass) {
49 subClass.prototype = Object.create(superClass.prototype);
50 subClass.prototype.constructor = subClass;
51 subClass.__proto__ = superClass;
52 }
53
54 function createCommonjsModule(fn) {
55 var module = { exports: {} };
56 return fn(module, module.exports), module.exports;
57 }
58
59 /** @license React v16.13.1
60 * react-is.development.js
61 *
62 * Copyright (c) Facebook, Inc. and its affiliates.
63 *
64 * This source code is licensed under the MIT license found in the
65 * LICENSE file in the root directory of this source tree.
66 */
67 var reactIs_development = createCommonjsModule(function (module, exports) {
68
69 {
70 (function () {
71 // nor polyfill, then a plain number is used for performance.
72
73 var hasSymbol = typeof Symbol === 'function' && Symbol.for;
74 var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
75 var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
76 var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
77 var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
78 var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
79 var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
80 var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary
81 // (unstable) APIs that have been removed. Can we remove the symbols?
82
83 var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
84 var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
85 var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
86 var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
87 var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;
88 var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
89 var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
90 var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;
91 var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;
92 var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;
93 var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;
94
95 function isValidElementType(type) {
96 return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
97 type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_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 || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);
98 }
99
100 function typeOf(object) {
101 if (typeof object === 'object' && object !== null) {
102 var $$typeof = object.$$typeof;
103
104 switch ($$typeof) {
105 case REACT_ELEMENT_TYPE:
106 var type = object.type;
107
108 switch (type) {
109 case REACT_ASYNC_MODE_TYPE:
110 case REACT_CONCURRENT_MODE_TYPE:
111 case REACT_FRAGMENT_TYPE:
112 case REACT_PROFILER_TYPE:
113 case REACT_STRICT_MODE_TYPE:
114 case REACT_SUSPENSE_TYPE:
115 return type;
116
117 default:
118 var $$typeofType = type && type.$$typeof;
119
120 switch ($$typeofType) {
121 case REACT_CONTEXT_TYPE:
122 case REACT_FORWARD_REF_TYPE:
123 case REACT_LAZY_TYPE:
124 case REACT_MEMO_TYPE:
125 case REACT_PROVIDER_TYPE:
126 return $$typeofType;
127
128 default:
129 return $$typeof;
130 }
131
132 }
133
134 case REACT_PORTAL_TYPE:
135 return $$typeof;
136 }
137 }
138
139 return undefined;
140 } // AsyncMode is deprecated along with isAsyncMode
141
142
143 var AsyncMode = REACT_ASYNC_MODE_TYPE;
144 var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
145 var ContextConsumer = REACT_CONTEXT_TYPE;
146 var ContextProvider = REACT_PROVIDER_TYPE;
147 var Element = REACT_ELEMENT_TYPE;
148 var ForwardRef = REACT_FORWARD_REF_TYPE;
149 var Fragment = REACT_FRAGMENT_TYPE;
150 var Lazy = REACT_LAZY_TYPE;
151 var Memo = REACT_MEMO_TYPE;
152 var Portal = REACT_PORTAL_TYPE;
153 var Profiler = REACT_PROFILER_TYPE;
154 var StrictMode = REACT_STRICT_MODE_TYPE;
155 var Suspense = REACT_SUSPENSE_TYPE;
156 var hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated
157
158 function isAsyncMode(object) {
159 {
160 if (!hasWarnedAboutDeprecatedIsAsyncMode) {
161 hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint
162
163 console['warn']('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.');
164 }
165 }
166 return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
167 }
168
169 function isConcurrentMode(object) {
170 return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
171 }
172
173 function isContextConsumer(object) {
174 return typeOf(object) === REACT_CONTEXT_TYPE;
175 }
176
177 function isContextProvider(object) {
178 return typeOf(object) === REACT_PROVIDER_TYPE;
179 }
180
181 function isElement(object) {
182 return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
183 }
184
185 function isForwardRef(object) {
186 return typeOf(object) === REACT_FORWARD_REF_TYPE;
187 }
188
189 function isFragment(object) {
190 return typeOf(object) === REACT_FRAGMENT_TYPE;
191 }
192
193 function isLazy(object) {
194 return typeOf(object) === REACT_LAZY_TYPE;
195 }
196
197 function isMemo(object) {
198 return typeOf(object) === REACT_MEMO_TYPE;
199 }
200
201 function isPortal(object) {
202 return typeOf(object) === REACT_PORTAL_TYPE;
203 }
204
205 function isProfiler(object) {
206 return typeOf(object) === REACT_PROFILER_TYPE;
207 }
208
209 function isStrictMode(object) {
210 return typeOf(object) === REACT_STRICT_MODE_TYPE;
211 }
212
213 function isSuspense(object) {
214 return typeOf(object) === REACT_SUSPENSE_TYPE;
215 }
216
217 exports.AsyncMode = AsyncMode;
218 exports.ConcurrentMode = ConcurrentMode;
219 exports.ContextConsumer = ContextConsumer;
220 exports.ContextProvider = ContextProvider;
221 exports.Element = Element;
222 exports.ForwardRef = ForwardRef;
223 exports.Fragment = Fragment;
224 exports.Lazy = Lazy;
225 exports.Memo = Memo;
226 exports.Portal = Portal;
227 exports.Profiler = Profiler;
228 exports.StrictMode = StrictMode;
229 exports.Suspense = Suspense;
230 exports.isAsyncMode = isAsyncMode;
231 exports.isConcurrentMode = isConcurrentMode;
232 exports.isContextConsumer = isContextConsumer;
233 exports.isContextProvider = isContextProvider;
234 exports.isElement = isElement;
235 exports.isForwardRef = isForwardRef;
236 exports.isFragment = isFragment;
237 exports.isLazy = isLazy;
238 exports.isMemo = isMemo;
239 exports.isPortal = isPortal;
240 exports.isProfiler = isProfiler;
241 exports.isStrictMode = isStrictMode;
242 exports.isSuspense = isSuspense;
243 exports.isValidElementType = isValidElementType;
244 exports.typeOf = typeOf;
245 })();
246 }
247 });
248
249 var reactIs = createCommonjsModule(function (module) {
250
251 {
252 module.exports = reactIs_development;
253 }
254 });
255
256 /*
257 object-assign
258 (c) Sindre Sorhus
259 @license MIT
260 */
261 /* eslint-disable no-unused-vars */
262
263 var getOwnPropertySymbols = Object.getOwnPropertySymbols;
264 var hasOwnProperty = Object.prototype.hasOwnProperty;
265 var propIsEnumerable = Object.prototype.propertyIsEnumerable;
266
267 function toObject(val) {
268 if (val === null || val === undefined) {
269 throw new TypeError('Object.assign cannot be called with null or undefined');
270 }
271
272 return Object(val);
273 }
274
275 function shouldUseNative() {
276 try {
277 if (!Object.assign) {
278 return false;
279 } // Detect buggy property enumeration order in older V8 versions.
280 // https://bugs.chromium.org/p/v8/issues/detail?id=4118
281
282
283 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
284
285 test1[5] = 'de';
286
287 if (Object.getOwnPropertyNames(test1)[0] === '5') {
288 return false;
289 } // https://bugs.chromium.org/p/v8/issues/detail?id=3056
290
291
292 var test2 = {};
293
294 for (var i = 0; i < 10; i++) {
295 test2['_' + String.fromCharCode(i)] = i;
296 }
297
298 var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
299 return test2[n];
300 });
301
302 if (order2.join('') !== '0123456789') {
303 return false;
304 } // https://bugs.chromium.org/p/v8/issues/detail?id=3056
305
306
307 var test3 = {};
308 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
309 test3[letter] = letter;
310 });
311
312 if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') {
313 return false;
314 }
315
316 return true;
317 } catch (err) {
318 // We don't expect any of the above to throw, but better to be safe.
319 return false;
320 }
321 }
322
323 var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
324 var from;
325 var to = toObject(target);
326 var symbols;
327
328 for (var s = 1; s < arguments.length; s++) {
329 from = Object(arguments[s]);
330
331 for (var key in from) {
332 if (hasOwnProperty.call(from, key)) {
333 to[key] = from[key];
334 }
335 }
336
337 if (getOwnPropertySymbols) {
338 symbols = getOwnPropertySymbols(from);
339
340 for (var i = 0; i < symbols.length; i++) {
341 if (propIsEnumerable.call(from, symbols[i])) {
342 to[symbols[i]] = from[symbols[i]];
343 }
344 }
345 }
346 }
347
348 return to;
349 };
350
351 /**
352 * Copyright (c) 2013-present, Facebook, Inc.
353 *
354 * This source code is licensed under the MIT license found in the
355 * LICENSE file in the root directory of this source tree.
356 */
357
358 var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
359 var ReactPropTypesSecret_1 = ReactPropTypesSecret;
360
361 /**
362 * Copyright (c) 2013-present, Facebook, Inc.
363 *
364 * This source code is licensed under the MIT license found in the
365 * LICENSE file in the root directory of this source tree.
366 */
367
368 var printWarning = function () {};
369
370 {
371 var ReactPropTypesSecret$1 = ReactPropTypesSecret_1;
372 var loggedTypeFailures = {};
373 var has = Function.call.bind(Object.prototype.hasOwnProperty);
374
375 printWarning = function (text) {
376 var message = 'Warning: ' + text;
377
378 if (typeof console !== 'undefined') {
379 console.error(message);
380 }
381
382 try {
383 // --- Welcome to debugging React ---
384 // This error was thrown as a convenience so that you can use this stack
385 // to find the callsite that caused this warning to fire.
386 throw new Error(message);
387 } catch (x) {}
388 };
389 }
390 /**
391 * Assert that the values match with the type specs.
392 * Error messages are memorized and will only be shown once.
393 *
394 * @param {object} typeSpecs Map of name to a ReactPropType
395 * @param {object} values Runtime values that need to be type-checked
396 * @param {string} location e.g. "prop", "context", "child context"
397 * @param {string} componentName Name of the component for error messages.
398 * @param {?Function} getStack Returns the component stack.
399 * @private
400 */
401
402
403 function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
404 {
405 for (var typeSpecName in typeSpecs) {
406 if (has(typeSpecs, typeSpecName)) {
407 var error; // Prop type validation may throw. In case they do, we don't want to
408 // fail the render phase where it didn't fail before. So we log it.
409 // After these have been cleaned up, we'll let them throw.
410
411 try {
412 // This is intentionally an invariant that gets caught. It's the same
413 // behavior as without this statement except with a better message.
414 if (typeof typeSpecs[typeSpecName] !== 'function') {
415 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] + '`.');
416 err.name = 'Invariant Violation';
417 throw err;
418 }
419
420 error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1);
421 } catch (ex) {
422 error = ex;
423 }
424
425 if (error && !(error instanceof Error)) {
426 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).');
427 }
428
429 if (error instanceof Error && !(error.message in loggedTypeFailures)) {
430 // Only monitor this failure once because there tends to be a lot of the
431 // same error.
432 loggedTypeFailures[error.message] = true;
433 var stack = getStack ? getStack() : '';
434 printWarning('Failed ' + location + ' type: ' + error.message + (stack != null ? stack : ''));
435 }
436 }
437 }
438 }
439 }
440 /**
441 * Resets warning cache when testing.
442 *
443 * @private
444 */
445
446
447 checkPropTypes.resetWarningCache = function () {
448 {
449 loggedTypeFailures = {};
450 }
451 };
452
453 var checkPropTypes_1 = checkPropTypes;
454
455 /**
456 * Copyright (c) 2013-present, Facebook, Inc.
457 *
458 * This source code is licensed under the MIT license found in the
459 * LICENSE file in the root directory of this source tree.
460 */
461
462 var has$1 = Function.call.bind(Object.prototype.hasOwnProperty);
463
464 var printWarning$1 = function () {};
465
466 {
467 printWarning$1 = function (text) {
468 var message = 'Warning: ' + text;
469
470 if (typeof console !== 'undefined') {
471 console.error(message);
472 }
473
474 try {
475 // --- Welcome to debugging React ---
476 // This error was thrown as a convenience so that you can use this stack
477 // to find the callsite that caused this warning to fire.
478 throw new Error(message);
479 } catch (x) {}
480 };
481 }
482
483 function emptyFunctionThatReturnsNull() {
484 return null;
485 }
486
487 var factoryWithTypeCheckers = function (isValidElement, throwOnDirectAccess) {
488 /* global Symbol */
489 var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
490 var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
491
492 /**
493 * Returns the iterator method function contained on the iterable object.
494 *
495 * Be sure to invoke the function with the iterable as context:
496 *
497 * var iteratorFn = getIteratorFn(myIterable);
498 * if (iteratorFn) {
499 * var iterator = iteratorFn.call(myIterable);
500 * ...
501 * }
502 *
503 * @param {?object} maybeIterable
504 * @return {?function}
505 */
506
507 function getIteratorFn(maybeIterable) {
508 var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
509
510 if (typeof iteratorFn === 'function') {
511 return iteratorFn;
512 }
513 }
514 /**
515 * Collection of methods that allow declaration and validation of props that are
516 * supplied to React components. Example usage:
517 *
518 * var Props = require('ReactPropTypes');
519 * var MyArticle = React.createClass({
520 * propTypes: {
521 * // An optional string prop named "description".
522 * description: Props.string,
523 *
524 * // A required enum prop named "category".
525 * category: Props.oneOf(['News','Photos']).isRequired,
526 *
527 * // A prop named "dialog" that requires an instance of Dialog.
528 * dialog: Props.instanceOf(Dialog).isRequired
529 * },
530 * render: function() { ... }
531 * });
532 *
533 * A more formal specification of how these methods are used:
534 *
535 * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
536 * decl := ReactPropTypes.{type}(.isRequired)?
537 *
538 * Each and every declaration produces a function with the same signature. This
539 * allows the creation of custom validation functions. For example:
540 *
541 * var MyLink = React.createClass({
542 * propTypes: {
543 * // An optional string or URI prop named "href".
544 * href: function(props, propName, componentName) {
545 * var propValue = props[propName];
546 * if (propValue != null && typeof propValue !== 'string' &&
547 * !(propValue instanceof URI)) {
548 * return new Error(
549 * 'Expected a string or an URI for ' + propName + ' in ' +
550 * componentName
551 * );
552 * }
553 * }
554 * },
555 * render: function() {...}
556 * });
557 *
558 * @internal
559 */
560
561
562 var ANONYMOUS = '<<anonymous>>'; // Important!
563 // Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
564
565 var ReactPropTypes = {
566 array: createPrimitiveTypeChecker('array'),
567 bool: createPrimitiveTypeChecker('boolean'),
568 func: createPrimitiveTypeChecker('function'),
569 number: createPrimitiveTypeChecker('number'),
570 object: createPrimitiveTypeChecker('object'),
571 string: createPrimitiveTypeChecker('string'),
572 symbol: createPrimitiveTypeChecker('symbol'),
573 any: createAnyTypeChecker(),
574 arrayOf: createArrayOfTypeChecker,
575 element: createElementTypeChecker(),
576 elementType: createElementTypeTypeChecker(),
577 instanceOf: createInstanceTypeChecker,
578 node: createNodeChecker(),
579 objectOf: createObjectOfTypeChecker,
580 oneOf: createEnumTypeChecker,
581 oneOfType: createUnionTypeChecker,
582 shape: createShapeTypeChecker,
583 exact: createStrictShapeTypeChecker
584 };
585 /**
586 * inlined Object.is polyfill to avoid requiring consumers ship their own
587 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
588 */
589
590 /*eslint-disable no-self-compare*/
591
592 function is(x, y) {
593 // SameValue algorithm
594 if (x === y) {
595 // Steps 1-5, 7-10
596 // Steps 6.b-6.e: +0 != -0
597 return x !== 0 || 1 / x === 1 / y;
598 } else {
599 // Step 6.a: NaN == NaN
600 return x !== x && y !== y;
601 }
602 }
603 /*eslint-enable no-self-compare*/
604
605 /**
606 * We use an Error-like object for backward compatibility as people may call
607 * PropTypes directly and inspect their output. However, we don't use real
608 * Errors anymore. We don't inspect their stack anyway, and creating them
609 * is prohibitively expensive if they are created too often, such as what
610 * happens in oneOfType() for any type before the one that matched.
611 */
612
613
614 function PropTypeError(message) {
615 this.message = message;
616 this.stack = '';
617 } // Make `instanceof Error` still work for returned errors.
618
619
620 PropTypeError.prototype = Error.prototype;
621
622 function createChainableTypeChecker(validate) {
623 {
624 var manualPropTypeCallCache = {};
625 var manualPropTypeWarningCount = 0;
626 }
627
628 function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
629 componentName = componentName || ANONYMOUS;
630 propFullName = propFullName || propName;
631
632 if (secret !== ReactPropTypesSecret_1) {
633 if (throwOnDirectAccess) {
634 // New behavior only for users of `prop-types` package
635 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');
636 err.name = 'Invariant Violation';
637 throw err;
638 } else if ( typeof console !== 'undefined') {
639 // Old behavior for people using React.PropTypes
640 var cacheKey = componentName + ':' + propName;
641
642 if (!manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors
643 manualPropTypeWarningCount < 3) {
644 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.');
645 manualPropTypeCallCache[cacheKey] = true;
646 manualPropTypeWarningCount++;
647 }
648 }
649 }
650
651 if (props[propName] == null) {
652 if (isRequired) {
653 if (props[propName] === null) {
654 return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
655 }
656
657 return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
658 }
659
660 return null;
661 } else {
662 return validate(props, propName, componentName, location, propFullName);
663 }
664 }
665
666 var chainedCheckType = checkType.bind(null, false);
667 chainedCheckType.isRequired = checkType.bind(null, true);
668 return chainedCheckType;
669 }
670
671 function createPrimitiveTypeChecker(expectedType) {
672 function validate(props, propName, componentName, location, propFullName, secret) {
673 var propValue = props[propName];
674 var propType = getPropType(propValue);
675
676 if (propType !== expectedType) {
677 // `propValue` being instance of, say, date/regexp, pass the 'object'
678 // check, but we can offer a more precise error message here rather than
679 // 'of type `object`'.
680 var preciseType = getPreciseType(propValue);
681 return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
682 }
683
684 return null;
685 }
686
687 return createChainableTypeChecker(validate);
688 }
689
690 function createAnyTypeChecker() {
691 return createChainableTypeChecker(emptyFunctionThatReturnsNull);
692 }
693
694 function createArrayOfTypeChecker(typeChecker) {
695 function validate(props, propName, componentName, location, propFullName) {
696 if (typeof typeChecker !== 'function') {
697 return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
698 }
699
700 var propValue = props[propName];
701
702 if (!Array.isArray(propValue)) {
703 var propType = getPropType(propValue);
704 return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
705 }
706
707 for (var i = 0; i < propValue.length; i++) {
708 var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret_1);
709
710 if (error instanceof Error) {
711 return error;
712 }
713 }
714
715 return null;
716 }
717
718 return createChainableTypeChecker(validate);
719 }
720
721 function createElementTypeChecker() {
722 function validate(props, propName, componentName, location, propFullName) {
723 var propValue = props[propName];
724
725 if (!isValidElement(propValue)) {
726 var propType = getPropType(propValue);
727 return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
728 }
729
730 return null;
731 }
732
733 return createChainableTypeChecker(validate);
734 }
735
736 function createElementTypeTypeChecker() {
737 function validate(props, propName, componentName, location, propFullName) {
738 var propValue = props[propName];
739
740 if (!reactIs.isValidElementType(propValue)) {
741 var propType = getPropType(propValue);
742 return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.'));
743 }
744
745 return null;
746 }
747
748 return createChainableTypeChecker(validate);
749 }
750
751 function createInstanceTypeChecker(expectedClass) {
752 function validate(props, propName, componentName, location, propFullName) {
753 if (!(props[propName] instanceof expectedClass)) {
754 var expectedClassName = expectedClass.name || ANONYMOUS;
755 var actualClassName = getClassName(props[propName]);
756 return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
757 }
758
759 return null;
760 }
761
762 return createChainableTypeChecker(validate);
763 }
764
765 function createEnumTypeChecker(expectedValues) {
766 if (!Array.isArray(expectedValues)) {
767 {
768 if (arguments.length > 1) {
769 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]).');
770 } else {
771 printWarning$1('Invalid argument supplied to oneOf, expected an array.');
772 }
773 }
774
775 return emptyFunctionThatReturnsNull;
776 }
777
778 function validate(props, propName, componentName, location, propFullName) {
779 var propValue = props[propName];
780
781 for (var i = 0; i < expectedValues.length; i++) {
782 if (is(propValue, expectedValues[i])) {
783 return null;
784 }
785 }
786
787 var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {
788 var type = getPreciseType(value);
789
790 if (type === 'symbol') {
791 return String(value);
792 }
793
794 return value;
795 });
796 return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
797 }
798
799 return createChainableTypeChecker(validate);
800 }
801
802 function createObjectOfTypeChecker(typeChecker) {
803 function validate(props, propName, componentName, location, propFullName) {
804 if (typeof typeChecker !== 'function') {
805 return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
806 }
807
808 var propValue = props[propName];
809 var propType = getPropType(propValue);
810
811 if (propType !== 'object') {
812 return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
813 }
814
815 for (var key in propValue) {
816 if (has$1(propValue, key)) {
817 var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
818
819 if (error instanceof Error) {
820 return error;
821 }
822 }
823 }
824
825 return null;
826 }
827
828 return createChainableTypeChecker(validate);
829 }
830
831 function createUnionTypeChecker(arrayOfTypeCheckers) {
832 if (!Array.isArray(arrayOfTypeCheckers)) {
833 printWarning$1('Invalid argument supplied to oneOfType, expected an instance of array.') ;
834 return emptyFunctionThatReturnsNull;
835 }
836
837 for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
838 var checker = arrayOfTypeCheckers[i];
839
840 if (typeof checker !== 'function') {
841 printWarning$1('Invalid argument supplied to oneOfType. Expected an array of check functions, but ' + 'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.');
842 return emptyFunctionThatReturnsNull;
843 }
844 }
845
846 function validate(props, propName, componentName, location, propFullName) {
847 for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
848 var checker = arrayOfTypeCheckers[i];
849
850 if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret_1) == null) {
851 return null;
852 }
853 }
854
855 return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
856 }
857
858 return createChainableTypeChecker(validate);
859 }
860
861 function createNodeChecker() {
862 function validate(props, propName, componentName, location, propFullName) {
863 if (!isNode(props[propName])) {
864 return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
865 }
866
867 return null;
868 }
869
870 return createChainableTypeChecker(validate);
871 }
872
873 function createShapeTypeChecker(shapeTypes) {
874 function validate(props, propName, componentName, location, propFullName) {
875 var propValue = props[propName];
876 var propType = getPropType(propValue);
877
878 if (propType !== 'object') {
879 return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
880 }
881
882 for (var key in shapeTypes) {
883 var checker = shapeTypes[key];
884
885 if (!checker) {
886 continue;
887 }
888
889 var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
890
891 if (error) {
892 return error;
893 }
894 }
895
896 return null;
897 }
898
899 return createChainableTypeChecker(validate);
900 }
901
902 function createStrictShapeTypeChecker(shapeTypes) {
903 function validate(props, propName, componentName, location, propFullName) {
904 var propValue = props[propName];
905 var propType = getPropType(propValue);
906
907 if (propType !== 'object') {
908 return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
909 } // We need to check all keys in case some are required but missing from
910 // props.
911
912
913 var allKeys = objectAssign({}, props[propName], shapeTypes);
914
915 for (var key in allKeys) {
916 var checker = shapeTypes[key];
917
918 if (!checker) {
919 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, ' '));
920 }
921
922 var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
923
924 if (error) {
925 return error;
926 }
927 }
928
929 return null;
930 }
931
932 return createChainableTypeChecker(validate);
933 }
934
935 function isNode(propValue) {
936 switch (typeof propValue) {
937 case 'number':
938 case 'string':
939 case 'undefined':
940 return true;
941
942 case 'boolean':
943 return !propValue;
944
945 case 'object':
946 if (Array.isArray(propValue)) {
947 return propValue.every(isNode);
948 }
949
950 if (propValue === null || isValidElement(propValue)) {
951 return true;
952 }
953
954 var iteratorFn = getIteratorFn(propValue);
955
956 if (iteratorFn) {
957 var iterator = iteratorFn.call(propValue);
958 var step;
959
960 if (iteratorFn !== propValue.entries) {
961 while (!(step = iterator.next()).done) {
962 if (!isNode(step.value)) {
963 return false;
964 }
965 }
966 } else {
967 // Iterator will provide entry [k,v] tuples rather than values.
968 while (!(step = iterator.next()).done) {
969 var entry = step.value;
970
971 if (entry) {
972 if (!isNode(entry[1])) {
973 return false;
974 }
975 }
976 }
977 }
978 } else {
979 return false;
980 }
981
982 return true;
983
984 default:
985 return false;
986 }
987 }
988
989 function isSymbol(propType, propValue) {
990 // Native Symbol.
991 if (propType === 'symbol') {
992 return true;
993 } // falsy value can't be a Symbol
994
995
996 if (!propValue) {
997 return false;
998 } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
999
1000
1001 if (propValue['@@toStringTag'] === 'Symbol') {
1002 return true;
1003 } // Fallback for non-spec compliant Symbols which are polyfilled.
1004
1005
1006 if (typeof Symbol === 'function' && propValue instanceof Symbol) {
1007 return true;
1008 }
1009
1010 return false;
1011 } // Equivalent of `typeof` but with special handling for array and regexp.
1012
1013
1014 function getPropType(propValue) {
1015 var propType = typeof propValue;
1016
1017 if (Array.isArray(propValue)) {
1018 return 'array';
1019 }
1020
1021 if (propValue instanceof RegExp) {
1022 // Old webkits (at least until Android 4.0) return 'function' rather than
1023 // 'object' for typeof a RegExp. We'll normalize this here so that /bla/
1024 // passes PropTypes.object.
1025 return 'object';
1026 }
1027
1028 if (isSymbol(propType, propValue)) {
1029 return 'symbol';
1030 }
1031
1032 return propType;
1033 } // This handles more types than `getPropType`. Only used for error messages.
1034 // See `createPrimitiveTypeChecker`.
1035
1036
1037 function getPreciseType(propValue) {
1038 if (typeof propValue === 'undefined' || propValue === null) {
1039 return '' + propValue;
1040 }
1041
1042 var propType = getPropType(propValue);
1043
1044 if (propType === 'object') {
1045 if (propValue instanceof Date) {
1046 return 'date';
1047 } else if (propValue instanceof RegExp) {
1048 return 'regexp';
1049 }
1050 }
1051
1052 return propType;
1053 } // Returns a string that is postfixed to a warning about an invalid type.
1054 // For example, "undefined" or "of type array"
1055
1056
1057 function getPostfixForTypeWarning(value) {
1058 var type = getPreciseType(value);
1059
1060 switch (type) {
1061 case 'array':
1062 case 'object':
1063 return 'an ' + type;
1064
1065 case 'boolean':
1066 case 'date':
1067 case 'regexp':
1068 return 'a ' + type;
1069
1070 default:
1071 return type;
1072 }
1073 } // Returns class name of the object, if any.
1074
1075
1076 function getClassName(propValue) {
1077 if (!propValue.constructor || !propValue.constructor.name) {
1078 return ANONYMOUS;
1079 }
1080
1081 return propValue.constructor.name;
1082 }
1083
1084 ReactPropTypes.checkPropTypes = checkPropTypes_1;
1085 ReactPropTypes.resetWarningCache = checkPropTypes_1.resetWarningCache;
1086 ReactPropTypes.PropTypes = ReactPropTypes;
1087 return ReactPropTypes;
1088 };
1089
1090 /**
1091 * Copyright (c) 2013-present, Facebook, Inc.
1092 *
1093 * This source code is licensed under the MIT license found in the
1094 * LICENSE file in the root directory of this source tree.
1095 */
1096 var propTypes = createCommonjsModule(function (module) {
1097 {
1098 var ReactIs = reactIs; // By explicitly using `prop-types` you are opting into new development behavior.
1099 // http://fb.me/prop-types-in-prod
1100
1101 var throwOnDirectAccess = true;
1102 module.exports = factoryWithTypeCheckers(ReactIs.isElement, throwOnDirectAccess);
1103 }
1104 });
1105
1106 /** @license React v17.0.1
1107 * react-is.production.min.js
1108 *
1109 * Copyright (c) Facebook, Inc. and its affiliates.
1110 *
1111 * This source code is licensed under the MIT license found in the
1112 * LICENSE file in the root directory of this source tree.
1113 */
1114
1115 if ("function" === typeof Symbol && Symbol.for) {
1116 var x = Symbol.for;
1117 x("react.element");
1118 x("react.portal");
1119 x("react.fragment");
1120 x("react.strict_mode");
1121 x("react.profiler");
1122 x("react.provider");
1123 x("react.context");
1124 x("react.forward_ref");
1125 x("react.suspense");
1126 x("react.suspense_list");
1127 x("react.memo");
1128 x("react.lazy");
1129 x("react.block");
1130 x("react.server.block");
1131 x("react.fundamental");
1132 x("react.debug_trace_mode");
1133 x("react.legacy_hidden");
1134 }
1135
1136 /** @license React v17.0.1
1137 * react-is.development.js
1138 *
1139 * Copyright (c) Facebook, Inc. and its affiliates.
1140 *
1141 * This source code is licensed under the MIT license found in the
1142 * LICENSE file in the root directory of this source tree.
1143 */
1144 var reactIs_development$1 = createCommonjsModule(function (module, exports) {
1145
1146 {
1147 (function () {
1148 // When adding new symbols to this file,
1149 // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
1150 // The Symbol used to tag the ReactElement-like types. If there is no native Symbol
1151 // nor polyfill, then a plain number is used for performance.
1152
1153 var REACT_ELEMENT_TYPE = 0xeac7;
1154 var REACT_PORTAL_TYPE = 0xeaca;
1155 var REACT_FRAGMENT_TYPE = 0xeacb;
1156 var REACT_STRICT_MODE_TYPE = 0xeacc;
1157 var REACT_PROFILER_TYPE = 0xead2;
1158 var REACT_PROVIDER_TYPE = 0xeacd;
1159 var REACT_CONTEXT_TYPE = 0xeace;
1160 var REACT_FORWARD_REF_TYPE = 0xead0;
1161 var REACT_SUSPENSE_TYPE = 0xead1;
1162 var REACT_SUSPENSE_LIST_TYPE = 0xead8;
1163 var REACT_MEMO_TYPE = 0xead3;
1164 var REACT_LAZY_TYPE = 0xead4;
1165 var REACT_BLOCK_TYPE = 0xead9;
1166 var REACT_SERVER_BLOCK_TYPE = 0xeada;
1167 var REACT_FUNDAMENTAL_TYPE = 0xead5;
1168 var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1;
1169 var REACT_LEGACY_HIDDEN_TYPE = 0xeae3;
1170
1171 if (typeof Symbol === 'function' && Symbol.for) {
1172 var symbolFor = Symbol.for;
1173 REACT_ELEMENT_TYPE = symbolFor('react.element');
1174 REACT_PORTAL_TYPE = symbolFor('react.portal');
1175 REACT_FRAGMENT_TYPE = symbolFor('react.fragment');
1176 REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode');
1177 REACT_PROFILER_TYPE = symbolFor('react.profiler');
1178 REACT_PROVIDER_TYPE = symbolFor('react.provider');
1179 REACT_CONTEXT_TYPE = symbolFor('react.context');
1180 REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref');
1181 REACT_SUSPENSE_TYPE = symbolFor('react.suspense');
1182 REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list');
1183 REACT_MEMO_TYPE = symbolFor('react.memo');
1184 REACT_LAZY_TYPE = symbolFor('react.lazy');
1185 REACT_BLOCK_TYPE = symbolFor('react.block');
1186 REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block');
1187 REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental');
1188 symbolFor('react.scope');
1189 symbolFor('react.opaque.id');
1190 REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode');
1191 symbolFor('react.offscreen');
1192 REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden');
1193 } // Filter certain DOM attributes (e.g. src, href) if their values are empty strings.
1194
1195
1196 var enableScopeAPI = false; // Experimental Create Event Handle API.
1197
1198 function isValidElementType(type) {
1199 if (typeof type === 'string' || typeof type === 'function') {
1200 return true;
1201 } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
1202
1203
1204 if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || type === REACT_DEBUG_TRACING_MODE_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || enableScopeAPI) {
1205 return true;
1206 }
1207
1208 if (typeof type === 'object' && type !== null) {
1209 if (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 || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_BLOCK_TYPE || type[0] === REACT_SERVER_BLOCK_TYPE) {
1210 return true;
1211 }
1212 }
1213
1214 return false;
1215 }
1216
1217 function typeOf(object) {
1218 if (typeof object === 'object' && object !== null) {
1219 var $$typeof = object.$$typeof;
1220
1221 switch ($$typeof) {
1222 case REACT_ELEMENT_TYPE:
1223 var type = object.type;
1224
1225 switch (type) {
1226 case REACT_FRAGMENT_TYPE:
1227 case REACT_PROFILER_TYPE:
1228 case REACT_STRICT_MODE_TYPE:
1229 case REACT_SUSPENSE_TYPE:
1230 case REACT_SUSPENSE_LIST_TYPE:
1231 return type;
1232
1233 default:
1234 var $$typeofType = type && type.$$typeof;
1235
1236 switch ($$typeofType) {
1237 case REACT_CONTEXT_TYPE:
1238 case REACT_FORWARD_REF_TYPE:
1239 case REACT_LAZY_TYPE:
1240 case REACT_MEMO_TYPE:
1241 case REACT_PROVIDER_TYPE:
1242 return $$typeofType;
1243
1244 default:
1245 return $$typeof;
1246 }
1247
1248 }
1249
1250 case REACT_PORTAL_TYPE:
1251 return $$typeof;
1252 }
1253 }
1254
1255 return undefined;
1256 }
1257
1258 var ContextConsumer = REACT_CONTEXT_TYPE;
1259 var ContextProvider = REACT_PROVIDER_TYPE;
1260 var Element = REACT_ELEMENT_TYPE;
1261 var ForwardRef = REACT_FORWARD_REF_TYPE;
1262 var Fragment = REACT_FRAGMENT_TYPE;
1263 var Lazy = REACT_LAZY_TYPE;
1264 var Memo = REACT_MEMO_TYPE;
1265 var Portal = REACT_PORTAL_TYPE;
1266 var Profiler = REACT_PROFILER_TYPE;
1267 var StrictMode = REACT_STRICT_MODE_TYPE;
1268 var Suspense = REACT_SUSPENSE_TYPE;
1269 var hasWarnedAboutDeprecatedIsAsyncMode = false;
1270 var hasWarnedAboutDeprecatedIsConcurrentMode = false; // AsyncMode should be deprecated
1271
1272 function isAsyncMode(object) {
1273 {
1274 if (!hasWarnedAboutDeprecatedIsAsyncMode) {
1275 hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint
1276
1277 console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 18+.');
1278 }
1279 }
1280 return false;
1281 }
1282
1283 function isConcurrentMode(object) {
1284 {
1285 if (!hasWarnedAboutDeprecatedIsConcurrentMode) {
1286 hasWarnedAboutDeprecatedIsConcurrentMode = true; // Using console['warn'] to evade Babel and ESLint
1287
1288 console['warn']('The ReactIs.isConcurrentMode() alias has been deprecated, ' + 'and will be removed in React 18+.');
1289 }
1290 }
1291 return false;
1292 }
1293
1294 function isContextConsumer(object) {
1295 return typeOf(object) === REACT_CONTEXT_TYPE;
1296 }
1297
1298 function isContextProvider(object) {
1299 return typeOf(object) === REACT_PROVIDER_TYPE;
1300 }
1301
1302 function isElement(object) {
1303 return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
1304 }
1305
1306 function isForwardRef(object) {
1307 return typeOf(object) === REACT_FORWARD_REF_TYPE;
1308 }
1309
1310 function isFragment(object) {
1311 return typeOf(object) === REACT_FRAGMENT_TYPE;
1312 }
1313
1314 function isLazy(object) {
1315 return typeOf(object) === REACT_LAZY_TYPE;
1316 }
1317
1318 function isMemo(object) {
1319 return typeOf(object) === REACT_MEMO_TYPE;
1320 }
1321
1322 function isPortal(object) {
1323 return typeOf(object) === REACT_PORTAL_TYPE;
1324 }
1325
1326 function isProfiler(object) {
1327 return typeOf(object) === REACT_PROFILER_TYPE;
1328 }
1329
1330 function isStrictMode(object) {
1331 return typeOf(object) === REACT_STRICT_MODE_TYPE;
1332 }
1333
1334 function isSuspense(object) {
1335 return typeOf(object) === REACT_SUSPENSE_TYPE;
1336 }
1337
1338 exports.ContextConsumer = ContextConsumer;
1339 exports.ContextProvider = ContextProvider;
1340 exports.Element = Element;
1341 exports.ForwardRef = ForwardRef;
1342 exports.Fragment = Fragment;
1343 exports.Lazy = Lazy;
1344 exports.Memo = Memo;
1345 exports.Portal = Portal;
1346 exports.Profiler = Profiler;
1347 exports.StrictMode = StrictMode;
1348 exports.Suspense = Suspense;
1349 exports.isAsyncMode = isAsyncMode;
1350 exports.isConcurrentMode = isConcurrentMode;
1351 exports.isContextConsumer = isContextConsumer;
1352 exports.isContextProvider = isContextProvider;
1353 exports.isElement = isElement;
1354 exports.isForwardRef = isForwardRef;
1355 exports.isFragment = isFragment;
1356 exports.isLazy = isLazy;
1357 exports.isMemo = isMemo;
1358 exports.isPortal = isPortal;
1359 exports.isProfiler = isProfiler;
1360 exports.isStrictMode = isStrictMode;
1361 exports.isSuspense = isSuspense;
1362 exports.isValidElementType = isValidElementType;
1363 exports.typeOf = typeOf;
1364 })();
1365 }
1366 });
1367
1368 var reactIs$1 = createCommonjsModule(function (module) {
1369
1370 {
1371 module.exports = reactIs_development$1;
1372 }
1373 });
1374
1375 function t(t) {
1376 return null != t && "object" == typeof t && 1 === t.nodeType;
1377 }
1378
1379 function e(t, e) {
1380 return (!e || "hidden" !== t) && "visible" !== t && "clip" !== t;
1381 }
1382
1383 function n(t, n) {
1384 if (t.clientHeight < t.scrollHeight || t.clientWidth < t.scrollWidth) {
1385 var r = getComputedStyle(t, null);
1386 return e(r.overflowY, n) || e(r.overflowX, n) || function (t) {
1387 var e = function (t) {
1388 if (!t.ownerDocument || !t.ownerDocument.defaultView) return null;
1389
1390 try {
1391 return t.ownerDocument.defaultView.frameElement;
1392 } catch (t) {
1393 return null;
1394 }
1395 }(t);
1396
1397 return !!e && (e.clientHeight < t.scrollHeight || e.clientWidth < t.scrollWidth);
1398 }(t);
1399 }
1400
1401 return !1;
1402 }
1403
1404 function r(t, e, n, r, i, o, l, d) {
1405 return o < t && l > e || o > t && l < e ? 0 : o <= t && d <= n || l >= e && d >= n ? o - t - r : l > e && d < n || o < t && d > n ? l - e + i : 0;
1406 }
1407
1408 function computeScrollIntoView (e, i) {
1409 var o = window,
1410 l = i.scrollMode,
1411 d = i.block,
1412 u = i.inline,
1413 h = i.boundary,
1414 a = i.skipOverflowHiddenElements,
1415 c = "function" == typeof h ? h : function (t) {
1416 return t !== h;
1417 };
1418 if (!t(e)) throw new TypeError("Invalid target");
1419
1420 for (var f = document.scrollingElement || document.documentElement, s = [], p = e; t(p) && c(p);) {
1421 if ((p = p.parentNode) === f) {
1422 s.push(p);
1423 break;
1424 }
1425
1426 p === document.body && n(p) && !n(document.documentElement) || n(p, a) && s.push(p);
1427 }
1428
1429 for (var g = o.visualViewport ? o.visualViewport.width : innerWidth, m = o.visualViewport ? o.visualViewport.height : innerHeight, w = window.scrollX || pageXOffset, v = window.scrollY || pageYOffset, W = e.getBoundingClientRect(), b = W.height, H = W.width, y = W.top, M = W.right, E = W.bottom, V = W.left, x = "start" === d || "nearest" === d ? y : "end" === d ? E : y + b / 2, I = "center" === u ? V + H / 2 : "end" === u ? M : V, C = [], T = 0; T < s.length; T++) {
1430 var k = s[T],
1431 B = k.getBoundingClientRect(),
1432 D = B.height,
1433 O = B.width,
1434 R = B.top,
1435 X = B.right,
1436 Y = B.bottom,
1437 L = B.left;
1438 if ("if-needed" === l && y >= 0 && V >= 0 && E <= m && M <= g && y >= R && E <= Y && V >= L && M <= X) return C;
1439 var S = getComputedStyle(k),
1440 j = parseInt(S.borderLeftWidth, 10),
1441 N = parseInt(S.borderTopWidth, 10),
1442 q = parseInt(S.borderRightWidth, 10),
1443 z = parseInt(S.borderBottomWidth, 10),
1444 A = 0,
1445 F = 0,
1446 G = "offsetWidth" in k ? k.offsetWidth - k.clientWidth - j - q : 0,
1447 J = "offsetHeight" in k ? k.offsetHeight - k.clientHeight - N - z : 0;
1448 if (f === k) A = "start" === d ? x : "end" === d ? x - m : "nearest" === d ? r(v, v + m, m, N, z, v + x, v + x + b, b) : x - m / 2, F = "start" === u ? I : "center" === u ? I - g / 2 : "end" === u ? I - g : r(w, w + g, g, j, q, w + I, w + I + H, H), A = Math.max(0, A + v), F = Math.max(0, F + w);else {
1449 A = "start" === d ? x - R - N : "end" === d ? x - Y + z + J : "nearest" === d ? r(R, Y, D, N, z + J, x, x + b, b) : x - (R + D / 2) + J / 2, F = "start" === u ? I - L - j : "center" === u ? I - (L + O / 2) + G / 2 : "end" === u ? I - X + q + G : r(L, X, O, j, q + G, I, I + H, H);
1450 var K = k.scrollLeft,
1451 P = k.scrollTop;
1452 x += P - (A = Math.max(0, Math.min(P + A, k.scrollHeight - D + J))), I += K - (F = Math.max(0, Math.min(K + F, k.scrollWidth - O + G)));
1453 }
1454 C.push({
1455 el: k,
1456 top: A,
1457 left: F
1458 });
1459 }
1460
1461 return C;
1462 }
1463
1464 var idCounter = 0;
1465 /**
1466 * Accepts a parameter and returns it if it's a function
1467 * or a noop function if it's not. This allows us to
1468 * accept a callback, but not worry about it if it's not
1469 * passed.
1470 * @param {Function} cb the callback
1471 * @return {Function} a function
1472 */
1473
1474 function cbToCb(cb) {
1475 return typeof cb === 'function' ? cb : noop;
1476 }
1477
1478 function noop() {}
1479 /**
1480 * Scroll node into view if necessary
1481 * @param {HTMLElement} node the element that should scroll into view
1482 * @param {HTMLElement} menuNode the menu element of the component
1483 */
1484
1485
1486 function scrollIntoView(node, menuNode) {
1487 if (!node) {
1488 return;
1489 }
1490
1491 var actions = computeScrollIntoView(node, {
1492 boundary: menuNode,
1493 block: 'nearest',
1494 scrollMode: 'if-needed'
1495 });
1496 actions.forEach(function (_ref) {
1497 var el = _ref.el,
1498 top = _ref.top,
1499 left = _ref.left;
1500 el.scrollTop = top;
1501 el.scrollLeft = left;
1502 });
1503 }
1504 /**
1505 * @param {HTMLElement} parent the parent node
1506 * @param {HTMLElement} child the child node
1507 * @return {Boolean} whether the parent is the child or the child is in the parent
1508 */
1509
1510
1511 function isOrContainsNode(parent, child) {
1512 return parent === child || child instanceof Node && parent.contains && parent.contains(child);
1513 }
1514 /**
1515 * Simple debounce implementation. Will call the given
1516 * function once after the time given has passed since
1517 * it was last called.
1518 * @param {Function} fn the function to call after the time
1519 * @param {Number} time the time to wait
1520 * @return {Function} the debounced function
1521 */
1522
1523
1524 function debounce(fn, time) {
1525 var timeoutId;
1526
1527 function cancel() {
1528 if (timeoutId) {
1529 clearTimeout(timeoutId);
1530 }
1531 }
1532
1533 function wrapper() {
1534 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1535 args[_key] = arguments[_key];
1536 }
1537
1538 cancel();
1539 timeoutId = setTimeout(function () {
1540 timeoutId = null;
1541 fn.apply(void 0, args);
1542 }, time);
1543 }
1544
1545 wrapper.cancel = cancel;
1546 return wrapper;
1547 }
1548 /**
1549 * This is intended to be used to compose event handlers.
1550 * They are executed in order until one of them sets
1551 * `event.preventDownshiftDefault = true`.
1552 * @param {...Function} fns the event handler functions
1553 * @return {Function} the event handler to add to an element
1554 */
1555
1556
1557 function callAllEventHandlers() {
1558 for (var _len2 = arguments.length, fns = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
1559 fns[_key2] = arguments[_key2];
1560 }
1561
1562 return function (event) {
1563 for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
1564 args[_key3 - 1] = arguments[_key3];
1565 }
1566
1567 return fns.some(function (fn) {
1568 if (fn) {
1569 fn.apply(void 0, [event].concat(args));
1570 }
1571
1572 return event.preventDownshiftDefault || event.hasOwnProperty('nativeEvent') && event.nativeEvent.preventDownshiftDefault;
1573 });
1574 };
1575 }
1576
1577 function handleRefs() {
1578 for (var _len4 = arguments.length, refs = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
1579 refs[_key4] = arguments[_key4];
1580 }
1581
1582 return function (node) {
1583 refs.forEach(function (ref) {
1584 if (typeof ref === 'function') {
1585 ref(node);
1586 } else if (ref) {
1587 ref.current = node;
1588 }
1589 });
1590 };
1591 }
1592 /**
1593 * This generates a unique ID for an instance of Downshift
1594 * @return {String} the unique ID
1595 */
1596
1597
1598 function generateId() {
1599 return String(idCounter++);
1600 }
1601 /**
1602 * Resets idCounter to 0. Used for SSR.
1603 */
1604
1605
1606 function resetIdCounter() {
1607 idCounter = 0;
1608 }
1609 /**
1610 * Default implementation for status message. Only added when menu is open.
1611 * Will specift if there are results in the list, and if so, how many,
1612 * and what keys are relevant.
1613 *
1614 * @param {Object} param the downshift state and other relevant properties
1615 * @return {String} the a11y status message
1616 */
1617
1618
1619 function getA11yStatusMessage(_ref2) {
1620 var isOpen = _ref2.isOpen,
1621 resultCount = _ref2.resultCount,
1622 previousResultCount = _ref2.previousResultCount;
1623
1624 if (!isOpen) {
1625 return '';
1626 }
1627
1628 if (!resultCount) {
1629 return 'No results are available.';
1630 }
1631
1632 if (resultCount !== previousResultCount) {
1633 return resultCount + " result" + (resultCount === 1 ? ' is' : 's are') + " available, use up and down arrow keys to navigate. Press Enter key to select.";
1634 }
1635
1636 return '';
1637 }
1638 /**
1639 * Takes an argument and if it's an array, returns the first item in the array
1640 * otherwise returns the argument
1641 * @param {*} arg the maybe-array
1642 * @param {*} defaultValue the value if arg is falsey not defined
1643 * @return {*} the arg or it's first item
1644 */
1645
1646
1647 function unwrapArray(arg, defaultValue) {
1648 arg = Array.isArray(arg) ?
1649 /* istanbul ignore next (preact) */
1650 arg[0] : arg;
1651
1652 if (!arg && defaultValue) {
1653 return defaultValue;
1654 } else {
1655 return arg;
1656 }
1657 }
1658 /**
1659 * @param {Object} element (P)react element
1660 * @return {Boolean} whether it's a DOM element
1661 */
1662
1663
1664 function isDOMElement(element) {
1665 // then we assume this is react
1666 return typeof element.type === 'string';
1667 }
1668 /**
1669 * @param {Object} element (P)react element
1670 * @return {Object} the props
1671 */
1672
1673
1674 function getElementProps(element) {
1675 return element.props;
1676 }
1677 /**
1678 * Throws a helpful error message for required properties. Useful
1679 * to be used as a default in destructuring or object params.
1680 * @param {String} fnName the function name
1681 * @param {String} propName the prop name
1682 */
1683
1684
1685 function requiredProp(fnName, propName) {
1686 // eslint-disable-next-line no-console
1687 console.error("The property \"" + propName + "\" is required in \"" + fnName + "\"");
1688 }
1689
1690 var stateKeys = ['highlightedIndex', 'inputValue', 'isOpen', 'selectedItem', 'type'];
1691 /**
1692 * @param {Object} state the state object
1693 * @return {Object} state that is relevant to downshift
1694 */
1695
1696 function pickState(state) {
1697 if (state === void 0) {
1698 state = {};
1699 }
1700
1701 var result = {};
1702 stateKeys.forEach(function (k) {
1703 if (state.hasOwnProperty(k)) {
1704 result[k] = state[k];
1705 }
1706 });
1707 return result;
1708 }
1709 /**
1710 * This will perform a shallow merge of the given state object
1711 * with the state coming from props
1712 * (for the controlled component scenario)
1713 * This is used in state updater functions so they're referencing
1714 * the right state regardless of where it comes from.
1715 *
1716 * @param {Object} state The state of the component/hook.
1717 * @param {Object} props The props that may contain controlled values.
1718 * @returns {Object} The merged controlled state.
1719 */
1720
1721
1722 function getState(state, props) {
1723 return Object.keys(state).reduce(function (prevState, key) {
1724 prevState[key] = isControlledProp(props, key) ? props[key] : state[key];
1725 return prevState;
1726 }, {});
1727 }
1728 /**
1729 * This determines whether a prop is a "controlled prop" meaning it is
1730 * state which is controlled by the outside of this component rather
1731 * than within this component.
1732 *
1733 * @param {Object} props The props that may contain controlled values.
1734 * @param {String} key the key to check
1735 * @return {Boolean} whether it is a controlled controlled prop
1736 */
1737
1738
1739 function isControlledProp(props, key) {
1740 return props[key] !== undefined;
1741 }
1742 /**
1743 * Normalizes the 'key' property of a KeyboardEvent in IE/Edge
1744 * @param {Object} event a keyboardEvent object
1745 * @return {String} keyboard key
1746 */
1747
1748
1749 function normalizeArrowKey(event) {
1750 var key = event.key,
1751 keyCode = event.keyCode;
1752 /* istanbul ignore next (ie) */
1753
1754 if (keyCode >= 37 && keyCode <= 40 && key.indexOf('Arrow') !== 0) {
1755 return "Arrow" + key;
1756 }
1757
1758 return key;
1759 }
1760 /**
1761 * Simple check if the value passed is object literal
1762 * @param {*} obj any things
1763 * @return {Boolean} whether it's object literal
1764 */
1765
1766
1767 function isPlainObject(obj) {
1768 return Object.prototype.toString.call(obj) === '[object Object]';
1769 }
1770 /**
1771 * Returns the new index in the list, in a circular way. If next value is out of bonds from the total,
1772 * it will wrap to either 0 or itemCount - 1.
1773 *
1774 * @param {number} moveAmount Number of positions to move. Negative to move backwards, positive forwards.
1775 * @param {number} baseIndex The initial position to move from.
1776 * @param {number} itemCount The total number of items.
1777 * @param {Function} getItemNodeFromIndex Used to check if item is disabled.
1778 * @param {boolean} circular Specify if navigation is circular. Default is true.
1779 * @returns {number} The new index after the move.
1780 */
1781
1782
1783 function getNextWrappingIndex(moveAmount, baseIndex, itemCount, getItemNodeFromIndex, circular) {
1784 if (circular === void 0) {
1785 circular = true;
1786 }
1787
1788 if (itemCount === 0) {
1789 return -1;
1790 }
1791
1792 var itemsLastIndex = itemCount - 1;
1793
1794 if (typeof baseIndex !== 'number' || baseIndex < 0 || baseIndex >= itemCount) {
1795 baseIndex = moveAmount > 0 ? -1 : itemsLastIndex + 1;
1796 }
1797
1798 var newIndex = baseIndex + moveAmount;
1799
1800 if (newIndex < 0) {
1801 newIndex = circular ? itemsLastIndex : 0;
1802 } else if (newIndex > itemsLastIndex) {
1803 newIndex = circular ? 0 : itemsLastIndex;
1804 }
1805
1806 var nonDisabledNewIndex = getNextNonDisabledIndex(moveAmount, newIndex, itemCount, getItemNodeFromIndex, circular);
1807
1808 if (nonDisabledNewIndex === -1) {
1809 return baseIndex >= itemCount ? -1 : baseIndex;
1810 }
1811
1812 return nonDisabledNewIndex;
1813 }
1814 /**
1815 * Returns the next index in the list of an item that is not disabled.
1816 *
1817 * @param {number} moveAmount Number of positions to move. Negative to move backwards, positive forwards.
1818 * @param {number} baseIndex The initial position to move from.
1819 * @param {number} itemCount The total number of items.
1820 * @param {Function} getItemNodeFromIndex Used to check if item is disabled.
1821 * @param {boolean} circular Specify if navigation is circular. Default is true.
1822 * @returns {number} The new index. Returns baseIndex if item is not disabled. Returns next non-disabled item otherwise. If no non-disabled found it will return -1.
1823 */
1824
1825
1826 function getNextNonDisabledIndex(moveAmount, baseIndex, itemCount, getItemNodeFromIndex, circular) {
1827 var currentElementNode = getItemNodeFromIndex(baseIndex);
1828
1829 if (!currentElementNode || !currentElementNode.hasAttribute('disabled')) {
1830 return baseIndex;
1831 }
1832
1833 if (moveAmount > 0) {
1834 for (var index = baseIndex + 1; index < itemCount; index++) {
1835 if (!getItemNodeFromIndex(index).hasAttribute('disabled')) {
1836 return index;
1837 }
1838 }
1839 } else {
1840 for (var _index = baseIndex - 1; _index >= 0; _index--) {
1841 if (!getItemNodeFromIndex(_index).hasAttribute('disabled')) {
1842 return _index;
1843 }
1844 }
1845 }
1846
1847 if (circular) {
1848 return moveAmount > 0 ? getNextNonDisabledIndex(1, 0, itemCount, getItemNodeFromIndex, false) : getNextNonDisabledIndex(-1, itemCount - 1, itemCount, getItemNodeFromIndex, false);
1849 }
1850
1851 return -1;
1852 }
1853 /**
1854 * Checks if event target is within the downshift elements.
1855 *
1856 * @param {EventTarget} target Target to check.
1857 * @param {HTMLElement[]} downshiftElements The elements that form downshift (list, toggle button etc).
1858 * @param {Document} document The document.
1859 * @param {boolean} checkActiveElement Whether to also check activeElement.
1860 *
1861 * @returns {boolean} Whether or not the target is within downshift elements.
1862 */
1863
1864
1865 function targetWithinDownshift(target, downshiftElements, document, checkActiveElement) {
1866 if (checkActiveElement === void 0) {
1867 checkActiveElement = true;
1868 }
1869
1870 return downshiftElements.some(function (contextNode) {
1871 return contextNode && (isOrContainsNode(contextNode, target) || checkActiveElement && isOrContainsNode(contextNode, document.activeElement));
1872 });
1873 } // eslint-disable-next-line import/no-mutable-exports
1874
1875
1876 var validateControlledUnchanged = noop;
1877 /* istanbul ignore next */
1878
1879 validateControlledUnchanged = function (state, prevProps, nextProps) {
1880 var warningDescription = "This prop should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled Downshift element for the lifetime of the component. More info: https://github.com/downshift-js/downshift#control-props";
1881 Object.keys(state).forEach(function (propKey) {
1882 if (prevProps[propKey] !== undefined && nextProps[propKey] === undefined) {
1883 // eslint-disable-next-line no-console
1884 console.error("downshift: A component has changed the controlled prop \"" + propKey + "\" to be uncontrolled. " + warningDescription);
1885 } else if (prevProps[propKey] === undefined && nextProps[propKey] !== undefined) {
1886 // eslint-disable-next-line no-console
1887 console.error("downshift: A component has changed the uncontrolled prop \"" + propKey + "\" to be controlled. " + warningDescription);
1888 }
1889 });
1890 };
1891
1892 var cleanupStatus = debounce(function (documentProp) {
1893 getStatusDiv(documentProp).textContent = '';
1894 }, 500);
1895 /**
1896 * @param {String} status the status message
1897 * @param {Object} documentProp document passed by the user.
1898 */
1899
1900 function setStatus(status, documentProp) {
1901 var div = getStatusDiv(documentProp);
1902
1903 if (!status) {
1904 return;
1905 }
1906
1907 div.textContent = status;
1908 cleanupStatus(documentProp);
1909 }
1910 /**
1911 * Get the status node or create it if it does not already exist.
1912 * @param {Object} documentProp document passed by the user.
1913 * @return {HTMLElement} the status node.
1914 */
1915
1916
1917 function getStatusDiv(documentProp) {
1918 if (documentProp === void 0) {
1919 documentProp = document;
1920 }
1921
1922 var statusDiv = documentProp.getElementById('a11y-status-message');
1923
1924 if (statusDiv) {
1925 return statusDiv;
1926 }
1927
1928 statusDiv = documentProp.createElement('div');
1929 statusDiv.setAttribute('id', 'a11y-status-message');
1930 statusDiv.setAttribute('role', 'status');
1931 statusDiv.setAttribute('aria-live', 'polite');
1932 statusDiv.setAttribute('aria-relevant', 'additions text');
1933 Object.assign(statusDiv.style, {
1934 border: '0',
1935 clip: 'rect(0 0 0 0)',
1936 height: '1px',
1937 margin: '-1px',
1938 overflow: 'hidden',
1939 padding: '0',
1940 position: 'absolute',
1941 width: '1px'
1942 });
1943 documentProp.body.appendChild(statusDiv);
1944 return statusDiv;
1945 }
1946
1947 var unknown = '__autocomplete_unknown__';
1948 var mouseUp = '__autocomplete_mouseup__';
1949 var itemMouseEnter = '__autocomplete_item_mouseenter__';
1950 var keyDownArrowUp = '__autocomplete_keydown_arrow_up__';
1951 var keyDownArrowDown = '__autocomplete_keydown_arrow_down__';
1952 var keyDownEscape = '__autocomplete_keydown_escape__';
1953 var keyDownEnter = '__autocomplete_keydown_enter__';
1954 var keyDownHome = '__autocomplete_keydown_home__';
1955 var keyDownEnd = '__autocomplete_keydown_end__';
1956 var clickItem = '__autocomplete_click_item__';
1957 var blurInput = '__autocomplete_blur_input__';
1958 var changeInput = '__autocomplete_change_input__';
1959 var keyDownSpaceButton = '__autocomplete_keydown_space_button__';
1960 var clickButton = '__autocomplete_click_button__';
1961 var blurButton = '__autocomplete_blur_button__';
1962 var controlledPropUpdatedSelectedItem = '__autocomplete_controlled_prop_updated_selected_item__';
1963 var touchEnd = '__autocomplete_touchend__';
1964
1965 var stateChangeTypes = /*#__PURE__*/Object.freeze({
1966 __proto__: null,
1967 unknown: unknown,
1968 mouseUp: mouseUp,
1969 itemMouseEnter: itemMouseEnter,
1970 keyDownArrowUp: keyDownArrowUp,
1971 keyDownArrowDown: keyDownArrowDown,
1972 keyDownEscape: keyDownEscape,
1973 keyDownEnter: keyDownEnter,
1974 keyDownHome: keyDownHome,
1975 keyDownEnd: keyDownEnd,
1976 clickItem: clickItem,
1977 blurInput: blurInput,
1978 changeInput: changeInput,
1979 keyDownSpaceButton: keyDownSpaceButton,
1980 clickButton: clickButton,
1981 blurButton: blurButton,
1982 controlledPropUpdatedSelectedItem: controlledPropUpdatedSelectedItem,
1983 touchEnd: touchEnd
1984 });
1985
1986 var Downshift = /*#__PURE__*/function () {
1987 var Downshift = /*#__PURE__*/function (_Component) {
1988 _inheritsLoose(Downshift, _Component);
1989
1990 function Downshift(_props) {
1991 var _this = _Component.call(this, _props) || this;
1992
1993 _this.id = _this.props.id || "downshift-" + generateId();
1994 _this.menuId = _this.props.menuId || _this.id + "-menu";
1995 _this.labelId = _this.props.labelId || _this.id + "-label";
1996 _this.inputId = _this.props.inputId || _this.id + "-input";
1997
1998 _this.getItemId = _this.props.getItemId || function (index) {
1999 return _this.id + "-item-" + index;
2000 };
2001
2002 _this.input = null;
2003 _this.items = [];
2004 _this.itemCount = null;
2005 _this.previousResultCount = 0;
2006 _this.timeoutIds = [];
2007
2008 _this.internalSetTimeout = function (fn, time) {
2009 var id = setTimeout(function () {
2010 _this.timeoutIds = _this.timeoutIds.filter(function (i) {
2011 return i !== id;
2012 });
2013 fn();
2014 }, time);
2015
2016 _this.timeoutIds.push(id);
2017 };
2018
2019 _this.setItemCount = function (count) {
2020 _this.itemCount = count;
2021 };
2022
2023 _this.unsetItemCount = function () {
2024 _this.itemCount = null;
2025 };
2026
2027 _this.setHighlightedIndex = function (highlightedIndex, otherStateToSet) {
2028 if (highlightedIndex === void 0) {
2029 highlightedIndex = _this.props.defaultHighlightedIndex;
2030 }
2031
2032 if (otherStateToSet === void 0) {
2033 otherStateToSet = {};
2034 }
2035
2036 otherStateToSet = pickState(otherStateToSet);
2037
2038 _this.internalSetState(_extends({
2039 highlightedIndex: highlightedIndex
2040 }, otherStateToSet));
2041 };
2042
2043 _this.clearSelection = function (cb) {
2044 _this.internalSetState({
2045 selectedItem: null,
2046 inputValue: '',
2047 highlightedIndex: _this.props.defaultHighlightedIndex,
2048 isOpen: _this.props.defaultIsOpen
2049 }, cb);
2050 };
2051
2052 _this.selectItem = function (item, otherStateToSet, cb) {
2053 otherStateToSet = pickState(otherStateToSet);
2054
2055 _this.internalSetState(_extends({
2056 isOpen: _this.props.defaultIsOpen,
2057 highlightedIndex: _this.props.defaultHighlightedIndex,
2058 selectedItem: item,
2059 inputValue: _this.props.itemToString(item)
2060 }, otherStateToSet), cb);
2061 };
2062
2063 _this.selectItemAtIndex = function (itemIndex, otherStateToSet, cb) {
2064 var item = _this.items[itemIndex];
2065
2066 if (item == null) {
2067 return;
2068 }
2069
2070 _this.selectItem(item, otherStateToSet, cb);
2071 };
2072
2073 _this.selectHighlightedItem = function (otherStateToSet, cb) {
2074 return _this.selectItemAtIndex(_this.getState().highlightedIndex, otherStateToSet, cb);
2075 };
2076
2077 _this.internalSetState = function (stateToSet, cb) {
2078 var isItemSelected, onChangeArg;
2079 var onStateChangeArg = {};
2080 var isStateToSetFunction = typeof stateToSet === 'function'; // we want to call `onInputValueChange` before the `setState` call
2081 // so someone controlling the `inputValue` state gets notified of
2082 // the input change as soon as possible. This avoids issues with
2083 // preserving the cursor position.
2084 // See https://github.com/downshift-js/downshift/issues/217 for more info.
2085
2086 if (!isStateToSetFunction && stateToSet.hasOwnProperty('inputValue')) {
2087 _this.props.onInputValueChange(stateToSet.inputValue, _extends({}, _this.getStateAndHelpers(), stateToSet));
2088 }
2089
2090 return _this.setState(function (state) {
2091 state = _this.getState(state);
2092 var newStateToSet = isStateToSetFunction ? stateToSet(state) : stateToSet; // Your own function that could modify the state that will be set.
2093
2094 newStateToSet = _this.props.stateReducer(state, newStateToSet); // checks if an item is selected, regardless of if it's different from
2095 // what was selected before
2096 // used to determine if onSelect and onChange callbacks should be called
2097
2098 isItemSelected = newStateToSet.hasOwnProperty('selectedItem'); // this keeps track of the object we want to call with setState
2099
2100 var nextState = {}; // this is just used to tell whether the state changed
2101 // and we're trying to update that state. OR if the selection has changed and we're
2102 // trying to update the selection
2103
2104 if (isItemSelected && newStateToSet.selectedItem !== state.selectedItem) {
2105 onChangeArg = newStateToSet.selectedItem;
2106 }
2107
2108 newStateToSet.type = newStateToSet.type || unknown;
2109 Object.keys(newStateToSet).forEach(function (key) {
2110 // onStateChangeArg should only have the state that is
2111 // actually changing
2112 if (state[key] !== newStateToSet[key]) {
2113 onStateChangeArg[key] = newStateToSet[key];
2114 } // the type is useful for the onStateChangeArg
2115 // but we don't actually want to set it in internal state.
2116 // this is an undocumented feature for now... Not all internalSetState
2117 // calls support it and I'm not certain we want them to yet.
2118 // But it enables users controlling the isOpen state to know when
2119 // the isOpen state changes due to mouseup events which is quite handy.
2120
2121
2122 if (key === 'type') {
2123 return;
2124 }
2125
2126 newStateToSet[key]; // if it's coming from props, then we don't care to set it internally
2127
2128 if (!isControlledProp(_this.props, key)) {
2129 nextState[key] = newStateToSet[key];
2130 }
2131 }); // if stateToSet is a function, then we weren't able to call onInputValueChange
2132 // earlier, so we'll call it now that we know what the inputValue state will be.
2133
2134 if (isStateToSetFunction && newStateToSet.hasOwnProperty('inputValue')) {
2135 _this.props.onInputValueChange(newStateToSet.inputValue, _extends({}, _this.getStateAndHelpers(), newStateToSet));
2136 }
2137
2138 return nextState;
2139 }, function () {
2140 // call the provided callback if it's a function
2141 cbToCb(cb)(); // only call the onStateChange and onChange callbacks if
2142 // we have relevant information to pass them.
2143
2144 var hasMoreStateThanType = Object.keys(onStateChangeArg).length > 1;
2145
2146 if (hasMoreStateThanType) {
2147 _this.props.onStateChange(onStateChangeArg, _this.getStateAndHelpers());
2148 }
2149
2150 if (isItemSelected) {
2151 _this.props.onSelect(stateToSet.selectedItem, _this.getStateAndHelpers());
2152 }
2153
2154 if (onChangeArg !== undefined) {
2155 _this.props.onChange(onChangeArg, _this.getStateAndHelpers());
2156 } // this is currently undocumented and therefore subject to change
2157 // We'll try to not break it, but just be warned.
2158
2159
2160 _this.props.onUserAction(onStateChangeArg, _this.getStateAndHelpers());
2161 });
2162 };
2163
2164 _this.rootRef = function (node) {
2165 return _this._rootNode = node;
2166 };
2167
2168 _this.getRootProps = function (_temp, _temp2) {
2169 var _extends2;
2170
2171 var _ref = _temp === void 0 ? {} : _temp,
2172 _ref$refKey = _ref.refKey,
2173 refKey = _ref$refKey === void 0 ? 'ref' : _ref$refKey,
2174 ref = _ref.ref,
2175 rest = _objectWithoutPropertiesLoose(_ref, ["refKey", "ref"]);
2176
2177 var _ref2 = _temp2 === void 0 ? {} : _temp2,
2178 _ref2$suppressRefErro = _ref2.suppressRefError,
2179 suppressRefError = _ref2$suppressRefErro === void 0 ? false : _ref2$suppressRefErro;
2180
2181 // this is used in the render to know whether the user has called getRootProps.
2182 // It uses that to know whether to apply the props automatically
2183 _this.getRootProps.called = true;
2184 _this.getRootProps.refKey = refKey;
2185 _this.getRootProps.suppressRefError = suppressRefError;
2186
2187 var _this$getState = _this.getState(),
2188 isOpen = _this$getState.isOpen;
2189
2190 return _extends((_extends2 = {}, _extends2[refKey] = handleRefs(ref, _this.rootRef), _extends2.role = 'combobox', _extends2['aria-expanded'] = isOpen, _extends2['aria-haspopup'] = 'listbox', _extends2['aria-owns'] = isOpen ? _this.menuId : null, _extends2['aria-labelledby'] = _this.labelId, _extends2), rest);
2191 };
2192
2193 _this.keyDownHandlers = {
2194 ArrowDown: function ArrowDown(event) {
2195 var _this2 = this;
2196
2197 event.preventDefault();
2198
2199 if (this.getState().isOpen) {
2200 var amount = event.shiftKey ? 5 : 1;
2201 this.moveHighlightedIndex(amount, {
2202 type: keyDownArrowDown
2203 });
2204 } else {
2205 this.internalSetState({
2206 isOpen: true,
2207 type: keyDownArrowDown
2208 }, function () {
2209 var itemCount = _this2.getItemCount();
2210
2211 if (itemCount > 0) {
2212 var _this2$getState = _this2.getState(),
2213 highlightedIndex = _this2$getState.highlightedIndex;
2214
2215 var nextHighlightedIndex = getNextWrappingIndex(1, highlightedIndex, itemCount, function (index) {
2216 return _this2.getItemNodeFromIndex(index);
2217 });
2218
2219 _this2.setHighlightedIndex(nextHighlightedIndex, {
2220 type: keyDownArrowDown
2221 });
2222 }
2223 });
2224 }
2225 },
2226 ArrowUp: function ArrowUp(event) {
2227 var _this3 = this;
2228
2229 event.preventDefault();
2230
2231 if (this.getState().isOpen) {
2232 var amount = event.shiftKey ? -5 : -1;
2233 this.moveHighlightedIndex(amount, {
2234 type: keyDownArrowUp
2235 });
2236 } else {
2237 this.internalSetState({
2238 isOpen: true,
2239 type: keyDownArrowUp
2240 }, function () {
2241 var itemCount = _this3.getItemCount();
2242
2243 if (itemCount > 0) {
2244 var _this3$getState = _this3.getState(),
2245 highlightedIndex = _this3$getState.highlightedIndex;
2246
2247 var nextHighlightedIndex = getNextWrappingIndex(-1, highlightedIndex, itemCount, function (index) {
2248 return _this3.getItemNodeFromIndex(index);
2249 });
2250
2251 _this3.setHighlightedIndex(nextHighlightedIndex, {
2252 type: keyDownArrowUp
2253 });
2254 }
2255 });
2256 }
2257 },
2258 Enter: function Enter(event) {
2259 if (event.which === 229) {
2260 return;
2261 }
2262
2263 var _this$getState2 = this.getState(),
2264 isOpen = _this$getState2.isOpen,
2265 highlightedIndex = _this$getState2.highlightedIndex;
2266
2267 if (isOpen && highlightedIndex != null) {
2268 event.preventDefault();
2269 var item = this.items[highlightedIndex];
2270 var itemNode = this.getItemNodeFromIndex(highlightedIndex);
2271
2272 if (item == null || itemNode && itemNode.hasAttribute('disabled')) {
2273 return;
2274 }
2275
2276 this.selectHighlightedItem({
2277 type: keyDownEnter
2278 });
2279 }
2280 },
2281 Escape: function Escape(event) {
2282 event.preventDefault();
2283 this.reset(_extends({
2284 type: keyDownEscape
2285 }, !this.state.isOpen && {
2286 selectedItem: null,
2287 inputValue: ''
2288 }));
2289 }
2290 };
2291 _this.buttonKeyDownHandlers = _extends({}, _this.keyDownHandlers, {
2292 ' ': function _(event) {
2293 event.preventDefault();
2294 this.toggleMenu({
2295 type: keyDownSpaceButton
2296 });
2297 }
2298 });
2299 _this.inputKeyDownHandlers = _extends({}, _this.keyDownHandlers, {
2300 Home: function Home(event) {
2301 var _this4 = this;
2302
2303 event.preventDefault();
2304 var itemCount = this.getItemCount();
2305
2306 var _this$getState3 = this.getState(),
2307 isOpen = _this$getState3.isOpen;
2308
2309 if (itemCount <= 0 || !isOpen) {
2310 return;
2311 } // get next non-disabled starting downwards from 0 if that's disabled.
2312
2313
2314 var newHighlightedIndex = getNextNonDisabledIndex(1, 0, itemCount, function (index) {
2315 return _this4.getItemNodeFromIndex(index);
2316 }, false);
2317 this.setHighlightedIndex(newHighlightedIndex, {
2318 type: keyDownHome
2319 });
2320 },
2321 End: function End(event) {
2322 var _this5 = this;
2323
2324 event.preventDefault();
2325 var itemCount = this.getItemCount();
2326
2327 var _this$getState4 = this.getState(),
2328 isOpen = _this$getState4.isOpen;
2329
2330 if (itemCount <= 0 || !isOpen) {
2331 return;
2332 } // get next non-disabled starting upwards from last index if that's disabled.
2333
2334
2335 var newHighlightedIndex = getNextNonDisabledIndex(-1, itemCount - 1, itemCount, function (index) {
2336 return _this5.getItemNodeFromIndex(index);
2337 }, false);
2338 this.setHighlightedIndex(newHighlightedIndex, {
2339 type: keyDownEnd
2340 });
2341 }
2342 });
2343
2344 _this.getToggleButtonProps = function (_temp3) {
2345 var _ref3 = _temp3 === void 0 ? {} : _temp3,
2346 onClick = _ref3.onClick,
2347 onPress = _ref3.onPress,
2348 onKeyDown = _ref3.onKeyDown,
2349 onKeyUp = _ref3.onKeyUp,
2350 onBlur = _ref3.onBlur,
2351 rest = _objectWithoutPropertiesLoose(_ref3, ["onClick", "onPress", "onKeyDown", "onKeyUp", "onBlur"]);
2352
2353 var _this$getState5 = _this.getState(),
2354 isOpen = _this$getState5.isOpen;
2355
2356 var enabledEventHandlers = {
2357 onClick: callAllEventHandlers(onClick, _this.buttonHandleClick),
2358 onKeyDown: callAllEventHandlers(onKeyDown, _this.buttonHandleKeyDown),
2359 onKeyUp: callAllEventHandlers(onKeyUp, _this.buttonHandleKeyUp),
2360 onBlur: callAllEventHandlers(onBlur, _this.buttonHandleBlur)
2361 };
2362 var eventHandlers = rest.disabled ? {} : enabledEventHandlers;
2363 return _extends({
2364 type: 'button',
2365 role: 'button',
2366 'aria-label': isOpen ? 'close menu' : 'open menu',
2367 'aria-haspopup': true,
2368 'data-toggle': true
2369 }, eventHandlers, rest);
2370 };
2371
2372 _this.buttonHandleKeyUp = function (event) {
2373 // Prevent click event from emitting in Firefox
2374 event.preventDefault();
2375 };
2376
2377 _this.buttonHandleKeyDown = function (event) {
2378 var key = normalizeArrowKey(event);
2379
2380 if (_this.buttonKeyDownHandlers[key]) {
2381 _this.buttonKeyDownHandlers[key].call(_assertThisInitialized(_this), event);
2382 }
2383 };
2384
2385 _this.buttonHandleClick = function (event) {
2386 event.preventDefault(); // handle odd case for Safari and Firefox which
2387 // don't give the button the focus properly.
2388
2389 /* istanbul ignore if (can't reasonably test this) */
2390
2391 if ( _this.props.environment.document.activeElement === _this.props.environment.document.body) {
2392 event.target.focus();
2393 } // to simplify testing components that use downshift, we'll not wrap this in a setTimeout
2394 // if the NODE_ENV is test. With the proper build system, this should be dead code eliminated
2395 // when building for production and should therefore have no impact on production code.
2396
2397
2398 // Ensure that toggle of menu occurs after the potential blur event in iOS
2399 _this.internalSetTimeout(function () {
2400 return _this.toggleMenu({
2401 type: clickButton
2402 });
2403 });
2404 };
2405
2406 _this.buttonHandleBlur = function (event) {
2407 var blurTarget = event.target; // Save blur target for comparison with activeElement later
2408 // Need setTimeout, so that when the user presses Tab, the activeElement is the next focused element, not body element
2409
2410 _this.internalSetTimeout(function () {
2411 if (!_this.isMouseDown && (_this.props.environment.document.activeElement == null || _this.props.environment.document.activeElement.id !== _this.inputId) && _this.props.environment.document.activeElement !== blurTarget // Do nothing if we refocus the same element again (to solve issue in Safari on iOS)
2412 ) {
2413 _this.reset({
2414 type: blurButton
2415 });
2416 }
2417 });
2418 };
2419
2420 _this.getLabelProps = function (props) {
2421 return _extends({
2422 htmlFor: _this.inputId,
2423 id: _this.labelId
2424 }, props);
2425 };
2426
2427 _this.getInputProps = function (_temp4) {
2428 var _ref4 = _temp4 === void 0 ? {} : _temp4,
2429 onKeyDown = _ref4.onKeyDown,
2430 onBlur = _ref4.onBlur,
2431 onChange = _ref4.onChange,
2432 onInput = _ref4.onInput,
2433 onChangeText = _ref4.onChangeText,
2434 rest = _objectWithoutPropertiesLoose(_ref4, ["onKeyDown", "onBlur", "onChange", "onInput", "onChangeText"]);
2435
2436 var onChangeKey;
2437 var eventHandlers = {};
2438 /* istanbul ignore next (preact) */
2439
2440 onChangeKey = 'onChange';
2441
2442 var _this$getState6 = _this.getState(),
2443 inputValue = _this$getState6.inputValue,
2444 isOpen = _this$getState6.isOpen,
2445 highlightedIndex = _this$getState6.highlightedIndex;
2446
2447 if (!rest.disabled) {
2448 var _eventHandlers;
2449
2450 eventHandlers = (_eventHandlers = {}, _eventHandlers[onChangeKey] = callAllEventHandlers(onChange, onInput, _this.inputHandleChange), _eventHandlers.onKeyDown = callAllEventHandlers(onKeyDown, _this.inputHandleKeyDown), _eventHandlers.onBlur = callAllEventHandlers(onBlur, _this.inputHandleBlur), _eventHandlers);
2451 }
2452 /* istanbul ignore if (react-native) */
2453
2454
2455 return _extends({
2456 'aria-autocomplete': 'list',
2457 'aria-activedescendant': isOpen && typeof highlightedIndex === 'number' && highlightedIndex >= 0 ? _this.getItemId(highlightedIndex) : null,
2458 'aria-controls': isOpen ? _this.menuId : null,
2459 'aria-labelledby': _this.labelId,
2460 // https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion
2461 // revert back since autocomplete="nope" is ignored on latest Chrome and Opera
2462 autoComplete: 'off',
2463 value: inputValue,
2464 id: _this.inputId
2465 }, eventHandlers, rest);
2466 };
2467
2468 _this.inputHandleKeyDown = function (event) {
2469 var key = normalizeArrowKey(event);
2470
2471 if (key && _this.inputKeyDownHandlers[key]) {
2472 _this.inputKeyDownHandlers[key].call(_assertThisInitialized(_this), event);
2473 }
2474 };
2475
2476 _this.inputHandleChange = function (event) {
2477 _this.internalSetState({
2478 type: changeInput,
2479 isOpen: true,
2480 inputValue: event.target.value,
2481 highlightedIndex: _this.props.defaultHighlightedIndex
2482 });
2483 };
2484
2485 _this.inputHandleBlur = function () {
2486 // Need setTimeout, so that when the user presses Tab, the activeElement is the next focused element, not the body element
2487 _this.internalSetTimeout(function () {
2488 var downshiftButtonIsActive = _this.props.environment.document && !!_this.props.environment.document.activeElement && !!_this.props.environment.document.activeElement.dataset && _this.props.environment.document.activeElement.dataset.toggle && _this._rootNode && _this._rootNode.contains(_this.props.environment.document.activeElement);
2489
2490 if (!_this.isMouseDown && !downshiftButtonIsActive) {
2491 _this.reset({
2492 type: blurInput
2493 });
2494 }
2495 });
2496 };
2497
2498 _this.menuRef = function (node) {
2499 _this._menuNode = node;
2500 };
2501
2502 _this.getMenuProps = function (_temp5, _temp6) {
2503 var _extends3;
2504
2505 var _ref5 = _temp5 === void 0 ? {} : _temp5,
2506 _ref5$refKey = _ref5.refKey,
2507 refKey = _ref5$refKey === void 0 ? 'ref' : _ref5$refKey,
2508 ref = _ref5.ref,
2509 props = _objectWithoutPropertiesLoose(_ref5, ["refKey", "ref"]);
2510
2511 var _ref6 = _temp6 === void 0 ? {} : _temp6,
2512 _ref6$suppressRefErro = _ref6.suppressRefError,
2513 suppressRefError = _ref6$suppressRefErro === void 0 ? false : _ref6$suppressRefErro;
2514
2515 _this.getMenuProps.called = true;
2516 _this.getMenuProps.refKey = refKey;
2517 _this.getMenuProps.suppressRefError = suppressRefError;
2518 return _extends((_extends3 = {}, _extends3[refKey] = handleRefs(ref, _this.menuRef), _extends3.role = 'listbox', _extends3['aria-labelledby'] = props && props['aria-label'] ? null : _this.labelId, _extends3.id = _this.menuId, _extends3), props);
2519 };
2520
2521 _this.getItemProps = function (_temp7) {
2522 var _enabledEventHandlers;
2523
2524 var _ref7 = _temp7 === void 0 ? {} : _temp7,
2525 onMouseMove = _ref7.onMouseMove,
2526 onMouseDown = _ref7.onMouseDown,
2527 onClick = _ref7.onClick,
2528 onPress = _ref7.onPress,
2529 index = _ref7.index,
2530 _ref7$item = _ref7.item,
2531 item = _ref7$item === void 0 ? requiredProp('getItemProps', 'item') : _ref7$item,
2532 rest = _objectWithoutPropertiesLoose(_ref7, ["onMouseMove", "onMouseDown", "onClick", "onPress", "index", "item"]);
2533
2534 if (index === undefined) {
2535 _this.items.push(item);
2536
2537 index = _this.items.indexOf(item);
2538 } else {
2539 _this.items[index] = item;
2540 }
2541
2542 var onSelectKey = 'onClick';
2543 var customClickHandler = onClick;
2544 var enabledEventHandlers = (_enabledEventHandlers = {
2545 // onMouseMove is used over onMouseEnter here. onMouseMove
2546 // is only triggered on actual mouse movement while onMouseEnter
2547 // can fire on DOM changes, interrupting keyboard navigation
2548 onMouseMove: callAllEventHandlers(onMouseMove, function () {
2549 if (index === _this.getState().highlightedIndex) {
2550 return;
2551 }
2552
2553 _this.setHighlightedIndex(index, {
2554 type: itemMouseEnter
2555 }); // We never want to manually scroll when changing state based
2556 // on `onMouseMove` because we will be moving the element out
2557 // from under the user which is currently scrolling/moving the
2558 // cursor
2559
2560
2561 _this.avoidScrolling = true;
2562
2563 _this.internalSetTimeout(function () {
2564 return _this.avoidScrolling = false;
2565 }, 250);
2566 }),
2567 onMouseDown: callAllEventHandlers(onMouseDown, function (event) {
2568 // This prevents the activeElement from being changed
2569 // to the item so it can remain with the current activeElement
2570 // which is a more common use case.
2571 event.preventDefault();
2572 })
2573 }, _enabledEventHandlers[onSelectKey] = callAllEventHandlers(customClickHandler, function () {
2574 _this.selectItemAtIndex(index, {
2575 type: clickItem
2576 });
2577 }), _enabledEventHandlers); // Passing down the onMouseDown handler to prevent redirect
2578 // of the activeElement if clicking on disabled items
2579
2580 var eventHandlers = rest.disabled ? {
2581 onMouseDown: enabledEventHandlers.onMouseDown
2582 } : enabledEventHandlers;
2583 return _extends({
2584 id: _this.getItemId(index),
2585 role: 'option',
2586 'aria-selected': _this.getState().highlightedIndex === index
2587 }, eventHandlers, rest);
2588 };
2589
2590 _this.clearItems = function () {
2591 _this.items = [];
2592 };
2593
2594 _this.reset = function (otherStateToSet, cb) {
2595 if (otherStateToSet === void 0) {
2596 otherStateToSet = {};
2597 }
2598
2599 otherStateToSet = pickState(otherStateToSet);
2600
2601 _this.internalSetState(function (_ref8) {
2602 var selectedItem = _ref8.selectedItem;
2603 return _extends({
2604 isOpen: _this.props.defaultIsOpen,
2605 highlightedIndex: _this.props.defaultHighlightedIndex,
2606 inputValue: _this.props.itemToString(selectedItem)
2607 }, otherStateToSet);
2608 }, cb);
2609 };
2610
2611 _this.toggleMenu = function (otherStateToSet, cb) {
2612 if (otherStateToSet === void 0) {
2613 otherStateToSet = {};
2614 }
2615
2616 otherStateToSet = pickState(otherStateToSet);
2617
2618 _this.internalSetState(function (_ref9) {
2619 var isOpen = _ref9.isOpen;
2620 return _extends({
2621 isOpen: !isOpen
2622 }, isOpen && {
2623 highlightedIndex: _this.props.defaultHighlightedIndex
2624 }, otherStateToSet);
2625 }, function () {
2626 var _this$getState7 = _this.getState(),
2627 isOpen = _this$getState7.isOpen,
2628 highlightedIndex = _this$getState7.highlightedIndex;
2629
2630 if (isOpen) {
2631 if (_this.getItemCount() > 0 && typeof highlightedIndex === 'number') {
2632 _this.setHighlightedIndex(highlightedIndex, otherStateToSet);
2633 }
2634 }
2635
2636 cbToCb(cb)();
2637 });
2638 };
2639
2640 _this.openMenu = function (cb) {
2641 _this.internalSetState({
2642 isOpen: true
2643 }, cb);
2644 };
2645
2646 _this.closeMenu = function (cb) {
2647 _this.internalSetState({
2648 isOpen: false
2649 }, cb);
2650 };
2651
2652 _this.updateStatus = debounce(function () {
2653 var state = _this.getState();
2654
2655 var item = _this.items[state.highlightedIndex];
2656
2657 var resultCount = _this.getItemCount();
2658
2659 var status = _this.props.getA11yStatusMessage(_extends({
2660 itemToString: _this.props.itemToString,
2661 previousResultCount: _this.previousResultCount,
2662 resultCount: resultCount,
2663 highlightedItem: item
2664 }, state));
2665
2666 _this.previousResultCount = resultCount;
2667 setStatus(status, _this.props.environment.document);
2668 }, 200);
2669
2670 // fancy destructuring + defaults + aliases
2671 // this basically says each value of state should either be set to
2672 // the initial value or the default value if the initial value is not provided
2673 var _this$props = _this.props,
2674 defaultHighlightedIndex = _this$props.defaultHighlightedIndex,
2675 _this$props$initialHi = _this$props.initialHighlightedIndex,
2676 _highlightedIndex = _this$props$initialHi === void 0 ? defaultHighlightedIndex : _this$props$initialHi,
2677 defaultIsOpen = _this$props.defaultIsOpen,
2678 _this$props$initialIs = _this$props.initialIsOpen,
2679 _isOpen = _this$props$initialIs === void 0 ? defaultIsOpen : _this$props$initialIs,
2680 _this$props$initialIn = _this$props.initialInputValue,
2681 _inputValue = _this$props$initialIn === void 0 ? '' : _this$props$initialIn,
2682 _this$props$initialSe = _this$props.initialSelectedItem,
2683 _selectedItem = _this$props$initialSe === void 0 ? null : _this$props$initialSe;
2684
2685 var _state = _this.getState({
2686 highlightedIndex: _highlightedIndex,
2687 isOpen: _isOpen,
2688 inputValue: _inputValue,
2689 selectedItem: _selectedItem
2690 });
2691
2692 if (_state.selectedItem != null && _this.props.initialInputValue === undefined) {
2693 _state.inputValue = _this.props.itemToString(_state.selectedItem);
2694 }
2695
2696 _this.state = _state;
2697 return _this;
2698 }
2699
2700 var _proto = Downshift.prototype;
2701
2702 /**
2703 * Clear all running timeouts
2704 */
2705 _proto.internalClearTimeouts = function internalClearTimeouts() {
2706 this.timeoutIds.forEach(function (id) {
2707 clearTimeout(id);
2708 });
2709 this.timeoutIds = [];
2710 }
2711 /**
2712 * Gets the state based on internal state or props
2713 * If a state value is passed via props, then that
2714 * is the value given, otherwise it's retrieved from
2715 * stateToMerge
2716 *
2717 * @param {Object} stateToMerge defaults to this.state
2718 * @return {Object} the state
2719 */
2720 ;
2721
2722 _proto.getState = function getState$1(stateToMerge) {
2723 if (stateToMerge === void 0) {
2724 stateToMerge = this.state;
2725 }
2726
2727 return getState(stateToMerge, this.props);
2728 };
2729
2730 _proto.getItemCount = function getItemCount() {
2731 // things read better this way. They're in priority order:
2732 // 1. `this.itemCount`
2733 // 2. `this.props.itemCount`
2734 // 3. `this.items.length`
2735 var itemCount = this.items.length;
2736
2737 if (this.itemCount != null) {
2738 itemCount = this.itemCount;
2739 } else if (this.props.itemCount !== undefined) {
2740 itemCount = this.props.itemCount;
2741 }
2742
2743 return itemCount;
2744 };
2745
2746 _proto.getItemNodeFromIndex = function getItemNodeFromIndex(index) {
2747 return this.props.environment.document.getElementById(this.getItemId(index));
2748 };
2749
2750 _proto.scrollHighlightedItemIntoView = function scrollHighlightedItemIntoView() {
2751 /* istanbul ignore else (react-native) */
2752 {
2753 var node = this.getItemNodeFromIndex(this.getState().highlightedIndex);
2754 this.props.scrollIntoView(node, this._menuNode);
2755 }
2756 };
2757
2758 _proto.moveHighlightedIndex = function moveHighlightedIndex(amount, otherStateToSet) {
2759 var _this6 = this;
2760
2761 var itemCount = this.getItemCount();
2762
2763 var _this$getState8 = this.getState(),
2764 highlightedIndex = _this$getState8.highlightedIndex;
2765
2766 if (itemCount > 0) {
2767 var nextHighlightedIndex = getNextWrappingIndex(amount, highlightedIndex, itemCount, function (index) {
2768 return _this6.getItemNodeFromIndex(index);
2769 });
2770 this.setHighlightedIndex(nextHighlightedIndex, otherStateToSet);
2771 }
2772 };
2773
2774 _proto.getStateAndHelpers = function getStateAndHelpers() {
2775 var _this$getState9 = this.getState(),
2776 highlightedIndex = _this$getState9.highlightedIndex,
2777 inputValue = _this$getState9.inputValue,
2778 selectedItem = _this$getState9.selectedItem,
2779 isOpen = _this$getState9.isOpen;
2780
2781 var itemToString = this.props.itemToString;
2782 var id = this.id;
2783 var getRootProps = this.getRootProps,
2784 getToggleButtonProps = this.getToggleButtonProps,
2785 getLabelProps = this.getLabelProps,
2786 getMenuProps = this.getMenuProps,
2787 getInputProps = this.getInputProps,
2788 getItemProps = this.getItemProps,
2789 openMenu = this.openMenu,
2790 closeMenu = this.closeMenu,
2791 toggleMenu = this.toggleMenu,
2792 selectItem = this.selectItem,
2793 selectItemAtIndex = this.selectItemAtIndex,
2794 selectHighlightedItem = this.selectHighlightedItem,
2795 setHighlightedIndex = this.setHighlightedIndex,
2796 clearSelection = this.clearSelection,
2797 clearItems = this.clearItems,
2798 reset = this.reset,
2799 setItemCount = this.setItemCount,
2800 unsetItemCount = this.unsetItemCount,
2801 setState = this.internalSetState;
2802 return {
2803 // prop getters
2804 getRootProps: getRootProps,
2805 getToggleButtonProps: getToggleButtonProps,
2806 getLabelProps: getLabelProps,
2807 getMenuProps: getMenuProps,
2808 getInputProps: getInputProps,
2809 getItemProps: getItemProps,
2810 // actions
2811 reset: reset,
2812 openMenu: openMenu,
2813 closeMenu: closeMenu,
2814 toggleMenu: toggleMenu,
2815 selectItem: selectItem,
2816 selectItemAtIndex: selectItemAtIndex,
2817 selectHighlightedItem: selectHighlightedItem,
2818 setHighlightedIndex: setHighlightedIndex,
2819 clearSelection: clearSelection,
2820 clearItems: clearItems,
2821 setItemCount: setItemCount,
2822 unsetItemCount: unsetItemCount,
2823 setState: setState,
2824 // props
2825 itemToString: itemToString,
2826 // derived
2827 id: id,
2828 // state
2829 highlightedIndex: highlightedIndex,
2830 inputValue: inputValue,
2831 isOpen: isOpen,
2832 selectedItem: selectedItem
2833 };
2834 } //////////////////////////// ROOT
2835 ;
2836
2837 _proto.componentDidMount = function componentDidMount() {
2838 var _this7 = this;
2839
2840 /* istanbul ignore if (react-native) */
2841 if ( this.getMenuProps.called && !this.getMenuProps.suppressRefError) {
2842 validateGetMenuPropsCalledCorrectly(this._menuNode, this.getMenuProps);
2843 }
2844 /* istanbul ignore if (react-native) */
2845
2846
2847 {
2848 // this.isMouseDown helps us track whether the mouse is currently held down.
2849 // This is useful when the user clicks on an item in the list, but holds the mouse
2850 // down long enough for the list to disappear (because the blur event fires on the input)
2851 // this.isMouseDown is used in the blur handler on the input to determine whether the blur event should
2852 // trigger hiding the menu.
2853 var onMouseDown = function () {
2854 _this7.isMouseDown = true;
2855 };
2856
2857 var onMouseUp = function (event) {
2858 _this7.isMouseDown = false; // if the target element or the activeElement is within a downshift node
2859 // then we don't want to reset downshift
2860
2861 var contextWithinDownshift = targetWithinDownshift(event.target, [_this7._rootNode, _this7._menuNode], _this7.props.environment.document);
2862
2863 if (!contextWithinDownshift && _this7.getState().isOpen) {
2864 _this7.reset({
2865 type: mouseUp
2866 }, function () {
2867 return _this7.props.onOuterClick(_this7.getStateAndHelpers());
2868 });
2869 }
2870 }; // Touching an element in iOS gives focus and hover states, but touching out of
2871 // the element will remove hover, and persist the focus state, resulting in the
2872 // blur event not being triggered.
2873 // this.isTouchMove helps us track whether the user is tapping or swiping on a touch screen.
2874 // If the user taps outside of Downshift, the component should be reset,
2875 // but not if the user is swiping
2876
2877
2878 var onTouchStart = function () {
2879 _this7.isTouchMove = false;
2880 };
2881
2882 var onTouchMove = function () {
2883 _this7.isTouchMove = true;
2884 };
2885
2886 var onTouchEnd = function (event) {
2887 var contextWithinDownshift = targetWithinDownshift(event.target, [_this7._rootNode, _this7._menuNode], _this7.props.environment.document, false);
2888
2889 if (!_this7.isTouchMove && !contextWithinDownshift && _this7.getState().isOpen) {
2890 _this7.reset({
2891 type: touchEnd
2892 }, function () {
2893 return _this7.props.onOuterClick(_this7.getStateAndHelpers());
2894 });
2895 }
2896 };
2897
2898 var environment = this.props.environment;
2899 environment.addEventListener('mousedown', onMouseDown);
2900 environment.addEventListener('mouseup', onMouseUp);
2901 environment.addEventListener('touchstart', onTouchStart);
2902 environment.addEventListener('touchmove', onTouchMove);
2903 environment.addEventListener('touchend', onTouchEnd);
2904
2905 this.cleanup = function () {
2906 _this7.internalClearTimeouts();
2907
2908 _this7.updateStatus.cancel();
2909
2910 environment.removeEventListener('mousedown', onMouseDown);
2911 environment.removeEventListener('mouseup', onMouseUp);
2912 environment.removeEventListener('touchstart', onTouchStart);
2913 environment.removeEventListener('touchmove', onTouchMove);
2914 environment.removeEventListener('touchend', onTouchEnd);
2915 };
2916 }
2917 };
2918
2919 _proto.shouldScroll = function shouldScroll(prevState, prevProps) {
2920 var _ref10 = this.props.highlightedIndex === undefined ? this.getState() : this.props,
2921 currentHighlightedIndex = _ref10.highlightedIndex;
2922
2923 var _ref11 = prevProps.highlightedIndex === undefined ? prevState : prevProps,
2924 prevHighlightedIndex = _ref11.highlightedIndex;
2925
2926 var scrollWhenOpen = currentHighlightedIndex && this.getState().isOpen && !prevState.isOpen;
2927 return scrollWhenOpen || currentHighlightedIndex !== prevHighlightedIndex;
2928 };
2929
2930 _proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
2931 validateControlledUnchanged(this.state, prevProps, this.props);
2932 /* istanbul ignore if (react-native) */
2933
2934 if ( this.getMenuProps.called && !this.getMenuProps.suppressRefError) {
2935 validateGetMenuPropsCalledCorrectly(this._menuNode, this.getMenuProps);
2936 }
2937
2938 if (isControlledProp(this.props, 'selectedItem') && this.props.selectedItemChanged(prevProps.selectedItem, this.props.selectedItem)) {
2939 this.internalSetState({
2940 type: controlledPropUpdatedSelectedItem,
2941 inputValue: this.props.itemToString(this.props.selectedItem)
2942 });
2943 }
2944
2945 if (!this.avoidScrolling && this.shouldScroll(prevState, prevProps)) {
2946 this.scrollHighlightedItemIntoView();
2947 }
2948 /* istanbul ignore else (react-native) */
2949
2950
2951 this.updateStatus();
2952 };
2953
2954 _proto.componentWillUnmount = function componentWillUnmount() {
2955 this.cleanup(); // avoids memory leak
2956 };
2957
2958 _proto.render = function render() {
2959 var children = unwrapArray(this.props.children, noop); // because the items are rerendered every time we call the children
2960 // we clear this out each render and it will be populated again as
2961 // getItemProps is called.
2962
2963 this.clearItems(); // we reset this so we know whether the user calls getRootProps during
2964 // this render. If they do then we don't need to do anything,
2965 // if they don't then we need to clone the element they return and
2966 // apply the props for them.
2967
2968 this.getRootProps.called = false;
2969 this.getRootProps.refKey = undefined;
2970 this.getRootProps.suppressRefError = undefined; // we do something similar for getMenuProps
2971
2972 this.getMenuProps.called = false;
2973 this.getMenuProps.refKey = undefined;
2974 this.getMenuProps.suppressRefError = undefined; // we do something similar for getLabelProps
2975
2976 this.getLabelProps.called = false; // and something similar for getInputProps
2977
2978 this.getInputProps.called = false;
2979 var element = unwrapArray(children(this.getStateAndHelpers()));
2980
2981 if (!element) {
2982 return null;
2983 }
2984
2985 if (this.getRootProps.called || this.props.suppressRefError) {
2986 if ( !this.getRootProps.suppressRefError && !this.props.suppressRefError) {
2987 validateGetRootPropsCalledCorrectly(element, this.getRootProps);
2988 }
2989
2990 return element;
2991 } else if (isDOMElement(element)) {
2992 // they didn't apply the root props, but we can clone
2993 // this and apply the props ourselves
2994 return /*#__PURE__*/react.cloneElement(element, this.getRootProps(getElementProps(element)));
2995 }
2996 /* istanbul ignore else */
2997
2998
2999 // they didn't apply the root props, but they need to
3000 // otherwise we can't query around the autocomplete
3001 throw new Error('downshift: If you return a non-DOM element, you must apply the getRootProps function');
3002 /* istanbul ignore next */
3003 };
3004
3005 return Downshift;
3006 }(react.Component);
3007
3008 Downshift.defaultProps = {
3009 defaultHighlightedIndex: null,
3010 defaultIsOpen: false,
3011 getA11yStatusMessage: getA11yStatusMessage,
3012 itemToString: function itemToString(i) {
3013 if (i == null) {
3014 return '';
3015 }
3016
3017 if ( isPlainObject(i) && !i.hasOwnProperty('toString')) {
3018 // eslint-disable-next-line no-console
3019 console.warn('downshift: An object was passed to the default implementation of `itemToString`. You should probably provide your own `itemToString` implementation. Please refer to the `itemToString` API documentation.', 'The object that was passed:', i);
3020 }
3021
3022 return String(i);
3023 },
3024 onStateChange: noop,
3025 onInputValueChange: noop,
3026 onUserAction: noop,
3027 onChange: noop,
3028 onSelect: noop,
3029 onOuterClick: noop,
3030 selectedItemChanged: function selectedItemChanged(prevItem, item) {
3031 return prevItem !== item;
3032 },
3033 environment: typeof window === 'undefined'
3034 /* istanbul ignore next (ssr) */
3035 ? {} : window,
3036 stateReducer: function stateReducer(state, stateToSet) {
3037 return stateToSet;
3038 },
3039 suppressRefError: false,
3040 scrollIntoView: scrollIntoView
3041 };
3042 Downshift.stateChangeTypes = stateChangeTypes;
3043 return Downshift;
3044 }();
3045
3046 Downshift.propTypes = {
3047 children: propTypes.func,
3048 defaultHighlightedIndex: propTypes.number,
3049 defaultIsOpen: propTypes.bool,
3050 initialHighlightedIndex: propTypes.number,
3051 initialSelectedItem: propTypes.any,
3052 initialInputValue: propTypes.string,
3053 initialIsOpen: propTypes.bool,
3054 getA11yStatusMessage: propTypes.func,
3055 itemToString: propTypes.func,
3056 onChange: propTypes.func,
3057 onSelect: propTypes.func,
3058 onStateChange: propTypes.func,
3059 onInputValueChange: propTypes.func,
3060 onUserAction: propTypes.func,
3061 onOuterClick: propTypes.func,
3062 selectedItemChanged: propTypes.func,
3063 stateReducer: propTypes.func,
3064 itemCount: propTypes.number,
3065 id: propTypes.string,
3066 environment: propTypes.shape({
3067 addEventListener: propTypes.func,
3068 removeEventListener: propTypes.func,
3069 document: propTypes.shape({
3070 getElementById: propTypes.func,
3071 activeElement: propTypes.any,
3072 body: propTypes.any
3073 })
3074 }),
3075 suppressRefError: propTypes.bool,
3076 scrollIntoView: propTypes.func,
3077 // things we keep in state for uncontrolled components
3078 // but can accept as props for controlled components
3079
3080 /* eslint-disable react/no-unused-prop-types */
3081 selectedItem: propTypes.any,
3082 isOpen: propTypes.bool,
3083 inputValue: propTypes.string,
3084 highlightedIndex: propTypes.number,
3085 labelId: propTypes.string,
3086 inputId: propTypes.string,
3087 menuId: propTypes.string,
3088 getItemId: propTypes.func
3089 /* eslint-enable react/no-unused-prop-types */
3090
3091 };
3092
3093 function validateGetMenuPropsCalledCorrectly(node, _ref12) {
3094 var refKey = _ref12.refKey;
3095
3096 if (!node) {
3097 // eslint-disable-next-line no-console
3098 console.error("downshift: The ref prop \"" + refKey + "\" from getMenuProps was not applied correctly on your menu element.");
3099 }
3100 }
3101
3102 function validateGetRootPropsCalledCorrectly(element, _ref13) {
3103 var refKey = _ref13.refKey;
3104 var refKeySpecified = refKey !== 'ref';
3105 var isComposite = !isDOMElement(element);
3106
3107 if (isComposite && !refKeySpecified && !reactIs$1.isForwardRef(element)) {
3108 // eslint-disable-next-line no-console
3109 console.error('downshift: You returned a non-DOM element. You must specify a refKey in getRootProps');
3110 } else if (!isComposite && refKeySpecified) {
3111 // eslint-disable-next-line no-console
3112 console.error("downshift: You returned a DOM element. You should not specify a refKey in getRootProps. You specified \"" + refKey + "\"");
3113 }
3114
3115 if (!reactIs$1.isForwardRef(element) && !getElementProps(element)[refKey]) {
3116 // eslint-disable-next-line no-console
3117 console.error("downshift: You must apply the ref prop \"" + refKey + "\" from getRootProps onto your root element.");
3118 }
3119 }
3120
3121 var dropdownDefaultStateValues = {
3122 highlightedIndex: -1,
3123 isOpen: false,
3124 selectedItem: null,
3125 inputValue: ''
3126 };
3127
3128 function callOnChangeProps(action, state, newState) {
3129 var props = action.props,
3130 type = action.type;
3131 var changes = {};
3132 Object.keys(state).forEach(function (key) {
3133 invokeOnChangeHandler(key, action, state, newState);
3134
3135 if (newState[key] !== state[key]) {
3136 changes[key] = newState[key];
3137 }
3138 });
3139
3140 if (props.onStateChange && Object.keys(changes).length) {
3141 props.onStateChange(_extends({
3142 type: type
3143 }, changes));
3144 }
3145 }
3146
3147 function invokeOnChangeHandler(key, action, state, newState) {
3148 var props = action.props,
3149 type = action.type;
3150 var handler = "on" + capitalizeString(key) + "Change";
3151
3152 if (props[handler] && newState[key] !== undefined && newState[key] !== state[key]) {
3153 props[handler](_extends({
3154 type: type
3155 }, newState));
3156 }
3157 }
3158 /**
3159 * Default state reducer that returns the changes.
3160 *
3161 * @param {Object} s state.
3162 * @param {Object} a action with changes.
3163 * @returns {Object} changes.
3164 */
3165
3166
3167 function stateReducer(s, a) {
3168 return a.changes;
3169 }
3170 /**
3171 * Returns a message to be added to aria-live region when item is selected.
3172 *
3173 * @param {Object} selectionParameters Parameters required to build the message.
3174 * @returns {string} The a11y message.
3175 */
3176
3177
3178 function getA11ySelectionMessage(selectionParameters) {
3179 var selectedItem = selectionParameters.selectedItem,
3180 itemToStringLocal = selectionParameters.itemToString;
3181 return selectedItem ? itemToStringLocal(selectedItem) + " has been selected." : '';
3182 }
3183 /**
3184 * Debounced call for updating the a11y message.
3185 */
3186
3187
3188 var updateA11yStatus = debounce(function (getA11yMessage, document) {
3189 setStatus(getA11yMessage(), document);
3190 }, 200); // istanbul ignore next
3191
3192 var useIsomorphicLayoutEffect = typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined' ? react.useLayoutEffect : react.useEffect;
3193
3194 function useElementIds(_ref) {
3195 var _ref$id = _ref.id,
3196 id = _ref$id === void 0 ? "downshift-" + generateId() : _ref$id,
3197 labelId = _ref.labelId,
3198 menuId = _ref.menuId,
3199 getItemId = _ref.getItemId,
3200 toggleButtonId = _ref.toggleButtonId,
3201 inputId = _ref.inputId;
3202 var elementIdsRef = react.useRef({
3203 labelId: labelId || id + "-label",
3204 menuId: menuId || id + "-menu",
3205 getItemId: getItemId || function (index) {
3206 return id + "-item-" + index;
3207 },
3208 toggleButtonId: toggleButtonId || id + "-toggle-button",
3209 inputId: inputId || id + "-input"
3210 });
3211 return elementIdsRef.current;
3212 }
3213
3214 function getItemIndex(index, item, items) {
3215 if (index !== undefined) {
3216 return index;
3217 }
3218
3219 if (items.length === 0) {
3220 return -1;
3221 }
3222
3223 return items.indexOf(item);
3224 }
3225
3226 function itemToString(item) {
3227 return item ? String(item) : '';
3228 }
3229
3230 function isAcceptedCharacterKey(key) {
3231 return /^\S{1}$/.test(key);
3232 }
3233
3234 function capitalizeString(string) {
3235 return "" + string.slice(0, 1).toUpperCase() + string.slice(1);
3236 }
3237
3238 function useLatestRef(val) {
3239 var ref = react.useRef(val); // technically this is not "concurrent mode safe" because we're manipulating
3240 // the value during render (so it's not idempotent). However, the places this
3241 // hook is used is to support memoizing callbacks which will be called
3242 // *during* render, so we need the latest values *during* render.
3243 // If not for this, then we'd probably want to use useLayoutEffect instead.
3244
3245 ref.current = val;
3246 return ref;
3247 }
3248 /**
3249 * Computes the controlled state using a the previous state, props,
3250 * two reducers, one from downshift and an optional one from the user.
3251 * Also calls the onChange handlers for state values that have changed.
3252 *
3253 * @param {Function} reducer Reducer function from downshift.
3254 * @param {Object} initialState Initial state of the hook.
3255 * @param {Object} props The hook props.
3256 * @returns {Array} An array with the state and an action dispatcher.
3257 */
3258
3259
3260 function useEnhancedReducer(reducer, initialState, props) {
3261 var prevStateRef = react.useRef();
3262 var actionRef = react.useRef();
3263 var enhancedReducer = react.useCallback(function (state, action) {
3264 actionRef.current = action;
3265 state = getState(state, action.props);
3266 var changes = reducer(state, action);
3267 var newState = action.props.stateReducer(state, _extends({}, action, {
3268 changes: changes
3269 }));
3270 return newState;
3271 }, [reducer]);
3272
3273 var _useReducer = react.useReducer(enhancedReducer, initialState),
3274 state = _useReducer[0],
3275 dispatch = _useReducer[1];
3276
3277 var propsRef = useLatestRef(props);
3278 var dispatchWithProps = react.useCallback(function (action) {
3279 return dispatch(_extends({
3280 props: propsRef.current
3281 }, action));
3282 }, [propsRef]);
3283 var action = actionRef.current;
3284 react.useEffect(function () {
3285 if (action && prevStateRef.current && prevStateRef.current !== state) {
3286 callOnChangeProps(action, getState(prevStateRef.current, action.props), state);
3287 }
3288
3289 prevStateRef.current = state;
3290 }, [state, props, action]);
3291 return [state, dispatchWithProps];
3292 }
3293 /**
3294 * Wraps the useEnhancedReducer and applies the controlled prop values before
3295 * returning the new state.
3296 *
3297 * @param {Function} reducer Reducer function from downshift.
3298 * @param {Object} initialState Initial state of the hook.
3299 * @param {Object} props The hook props.
3300 * @returns {Array} An array with the state and an action dispatcher.
3301 */
3302
3303
3304 function useControlledReducer(reducer, initialState, props) {
3305 var _useEnhancedReducer = useEnhancedReducer(reducer, initialState, props),
3306 state = _useEnhancedReducer[0],
3307 dispatch = _useEnhancedReducer[1];
3308
3309 return [getState(state, props), dispatch];
3310 }
3311
3312 var defaultProps = {
3313 itemToString: itemToString,
3314 stateReducer: stateReducer,
3315 getA11ySelectionMessage: getA11ySelectionMessage,
3316 scrollIntoView: scrollIntoView,
3317 circularNavigation: false,
3318 environment: typeof window === 'undefined'
3319 /* istanbul ignore next (ssr) */
3320 ? {} : window
3321 };
3322
3323 function getDefaultValue(props, propKey, defaultStateValues) {
3324 if (defaultStateValues === void 0) {
3325 defaultStateValues = dropdownDefaultStateValues;
3326 }
3327
3328 var defaultPropKey = "default" + capitalizeString(propKey);
3329
3330 if (defaultPropKey in props) {
3331 return props[defaultPropKey];
3332 }
3333
3334 return defaultStateValues[propKey];
3335 }
3336
3337 function getInitialValue(props, propKey, defaultStateValues) {
3338 if (defaultStateValues === void 0) {
3339 defaultStateValues = dropdownDefaultStateValues;
3340 }
3341
3342 if (propKey in props) {
3343 return props[propKey];
3344 }
3345
3346 var initialPropKey = "initial" + capitalizeString(propKey);
3347
3348 if (initialPropKey in props) {
3349 return props[initialPropKey];
3350 }
3351
3352 return getDefaultValue(props, propKey, defaultStateValues);
3353 }
3354
3355 function getInitialState(props) {
3356 var selectedItem = getInitialValue(props, 'selectedItem');
3357 var isOpen = getInitialValue(props, 'isOpen');
3358 var highlightedIndex = getInitialValue(props, 'highlightedIndex');
3359 var inputValue = getInitialValue(props, 'inputValue');
3360 return {
3361 highlightedIndex: highlightedIndex < 0 && selectedItem && isOpen ? props.items.indexOf(selectedItem) : highlightedIndex,
3362 isOpen: isOpen,
3363 selectedItem: selectedItem,
3364 inputValue: inputValue
3365 };
3366 }
3367
3368 function getHighlightedIndexOnOpen(props, state, offset, getItemNodeFromIndex) {
3369 var items = props.items,
3370 initialHighlightedIndex = props.initialHighlightedIndex,
3371 defaultHighlightedIndex = props.defaultHighlightedIndex;
3372 var selectedItem = state.selectedItem,
3373 highlightedIndex = state.highlightedIndex;
3374
3375 if (items.length === 0) {
3376 return -1;
3377 } // initialHighlightedIndex will give value to highlightedIndex on initial state only.
3378
3379
3380 if (initialHighlightedIndex !== undefined && highlightedIndex === initialHighlightedIndex) {
3381 return initialHighlightedIndex;
3382 }
3383
3384 if (defaultHighlightedIndex !== undefined) {
3385 return defaultHighlightedIndex;
3386 }
3387
3388 if (selectedItem) {
3389 if (offset === 0) {
3390 return items.indexOf(selectedItem);
3391 }
3392
3393 return getNextWrappingIndex(offset, items.indexOf(selectedItem), items.length, getItemNodeFromIndex, false);
3394 }
3395
3396 if (offset === 0) {
3397 return -1;
3398 }
3399
3400 return offset < 0 ? items.length - 1 : 0;
3401 }
3402 /**
3403 * Reuse the movement tracking of mouse and touch events.
3404 *
3405 * @param {boolean} isOpen Whether the dropdown is open or not.
3406 * @param {Array<Object>} downshiftElementRefs Downshift element refs to track movement (toggleButton, menu etc.)
3407 * @param {Object} environment Environment where component/hook exists.
3408 * @param {Function} handleBlur Handler on blur from mouse or touch.
3409 * @returns {Object} Ref containing whether mouseDown or touchMove event is happening
3410 */
3411
3412
3413 function useMouseAndTouchTracker(isOpen, downshiftElementRefs, environment, handleBlur) {
3414 var mouseAndTouchTrackersRef = react.useRef({
3415 isMouseDown: false,
3416 isTouchMove: false
3417 });
3418 react.useEffect(function () {
3419 // The same strategy for checking if a click occurred inside or outside downsift
3420 // as in downshift.js.
3421 var onMouseDown = function () {
3422 mouseAndTouchTrackersRef.current.isMouseDown = true;
3423 };
3424
3425 var onMouseUp = function (event) {
3426 mouseAndTouchTrackersRef.current.isMouseDown = false;
3427
3428 if (isOpen && !targetWithinDownshift(event.target, downshiftElementRefs.map(function (ref) {
3429 return ref.current;
3430 }), environment.document)) {
3431 handleBlur();
3432 }
3433 };
3434
3435 var onTouchStart = function () {
3436 mouseAndTouchTrackersRef.current.isTouchMove = false;
3437 };
3438
3439 var onTouchMove = function () {
3440 mouseAndTouchTrackersRef.current.isTouchMove = true;
3441 };
3442
3443 var onTouchEnd = function (event) {
3444 if (isOpen && !mouseAndTouchTrackersRef.current.isTouchMove && !targetWithinDownshift(event.target, downshiftElementRefs.map(function (ref) {
3445 return ref.current;
3446 }), environment.document, false)) {
3447 handleBlur();
3448 }
3449 };
3450
3451 environment.addEventListener('mousedown', onMouseDown);
3452 environment.addEventListener('mouseup', onMouseUp);
3453 environment.addEventListener('touchstart', onTouchStart);
3454 environment.addEventListener('touchmove', onTouchMove);
3455 environment.addEventListener('touchend', onTouchEnd);
3456 return function () {
3457 environment.removeEventListener('mousedown', onMouseDown);
3458 environment.removeEventListener('mouseup', onMouseUp);
3459 environment.removeEventListener('touchstart', onTouchStart);
3460 environment.removeEventListener('touchmove', onTouchMove);
3461 environment.removeEventListener('touchend', onTouchEnd);
3462 }; // eslint-disable-next-line react-hooks/exhaustive-deps
3463 }, [isOpen, environment]);
3464 return mouseAndTouchTrackersRef;
3465 }
3466 /* istanbul ignore next */
3467 // eslint-disable-next-line import/no-mutable-exports
3468
3469
3470 var useGetterPropsCalledChecker = function () {
3471 return noop;
3472 };
3473 /**
3474 * Custom hook that checks if getter props are called correctly.
3475 *
3476 * @param {...any} propKeys Getter prop names to be handled.
3477 * @returns {Function} Setter function called inside getter props to set call information.
3478 */
3479
3480 /* istanbul ignore next */
3481
3482
3483 useGetterPropsCalledChecker = function () {
3484 var isInitialMountRef = react.useRef(true);
3485
3486 for (var _len = arguments.length, propKeys = new Array(_len), _key = 0; _key < _len; _key++) {
3487 propKeys[_key] = arguments[_key];
3488 }
3489
3490 var getterPropsCalledRef = react.useRef(propKeys.reduce(function (acc, propKey) {
3491 acc[propKey] = {};
3492 return acc;
3493 }, {}));
3494 react.useEffect(function () {
3495 Object.keys(getterPropsCalledRef.current).forEach(function (propKey) {
3496 var propCallInfo = getterPropsCalledRef.current[propKey];
3497
3498 if (isInitialMountRef.current) {
3499 if (!Object.keys(propCallInfo).length) {
3500 // eslint-disable-next-line no-console
3501 console.error("downshift: You forgot to call the " + propKey + " getter function on your component / element.");
3502 return;
3503 }
3504 }
3505
3506 var suppressRefError = propCallInfo.suppressRefError,
3507 refKey = propCallInfo.refKey,
3508 elementRef = propCallInfo.elementRef;
3509
3510 if ((!elementRef || !elementRef.current) && !suppressRefError) {
3511 // eslint-disable-next-line no-console
3512 console.error("downshift: The ref prop \"" + refKey + "\" from " + propKey + " was not applied correctly on your element.");
3513 }
3514 });
3515 isInitialMountRef.current = false;
3516 });
3517 var setGetterPropCallInfo = react.useCallback(function (propKey, suppressRefError, refKey, elementRef) {
3518 getterPropsCalledRef.current[propKey] = {
3519 suppressRefError: suppressRefError,
3520 refKey: refKey,
3521 elementRef: elementRef
3522 };
3523 }, []);
3524 return setGetterPropCallInfo;
3525 };
3526
3527 function useA11yMessageSetter(getA11yMessage, dependencyArray, _ref2) {
3528 var isInitialMount = _ref2.isInitialMount,
3529 highlightedIndex = _ref2.highlightedIndex,
3530 items = _ref2.items,
3531 environment = _ref2.environment,
3532 rest = _objectWithoutPropertiesLoose(_ref2, ["isInitialMount", "highlightedIndex", "items", "environment"]);
3533
3534 // Sets a11y status message on changes in state.
3535 react.useEffect(function () {
3536 if (isInitialMount) {
3537 return;
3538 }
3539
3540 updateA11yStatus(function () {
3541 return getA11yMessage(_extends({
3542 highlightedIndex: highlightedIndex,
3543 highlightedItem: items[highlightedIndex],
3544 resultCount: items.length
3545 }, rest));
3546 }, environment.document); // eslint-disable-next-line react-hooks/exhaustive-deps
3547 }, dependencyArray);
3548 }
3549
3550 function useScrollIntoView(_ref3) {
3551 var highlightedIndex = _ref3.highlightedIndex,
3552 isOpen = _ref3.isOpen,
3553 itemRefs = _ref3.itemRefs,
3554 getItemNodeFromIndex = _ref3.getItemNodeFromIndex,
3555 menuElement = _ref3.menuElement,
3556 scrollIntoViewProp = _ref3.scrollIntoView;
3557 // used not to scroll on highlight by mouse.
3558 var shouldScrollRef = react.useRef(true); // Scroll on highlighted item if change comes from keyboard.
3559
3560 useIsomorphicLayoutEffect(function () {
3561 if (highlightedIndex < 0 || !isOpen || !Object.keys(itemRefs.current).length) {
3562 return;
3563 }
3564
3565 if (shouldScrollRef.current === false) {
3566 shouldScrollRef.current = true;
3567 } else {
3568 scrollIntoViewProp(getItemNodeFromIndex(highlightedIndex), menuElement);
3569 } // eslint-disable-next-line react-hooks/exhaustive-deps
3570
3571 }, [highlightedIndex]);
3572 return shouldScrollRef;
3573 } // eslint-disable-next-line import/no-mutable-exports
3574
3575
3576 var useControlPropsValidator = noop;
3577 /* istanbul ignore next */
3578
3579 useControlPropsValidator = function (_ref4) {
3580 var isInitialMount = _ref4.isInitialMount,
3581 props = _ref4.props,
3582 state = _ref4.state;
3583 // used for checking when props are moving from controlled to uncontrolled.
3584 var prevPropsRef = react.useRef(props);
3585 react.useEffect(function () {
3586 if (isInitialMount) {
3587 return;
3588 }
3589
3590 validateControlledUnchanged(state, prevPropsRef.current, props);
3591 prevPropsRef.current = props;
3592 }, [state, props, isInitialMount]);
3593 };
3594
3595 var MenuMouseLeave = '__menu_mouse_leave__';
3596 var ItemMouseMove = '__item_mouse_move__';
3597 var ItemClick = '__item_click__';
3598 var ToggleButtonClick = '__togglebutton_click__';
3599 var FunctionToggleMenu = '__function_toggle_menu__';
3600 var FunctionOpenMenu = '__function_open_menu__';
3601 var FunctionCloseMenu = '__function_close_menu__';
3602 var FunctionSetHighlightedIndex = '__function_set_highlighted_index__';
3603 var FunctionSelectItem = '__function_select_item__';
3604 var FunctionSetInputValue = '__function_set_input_value__';
3605 var FunctionReset = '__function_reset__'; // to be used by useSelect and useCombobox
3606
3607 function productionEnumFn(state) {
3608 return state;
3609 }
3610
3611 /* eslint-disable complexity */
3612
3613 function downshiftCommonReducer(state, action) {
3614 var type = action.type,
3615 props = action.props;
3616 var changes;
3617
3618 switch (type) {
3619 case ItemMouseMove:
3620 changes = {
3621 highlightedIndex: action.index
3622 };
3623 break;
3624
3625 case MenuMouseLeave:
3626 changes = {
3627 highlightedIndex: -1
3628 };
3629 break;
3630
3631 case ToggleButtonClick:
3632 case FunctionToggleMenu:
3633 changes = {
3634 isOpen: !state.isOpen,
3635 highlightedIndex: state.isOpen ? -1 : getHighlightedIndexOnOpen(props, state, 0)
3636 };
3637 break;
3638
3639 case FunctionOpenMenu:
3640 changes = {
3641 isOpen: true,
3642 highlightedIndex: getHighlightedIndexOnOpen(props, state, 0)
3643 };
3644 break;
3645
3646 case FunctionCloseMenu:
3647 changes = {
3648 isOpen: false
3649 };
3650 break;
3651
3652 case FunctionSetHighlightedIndex:
3653 changes = {
3654 highlightedIndex: action.highlightedIndex
3655 };
3656 break;
3657
3658 case FunctionSetInputValue:
3659 changes = {
3660 inputValue: action.inputValue
3661 };
3662 break;
3663
3664 case FunctionReset:
3665 changes = {
3666 highlightedIndex: getDefaultValue(props, 'highlightedIndex'),
3667 isOpen: getDefaultValue(props, 'isOpen'),
3668 selectedItem: getDefaultValue(props, 'selectedItem'),
3669 inputValue: getDefaultValue(props, 'inputValue')
3670 };
3671 break;
3672
3673 default:
3674 throw new Error('Reducer called without proper action type.');
3675 }
3676
3677 return _extends({}, state, changes);
3678 }
3679 /* eslint-enable complexity */
3680
3681 function getItemIndexByCharacterKey(keysSoFar, highlightedIndex, items, itemToString, getItemNodeFromIndex) {
3682 var lowerCasedKeysSoFar = keysSoFar.toLowerCase();
3683
3684 for (var index = 0; index < items.length; index++) {
3685 var offsetIndex = (index + highlightedIndex + 1) % items.length;
3686
3687 if (itemToString(items[offsetIndex]).toLowerCase().startsWith(lowerCasedKeysSoFar)) {
3688 var element = getItemNodeFromIndex(offsetIndex);
3689
3690 if (!(element && element.hasAttribute('disabled'))) {
3691 return offsetIndex;
3692 }
3693 }
3694 }
3695
3696 return highlightedIndex;
3697 }
3698
3699 var propTypes$1 = {
3700 items: propTypes.array.isRequired,
3701 itemToString: propTypes.func,
3702 getA11yStatusMessage: propTypes.func,
3703 getA11ySelectionMessage: propTypes.func,
3704 circularNavigation: propTypes.bool,
3705 highlightedIndex: propTypes.number,
3706 defaultHighlightedIndex: propTypes.number,
3707 initialHighlightedIndex: propTypes.number,
3708 isOpen: propTypes.bool,
3709 defaultIsOpen: propTypes.bool,
3710 initialIsOpen: propTypes.bool,
3711 selectedItem: propTypes.any,
3712 initialSelectedItem: propTypes.any,
3713 defaultSelectedItem: propTypes.any,
3714 id: propTypes.string,
3715 labelId: propTypes.string,
3716 menuId: propTypes.string,
3717 getItemId: propTypes.func,
3718 toggleButtonId: propTypes.string,
3719 stateReducer: propTypes.func,
3720 onSelectedItemChange: propTypes.func,
3721 onHighlightedIndexChange: propTypes.func,
3722 onStateChange: propTypes.func,
3723 onIsOpenChange: propTypes.func,
3724 environment: propTypes.shape({
3725 addEventListener: propTypes.func,
3726 removeEventListener: propTypes.func,
3727 document: propTypes.shape({
3728 getElementById: propTypes.func,
3729 activeElement: propTypes.any,
3730 body: propTypes.any
3731 })
3732 })
3733 };
3734 /**
3735 * Default implementation for status message. Only added when menu is open.
3736 * Will specift if there are results in the list, and if so, how many,
3737 * and what keys are relevant.
3738 *
3739 * @param {Object} param the downshift state and other relevant properties
3740 * @return {String} the a11y status message
3741 */
3742
3743 function getA11yStatusMessage$1(_ref) {
3744 var isOpen = _ref.isOpen,
3745 resultCount = _ref.resultCount,
3746 previousResultCount = _ref.previousResultCount;
3747
3748 if (!isOpen) {
3749 return '';
3750 }
3751
3752 if (!resultCount) {
3753 return 'No results are available.';
3754 }
3755
3756 if (resultCount !== previousResultCount) {
3757 return resultCount + " result" + (resultCount === 1 ? ' is' : 's are') + " available, use up and down arrow keys to navigate. Press Enter or Space Bar keys to select.";
3758 }
3759
3760 return '';
3761 }
3762
3763 var defaultProps$1 = _extends({}, defaultProps, {
3764 getA11yStatusMessage: getA11yStatusMessage$1
3765 }); // eslint-disable-next-line import/no-mutable-exports
3766
3767
3768 var validatePropTypes = noop;
3769 /* istanbul ignore next */
3770
3771 validatePropTypes = function (options, caller) {
3772 propTypes.checkPropTypes(propTypes$1, options, 'prop', caller.name);
3773 };
3774
3775 var MenuKeyDownArrowDown = productionEnumFn('__menu_keydown_arrow_down__');
3776 var MenuKeyDownArrowUp = productionEnumFn('__menu_keydown_arrow_up__');
3777 var MenuKeyDownEscape = productionEnumFn('__menu_keydown_escape__');
3778 var MenuKeyDownHome = productionEnumFn('__menu_keydown_home__');
3779 var MenuKeyDownEnd = productionEnumFn('__menu_keydown_end__');
3780 var MenuKeyDownEnter = productionEnumFn('__menu_keydown_enter__');
3781 var MenuKeyDownSpaceButton = productionEnumFn('__menu_keydown_space_button__');
3782 var MenuKeyDownCharacter = productionEnumFn('__menu_keydown_character__');
3783 var MenuBlur = productionEnumFn('__menu_blur__');
3784 var ToggleButtonKeyDownArrowDown = productionEnumFn('__togglebutton_keydown_arrow_down__');
3785 var ToggleButtonKeyDownArrowUp = productionEnumFn('__togglebutton_keydown_arrow_up__');
3786 var ToggleButtonKeyDownCharacter = productionEnumFn('__togglebutton_keydown_character__');
3787
3788 var stateChangeTypes$1 = /*#__PURE__*/Object.freeze({
3789 __proto__: null,
3790 MenuKeyDownArrowDown: MenuKeyDownArrowDown,
3791 MenuKeyDownArrowUp: MenuKeyDownArrowUp,
3792 MenuKeyDownEscape: MenuKeyDownEscape,
3793 MenuKeyDownHome: MenuKeyDownHome,
3794 MenuKeyDownEnd: MenuKeyDownEnd,
3795 MenuKeyDownEnter: MenuKeyDownEnter,
3796 MenuKeyDownSpaceButton: MenuKeyDownSpaceButton,
3797 MenuKeyDownCharacter: MenuKeyDownCharacter,
3798 MenuBlur: MenuBlur,
3799 ToggleButtonKeyDownArrowDown: ToggleButtonKeyDownArrowDown,
3800 ToggleButtonKeyDownArrowUp: ToggleButtonKeyDownArrowUp,
3801 ToggleButtonKeyDownCharacter: ToggleButtonKeyDownCharacter,
3802 MenuMouseLeave: MenuMouseLeave,
3803 ItemMouseMove: ItemMouseMove,
3804 ItemClick: ItemClick,
3805 ToggleButtonClick: ToggleButtonClick,
3806 FunctionToggleMenu: FunctionToggleMenu,
3807 FunctionOpenMenu: FunctionOpenMenu,
3808 FunctionCloseMenu: FunctionCloseMenu,
3809 FunctionSetHighlightedIndex: FunctionSetHighlightedIndex,
3810 FunctionSelectItem: FunctionSelectItem,
3811 FunctionSetInputValue: FunctionSetInputValue,
3812 FunctionReset: FunctionReset,
3813 productionEnumFn: productionEnumFn
3814 });
3815
3816 /* eslint-disable complexity */
3817
3818 function downshiftSelectReducer(state, action) {
3819 var type = action.type,
3820 props = action.props,
3821 shiftKey = action.shiftKey;
3822 var changes;
3823
3824 switch (type) {
3825 case ItemClick:
3826 changes = {
3827 isOpen: getDefaultValue(props, 'isOpen'),
3828 highlightedIndex: getDefaultValue(props, 'highlightedIndex'),
3829 selectedItem: props.items[action.index]
3830 };
3831 break;
3832
3833 case ToggleButtonKeyDownCharacter:
3834 {
3835 var lowercasedKey = action.key;
3836 var inputValue = "" + state.inputValue + lowercasedKey;
3837 var itemIndex = getItemIndexByCharacterKey(inputValue, state.selectedItem ? props.items.indexOf(state.selectedItem) : -1, props.items, props.itemToString, action.getItemNodeFromIndex);
3838 changes = _extends({
3839 inputValue: inputValue
3840 }, itemIndex >= 0 && {
3841 selectedItem: props.items[itemIndex]
3842 });
3843 }
3844 break;
3845
3846 case ToggleButtonKeyDownArrowDown:
3847 changes = {
3848 highlightedIndex: getHighlightedIndexOnOpen(props, state, 1, action.getItemNodeFromIndex),
3849 isOpen: true
3850 };
3851 break;
3852
3853 case ToggleButtonKeyDownArrowUp:
3854 changes = {
3855 highlightedIndex: getHighlightedIndexOnOpen(props, state, -1, action.getItemNodeFromIndex),
3856 isOpen: true
3857 };
3858 break;
3859
3860 case MenuKeyDownEnter:
3861 case MenuKeyDownSpaceButton:
3862 changes = _extends({
3863 isOpen: getDefaultValue(props, 'isOpen'),
3864 highlightedIndex: getDefaultValue(props, 'highlightedIndex')
3865 }, state.highlightedIndex >= 0 && {
3866 selectedItem: props.items[state.highlightedIndex]
3867 });
3868 break;
3869
3870 case MenuKeyDownHome:
3871 changes = {
3872 highlightedIndex: getNextNonDisabledIndex(1, 0, props.items.length, action.getItemNodeFromIndex, false)
3873 };
3874 break;
3875
3876 case MenuKeyDownEnd:
3877 changes = {
3878 highlightedIndex: getNextNonDisabledIndex(-1, props.items.length - 1, props.items.length, action.getItemNodeFromIndex, false)
3879 };
3880 break;
3881
3882 case MenuKeyDownEscape:
3883 changes = {
3884 isOpen: false,
3885 highlightedIndex: -1
3886 };
3887 break;
3888
3889 case MenuBlur:
3890 changes = {
3891 isOpen: false,
3892 highlightedIndex: -1
3893 };
3894 break;
3895
3896 case MenuKeyDownCharacter:
3897 {
3898 var _lowercasedKey = action.key;
3899
3900 var _inputValue = "" + state.inputValue + _lowercasedKey;
3901
3902 var highlightedIndex = getItemIndexByCharacterKey(_inputValue, state.highlightedIndex, props.items, props.itemToString, action.getItemNodeFromIndex);
3903 changes = _extends({
3904 inputValue: _inputValue
3905 }, highlightedIndex >= 0 && {
3906 highlightedIndex: highlightedIndex
3907 });
3908 }
3909 break;
3910
3911 case MenuKeyDownArrowDown:
3912 changes = {
3913 highlightedIndex: getNextWrappingIndex(shiftKey ? 5 : 1, state.highlightedIndex, props.items.length, action.getItemNodeFromIndex, props.circularNavigation)
3914 };
3915 break;
3916
3917 case MenuKeyDownArrowUp:
3918 changes = {
3919 highlightedIndex: getNextWrappingIndex(shiftKey ? -5 : -1, state.highlightedIndex, props.items.length, action.getItemNodeFromIndex, props.circularNavigation)
3920 };
3921 break;
3922
3923 case FunctionSelectItem:
3924 changes = {
3925 selectedItem: action.selectedItem
3926 };
3927 break;
3928
3929 default:
3930 return downshiftCommonReducer(state, action);
3931 }
3932
3933 return _extends({}, state, changes);
3934 }
3935 /* eslint-enable complexity */
3936
3937 useSelect.stateChangeTypes = stateChangeTypes$1;
3938
3939 function useSelect(userProps) {
3940 if (userProps === void 0) {
3941 userProps = {};
3942 }
3943
3944 validatePropTypes(userProps, useSelect); // Props defaults and destructuring.
3945
3946 var props = _extends({}, defaultProps$1, userProps);
3947
3948 var items = props.items,
3949 scrollIntoView = props.scrollIntoView,
3950 environment = props.environment,
3951 initialIsOpen = props.initialIsOpen,
3952 defaultIsOpen = props.defaultIsOpen,
3953 itemToString = props.itemToString,
3954 getA11ySelectionMessage = props.getA11ySelectionMessage,
3955 getA11yStatusMessage = props.getA11yStatusMessage; // Initial state depending on controlled props.
3956
3957 var initialState = getInitialState(props);
3958
3959 var _useControlledReducer = useControlledReducer(downshiftSelectReducer, initialState, props),
3960 state = _useControlledReducer[0],
3961 dispatch = _useControlledReducer[1];
3962
3963 var isOpen = state.isOpen,
3964 highlightedIndex = state.highlightedIndex,
3965 selectedItem = state.selectedItem,
3966 inputValue = state.inputValue; // Element efs.
3967
3968 var toggleButtonRef = react.useRef(null);
3969 var menuRef = react.useRef(null);
3970 var itemRefs = react.useRef();
3971 itemRefs.current = {}; // used not to trigger menu blur action in some scenarios.
3972
3973 var shouldBlurRef = react.useRef(true); // used to keep the inputValue clearTimeout object between renders.
3974
3975 var clearTimeoutRef = react.useRef(null); // prevent id re-generation between renders.
3976
3977 var elementIds = useElementIds(props); // used to keep track of how many items we had on previous cycle.
3978
3979 var previousResultCountRef = react.useRef();
3980 var isInitialMountRef = react.useRef(true); // utility callback to get item element.
3981
3982 var latest = useLatestRef({
3983 state: state,
3984 props: props
3985 }); // Some utils.
3986
3987 var getItemNodeFromIndex = react.useCallback(function (index) {
3988 return itemRefs.current[elementIds.getItemId(index)];
3989 }, [elementIds]); // Effects.
3990 // Sets a11y status message on changes in state.
3991
3992 useA11yMessageSetter(getA11yStatusMessage, [isOpen, highlightedIndex, inputValue, items], _extends({
3993 isInitialMount: isInitialMountRef.current,
3994 previousResultCount: previousResultCountRef.current,
3995 items: items,
3996 environment: environment,
3997 itemToString: itemToString
3998 }, state)); // Sets a11y status message on changes in selectedItem.
3999
4000 useA11yMessageSetter(getA11ySelectionMessage, [selectedItem], _extends({
4001 isInitialMount: isInitialMountRef.current,
4002 previousResultCount: previousResultCountRef.current,
4003 items: items,
4004 environment: environment,
4005 itemToString: itemToString
4006 }, state)); // Scroll on highlighted item if change comes from keyboard.
4007
4008 var shouldScrollRef = useScrollIntoView({
4009 menuElement: menuRef.current,
4010 highlightedIndex: highlightedIndex,
4011 isOpen: isOpen,
4012 itemRefs: itemRefs,
4013 scrollIntoView: scrollIntoView,
4014 getItemNodeFromIndex: getItemNodeFromIndex
4015 }); // Sets cleanup for the keysSoFar after 500ms.
4016
4017 react.useEffect(function () {
4018 // init the clean function here as we need access to dispatch.
4019 if (isInitialMountRef.current) {
4020 clearTimeoutRef.current = debounce(function (outerDispatch) {
4021 outerDispatch({
4022 type: FunctionSetInputValue,
4023 inputValue: ''
4024 });
4025 }, 500);
4026 }
4027
4028 if (!inputValue) {
4029 return;
4030 }
4031
4032 clearTimeoutRef.current(dispatch);
4033 }, [dispatch, inputValue]);
4034 useControlPropsValidator({
4035 isInitialMount: isInitialMountRef.current,
4036 props: props,
4037 state: state
4038 });
4039 /* Controls the focus on the menu or the toggle button. */
4040
4041 react.useEffect(function () {
4042 // Don't focus menu on first render.
4043 if (isInitialMountRef.current) {
4044 // Unless it was initialised as open.
4045 if ((initialIsOpen || defaultIsOpen || isOpen) && menuRef.current) {
4046 menuRef.current.focus();
4047 }
4048
4049 return;
4050 } // Focus menu on open.
4051
4052
4053 if (isOpen) {
4054 // istanbul ignore else
4055 if (menuRef.current) {
4056 menuRef.current.focus();
4057 }
4058
4059 return;
4060 } // Focus toggleButton on close, but not if it was closed with (Shift+)Tab.
4061
4062
4063 if (environment.document.activeElement === menuRef.current) {
4064 // istanbul ignore else
4065 if (toggleButtonRef.current) {
4066 shouldBlurRef.current = false;
4067 toggleButtonRef.current.focus();
4068 }
4069 } // eslint-disable-next-line react-hooks/exhaustive-deps
4070
4071 }, [isOpen]);
4072 react.useEffect(function () {
4073 if (isInitialMountRef.current) {
4074 return;
4075 }
4076
4077 previousResultCountRef.current = items.length;
4078 }); // Add mouse/touch events to document.
4079
4080 var mouseAndTouchTrackersRef = useMouseAndTouchTracker(isOpen, [menuRef, toggleButtonRef], environment, function () {
4081 dispatch({
4082 type: MenuBlur
4083 });
4084 });
4085 var setGetterPropCallInfo = useGetterPropsCalledChecker('getMenuProps', 'getToggleButtonProps'); // Make initial ref false.
4086
4087 react.useEffect(function () {
4088 isInitialMountRef.current = false;
4089 }, []); // Event handler functions.
4090
4091 var toggleButtonKeyDownHandlers = react.useMemo(function () {
4092 return {
4093 ArrowDown: function ArrowDown(event) {
4094 event.preventDefault();
4095 dispatch({
4096 type: ToggleButtonKeyDownArrowDown,
4097 getItemNodeFromIndex: getItemNodeFromIndex,
4098 shiftKey: event.shiftKey
4099 });
4100 },
4101 ArrowUp: function ArrowUp(event) {
4102 event.preventDefault();
4103 dispatch({
4104 type: ToggleButtonKeyDownArrowUp,
4105 getItemNodeFromIndex: getItemNodeFromIndex,
4106 shiftKey: event.shiftKey
4107 });
4108 }
4109 };
4110 }, [dispatch, getItemNodeFromIndex]);
4111 var menuKeyDownHandlers = react.useMemo(function () {
4112 return {
4113 ArrowDown: function ArrowDown(event) {
4114 event.preventDefault();
4115 dispatch({
4116 type: MenuKeyDownArrowDown,
4117 getItemNodeFromIndex: getItemNodeFromIndex,
4118 shiftKey: event.shiftKey
4119 });
4120 },
4121 ArrowUp: function ArrowUp(event) {
4122 event.preventDefault();
4123 dispatch({
4124 type: MenuKeyDownArrowUp,
4125 getItemNodeFromIndex: getItemNodeFromIndex,
4126 shiftKey: event.shiftKey
4127 });
4128 },
4129 Home: function Home(event) {
4130 event.preventDefault();
4131 dispatch({
4132 type: MenuKeyDownHome,
4133 getItemNodeFromIndex: getItemNodeFromIndex
4134 });
4135 },
4136 End: function End(event) {
4137 event.preventDefault();
4138 dispatch({
4139 type: MenuKeyDownEnd,
4140 getItemNodeFromIndex: getItemNodeFromIndex
4141 });
4142 },
4143 Escape: function Escape() {
4144 dispatch({
4145 type: MenuKeyDownEscape
4146 });
4147 },
4148 Enter: function Enter(event) {
4149 event.preventDefault();
4150 dispatch({
4151 type: MenuKeyDownEnter
4152 });
4153 },
4154 ' ': function _(event) {
4155 event.preventDefault();
4156 dispatch({
4157 type: MenuKeyDownSpaceButton
4158 });
4159 }
4160 };
4161 }, [dispatch, getItemNodeFromIndex]); // Action functions.
4162
4163 var toggleMenu = react.useCallback(function () {
4164 dispatch({
4165 type: FunctionToggleMenu
4166 });
4167 }, [dispatch]);
4168 var closeMenu = react.useCallback(function () {
4169 dispatch({
4170 type: FunctionCloseMenu
4171 });
4172 }, [dispatch]);
4173 var openMenu = react.useCallback(function () {
4174 dispatch({
4175 type: FunctionOpenMenu
4176 });
4177 }, [dispatch]);
4178 var setHighlightedIndex = react.useCallback(function (newHighlightedIndex) {
4179 dispatch({
4180 type: FunctionSetHighlightedIndex,
4181 highlightedIndex: newHighlightedIndex
4182 });
4183 }, [dispatch]);
4184 var selectItem = react.useCallback(function (newSelectedItem) {
4185 dispatch({
4186 type: FunctionSelectItem,
4187 selectedItem: newSelectedItem
4188 });
4189 }, [dispatch]);
4190 var reset = react.useCallback(function () {
4191 dispatch({
4192 type: FunctionReset
4193 });
4194 }, [dispatch]);
4195 var setInputValue = react.useCallback(function (newInputValue) {
4196 dispatch({
4197 type: FunctionSetInputValue,
4198 inputValue: newInputValue
4199 });
4200 }, [dispatch]); // Getter functions.
4201
4202 var getLabelProps = react.useCallback(function (labelProps) {
4203 return _extends({
4204 id: elementIds.labelId,
4205 htmlFor: elementIds.toggleButtonId
4206 }, labelProps);
4207 }, [elementIds]);
4208 var getMenuProps = react.useCallback(function (_temp, _temp2) {
4209 var _extends2;
4210
4211 var _ref = _temp === void 0 ? {} : _temp,
4212 onMouseLeave = _ref.onMouseLeave,
4213 _ref$refKey = _ref.refKey,
4214 refKey = _ref$refKey === void 0 ? 'ref' : _ref$refKey,
4215 onKeyDown = _ref.onKeyDown,
4216 onBlur = _ref.onBlur,
4217 ref = _ref.ref,
4218 rest = _objectWithoutPropertiesLoose(_ref, ["onMouseLeave", "refKey", "onKeyDown", "onBlur", "ref"]);
4219
4220 var _ref2 = _temp2 === void 0 ? {} : _temp2,
4221 _ref2$suppressRefErro = _ref2.suppressRefError,
4222 suppressRefError = _ref2$suppressRefErro === void 0 ? false : _ref2$suppressRefErro;
4223
4224 var latestState = latest.current.state;
4225 setGetterPropCallInfo('getMenuProps', suppressRefError, refKey, menuRef);
4226 return _extends((_extends2 = {}, _extends2[refKey] = handleRefs(ref, function (menuNode) {
4227 menuRef.current = menuNode;
4228 }), _extends2.id = elementIds.menuId, _extends2.role = 'listbox', _extends2['aria-labelledby'] = elementIds.labelId, _extends2.tabIndex = -1, _extends2), latestState.isOpen && latestState.highlightedIndex > -1 && {
4229 'aria-activedescendant': elementIds.getItemId(latestState.highlightedIndex)
4230 }, {
4231 onMouseLeave: callAllEventHandlers(onMouseLeave, function menuHandleMouseLeave() {
4232 dispatch({
4233 type: MenuMouseLeave
4234 });
4235 }),
4236 onKeyDown: callAllEventHandlers(onKeyDown, function menuHandleKeyDown(event) {
4237 var key = normalizeArrowKey(event);
4238
4239 if (key && menuKeyDownHandlers[key]) {
4240 menuKeyDownHandlers[key](event);
4241 } else if (isAcceptedCharacterKey(key)) {
4242 dispatch({
4243 type: MenuKeyDownCharacter,
4244 key: key,
4245 getItemNodeFromIndex: getItemNodeFromIndex
4246 });
4247 }
4248 }),
4249 onBlur: callAllEventHandlers(onBlur, function menuHandleBlur() {
4250 // if the blur was a result of selection, we don't trigger this action.
4251 if (shouldBlurRef.current === false) {
4252 shouldBlurRef.current = true;
4253 return;
4254 }
4255
4256 var shouldBlur = !mouseAndTouchTrackersRef.current.isMouseDown;
4257 /* istanbul ignore else */
4258
4259 if (shouldBlur) {
4260 dispatch({
4261 type: MenuBlur
4262 });
4263 }
4264 })
4265 }, rest);
4266 }, [dispatch, latest, menuKeyDownHandlers, mouseAndTouchTrackersRef, setGetterPropCallInfo, elementIds, getItemNodeFromIndex]);
4267 var getToggleButtonProps = react.useCallback(function (_temp3, _temp4) {
4268 var _extends3;
4269
4270 var _ref3 = _temp3 === void 0 ? {} : _temp3,
4271 onClick = _ref3.onClick,
4272 onKeyDown = _ref3.onKeyDown,
4273 _ref3$refKey = _ref3.refKey,
4274 refKey = _ref3$refKey === void 0 ? 'ref' : _ref3$refKey,
4275 ref = _ref3.ref,
4276 rest = _objectWithoutPropertiesLoose(_ref3, ["onClick", "onKeyDown", "refKey", "ref"]);
4277
4278 var _ref4 = _temp4 === void 0 ? {} : _temp4,
4279 _ref4$suppressRefErro = _ref4.suppressRefError,
4280 suppressRefError = _ref4$suppressRefErro === void 0 ? false : _ref4$suppressRefErro;
4281
4282 var toggleButtonHandleClick = function () {
4283 dispatch({
4284 type: ToggleButtonClick
4285 });
4286 };
4287
4288 var toggleButtonHandleKeyDown = function (event) {
4289 var key = normalizeArrowKey(event);
4290
4291 if (key && toggleButtonKeyDownHandlers[key]) {
4292 toggleButtonKeyDownHandlers[key](event);
4293 } else if (isAcceptedCharacterKey(key)) {
4294 dispatch({
4295 type: ToggleButtonKeyDownCharacter,
4296 key: key,
4297 getItemNodeFromIndex: getItemNodeFromIndex
4298 });
4299 }
4300 };
4301
4302 var toggleProps = _extends((_extends3 = {}, _extends3[refKey] = handleRefs(ref, function (toggleButtonNode) {
4303 toggleButtonRef.current = toggleButtonNode;
4304 }), _extends3.id = elementIds.toggleButtonId, _extends3['aria-haspopup'] = 'listbox', _extends3['aria-expanded'] = latest.current.state.isOpen, _extends3['aria-labelledby'] = elementIds.labelId + " " + elementIds.toggleButtonId, _extends3), rest);
4305
4306 if (!rest.disabled) {
4307 toggleProps.onClick = callAllEventHandlers(onClick, toggleButtonHandleClick);
4308 toggleProps.onKeyDown = callAllEventHandlers(onKeyDown, toggleButtonHandleKeyDown);
4309 }
4310
4311 setGetterPropCallInfo('getToggleButtonProps', suppressRefError, refKey, toggleButtonRef);
4312 return toggleProps;
4313 }, [dispatch, latest, toggleButtonKeyDownHandlers, setGetterPropCallInfo, elementIds, getItemNodeFromIndex]);
4314 var getItemProps = react.useCallback(function (_temp5) {
4315 var _extends4;
4316
4317 var _ref5 = _temp5 === void 0 ? {} : _temp5,
4318 item = _ref5.item,
4319 index = _ref5.index,
4320 onMouseMove = _ref5.onMouseMove,
4321 onClick = _ref5.onClick,
4322 _ref5$refKey = _ref5.refKey,
4323 refKey = _ref5$refKey === void 0 ? 'ref' : _ref5$refKey,
4324 ref = _ref5.ref,
4325 rest = _objectWithoutPropertiesLoose(_ref5, ["item", "index", "onMouseMove", "onClick", "refKey", "ref"]);
4326
4327 var _latest$current = latest.current,
4328 latestState = _latest$current.state,
4329 latestProps = _latest$current.props;
4330
4331 var itemHandleMouseMove = function () {
4332 if (index === latestState.highlightedIndex) {
4333 return;
4334 }
4335
4336 shouldScrollRef.current = false;
4337 dispatch({
4338 type: ItemMouseMove,
4339 index: index
4340 });
4341 };
4342
4343 var itemHandleClick = function () {
4344 dispatch({
4345 type: ItemClick,
4346 index: index
4347 });
4348 };
4349
4350 var itemIndex = getItemIndex(index, item, latestProps.items);
4351
4352 if (itemIndex < 0) {
4353 throw new Error('Pass either item or item index in getItemProps!');
4354 }
4355
4356 var itemProps = _extends((_extends4 = {
4357 role: 'option',
4358 'aria-selected': "" + (itemIndex === latestState.highlightedIndex),
4359 id: elementIds.getItemId(itemIndex)
4360 }, _extends4[refKey] = handleRefs(ref, function (itemNode) {
4361 if (itemNode) {
4362 itemRefs.current[elementIds.getItemId(itemIndex)] = itemNode;
4363 }
4364 }), _extends4), rest);
4365
4366 if (!rest.disabled) {
4367 itemProps.onMouseMove = callAllEventHandlers(onMouseMove, itemHandleMouseMove);
4368 itemProps.onClick = callAllEventHandlers(onClick, itemHandleClick);
4369 }
4370
4371 return itemProps;
4372 }, [dispatch, latest, shouldScrollRef, elementIds]);
4373 return {
4374 // prop getters.
4375 getToggleButtonProps: getToggleButtonProps,
4376 getLabelProps: getLabelProps,
4377 getMenuProps: getMenuProps,
4378 getItemProps: getItemProps,
4379 // actions.
4380 toggleMenu: toggleMenu,
4381 openMenu: openMenu,
4382 closeMenu: closeMenu,
4383 setHighlightedIndex: setHighlightedIndex,
4384 selectItem: selectItem,
4385 reset: reset,
4386 setInputValue: setInputValue,
4387 // state.
4388 highlightedIndex: highlightedIndex,
4389 isOpen: isOpen,
4390 selectedItem: selectedItem,
4391 inputValue: inputValue
4392 };
4393 }
4394
4395 var InputKeyDownArrowDown = productionEnumFn('__input_keydown_arrow_down__');
4396 var InputKeyDownArrowUp = productionEnumFn('__input_keydown_arrow_up__');
4397 var InputKeyDownEscape = productionEnumFn('__input_keydown_escape__');
4398 var InputKeyDownHome = productionEnumFn('__input_keydown_home__');
4399 var InputKeyDownEnd = productionEnumFn('__input_keydown_end__');
4400 var InputKeyDownEnter = productionEnumFn('__input_keydown_enter__');
4401 var InputChange = productionEnumFn('__input_change__');
4402 var InputBlur = productionEnumFn('__input_blur__');
4403 var ControlledPropUpdatedSelectedItem = productionEnumFn('__controlled_prop_updated_selected_item__');
4404
4405 var stateChangeTypes$2 = /*#__PURE__*/Object.freeze({
4406 __proto__: null,
4407 InputKeyDownArrowDown: InputKeyDownArrowDown,
4408 InputKeyDownArrowUp: InputKeyDownArrowUp,
4409 InputKeyDownEscape: InputKeyDownEscape,
4410 InputKeyDownHome: InputKeyDownHome,
4411 InputKeyDownEnd: InputKeyDownEnd,
4412 InputKeyDownEnter: InputKeyDownEnter,
4413 InputChange: InputChange,
4414 InputBlur: InputBlur,
4415 ControlledPropUpdatedSelectedItem: ControlledPropUpdatedSelectedItem,
4416 MenuMouseLeave: MenuMouseLeave,
4417 ItemMouseMove: ItemMouseMove,
4418 ItemClick: ItemClick,
4419 ToggleButtonClick: ToggleButtonClick,
4420 FunctionToggleMenu: FunctionToggleMenu,
4421 FunctionOpenMenu: FunctionOpenMenu,
4422 FunctionCloseMenu: FunctionCloseMenu,
4423 FunctionSetHighlightedIndex: FunctionSetHighlightedIndex,
4424 FunctionSelectItem: FunctionSelectItem,
4425 FunctionSetInputValue: FunctionSetInputValue,
4426 FunctionReset: FunctionReset,
4427 productionEnumFn: productionEnumFn
4428 });
4429
4430 function getInitialState$1(props) {
4431 var initialState = getInitialState(props);
4432 var selectedItem = initialState.selectedItem;
4433 var inputValue = initialState.inputValue;
4434
4435 if (inputValue === '' && selectedItem && props.defaultInputValue === undefined && props.initialInputValue === undefined && props.inputValue === undefined) {
4436 inputValue = props.itemToString(selectedItem);
4437 }
4438
4439 return _extends({}, initialState, {
4440 inputValue: inputValue
4441 });
4442 }
4443
4444 var propTypes$2 = {
4445 items: propTypes.array.isRequired,
4446 itemToString: propTypes.func,
4447 getA11yStatusMessage: propTypes.func,
4448 getA11ySelectionMessage: propTypes.func,
4449 circularNavigation: propTypes.bool,
4450 highlightedIndex: propTypes.number,
4451 defaultHighlightedIndex: propTypes.number,
4452 initialHighlightedIndex: propTypes.number,
4453 isOpen: propTypes.bool,
4454 defaultIsOpen: propTypes.bool,
4455 initialIsOpen: propTypes.bool,
4456 selectedItem: propTypes.any,
4457 initialSelectedItem: propTypes.any,
4458 defaultSelectedItem: propTypes.any,
4459 inputValue: propTypes.string,
4460 defaultInputValue: propTypes.string,
4461 initialInputValue: propTypes.string,
4462 id: propTypes.string,
4463 labelId: propTypes.string,
4464 menuId: propTypes.string,
4465 getItemId: propTypes.func,
4466 inputId: propTypes.string,
4467 toggleButtonId: propTypes.string,
4468 stateReducer: propTypes.func,
4469 onSelectedItemChange: propTypes.func,
4470 onHighlightedIndexChange: propTypes.func,
4471 onStateChange: propTypes.func,
4472 onIsOpenChange: propTypes.func,
4473 onInputValueChange: propTypes.func,
4474 environment: propTypes.shape({
4475 addEventListener: propTypes.func,
4476 removeEventListener: propTypes.func,
4477 document: propTypes.shape({
4478 getElementById: propTypes.func,
4479 activeElement: propTypes.any,
4480 body: propTypes.any
4481 })
4482 })
4483 };
4484 /**
4485 * The useCombobox version of useControlledReducer, which also
4486 * checks if the controlled prop selectedItem changed between
4487 * renders. If so, it will also update inputValue with its
4488 * string equivalent. It uses the common useEnhancedReducer to
4489 * compute the rest of the state.
4490 *
4491 * @param {Function} reducer Reducer function from downshift.
4492 * @param {Object} initialState Initial state of the hook.
4493 * @param {Object} props The hook props.
4494 * @returns {Array} An array with the state and an action dispatcher.
4495 */
4496
4497 function useControlledReducer$1(reducer, initialState, props) {
4498 var previousSelectedItemRef = react.useRef();
4499
4500 var _useEnhancedReducer = useEnhancedReducer(reducer, initialState, props),
4501 state = _useEnhancedReducer[0],
4502 dispatch = _useEnhancedReducer[1]; // ToDo: if needed, make same approach as selectedItemChanged from Downshift.
4503
4504
4505 react.useEffect(function () {
4506 if (isControlledProp(props, 'selectedItem')) {
4507 if (previousSelectedItemRef.current !== props.selectedItem) {
4508 dispatch({
4509 type: ControlledPropUpdatedSelectedItem,
4510 inputValue: props.itemToString(props.selectedItem)
4511 });
4512 }
4513
4514 previousSelectedItemRef.current = state.selectedItem === previousSelectedItemRef.current ? props.selectedItem : state.selectedItem;
4515 }
4516 });
4517 return [getState(state, props), dispatch];
4518 } // eslint-disable-next-line import/no-mutable-exports
4519
4520
4521 var validatePropTypes$1 = noop;
4522 /* istanbul ignore next */
4523
4524 validatePropTypes$1 = function (options, caller) {
4525 propTypes.checkPropTypes(propTypes$2, options, 'prop', caller.name);
4526 };
4527
4528 var defaultProps$2 = _extends({}, defaultProps, {
4529 getA11yStatusMessage: getA11yStatusMessage,
4530 circularNavigation: true
4531 });
4532
4533 /* eslint-disable complexity */
4534
4535 function downshiftUseComboboxReducer(state, action) {
4536 var type = action.type,
4537 props = action.props,
4538 shiftKey = action.shiftKey;
4539 var changes;
4540
4541 switch (type) {
4542 case ItemClick:
4543 changes = {
4544 isOpen: getDefaultValue(props, 'isOpen'),
4545 highlightedIndex: getDefaultValue(props, 'highlightedIndex'),
4546 selectedItem: props.items[action.index],
4547 inputValue: props.itemToString(props.items[action.index])
4548 };
4549 break;
4550
4551 case InputKeyDownArrowDown:
4552 if (state.isOpen) {
4553 changes = {
4554 highlightedIndex: getNextWrappingIndex(shiftKey ? 5 : 1, state.highlightedIndex, props.items.length, action.getItemNodeFromIndex, props.circularNavigation)
4555 };
4556 } else {
4557 changes = {
4558 highlightedIndex: getHighlightedIndexOnOpen(props, state, 1, action.getItemNodeFromIndex),
4559 isOpen: true
4560 };
4561 }
4562
4563 break;
4564
4565 case InputKeyDownArrowUp:
4566 if (state.isOpen) {
4567 changes = {
4568 highlightedIndex: getNextWrappingIndex(shiftKey ? -5 : -1, state.highlightedIndex, props.items.length, action.getItemNodeFromIndex, props.circularNavigation)
4569 };
4570 } else {
4571 changes = {
4572 highlightedIndex: getHighlightedIndexOnOpen(props, state, -1, action.getItemNodeFromIndex),
4573 isOpen: true
4574 };
4575 }
4576
4577 break;
4578
4579 case InputKeyDownEnter:
4580 changes = _extends({}, state.isOpen && state.highlightedIndex >= 0 && {
4581 selectedItem: props.items[state.highlightedIndex],
4582 isOpen: getDefaultValue(props, 'isOpen'),
4583 highlightedIndex: getDefaultValue(props, 'highlightedIndex'),
4584 inputValue: props.itemToString(props.items[state.highlightedIndex])
4585 });
4586 break;
4587
4588 case InputKeyDownEscape:
4589 changes = _extends({
4590 isOpen: false,
4591 highlightedIndex: -1
4592 }, !state.isOpen && {
4593 selectedItem: null,
4594 inputValue: ''
4595 });
4596 break;
4597
4598 case InputKeyDownHome:
4599 changes = _extends({}, state.isOpen && {
4600 highlightedIndex: getNextNonDisabledIndex(1, 0, props.items.length, action.getItemNodeFromIndex, false)
4601 });
4602 break;
4603
4604 case InputKeyDownEnd:
4605 changes = _extends({}, state.isOpen && {
4606 highlightedIndex: getNextNonDisabledIndex(-1, props.items.length - 1, props.items.length, action.getItemNodeFromIndex, false)
4607 });
4608 break;
4609
4610 case InputBlur:
4611 if (state.isOpen) {
4612 changes = _extends({
4613 isOpen: false,
4614 highlightedIndex: -1
4615 }, state.highlightedIndex >= 0 && action.selectItem && {
4616 selectedItem: props.items[state.highlightedIndex],
4617 inputValue: props.itemToString(props.items[state.highlightedIndex])
4618 });
4619 }
4620
4621 break;
4622
4623 case InputChange:
4624 changes = {
4625 isOpen: true,
4626 highlightedIndex: getDefaultValue(props, 'highlightedIndex'),
4627 inputValue: action.inputValue
4628 };
4629 break;
4630
4631 case FunctionSelectItem:
4632 changes = {
4633 selectedItem: action.selectedItem,
4634 inputValue: props.itemToString(action.selectedItem)
4635 };
4636 break;
4637
4638 case ControlledPropUpdatedSelectedItem:
4639 changes = {
4640 inputValue: action.inputValue
4641 };
4642 break;
4643
4644 default:
4645 return downshiftCommonReducer(state, action);
4646 }
4647
4648 return _extends({}, state, changes);
4649 }
4650 /* eslint-enable complexity */
4651
4652 useCombobox.stateChangeTypes = stateChangeTypes$2;
4653
4654 function useCombobox(userProps) {
4655 if (userProps === void 0) {
4656 userProps = {};
4657 }
4658
4659 validatePropTypes$1(userProps, useCombobox); // Props defaults and destructuring.
4660
4661 var props = _extends({}, defaultProps$2, userProps);
4662
4663 var initialIsOpen = props.initialIsOpen,
4664 defaultIsOpen = props.defaultIsOpen,
4665 items = props.items,
4666 scrollIntoView = props.scrollIntoView,
4667 environment = props.environment,
4668 getA11yStatusMessage = props.getA11yStatusMessage,
4669 getA11ySelectionMessage = props.getA11ySelectionMessage,
4670 itemToString = props.itemToString; // Initial state depending on controlled props.
4671
4672 var initialState = getInitialState$1(props);
4673
4674 var _useControlledReducer = useControlledReducer$1(downshiftUseComboboxReducer, initialState, props),
4675 state = _useControlledReducer[0],
4676 dispatch = _useControlledReducer[1];
4677
4678 var isOpen = state.isOpen,
4679 highlightedIndex = state.highlightedIndex,
4680 selectedItem = state.selectedItem,
4681 inputValue = state.inputValue; // Element refs.
4682
4683 var menuRef = react.useRef(null);
4684 var itemRefs = react.useRef();
4685 var inputRef = react.useRef(null);
4686 var toggleButtonRef = react.useRef(null);
4687 var comboboxRef = react.useRef(null);
4688 itemRefs.current = {};
4689 var isInitialMountRef = react.useRef(true); // prevent id re-generation between renders.
4690
4691 var elementIds = useElementIds(props); // used to keep track of how many items we had on previous cycle.
4692
4693 var previousResultCountRef = react.useRef(); // utility callback to get item element.
4694
4695 var latest = useLatestRef({
4696 state: state,
4697 props: props
4698 });
4699 var getItemNodeFromIndex = react.useCallback(function (index) {
4700 return itemRefs.current[elementIds.getItemId(index)];
4701 }, [elementIds]); // Effects.
4702 // Sets a11y status message on changes in state.
4703
4704 useA11yMessageSetter(getA11yStatusMessage, [isOpen, highlightedIndex, inputValue, items], _extends({
4705 isInitialMount: isInitialMountRef.current,
4706 previousResultCount: previousResultCountRef.current,
4707 items: items,
4708 environment: environment,
4709 itemToString: itemToString
4710 }, state)); // Sets a11y status message on changes in selectedItem.
4711
4712 useA11yMessageSetter(getA11ySelectionMessage, [selectedItem], _extends({
4713 isInitialMount: isInitialMountRef.current,
4714 previousResultCount: previousResultCountRef.current,
4715 items: items,
4716 environment: environment,
4717 itemToString: itemToString
4718 }, state)); // Scroll on highlighted item if change comes from keyboard.
4719
4720 var shouldScrollRef = useScrollIntoView({
4721 menuElement: menuRef.current,
4722 highlightedIndex: highlightedIndex,
4723 isOpen: isOpen,
4724 itemRefs: itemRefs,
4725 scrollIntoView: scrollIntoView,
4726 getItemNodeFromIndex: getItemNodeFromIndex
4727 });
4728 useControlPropsValidator({
4729 isInitialMount: isInitialMountRef.current,
4730 props: props,
4731 state: state
4732 }); // Focus the input on first render if required.
4733
4734 react.useEffect(function () {
4735 if ((initialIsOpen || defaultIsOpen || isOpen) && inputRef.current) {
4736 inputRef.current.focus();
4737 } // eslint-disable-next-line react-hooks/exhaustive-deps
4738
4739 }, []);
4740 react.useEffect(function () {
4741 if (isInitialMountRef.current) {
4742 return;
4743 }
4744
4745 previousResultCountRef.current = items.length;
4746 }); // Add mouse/touch events to document.
4747
4748 var mouseAndTouchTrackersRef = useMouseAndTouchTracker(isOpen, [comboboxRef, menuRef, toggleButtonRef], environment, function () {
4749 dispatch({
4750 type: InputBlur,
4751 selectItem: false
4752 });
4753 });
4754 var setGetterPropCallInfo = useGetterPropsCalledChecker('getInputProps', 'getComboboxProps', 'getMenuProps'); // Make initial ref false.
4755
4756 react.useEffect(function () {
4757 isInitialMountRef.current = false;
4758 }, []);
4759 /* Event handler functions */
4760
4761 var inputKeyDownHandlers = react.useMemo(function () {
4762 return {
4763 ArrowDown: function ArrowDown(event) {
4764 event.preventDefault();
4765 dispatch({
4766 type: InputKeyDownArrowDown,
4767 shiftKey: event.shiftKey,
4768 getItemNodeFromIndex: getItemNodeFromIndex
4769 });
4770 },
4771 ArrowUp: function ArrowUp(event) {
4772 event.preventDefault();
4773 dispatch({
4774 type: InputKeyDownArrowUp,
4775 shiftKey: event.shiftKey,
4776 getItemNodeFromIndex: getItemNodeFromIndex
4777 });
4778 },
4779 Home: function Home(event) {
4780 event.preventDefault();
4781 dispatch({
4782 type: InputKeyDownHome,
4783 getItemNodeFromIndex: getItemNodeFromIndex
4784 });
4785 },
4786 End: function End(event) {
4787 event.preventDefault();
4788 dispatch({
4789 type: InputKeyDownEnd,
4790 getItemNodeFromIndex: getItemNodeFromIndex
4791 });
4792 },
4793 Escape: function Escape() {
4794 dispatch({
4795 type: InputKeyDownEscape
4796 });
4797 },
4798 Enter: function Enter(event) {
4799 // if IME composing, wait for next Enter keydown event.
4800 if (event.which === 229) {
4801 return;
4802 }
4803
4804 var latestState = latest.current.state;
4805
4806 if (latestState.isOpen) {
4807 event.preventDefault();
4808 }
4809
4810 dispatch({
4811 type: InputKeyDownEnter,
4812 getItemNodeFromIndex: getItemNodeFromIndex
4813 });
4814 }
4815 };
4816 }, [dispatch, latest, getItemNodeFromIndex]); // Getter props.
4817
4818 var getLabelProps = react.useCallback(function (labelProps) {
4819 return _extends({
4820 id: elementIds.labelId,
4821 htmlFor: elementIds.inputId
4822 }, labelProps);
4823 }, [elementIds]);
4824 var getMenuProps = react.useCallback(function (_temp, _temp2) {
4825 var _extends2;
4826
4827 var _ref = _temp === void 0 ? {} : _temp,
4828 onMouseLeave = _ref.onMouseLeave,
4829 _ref$refKey = _ref.refKey,
4830 refKey = _ref$refKey === void 0 ? 'ref' : _ref$refKey,
4831 ref = _ref.ref,
4832 rest = _objectWithoutPropertiesLoose(_ref, ["onMouseLeave", "refKey", "ref"]);
4833
4834 var _ref2 = _temp2 === void 0 ? {} : _temp2,
4835 _ref2$suppressRefErro = _ref2.suppressRefError,
4836 suppressRefError = _ref2$suppressRefErro === void 0 ? false : _ref2$suppressRefErro;
4837
4838 setGetterPropCallInfo('getMenuProps', suppressRefError, refKey, menuRef);
4839 return _extends((_extends2 = {}, _extends2[refKey] = handleRefs(ref, function (menuNode) {
4840 menuRef.current = menuNode;
4841 }), _extends2.id = elementIds.menuId, _extends2.role = 'listbox', _extends2['aria-labelledby'] = elementIds.labelId, _extends2.onMouseLeave = callAllEventHandlers(onMouseLeave, function () {
4842 dispatch({
4843 type: MenuMouseLeave
4844 });
4845 }), _extends2), rest);
4846 }, [dispatch, setGetterPropCallInfo, elementIds]);
4847 var getItemProps = react.useCallback(function (_temp3) {
4848 var _extends3, _ref4;
4849
4850 var _ref3 = _temp3 === void 0 ? {} : _temp3,
4851 item = _ref3.item,
4852 index = _ref3.index,
4853 _ref3$refKey = _ref3.refKey,
4854 refKey = _ref3$refKey === void 0 ? 'ref' : _ref3$refKey,
4855 ref = _ref3.ref,
4856 onMouseMove = _ref3.onMouseMove,
4857 onClick = _ref3.onClick,
4858 onPress = _ref3.onPress,
4859 rest = _objectWithoutPropertiesLoose(_ref3, ["item", "index", "refKey", "ref", "onMouseMove", "onClick", "onPress"]);
4860
4861 var _latest$current = latest.current,
4862 latestProps = _latest$current.props,
4863 latestState = _latest$current.state;
4864 var itemIndex = getItemIndex(index, item, latestProps.items);
4865
4866 if (itemIndex < 0) {
4867 throw new Error('Pass either item or item index in getItemProps!');
4868 }
4869
4870 var onSelectKey = 'onClick';
4871 var customClickHandler = onClick;
4872 return _extends((_extends3 = {}, _extends3[refKey] = handleRefs(ref, function (itemNode) {
4873 if (itemNode) {
4874 itemRefs.current[elementIds.getItemId(itemIndex)] = itemNode;
4875 }
4876 }), _extends3.role = 'option', _extends3['aria-selected'] = "" + (itemIndex === latestState.highlightedIndex), _extends3.id = elementIds.getItemId(itemIndex), _extends3), !rest.disabled && (_ref4 = {
4877 onMouseMove: callAllEventHandlers(onMouseMove, function itemHandleMouseMove() {
4878 if (index === latestState.highlightedIndex) {
4879 return;
4880 }
4881
4882 shouldScrollRef.current = false;
4883 dispatch({
4884 type: ItemMouseMove,
4885 index: index
4886 });
4887 })
4888 }, _ref4[onSelectKey] = callAllEventHandlers(customClickHandler, function itemHandleClick() {
4889 dispatch({
4890 type: ItemClick,
4891 index: index
4892 });
4893
4894 if (inputRef.current) {
4895 inputRef.current.focus();
4896 }
4897 }), _ref4), rest);
4898 }, [dispatch, latest, shouldScrollRef, elementIds]);
4899 var getToggleButtonProps = react.useCallback(function (_temp4) {
4900 var _extends4;
4901
4902 var _ref5 = _temp4 === void 0 ? {} : _temp4,
4903 onClick = _ref5.onClick,
4904 onPress = _ref5.onPress,
4905 _ref5$refKey = _ref5.refKey,
4906 refKey = _ref5$refKey === void 0 ? 'ref' : _ref5$refKey,
4907 ref = _ref5.ref,
4908 rest = _objectWithoutPropertiesLoose(_ref5, ["onClick", "onPress", "refKey", "ref"]);
4909
4910 var toggleButtonHandleClick = function () {
4911 dispatch({
4912 type: ToggleButtonClick
4913 });
4914
4915 if (!latest.current.state.isOpen && inputRef.current) {
4916 inputRef.current.focus();
4917 }
4918 };
4919
4920 return _extends((_extends4 = {}, _extends4[refKey] = handleRefs(ref, function (toggleButtonNode) {
4921 toggleButtonRef.current = toggleButtonNode;
4922 }), _extends4.id = elementIds.toggleButtonId, _extends4.tabIndex = -1, _extends4), !rest.disabled && _extends({}, {
4923 onClick: callAllEventHandlers(onClick, toggleButtonHandleClick)
4924 }), rest);
4925 }, [dispatch, latest, elementIds]);
4926 var getInputProps = react.useCallback(function (_temp5, _temp6) {
4927 var _extends5;
4928
4929 var _ref6 = _temp5 === void 0 ? {} : _temp5,
4930 onKeyDown = _ref6.onKeyDown,
4931 onChange = _ref6.onChange,
4932 onInput = _ref6.onInput,
4933 onBlur = _ref6.onBlur,
4934 onChangeText = _ref6.onChangeText,
4935 _ref6$refKey = _ref6.refKey,
4936 refKey = _ref6$refKey === void 0 ? 'ref' : _ref6$refKey,
4937 ref = _ref6.ref,
4938 rest = _objectWithoutPropertiesLoose(_ref6, ["onKeyDown", "onChange", "onInput", "onBlur", "onChangeText", "refKey", "ref"]);
4939
4940 var _ref7 = _temp6 === void 0 ? {} : _temp6,
4941 _ref7$suppressRefErro = _ref7.suppressRefError,
4942 suppressRefError = _ref7$suppressRefErro === void 0 ? false : _ref7$suppressRefErro;
4943
4944 setGetterPropCallInfo('getInputProps', suppressRefError, refKey, inputRef);
4945 var latestState = latest.current.state;
4946
4947 var inputHandleKeyDown = function (event) {
4948 var key = normalizeArrowKey(event);
4949
4950 if (key && inputKeyDownHandlers[key]) {
4951 inputKeyDownHandlers[key](event);
4952 }
4953 };
4954
4955 var inputHandleChange = function (event) {
4956 dispatch({
4957 type: InputChange,
4958 inputValue: event.target.value
4959 });
4960 };
4961
4962 var inputHandleBlur = function () {
4963 /* istanbul ignore else */
4964 if (!mouseAndTouchTrackersRef.current.isMouseDown) {
4965 dispatch({
4966 type: InputBlur,
4967 selectItem: true
4968 });
4969 }
4970 };
4971 /* istanbul ignore next (preact) */
4972
4973
4974 var onChangeKey = 'onChange';
4975 var eventHandlers = {};
4976
4977 if (!rest.disabled) {
4978 var _eventHandlers;
4979
4980 eventHandlers = (_eventHandlers = {}, _eventHandlers[onChangeKey] = callAllEventHandlers(onChange, onInput, inputHandleChange), _eventHandlers.onKeyDown = callAllEventHandlers(onKeyDown, inputHandleKeyDown), _eventHandlers.onBlur = callAllEventHandlers(onBlur, inputHandleBlur), _eventHandlers);
4981 }
4982 /* istanbul ignore if (react-native) */
4983
4984
4985 return _extends((_extends5 = {}, _extends5[refKey] = handleRefs(ref, function (inputNode) {
4986 inputRef.current = inputNode;
4987 }), _extends5.id = elementIds.inputId, _extends5['aria-autocomplete'] = 'list', _extends5['aria-controls'] = elementIds.menuId, _extends5), latestState.isOpen && latestState.highlightedIndex > -1 && {
4988 'aria-activedescendant': elementIds.getItemId(latestState.highlightedIndex)
4989 }, {
4990 'aria-labelledby': elementIds.labelId,
4991 // https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion
4992 // revert back since autocomplete="nope" is ignored on latest Chrome and Opera
4993 autoComplete: 'off',
4994 value: latestState.inputValue
4995 }, eventHandlers, rest);
4996 }, [dispatch, inputKeyDownHandlers, latest, mouseAndTouchTrackersRef, setGetterPropCallInfo, elementIds]);
4997 var getComboboxProps = react.useCallback(function (_temp7, _temp8) {
4998 var _extends6;
4999
5000 var _ref8 = _temp7 === void 0 ? {} : _temp7,
5001 _ref8$refKey = _ref8.refKey,
5002 refKey = _ref8$refKey === void 0 ? 'ref' : _ref8$refKey,
5003 ref = _ref8.ref,
5004 rest = _objectWithoutPropertiesLoose(_ref8, ["refKey", "ref"]);
5005
5006 var _ref9 = _temp8 === void 0 ? {} : _temp8,
5007 _ref9$suppressRefErro = _ref9.suppressRefError,
5008 suppressRefError = _ref9$suppressRefErro === void 0 ? false : _ref9$suppressRefErro;
5009
5010 setGetterPropCallInfo('getComboboxProps', suppressRefError, refKey, comboboxRef);
5011 return _extends((_extends6 = {}, _extends6[refKey] = handleRefs(ref, function (comboboxNode) {
5012 comboboxRef.current = comboboxNode;
5013 }), _extends6.role = 'combobox', _extends6['aria-haspopup'] = 'listbox', _extends6['aria-owns'] = elementIds.menuId, _extends6['aria-expanded'] = latest.current.state.isOpen, _extends6), rest);
5014 }, [latest, setGetterPropCallInfo, elementIds]); // returns
5015
5016 var toggleMenu = react.useCallback(function () {
5017 dispatch({
5018 type: FunctionToggleMenu
5019 });
5020 }, [dispatch]);
5021 var closeMenu = react.useCallback(function () {
5022 dispatch({
5023 type: FunctionCloseMenu
5024 });
5025 }, [dispatch]);
5026 var openMenu = react.useCallback(function () {
5027 dispatch({
5028 type: FunctionOpenMenu
5029 });
5030 }, [dispatch]);
5031 var setHighlightedIndex = react.useCallback(function (newHighlightedIndex) {
5032 dispatch({
5033 type: FunctionSetHighlightedIndex,
5034 highlightedIndex: newHighlightedIndex
5035 });
5036 }, [dispatch]);
5037 var selectItem = react.useCallback(function (newSelectedItem) {
5038 dispatch({
5039 type: FunctionSelectItem,
5040 selectedItem: newSelectedItem
5041 });
5042 }, [dispatch]);
5043 var setInputValue = react.useCallback(function (newInputValue) {
5044 dispatch({
5045 type: FunctionSetInputValue,
5046 inputValue: newInputValue
5047 });
5048 }, [dispatch]);
5049 var reset = react.useCallback(function () {
5050 dispatch({
5051 type: FunctionReset
5052 });
5053 }, [dispatch]);
5054 return {
5055 // prop getters.
5056 getItemProps: getItemProps,
5057 getLabelProps: getLabelProps,
5058 getMenuProps: getMenuProps,
5059 getInputProps: getInputProps,
5060 getComboboxProps: getComboboxProps,
5061 getToggleButtonProps: getToggleButtonProps,
5062 // actions.
5063 toggleMenu: toggleMenu,
5064 openMenu: openMenu,
5065 closeMenu: closeMenu,
5066 setHighlightedIndex: setHighlightedIndex,
5067 setInputValue: setInputValue,
5068 selectItem: selectItem,
5069 reset: reset,
5070 // state.
5071 highlightedIndex: highlightedIndex,
5072 isOpen: isOpen,
5073 selectedItem: selectedItem,
5074 inputValue: inputValue
5075 };
5076 }
5077
5078 var defaultStateValues = {
5079 activeIndex: -1,
5080 selectedItems: []
5081 };
5082 /**
5083 * Returns the initial value for a state key in the following order:
5084 * 1. controlled prop, 2. initial prop, 3. default prop, 4. default
5085 * value from Downshift.
5086 *
5087 * @param {Object} props Props passed to the hook.
5088 * @param {string} propKey Props key to generate the value for.
5089 * @returns {any} The initial value for that prop.
5090 */
5091
5092 function getInitialValue$1(props, propKey) {
5093 return getInitialValue(props, propKey, defaultStateValues);
5094 }
5095 /**
5096 * Returns the default value for a state key in the following order:
5097 * 1. controlled prop, 2. default prop, 3. default value from Downshift.
5098 *
5099 * @param {Object} props Props passed to the hook.
5100 * @param {string} propKey Props key to generate the value for.
5101 * @returns {any} The initial value for that prop.
5102 */
5103
5104
5105 function getDefaultValue$1(props, propKey) {
5106 return getDefaultValue(props, propKey, defaultStateValues);
5107 }
5108 /**
5109 * Gets the initial state based on the provided props. It uses initial, default
5110 * and controlled props related to state in order to compute the initial value.
5111 *
5112 * @param {Object} props Props passed to the hook.
5113 * @returns {Object} The initial state.
5114 */
5115
5116
5117 function getInitialState$2(props) {
5118 var activeIndex = getInitialValue$1(props, 'activeIndex');
5119 var selectedItems = getInitialValue$1(props, 'selectedItems');
5120 return {
5121 activeIndex: activeIndex,
5122 selectedItems: selectedItems
5123 };
5124 }
5125 /**
5126 * Returns true if dropdown keydown operation is permitted. Should not be
5127 * allowed on keydown with modifier keys (ctrl, alt, shift, meta), on
5128 * input element with text content that is either highlighted or selection
5129 * cursor is not at the starting position.
5130 *
5131 * @param {KeyboardEvent} event The event from keydown.
5132 * @returns {boolean} Whether the operation is allowed.
5133 */
5134
5135
5136 function isKeyDownOperationPermitted(event) {
5137 if (event.shiftKey || event.metaKey || event.ctrlKey || event.altKey) {
5138 return false;
5139 }
5140
5141 var element = event.target;
5142
5143 if (element instanceof HTMLInputElement && // if element is a text input
5144 element.value !== '' && ( // and we have text in it
5145 // and cursor is either not at the start or is currently highlighting text.
5146 element.selectionStart !== 0 || element.selectionEnd !== 0)) {
5147 return false;
5148 }
5149
5150 return true;
5151 }
5152 /**
5153 * Returns a message to be added to aria-live region when item is removed.
5154 *
5155 * @param {Object} selectionParameters Parameters required to build the message.
5156 * @returns {string} The a11y message.
5157 */
5158
5159
5160 function getA11yRemovalMessage(selectionParameters) {
5161 var removedSelectedItem = selectionParameters.removedSelectedItem,
5162 itemToStringLocal = selectionParameters.itemToString;
5163 return itemToStringLocal(removedSelectedItem) + " has been removed.";
5164 }
5165
5166 var propTypes$3 = {
5167 selectedItems: propTypes.array,
5168 initialSelectedItems: propTypes.array,
5169 defaultSelectedItems: propTypes.array,
5170 itemToString: propTypes.func,
5171 getA11yRemovalMessage: propTypes.func,
5172 stateReducer: propTypes.func,
5173 activeIndex: propTypes.number,
5174 initialActiveIndex: propTypes.number,
5175 defaultActiveIndex: propTypes.number,
5176 onActiveIndexChange: propTypes.func,
5177 onSelectedItemsChange: propTypes.func,
5178 keyNavigationNext: propTypes.string,
5179 keyNavigationPrevious: propTypes.string,
5180 environment: propTypes.shape({
5181 addEventListener: propTypes.func,
5182 removeEventListener: propTypes.func,
5183 document: propTypes.shape({
5184 getElementById: propTypes.func,
5185 activeElement: propTypes.any,
5186 body: propTypes.any
5187 })
5188 })
5189 };
5190 var defaultProps$3 = {
5191 itemToString: defaultProps.itemToString,
5192 stateReducer: defaultProps.stateReducer,
5193 environment: defaultProps.environment,
5194 getA11yRemovalMessage: getA11yRemovalMessage,
5195 keyNavigationNext: 'ArrowRight',
5196 keyNavigationPrevious: 'ArrowLeft'
5197 }; // eslint-disable-next-line import/no-mutable-exports
5198
5199 var validatePropTypes$2 = noop;
5200 /* istanbul ignore next */
5201
5202 validatePropTypes$2 = function (options, caller) {
5203 propTypes.checkPropTypes(propTypes$3, options, 'prop', caller.name);
5204 };
5205
5206 var SelectedItemClick = '__selected_item_click__';
5207 var SelectedItemKeyDownDelete = '__selected_item_keydown_delete__';
5208 var SelectedItemKeyDownBackspace = '__selected_item_keydown_backspace__';
5209 var SelectedItemKeyDownNavigationNext = '__selected_item_keydown_navigation_next__';
5210 var SelectedItemKeyDownNavigationPrevious = '__selected_item_keydown_navigation_previous__';
5211 var DropdownKeyDownNavigationPrevious = '__dropdown_keydown_navigation_previous__';
5212 var DropdownKeyDownBackspace = '__dropdown_keydown_backspace__';
5213 var DropdownClick = '__dropdown_click__';
5214 var FunctionAddSelectedItem = '__function_add_selected_item__';
5215 var FunctionRemoveSelectedItem = '__function_remove_selected_item__';
5216 var FunctionSetSelectedItems = '__function_set_selected_items__';
5217 var FunctionSetActiveIndex = '__function_set_active_index__';
5218 var FunctionReset$1 = '__function_reset__';
5219
5220 var stateChangeTypes$3 = /*#__PURE__*/Object.freeze({
5221 __proto__: null,
5222 SelectedItemClick: SelectedItemClick,
5223 SelectedItemKeyDownDelete: SelectedItemKeyDownDelete,
5224 SelectedItemKeyDownBackspace: SelectedItemKeyDownBackspace,
5225 SelectedItemKeyDownNavigationNext: SelectedItemKeyDownNavigationNext,
5226 SelectedItemKeyDownNavigationPrevious: SelectedItemKeyDownNavigationPrevious,
5227 DropdownKeyDownNavigationPrevious: DropdownKeyDownNavigationPrevious,
5228 DropdownKeyDownBackspace: DropdownKeyDownBackspace,
5229 DropdownClick: DropdownClick,
5230 FunctionAddSelectedItem: FunctionAddSelectedItem,
5231 FunctionRemoveSelectedItem: FunctionRemoveSelectedItem,
5232 FunctionSetSelectedItems: FunctionSetSelectedItems,
5233 FunctionSetActiveIndex: FunctionSetActiveIndex,
5234 FunctionReset: FunctionReset$1
5235 });
5236
5237 /* eslint-disable complexity */
5238
5239 function downshiftMultipleSelectionReducer(state, action) {
5240 var type = action.type,
5241 index = action.index,
5242 props = action.props,
5243 selectedItem = action.selectedItem;
5244 var activeIndex = state.activeIndex,
5245 selectedItems = state.selectedItems;
5246 var changes;
5247
5248 switch (type) {
5249 case SelectedItemClick:
5250 changes = {
5251 activeIndex: index
5252 };
5253 break;
5254
5255 case SelectedItemKeyDownNavigationPrevious:
5256 changes = {
5257 activeIndex: activeIndex - 1 < 0 ? 0 : activeIndex - 1
5258 };
5259 break;
5260
5261 case SelectedItemKeyDownNavigationNext:
5262 changes = {
5263 activeIndex: activeIndex + 1 >= selectedItems.length ? -1 : activeIndex + 1
5264 };
5265 break;
5266
5267 case SelectedItemKeyDownBackspace:
5268 case SelectedItemKeyDownDelete:
5269 {
5270 var newActiveIndex = activeIndex;
5271
5272 if (selectedItems.length === 1) {
5273 newActiveIndex = -1;
5274 } else if (activeIndex === selectedItems.length - 1) {
5275 newActiveIndex = selectedItems.length - 2;
5276 }
5277
5278 changes = _extends({
5279 selectedItems: [].concat(selectedItems.slice(0, activeIndex), selectedItems.slice(activeIndex + 1))
5280 }, {
5281 activeIndex: newActiveIndex
5282 });
5283 break;
5284 }
5285
5286 case DropdownKeyDownNavigationPrevious:
5287 changes = {
5288 activeIndex: selectedItems.length - 1
5289 };
5290 break;
5291
5292 case DropdownKeyDownBackspace:
5293 changes = {
5294 selectedItems: selectedItems.slice(0, selectedItems.length - 1)
5295 };
5296 break;
5297
5298 case FunctionAddSelectedItem:
5299 changes = {
5300 selectedItems: [].concat(selectedItems, [selectedItem])
5301 };
5302 break;
5303
5304 case DropdownClick:
5305 changes = {
5306 activeIndex: -1
5307 };
5308 break;
5309
5310 case FunctionRemoveSelectedItem:
5311 {
5312 var _newActiveIndex = activeIndex;
5313 var selectedItemIndex = selectedItems.indexOf(selectedItem);
5314
5315 if (selectedItems.length === 1) {
5316 _newActiveIndex = -1;
5317 } else if (selectedItemIndex === selectedItems.length - 1) {
5318 _newActiveIndex = selectedItems.length - 2;
5319 }
5320
5321 changes = _extends({
5322 selectedItems: [].concat(selectedItems.slice(0, selectedItemIndex), selectedItems.slice(selectedItemIndex + 1))
5323 }, {
5324 activeIndex: _newActiveIndex
5325 });
5326 break;
5327 }
5328
5329 case FunctionSetSelectedItems:
5330 {
5331 var newSelectedItems = action.selectedItems;
5332 changes = {
5333 selectedItems: newSelectedItems
5334 };
5335 break;
5336 }
5337
5338 case FunctionSetActiveIndex:
5339 {
5340 var _newActiveIndex2 = action.activeIndex;
5341 changes = {
5342 activeIndex: _newActiveIndex2
5343 };
5344 break;
5345 }
5346
5347 case FunctionReset$1:
5348 changes = {
5349 activeIndex: getDefaultValue$1(props, 'activeIndex'),
5350 selectedItems: getDefaultValue$1(props, 'selectedItems')
5351 };
5352 break;
5353
5354 default:
5355 throw new Error('Reducer called without proper action type.');
5356 }
5357
5358 return _extends({}, state, changes);
5359 }
5360
5361 useMultipleSelection.stateChangeTypes = stateChangeTypes$3;
5362
5363 function useMultipleSelection(userProps) {
5364 if (userProps === void 0) {
5365 userProps = {};
5366 }
5367
5368 validatePropTypes$2(userProps, useMultipleSelection); // Props defaults and destructuring.
5369
5370 var props = _extends({}, defaultProps$3, userProps);
5371
5372 var getA11yRemovalMessage = props.getA11yRemovalMessage,
5373 itemToString = props.itemToString,
5374 environment = props.environment,
5375 keyNavigationNext = props.keyNavigationNext,
5376 keyNavigationPrevious = props.keyNavigationPrevious; // Reducer init.
5377
5378 var _useControlledReducer = useControlledReducer(downshiftMultipleSelectionReducer, getInitialState$2(props), props),
5379 state = _useControlledReducer[0],
5380 dispatch = _useControlledReducer[1];
5381
5382 var activeIndex = state.activeIndex,
5383 selectedItems = state.selectedItems; // Refs.
5384
5385 var isInitialMountRef = react.useRef(true);
5386 var dropdownRef = react.useRef(null);
5387 var previousSelectedItemsRef = react.useRef(selectedItems);
5388 var selectedItemRefs = react.useRef();
5389 selectedItemRefs.current = [];
5390 var latest = useLatestRef({
5391 state: state,
5392 props: props
5393 }); // Effects.
5394
5395 /* Sets a11y status message on changes in selectedItem. */
5396
5397 react.useEffect(function () {
5398 if (isInitialMountRef.current) {
5399 return;
5400 }
5401
5402 if (selectedItems.length < previousSelectedItemsRef.current.length) {
5403 var removedSelectedItem = previousSelectedItemsRef.current.find(function (item) {
5404 return selectedItems.indexOf(item) < 0;
5405 });
5406 setStatus(getA11yRemovalMessage({
5407 itemToString: itemToString,
5408 resultCount: selectedItems.length,
5409 removedSelectedItem: removedSelectedItem,
5410 activeIndex: activeIndex,
5411 activeSelectedItem: selectedItems[activeIndex]
5412 }), environment.document);
5413 }
5414
5415 previousSelectedItemsRef.current = selectedItems; // eslint-disable-next-line react-hooks/exhaustive-deps
5416 }, [selectedItems.length]); // Sets focus on active item.
5417
5418 react.useEffect(function () {
5419 if (isInitialMountRef.current) {
5420 return;
5421 }
5422
5423 if (activeIndex === -1 && dropdownRef.current) {
5424 dropdownRef.current.focus();
5425 } else if (selectedItemRefs.current[activeIndex]) {
5426 selectedItemRefs.current[activeIndex].focus();
5427 }
5428 }, [activeIndex]);
5429 useControlPropsValidator({
5430 isInitialMount: isInitialMountRef.current,
5431 props: props,
5432 state: state
5433 });
5434 var setGetterPropCallInfo = useGetterPropsCalledChecker('getDropdownProps'); // Make initial ref false.
5435
5436 react.useEffect(function () {
5437 isInitialMountRef.current = false;
5438 }, []); // Event handler functions.
5439
5440 var selectedItemKeyDownHandlers = react.useMemo(function () {
5441 var _ref;
5442
5443 return _ref = {}, _ref[keyNavigationPrevious] = function () {
5444 dispatch({
5445 type: SelectedItemKeyDownNavigationPrevious
5446 });
5447 }, _ref[keyNavigationNext] = function () {
5448 dispatch({
5449 type: SelectedItemKeyDownNavigationNext
5450 });
5451 }, _ref.Delete = function Delete() {
5452 dispatch({
5453 type: SelectedItemKeyDownDelete
5454 });
5455 }, _ref.Backspace = function Backspace() {
5456 dispatch({
5457 type: SelectedItemKeyDownBackspace
5458 });
5459 }, _ref;
5460 }, [dispatch, keyNavigationNext, keyNavigationPrevious]);
5461 var dropdownKeyDownHandlers = react.useMemo(function () {
5462 var _ref2;
5463
5464 return _ref2 = {}, _ref2[keyNavigationPrevious] = function (event) {
5465 if (isKeyDownOperationPermitted(event)) {
5466 dispatch({
5467 type: DropdownKeyDownNavigationPrevious
5468 });
5469 }
5470 }, _ref2.Backspace = function Backspace(event) {
5471 if (isKeyDownOperationPermitted(event)) {
5472 dispatch({
5473 type: DropdownKeyDownBackspace
5474 });
5475 }
5476 }, _ref2;
5477 }, [dispatch, keyNavigationPrevious]); // Getter props.
5478
5479 var getSelectedItemProps = react.useCallback(function (_temp) {
5480 var _extends2;
5481
5482 var _ref3 = _temp === void 0 ? {} : _temp,
5483 _ref3$refKey = _ref3.refKey,
5484 refKey = _ref3$refKey === void 0 ? 'ref' : _ref3$refKey,
5485 ref = _ref3.ref,
5486 onClick = _ref3.onClick,
5487 onKeyDown = _ref3.onKeyDown,
5488 selectedItem = _ref3.selectedItem,
5489 index = _ref3.index,
5490 rest = _objectWithoutPropertiesLoose(_ref3, ["refKey", "ref", "onClick", "onKeyDown", "selectedItem", "index"]);
5491
5492 var latestState = latest.current.state;
5493 var itemIndex = getItemIndex(index, selectedItem, latestState.selectedItems);
5494
5495 if (itemIndex < 0) {
5496 throw new Error('Pass either selectedItem or index in getSelectedItemProps!');
5497 }
5498
5499 return _extends((_extends2 = {}, _extends2[refKey] = handleRefs(ref, function (selectedItemNode) {
5500 if (selectedItemNode) {
5501 selectedItemRefs.current.push(selectedItemNode);
5502 }
5503 }), _extends2.tabIndex = index === latestState.activeIndex ? 0 : -1, _extends2.onClick = callAllEventHandlers(onClick, function selectedItemHandleClick() {
5504 dispatch({
5505 type: SelectedItemClick,
5506 index: index
5507 });
5508 }), _extends2.onKeyDown = callAllEventHandlers(onKeyDown, function selectedItemHandleKeyDown(event) {
5509 var key = normalizeArrowKey(event);
5510
5511 if (key && selectedItemKeyDownHandlers[key]) {
5512 selectedItemKeyDownHandlers[key](event);
5513 }
5514 }), _extends2), rest);
5515 }, [dispatch, latest, selectedItemKeyDownHandlers]);
5516 var getDropdownProps = react.useCallback(function (_temp2, _temp3) {
5517 var _extends3;
5518
5519 var _ref4 = _temp2 === void 0 ? {} : _temp2,
5520 _ref4$refKey = _ref4.refKey,
5521 refKey = _ref4$refKey === void 0 ? 'ref' : _ref4$refKey,
5522 ref = _ref4.ref,
5523 onKeyDown = _ref4.onKeyDown,
5524 onClick = _ref4.onClick,
5525 _ref4$preventKeyActio = _ref4.preventKeyAction,
5526 preventKeyAction = _ref4$preventKeyActio === void 0 ? false : _ref4$preventKeyActio,
5527 rest = _objectWithoutPropertiesLoose(_ref4, ["refKey", "ref", "onKeyDown", "onClick", "preventKeyAction"]);
5528
5529 var _ref5 = _temp3 === void 0 ? {} : _temp3,
5530 _ref5$suppressRefErro = _ref5.suppressRefError,
5531 suppressRefError = _ref5$suppressRefErro === void 0 ? false : _ref5$suppressRefErro;
5532
5533 setGetterPropCallInfo('getDropdownProps', suppressRefError, refKey, dropdownRef);
5534 return _extends((_extends3 = {}, _extends3[refKey] = handleRefs(ref, function (dropdownNode) {
5535 if (dropdownNode) {
5536 dropdownRef.current = dropdownNode;
5537 }
5538 }), _extends3), !preventKeyAction && {
5539 onKeyDown: callAllEventHandlers(onKeyDown, function dropdownHandleKeyDown(event) {
5540 var key = normalizeArrowKey(event);
5541
5542 if (key && dropdownKeyDownHandlers[key]) {
5543 dropdownKeyDownHandlers[key](event);
5544 }
5545 }),
5546 onClick: callAllEventHandlers(onClick, function dropdownHandleClick() {
5547 dispatch({
5548 type: DropdownClick
5549 });
5550 })
5551 }, rest);
5552 }, [dispatch, dropdownKeyDownHandlers, setGetterPropCallInfo]); // returns
5553
5554 var addSelectedItem = react.useCallback(function (selectedItem) {
5555 dispatch({
5556 type: FunctionAddSelectedItem,
5557 selectedItem: selectedItem
5558 });
5559 }, [dispatch]);
5560 var removeSelectedItem = react.useCallback(function (selectedItem) {
5561 dispatch({
5562 type: FunctionRemoveSelectedItem,
5563 selectedItem: selectedItem
5564 });
5565 }, [dispatch]);
5566 var setSelectedItems = react.useCallback(function (newSelectedItems) {
5567 dispatch({
5568 type: FunctionSetSelectedItems,
5569 selectedItems: newSelectedItems
5570 });
5571 }, [dispatch]);
5572 var setActiveIndex = react.useCallback(function (newActiveIndex) {
5573 dispatch({
5574 type: FunctionSetActiveIndex,
5575 activeIndex: newActiveIndex
5576 });
5577 }, [dispatch]);
5578 var reset = react.useCallback(function () {
5579 dispatch({
5580 type: FunctionReset$1
5581 });
5582 }, [dispatch]);
5583 return {
5584 getSelectedItemProps: getSelectedItemProps,
5585 getDropdownProps: getDropdownProps,
5586 addSelectedItem: addSelectedItem,
5587 removeSelectedItem: removeSelectedItem,
5588 setSelectedItems: setSelectedItems,
5589 setActiveIndex: setActiveIndex,
5590 reset: reset,
5591 selectedItems: selectedItems,
5592 activeIndex: activeIndex
5593 };
5594 }
5595
5596 exports.default = Downshift;
5597 exports.resetIdCounter = resetIdCounter;
5598 exports.useCombobox = useCombobox;
5599 exports.useMultipleSelection = useMultipleSelection;
5600 exports.useSelect = useSelect;
5601
5602 Object.defineProperty(exports, '__esModule', { value: true });
5603
5604})));
5605//# sourceMappingURL=downshift.umd.js.map