UNPKG

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