@elastic/eui
Version:
Elastic UI Component Library
372 lines (371 loc) • 22.6 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.EuiSuperSelect = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _classnames = _interopRequireDefault(require("classnames"));
var _accessibility = require("../../accessibility");
var _services = require("../../../services");
var _super_select_control = require("./super_select_control");
var _popover = require("../../popover");
var _context_menu = require("../../context_menu");
var _i18n = require("../../i18n");
var _react2 = require("@emotion/react");
var _excluded = ["className", "options", "valueOfSelected", "placeholder", "onChange", "isOpen", "isInvalid", "hasDividers", "itemClassName", "itemLayoutAlign", "fullWidth", "popoverProps", "compressed"],
_excluded2 = ["value", "dropdownDisplay", "inputDisplay"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } /*
* 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 ShiftDirection = /*#__PURE__*/function (ShiftDirection) {
ShiftDirection["BACK"] = "back";
ShiftDirection["FORWARD"] = "forward";
return ShiftDirection;
}(ShiftDirection || {});
var EuiSuperSelect = /*#__PURE__*/function (_Component) {
_inherits(EuiSuperSelect, _Component);
var _super = _createSuper(EuiSuperSelect);
function EuiSuperSelect() {
var _this;
_classCallCheck(this, EuiSuperSelect);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_defineProperty(_assertThisInitialized(_this), "itemNodes", []);
_defineProperty(_assertThisInitialized(_this), "_isMounted", false);
_defineProperty(_assertThisInitialized(_this), "describedById", (0, _services.htmlIdGenerator)('euiSuperSelect_')('_screenreaderDescribeId'));
_defineProperty(_assertThisInitialized(_this), "state", {
isPopoverOpen: _this.props.isOpen || false
});
_defineProperty(_assertThisInitialized(_this), "setItemNode", function (node, index) {
_this.itemNodes[index] = node;
});
_defineProperty(_assertThisInitialized(_this), "openPopover", function () {
_this.setState({
isPopoverOpen: true
});
var focusSelected = function focusSelected() {
var indexOfSelected = _this.props.options.reduce(function (indexOfSelected, option, index) {
if (indexOfSelected != null) return indexOfSelected;
if (option == null) return null;
return option.value === _this.props.valueOfSelected ? index : null;
}, null);
requestAnimationFrame(function () {
if (!_this._isMounted) {
return;
}
if (_this.props.valueOfSelected != null) {
if (indexOfSelected != null) {
_this.focusItemAt(indexOfSelected);
} else {
focusSelected();
}
} else {
var firstFocusableOption = _this.props.options.findIndex(function (_ref) {
var disabled = _ref.disabled;
return disabled !== true;
});
_this.focusItemAt(firstFocusableOption);
}
if (_this.props.onFocus) {
_this.props.onFocus();
}
});
};
requestAnimationFrame(focusSelected);
});
_defineProperty(_assertThisInitialized(_this), "closePopover", function () {
_this.setState({
isPopoverOpen: false
});
if (_this.props.onBlur) {
_this.props.onBlur();
}
});
_defineProperty(_assertThisInitialized(_this), "itemClicked", function (value) {
_this.closePopover();
if (_this.props.onChange) {
_this.props.onChange(value);
}
});
_defineProperty(_assertThisInitialized(_this), "onSelectKeyDown", function (event) {
if (event.key === _services.keys.ARROW_UP || event.key === _services.keys.ARROW_DOWN) {
event.preventDefault();
event.stopPropagation();
_this.openPopover();
}
});
_defineProperty(_assertThisInitialized(_this), "onItemKeyDown", function (event) {
switch (event.key) {
case _services.keys.ESCAPE:
// close the popover and prevent ancestors from handling
event.preventDefault();
event.stopPropagation();
_this.closePopover();
break;
case _services.keys.TAB:
// no-op
event.preventDefault();
event.stopPropagation();
break;
case _services.keys.ARROW_UP:
event.preventDefault();
event.stopPropagation();
_this.shiftFocus(ShiftDirection.BACK);
break;
case _services.keys.ARROW_DOWN:
event.preventDefault();
event.stopPropagation();
_this.shiftFocus(ShiftDirection.FORWARD);
break;
}
});
return _this;
}
_createClass(EuiSuperSelect, [{
key: "componentDidMount",
value: function componentDidMount() {
this._isMounted = true;
if (this.props.isOpen) {
this.openPopover();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this._isMounted = false;
}
}, {
key: "focusItemAt",
value: function focusItemAt(index) {
var targetElement = this.itemNodes[index];
if (targetElement != null) {
targetElement.focus();
}
}
}, {
key: "shiftFocus",
value: function shiftFocus(direction) {
var currentIndex = this.itemNodes.indexOf(document.activeElement);
var targetElementIndex;
if (currentIndex === -1) {
// somehow the select options has lost focus
targetElementIndex = 0;
} else {
if (direction === ShiftDirection.BACK) {
targetElementIndex = currentIndex === 0 ? this.itemNodes.length - 1 : currentIndex - 1;
} else {
targetElementIndex = currentIndex === this.itemNodes.length - 1 ? 0 : currentIndex + 1;
}
}
this.focusItemAt(targetElementIndex);
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var _this$props = this.props,
className = _this$props.className,
options = _this$props.options,
valueOfSelected = _this$props.valueOfSelected,
placeholder = _this$props.placeholder,
onChange = _this$props.onChange,
isOpen = _this$props.isOpen,
isInvalid = _this$props.isInvalid,
hasDividers = _this$props.hasDividers,
itemClassName = _this$props.itemClassName,
itemLayoutAlign = _this$props.itemLayoutAlign,
fullWidth = _this$props.fullWidth,
popoverProps = _this$props.popoverProps,
compressed = _this$props.compressed,
rest = _objectWithoutProperties(_this$props, _excluded);
var popoverClasses = (0, _classnames.default)('euiSuperSelect', popoverProps === null || popoverProps === void 0 ? void 0 : popoverProps.className);
var buttonClasses = (0, _classnames.default)({
'euiSuperSelect--isOpen__button': this.state.isPopoverOpen
}, className);
var itemClasses = (0, _classnames.default)('euiSuperSelect__item', {
'euiSuperSelect__item--hasDividers': hasDividers
}, itemClassName);
var button = (0, _react2.jsx)(_super_select_control.EuiSuperSelectControl, _extends({
options: options,
value: valueOfSelected,
placeholder: placeholder,
onClick: this.state.isPopoverOpen ? this.closePopover : this.openPopover,
onKeyDown: this.onSelectKeyDown,
className: buttonClasses,
fullWidth: fullWidth,
isInvalid: isInvalid,
compressed: compressed
}, rest));
var items = options.map(function (option, index) {
var value = option.value,
dropdownDisplay = option.dropdownDisplay,
inputDisplay = option.inputDisplay,
optionRest = _objectWithoutProperties(option, _excluded2);
return (0, _react2.jsx)(_context_menu.EuiContextMenuItem, _extends({
key: index,
className: itemClasses,
icon: valueOfSelected === value ? 'check' : 'empty',
onClick: function onClick() {
return _this2.itemClicked(value);
},
onKeyDown: _this2.onItemKeyDown,
layoutAlign: itemLayoutAlign,
buttonRef: function buttonRef(node) {
return _this2.setItemNode(node, index);
},
role: "option",
id: value,
"aria-selected": valueOfSelected === value
}, optionRest), dropdownDisplay || inputDisplay);
});
return (0, _react2.jsx)(_popover.EuiInputPopover, _extends({
closePopover: this.closePopover,
panelPaddingSize: "none"
}, popoverProps, {
className: popoverClasses,
isOpen: isOpen || this.state.isPopoverOpen,
input: button,
fullWidth: fullWidth
}), (0, _react2.jsx)(_accessibility.EuiScreenReaderOnly, null, (0, _react2.jsx)("p", {
id: this.describedById
}, (0, _react2.jsx)(_i18n.EuiI18n, {
token: "euiSuperSelect.screenReaderAnnouncement",
default: "You are in a form selector and must select a single option. Use the Up and Down arrow keys to navigate or Escape to close."
}))), (0, _react2.jsx)(_i18n.EuiI18n, {
token: "euiSuperSelect.ariaLabel",
default: "Select listbox"
}, function (ariaLabel) {
return (0, _react2.jsx)("div", {
"aria-label": ariaLabel,
"aria-describedby": _this2.describedById,
className: "euiSuperSelect__listbox",
role: "listbox",
"aria-activedescendant": valueOfSelected,
tabIndex: 0
}, items);
}));
}
}]);
return EuiSuperSelect;
}(_react.Component);
exports.EuiSuperSelect = EuiSuperSelect;
_defineProperty(EuiSuperSelect, "defaultProps", {
hasDividers: false,
fullWidth: false,
compressed: false,
isInvalid: false,
isLoading: false
});
EuiSuperSelect.propTypes = {
className: _propTypes.default.string,
"aria-label": _propTypes.default.string,
"data-test-subj": _propTypes.default.string,
css: _propTypes.default.any,
/**
* @default false
*/
compressed: _propTypes.default.bool,
/**
* Expand to fill 100% of the parent.
* Defaults to `fullWidth` prop of `<EuiForm>`.
* @default false
*/
fullWidth: _propTypes.default.bool,
/**
* @default false
*/
isInvalid: _propTypes.default.bool,
/**
* @default false
*/
isLoading: _propTypes.default.bool,
readOnly: _propTypes.default.bool,
name: _propTypes.default.string,
/**
* Placeholder to display when the current selected value is empty.
*/
placeholder: _propTypes.default.oneOfType([_propTypes.default.node, _propTypes.default.node]),
/**
* Creates an input group with element(s) coming before input.
* `string` | `ReactElement` or an array of these
*/
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]),
/**
* Creates an input group with element(s) coming after input.
* `string` | `ReactElement` or an array of these
*/
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]),
/**
* Pass an array of options that must at least include:
* `value`: storing unique value of item,
* `inputDisplay`: what shows inside the form input when selected
* `dropdownDisplay` (optional): what shows for the item in the dropdown
*/
options: _propTypes.default.arrayOf(_propTypes.default.shape({
value: _propTypes.default.any.isRequired,
inputDisplay: _propTypes.default.node,
dropdownDisplay: _propTypes.default.node,
disabled: _propTypes.default.bool,
"data-test-subj": _propTypes.default.string
}).isRequired).isRequired,
valueOfSelected: _propTypes.default.any,
/**
* Classes for the context menu item
*/
itemClassName: _propTypes.default.string,
/**
* You must pass an `onChange` function to handle the update of the value
*/
onChange: _propTypes.default.func,
onFocus: _propTypes.default.func,
onBlur: _propTypes.default.func,
/**
* Change to `true` if you want horizontal lines between options.
* This is best used when options are multi-line.
*/
hasDividers: _propTypes.default.bool,
/**
* Change `EuiContextMenuItem` layout position of icon
*/
itemLayoutAlign: _propTypes.default.oneOf(["center", "top", "bottom"]),
/**
* Controls whether the options are shown. Default: false
*/
isOpen: _propTypes.default.bool,
/**
* Optional props to pass to the underlying [EuiPopover](/#/layout/popover).
* Allows fine-grained control of the popover dropdown menu, including
* `repositionOnScroll` for EuiSuperSelects used within scrollable containers,
* and customizing popover panel styling.
*
* Does not accept a nested `popoverProps.isOpen` property - use the top level
* `isOpen` API instead.
*/
popoverProps: _propTypes.default.any
};