UNPKG

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