@elastic/eui
Version:
Elastic UI Component Library
331 lines (323 loc) • 22.4 kB
JavaScript
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); }
var _excluded = ["onItemClick", "onBlur", "onFocus", "onInput", "onSearch", "status", "append", "tooltipContent", "suggestions", "id", "aria-label", "aria-labelledby", "isPreFiltered", "isVirtualized", "fullWidth", "maxHeight"];
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
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); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
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; }
/*
* 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 React, { useState, useCallback } from 'react';
import PropTypes from "prop-types";
import classNames from 'classnames';
import { EuiIcon } from '../icon';
import { useEuiI18n } from '../i18n';
import { EuiInputPopover } from '../popover';
import { EuiSelectable } from '../selectable';
import { EuiToolTip } from '../tool_tip';
import { EuiSuggestItem } from './suggest_item';
import { jsx as ___EmotionJSX } from "@emotion/react";
var statusMap = {
unsaved: {
icon: 'dot',
color: 'accent'
},
saved: {
icon: 'checkInCircleFilled',
color: 'success'
},
unchanged: {
icon: '',
color: 'success'
},
loading: {}
};
// keys of _EuiSuggestItemPropsBase
var suggestItemPropsKeys = ['label', 'type', 'description', 'labelDisplay', 'labelWidth', 'descriptionDisplay'];
export var EuiSuggest = function EuiSuggest(_ref) {
var onItemClick = _ref.onItemClick,
onBlur = _ref.onBlur,
onFocus = _ref.onFocus,
onInput = _ref.onInput,
onSearch = _ref.onSearch,
_ref$status = _ref.status,
status = _ref$status === void 0 ? 'unchanged' : _ref$status,
append = _ref.append,
tooltipContent = _ref.tooltipContent,
suggestions = _ref.suggestions,
id = _ref.id,
ariaLabel = _ref['aria-label'],
labelId = _ref['aria-labelledby'],
_ref$isPreFiltered = _ref.isPreFiltered,
isPreFiltered = _ref$isPreFiltered === void 0 ? false : _ref$isPreFiltered,
_ref$isVirtualized = _ref.isVirtualized,
isVirtualized = _ref$isVirtualized === void 0 ? false : _ref$isVirtualized,
_ref$fullWidth = _ref.fullWidth,
fullWidth = _ref$fullWidth === void 0 ? true : _ref$fullWidth,
_ref$maxHeight = _ref.maxHeight,
maxHeight = _ref$maxHeight === void 0 ? '60vh' : _ref$maxHeight,
rest = _objectWithoutProperties(_ref, _excluded);
/**
* Popover helpers
*/
var _useState = useState(null),
_useState2 = _slicedToArray(_useState, 2),
popoverRef = _useState2[0],
setPopoverRef = _useState2[1];
var _useState3 = useState(false),
_useState4 = _slicedToArray(_useState3, 2),
isPopoverOpen = _useState4[0],
setIsPopoverOpen = _useState4[1];
var openPopover = function openPopover() {
return setIsPopoverOpen(true);
};
var closePopover = function closePopover() {
return setIsPopoverOpen(false);
};
/**
* Search helpers
*/
var searchOnFocus = function searchOnFocus(e) {
onFocus === null || onFocus === void 0 ? void 0 : onFocus(e);
openPopover();
};
var searchOnBlur = function searchOnBlur(e) {
onBlur === null || onBlur === void 0 ? void 0 : onBlur(e);
if (!(popoverRef !== null && popoverRef !== void 0 && popoverRef.contains(e.relatedTarget))) {
closePopover();
}
};
var searchOnInput = function searchOnInput(e) {
onInput === null || onInput === void 0 ? void 0 : onInput(e.target);
openPopover();
};
var searchOnChange = function searchOnChange(value) {
onSearch === null || onSearch === void 0 ? void 0 : onSearch(value);
};
/**
* Status
*/
var icon = '';
var color = '';
if (statusMap[status]) {
icon = statusMap[status].icon || '';
color = statusMap[status].color || '';
}
// EuiFieldText's append accepts an array of elements so start by creating an empty array
var appendArray = [];
var _useEuiI18n = useEuiI18n(['euiSuggest.stateSavedTooltip', 'euiSuggest.stateUnsavedTooltip'], ['Saved.', 'Changes have not been saved.']),
_useEuiI18n2 = _slicedToArray(_useEuiI18n, 2),
statusSaved = _useEuiI18n2[0],
statusUnsaved = _useEuiI18n2[1];
statusMap.saved.tooltip = statusSaved;
statusMap.unsaved.tooltip = statusUnsaved;
var statusElement = (status === 'saved' || status === 'unsaved') && ___EmotionJSX(EuiToolTip, {
position: "left",
content: tooltipContent || statusMap[status].tooltip
}, ___EmotionJSX(EuiIcon, {
className: "euiSuggestInput__statusIcon",
color: color,
type: icon
}));
// Push the status element to the array if it is not undefined
if (statusElement) appendArray.push(statusElement);
// Check to see if consumer passed an append item and if so, add it to the array
if (append) appendArray.push(append);
var _useEuiI18n3 = useEuiI18n(['euiSuggest.stateLoading', 'euiSuggest.stateSaved', 'euiSuggest.stateUnsaved', 'euiSuggest.stateUnchanged'], ['State: loading.', 'State: saved.', 'State: unsaved.', 'State: unchanged.']),
_useEuiI18n4 = _slicedToArray(_useEuiI18n3, 4),
stateLoading = _useEuiI18n4[0],
stateSaved = _useEuiI18n4[1],
stateUnsaved = _useEuiI18n4[2],
stateUnchanged = _useEuiI18n4[3];
var stateMessageMap = {
loading: stateLoading,
saved: stateSaved,
unsaved: stateUnsaved,
unchanged: stateUnchanged
};
var stateMessage = stateMessageMap[status];
/**
* Options list
*/
var suggestionList = suggestions.map(function (props) {
// Omit props destined for the EuiSuggestItem so that they don't
// cause warnings or render in the DOM of the EuiSelectableItem
var data = {};
var liProps = {
label: props.label
};
Object.keys(props).forEach(function (key) {
if (suggestItemPropsKeys.includes(key)) {
// @ts-ignore string index type
data[key] = props[key];
} else {
// @ts-ignore string index type
liProps[key] = props[key];
}
});
return _objectSpread(_objectSpread({}, liProps), {}, {
data: data,
className: classNames(props.className, 'euiSuggestItemOption'),
// Force truncation if `isVirtualized` is true
truncate: isVirtualized ? true : props.truncate
});
});
var renderOption = useCallback(function (props) {
return ___EmotionJSX(EuiSuggestItem, props);
}, []);
var onItemSelect = useCallback(function (options) {
if (onItemClick) {
var selectedIndex = options.findIndex(function (option) {
return option.checked === 'on';
});
if (selectedIndex >= 0) {
var selectedSuggestion = suggestions[selectedIndex];
onItemClick(selectedSuggestion);
}
}
}, [onItemClick, suggestions]);
return ___EmotionJSX(React.Fragment, null, ___EmotionJSX(EuiSelectable, {
selectableScreenReaderText: stateMessage,
singleSelection: true,
height: isVirtualized ? undefined : 'full',
options: suggestionList,
renderOption: renderOption,
onChange: onItemSelect,
listProps: {
bordered: false,
showIcons: false,
onFocusBadge: false,
paddingSize: 'none',
textWrap: isVirtualized ? 'truncate' : 'wrap',
isVirtualized: isVirtualized
},
searchable: true,
isPreFiltered: isPreFiltered,
searchProps: _objectSpread({
id: id,
append: appendArray.length ? appendArray : undefined,
fullWidth: fullWidth,
isLoading: status === 'loading' ? true : false,
onFocus: searchOnFocus,
onBlur: searchOnBlur,
onInput: searchOnInput,
onChange: searchOnChange,
'aria-label': ariaLabel,
'aria-labelledby': labelId
}, rest)
}, function (list, search) {
return ___EmotionJSX(EuiInputPopover, {
disableFocusTrap: true,
input: ___EmotionJSX(React.Fragment, null, search),
isOpen: isPopoverOpen,
panelPaddingSize: "none",
fullWidth: fullWidth,
closePopover: closePopover,
panelRef: setPopoverRef,
panelProps: {
'aria-live': undefined,
'aria-modal': false,
role: undefined
}
}, ___EmotionJSX("div", {
style: {
maxHeight: maxHeight
},
className: "eui-yScroll"
}, list));
}));
};
EuiSuggest.propTypes = {
className: PropTypes.string,
"aria-label": PropTypes.oneOfType([PropTypes.string, PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.string])]),
"data-test-subj": PropTypes.string,
css: PropTypes.any,
/**
* List of suggestions to display using EuiSuggestItem.
* Accepts props from #EuiSuggestItemProps
*/
suggestions: PropTypes.arrayOf(PropTypes.shape({
className: PropTypes.string,
"aria-label": PropTypes.string,
"data-test-subj": PropTypes.string,
css: PropTypes.any,
/**
* Takes `iconType` for EuiIcon and 'color'. 'color' can be tint1 through tint9.
*/
type: PropTypes.shape({
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]).isRequired,
color: PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.oneOf(["tint0", "tint1", "tint2", "tint3", "tint4", "tint5", "tint6", "tint7", "tint8", "tint9", "tint10"]).isRequired]).isRequired
}).isRequired,
/**
* Label or primary text.
*/
label: PropTypes.string.isRequired,
/**
* Description or secondary text (optional).
*/
description: PropTypes.string,
/**
* Percentage width of `label`.
* Accepts multiples of `10`, from `20` to `90`.
* Label will expand to 100% if `description` is not provided.
*/
labelWidth: PropTypes.oneOf(["20", "30", "40", "50", "60", "70", "80", "90", 20, 30, 40, 50, 60, 70, 80, 90]),
/**
* Truncates both label and description.
*/
truncate: PropTypes.bool
}).isRequired).isRequired,
/**
* Changes the content of the tooltip that wraps the status icon
*/
tooltipContent: PropTypes.string,
/**
* Status of the current query 'unsaved', 'saved', 'unchanged' or 'loading'.
*/
status: PropTypes.any,
/**
* Element to be appended to the input bar.
*/
append: PropTypes.any,
/**
* Handler for click on an EuiSuggestItem.
*/
onItemClick: PropTypes.func,
/**
* Callback function called when the input changes.
*/
onInput: PropTypes.func,
/**
* Callback function called when the search changes.
*/
onSearch: PropTypes.func,
/**
* Use virtualized rendering for list items with `react-window`.
* Best used when there are a lot of items.
*/
isVirtualized: PropTypes.bool,
/**
* Maximum height to set for the list.
* Default is `60vh`
*/
maxHeight: PropTypes.any,
/**
* Control whether or not options get filtered internally or if consumer will filter.
* Default `false`
*/
isPreFiltered: PropTypes.bool,
"aria-labelledby": PropTypes.oneOfType([PropTypes.string, PropTypes.string.isRequired])
};