UNPKG

downshift

Version:

🏎 A set of primitives to build simple, flexible, WAI-ARIA compliant React autocomplete, combobox or select dropdown components.

1,285 lines (1,239 loc) 166 kB
import _objectWithoutPropertiesLoose from '@babel/runtime/helpers/esm/objectWithoutPropertiesLoose'; import _extends from '@babel/runtime/helpers/esm/extends'; import _inheritsLoose from '@babel/runtime/helpers/esm/inheritsLoose'; import PropTypes from 'prop-types'; import * as React from 'react'; import { cloneElement, Component, useRef, useCallback, useEffect, useMemo } from 'react'; import { isForwardRef } from 'react-is'; import { compute } from 'compute-scroll-into-view'; var unknown = process.env.NODE_ENV !== "production" ? '__autocomplete_unknown__' : 0; var mouseUp = process.env.NODE_ENV !== "production" ? '__autocomplete_mouseup__' : 1; var itemMouseEnter = process.env.NODE_ENV !== "production" ? '__autocomplete_item_mouseenter__' : 2; var keyDownArrowUp = process.env.NODE_ENV !== "production" ? '__autocomplete_keydown_arrow_up__' : 3; var keyDownArrowDown = process.env.NODE_ENV !== "production" ? '__autocomplete_keydown_arrow_down__' : 4; var keyDownEscape = process.env.NODE_ENV !== "production" ? '__autocomplete_keydown_escape__' : 5; var keyDownEnter = process.env.NODE_ENV !== "production" ? '__autocomplete_keydown_enter__' : 6; var keyDownHome = process.env.NODE_ENV !== "production" ? '__autocomplete_keydown_home__' : 7; var keyDownEnd = process.env.NODE_ENV !== "production" ? '__autocomplete_keydown_end__' : 8; var clickItem = process.env.NODE_ENV !== "production" ? '__autocomplete_click_item__' : 9; var blurInput = process.env.NODE_ENV !== "production" ? '__autocomplete_blur_input__' : 10; var changeInput = process.env.NODE_ENV !== "production" ? '__autocomplete_change_input__' : 11; var keyDownSpaceButton = process.env.NODE_ENV !== "production" ? '__autocomplete_keydown_space_button__' : 12; var clickButton = process.env.NODE_ENV !== "production" ? '__autocomplete_click_button__' : 13; var blurButton = process.env.NODE_ENV !== "production" ? '__autocomplete_blur_button__' : 14; var controlledPropUpdatedSelectedItem = process.env.NODE_ENV !== "production" ? '__autocomplete_controlled_prop_updated_selected_item__' : 15; var touchEnd = process.env.NODE_ENV !== "production" ? '__autocomplete_touchend__' : 16; var stateChangeTypes$4 = /*#__PURE__*/Object.freeze({ __proto__: null, blurButton: blurButton, blurInput: blurInput, changeInput: changeInput, clickButton: clickButton, clickItem: clickItem, controlledPropUpdatedSelectedItem: controlledPropUpdatedSelectedItem, itemMouseEnter: itemMouseEnter, keyDownArrowDown: keyDownArrowDown, keyDownArrowUp: keyDownArrowUp, keyDownEnd: keyDownEnd, keyDownEnter: keyDownEnter, keyDownEscape: keyDownEscape, keyDownHome: keyDownHome, keyDownSpaceButton: keyDownSpaceButton, mouseUp: mouseUp, touchEnd: touchEnd, unknown: unknown }); var idCounter = 0; /** * This generates a unique ID for an instance of Downshift * @return {string} the unique ID */ function generateId() { return String(idCounter++); } /** * Resets idCounter to 0. Used for SSR. */ function resetIdCounter() { // istanbul ignore next if ('useId' in React) { console.warn("It is not necessary to call resetIdCounter when using React 18+"); return; } idCounter = 0; } function useLatestRef(val) { var ref = React.useRef(val); // technically this is not "concurrent mode safe" because we're manipulating // the value during render (so it's not idempotent). However, the places this // hook is used is to support memoizing callbacks which will be called // *during* render, so we need the latest values *during* render. // If not for this, then we'd probably want to use useLayoutEffect instead. ref.current = val; return ref; } function handleRefs$1() { for (var _len = arguments.length, refs = new Array(_len), _key = 0; _key < _len; _key++) { refs[_key] = arguments[_key]; } return function (node) { refs.forEach(function (ref) { if (typeof ref === 'function') { ref(node); } else if (ref) { ref.current = node; } }); }; } /** * This is intended to be used to compose event handlers. * They are executed in order until one of them sets * `event.preventDownshiftDefault = true`. * @param fns the event handler functions * @return the event handler to add to an element */ function callAllEventHandlers$1() { for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) { fns[_key] = arguments[_key]; } return function (event) { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } return fns.some(function (fn) { if (fn) { fn.apply(void 0, [event].concat(args)); } return event.preventDownshiftDefault || event.hasOwnProperty('nativeEvent') && event.nativeEvent.preventDownshiftDefault; }); }; } /** * Simple debounce implementation. Will call the given * function once after the time given has passed since * it was last called. */ function debounce$1(fn, time) { var timeoutId; function cancel() { if (timeoutId) { clearTimeout(timeoutId); } } function wrapper() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } cancel(); timeoutId = setTimeout(function () { timeoutId = null; fn.apply(void 0, args); }, time); } wrapper.cancel = cancel; return wrapper; } var cleanupStatus = debounce$1(function (document) { getStatusDiv(document).textContent = ''; }, 500); /** * Get the status node or create it if it does not already exist. */ function getStatusDiv(document) { var statusDiv = document.getElementById('a11y-status-message'); if (statusDiv) { return statusDiv; } statusDiv = document.createElement('div'); statusDiv.setAttribute('id', 'a11y-status-message'); statusDiv.setAttribute('role', 'status'); statusDiv.setAttribute('aria-live', 'polite'); statusDiv.setAttribute('aria-relevant', 'additions text'); Object.assign(statusDiv.style, { border: '0', clip: 'rect(0 0 0 0)', height: '1px', margin: '-1px', overflow: 'hidden', padding: '0', position: 'absolute', width: '1px' }); document.body.appendChild(statusDiv); return statusDiv; } /** * Sets aria live status to a div element that's visually hidden. */ function setStatus(status, document) { if (!status || !document) { return; } var div = getStatusDiv(document); div.textContent = status; cleanupStatus(document); } /** * Removes the status element from the DOM */ function cleanupStatusDiv(document) { var statusDiv = document == null ? void 0 : document.getElementById('a11y-status-message'); if (statusDiv) { statusDiv.remove(); } } function noop() {} // eslint-disable-next-line import/no-mutable-exports var validatePropTypes$1 = noop; /* istanbul ignore next */ if (process.env.NODE_ENV !== 'production') { validatePropTypes$1 = function validatePropTypes(options, caller, propTypes) { PropTypes.checkPropTypes(propTypes, options, 'prop', caller.name); }; } /** * This will perform a shallow merge of the given state object * with the state coming from props * (for the controlled component scenario) * This is used in state updater functions so they're referencing * the right state regardless of where it comes from. * * @param state The state of the component/hook. * @param props The props that may contain controlled values. * @returns The merged controlled state. */ function getState(state, props) { if (!props) { return state; } var keys = Object.keys(state); return keys.reduce(function (newState, key) { if (props[key] !== undefined) { newState[key] = props[key]; } return newState; }, _extends({}, state)); } /** * Scroll node into view if necessary * @param {HTMLElement} node the element that should scroll into view * @param {HTMLElement} menuNode the menu element of the component */ function scrollIntoView(node, menuNode) { if (!node) { return; } var actions = compute(node, { boundary: menuNode, block: 'nearest', scrollMode: 'if-needed' }); actions.forEach(function (_ref) { var el = _ref.el, top = _ref.top, left = _ref.left; el.scrollTop = top; el.scrollLeft = left; }); } /** * Accepts a parameter and returns it if it's a function * or a noop function if it's not. This allows us to * accept a callback, but not worry about it if it's not * passed. * @param {Function} cb the callback * @return {Function} a function */ function cbToCb(cb) { return typeof cb === 'function' ? cb : noop; } /** * @param {HTMLElement} parent the parent node * @param {HTMLElement} child the child node * @param {Window} environment The window context where downshift renders. * @return {Boolean} whether the parent is the child or the child is in the parent */ function isOrContainsNode(parent, child, environment) { var result = parent === child || child instanceof environment.Node && parent.contains && parent.contains(child); return result; } /** * Simple debounce implementation. Will call the given * function once after the time given has passed since * it was last called. * @param {Function} fn the function to call after the time * @param {Number} time the time to wait * @return {Function} the debounced function */ function debounce(fn, time) { var timeoutId; function cancel() { if (timeoutId) { clearTimeout(timeoutId); } } function wrapper() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } cancel(); timeoutId = setTimeout(function () { timeoutId = null; fn.apply(void 0, args); }, time); } wrapper.cancel = cancel; return wrapper; } /** * This is intended to be used to compose event handlers. * They are executed in order until one of them sets * `event.preventDownshiftDefault = true`. * @param {...Function} fns the event handler functions * @return {Function} the event handler to add to an element */ function callAllEventHandlers() { for (var _len2 = arguments.length, fns = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { fns[_key2] = arguments[_key2]; } return function (event) { for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { args[_key3 - 1] = arguments[_key3]; } return fns.some(function (fn) { if (fn) { fn.apply(void 0, [event].concat(args)); } return event.preventDownshiftDefault || event.hasOwnProperty('nativeEvent') && event.nativeEvent.preventDownshiftDefault; }); }; } function handleRefs() { for (var _len4 = arguments.length, refs = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { refs[_key4] = arguments[_key4]; } return function (node) { refs.forEach(function (ref) { if (typeof ref === 'function') { ref(node); } else if (ref) { ref.current = node; } }); }; } /** * Default implementation for status message. Only added when menu is open. * Will specify if there are results in the list, and if so, how many, * and what keys are relevant. * * @param {Object} param the downshift state and other relevant properties * @return {String} the a11y status message */ function getA11yStatusMessage(_ref) { var isOpen = _ref.isOpen, resultCount = _ref.resultCount, previousResultCount = _ref.previousResultCount; if (!isOpen) { return ''; } if (!resultCount) { return 'No results are available.'; } if (resultCount !== previousResultCount) { return resultCount + " result" + (resultCount === 1 ? ' is' : 's are') + " available, use up and down arrow keys to navigate. Press Enter key to select."; } return ''; } /** * Takes an argument and if it's an array, returns the first item in the array * otherwise returns the argument * @param {*} arg the maybe-array * @param {*} defaultValue the value if arg is falsey not defined * @return {*} the arg or it's first item */ function unwrapArray(arg, defaultValue) { arg = Array.isArray(arg) ? /* istanbul ignore next (preact) */arg[0] : arg; if (!arg && defaultValue) { return defaultValue; } else { return arg; } } /** * @param {Object} element (P)react element * @return {Boolean} whether it's a DOM element */ function isDOMElement(element) { // then we assume this is react return typeof element.type === 'string'; } /** * @param {Object} element (P)react element * @return {Object} the props */ function getElementProps(element) { return element.props; } /** * Throws a helpful error message for required properties. Useful * to be used as a default in destructuring or object params. * @param {String} fnName the function name * @param {String} propName the prop name */ function requiredProp(fnName, propName) { // eslint-disable-next-line no-console console.error("The property \"" + propName + "\" is required in \"" + fnName + "\""); } var stateKeys = ['highlightedIndex', 'inputValue', 'isOpen', 'selectedItem', 'type']; /** * @param {Object} state the state object * @return {Object} state that is relevant to downshift */ function pickState(state) { if (state === void 0) { state = {}; } var result = {}; stateKeys.forEach(function (k) { if (state.hasOwnProperty(k)) { result[k] = state[k]; } }); return result; } /** * This determines whether a prop is a "controlled prop" meaning it is * state which is controlled by the outside of this component rather * than within this component. * * @param {Object} props The props that may contain controlled values. * @param {String} key the key to check * @return {Boolean} whether it is a controlled controlled prop */ function isControlledProp(props, key) { return props[key] !== undefined; } /** * Normalizes the 'key' property of a KeyboardEvent in IE/Edge * @param {Object} event a keyboardEvent object * @return {String} keyboard key */ function normalizeArrowKey(event) { var key = event.key, keyCode = event.keyCode; /* istanbul ignore next (ie) */ if (keyCode >= 37 && keyCode <= 40 && key.indexOf('Arrow') !== 0) { return "Arrow" + key; } return key; } /** * Simple check if the value passed is object literal * @param {*} obj any things * @return {Boolean} whether it's object literal */ function isPlainObject(obj) { return Object.prototype.toString.call(obj) === '[object Object]'; } /** * Returns the next non-disabled highlightedIndex value. * * @param {number} start The current highlightedIndex. * @param {number} offset The offset from the current highlightedIndex to start searching. * @param {unknown[]} items The items array. * @param {(item: unknown, index: number) => boolean} isItemDisabled Function that tells if an item is disabled or not. * @param {boolean?} circular If the search reaches the end, if it can search again starting from the other end. * @returns {number} The next highlightedIndex. */ function getHighlightedIndex(start, offset, items, isItemDisabled, circular) { if (circular === void 0) { circular = false; } var count = items.length; if (count === 0) { return -1; } var itemsLastIndex = count - 1; if (typeof start !== 'number' || start < 0 || start > itemsLastIndex) { start = offset > 0 ? -1 : itemsLastIndex + 1; } var current = start + offset; if (current < 0) { current = circular ? itemsLastIndex : 0; } else if (current > itemsLastIndex) { current = circular ? 0 : itemsLastIndex; } var highlightedIndex = getNonDisabledIndex(current, offset < 0, items, isItemDisabled, circular); if (highlightedIndex === -1) { return start >= count ? -1 : start; } return highlightedIndex; } /** * Returns the next non-disabled highlightedIndex value. * * @param {number} start The current highlightedIndex. * @param {boolean} backwards If true, it will search backwards from the start. * @param {unknown[]} items The items array. * @param {(item: unknown, index: number) => boolean} isItemDisabled Function that tells if an item is disabled or not. * @param {boolean} circular If the search reaches the end, if it can search again starting from the other end. * @returns {number} The next non-disabled index. */ function getNonDisabledIndex(start, backwards, items, isItemDisabled, circular) { if (circular === void 0) { circular = false; } var count = items.length; if (backwards) { for (var index = start; index >= 0; index--) { if (!isItemDisabled(items[index], index)) { return index; } } } else { for (var _index = start; _index < count; _index++) { if (!isItemDisabled(items[_index], _index)) { return _index; } } } if (circular) { return getNonDisabledIndex(backwards ? count - 1 : 0, backwards, items, isItemDisabled); } return -1; } /** * Checks if event target is within the downshift elements. * * @param {EventTarget} target Target to check. * @param {HTMLElement[]} downshiftElements The elements that form downshift (list, toggle button etc). * @param {Window} environment The window context where downshift renders. * @param {boolean} checkActiveElement Whether to also check activeElement. * * @returns {boolean} Whether or not the target is within downshift elements. */ function targetWithinDownshift(target, downshiftElements, environment, checkActiveElement) { if (checkActiveElement === void 0) { checkActiveElement = true; } return environment && downshiftElements.some(function (contextNode) { return contextNode && (isOrContainsNode(contextNode, target, environment) || checkActiveElement && isOrContainsNode(contextNode, environment.document.activeElement, environment)); }); } // eslint-disable-next-line import/no-mutable-exports var validateControlledUnchanged = noop; /* istanbul ignore next */ if (process.env.NODE_ENV !== 'production') { validateControlledUnchanged = function validateControlledUnchanged(state, prevProps, nextProps) { 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"; Object.keys(state).forEach(function (propKey) { if (prevProps[propKey] !== undefined && nextProps[propKey] === undefined) { // eslint-disable-next-line no-console console.error("downshift: A component has changed the controlled prop \"" + propKey + "\" to be uncontrolled. " + warningDescription); } else if (prevProps[propKey] === undefined && nextProps[propKey] !== undefined) { // eslint-disable-next-line no-console console.error("downshift: A component has changed the uncontrolled prop \"" + propKey + "\" to be controlled. " + warningDescription); } }); }; } var _excluded$4 = ["refKey", "ref"], _excluded2$4 = ["onClick", "onPress", "onKeyDown", "onKeyUp", "onBlur"], _excluded3$3 = ["onKeyDown", "onBlur", "onChange", "onInput", "onChangeText"], _excluded4$2 = ["refKey", "ref"], _excluded5 = ["onMouseMove", "onMouseDown", "onClick", "onPress", "index", "item"]; var Downshift = /*#__PURE__*/function () { var Downshift = /*#__PURE__*/function (_Component) { function Downshift(_props) { var _this; _this = _Component.call(this, _props) || this; // fancy destructuring + defaults + aliases // this basically says each value of state should either be set to // the initial value or the default value if the initial value is not provided _this.id = _this.props.id || "downshift-" + generateId(); _this.menuId = _this.props.menuId || _this.id + "-menu"; _this.labelId = _this.props.labelId || _this.id + "-label"; _this.inputId = _this.props.inputId || _this.id + "-input"; _this.getItemId = _this.props.getItemId || function (index) { return _this.id + "-item-" + index; }; _this.items = []; // itemCount can be changed asynchronously // from within downshift (so it can't come from a prop) // this is why we store it as an instance and use // getItemCount rather than just use items.length // (to support windowing + async) _this.itemCount = null; _this.previousResultCount = 0; _this.timeoutIds = []; /** * @param {Function} fn the function to call after the time * @param {Number} time the time to wait */ _this.internalSetTimeout = function (fn, time) { var id = setTimeout(function () { _this.timeoutIds = _this.timeoutIds.filter(function (i) { return i !== id; }); fn(); }, time); _this.timeoutIds.push(id); }; _this.setItemCount = function (count) { _this.itemCount = count; }; _this.unsetItemCount = function () { _this.itemCount = null; }; _this.isItemDisabled = function (_item, index) { var currentElementNode = _this.getItemNodeFromIndex(index); return currentElementNode && currentElementNode.hasAttribute('disabled'); }; _this.setHighlightedIndex = function (highlightedIndex, otherStateToSet) { if (highlightedIndex === void 0) { highlightedIndex = _this.props.defaultHighlightedIndex; } if (otherStateToSet === void 0) { otherStateToSet = {}; } otherStateToSet = pickState(otherStateToSet); _this.internalSetState(_extends({ highlightedIndex: highlightedIndex }, otherStateToSet)); }; _this.clearSelection = function (cb) { _this.internalSetState({ selectedItem: null, inputValue: '', highlightedIndex: _this.props.defaultHighlightedIndex, isOpen: _this.props.defaultIsOpen }, cb); }; _this.selectItem = function (item, otherStateToSet, cb) { otherStateToSet = pickState(otherStateToSet); _this.internalSetState(_extends({ isOpen: _this.props.defaultIsOpen, highlightedIndex: _this.props.defaultHighlightedIndex, selectedItem: item, inputValue: _this.props.itemToString(item) }, otherStateToSet), cb); }; _this.selectItemAtIndex = function (itemIndex, otherStateToSet, cb) { var item = _this.items[itemIndex]; if (item == null) { return; } _this.selectItem(item, otherStateToSet, cb); }; _this.selectHighlightedItem = function (otherStateToSet, cb) { return _this.selectItemAtIndex(_this.getState().highlightedIndex, otherStateToSet, cb); }; // any piece of our state can live in two places: // 1. Uncontrolled: it's internal (this.state) // We will call this.setState to update that state // 2. Controlled: it's external (this.props) // We will call this.props.onStateChange to update that state // // In addition, we'll call this.props.onChange if the // selectedItem is changed. _this.internalSetState = function (stateToSet, cb) { var isItemSelected, onChangeArg; var onStateChangeArg = {}; var isStateToSetFunction = typeof stateToSet === 'function'; // we want to call `onInputValueChange` before the `setState` call // so someone controlling the `inputValue` state gets notified of // the input change as soon as possible. This avoids issues with // preserving the cursor position. // See https://github.com/downshift-js/downshift/issues/217 for more info. if (!isStateToSetFunction && stateToSet.hasOwnProperty('inputValue')) { _this.props.onInputValueChange(stateToSet.inputValue, _extends({}, _this.getStateAndHelpers(), stateToSet)); } return _this.setState(function (state) { var _newStateToSet; state = _this.getState(state); var newStateToSet = isStateToSetFunction ? stateToSet(state) : stateToSet; // Your own function that could modify the state that will be set. newStateToSet = _this.props.stateReducer(state, newStateToSet); // checks if an item is selected, regardless of if it's different from // what was selected before // used to determine if onSelect and onChange callbacks should be called isItemSelected = newStateToSet.hasOwnProperty('selectedItem'); // this keeps track of the object we want to call with setState var nextState = {}; // we need to call on change if the outside world is controlling any of our state // and we're trying to update that state. OR if the selection has changed and we're // trying to update the selection if (isItemSelected && newStateToSet.selectedItem !== state.selectedItem) { onChangeArg = newStateToSet.selectedItem; } (_newStateToSet = newStateToSet).type || (_newStateToSet.type = unknown); Object.keys(newStateToSet).forEach(function (key) { // onStateChangeArg should only have the state that is // actually changing if (state[key] !== newStateToSet[key]) { onStateChangeArg[key] = newStateToSet[key]; } // the type is useful for the onStateChangeArg // but we don't actually want to set it in internal state. // this is an undocumented feature for now... Not all internalSetState // calls support it and I'm not certain we want them to yet. // But it enables users controlling the isOpen state to know when // the isOpen state changes due to mouseup events which is quite handy. if (key === 'type') { return; } newStateToSet[key]; // if it's coming from props, then we don't care to set it internally if (!isControlledProp(_this.props, key)) { nextState[key] = newStateToSet[key]; } }); // if stateToSet is a function, then we weren't able to call onInputValueChange // earlier, so we'll call it now that we know what the inputValue state will be. if (isStateToSetFunction && newStateToSet.hasOwnProperty('inputValue')) { _this.props.onInputValueChange(newStateToSet.inputValue, _extends({}, _this.getStateAndHelpers(), newStateToSet)); } return nextState; }, function () { // call the provided callback if it's a function cbToCb(cb)(); // only call the onStateChange and onChange callbacks if // we have relevant information to pass them. var hasMoreStateThanType = Object.keys(onStateChangeArg).length > 1; if (hasMoreStateThanType) { _this.props.onStateChange(onStateChangeArg, _this.getStateAndHelpers()); } if (isItemSelected) { _this.props.onSelect(stateToSet.selectedItem, _this.getStateAndHelpers()); } if (onChangeArg !== undefined) { _this.props.onChange(onChangeArg, _this.getStateAndHelpers()); } // this is currently undocumented and therefore subject to change // We'll try to not break it, but just be warned. _this.props.onUserAction(onStateChangeArg, _this.getStateAndHelpers()); }); }; //////////////////////////// ROOT _this.rootRef = function (node) { return _this._rootNode = node; }; _this.getRootProps = function (_temp, _temp2) { var _extends2; var _ref = _temp === void 0 ? {} : _temp, _ref$refKey = _ref.refKey, refKey = _ref$refKey === void 0 ? 'ref' : _ref$refKey, ref = _ref.ref, rest = _objectWithoutPropertiesLoose(_ref, _excluded$4); var _ref2 = _temp2 === void 0 ? {} : _temp2, _ref2$suppressRefErro = _ref2.suppressRefError, suppressRefError = _ref2$suppressRefErro === void 0 ? false : _ref2$suppressRefErro; // this is used in the render to know whether the user has called getRootProps. // It uses that to know whether to apply the props automatically _this.getRootProps.called = true; _this.getRootProps.refKey = refKey; _this.getRootProps.suppressRefError = suppressRefError; var _this$getState = _this.getState(), isOpen = _this$getState.isOpen; 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 : undefined, _extends2['aria-labelledby'] = _this.labelId, _extends2), rest); }; //\\\\\\\\\\\\\\\\\\\\\\\\\\ ROOT _this.keyDownHandlers = { ArrowDown: function ArrowDown(event) { var _this2 = this; event.preventDefault(); if (this.getState().isOpen) { var amount = event.shiftKey ? 5 : 1; this.moveHighlightedIndex(amount, { type: keyDownArrowDown }); } else { this.internalSetState({ isOpen: true, type: keyDownArrowDown }, function () { var itemCount = _this2.getItemCount(); if (itemCount > 0) { var _this2$getState = _this2.getState(), highlightedIndex = _this2$getState.highlightedIndex; var nextHighlightedIndex = getHighlightedIndex(highlightedIndex, 1, { length: itemCount }, _this2.isItemDisabled, true); _this2.setHighlightedIndex(nextHighlightedIndex, { type: keyDownArrowDown }); } }); } }, ArrowUp: function ArrowUp(event) { var _this3 = this; event.preventDefault(); if (this.getState().isOpen) { var amount = event.shiftKey ? -5 : -1; this.moveHighlightedIndex(amount, { type: keyDownArrowUp }); } else { this.internalSetState({ isOpen: true, type: keyDownArrowUp }, function () { var itemCount = _this3.getItemCount(); if (itemCount > 0) { var _this3$getState = _this3.getState(), highlightedIndex = _this3$getState.highlightedIndex; var nextHighlightedIndex = getHighlightedIndex(highlightedIndex, -1, { length: itemCount }, _this3.isItemDisabled, true); _this3.setHighlightedIndex(nextHighlightedIndex, { type: keyDownArrowUp }); } }); } }, Enter: function Enter(event) { if (event.which === 229) { return; } var _this$getState2 = this.getState(), isOpen = _this$getState2.isOpen, highlightedIndex = _this$getState2.highlightedIndex; if (isOpen && highlightedIndex != null) { event.preventDefault(); var item = this.items[highlightedIndex]; var itemNode = this.getItemNodeFromIndex(highlightedIndex); if (item == null || itemNode && itemNode.hasAttribute('disabled')) { return; } this.selectHighlightedItem({ type: keyDownEnter }); } }, Escape: function Escape(event) { event.preventDefault(); this.reset(_extends({ type: keyDownEscape }, !this.state.isOpen && { selectedItem: null, inputValue: '' })); } }; //////////////////////////// BUTTON _this.buttonKeyDownHandlers = _extends({}, _this.keyDownHandlers, { ' ': function _(event) { event.preventDefault(); this.toggleMenu({ type: keyDownSpaceButton }); } }); _this.inputKeyDownHandlers = _extends({}, _this.keyDownHandlers, { Home: function Home(event) { var _this$getState3 = this.getState(), isOpen = _this$getState3.isOpen; if (!isOpen) { return; } event.preventDefault(); var itemCount = this.getItemCount(); if (itemCount <= 0 || !isOpen) { return; } // get next non-disabled starting downwards from 0 if that's disabled. var newHighlightedIndex = getNonDisabledIndex(0, false, { length: itemCount }, this.isItemDisabled); this.setHighlightedIndex(newHighlightedIndex, { type: keyDownHome }); }, End: function End(event) { var _this$getState4 = this.getState(), isOpen = _this$getState4.isOpen; if (!isOpen) { return; } event.preventDefault(); var itemCount = this.getItemCount(); if (itemCount <= 0 || !isOpen) { return; } // get next non-disabled starting upwards from last index if that's disabled. var newHighlightedIndex = getNonDisabledIndex(itemCount - 1, true, { length: itemCount }, this.isItemDisabled); this.setHighlightedIndex(newHighlightedIndex, { type: keyDownEnd }); } }); _this.getToggleButtonProps = function (_temp3) { var _ref3 = _temp3 === void 0 ? {} : _temp3, onClick = _ref3.onClick; _ref3.onPress; var onKeyDown = _ref3.onKeyDown, onKeyUp = _ref3.onKeyUp, onBlur = _ref3.onBlur, rest = _objectWithoutPropertiesLoose(_ref3, _excluded2$4); var _this$getState5 = _this.getState(), isOpen = _this$getState5.isOpen; var enabledEventHandlers = { onClick: callAllEventHandlers(onClick, _this.buttonHandleClick), onKeyDown: callAllEventHandlers(onKeyDown, _this.buttonHandleKeyDown), onKeyUp: callAllEventHandlers(onKeyUp, _this.buttonHandleKeyUp), onBlur: callAllEventHandlers(onBlur, _this.buttonHandleBlur) }; var eventHandlers = rest.disabled ? {} : enabledEventHandlers; return _extends({ type: 'button', role: 'button', 'aria-label': isOpen ? 'close menu' : 'open menu', 'aria-haspopup': true, 'data-toggle': true }, eventHandlers, rest); }; _this.buttonHandleKeyUp = function (event) { // Prevent click event from emitting in Firefox event.preventDefault(); }; _this.buttonHandleKeyDown = function (event) { var key = normalizeArrowKey(event); if (_this.buttonKeyDownHandlers[key]) { _this.buttonKeyDownHandlers[key].call(_this, event); } }; _this.buttonHandleClick = function (event) { event.preventDefault(); // handle odd case for Safari and Firefox which // don't give the button the focus properly. /* istanbul ignore if (can't reasonably test this) */ if (_this.props.environment) { var _this$props$environme = _this.props.environment.document, body = _this$props$environme.body, activeElement = _this$props$environme.activeElement; if (body && body === activeElement) { event.target.focus(); } } // to simplify testing components that use downshift, we'll not wrap this in a setTimeout // if the NODE_ENV is test. With the proper build system, this should be dead code eliminated // when building for production and should therefore have no impact on production code. if (process.env.NODE_ENV === 'test') { _this.toggleMenu({ type: clickButton }); } else { // Ensure that toggle of menu occurs after the potential blur event in iOS _this.internalSetTimeout(function () { return _this.toggleMenu({ type: clickButton }); }); } }; _this.buttonHandleBlur = function (event) { var blurTarget = event.target; // Save blur target for comparison with activeElement later // Need setTimeout, so that when the user presses Tab, the activeElement is the next focused element, not body element _this.internalSetTimeout(function () { if (_this.isMouseDown || !_this.props.environment) { return; } var activeElement = _this.props.environment.document.activeElement; if ((activeElement == null || activeElement.id !== _this.inputId) && activeElement !== blurTarget // Do nothing if we refocus the same element again (to solve issue in Safari on iOS) ) { _this.reset({ type: blurButton }); } }); }; //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ BUTTON /////////////////////////////// LABEL _this.getLabelProps = function (props) { return _extends({ htmlFor: _this.inputId, id: _this.labelId }, props); }; //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ LABEL /////////////////////////////// INPUT _this.getInputProps = function (_temp4) { var _ref4 = _temp4 === void 0 ? {} : _temp4, onKeyDown = _ref4.onKeyDown, onBlur = _ref4.onBlur, onChange = _ref4.onChange, onInput = _ref4.onInput; _ref4.onChangeText; var rest = _objectWithoutPropertiesLoose(_ref4, _excluded3$3); var onChangeKey; var eventHandlers = {}; /* istanbul ignore next (preact) */ { onChangeKey = 'onChange'; } var _this$getState6 = _this.getState(), inputValue = _this$getState6.inputValue, isOpen = _this$getState6.isOpen, highlightedIndex = _this$getState6.highlightedIndex; if (!rest.disabled) { var _eventHandlers; eventHandlers = (_eventHandlers = {}, _eventHandlers[onChangeKey] = callAllEventHandlers(onChange, onInput, _this.inputHandleChange), _eventHandlers.onKeyDown = callAllEventHandlers(onKeyDown, _this.inputHandleKeyDown), _eventHandlers.onBlur = callAllEventHandlers(onBlur, _this.inputHandleBlur), _eventHandlers); } return _extends({ 'aria-autocomplete': 'list', 'aria-activedescendant': isOpen && typeof highlightedIndex === 'number' && highlightedIndex >= 0 ? _this.getItemId(highlightedIndex) : undefined, 'aria-controls': isOpen ? _this.menuId : undefined, 'aria-labelledby': rest && rest['aria-label'] ? undefined : _this.labelId, // https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion // revert back since autocomplete="nope" is ignored on latest Chrome and Opera autoComplete: 'off', value: inputValue, id: _this.inputId }, eventHandlers, rest); }; _this.inputHandleKeyDown = function (event) { var key = normalizeArrowKey(event); if (key && _this.inputKeyDownHandlers[key]) { _this.inputKeyDownHandlers[key].call(_this, event); } }; _this.inputHandleChange = function (event) { _this.internalSetState({ type: changeInput, isOpen: true, inputValue: event.target.value, highlightedIndex: _this.props.defaultHighlightedIndex }); }; _this.inputHandleBlur = function () { // Need setTimeout, so that when the user presses Tab, the activeElement is the next focused element, not the body element _this.internalSetTimeout(function () { var _activeElement$datase; if (_this.isMouseDown || !_this.props.environment) { return; } var activeElement = _this.props.environment.document.activeElement; var downshiftButtonIsActive = (activeElement == null || (_activeElement$datase = activeElement.dataset) == null ? void 0 : _activeElement$datase.toggle) && _this._rootNode && _this._rootNode.contains(activeElement); if (!downshiftButtonIsActive) { _this.reset({ type: blurInput }); } }); }; //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ INPUT /////////////////////////////// MENU _this.menuRef = function (node) { _this._menuNode = node; }; _this.getMenuProps = function (_temp5, _temp6) { var _extends3; var _ref5 = _temp5 === void 0 ? {} : _temp5, _ref5$refKey = _ref5.refKey, refKey = _ref5$refKey === void 0 ? 'ref' : _ref5$refKey, ref = _ref5.ref, props = _objectWithoutPropertiesLoose(_ref5, _excluded4$2); var _ref6 = _temp6 === void 0 ? {} : _temp6, _ref6$suppressRefErro = _ref6.suppressRefError, suppressRefError = _ref6$suppressRefErro === void 0 ? false : _ref6$suppressRefErro; _this.getMenuProps.called = true; _this.getMenuProps.refKey = refKey; _this.getMenuProps.suppressRefError = suppressRefError; return _extends((_extends3 = {}, _extends3[refKey] = handleRefs(ref, _this.menuRef), _extends3.role = 'listbox', _extends3['aria-labelledby'] = props && props['aria-label'] ? undefined : _this.labelId, _extends3.id = _this.menuId, _extends3), props); }; //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ MENU /////////////////////////////// ITEM _this.getItemProps = function (_temp7) { var _enabledEventHandlers; var _ref7 = _temp7 === void 0 ? {} : _temp7, onMouseMove = _ref7.onMouseMove, onMouseDown = _ref7.onMouseDown, onClick = _ref7.onClick; _ref7.onPress; var index = _ref7.index, _ref7$item = _ref7.item, item = _ref7$item === void 0 ? process.env.NODE_ENV === 'production' ? /* istanbul ignore next */undefined : requiredProp('getItemProps', 'item') : _ref7$item, rest = _objectWithoutPropertiesLoose(_ref7, _excluded5); if (index === undefined) { _this.items.push(item); index = _this.items.indexOf(item); } else { _this.items[index] = item; } var onSelectKey = 'onClick'; var customClickHandler = onClick; var enabledEventHandlers = (_enabledEventHandlers = { // onMouseMove is used over onMouseEnter here. onMouseMove // is only triggered on actual mouse movement while onMouseEnter // can fire on DOM changes, interrupting keyboard navigation onMouseMove: callAllEventHandlers(onMouseMove, function () { if (index === _this.getState().highlightedIndex) { return; } _this.setHighlightedIndex(index, { type: itemMouseEnter }); // We never want to manually scroll when changing state based // on `onMouseMove` because we will be moving the element out // from under the user which is currently scrolling/moving the // cursor _this.avoidScrolling = true; _this.internalSetTimeout(function () { return _this.avoidScrolling = false; }, 250); }), onMouseDown: callAllEventHandlers(onMouseDown, function (event) { // This prevents the activeElement from being changed // to the item so it can remain with the current activeElement // which is a more common use case. event.preventDefault(); }) }, _enabledEventHandlers[onSelectKey] = callAllEventHandlers(customClickHandler, function () { _this.selectItemAtIndex(index, { type: clickItem }); }), _enabledEventHandlers); // Passing down the onMouseDown handler to prevent redirect // of the activeElement if clicking on disabled items var eventHandlers = rest.disabled ? { onMouseDown: enabledEventHandlers.onMouseDown } : enabledEventHandlers; return _extends({ id: _this.getItemId(index), role: 'option', 'aria-selected': _this.getState().highlightedIndex === index }, eventHandlers, rest); }; //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ ITEM _this.clearItems = function () { _this.items = []; }; _this.reset = function (otherStateToSet, cb) { if (otherStateToSet === void 0) { otherStateToSet = {}; } otherStateToSet = pickState(otherStateToSet); _this.internalSetState(function (_ref8) { var selectedItem = _ref8.selectedItem; return _extends({ isOpen: _this.props.defaultIsOpen, highlightedIndex: _this.props.defaultHighlightedIndex, inputValue: _this.props.itemToString(selectedItem) }, otherStateToSet); }, cb); }; _this.toggleMenu = function (otherStateToSet, cb) { if (otherStateToSet === void 0) { otherStateToSet = {}; } otherStateToSet = pickState(otherStateToSet); _this.internalSetState(function (_ref9) { var isOpen = _ref9.isOpen; return _extends({ isOpen: !isOpen }, isOpen && { highlightedIndex: _this.props.defaultHighlightedIndex }, otherStateToSet); }, function () { var _this$getState7 = _this.getState(), isOpen = _this$getState7.isOpen, highlightedIndex = _this$getState7.highlightedIndex; if (isOpen) { if (_this.getItemCount() > 0 && typeof highlightedIndex === 'number') { _this.setHighlightedIndex(highlightedIndex, otherStateToSet); } } cbToCb(cb)(); }); }; _this.openMenu = function (cb) { _this.internalSetState({ isOpen: true }, cb); }; _this.closeMenu = function (cb) { _this.internalSetState({ isOpen: false }, cb); }; _this.updateStatus = debounce(function () { var _this$props; if (!((_this$props = _this.props) != null && (_this$props = _this$props.environment) != null && _this$props.document)) { return; } var state = _this.getState(); var item = _this.items[state.highlightedIndex]; var resultCount = _this.getItemCount(); var status = _this.props.getA11yStatusMessage(_extends({ itemToString: _this.props.itemToString, previousResultCount: _this.previousResultCount, resultCount: resultCount, highlightedItem: item }, state)); _this.previousResultCount = resultCount; setStatus(status, _this.props.environment.document); }, 200); var _this$props2 = _this.props, defaultHighlightedIndex = _this$props2.defaultHighlightedIndex, _this$props2$initialH = _this$props2.initialHighlightedIndex, _highlightedIndex = _this$props2$initialH === void 0 ? defaultHighlightedIndex : _this$props2$initialH, defaultIsOpen = _this$props2.defaultIsOpen, _this$props2$initialI = _this$props2.initialIsOpen, _isOpen = _this$props2$initialI === void 0 ? defaultIsOpen : _this$props2$initialI, _this$props2$initialI2 = _this$props2.initialInputValue, _inputValue = _this$props2$initialI2 === void 0 ? '' : _this$props2$initialI2, _this$props2$initialS = _this$props2.initialSelectedItem, _selectedItem = _this$props2$initialS === void 0 ? null : _this$props2$initialS; var _state = _this.getState({ highlightedIndex: _highlightedIndex, isOpen: _isOpen, inputValue: _inputValue, selectedItem: _selectedItem }); if (_state.selectedItem != null && _this.props.initialInputValue === undefined) { _state.inputValue = _this.props.itemToString(_state.selectedItem); } _this.state = _state; return _this; } _inheritsLoose(Downshift, _Component); var _proto = Downshift.prototype; /** * Clear all running timeouts */ _proto.internalClearTimeouts = function internalClearTimeouts() { this.timeoutIds.forEach(function (id) { clearTimeout(id); }); this.timeoutIds = []; } /** * Gets the state based on internal state or props * If a state value is passed via props, then that * is the value given, otherwise it's retrieved from * stateToMerge * * @param {Object} stateToMerge defaults to this.state * @return {Object} the state */; _proto.getState = function getState$1(stateToMerge) { if (stateToMerge === void 0) { stateToMerge = this.state; } return getState(stateToMerge, this.props); }; _proto.getItemCount = function getItemCount() { // things read better this way. They're in priority order: // 1. `this.itemCount` // 2. `this.props.itemCount` // 3. `this.items.length` var itemCount = this.items.length; if (this.itemCount != null) { itemCount = this.itemCount; } else if (this.props.