UNPKG

@elastic/eui

Version:

Elastic UI Component Library

280 lines (279 loc) 23.3 kB
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); } var _excluded = ["children", "className", "disabled", "checked", "isFocused", "showIcons", "prepend", "append", "allowExclusions", "singleSelection", "onFocusBadge", "role", "searchable", "toolTipContent", "toolTipProps"], _excluded2 = ["children", "className"]; 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) { _defineProperty(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; } 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); } 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; } /* * 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, { useMemo } from 'react'; import { EuiI18n } from '../../i18n'; import { EuiScreenReaderOnly } from '../../accessibility'; import { EuiBadge } from '../../badge'; import { EuiListItemLayout } from '../../list_item_layout/_list_item_layout'; import { jsx as ___EmotionJSX } from "@emotion/react"; export var 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 = _objectWithoutProperties(_ref, _excluded); var classes = classNames('euiSelectableListItem', { 'euiSelectableListItem-isFocused': isFocused }, className); var onFocusBadgeNode = useMemo(function () { var defaultOnFocusBadgeProps = { 'aria-hidden': true, iconType: 'return', iconSide: 'left', color: 'hollow' }; if (onFocusBadge === true) { return ___EmotionJSX(EuiBadge, _extends({ className: "euiSelectableListItem__onFocusBadge" }, defaultOnFocusBadgeProps)); } else if (typeof onFocusBadge !== 'boolean' && !!onFocusBadge) { var _children = onFocusBadge.children, _className = onFocusBadge.className, restBadgeProps = _objectWithoutProperties(onFocusBadge, _excluded2); return ___EmotionJSX(EuiBadge, _extends({ className: classNames('euiSelectableListItem__onFocusBadge', _className) }, defaultOnFocusBadgeProps, restBadgeProps), _children); } }, [onFocusBadge]); var screenReaderText = useMemo(function () { 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; } return state || instructions ? ___EmotionJSX(EuiScreenReaderOnly, null, ___EmotionJSX("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) && ___EmotionJSX(React.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 ___EmotionJSX(EuiListItemLayout, listItemLayoutProps, children, screenReaderText); }; 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.any, /** * 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, singleSelection: 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", "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.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]), /** * 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.bool, /** * 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]), /** * 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"]), /** * Optional custom tooltip content for the button */ toolTipContent: PropTypes.node, /** * Optional props to pass to the underlying **[EuiToolTip](/#/display/tooltip)** */ toolTipProps: PropTypes.any };