?
return Object(external_wp_element_["createElement"])("ul", {
ref: this.bindList,
className: "components-form-token-field__suggestions-list",
id: "components-form-token-suggestions-".concat(this.props.instanceId),
role: "listbox"
}, Object(external_lodash_["map"])(this.props.suggestions, function (suggestion, index) {
var match = _this5.computeSuggestionMatch(suggestion);
var classeName = classnames_default()('components-form-token-field__suggestion', {
'is-selected': index === _this5.props.selectedIndex
});
/* eslint-disable jsx-a11y/click-events-have-key-events */
return Object(external_wp_element_["createElement"])("li", {
id: "components-form-token-suggestions-".concat(_this5.props.instanceId, "-").concat(index),
role: "option",
className: classeName,
key: _this5.props.displayTransform(suggestion),
onMouseDown: _this5.handleMouseDown,
onClick: _this5.handleClick(suggestion),
onMouseEnter: _this5.handleHover(suggestion),
"aria-selected": index === _this5.props.selectedIndex
}, match ? Object(external_wp_element_["createElement"])("span", {
"aria-label": _this5.props.displayTransform(suggestion)
}, match.suggestionBeforeMatch, Object(external_wp_element_["createElement"])("strong", {
className: "components-form-token-field__suggestion-match"
}, match.suggestionMatch), match.suggestionAfterMatch) : _this5.props.displayTransform(suggestion));
/* eslint-enable jsx-a11y/click-events-have-key-events */
}));
}
}]);
return SuggestionsList;
}(external_wp_element_["Component"]);
suggestions_list_SuggestionsList.defaultProps = {
match: '',
onHover: function onHover() {},
onSelect: function onSelect() {},
suggestions: Object.freeze([])
};
/* harmony default export */ var suggestions_list = (Object(external_wp_compose_["withSafeTimeout"])(suggestions_list_SuggestionsList));
// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/higher-order/with-focus-outside/index.js
/**
* WordPress dependencies
*/
/* harmony default export */ var with_focus_outside = (Object(external_wp_compose_["createHigherOrderComponent"])(function (WrappedComponent) {
return function (props) {
var _useState = Object(external_wp_element_["useState"])(),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
handleFocusOutside = _useState2[0],
setHandleFocusOutside = _useState2[1];
var bindFocusOutsideHandler = Object(external_wp_element_["useCallback"])(function (node) {
return setHandleFocusOutside(function () {
return node !== null && node !== void 0 && node.handleFocusOutside ? node.handleFocusOutside.bind(node) : undefined;
});
}, []);
return Object(external_wp_element_["createElement"])("div", Object(external_wp_compose_["__experimentalUseFocusOutside"])(handleFocusOutside), Object(external_wp_element_["createElement"])(WrappedComponent, Object(esm_extends["a" /* default */])({
ref: bindFocusOutsideHandler
}, props)));
};
}, 'withFocusOutside'));
// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/combobox-control/index.js
function combobox_control_createSuper(Derived) { var hasNativeReflectConstruct = combobox_control_isNativeReflectConstruct(); return function _createSuperInternal() { var Super = Object(getPrototypeOf["a" /* default */])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = Object(getPrototypeOf["a" /* default */])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return Object(possibleConstructorReturn["a" /* default */])(this, result); }; }
function combobox_control_isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
var DetectOutside = with_focus_outside( /*#__PURE__*/function (_Component) {
Object(inherits["a" /* default */])(_class, _Component);
var _super = combobox_control_createSuper(_class);
function _class() {
Object(classCallCheck["a" /* default */])(this, _class);
return _super.apply(this, arguments);
}
Object(createClass["a" /* default */])(_class, [{
key: "handleFocusOutside",
value: function handleFocusOutside(event) {
this.props.onFocusOutside(event);
}
}, {
key: "render",
value: function render() {
return this.props.children;
}
}]);
return _class;
}(external_wp_element_["Component"]));
function ComboboxControl(_ref) {
var _currentOption$label;
var value = _ref.value,
label = _ref.label,
options = _ref.options,
onChange = _ref.onChange,
onFilterValueChange = _ref.onFilterValueChange,
hideLabelFromVision = _ref.hideLabelFromVision,
help = _ref.help,
_ref$allowReset = _ref.allowReset,
allowReset = _ref$allowReset === void 0 ? true : _ref$allowReset,
className = _ref.className,
_ref$messages = _ref.messages,
messages = _ref$messages === void 0 ? {
selected: Object(external_wp_i18n_["__"])('Item selected.')
} : _ref$messages;
var instanceId = Object(external_wp_compose_["useInstanceId"])(ComboboxControl);
var _useState = Object(external_wp_element_["useState"])(null),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
selectedSuggestion = _useState2[0],
setSelectedSuggestion = _useState2[1];
var _useState3 = Object(external_wp_element_["useState"])(false),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
isExpanded = _useState4[0],
setIsExpanded = _useState4[1];
var _useState5 = Object(external_wp_element_["useState"])(''),
_useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
inputValue = _useState6[0],
setInputValue = _useState6[1];
var inputContainer = Object(external_wp_element_["useRef"])();
var currentOption = options.find(function (option) {
return option.value === value;
});
var currentLabel = (_currentOption$label = currentOption === null || currentOption === void 0 ? void 0 : currentOption.label) !== null && _currentOption$label !== void 0 ? _currentOption$label : '';
var matchingSuggestions = Object(external_wp_element_["useMemo"])(function () {
var startsWithMatch = [];
var containsMatch = [];
var match = Object(external_lodash_["deburr"])(inputValue.toLocaleLowerCase());
options.forEach(function (option) {
var index = Object(external_lodash_["deburr"])(option.label).toLocaleLowerCase().indexOf(match);
if (index === 0) {
startsWithMatch.push(option);
} else if (index > 0) {
containsMatch.push(option);
}
});
return startsWithMatch.concat(containsMatch);
}, [inputValue, options, value]);
var onSuggestionSelected = function onSuggestionSelected(newSelectedSuggestion) {
onChange(newSelectedSuggestion.value);
Object(external_wp_a11y_["speak"])(messages.selected, 'assertive');
setSelectedSuggestion(newSelectedSuggestion);
setInputValue('');
setIsExpanded(false);
};
var handleArrowNavigation = function handleArrowNavigation() {
var offset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
var index = matchingSuggestions.indexOf(selectedSuggestion);
var nextIndex = index + offset;
if (nextIndex < 0) {
nextIndex = matchingSuggestions.length - 1;
} else if (nextIndex >= matchingSuggestions.length) {
nextIndex = 0;
}
setSelectedSuggestion(matchingSuggestions[nextIndex]);
setIsExpanded(true);
};
var onKeyDown = function onKeyDown(event) {
var preventDefault = false;
switch (event.keyCode) {
case external_wp_keycodes_["ENTER"]:
if (selectedSuggestion) {
onSuggestionSelected(selectedSuggestion);
preventDefault = true;
}
break;
case external_wp_keycodes_["UP"]:
handleArrowNavigation(-1);
preventDefault = true;
break;
case external_wp_keycodes_["DOWN"]:
handleArrowNavigation(1);
preventDefault = true;
break;
case external_wp_keycodes_["ESCAPE"]:
setIsExpanded(false);
setSelectedSuggestion(null);
preventDefault = true;
event.stopPropagation();
break;
default:
break;
}
if (preventDefault) {
event.preventDefault();
}
};
var onFocus = function onFocus() {
setIsExpanded(true);
onFilterValueChange('');
setInputValue('');
};
var onFocusOutside = function onFocusOutside() {
setIsExpanded(false);
};
var onInputChange = function onInputChange(event) {
var text = event.value;
setInputValue(text);
onFilterValueChange(text);
setIsExpanded(true);
};
var handleOnReset = function handleOnReset() {
onChange(null);
inputContainer.current.input.focus();
}; // Announcements
Object(external_wp_element_["useEffect"])(function () {
var hasMatchingSuggestions = matchingSuggestions.length > 0;
if (isExpanded) {
var message = hasMatchingSuggestions ? Object(external_wp_i18n_["sprintf"])(
/* translators: %d: number of results. */
Object(external_wp_i18n_["_n"])('%d result found, use up and down arrow keys to navigate.', '%d results found, use up and down arrow keys to navigate.', matchingSuggestions.length), matchingSuggestions.length) : Object(external_wp_i18n_["__"])('No results.');
Object(external_wp_a11y_["speak"])(message, 'polite');
}
}, [matchingSuggestions, isExpanded]); // Disable reason: There is no appropriate role which describes the
// input container intended accessible usability.
// TODO: Refactor click detection to use blur to stop propagation.
/* eslint-disable jsx-a11y/no-static-element-interactions */
return Object(external_wp_element_["createElement"])(DetectOutside, {
onFocusOutside: onFocusOutside
}, Object(external_wp_element_["createElement"])(base_control, {
className: classnames_default()(className, 'components-combobox-control'),
tabIndex: "-1",
label: label,
id: "components-form-token-input-".concat(instanceId),
hideLabelFromVision: hideLabelFromVision,
help: help
}, Object(external_wp_element_["createElement"])("div", {
className: "components-combobox-control__suggestions-container",
tabIndex: "-1",
onKeyDown: onKeyDown
}, Object(external_wp_element_["createElement"])(flex_Flex, null, Object(external_wp_element_["createElement"])(block, null, Object(external_wp_element_["createElement"])(token_input, {
className: "components-combobox-control__input",
instanceId: instanceId,
ref: inputContainer,
value: isExpanded ? inputValue : currentLabel,
"aria-label": currentLabel ? "".concat(currentLabel, ", ").concat(label) : null,
onFocus: onFocus,
isExpanded: isExpanded,
selectedSuggestionIndex: matchingSuggestions.indexOf(selectedSuggestion),
onChange: onInputChange
})), allowReset && Object(external_wp_element_["createElement"])(flex_item, null, Object(external_wp_element_["createElement"])(build_module_button["a" /* default */], {
className: "components-combobox-control__reset",
icon: close_small["a" /* default */],
disabled: !value,
onClick: handleOnReset,
label: Object(external_wp_i18n_["__"])('Reset')
}))), isExpanded && Object(external_wp_element_["createElement"])(suggestions_list, {
instanceId: instanceId,
match: {
label: inputValue
},
displayTransform: function displayTransform(suggestion) {
return suggestion.label;
},
suggestions: matchingSuggestions,
selectedIndex: matchingSuggestions.indexOf(selectedSuggestion),
onHover: setSelectedSuggestion,
onSelect: onSuggestionSelected,
scrollIntoView: true
}))));
/* eslint-enable jsx-a11y/no-static-element-interactions */
}
/* harmony default export */ var combobox_control = (ComboboxControl);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js
var objectWithoutPropertiesLoose = __webpack_require__(44);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js
var inheritsLoose = __webpack_require__(178);
// EXTERNAL MODULE: ./node_modules/prop-types/index.js
var prop_types = __webpack_require__(30);
var prop_types_default = /*#__PURE__*/__webpack_require__.n(prop_types);
// EXTERNAL MODULE: ./node_modules/downshift/node_modules/react-is/index.js
var react_is = __webpack_require__(204);
// CONCATENATED MODULE: ./node_modules/compute-scroll-into-view/dist/index.module.js
function t(t){return"object"==typeof t&&null!=t&&1===t.nodeType}function index_module_e(t,e){return(!e||"hidden"!==t)&&"visible"!==t&&"clip"!==t}function n(t,n){if(t.clientHeight
e||o>t&&l=e&&d>=n?o-t-r:l>e&&dn?l-e+i:0}/* harmony default export */ var index_module = (function(e,i){var o=window,l=i.scrollMode,d=i.block,u=i.inline,h=i.boundary,a=i.skipOverflowHiddenElements,c="function"==typeof h?h:function(t){return t!==h};if(!t(e))throw new TypeError("Invalid target");for(var f=document.scrollingElement||document.documentElement,s=[],p=e;t(p)&&c(p);){if((p=p.parentElement)===f){s.push(p);break}null!=p&&p===document.body&&n(p)&&!n(document.documentElement)||null!=p&&n(p,a)&&s.push(p)}for(var m=o.visualViewport?o.visualViewport.width:innerWidth,g=o.visualViewport?o.visualViewport.height:innerHeight,w=window.scrollX||pageXOffset,v=window.scrollY||pageYOffset,W=e.getBoundingClientRect(),b=W.height,H=W.width,y=W.top,E=W.right,M=W.bottom,V=W.left,x="start"===d||"nearest"===d?y:"end"===d?M:y+b/2,I="center"===u?V+H/2:"end"===u?E:V,C=[],T=0;T=0&&V>=0&&M<=g&&E<=m&&y>=R&&M<=Y&&V>=L&&E<=X)return C;var S=getComputedStyle(k),j=parseInt(S.borderLeftWidth,10),q=parseInt(S.borderTopWidth,10),z=parseInt(S.borderRightWidth,10),A=parseInt(S.borderBottomWidth,10),F=0,G=0,J="offsetWidth"in k?k.offsetWidth-k.clientWidth-j-z:0,K="offsetHeight"in k?k.offsetHeight-k.clientHeight-q-A:0;if(f===k)F="start"===d?x:"end"===d?x-g:"nearest"===d?index_module_r(v,v+g,g,q,A,v+x,v+x+b,b):x-g/2,G="start"===u?I:"center"===u?I-m/2:"end"===u?I-m:index_module_r(w,w+m,m,j,z,w+I,w+I+H,H),F=Math.max(0,F+v),G=Math.max(0,G+w);else{F="start"===d?x-R-q:"end"===d?x-Y+A+K:"nearest"===d?index_module_r(R,Y,D,q,A+K,x,x+b,b):x-(R+D/2)+K/2,G="start"===u?I-L-j:"center"===u?I-(L+O/2)+J/2:"end"===u?I-X+z+J:index_module_r(L,X,O,j,z+J,I,I+H,H);var N=k.scrollLeft,P=k.scrollTop;x+=P-(F=Math.max(0,Math.min(P+F,k.scrollHeight-D+K))),I+=N-(G=Math.max(0,Math.min(N+G,k.scrollWidth-O+J)))}C.push({el:k,top:F,left:G})}return C});
// CONCATENATED MODULE: ./node_modules/downshift/dist/downshift.esm.js
var idCounter = 0;
/**
* 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 : downshift_esm_noop;
}
function downshift_esm_noop() {}
/**
* 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 downshift_esm_scrollIntoView(node, menuNode) {
if (!node) {
return;
}
var actions = index_module(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;
});
}
/**
* @param {HTMLElement} parent the parent node
* @param {HTMLElement} child the child node
* @return {Boolean} whether the parent is the child or the child is in the parent
*/
function isOrContainsNode(parent, child) {
return parent === child || child instanceof Node && parent.contains && parent.contains(child);
}
/**
* 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;
}
});
};
}
/**
* This generates a unique ID for an instance of Downshift
* @return {String} the unique ID
*/
function downshift_esm_generateId() {
return String(idCounter++);
}
/**
* Resets idCounter to 0. Used for SSR.
*/
function resetIdCounter() {
idCounter = 0;
}
/**
* Default implementation for status message. Only added when menu is open.
* Will specift 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 downshift_esm_getA11yStatusMessage(_ref2) {
var isOpen = _ref2.isOpen,
resultCount = _ref2.resultCount,
previousResultCount = _ref2.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) {
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 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 {Object} state The state of the component/hook.
* @param {Object} props The props that may contain controlled values.
* @returns {Object} The merged controlled state.
*/
function getState(state, props) {
return Object.keys(state).reduce(function (prevState, key) {
prevState[key] = isControlledProp(props, key) ? props[key] : state[key];
return prevState;
}, {});
}
/**
* 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 new index in the list, in a circular way. If next value is out of bonds from the total,
* it will wrap to either 0 or itemCount - 1.
*
* @param {number} moveAmount Number of positions to move. Negative to move backwards, positive forwards.
* @param {number} baseIndex The initial position to move from.
* @param {number} itemCount The total number of items.
* @param {Function} getItemNodeFromIndex Used to check if item is disabled.
* @param {boolean} circular Specify if navigation is circular. Default is true.
* @returns {number} The new index after the move.
*/
function getNextWrappingIndex(moveAmount, baseIndex, itemCount, getItemNodeFromIndex, circular) {
if (circular === void 0) {
circular = true;
}
if (itemCount === 0) {
return -1;
}
var itemsLastIndex = itemCount - 1;
if (typeof baseIndex !== 'number' || baseIndex < 0 || baseIndex >= itemCount) {
baseIndex = moveAmount > 0 ? -1 : itemsLastIndex + 1;
}
var newIndex = baseIndex + moveAmount;
if (newIndex < 0) {
newIndex = circular ? itemsLastIndex : 0;
} else if (newIndex > itemsLastIndex) {
newIndex = circular ? 0 : itemsLastIndex;
}
var nonDisabledNewIndex = getNextNonDisabledIndex(moveAmount, newIndex, itemCount, getItemNodeFromIndex, circular);
if (nonDisabledNewIndex === -1) {
return baseIndex >= itemCount ? -1 : baseIndex;
}
return nonDisabledNewIndex;
}
/**
* Returns the next index in the list of an item that is not disabled.
*
* @param {number} moveAmount Number of positions to move. Negative to move backwards, positive forwards.
* @param {number} baseIndex The initial position to move from.
* @param {number} itemCount The total number of items.
* @param {Function} getItemNodeFromIndex Used to check if item is disabled.
* @param {boolean} circular Specify if navigation is circular. Default is true.
* @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.
*/
function getNextNonDisabledIndex(moveAmount, baseIndex, itemCount, getItemNodeFromIndex, circular) {
var currentElementNode = getItemNodeFromIndex(baseIndex);
if (!currentElementNode || !currentElementNode.hasAttribute('disabled')) {
return baseIndex;
}
if (moveAmount > 0) {
for (var index = baseIndex + 1; index < itemCount; index++) {
if (!getItemNodeFromIndex(index).hasAttribute('disabled')) {
return index;
}
}
} else {
for (var _index = baseIndex - 1; _index >= 0; _index--) {
if (!getItemNodeFromIndex(_index).hasAttribute('disabled')) {
return _index;
}
}
}
if (circular) {
return moveAmount > 0 ? getNextNonDisabledIndex(1, 0, itemCount, getItemNodeFromIndex, false) : getNextNonDisabledIndex(-1, itemCount - 1, itemCount, getItemNodeFromIndex, false);
}
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 {Document} document The document.
* @param {boolean} checkActiveElement Whether to also check activeElement.
*
* @returns {boolean} Whether or not the target is within downshift elements.
*/
function targetWithinDownshift(target, downshiftElements, document, checkActiveElement) {
if (checkActiveElement === void 0) {
checkActiveElement = true;
}
return downshiftElements.some(function (contextNode) {
return contextNode && (isOrContainsNode(contextNode, target) || checkActiveElement && isOrContainsNode(contextNode, document.activeElement));
});
} // eslint-disable-next-line import/no-mutable-exports
var validateControlledUnchanged = downshift_esm_noop;
/* istanbul ignore next */
if (false) {}
var cleanupStatus = debounce(function (documentProp) {
getStatusDiv(documentProp).textContent = '';
}, 500);
/**
* @param {String} status the status message
* @param {Object} documentProp document passed by the user.
*/
function setStatus(status, documentProp) {
var div = getStatusDiv(documentProp);
if (!status) {
return;
}
div.textContent = status;
cleanupStatus(documentProp);
}
/**
* Get the status node or create it if it does not already exist.
* @param {Object} documentProp document passed by the user.
* @return {HTMLElement} the status node.
*/
function getStatusDiv(documentProp) {
if (documentProp === void 0) {
documentProp = document;
}
var statusDiv = documentProp.getElementById('a11y-status-message');
if (statusDiv) {
return statusDiv;
}
statusDiv = documentProp.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'
});
documentProp.body.appendChild(statusDiv);
return statusDiv;
}
var unknown = false ? undefined : 0;
var mouseUp = false ? undefined : 1;
var itemMouseEnter = false ? undefined : 2;
var keyDownArrowUp = false ? undefined : 3;
var keyDownArrowDown = false ? undefined : 4;
var keyDownEscape = false ? undefined : 5;
var keyDownEnter = false ? undefined : 6;
var keyDownHome = false ? undefined : 7;
var keyDownEnd = false ? undefined : 8;
var clickItem = false ? undefined : 9;
var blurInput = false ? undefined : 10;
var changeInput = false ? undefined : 11;
var keyDownSpaceButton = false ? undefined : 12;
var clickButton = false ? undefined : 13;
var blurButton = false ? undefined : 14;
var controlledPropUpdatedSelectedItem = false ? undefined : 15;
var touchEnd = false ? undefined : 16;
var downshift_esm_stateChangeTypes = /*#__PURE__*/Object.freeze({
__proto__: null,
unknown: unknown,
mouseUp: mouseUp,
itemMouseEnter: itemMouseEnter,
keyDownArrowUp: keyDownArrowUp,
keyDownArrowDown: keyDownArrowDown,
keyDownEscape: keyDownEscape,
keyDownEnter: keyDownEnter,
keyDownHome: keyDownHome,
keyDownEnd: keyDownEnd,
clickItem: clickItem,
blurInput: blurInput,
changeInput: changeInput,
keyDownSpaceButton: keyDownSpaceButton,
clickButton: clickButton,
blurButton: blurButton,
controlledPropUpdatedSelectedItem: controlledPropUpdatedSelectedItem,
touchEnd: touchEnd
});
var downshift_esm_Downshift = /*#__PURE__*/function () {
var Downshift = /*#__PURE__*/function (_Component) {
Object(inheritsLoose["a" /* default */])(Downshift, _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-" + downshift_esm_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.input = null;
_this.items = [];
_this.itemCount = null;
_this.previousResultCount = 0;
_this.timeoutIds = [];
_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.setHighlightedIndex = function (highlightedIndex, otherStateToSet) {
if (highlightedIndex === void 0) {
highlightedIndex = _this.props.defaultHighlightedIndex;
}
if (otherStateToSet === void 0) {
otherStateToSet = {};
}
otherStateToSet = pickState(otherStateToSet);
_this.internalSetState(Object(esm_extends["a" /* default */])({
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(Object(esm_extends["a" /* default */])({
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);
};
_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, Object(esm_extends["a" /* default */])({}, _this.getStateAndHelpers(), stateToSet));
}
return _this.setState(function (state) {
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 = {}; // this is just used to tell whether the state changed
// 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.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, Object(esm_extends["a" /* default */])({}, _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());
});
};
_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 = Object(objectWithoutPropertiesLoose["a" /* default */])(_ref, ["refKey", "ref"]);
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 Object(esm_extends["a" /* default */])((_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);
};
_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 = getNextWrappingIndex(1, highlightedIndex, itemCount, function (index) {
return _this2.getItemNodeFromIndex(index);
});
_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 = getNextWrappingIndex(-1, highlightedIndex, itemCount, function (index) {
return _this3.getItemNodeFromIndex(index);
});
_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(Object(esm_extends["a" /* default */])({
type: keyDownEscape
}, !this.state.isOpen && {
selectedItem: null,
inputValue: ''
}));
}
};
_this.buttonKeyDownHandlers = Object(esm_extends["a" /* default */])({}, _this.keyDownHandlers, {
' ': function _(event) {
event.preventDefault();
this.toggleMenu({
type: keyDownSpaceButton
});
}
});
_this.inputKeyDownHandlers = Object(esm_extends["a" /* default */])({}, _this.keyDownHandlers, {
Home: function Home(event) {
var _this4 = this;
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 = getNextNonDisabledIndex(1, 0, itemCount, function (index) {
return _this4.getItemNodeFromIndex(index);
}, false);
this.setHighlightedIndex(newHighlightedIndex, {
type: keyDownHome
});
},
End: function End(event) {
var _this5 = this;
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 = getNextNonDisabledIndex(-1, itemCount - 1, itemCount, function (index) {
return _this5.getItemNodeFromIndex(index);
}, false);
this.setHighlightedIndex(newHighlightedIndex, {
type: keyDownEnd
});
}
});
_this.getToggleButtonProps = function (_temp3) {
var _ref3 = _temp3 === void 0 ? {} : _temp3,
onClick = _ref3.onClick,
onPress = _ref3.onPress,
onKeyDown = _ref3.onKeyDown,
onKeyUp = _ref3.onKeyUp,
onBlur = _ref3.onBlur,
rest = Object(objectWithoutPropertiesLoose["a" /* default */])(_ref3, ["onClick", "onPress", "onKeyDown", "onKeyUp", "onBlur"]);
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 Object(esm_extends["a" /* default */])({
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(Object(assertThisInitialized["a" /* default */])(_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.document.activeElement === _this.props.environment.document.body) {
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 (false) {} 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.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)
) {
_this.reset({
type: blurButton
});
}
});
};
_this.getLabelProps = function (props) {
return Object(esm_extends["a" /* default */])({
htmlFor: _this.inputId,
id: _this.labelId
}, props);
};
_this.getInputProps = function (_temp4) {
var _ref4 = _temp4 === void 0 ? {} : _temp4,
onKeyDown = _ref4.onKeyDown,
onBlur = _ref4.onBlur,
onChange = _ref4.onChange,
onInput = _ref4.onInput,
onChangeText = _ref4.onChangeText,
rest = Object(objectWithoutPropertiesLoose["a" /* default */])(_ref4, ["onKeyDown", "onBlur", "onChange", "onInput", "onChangeText"]);
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 Object(esm_extends["a" /* default */])({
'aria-autocomplete': 'list',
'aria-activedescendant': isOpen && typeof highlightedIndex === 'number' && highlightedIndex >= 0 ? _this.getItemId(highlightedIndex) : null,
'aria-controls': isOpen ? _this.menuId : null,
'aria-labelledby': _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(Object(assertThisInitialized["a" /* default */])(_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 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);
if (!_this.isMouseDown && !downshiftButtonIsActive) {
_this.reset({
type: blurInput
});
}
});
};
_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 = Object(objectWithoutPropertiesLoose["a" /* default */])(_ref5, ["refKey", "ref"]);
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 Object(esm_extends["a" /* default */])((_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);
};
_this.getItemProps = function (_temp7) {
var _enabledEventHandlers;
var _ref7 = _temp7 === void 0 ? {} : _temp7,
onMouseMove = _ref7.onMouseMove,
onMouseDown = _ref7.onMouseDown,
onClick = _ref7.onClick,
onPress = _ref7.onPress,
index = _ref7.index,
_ref7$item = _ref7.item,
item = _ref7$item === void 0 ? true ?
/* istanbul ignore next */
undefined : undefined : _ref7$item,
rest = Object(objectWithoutPropertiesLoose["a" /* default */])(_ref7, ["onMouseMove", "onMouseDown", "onClick", "onPress", "index", "item"]);
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 Object(esm_extends["a" /* default */])({
id: _this.getItemId(index),
role: 'option',
'aria-selected': _this.getState().highlightedIndex === index
}, eventHandlers, rest);
};
_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 Object(esm_extends["a" /* default */])({
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 Object(esm_extends["a" /* default */])({
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 state = _this.getState();
var item = _this.items[state.highlightedIndex];
var resultCount = _this.getItemCount();
var status = _this.props.getA11yStatusMessage(Object(esm_extends["a" /* default */])({
itemToString: _this.props.itemToString,
previousResultCount: _this.previousResultCount,
resultCount: resultCount,
highlightedItem: item
}, state));
_this.previousResultCount = resultCount;
setStatus(status, _this.props.environment.document);
}, 200);
var _this$props = _this.props,
defaultHighlightedIndex = _this$props.defaultHighlightedIndex,
_this$props$initialHi = _this$props.initialHighlightedIndex,
_highlightedIndex = _this$props$initialHi === void 0 ? defaultHighlightedIndex : _this$props$initialHi,
defaultIsOpen = _this$props.defaultIsOpen,
_this$props$initialIs = _this$props.initialIsOpen,
_isOpen = _this$props$initialIs === void 0 ? defaultIsOpen : _this$props$initialIs,
_this$props$initialIn = _this$props.initialInputValue,
_inputValue = _this$props$initialIn === void 0 ? '' : _this$props$initialIn,
_this$props$initialSe = _this$props.initialSelectedItem,
_selectedItem = _this$props$initialSe === void 0 ? null : _this$props$initialSe;
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;
}
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.itemCount !== undefined) {
itemCount = this.props.itemCount;
}
return itemCount;
};
_proto.getItemNodeFromIndex = function getItemNodeFromIndex(index) {
return this.props.environment.document.getElementById(this.getItemId(index));
};
_proto.scrollHighlightedItemIntoView = function scrollHighlightedItemIntoView() {
/* istanbul ignore else (react-native) */
{
var node = this.getItemNodeFromIndex(this.getState().highlightedIndex);
this.props.scrollIntoView(node, this._menuNode);
}
};
_proto.moveHighlightedIndex = function moveHighlightedIndex(amount, otherStateToSet) {
var _this6 = this;
var itemCount = this.getItemCount();
var _this$getState8 = this.getState(),
highlightedIndex = _this$getState8.highlightedIndex;
if (itemCount > 0) {
var nextHighlightedIndex = getNextWrappingIndex(amount, highlightedIndex, itemCount, function (index) {
return _this6.getItemNodeFromIndex(index);
});
this.setHighlightedIndex(nextHighlightedIndex, otherStateToSet);
}
};
_proto.getStateAndHelpers = function getStateAndHelpers() {
var _this$getState9 = this.getState(),
highlightedIndex = _this$getState9.highlightedIndex,
inputValue = _this$getState9.inputValue,
selectedItem = _this$getState9.selectedItem,
isOpen = _this$getState9.isOpen;
var itemToString = this.props.itemToString;
var id = this.id;
var getRootProps = this.getRootProps,
getToggleButtonProps = this.getToggleButtonProps,
getLabelProps = this.getLabelProps,
getMenuProps = this.getMenuProps,
getInputProps = this.getInputProps,
getItemProps = this.getItemProps,
openMenu = this.openMenu,
closeMenu = this.closeMenu,
toggleMenu = this.toggleMenu,
selectItem = this.selectItem,
selectItemAtIndex = this.selectItemAtIndex,
selectHighlightedItem = this.selectHighlightedItem,
setHighlightedIndex = this.setHighlightedIndex,
clearSelection = this.clearSelection,
clearItems = this.clearItems,
reset = this.reset,
setItemCount = this.setItemCount,
unsetItemCount = this.unsetItemCount,
setState = this.internalSetState;
return {
// prop getters
getRootProps: getRootProps,
getToggleButtonProps: getToggleButtonProps,
getLabelProps: getLabelProps,
getMenuProps: getMenuProps,
getInputProps: getInputProps,
getItemProps: getItemProps,
// actions
reset: reset,
openMenu: openMenu,
closeMenu: closeMenu,
toggleMenu: toggleMenu,
selectItem: selectItem,
selectItemAtIndex: selectItemAtIndex,
selectHighlightedItem: selectHighlightedItem,
setHighlightedIndex: setHighlightedIndex,
clearSelection: clearSelection,
clearItems: clearItems,
setItemCount: setItemCount,
unsetItemCount: unsetItemCount,
setState: setState,
// props
itemToString: itemToString,
// derived
id: id,
// state
highlightedIndex: highlightedIndex,
inputValue: inputValue,
isOpen: isOpen,
selectedItem: selectedItem
};
} //////////////////////////// ROOT
;
_proto.componentDidMount = function componentDidMount() {
var _this7 = this;
/* istanbul ignore if (react-native) */
if (false) {}
/* istanbul ignore if (react-native) */
{
// this.isMouseDown helps us track whether the mouse is currently held down.
// This is useful when the user clicks on an item in the list, but holds the mouse
// down long enough for the list to disappear (because the blur event fires on the input)
// this.isMouseDown is used in the blur handler on the input to determine whether the blur event should
// trigger hiding the menu.
var onMouseDown = function onMouseDown() {
_this7.isMouseDown = true;
};
var onMouseUp = function onMouseUp(event) {
_this7.isMouseDown = false; // if the target element or the activeElement is within a downshift node
// then we don't want to reset downshift
var contextWithinDownshift = targetWithinDownshift(event.target, [_this7._rootNode, _this7._menuNode], _this7.props.environment.document);
if (!contextWithinDownshift && _this7.getState().isOpen) {
_this7.reset({
type: mouseUp
}, function () {
return _this7.props.onOuterClick(_this7.getStateAndHelpers());
});
}
}; // Touching an element in iOS gives focus and hover states, but touching out of
// the element will remove hover, and persist the focus state, resulting in the
// blur event not being triggered.
// this.isTouchMove helps us track whether the user is tapping or swiping on a touch screen.
// If the user taps outside of Downshift, the component should be reset,
// but not if the user is swiping
var onTouchStart = function onTouchStart() {
_this7.isTouchMove = false;
};
var onTouchMove = function onTouchMove() {
_this7.isTouchMove = true;
};
var onTouchEnd = function onTouchEnd(event) {
var contextWithinDownshift = targetWithinDownshift(event.target, [_this7._rootNode, _this7._menuNode], _this7.props.environment.document, false);
if (!_this7.isTouchMove && !contextWithinDownshift && _this7.getState().isOpen) {
_this7.reset({
type: touchEnd
}, function () {
return _this7.props.onOuterClick(_this7.getStateAndHelpers());
});
}
};
var environment = this.props.environment;
environment.addEventListener('mousedown', onMouseDown);
environment.addEventListener('mouseup', onMouseUp);
environment.addEventListener('touchstart', onTouchStart);
environment.addEventListener('touchmove', onTouchMove);
environment.addEventListener('touchend', onTouchEnd);
this.cleanup = function () {
_this7.internalClearTimeouts();
_this7.updateStatus.cancel();
environment.removeEventListener('mousedown', onMouseDown);
environment.removeEventListener('mouseup', onMouseUp);
environment.removeEventListener('touchstart', onTouchStart);
environment.removeEventListener('touchmove', onTouchMove);
environment.removeEventListener('touchend', onTouchEnd);
};
}
};
_proto.shouldScroll = function shouldScroll(prevState, prevProps) {
var _ref10 = this.props.highlightedIndex === undefined ? this.getState() : this.props,
currentHighlightedIndex = _ref10.highlightedIndex;
var _ref11 = prevProps.highlightedIndex === undefined ? prevState : prevProps,
prevHighlightedIndex = _ref11.highlightedIndex;
var scrollWhenOpen = currentHighlightedIndex && this.getState().isOpen && !prevState.isOpen;
var scrollWhenNavigating = currentHighlightedIndex !== prevHighlightedIndex;
return scrollWhenOpen || scrollWhenNavigating;
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
if (false) {}
if (isControlledProp(this.props, 'selectedItem') && this.props.selectedItemChanged(prevProps.selectedItem, this.props.selectedItem)) {
this.internalSetState({
type: controlledPropUpdatedSelectedItem,
inputValue: this.props.itemToString(this.props.selectedItem)
});
}
if (!this.avoidScrolling && this.shouldScroll(prevState, prevProps)) {
this.scrollHighlightedItemIntoView();
}
/* istanbul ignore else (react-native) */
{
this.updateStatus();
}
};
_proto.componentWillUnmount = function componentWillUnmount() {
this.cleanup(); // avoids memory leak
};
_proto.render = function render() {
var children = unwrapArray(this.props.children, downshift_esm_noop); // because the items are rerendered every time we call the children
// we clear this out each render and it will be populated again as
// getItemProps is called.
this.clearItems(); // we reset this so we know whether the user calls getRootProps during
// this render. If they do then we don't need to do anything,
// if they don't then we need to clone the element they return and
// apply the props for them.
this.getRootProps.called = false;
this.getRootProps.refKey = undefined;
this.getRootProps.suppressRefError = undefined; // we do something similar for getMenuProps
this.getMenuProps.called = false;
this.getMenuProps.refKey = undefined;
this.getMenuProps.suppressRefError = undefined; // we do something similar for getLabelProps
this.getLabelProps.called = false; // and something similar for getInputProps
this.getInputProps.called = false;
var element = unwrapArray(children(this.getStateAndHelpers()));
if (!element) {
return null;
}
if (this.getRootProps.called || this.props.suppressRefError) {
if (false) {}
return element;
} else if (isDOMElement(element)) {
// they didn't apply the root props, but we can clone
// this and apply the props ourselves
return /*#__PURE__*/Object(external_React_["cloneElement"])(element, this.getRootProps(getElementProps(element)));
}
/* istanbul ignore else */
if (false) {}
/* istanbul ignore next */
return undefined;
};
return Downshift;
}(external_React_["Component"]);
Downshift.defaultProps = {
defaultHighlightedIndex: null,
defaultIsOpen: false,
getA11yStatusMessage: downshift_esm_getA11yStatusMessage,
itemToString: function itemToString(i) {
if (i == null) {
return '';
}
if (false) {}
return String(i);
},
onStateChange: downshift_esm_noop,
onInputValueChange: downshift_esm_noop,
onUserAction: downshift_esm_noop,
onChange: downshift_esm_noop,
onSelect: downshift_esm_noop,
onOuterClick: downshift_esm_noop,
selectedItemChanged: function selectedItemChanged(prevItem, item) {
return prevItem !== item;
},
environment: typeof window === 'undefined'
/* istanbul ignore next (ssr) */
? {} : window,
stateReducer: function stateReducer(state, stateToSet) {
return stateToSet;
},
suppressRefError: false,
scrollIntoView: downshift_esm_scrollIntoView
};
Downshift.stateChangeTypes = downshift_esm_stateChangeTypes;
return Downshift;
}();
false ? undefined : void 0;
function validateGetMenuPropsCalledCorrectly(node, _ref12) {
var refKey = _ref12.refKey;
if (!node) {
// eslint-disable-next-line no-console
console.error("downshift: The ref prop \"" + refKey + "\" from getMenuProps was not applied correctly on your menu element.");
}
}
function validateGetRootPropsCalledCorrectly(element, _ref13) {
var refKey = _ref13.refKey;
var refKeySpecified = refKey !== 'ref';
var isComposite = !isDOMElement(element);
if (isComposite && !refKeySpecified && !Object(react_is["isForwardRef"])(element)) {
// eslint-disable-next-line no-console
console.error('downshift: You returned a non-DOM element. You must specify a refKey in getRootProps');
} else if (!isComposite && refKeySpecified) {
// eslint-disable-next-line no-console
console.error("downshift: You returned a DOM element. You should not specify a refKey in getRootProps. You specified \"" + refKey + "\"");
}
if (!Object(react_is["isForwardRef"])(element) && !getElementProps(element)[refKey]) {
// eslint-disable-next-line no-console
console.error("downshift: You must apply the ref prop \"" + refKey + "\" from getRootProps onto your root element.");
}
}
var dropdownDefaultStateValues = {
highlightedIndex: -1,
isOpen: false,
selectedItem: null,
inputValue: ''
};
function callOnChangeProps(action, state, newState) {
var props = action.props,
type = action.type;
var changes = {};
Object.keys(state).forEach(function (key) {
invokeOnChangeHandler(key, action, state, newState);
if (newState[key] !== state[key]) {
changes[key] = newState[key];
}
});
if (props.onStateChange && Object.keys(changes).length) {
props.onStateChange(Object(esm_extends["a" /* default */])({
type: type
}, changes));
}
}
function invokeOnChangeHandler(key, action, state, newState) {
var props = action.props,
type = action.type;
var handler = "on" + capitalizeString(key) + "Change";
if (props[handler] && newState[key] !== undefined && newState[key] !== state[key]) {
props[handler](Object(esm_extends["a" /* default */])({
type: type
}, newState));
}
}
/**
* Default state reducer that returns the changes.
*
* @param {Object} s state.
* @param {Object} a action with changes.
* @returns {Object} changes.
*/
function downshift_esm_stateReducer(s, a) {
return a.changes;
}
/**
* Returns a message to be added to aria-live region when item is selected.
*
* @param {Object} selectionParameters Parameters required to build the message.
* @returns {string} The a11y message.
*/
function downshift_esm_getA11ySelectionMessage(selectionParameters) {
var selectedItem = selectionParameters.selectedItem,
itemToStringLocal = selectionParameters.itemToString;
return selectedItem ? itemToStringLocal(selectedItem) + " has been selected." : '';
}
/**
* Debounced call for updating the a11y message.
*/
var updateA11yStatus = debounce(function (getA11yMessage, document) {
setStatus(getA11yMessage(), document);
}, 200); // istanbul ignore next
var useIsomorphicLayoutEffect = typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined' ? external_React_["useLayoutEffect"] : external_React_["useEffect"];
function useElementIds(_ref) {
var _ref$id = _ref.id,
id = _ref$id === void 0 ? "downshift-" + downshift_esm_generateId() : _ref$id,
labelId = _ref.labelId,
menuId = _ref.menuId,
getItemId = _ref.getItemId,
toggleButtonId = _ref.toggleButtonId,
inputId = _ref.inputId;
var elementIdsRef = Object(external_React_["useRef"])({
labelId: labelId || id + "-label",
menuId: menuId || id + "-menu",
getItemId: getItemId || function (index) {
return id + "-item-" + index;
},
toggleButtonId: toggleButtonId || id + "-toggle-button",
inputId: inputId || id + "-input"
});
return elementIdsRef.current;
}
function getItemIndex(index, item, items) {
if (index !== undefined) {
return index;
}
if (items.length === 0) {
return -1;
}
return items.indexOf(item);
}
function downshift_esm_itemToString(item) {
return item ? String(item) : '';
}
function isAcceptedCharacterKey(key) {
return /^\S{1}$/.test(key);
}
function capitalizeString(string) {
return "" + string.slice(0, 1).toUpperCase() + string.slice(1);
}
function useLatestRef(val) {
var ref = Object(external_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;
}
/**
* Computes the controlled state using a the previous state, props,
* two reducers, one from downshift and an optional one from the user.
* Also calls the onChange handlers for state values that have changed.
*
* @param {Function} reducer Reducer function from downshift.
* @param {Object} initialState Initial state of the hook.
* @param {Object} props The hook props.
* @returns {Array} An array with the state and an action dispatcher.
*/
function useEnhancedReducer(reducer, initialState, props) {
var prevStateRef = Object(external_React_["useRef"])();
var actionRef = Object(external_React_["useRef"])();
var enhancedReducer = Object(external_React_["useCallback"])(function (state, action) {
actionRef.current = action;
state = getState(state, action.props);
var changes = reducer(state, action);
var newState = action.props.stateReducer(state, Object(esm_extends["a" /* default */])({}, action, {
changes: changes
}));
return newState;
}, [reducer]);
var _useReducer = Object(external_React_["useReducer"])(enhancedReducer, initialState),
state = _useReducer[0],
dispatch = _useReducer[1];
var propsRef = useLatestRef(props);
var dispatchWithProps = Object(external_React_["useCallback"])(function (action) {
return dispatch(Object(esm_extends["a" /* default */])({
props: propsRef.current
}, action));
}, [propsRef]);
var action = actionRef.current;
Object(external_React_["useEffect"])(function () {
if (action && prevStateRef.current && prevStateRef.current !== state) {
callOnChangeProps(action, getState(prevStateRef.current, action.props), state);
}
prevStateRef.current = state;
}, [state, props, action]);
return [state, dispatchWithProps];
}
/**
* Wraps the useEnhancedReducer and applies the controlled prop values before
* returning the new state.
*
* @param {Function} reducer Reducer function from downshift.
* @param {Object} initialState Initial state of the hook.
* @param {Object} props The hook props.
* @returns {Array} An array with the state and an action dispatcher.
*/
function useControlledReducer(reducer, initialState, props) {
var _useEnhancedReducer = useEnhancedReducer(reducer, initialState, props),
state = _useEnhancedReducer[0],
dispatch = _useEnhancedReducer[1];
return [getState(state, props), dispatch];
}
var downshift_esm_defaultProps = {
itemToString: downshift_esm_itemToString,
stateReducer: downshift_esm_stateReducer,
getA11ySelectionMessage: downshift_esm_getA11ySelectionMessage,
scrollIntoView: downshift_esm_scrollIntoView,
circularNavigation: false,
environment: typeof window === 'undefined'
/* istanbul ignore next (ssr) */
? {} : window
};
function getDefaultValue(props, propKey, defaultStateValues) {
if (defaultStateValues === void 0) {
defaultStateValues = dropdownDefaultStateValues;
}
var defaultPropKey = "default" + capitalizeString(propKey);
if (defaultPropKey in props) {
return props[defaultPropKey];
}
return defaultStateValues[propKey];
}
function getInitialValue(props, propKey, defaultStateValues) {
if (defaultStateValues === void 0) {
defaultStateValues = dropdownDefaultStateValues;
}
if (propKey in props) {
return props[propKey];
}
var initialPropKey = "initial" + capitalizeString(propKey);
if (initialPropKey in props) {
return props[initialPropKey];
}
return getDefaultValue(props, propKey, defaultStateValues);
}
function downshift_esm_getInitialState(props) {
var selectedItem = getInitialValue(props, 'selectedItem');
var isOpen = getInitialValue(props, 'isOpen');
var highlightedIndex = getInitialValue(props, 'highlightedIndex');
var inputValue = getInitialValue(props, 'inputValue');
return {
highlightedIndex: highlightedIndex < 0 && selectedItem && isOpen ? props.items.indexOf(selectedItem) : highlightedIndex,
isOpen: isOpen,
selectedItem: selectedItem,
inputValue: inputValue
};
}
function getHighlightedIndexOnOpen(props, state, offset, getItemNodeFromIndex) {
var items = props.items,
initialHighlightedIndex = props.initialHighlightedIndex,
defaultHighlightedIndex = props.defaultHighlightedIndex;
var selectedItem = state.selectedItem,
highlightedIndex = state.highlightedIndex;
if (items.length === 0) {
return -1;
} // initialHighlightedIndex will give value to highlightedIndex on initial state only.
if (initialHighlightedIndex !== undefined && highlightedIndex === initialHighlightedIndex) {
return initialHighlightedIndex;
}
if (defaultHighlightedIndex !== undefined) {
return defaultHighlightedIndex;
}
if (selectedItem) {
if (offset === 0) {
return items.indexOf(selectedItem);
}
return getNextWrappingIndex(offset, items.indexOf(selectedItem), items.length, getItemNodeFromIndex, false);
}
if (offset === 0) {
return -1;
}
return offset < 0 ? items.length - 1 : 0;
}
/**
* Reuse the movement tracking of mouse and touch events.
*
* @param {boolean} isOpen Whether the dropdown is open or not.
* @param {Array