UNPKG

@elastic/eui

Version:

Elastic UI Component Library

305 lines (297 loc) 23.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "COLORS", { enumerable: true, get: function get() { return _named_colors.COLORS; } }); exports.clearIconComponentCache = exports.appendIconComponentCache = exports.TYPES = exports.SIZES = exports.EuiIconClass = exports.EuiIcon = void 0; var _react = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _classnames = _interopRequireDefault(require("classnames")); var _common = require("../common"); var _icon_map = require("./icon_map"); var _empty = require("./assets/empty"); var _react2 = require("../../services/react"); var _services = require("../../services"); var _named_colors = require("./named_colors"); var _icon = require("./icon.styles"); var _react3 = require("@emotion/react"); var _excluded = ["type", "size", "color", "className", "tabIndex", "title", "onIconLoad", "style", "stylesMemoizer"]; function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } 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); } 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 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 _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; } 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 _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, 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); } /* * 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 getIsAppIcon = function getIsAppIcon(iconType) { if (typeof iconType !== 'string') return false; if (iconType === 'dataVisualizer') return true; // Special case if (iconType.indexOf('data:') === 0) return false; // Inline data URIs should be short-circuited for performance return iconType.endsWith('App') || iconType.endsWith('Job'); }; var TYPES = exports.TYPES = (0, _common.keysOf)(_icon_map.typeToPathMap); // We accept arbitrary color strings, which are impossible to type. var SIZES = exports.SIZES = ['original', 's', 'm', 'l', 'xl', 'xxl']; function isEuiIconType(x) { return typeof x === 'string' && _icon_map.typeToPathMap.hasOwnProperty(x); } function getInitialIcon(icon) { if (icon == null) { return undefined; } if (isEuiIconType(icon)) { if (iconComponentCache.hasOwnProperty(icon)) { return iconComponentCache[icon]; } return undefined; } return icon; } var generateId = (0, _services.htmlIdGenerator)(); var iconComponentCache = {}; var clearIconComponentCache = exports.clearIconComponentCache = function clearIconComponentCache(iconType) { if (iconType != null) { delete iconComponentCache[iconType]; } else { iconComponentCache = {}; } }; var appendIconComponentCache = exports.appendIconComponentCache = function appendIconComponentCache(iconTypeToIconComponentMap) { for (var iconType in iconTypeToIconComponentMap) { if (iconTypeToIconComponentMap.hasOwnProperty(iconType)) { iconComponentCache[iconType] = iconTypeToIconComponentMap[iconType]; } } }; var EuiIconClass = exports.EuiIconClass = /*#__PURE__*/function (_PureComponent) { function EuiIconClass(props) { var _this; _classCallCheck(this, EuiIconClass); _this = _callSuper(this, EuiIconClass, [props]); _defineProperty(_this, "isMounted", false); _defineProperty(_this, "loadIconComponent", function (iconType) { if (iconComponentCache.hasOwnProperty(iconType)) { // exists in cache _this.setState({ isLoading: false, neededLoading: false, icon: iconComponentCache[iconType] }); _this.onIconLoad(); return; } (function (specifier) { return new Promise(function (r) { return r("".concat(specifier)); }).then(function (s) { return _interopRequireWildcard(require(s)); }); })( /* webpackChunkName: "icon.[request]" */ // It's important that we don't use a template string here, it // stops webpack from building a dynamic require context. // eslint-disable-next-line prefer-template './assets/' + _icon_map.typeToPathMap[iconType]).then(function (_ref) { var icon = _ref.icon; iconComponentCache[iconType] = icon; (0, _react2.enqueueStateChange)(function () { if (_this.isMounted && _this.props.type === iconType) { _this.setState({ icon: icon, iconTitle: iconType, isLoading: false }, _this.onIconLoad); } }); }); }); _defineProperty(_this, "onIconLoad", function () { var onIconLoad = _this.props.onIconLoad; if (onIconLoad) { onIconLoad(); } }); var type = props.type; var initialIcon = getInitialIcon(type); _this.state = { icon: initialIcon, iconTitle: undefined, isLoading: false, neededLoading: false }; return _this; } _inherits(EuiIconClass, _PureComponent); return _createClass(EuiIconClass, [{ key: "componentDidMount", value: function componentDidMount() { this.isMounted = true; var type = this.props.type; if (isEuiIconType(type) && this.state.icon == null) { this.setState({ neededLoading: true, isLoading: true }); this.loadIconComponent(type); } else { this.onIconLoad(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { var type = this.props.type; if (type !== prevProps.type) { if (isEuiIconType(type)) { this.setState({ neededLoading: iconComponentCache.hasOwnProperty(type), isLoading: true }); this.loadIconComponent(type); } else { this.setState({ icon: type, neededLoading: true, isLoading: false }); } } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.isMounted = false; } }, { key: "render", value: function render() { var _this$props = this.props, type = _this$props.type, _this$props$size = _this$props.size, size = _this$props$size === void 0 ? 'm' : _this$props$size, color = _this$props.color, className = _this$props.className, tabIndex = _this$props.tabIndex, title = _this$props.title, onIconLoad = _this$props.onIconLoad, style = _this$props.style, stylesMemoizer = _this$props.stylesMemoizer, rest = _objectWithoutProperties(_this$props, _excluded); var _this$state = this.state, isLoading = _this$state.isLoading, neededLoading = _this$state.neededLoading, iconTitle = _this$state.iconTitle; var isLoaded = !isLoading && neededLoading; var isCustomColor = color && !(0, _named_colors.isNamedColor)(color); var optionalCustomStyles = isCustomColor ? _objectSpread({ color: color }, style) : style; // These icons are a little special and get some extra CSS flexibility var isAppIcon = getIsAppIcon(type); // App color styles are only applied if no color is passed or if color="default" is passed var appIconHasColor = color && color !== 'default'; // The Elastic logo should be an outline in text and ghost mode var isElasticLogoOutline = type === 'logoElastic' && (color === 'ghost' || color === 'text'); var classes = (0, _classnames.default)('euiIcon', className); // Emotion styles var styles = stylesMemoizer(_icon.euiIconStyles); var cssStyles = [styles.euiIcon, styles[size], color && (0, _named_colors.isNamedColor)(color) && styles[color], isCustomColor && styles.customColor, isElasticLogoOutline && styles.logoElasticOutline, isAppIcon && !appIconHasColor && styles.app, isLoading && styles.isLoading, !isLoading && neededLoading && styles.isLoaded]; var icon = this.state.icon || _empty.icon; if (typeof icon === 'string') { return (0, _react3.jsx)("img", _extends({ alt: title ? title : '', src: icon, className: classes, css: cssStyles, style: style, tabIndex: tabIndex }, rest)); } else { var Svg = icon; // If there is no aria-label, aria-labelledby, or title it gets aria-hidden true var isAriaHidden = !(this.props['aria-label'] || this.props['aria-labelledby'] || this.props.title); // If no aria-label or aria-labelledby is provided but there's a title, a titleId is generated // The svg aria-labelledby attribute gets this titleId // The svg title element gets this titleId as an id var titleId = !this.props['aria-label'] && !this.props['aria-labelledby'] && title ? { titleId: generateId() } : undefined; return (0, _react3.jsx)(Svg, _extends({ className: classes, style: optionalCustomStyles, css: cssStyles, tabIndex: tabIndex, role: "img", title: title }, titleId, { "data-icon-type": iconTitle, "data-is-loaded": isLoaded || undefined, "data-is-loading": isLoading || undefined }, rest, { "aria-hidden": isAriaHidden || rest['aria-hidden'] })); } } }]); }(_react.PureComponent); EuiIconClass.propTypes = { className: _propTypes.default.string, "aria-label": _propTypes.default.string, "data-test-subj": _propTypes.default.string, css: _propTypes.default.any, /** * `Enum` is any of the named icons listed in the docs, `string` is usually a URL to an SVG file, and `elementType` is any React SVG component */ type: _propTypes.default.oneOfType([_propTypes.default.oneOf(["accessibility", "addDataApp", "advancedSettingsApp", "agentApp", "aggregate", "analyzeEvent", "annotation", "anomalyChart", "anomalySwimLane", "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", "changePointDetection", "check", "checkInCircleFilled", "cheer", "classificationJob", "clickLeft", "clickRight", "clock", "clockCounter", "cloudDrizzle", "cloudStormy", "cloudSunny", "cluster", "codeApp", "color", "compute", "console", "consoleApp", "container", "continuityAbove", "continuityAboveBelow", "continuityBelow", "continuityWithin", "controlsHorizontal", "controlsVertical", "copy", "copyClipboard", "createAdvancedJob", "createMultiMetricJob", "createPopulationJob", "createSingleMetricJob", "cross", "crossClusterReplicationApp", "crossInCircle", "crosshairs", "currency", "cut", "dashboardApp", "dataVisualizer", "database", "desktop", "devToolsApp", "diff", "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", "endpoint", "eql", "eraser", "error", "errorFilled", "esqlVis", "exit", "expand", "expandMini", "exportAction", "eye", "eyeClosed", "faceHappy", "faceNeutral", "faceSad", "fieldStatistics", "filebeatApp", "filter", "filterExclude", "filterIgnore", "filterInclude", "filterInCircle", "flag", "fleetApp", "fold", "folderCheck", "folderClosed", "folderExclamation", "folderOpen", "frameNext", "framePrevious", "fullScreen", "fullScreenExit", "function", "gear", "gisApp", "glasses", "globe", "grab", "grabHorizontal", "grabOmnidirectional", "gradient", "graphApp", "grid", "grokApp", "heart", "heartbeatApp", "heatmap", "help", "home", "iInCircle", "image", "importAction", "index", "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", "logPatternAnalysis", "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", "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", "minusInSquare", "mobile", "monitoringApp", "moon", "move", "namespace", "nested", "newChat", "node", "notebookApp", "number", "offline", "online", "outlierDetectionJob", "package", "packetbeatApp", "pageSelect", "pagesSelect", "palette", "paperClip", "partial", "pause", "payment", "pencil", "percent", "pin", "pinFilled", "pipeBreaks", "pipelineApp", "pipeNoBreaks", "pivot", "play", "playFilled", "plus", "plusInCircle", "plusInCircleFilled", "plusInSquare", "popout", "push", "questionInCircle", "quote", "recentlyViewedApp", "refresh", "regressionJob", "reporter", "reportingApp", "returnKey", "save", "savedObjectsApp", "scale", "search", "searchProfilerApp", "securityAnalyticsApp", "securityApp", "securitySignal", "securitySignalDetected", "securitySignalResolved", "sessionViewer", "shard", "share", "singleMetricViewer", "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", "transitionLeftIn", "transitionLeftOut", "transitionTopIn", "transitionTopOut", "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", "warningFilled", "alert", "watchesApp", "wordWrap", "wordWrapDisabled", "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]).isRequired, /** * One of EUI's color palette or a valid CSS color value https://developer.mozilla.org/en-US/docs/Web/CSS/color_value. * Note that coloring only works if your SVG is removed of fill attributes. */ color: _propTypes.default.oneOfType([_propTypes.default.string.isRequired, _propTypes.default.any.isRequired]), /** * Note that every size other than `original` assumes the provided SVG sits on a square viewbox. */ size: _propTypes.default.any, /** * Descriptive title for naming the icon based on its use */ title: _propTypes.default.string, /** * A unique identifier for the title element */ titleId: _propTypes.default.string, /** * Its value should be one or more element IDs */ "aria-labelledby": _propTypes.default.string, /** * Callback when the icon has been loaded & rendered */ onIconLoad: _propTypes.default.func }; var EuiIcon = exports.EuiIcon = (0, _services.withEuiStylesMemoizer)(EuiIconClass);