@elastic/eui
Version:
Elastic UI Component Library
236 lines (232 loc) • 18.9 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 = ["children", "color", "iconType", "iconSide", "className", "isDisabled", "onClick", "iconOnClick", "onClickAriaLabel", "iconOnClickAriaLabel", "closeButtonProps", "href", "rel", "target", "style"];
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 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 _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, { useMemo } from 'react';
import PropTypes from "prop-types";
import classNames from 'classnames';
import { useEuiTheme, getSecureRelForTarget, wcagContrastMin } from '../../services';
import { EuiInnerText } from '../inner_text';
import { EuiIcon } from '../icon';
import { validateHref } from '../../services/security/href_validator';
import { getTextColor, getColorContrast, getIsValidColor } from './color_utils';
import { euiBadgeStyles } from './badge.styles';
import { jsx as ___EmotionJSX } from "@emotion/react";
export var ICON_SIDES = ['left', 'right'];
export var COLORS = ['default', 'hollow', 'primary', 'success', 'accent', 'warning', 'danger'];
export var EuiBadge = function EuiBadge(_ref) {
var children = _ref.children,
_ref$color = _ref.color,
color = _ref$color === void 0 ? 'default' : _ref$color,
iconType = _ref.iconType,
_ref$iconSide = _ref.iconSide,
iconSide = _ref$iconSide === void 0 ? 'left' : _ref$iconSide,
className = _ref.className,
_isDisabled = _ref.isDisabled,
onClick = _ref.onClick,
iconOnClick = _ref.iconOnClick,
onClickAriaLabel = _ref.onClickAriaLabel,
iconOnClickAriaLabel = _ref.iconOnClickAriaLabel,
closeButtonProps = _ref.closeButtonProps,
href = _ref.href,
rel = _ref.rel,
target = _ref.target,
style = _ref.style,
rest = _objectWithoutProperties(_ref, _excluded);
var euiTheme = useEuiTheme();
var isHrefValid = !href || validateHref(href);
var isDisabled = _isDisabled || !isHrefValid;
var isNamedColor = COLORS.includes(color);
var customColorStyles = useMemo(function () {
// Named colors set their styles via Emotion CSS and not inline styles
if (isNamedColor) return style;
// Do our best to ensure custom colors provide sufficient contrast
try {
// Set dark or light text color based upon best contrast
var textColor = getTextColor(euiTheme, color);
// Check the contrast ratio. If it's low contrast, emit a console awrning
var contrastRatio = getColorContrast(textColor, color);
if (contrastRatio < wcagContrastMin) {
console.warn("Warning: ".concat(color, " badge has a low contrast of ").concat(contrastRatio.toFixed(2), ". Should be above ").concat(wcagContrastMin, "."));
}
return _objectSpread({
backgroundColor: color,
color: textColor
}, style);
} catch (err) {
if (!getIsValidColor(color)) {
console.warn('EuiBadge expects a valid color. This can either be a three or six ' + "character hex value, rgb(a) value, hsv value, hollow, or one of the following: ".concat(COLORS, ". ") + "Instead got ".concat(color, "."));
}
}
}, [color, isNamedColor, style, euiTheme]);
var styles = euiBadgeStyles(euiTheme);
var cssStyles = [styles.euiBadge, isNamedColor && styles[color], (onClick || href) && !iconOnClick && styles.clickable, isDisabled && styles.disabled];
var textCssStyles = [styles.text.euiBadge__text, (onClick || href) && !isDisabled && styles.text.clickable];
var iconCssStyles = [styles.icon.euiBadge__icon, styles.icon[iconSide]];
var iconButtonCssStyles = [styles.iconButton.euiBadge__iconButton, styles.iconButton[iconSide]];
var classes = classNames('euiBadge', className);
var closeClassNames = classNames('euiBadge__icon', closeButtonProps === null || closeButtonProps === void 0 ? void 0 : closeButtonProps.className);
var Element = href && !isDisabled ? 'a' : 'button';
var relObj = {};
if (href && !isDisabled) {
relObj.href = href;
relObj.target = target;
relObj.rel = getSecureRelForTarget({
href: href,
target: target,
rel: rel
});
}
if (onClick) {
relObj.onClick = onClick;
}
var optionalIcon = null;
if (iconType) {
if (iconOnClick) {
if (!iconOnClickAriaLabel) {
console.warn('When passing the iconOnClick props to EuiBadge, you must also provide iconOnClickAriaLabel');
}
optionalIcon = ___EmotionJSX("button", {
type: "button",
className: "euiBadge__iconButton",
css: iconButtonCssStyles,
"aria-label": iconOnClickAriaLabel,
disabled: isDisabled,
title: iconOnClickAriaLabel,
onClick: iconOnClick
}, ___EmotionJSX(EuiIcon, _extends({
type: iconType,
size: "s",
color: "inherit" // forces the icon to inherit its parent color
}, closeButtonProps, {
className: closeClassNames,
css: [].concat(iconCssStyles, [closeButtonProps === null || closeButtonProps === void 0 ? void 0 : closeButtonProps.css])
})));
} else {
optionalIcon = ___EmotionJSX(EuiIcon, {
type: iconType,
size: children ? 's' : 'm',
className: "euiBadge__icon",
css: iconCssStyles,
color: "inherit" // forces the icon to inherit its parent color
});
}
}
if (onClick && !onClickAriaLabel) {
console.warn('When passing onClick to EuiBadge, you must also provide onClickAriaLabel');
}
var content = ___EmotionJSX("span", {
className: "euiBadge__content",
css: styles.euiBadge__content
}, iconSide === 'left' && optionalIcon, children && ___EmotionJSX("span", {
className: "euiBadge__text",
css: textCssStyles
}, children), iconSide === 'right' && optionalIcon);
if (iconOnClick) {
return onClick || href ? ___EmotionJSX("span", {
className: classes,
css: cssStyles,
style: customColorStyles
}, ___EmotionJSX("span", {
className: "euiBadge__content",
css: styles.euiBadge__content
}, iconSide === 'left' && optionalIcon, ___EmotionJSX(EuiInnerText, null, function (ref, innerText) {
return ___EmotionJSX(Element, _extends({
className: "euiBadge__childButton",
css: styles.euiBadge__childButton,
disabled: isDisabled,
"aria-label": onClickAriaLabel,
ref: ref,
title: innerText
}, relObj, rest), children);
}), iconSide === 'right' && optionalIcon)) : ___EmotionJSX(EuiInnerText, null, function (ref, innerText) {
return ___EmotionJSX("span", _extends({
className: classes,
css: cssStyles,
style: customColorStyles,
ref: ref,
title: innerText
}, rest), content);
});
} else if (onClick || href) {
return ___EmotionJSX(EuiInnerText, null, function (ref, innerText) {
return ___EmotionJSX(Element, _extends({
disabled: isDisabled,
"aria-label": onClickAriaLabel,
className: classes,
css: cssStyles,
style: customColorStyles,
ref: ref,
title: innerText
}, relObj, rest), content);
});
} else {
return ___EmotionJSX(EuiInnerText, null, function (ref, innerText) {
return ___EmotionJSX("span", _extends({
className: classes,
css: cssStyles,
style: customColorStyles,
ref: ref,
title: innerText
}, rest), content);
});
}
};
EuiBadge.propTypes = {
/**
* 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
};