UNPKG

@elastic/eui

Version:

Elastic UI Component Library

350 lines (348 loc) 25.1 kB
var _excluded = ["children", "className", "disabled", "checked", "isFocused", "showIcons", "prepend", "append", "allowExclusions", "onFocusBadge", "paddingSize", "role", "searchable", "textWrap"], _excluded2 = ["children", "className"]; 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. */ import classNames from 'classnames'; import PropTypes from "prop-types"; import React, { Component } from 'react'; import { keysOf } from '../../common'; import { EuiI18n } from '../../i18n'; import { EuiIcon } from '../../icon'; import { EuiScreenReaderOnly } from '../../accessibility'; import { EuiBadge } from '../../badge'; import { jsx as ___EmotionJSX } from "@emotion/react"; function resolveIconAndColor(checked) { switch (checked) { case 'on': return { icon: 'check', color: 'text' }; case 'off': return { icon: 'cross', color: 'text' }; case 'mixed': return { icon: 'minus', color: 'text' }; case undefined: default: return { icon: 'empty' }; } } var paddingSizeToClassNameMap = { none: null, s: 'euiSelectableListItem--paddingSmall' }; export var PADDING_SIZES = keysOf(paddingSizeToClassNameMap); export var EuiSelectableListItem = /*#__PURE__*/function (_Component) { _inherits(EuiSelectableListItem, _Component); var _super = _createSuper(EuiSelectableListItem); function EuiSelectableListItem(props) { var _this; _classCallCheck(this, EuiSelectableListItem); _this = _super.call(this, props); // aria-checked is intended to be used with role="checkbox" but // the MDN documentation lists it as a possibility for role="option". // See https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked // and https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/option_role _defineProperty(_assertThisInitialized(_this), "isChecked", function (role, checked) { var rolesThatCanBeMixed = ['option', 'checkbox', 'menuitemcheckbox']; var rolesThatCanBeChecked = [].concat(rolesThatCanBeMixed, ['radio', 'menuitemradio', 'switch']); if (!rolesThatCanBeChecked.includes(role)) return undefined; switch (checked) { case 'on': case 'off': return true; case 'mixed': if (rolesThatCanBeMixed.includes(role)) { return 'mixed'; } else { return false; } default: return false; } }); return _this; } _createClass(EuiSelectableListItem, [{ key: "render", value: function render() { var _this$props = this.props, children = _this$props.children, className = _this$props.className, disabled = _this$props.disabled, checked = _this$props.checked, isFocused = _this$props.isFocused, showIcons = _this$props.showIcons, prepend = _this$props.prepend, append = _this$props.append, allowExclusions = _this$props.allowExclusions, onFocusBadge = _this$props.onFocusBadge, _this$props$paddingSi = _this$props.paddingSize, paddingSize = _this$props$paddingSi === void 0 ? 's' : _this$props$paddingSi, _this$props$role = _this$props.role, role = _this$props$role === void 0 ? 'option' : _this$props$role, searchable = _this$props.searchable, textWrap = _this$props.textWrap, rest = _objectWithoutProperties(_this$props, _excluded); var classes = classNames('euiSelectableListItem', { 'euiSelectableListItem-isFocused': isFocused }, paddingSizeToClassNameMap[paddingSize], className); var textClasses = classNames('euiSelectableListItem__text', _defineProperty({}, "euiSelectableListItem__text--".concat(textWrap), textWrap)); var optionIcon; if (showIcons) { var _resolveIconAndColor = resolveIconAndColor(checked), icon = _resolveIconAndColor.icon, color = _resolveIconAndColor.color; optionIcon = ___EmotionJSX(EuiIcon, { className: "euiSelectableListItem__icon", color: color, type: icon }); } var state; var instructions; var screenReaderStrings = { checked: { state: ___EmotionJSX(EuiI18n, { token: "euiSelectableListItem.checkedOption", default: "Checked option." }), instructions: ___EmotionJSX(EuiI18n, { token: "euiSelectableListItem.checkOptionInstructions", default: "To check this option, press Enter." }) }, unchecked: { instructions: ___EmotionJSX(EuiI18n, { token: "euiSelectableListItem.uncheckOptionInstructions", default: "To uncheck this option, press Enter." }) }, excluded: { state: ___EmotionJSX(EuiI18n, { token: "euiSelectableListItem.excludedOption", default: "Excluded option." }), instructions: ___EmotionJSX(EuiI18n, { token: "euiSelectableListItem.excludeOptionInstructions", default: "To exclude this option, press Enter." }) }, mixed: { state: ___EmotionJSX(EuiI18n, { token: "euiSelectableListItem.mixedOption", default: "Mixed (indeterminate) option." }), instructions: ___EmotionJSX(EuiI18n, { token: "euiSelectableListItem.mixedOptionInstructions", default: "To check this option for all, press Enter once." }), uncheckInstructions: ___EmotionJSX(EuiI18n, { token: "euiSelectableListItem.mixedOptionUncheckInstructions", default: "To uncheck this option for all, press Enter twice." }), excludeInstructions: ___EmotionJSX(EuiI18n, { token: "euiSelectableListItem.mixedOptionExcludeInstructions", default: "To exclude this option for all, press Enter twice." }) } }; switch (checked) { case 'on': state = screenReaderStrings.checked.state; instructions = allowExclusions ? screenReaderStrings.excluded.instructions : searchable ? screenReaderStrings.unchecked.instructions : undefined; break; case 'off': state = screenReaderStrings.excluded.state; instructions = screenReaderStrings.unchecked.instructions; break; case 'mixed': state = screenReaderStrings.mixed.state; instructions = ___EmotionJSX(React.Fragment, null, screenReaderStrings.mixed.instructions, ' ', allowExclusions ? screenReaderStrings.mixed.excludeInstructions : screenReaderStrings.mixed.uncheckInstructions); break; case undefined: default: instructions = allowExclusions || searchable ? screenReaderStrings.checked.instructions : undefined; break; } var prependNode; if (prepend) { prependNode = ___EmotionJSX("span", { className: "euiSelectableListItem__prepend" }, prepend); } var appendNode; if (append || !!onFocusBadge) { var onFocusBadgeNode; var defaultOnFocusBadgeProps = { 'aria-hidden': true, iconType: 'returnKey', iconSide: 'left', color: 'hollow' }; if (onFocusBadge === true) { onFocusBadgeNode = ___EmotionJSX(EuiBadge, _extends({ className: "euiSelectableListItem__onFocusBadge" }, defaultOnFocusBadgeProps)); } else if (!!onFocusBadge && onFocusBadge !== false) { var _children = onFocusBadge.children, _className = onFocusBadge.className, restBadgeProps = _objectWithoutProperties(onFocusBadge, _excluded2); onFocusBadgeNode = ___EmotionJSX(EuiBadge, _extends({ className: classNames('euiSelectableListItem__onFocusBadge', _className) }, defaultOnFocusBadgeProps, restBadgeProps), _children); } // Only display the append wrapper if append exists or isFocused if (append || isFocused && !disabled) { appendNode = ___EmotionJSX("span", { className: "euiSelectableListItem__append" }, append, " ", isFocused && !disabled ? onFocusBadgeNode : null); } } var screenReaderText = (state || instructions) && ___EmotionJSX(EuiScreenReaderOnly, null, ___EmotionJSX("div", null, state || instructions ? '. ' : null, state, state && instructions ? ' ' : null, instructions)); return ___EmotionJSX("li", _extends({ role: role, "aria-disabled": disabled, "aria-checked": this.isChecked(role, checked) // Whether the item is "checked" , "aria-selected": !disabled && isFocused // Whether the item has keyboard focus per W3 spec , className: classes }, rest), ___EmotionJSX("span", { className: "euiSelectableListItem__content" }, optionIcon, prependNode, ___EmotionJSX("span", { className: textClasses }, children, screenReaderText), appendNode)); } }]); return EuiSelectableListItem; }(Component); _defineProperty(EuiSelectableListItem, "defaultProps", { showIcons: true, onFocusBadge: true, textWrap: 'truncate' }); EuiSelectableListItem.propTypes = { className: PropTypes.string, "aria-label": PropTypes.string, "data-test-subj": PropTypes.string, css: PropTypes.any, children: PropTypes.node, /** * Applies an icon and visual styling to activated items */ checked: PropTypes.oneOf(["on", "off", "mixed", undefined]), /** * Shows icons based on `checked` type */ showIcons: PropTypes.bool, /** * Highlights the item for pseudo focus */ isFocused: PropTypes.bool, disabled: PropTypes.bool, prepend: PropTypes.node, append: PropTypes.node, allowExclusions: PropTypes.bool, /** * When enabled by setting to either `true` or passing custom a custom badge, * shows a hollow badge as an append (far right) when the item is focused. * The default content when `true` is `↩ to select/deselect/include/exclude` */ onFocusBadge: PropTypes.oneOfType([PropTypes.bool.isRequired, PropTypes.shape({ /** * Accepts any string from our icon library */ iconType: PropTypes.oneOfType([PropTypes.oneOf(["accessibility", "addDataApp", "advancedSettingsApp", "agentApp", "aggregate", "analyzeEvent", "annotation", "apmApp", "apmTrace", "appSearchApp", "apps", "arrowDown", "arrowLeft", "arrowRight", "arrowUp", "arrowStart", "arrowEnd", "article", "asterisk", "at", "auditbeatApp", "beaker", "bell", "bellSlash", "beta", "bolt", "boxesHorizontal", "boxesVertical", "branch", "branchUser", "broom", "brush", "bug", "bullseye", "calendar", "canvasApp", "casesApp", "check", "checkInCircleFilled", "cheer", "classificationJob", "clock", "cloudDrizzle", "cloudStormy", "cloudSunny", "cluster", "codeApp", "color", "compute", "console", "consoleApp", "container", "continuityAbove", "continuityAboveBelow", "continuityBelow", "continuityWithin", "controlsHorizontal", "controlsVertical", "copy", "copyClipboard", "createAdvancedJob", "createMultiMetricJob", "createPopulationJob", "createSingleMetricJob", "cross", "crossClusterReplicationApp", "crosshairs", "currency", "cut", "dashboardApp", "dataVisualizer", "database", "desktop", "devToolsApp", "discoverApp", "discuss", "document", "documentEdit", "documentation", "documents", "dot", "dotInCircle", "doubleArrowLeft", "doubleArrowRight", "download", "editorAlignCenter", "editorAlignLeft", "editorAlignRight", "editorBold", "editorChecklist", "editorCodeBlock", "editorComment", "editorDistributeHorizontal", "editorDistributeVertical", "editorHeading", "editorItalic", "editorItemAlignBottom", "editorItemAlignCenter", "editorItemAlignLeft", "editorItemAlignMiddle", "editorItemAlignRight", "editorItemAlignTop", "editorLink", "editorOrderedList", "editorPositionBottomLeft", "editorPositionBottomRight", "editorPositionTopLeft", "editorPositionTopRight", "editorRedo", "editorStrike", "editorTable", "editorUnderline", "editorUndo", "editorUnorderedList", "email", "empty", "emsApp", "eql", "eraser", "error", "exit", "expand", "expandMini", "exportAction", "eye", "eyeClosed", "faceHappy", "faceNeutral", "faceSad", "filebeatApp", "filter", "filterExclude", "filterIgnore", "filterInclude", "filterInCircle", "flag", "fleetApp", "fold", "folderCheck", "folderClosed", "folderExclamation", "folderOpen", "frameNext", "framePrevious", "fullScreen", "fullScreenExit", "function", "gear", "gisApp", "glasses", "globe", "grab", "grabHorizontal", "graphApp", "grid", "grokApp", "heart", "heartbeatApp", "heatmap", "help", "home", "iInCircle", "image", "importAction", "indexClose", "indexEdit", "indexFlush", "indexManagementApp", "indexMapping", "indexOpen", "indexPatternApp", "indexRollupApp", "indexRuntime", "indexSettings", "indexTemporary", "infinity", "inputOutput", "inspect", "invert", "ip", "key", "keyboard", "kqlField", "kqlFunction", "kqlOperand", "kqlSelector", "kqlValue", "kubernetesNode", "kubernetesPod", "launch", "layers", "lensApp", "lettering", "lineDashed", "lineDotted", "lineSolid", "link", "list", "listAdd", "lock", "lockOpen", "logoAWS", "logoAWSMono", "logoAerospike", "logoApache", "logoAppSearch", "logoAzure", "logoAzureMono", "logoBeats", "logoBusinessAnalytics", "logoCeph", "logoCloud", "logoCloudEnterprise", "logoCode", "logoCodesandbox", "logoCouchbase", "logoDocker", "logoDropwizard", "logoElastic", "logoElasticStack", "logoElasticsearch", "logoEnterpriseSearch", "logoEtcd", "logoGCP", "logoGCPMono", "logoGithub", "logoGmail", "logoGolang", "logoGoogleG", "logoHAproxy", "logoIBM", "logoIBMMono", "logoKafka", "logoKibana", "logoKubernetes", "logoLogging", "logoLogstash", "logoMaps", "logoMemcached", "logoMetrics", "logoMongodb", "logoMySQL", "logoNginx", "logoObservability", "logoOsquery", "logoPhp", "logoPostgres", "logoPrometheus", "logoRabbitmq", "logoRedis", "logoSecurity", "logoSiteSearch", "logoSketch", "logoSlack", "logoUptime", "logoVulnerabilityManagement", "logoWebhook", "logoWindows", "logoWorkplaceSearch", "logsApp", "logstashFilter", "logstashIf", "logstashInput", "logstashOutput", "logstashQueue", "machineLearningApp", "magnet", "magnifyWithExclamation", "magnifyWithMinus", "magnifyWithPlus", "managementApp", "mapMarker", "memory", "menu", "menuDown", "menuLeft", "menuRight", "menuUp", "merge", "metricbeatApp", "metricsApp", "minimize", "minus", "minusInCircle", "minusInCircleFilled", "mobile", "monitoringApp", "moon", "namespace", "nested", "node", "notebookApp", "number", "offline", "online", "outlierDetectionJob", "package", "packetbeatApp", "pageSelect", "pagesSelect", "paperClip", "partial", "pause", "payment", "pencil", "percent", "pin", "pinFilled", "pipelineApp", "pivot", "play", "playFilled", "plus", "plusInCircle", "plusInCircleFilled", "popout", "push", "questionInCircle", "quote", "recentlyViewedApp", "refresh", "regressionJob", "reporter", "reportingApp", "returnKey", "save", "savedObjectsApp", "scale", "search", "searchProfilerApp", "securityAnalyticsApp", "securityApp", "securitySignal", "securitySignalDetected", "securitySignalResolved", "sessionViewer", "shard", "share", "snowflake", "sortAscending", "sortDescending", "sortDown", "sortLeft", "sortRight", "sortUp", "sortable", "spaces", "spacesApp", "sparkles", "sqlApp", "starEmpty", "starEmptySpace", "starFilled", "starFilledSpace", "starMinusEmpty", "starMinusFilled", "starPlusEmpty", "starPlusFilled", "stats", "stop", "stopFilled", "stopSlash", "storage", "string", "submodule", "sun", "swatchInput", "symlink", "tableDensityCompact", "tableDensityExpanded", "tableDensityNormal", "tableOfContents", "tag", "tear", "temperature", "timeline", "timelineWithArrow", "timelionApp", "timeRefresh", "timeslider", "training", "trash", "unfold", "unlink", "upgradeAssistantApp", "uptimeApp", "user", "userAvatar", "users", "usersRolesApp", "vector", "videoPlayer", "visArea", "visAreaStacked", "visBarHorizontal", "visBarHorizontalStacked", "visBarVertical", "visBarVerticalStacked", "visGauge", "visGoal", "visLine", "visMapCoordinate", "visMapRegion", "visMetric", "visPie", "visTable", "visTagCloud", "visText", "visTimelion", "visVega", "visVisualBuilder", "visualizeApp", "vulnerabilityManagementApp", "warning", "alert", "watchesApp", "wordWrap", "wordWrapDisabled", "workplaceSearchApp", "wrench", "tokenAlias", "tokenAnnotation", "tokenArray", "tokenBinary", "tokenBoolean", "tokenClass", "tokenCompletionSuggester", "tokenConstant", "tokenDate", "tokenDenseVector", "tokenElement", "tokenEnum", "tokenEnumMember", "tokenEvent", "tokenException", "tokenField", "tokenFile", "tokenFlattened", "tokenFunction", "tokenGeo", "tokenHistogram", "tokenInterface", "tokenIP", "tokenJoin", "tokenKey", "tokenKeyword", "tokenMethod", "tokenMetricCounter", "tokenMetricGauge", "tokenModule", "tokenNamespace", "tokenNested", "tokenNull", "tokenNumber", "tokenObject", "tokenOperator", "tokenPackage", "tokenParameter", "tokenPercolator", "tokenProperty", "tokenRange", "tokenRankFeature", "tokenRankFeatures", "tokenRepo", "tokenSearchType", "tokenShape", "tokenString", "tokenStruct", "tokenSymbol", "tokenTag", "tokenText", "tokenTokenCount", "tokenVariable"]).isRequired, PropTypes.string.isRequired, PropTypes.elementType.isRequired]), /** * The side of the badge the icon should sit */ iconSide: PropTypes.any, /** * Accepts either our palette colors (primary, success ..etc) or a hex value `#FFFFFF`, `#000`. */ color: PropTypes.oneOfType([PropTypes.any.isRequired, PropTypes.string.isRequired]), /** * Will override any color passed through the `color` prop. */ isDisabled: PropTypes.bool, /** * Props passed to the close button. */ closeButtonProps: PropTypes.any, className: PropTypes.string, "aria-label": PropTypes.string, "data-test-subj": PropTypes.string, css: PropTypes.any, /** * Will apply an onclick to icon within the badge */ iconOnClick: PropTypes.func, /** * Aria label applied to the iconOnClick button */ iconOnClickAriaLabel: PropTypes.any, /** * Will apply an onclick to the badge itself */ onClick: PropTypes.func, /** * Aria label applied to the onClick button */ onClickAriaLabel: PropTypes.any, href: PropTypes.string, target: PropTypes.string, rel: PropTypes.string }).isRequired]), /** * Padding for the list items. */ paddingSize: PropTypes.any, /** * Whether the `EuiSelectable` instance is searchable. * When true, the Space key will not toggle selection, as it will type into the search box instead. Screen reader instructions will be added instructing users to use the Enter key to select items. * When false, the Space key will toggle item selection. No extra screen reader instructions will be added, as Space to toggle is a generally standard for most select/checked elements. */ searchable: PropTypes.bool, /** * Attribute applied the option `<li>`. * If set to a role that allows [aria-checked](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked), * `aria-checked` will be automatically configured. */ role: PropTypes.any, /** * How to handle long text within the item. * Wrapping only works if virtualization is off. */ textWrap: PropTypes.oneOf(["truncate", "wrap"]) };