UNPKG

@elastic/eui

Version:

Elastic UI Component Library

285 lines (284 loc) 23.7 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _typeof = require("@babel/runtime/helpers/typeof"); Object.defineProperty(exports, "__esModule", { value: true }); exports.EuiSelectableListItem = void 0; var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties")); var _classnames = _interopRequireDefault(require("classnames")); var _propTypes = _interopRequireDefault(require("prop-types")); var _react = _interopRequireWildcard(require("react")); var _i18n = require("../../i18n"); var _accessibility = require("../../accessibility"); var _badge = require("../../badge"); var _list_item_layout = require("../../list_item_layout/_list_item_layout"); var _react2 = require("@emotion/react"); var _excluded = ["children", "className", "disabled", "checked", "isFocused", "showIcons", "prepend", "append", "allowExclusions", "singleSelection", "onFocusBadge", "role", "searchable", "toolTipContent", "toolTipProps"], _excluded2 = ["children", "className"]; /* * 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. */ 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 ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } var EuiSelectableListItem = exports.EuiSelectableListItem = function EuiSelectableListItem(_ref) { var children = _ref.children, className = _ref.className, disabled = _ref.disabled, checked = _ref.checked, isFocused = _ref.isFocused, _ref$showIcons = _ref.showIcons, showIcons = _ref$showIcons === void 0 ? true : _ref$showIcons, prepend = _ref.prepend, append = _ref.append, allowExclusions = _ref.allowExclusions, _ref$singleSelection = _ref.singleSelection, singleSelection = _ref$singleSelection === void 0 ? true : _ref$singleSelection, _ref$onFocusBadge = _ref.onFocusBadge, onFocusBadge = _ref$onFocusBadge === void 0 ? false : _ref$onFocusBadge, _ref$role = _ref.role, role = _ref$role === void 0 ? 'option' : _ref$role, searchable = _ref.searchable, toolTipContent = _ref.toolTipContent, toolTipProps = _ref.toolTipProps, rest = (0, _objectWithoutProperties2.default)(_ref, _excluded); var classes = (0, _classnames.default)('euiSelectableListItem', { 'euiSelectableListItem-isFocused': isFocused }, className); var onFocusBadgeNode = (0, _react.useMemo)(function () { var defaultOnFocusBadgeProps = { 'aria-hidden': true, iconType: 'return', iconSide: 'left', color: 'hollow' }; if (onFocusBadge === true) { return (0, _react2.jsx)(_badge.EuiBadge, (0, _extends2.default)({ className: "euiSelectableListItem__onFocusBadge" }, defaultOnFocusBadgeProps)); } else if (typeof onFocusBadge !== 'boolean' && !!onFocusBadge) { var _children = onFocusBadge.children, _className = onFocusBadge.className, restBadgeProps = (0, _objectWithoutProperties2.default)(onFocusBadge, _excluded2); return (0, _react2.jsx)(_badge.EuiBadge, (0, _extends2.default)({ className: (0, _classnames.default)('euiSelectableListItem__onFocusBadge', _className) }, defaultOnFocusBadgeProps, restBadgeProps), _children); } }, [onFocusBadge]); var screenReaderText = (0, _react.useMemo)(function () { var state; var instructions; var screenReaderStrings = { checked: { state: (0, _react2.jsx)(_i18n.EuiI18n, { token: "euiSelectableListItem.checkedOption", default: "Checked option." }), instructions: (0, _react2.jsx)(_i18n.EuiI18n, { token: "euiSelectableListItem.checkOptionInstructions", default: "To check this option, press Enter." }) }, unchecked: { instructions: (0, _react2.jsx)(_i18n.EuiI18n, { token: "euiSelectableListItem.uncheckOptionInstructions", default: "To uncheck this option, press Enter." }) }, excluded: { state: (0, _react2.jsx)(_i18n.EuiI18n, { token: "euiSelectableListItem.excludedOption", default: "Excluded option." }), instructions: (0, _react2.jsx)(_i18n.EuiI18n, { token: "euiSelectableListItem.excludeOptionInstructions", default: "To exclude this option, press Enter." }) }, mixed: { state: (0, _react2.jsx)(_i18n.EuiI18n, { token: "euiSelectableListItem.mixedOption", default: "Mixed (indeterminate) option." }), instructions: (0, _react2.jsx)(_i18n.EuiI18n, { token: "euiSelectableListItem.mixedOptionInstructions", default: "To check this option for all, press Enter once." }), uncheckInstructions: (0, _react2.jsx)(_i18n.EuiI18n, { token: "euiSelectableListItem.mixedOptionUncheckInstructions", default: "To uncheck this option for all, press Enter twice." }), excludeInstructions: (0, _react2.jsx)(_i18n.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 = (0, _react2.jsx)(_react.default.Fragment, null, screenReaderStrings.mixed.instructions, ' ', allowExclusions ? screenReaderStrings.mixed.excludeInstructions : screenReaderStrings.mixed.uncheckInstructions); break; case undefined: default: instructions = allowExclusions || searchable ? screenReaderStrings.checked.instructions : undefined; break; } return state || instructions ? (0, _react2.jsx)(_accessibility.EuiScreenReaderOnly, null, (0, _react2.jsx)("div", null, state || instructions ? '. ' : null, state, state && instructions ? ' ' : null, instructions)) : null; }, [checked, searchable, allowExclusions]); var hasToolTip = !!toolTipContent && !disabled; var showOnFocusBadge = isFocused && !disabled && !!onFocusBadgeNode; var listItemLayoutProps = _objectSpread({ element: 'li', role: role, className: classes, checked: checked, isDisabled: disabled, isFocused: !disabled && isFocused, isSelected: checked !== undefined, isSingleSelection: singleSelection, selectionMode: allowExclusions || checked === 'mixed' ? 'checked' : undefined, showIndicator: showIcons, prepend: prepend, prependProps: { className: 'euiSelectableListItem__prepend' }, append: (append || showOnFocusBadge) && (0, _react2.jsx)(_react.default.Fragment, null, append, showOnFocusBadge ? onFocusBadgeNode : null), appendProps: { className: 'euiSelectableListItem__append' }, contentProps: { className: 'euiSelectableListItem__content' }, textProps: { className: 'euiSelectableListItem__text' }, tooltipProps: hasToolTip ? _objectSpread({ content: toolTipContent, anchorClassName: 'eui-fullWidth', position: 'left' }, toolTipProps) : undefined }, rest); return (0, _react2.jsx)(_list_item_layout.EuiListItemLayout, listItemLayoutProps, children, screenReaderText); }; EuiSelectableListItem.propTypes = { className: _propTypes.default.string, "aria-label": _propTypes.default.string, "data-test-subj": _propTypes.default.string, css: _propTypes.default.any, children: _propTypes.default.node, /** * Applies an icon and visual styling to activated items */ checked: _propTypes.default.any, /** * Shows icons based on `checked` type */ showIcons: _propTypes.default.bool, /** * Highlights the item for pseudo focus */ isFocused: _propTypes.default.bool, disabled: _propTypes.default.bool, prepend: _propTypes.default.node, append: _propTypes.default.node, allowExclusions: _propTypes.default.bool, singleSelection: _propTypes.default.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.default.oneOfType([_propTypes.default.bool.isRequired, _propTypes.default.shape({ /** * Accepts any string from our icon library */ iconType: _propTypes.default.oneOfType([_propTypes.default.oneOf(["accessibility", "addDataApp", "addToDashboard", "advancedSettingsApp", "agentApp", "aggregate", "alignBottom", "alignBottomLeft", "alignBottomRight", "alignCenterHorizontal", "alignCenterVertical", "alignLeft", "alignRight", "alignTop", "alignTopLeft", "alignTopRight", "alert", "analyzeEvent", "annotation", "anomalyChart", "chartAnomaly", "anomalySwimLane", "apmApp", "apmTrace", "chartWaterfall", "appSearchApp", "apps", "arrowDown", "chevronSingleDown", "arrowLeft", "chevronSingleLeft", "arrowRight", "chevronSingleRight", "arrowUp", "chevronSingleUp", "arrowStart", "chevronLimitLeft", "arrowEnd", "chevronLimitRight", "article", "asterisk", "at", "archive", "axisX", "axisYLeft", "axisYRight", "auditbeatApp", "backgroundTask", "beaker", "bell", "bellSlash", "beta", "bolt", "boxesHorizontal", "boxesVertical", "branch", "briefcase", "branchUser", "broom", "brush", "bug", "bulb", "bullseye", "calendar", "canvasApp", "casesApp", "changePointDetection", "chartChangePoint", "chartArea", "chartAreaStack", "chartBarHorizontal", "chartBarHorizontalStack", "chartBarVertical", "chartBarVerticalStack", "chartGauge", "chartHeatmap", "chartLine", "chartPie", "chartTagCloud", "chartThreshold", "check", "checkCircle", "checkInCircleFilled", "checkCircleFill", "cheer", "popper", "classificationJob", "clickLeft", "clickRight", "clock", "clockCounter", "clockControl", "cloud", "cloudDrizzle", "cloudStormy", "cloudSunny", "cluster", "code", "codeApp", "color", "paintBucket", "commandLine", "comment", "compare", "compute", "processor", "console", "consoleApp", "container", "continuityAbove", "continuityAboveBelow", "continuityBelow", "continuityWithin", "contrast", "contrastHigh", "contrastFill", "controls", "controlsHorizontal", "controlsVertical", "copy", "copyClipboard", "crossProjectSearch", "createAdvancedJob", "createGenericJob", "createGeoJob", "createMultiMetricJob", "createPopulationJob", "createSingleMetricJob", "cross", "crossClusterReplicationApp", "crossInCircle", "crossCircle", "crosshair", "crosshairs", "currency", "money", "cut", "scissors", "dashboardApp", "dashedCircle", "dataVisualizer", "database", "desktop", "display", "devToolsApp", "diff", "discoverApp", "distributeHorizontal", "distributeVertical", "download", "drag", "dragHorizontal", "dragVertical", "discuss", "document", "documentEdit", "documentation", "documents", "dot", "dotInCircle", "doubleArrowLeft", "chevronDoubleLeft", "doubleArrowRight", "chevronDoubleRight", "ellipsis", "editorAlignCenter", "textAlignCenter", "editorAlignLeft", "textAlignLeft", "editorAlignRight", "textAlignRight", "editorBold", "textBold", "editorChecklist", "listCheck", "editorCodeBlock", "editorComment", "editorDistributeHorizontal", "editorDistributeVertical", "editorHeading", "textHeading", "editorItalic", "textItalic", "editorItemAlignBottom", "editorItemAlignCenter", "editorItemAlignLeft", "editorItemAlignMiddle", "editorItemAlignRight", "editorItemAlignTop", "editorLink", "editorOrderedList", "listNumber", "editorPositionBottomLeft", "editorPositionBottomRight", "editorPositionTopLeft", "editorPositionTopRight", "editorRedo", "redo", "editorStrike", "textStrike", "editorTable", "table", "editorUnderline", "textUnderline", "editorUndo", "undo", "editorUnorderedList", "listBullet", "email", "mail", "empty", "emsApp", "endpoint", "eql", "query", "eraser", "error", "errorFilled", "errorFill", "esqlVis", "exit", "logOut", "expand", "maximize", "expandMini", "export", "exportAction", "upload", "external", "eye", "eyeClosed", "eyeSlash", "faceHappy", "faceNeutral", "faceSad", "fieldStatistics", "tableInfo", "filebeatApp", "filter", "filterExclude", "filterIgnore", "filterInclude", "filterInCircle", "flask", "flag", "fleetApp", "fold", "folder", "folderClosed", "folderClose", "folderCheck", "folderExclamation", "folderOpen", "folderOpened", "frameNext", "framePrevious", "fullScreen", "fullScreenExit", "function", "gear", "gisApp", "glasses", "globe", "grab", "grabHorizontal", "grabOmnidirectional", "gradient", "graphApp", "grid", "grokApp", "heart", "heartbeatApp", "heatmap", "help", "home", "hourglass", "if", "info", "image", "importAction", "index", "indexClose", "indexEdit", "indexFlush", "indexManagementApp", "indexMapping", "mapping", "indexOpen", "indexPatternApp", "indexRollupApp", "indexRuntime", "indexSettings", "indexTemporary", "tableTime", "infinity", "inputOutput", "inspect", "invert", "ip", "key", "keyboard", "kqlField", "queryField", "kqlFunction", "kqlOperand", "queryOperand", "kqlSelector", "querySelector", "kqlValue", "queryValue", "kubernetesNode", "kubernetesPod", "launch", "rocket", "layers", "lensApp", "lettering", "text", "lineBreak", "lineBreakSlash", "lineDash", "lineDashed", "lineDot", "lineDotted", "lineSolid", "link", "linkSlash", "list", "listAdd", "lock", "lockOpen", "logPatternAnalysis", "pattern", "logRateAnalysis", "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", "logoVectorDB", "logoVulnerabilityManagement", "logoWebhook", "logoWindows", "logoWorkplaceSearch", "logsApp", "logstashFilter", "logstashIf", "logstashInput", "logstashOutput", "logstashQueue", "queue", "machineLearningApp", "magnet", "magnify", "magnifyExclamation", "magnifyMinus", "magnifyPlus", "magnifyWithExclamation", "magnifyWithMinus", "magnifyWithPlus", "managementApp", "map", "mapMarker", "waypoint", "megaphone", "memory", "menu", "menuDown", "menuLeft", "menuRight", "menuUp", "merge", "metricbeatApp", "metricsApp", "minimize", "minus", "minusCircle", "minusInCircle", "minusInCircleFilled", "minusInSquare", "minusSquare", "mobile", "monitoringApp", "moon", "move", "namespace", "nested", "newChat", "node", "vectorTriangle", "notebookApp", "number", "offline", "wifiSlash", "online", "wifi", "outlierDetectionJob", "package", "packetbeatApp", "pageSelect", "pagesSelect", "palette", "paperClip", "partial", "pause", "payment", "pencil", "percent", "pin", "pinFill", "pinFilled", "pipeBreaks", "pipelineApp", "pipeNoBreaks", "pivot", "play", "playFilled", "plugs", "plus", "plusCircle", "plusInCircle", "plusInCircleFilled", "plusInSquare", "plusSquare", "popout", "presentation", "productRobot", "productAgent", "productCloudInfra", "productDashboard", "productDiscover", "productML", "productStreamsClassic", "productStreamsWired", "push", "send", "question", "quote", "radar", "readOnly", "recentlyViewedApp", "refresh", "regressionJob", "reporter", "reportingApp", "return", "returnKey", "save", "savedObjectsApp", "scale", "search", "searchProfilerApp", "section", "securityAnalyticsApp", "securityApp", "securitySignal", "securitySignalDetected", "securitySignalResolved", "server", "sessionViewer", "shard", "share", "significantEvents", "singleMetricViewer", "snowflake", "sortAscending", "sortDescending", "sortDown", "sortLeft", "sortRight", "sortUp", "sortable", "spaces", "spacesApp", "sparkles", "sqlApp", "star", "starEmpty", "starEmptySpace", "starFill", "starFilled", "starFillSpace", "starFilledSpace", "starMinusEmpty", "starMinusFill", "starMinusFilled", "starPlusEmpty", "starPlusFill", "starPlusFilled", "stats", "stop", "stopFill", "stopFilled", "stopSlash", "storage", "streamsClassic", "streamsWired", "string", "submodule", "sun", "swatchInput", "symlink", "tableDensityCompact", "tableDensityHigh", "tableDensityExpanded", "tableDensityLow", "tableDensityNormal", "tableOfContents", "tag", "tear", "temperature", "thermometer", "thumbDown", "thumbUp", "timeline", "timelineWithArrow", "timelionApp", "timeRefresh", "refreshTime", "timeslider", "training", "transitionBottomIn", "transitionBottomOut", "transitionLeftIn", "transitionLeftOut", "transitionTopIn", "transitionTopOut", "trash", "unfold", "unlink", "upgradeAssistantApp", "uptimeApp", "user", "userAvatar", "users", "usersRolesApp", "unarchive", "vector", "vectorSquare", "videoPlayer", "visArea", "visAreaStacked", "visBarHorizontal", "visBarHorizontalStacked", "visBarVertical", "visBarVerticalStacked", "visGauge", "visGoal", "visLine", "visMapCoordinate", "visMapRegion", "visMetric", "chartMetric", "visPie", "visTable", "visTagCloud", "visText", "visTimelion", "visVega", "visVisualBuilder", "visualizeApp", "vulnerabilityManagementApp", "warning", "warningFilled", "warningFill", "watchesApp", "web", "wordWrap", "wordWrapDisabled", "workflowsApp", "workflow", "workplaceSearchApp", "wrench", "tokenAlias", "tokenAnnotation", "tokenArray", "tokenBinary", "tokenBoolean", "tokenClass", "tokenCompletionSuggester", "tokenConstant", "tokenDate", "tokenDimension", "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", "tokenSemanticText", "tokenShape", "tokenString", "tokenStruct", "tokenSymbol", "tokenTag", "tokenText", "tokenTokenCount", "tokenVariable", "tokenVectorDense", "tokenDenseVector", "tokenVectorSparse"]).isRequired, _propTypes.default.string.isRequired, _propTypes.default.elementType.isRequired]), /** * The side of the badge the icon should sit */ iconSide: _propTypes.default.any, /** * Accepts either our palette colors (primary, success ..etc) or a hex value `#FFFFFF`, `#000`. */ color: _propTypes.default.oneOfType([_propTypes.default.any.isRequired, _propTypes.default.string.isRequired]), /** * Whether the badge should use filled (more intense) colors. * It has no effect when a non-named color is passed to the `color` prop. * @default false */ fill: _propTypes.default.bool, /** * Will override any color passed through the `color` prop. */ isDisabled: _propTypes.default.bool, /** * Props passed to the close button. */ closeButtonProps: _propTypes.default.any, className: _propTypes.default.string, "aria-label": _propTypes.default.string, "data-test-subj": _propTypes.default.string, css: _propTypes.default.any, /** * Will apply an onclick to icon within the badge */ iconOnClick: _propTypes.default.func, /** * Aria label applied to the iconOnClick button */ iconOnClickAriaLabel: _propTypes.default.any, /** * Will apply an onclick to the badge itself */ onClick: _propTypes.default.func, /** * Aria label applied to the onClick button */ onClickAriaLabel: _propTypes.default.any, href: _propTypes.default.string, target: _propTypes.default.string, rel: _propTypes.default.string }).isRequired]), /** * 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.default.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.default.any, /** * How to handle long text within the item. * Wrapping only works if virtualization is off. */ textWrap: _propTypes.default.oneOf(["truncate", "wrap"]), /** * 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 };