@elastic/eui
Version:
Elastic UI Component Library
403 lines (401 loc) • 23.5 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.EuiComboBoxInput = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _classnames = _interopRequireDefault(require("classnames"));
var _services = require("../../../services");
var _accessibility = require("../../accessibility");
var _form_control_layout = require("../../form/form_control_layout");
var _utils = require("../utils");
var _combo_box_pill = require("./combo_box_pill");
var _combo_box_input = require("./combo_box_input.styles");
var _react2 = require("@emotion/react");
var _excluded = ["key", "label", "color", "onClick", "append", "prepend", "truncationProps", "toolTipContent", "toolTipProps"];
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], t.indexOf(o) >= 0 || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.indexOf(n) >= 0) continue; t[n] = r[n]; } return t; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
var EuiComboBoxInput = exports.EuiComboBoxInput = /*#__PURE__*/function (_Component) {
function EuiComboBoxInput() {
var _this;
_classCallCheck(this, EuiComboBoxInput);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _callSuper(this, EuiComboBoxInput, [].concat(args));
_defineProperty(_this, "state", {
inputWidth: 2,
hasFocus: false
});
_defineProperty(_this, "widthUtils", void 0);
_defineProperty(_this, "inputRefCallback", function (el) {
var _this$props$inputRef, _this$props;
_this.widthUtils = new _services.CanvasTextUtils({
container: el
});
(_this$props$inputRef = (_this$props = _this.props).inputRef) === null || _this$props$inputRef === void 0 || _this$props$inputRef.call(_this$props, el);
});
_defineProperty(_this, "updateInputSize", function (inputValue) {
if (!_this.widthUtils) return;
if (_this.asPlainText) return;
_this.widthUtils.setTextToCheck(inputValue);
// Canvas has minute subpixel differences in rendering compared to DOM
// We'll buffer the input by ~2px just to ensure sufficient width
var inputWidth = Math.ceil(_this.widthUtils.textWidth) + 2;
_this.setState({
inputWidth: inputWidth
});
});
_defineProperty(_this, "onFocus", function (event) {
_this.props.onFocus(event);
_this.setState({
hasFocus: true
});
});
_defineProperty(_this, "onBlur", function (event) {
if (_this.props.onBlur) {
_this.props.onBlur(event);
}
_this.setState({
hasFocus: false
});
});
_defineProperty(_this, "onKeyDown", function (event) {
var _this$props2 = _this.props,
searchValue = _this$props2.searchValue,
hasSelectedOptions = _this$props2.hasSelectedOptions,
selectedOptions = _this$props2.selectedOptions,
onRemoveOption = _this$props2.onRemoveOption,
singleSelection = _this$props2.singleSelection,
isListOpen = _this$props2.isListOpen,
onOpenListClick = _this$props2.onOpenListClick,
onChange = _this$props2.onChange;
var searchIsEmpty = !searchValue.length;
if (event.key === _services.keys.BACKSPACE) {
// When backspacing in a plain text combobox, change normally and remove the selection
if (_this.asPlainText) {
onChange(event.currentTarget.value);
if (hasSelectedOptions) {
onRemoveOption(selectedOptions[selectedOptions.length - 1]);
}
}
// When backspacing from an empty input, delete the last pill option in the list
else if (searchIsEmpty && hasSelectedOptions) {
onRemoveOption(selectedOptions[selectedOptions.length - 1]);
if (!!singleSelection && !isListOpen) {
onOpenListClick();
}
}
}
});
_defineProperty(_this, "renderPills", function () {
// Don't render a pill for plain text comboboxes - use the input instead
if (_this.asPlainText) return null;
// Don't render the single pill selection while searching
if (_this.props.singleSelection && _this.props.searchValue) return null;
var _this$props3 = _this.props,
selectedOptions = _this$props3.selectedOptions,
isDisabled = _this$props3.isDisabled,
onRemoveOption = _this$props3.onRemoveOption;
if (!selectedOptions || !selectedOptions.length) return null;
return selectedOptions.map(function (option) {
var key = option.key,
label = option.label,
color = option.color,
onClick = option.onClick,
append = option.append,
prepend = option.prepend,
truncationProps = option.truncationProps,
toolTipContent = option.toolTipContent,
toolTipProps = option.toolTipProps,
rest = _objectWithoutProperties(option, _excluded);
var pillOnClose = isDisabled || _this.props.singleSelection || onClick ? undefined : onRemoveOption;
return (0, _react2.jsx)(_combo_box_pill.EuiComboBoxPill, _extends({
option: option,
onClose: pillOnClose,
key: key !== null && key !== void 0 ? key : label.toLowerCase(),
color: color,
onClick: onClick,
onClickAriaLabel: onClick ? 'Change' : undefined
}, rest), label);
});
});
return _this;
}
_inherits(EuiComboBoxInput, _Component);
return _createClass(EuiComboBoxInput, [{
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.searchValue !== this.props.searchValue) {
this.updateInputSize(this.props.searchValue);
}
}
}, {
key: "asPlainText",
get: function get() {
var singleSelection = this.props.singleSelection;
var isSingleSelectionConfig = singleSelection && _typeof(singleSelection) === 'object';
return !!(isSingleSelectionConfig && singleSelection.asPlainText);
}
}, {
key: "searchValue",
get: function get() {
var _this$props4 = this.props,
searchValue = _this$props4.searchValue,
selectedOptions = _this$props4.selectedOptions;
if (this.asPlainText) {
var _selectedOptions$;
return searchValue || (selectedOptions === null || selectedOptions === void 0 || (_selectedOptions$ = selectedOptions[0]) === null || _selectedOptions$ === void 0 ? void 0 : _selectedOptions$.label) || '';
} else {
return searchValue;
}
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var _this$props5 = this.props,
compressed = _this$props5.compressed,
focusedOptionId = _this$props5.focusedOptionId,
fullWidth = _this$props5.fullWidth,
hasSelectedOptions = _this$props5.hasSelectedOptions,
id = _this$props5.id,
isDisabled = _this$props5.isDisabled,
isListOpen = _this$props5.isListOpen,
noIcon = _this$props5.noIcon,
_onChange = _this$props5.onChange,
onClear = _this$props5.onClear,
onClick = _this$props5.onClick,
onFocus = _this$props5.onFocus,
onCloseListClick = _this$props5.onCloseListClick,
onOpenListClick = _this$props5.onOpenListClick,
placeholder = _this$props5.placeholder,
rootId = _this$props5.rootId,
searchValue = _this$props5.searchValue,
selectedOptions = _this$props5.selectedOptions,
singleSelection = _this$props5.singleSelection,
value = _this$props5.value,
prepend = _this$props5.prepend,
append = _this$props5.append,
isLoading = _this$props5.isLoading,
isInvalid = _this$props5.isInvalid,
autoFocus = _this$props5.autoFocus,
ariaLabel = _this$props5['aria-label'],
ariaLabelledby = _this$props5['aria-labelledby'],
ariaDescribedby = _this$props5['aria-describedby'];
var removeOptionMessage;
var removeOptionMessageId;
if (this.state.hasFocus) {
var readPlaceholder = placeholder ? "".concat(placeholder, ".") : '';
var removeOptionMessageContent = "Combo box. Selected. ".concat(searchValue ? "".concat(searchValue, ". Selected. ") : '').concat(selectedOptions && selectedOptions.length > 0 ? "".concat(value, ". Press Backspace to delete ").concat(selectedOptions[selectedOptions.length - 1].label, ". ") : '', "Combo box input. ").concat(readPlaceholder, " Type some text or, to display a list of choices, press Down Arrow. ") + 'To exit the list of choices, press Escape.';
removeOptionMessageId = rootId('removeOptionMessage');
// aria-live="assertive" will read this message aloud immediately once it enters the DOM.
// We'll render to the DOM when the input gains focus and remove it when the input loses focus.
// We'll use aria-hidden to prevent default aria information from being read by the screen
// reader.
removeOptionMessage = (0, _react2.jsx)(_accessibility.EuiScreenReaderOnly, null, (0, _react2.jsx)("span", {
"aria-live": "polite",
id: removeOptionMessageId
}, removeOptionMessageContent));
}
var isInGroup = singleSelection && (prepend || append);
var showPlaceholder = placeholder && !(selectedOptions !== null && selectedOptions !== void 0 && selectedOptions.length) && !searchValue;
var clickProps = {};
if (!isDisabled && onClear && hasSelectedOptions) {
clickProps.clear = {
'data-test-subj': 'comboBoxClearButton',
onClick: onClear
};
}
var icon;
if (!noIcon && !isDisabled) {
icon = {
'aria-label': isListOpen ? 'Close list of options' : 'Open list of options',
'data-test-subj': 'comboBoxToggleListButton',
disabled: isDisabled,
onClick: isListOpen && !isDisabled ? onCloseListClick : onOpenListClick,
side: 'right',
tabIndex: -1,
type: 'chevronSingleDown'
};
}
var wrapClasses = (0, _classnames.default)('euiComboBox__inputWrap', {
'euiComboBox__inputWrap--plainText': this.asPlainText
});
return (0, _react2.jsx)(_services.RenderWithEuiStylesMemoizer, null, function (stylesMemoizer) {
var styles = stylesMemoizer(_combo_box_input.euiComboBoxInputStyles);
var stateCss = isListOpen ? styles.open : isInvalid ? styles.invalid : undefined;
var cssStyles = [styles.euiComboBoxInputWrapper, !singleSelection && styles.multiSelect, compressed ? styles.compressed : styles.uncompressed].concat(_toConsumableArray(_this2.asPlainText || showPlaceholder ? [styles.plainText.plainText, compressed ? styles.plainText.compressed : styles.plainText.uncompressed] : []), [isDisabled ? styles.disabled : stateCss, isInGroup && styles.inGroup]);
var formLayoutStyles = [styles.formLayout.euiComboBox__formControlLayout, !singleSelection && styles.formLayout.multiSelect];
return (0, _react2.jsx)(_form_control_layout.EuiFormControlLayout, _extends({
icon: icon
}, clickProps, {
inputId: id,
isLoading: isLoading,
isInvalid: isInvalid,
isDisabled: isDisabled,
compressed: compressed,
fullWidth: fullWidth,
prepend: prepend,
append: append,
css: formLayoutStyles
}), (0, _react2.jsx)("div", {
css: cssStyles,
className: wrapClasses,
"data-test-subj": "comboBoxInput",
onClick: onClick,
tabIndex: -1 // becomes onBlur event's relatedTarget, otherwise relatedTarget is null when clicking on this div
}, _this2.renderPills(), (0, _react2.jsx)(_utils.EuiComboBoxOptionAppendPrepend, {
option: _this2.asPlainText ? selectedOptions === null || selectedOptions === void 0 ? void 0 : selectedOptions[0] : undefined,
classNamePrefix: "euiComboBoxPlainTextSelection",
marginSize: "xxs"
}, (0, _react2.jsx)("input", {
"aria-activedescendant": focusedOptionId,
"aria-autocomplete": "list",
"aria-controls": isListOpen ? rootId('listbox') : '',
"aria-expanded": isListOpen,
"aria-label": ariaLabel,
"aria-labelledby": ariaLabelledby,
"aria-describedby": ariaDescribedby,
"aria-invalid": isInvalid,
"aria-haspopup": "listbox",
css: styles.euiComboBoxInput,
className: "euiComboBox__input",
"data-test-subj": "comboBoxSearchInput",
disabled: isDisabled,
id: id,
onBlur: _this2.onBlur,
onChange: function onChange(event) {
return _onChange(event.target.value);
},
onFocus: _this2.onFocus,
onKeyDown: _this2.onKeyDown,
ref: _this2.inputRefCallback,
role: "combobox",
style: {
inlineSize: _this2.asPlainText || showPlaceholder ? '100%' : _this2.state.inputWidth
},
placeholder: showPlaceholder ? placeholder : undefined,
value: _this2.searchValue,
autoFocus: autoFocus,
autoComplete: "off"
// Force the menu to re-open on every input click - only necessary when plain text
,
onClick: _this2.asPlainText ? onFocus : undefined // Type shenanigans - event should be mostly the same
})), removeOptionMessage));
});
}
}]);
}(_react.Component);
EuiComboBoxInput.propTypes = {
compressed: _propTypes.default.bool.isRequired,
focusedOptionId: _propTypes.default.string,
fullWidth: _propTypes.default.bool,
hasSelectedOptions: _propTypes.default.bool.isRequired,
id: _propTypes.default.string,
inputRef: _propTypes.default.any,
isDisabled: _propTypes.default.bool,
isListOpen: _propTypes.default.bool.isRequired,
noIcon: _propTypes.default.bool.isRequired,
onBlur: _propTypes.default.any,
onChange: _propTypes.default.func.isRequired,
onClear: _propTypes.default.func,
onClick: _propTypes.default.func.isRequired,
onCloseListClick: _propTypes.default.func.isRequired,
onFocus: _propTypes.default.any.isRequired,
onOpenListClick: _propTypes.default.func.isRequired,
onRemoveOption: _propTypes.default.func.isRequired,
placeholder: _propTypes.default.string,
rootId: _propTypes.default.any.isRequired,
searchValue: _propTypes.default.string.isRequired,
selectedOptions: _propTypes.default.arrayOf(_propTypes.default.shape({
isGroupLabelOption: _propTypes.default.bool,
label: _propTypes.default.string.isRequired,
key: _propTypes.default.string,
options: _propTypes.default.arrayOf(_propTypes.default.shape({
isGroupLabelOption: _propTypes.default.bool,
label: _propTypes.default.string.isRequired,
key: _propTypes.default.string,
options: _propTypes.default.arrayOf(_propTypes.default.any.isRequired),
value: _propTypes.default.any,
prepend: _propTypes.default.node,
append: _propTypes.default.node,
truncationProps: _propTypes.default.any,
/**
* Optional custom tooltip content for the button
*/
toolTipContent: _propTypes.default.node,
/**
* Optional props to pass to the underlying **[EuiToolTip](/#/display/tooltip)**
*/
toolTipProps: _propTypes.default.any,
className: _propTypes.default.string,
"aria-label": _propTypes.default.string,
"data-test-subj": _propTypes.default.string,
css: _propTypes.default.any
}).isRequired),
value: _propTypes.default.any,
prepend: _propTypes.default.node,
append: _propTypes.default.node,
truncationProps: _propTypes.default.any,
/**
* Optional custom tooltip content for the button
*/
toolTipContent: _propTypes.default.node,
/**
* Optional props to pass to the underlying **[EuiToolTip](/#/display/tooltip)**
*/
toolTipProps: _propTypes.default.any,
className: _propTypes.default.string,
"aria-label": _propTypes.default.string,
"data-test-subj": _propTypes.default.string,
css: _propTypes.default.any
}).isRequired).isRequired,
singleSelection: _propTypes.default.oneOfType([_propTypes.default.bool.isRequired, _propTypes.default.shape({
asPlainText: _propTypes.default.bool
}).isRequired]),
toggleButtonRef: _propTypes.default.any,
value: _propTypes.default.string,
prepend: _propTypes.default.oneOfType([_propTypes.default.oneOfType([_propTypes.default.string.isRequired, _propTypes.default.element.isRequired]).isRequired, _propTypes.default.arrayOf(_propTypes.default.oneOfType([_propTypes.default.string.isRequired, _propTypes.default.element.isRequired]).isRequired).isRequired]),
append: _propTypes.default.oneOfType([_propTypes.default.oneOfType([_propTypes.default.string.isRequired, _propTypes.default.element.isRequired]).isRequired, _propTypes.default.arrayOf(_propTypes.default.oneOfType([_propTypes.default.string.isRequired, _propTypes.default.element.isRequired]).isRequired).isRequired]),
isLoading: _propTypes.default.bool,
isInvalid: _propTypes.default.bool,
autoFocus: _propTypes.default.bool,
"aria-label": _propTypes.default.string,
"aria-labelledby": _propTypes.default.string,
"aria-describedby": _propTypes.default.string,
className: _propTypes.default.string,
"data-test-subj": _propTypes.default.string,
css: _propTypes.default.any
};