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 _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) { n[e] = r[e]; } return n; }
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 _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 _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], -1 === t.indexOf(o) && {}.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 (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } } return t; }
/*
 * SPDX-License-Identifier: Apache-2.0
 *
 * The OpenSearch Contributors require contributions made to
 * this file be licensed under the Apache-2.0 license or a
 * compatible open source license.
 *
 * Modifications Copyright OpenSearch Contributors. See
 * GitHub history for details.
 */

/*
 * Licensed to Elasticsearch B.V. under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch B.V. licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import React from 'react';
import PropTypes from "prop-types";
import classNames from 'classnames';
import chroma from 'chroma-js';
import { keysOf } from '../common';
import { euiPaletteColorBlindBehindText, getSecureRelForTarget, isColorDark } from '../../services';
import { EuiInnerText } from '../inner_text';
import { EuiIcon } from '../icon';
import { chromaValid, parseColor } from '../color_picker/utils';
import { validateHref } from '../../services/security/href_validator';
// TODO - replace with variables once https://github.com/elastic/oui/issues/2731 is closed
var colorInk = '#000';
var colorGhost = '#fff';

// The color blind palette has some stricter accessibility needs with regards to
// charts and contrast. We use the euiPaletteColorBlindBehindText variant here since our
// accessibility concerns pertain to foreground (text) and background contrast
var visColors = euiPaletteColorBlindBehindText();
var colorToHexMap = {
  // TODO - replace with variable once https://github.com/elastic/oui/issues/2731 is closed
  default: '#d3dae6',
  primary: visColors[1],
  success: visColors[0],
  secondary: visColors[0],
  accent: visColors[2],
  warning: visColors[5],
  danger: visColors[9]
};
export var COLORS = keysOf(colorToHexMap);
var iconSideToClassNameMap = {
  left: 'euiBadge--iconLeft',
  right: 'euiBadge--iconRight'
};
export var ICON_SIDES = keysOf(iconSideToClassNameMap);
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, ["children", "color", "iconType", "iconSide", "className", "isDisabled", "onClick", "iconOnClick", "onClickAriaLabel", "iconOnClickAriaLabel", "closeButtonProps", "href", "rel", "target", "style"]);
  var isHrefValid = !href || validateHref(href);
  var isDisabled = _isDisabled || !isHrefValid;
  var optionalCustomStyles = style;
  var textColor = null;
  // TODO - replace with variable once https://github.com/elastic/oui/issues/2731 is closed
  var wcagContrastBase = 4.5; // WCAG AA contrast level
  var wcagContrast = null;
  var colorHex = null;

  // Check if a valid color name was provided
  try {
    if (COLORS.indexOf(color) > -1) {
      // Get the hex equivalent for the provided color name
      colorHex = colorToHexMap[color];

      // Set dark or light text color based upon best contrast
      textColor = setTextColor(colorHex);
      optionalCustomStyles = _objectSpread({
        backgroundColor: colorHex,
        color: textColor
      }, optionalCustomStyles);
    } else if (color !== 'hollow') {
      // This is a custom color that is neither from the base palette nor hollow
      // Let's do our best to ensure that it provides sufficient contrast

      // Set dark or light text color based upon best contrast
      textColor = setTextColor(color);

      // Check the contrast
      wcagContrast = getColorContrast(textColor, color);
      if (wcagContrast < wcagContrastBase) {
        // It's low contrast, so lets show a warning in the console
        console.warn('Warning: ', color, ' badge has low contrast of ', wcagContrast.toFixed(2), '. Should be above ', wcagContrastBase, '.');
      }
      optionalCustomStyles = _objectSpread({
        backgroundColor: color,
        color: textColor
      }, optionalCustomStyles);
    }
  } catch (err) {
    handleInvalidColor(color);
  }
  var classes = classNames('euiBadge', {
    'euiBadge-isClickable': (onClick || href) && !iconOnClick,
    'euiBadge-isDisabled': isDisabled,
    'euiBadge--hollow': color === 'hollow'
  }, iconSideToClassNameMap[iconSide], className);
  var closeClassNames = classNames('euiBadge__icon', closeButtonProps && 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 = /*#__PURE__*/React.createElement("button", {
        type: "button",
        className: "euiBadge__iconButton",
        "aria-label": iconOnClickAriaLabel,
        disabled: isDisabled,
        title: iconOnClickAriaLabel,
        onClick: iconOnClick
      }, /*#__PURE__*/React.createElement(EuiIcon, _extends({
        type: iconType,
        size: "s",
        color: "inherit" // forces the icon to inherit its parent color
      }, closeButtonProps, {
        className: closeClassNames
      })));
    } else {
      optionalIcon = /*#__PURE__*/React.createElement(EuiIcon, {
        type: iconType,
        size: children ? 's' : 'm',
        className: "euiBadge__icon",
        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 = /*#__PURE__*/React.createElement("span", {
    className: "euiBadge__content"
  }, children && /*#__PURE__*/React.createElement("span", {
    className: "euiBadge__text"
  }, children), optionalIcon);
  if (iconOnClick) {
    return onClick || href ? /*#__PURE__*/React.createElement("span", {
      className: classes,
      style: optionalCustomStyles
    }, /*#__PURE__*/React.createElement("span", {
      className: "euiBadge__content"
    }, /*#__PURE__*/React.createElement(EuiInnerText, null, function (ref, innerText) {
      return /*#__PURE__*/React.createElement(Element, _extends({
        className: "euiBadge__childButton",
        disabled: isDisabled,
        "aria-label": onClickAriaLabel,
        ref: ref,
        title: innerText
      }, relObj, rest), children);
    }), optionalIcon)) : /*#__PURE__*/React.createElement(EuiInnerText, null, function (ref, innerText) {
      return /*#__PURE__*/React.createElement("span", _extends({
        className: classes,
        style: optionalCustomStyles,
        ref: ref,
        title: innerText
      }, rest), content);
    });
  } else if (onClick || href) {
    return /*#__PURE__*/React.createElement(EuiInnerText, null, function (ref, innerText) {
      return /*#__PURE__*/React.createElement(Element, _extends({
        disabled: isDisabled,
        "aria-label": onClickAriaLabel,
        className: classes,
        style: optionalCustomStyles,
        ref: ref,
        title: innerText
      }, relObj, rest), content);
    });
  } else {
    return /*#__PURE__*/React.createElement(EuiInnerText, null, function (ref, innerText) {
      return /*#__PURE__*/React.createElement("span", _extends({
        className: classes,
        style: optionalCustomStyles,
        ref: ref,
        title: innerText
      }, rest), content);
    });
  }
};
EuiBadge.propTypes = {
  /**
     * Accepts any string from our icon library
     */
  iconType: PropTypes.oneOfType([PropTypes.oneOf(["accessibility", "addBookmark", "addDataApp", "advancedSettingsApp", "aggregate", "alert", "analyzeEvent", "annotation", "anomalyDetection", "apmApp", "apmTrace", "apps", "appSearchApp", "arrowDown", "arrowLeft", "arrowRight", "arrowUp", "asterisk", "auditbeatApp", "beaker", "bell", "bellSlash", "bolt", "bookOpen", "boxesHorizontal", "boxesVertical", "branch", "broom", "brush", "bug", "bullseye", "calendar", "canvasApp", "codeApp", "chatLeft", "chatRight", "check", "checkInCircleEmpty", "checkInCircleFilled", "cheer", "classificationJob", "clock", "cloudDrizzle", "cloudStormy", "cloudSunny", "color", "compass", "compute", "console", "consoleApp", "continuityAbove", "continuityAboveBelow", "continuityBelow", "continuityWithin", "controlsHorizontal", "controlsVertical", "copy", "copyClipboard", "createAdvancedJob", "createMultiMetricJob", "createPopulationJob", "createSingleMetricJob", "cross", "crossClusterReplicationApp", "crosshairs", "crossInACircleFilled", "crossInCircleEmpty", "crossInCircleFilled", "currency", "cut", "dashboard", "dashboardApp", "database", "dataVisualizer", "devToolsApp", "discoverApp", "document", "documentation", "documentEdit", "documents", "dot", "download", "dockedBottom", "dockedDetached", "dockedLeft", "dockedRight", "dockedTakeover", "dockedTop", "editorAlignCenter", "editorAlignLeft", "editorAlignRight", "editorBold", "editorCodeBlock", "editorComment", "editorDistributeHorizontal", "editorDistributeVertical", "editorHeading", "editorItalic", "editorItemAlignLeft", "editorItemAlignBottom", "editorItemAlignCenter", "editorItemAlignMiddle", "editorItemAlignRight", "editorItemAlignTop", "editorLink", "editorOrderedList", "editorPositionBottomLeft", "editorPositionBottomRight", "editorPositionTopLeft", "editorPositionTopRight", "editorRedo", "editorStrike", "editorTable", "editorUnderline", "editorUndo", "editorUnorderedList", "email", "empty", "emsApp", "eql", "eraser", "exit", "expand", "expandMini", "exportAction", "eye", "eyeClosed", "faceHappy", "faceNeutral", "faceSad", "filebeatApp", "filter", "flag", "fold", "folderCheck", "folderClosed", "folderExclamation", "folderOpen", "frameNext", "framePrevious", "fullScreen", "fullScreenExit", "function", "functionAdd", "gear", "generate", "generateContent", "gisApp", "glasses", "globe", "grab", "grabHorizontal", "graphApp", "grid", "grokApp", "heart", "heartbeatApp", "heatmap", "help", "history", "home", "iInCircle", "image", "importAction", "indexClose", "indexEdit", "indexFlush", "indexManagementApp", "indexMapping", "indexOpen", "indexPatternApp", "indexRollupApp", "indexRuntime", "indexSettings", "inputOutput", "inspect", "integrationGeneral", "integrationObservability", "integrationSearch", "integrationSecurity", "invert", "ip", "keyboardShortcut", "kqlField", "kqlFunction", "kqlOperand", "kqlSelector", "kqlValue", "layers", "lensApp", "lineChart", "link", "list", "listAdd", "lock", "lockOpen", "logsApp", "logoAerospike", "logoApache", "logoAppSearch", "logoAWS", "logoAWSMono", "logoAzure", "logoAzureMono", "logoBeats", "logoBusinessAnalytics", "logoCeph", "logoCloud", "logoCloudEnterprise", "logoCode", "logoCodesandbox", "logoCouchbase", "logoDocker", "logoDropwizard", "logoElastic", "logoElasticsearch", "logoElasticStack", "logoEnterpriseSearch", "logoEtcd", "logoGCP", "logoGCPMono", "logoGithub", "logoGmail", "logoGolang", "logoGoogleG", "logoHAproxy", "logoIBM", "logoIBMMono", "logoKafka", "logoKibana", "logoKubernetes", "logoLogging", "logoLogstash", "logoMaps", "logoMemcached", "logoMetrics", "logoMongodb", "logoMySQL", "logoNginx", "logoObservability", "logoOpenSearch", "logoOsquery", "logoPhp", "logoPostgres", "logoPrometheus", "logoRabbitmq", "logoRedis", "logoSecurity", "logoSiteSearch", "logoSketch", "logoSlack", "logoUptime", "logoWebhook", "logoWindows", "logoWorkplaceSearch", "logstashFilter", "logstashIf", "logstashInput", "logstashOutput", "logstashQueue", "machineLearningApp", "magnet", "magnifyWithMinus", "magnifyWithPlus", "managementApp", "mapMarker", "memory", "menu", "menuDown", "menuLeft", "menuRight", "menuUp", "merge", "metricbeatApp", "metricsApp", "minimize", "minus", "minusInCircle", "minusInCircleFilled", "mobile", "monitoringApp", "moon", "nested", "node", "notebookApp", "number", "offline", "online", "outlierDetectionJob", "package", "packetbeatApp", "pageSelect", "pagesSelect", "partial", "paperClip", "pause", "pencil", "percent", "pin", "pinFilled", "pipelineApp", "play", "playFilled", "plus", "plusInCircle", "plusInCircleFilled", "polygon", "popout", "power", "pulse", "push", "questionInCircle", "quote", "radar", "radius", "recent", "recentlyViewedApp", "redeploy", "refresh", "regressionJob", "reporter", "reportingApp", "returnKey", "rocket", "save", "savedObjectsApp", "scale", "search", "searchProfilerApp", "securityAnalyticsApp", "securityApp", "securitySignal", "securitySignalDetected", "securitySignalResolved", "shard", "share", "snowflake", "sortable", "sortDown", "sortLeft", "sortRight", "sortUp", "spacesApp", "sparkleFilled", "sqlApp", "starEmpty", "starEmptySpace", "starFilled", "starFilledSpace", "starMinusEmpty", "starMinusFilled", "starPlusEmpty", "starPlusFilled", "stats", "stop", "stopFilled", "stopSlash", "storage", "string", "submodule", "swatchInput", "symlink", "tableOfContents", "tableDensityExpanded", "tableDensityCompact", "tableDensityNormal", "tag", "tear", "temperature", "thumbsDown", "thumbsUp", "timeline", "timelionApp", "timeslider", "training", "trash", "upgradeAssistantApp", "uptimeApp", "undeploy", "unfold", "unlink", "user", "users", "usersRolesApp", "vector", "videoPlayer", "visArea", "visAreaStacked", "visBarHorizontal", "visBarHorizontalStacked", "visBarVertical", "visBarVerticalStacked", "visBuilder", "visBuilderSavedObject", "visGauge", "visGoal", "visLine", "visMapCoordinate", "visMapRegion", "visMetric", "visPie", "visQueryDQL", "visQueryPPL", "visQueryPromQL", "visQuerySQL", "visTable", "visTagCloud", "visText", "visTimelion", "visualizeApp", "visVega", "visVisualBuilder", "watchesApp", "wordWrap", "wordWrapDisabled", "workplaceSearchApp", "wrench", "tokenClass", "tokenProperty", "tokenEnum", "tokenVariable", "tokenMethod", "tokenAnnotation", "tokenException", "tokenInterface", "tokenParameter", "tokenField", "tokenElement", "tokenFunction", "tokenBoolean", "tokenString", "tokenArray", "tokenNumber", "tokenConstant", "tokenObject", "tokenEvent", "tokenKey", "tokenNull", "tokenStruct", "tokenPackage", "tokenOperator", "tokenEnumMember", "tokenRepo", "tokenSymbol", "tokenFile", "tokenModule", "tokenNamespace", "tokenDate", "tokenIP", "tokenNested", "tokenAlias", "tokenShape", "tokenGeo", "tokenRange", "tokenBinary", "tokenJoin", "tokenPercolator", "tokenFlattened", "tokenRankFeature", "tokenRankFeatures", "tokenKeyword", "tokenCompletionSuggester", "tokenDenseVector", "tokenText", "tokenTokenCount", "tokenSearchType", "tokenHistogram", "wsAnalytics", "wsEssentials", "wsObservability", "wsSearch", "wsSecurityAnalytics", "wsSelector", "navAdministration", "navAiFlow", "navAlerting", "navAnomalyDetection", "navDashboards", "navData", "navDetectionRules", "navDevtools", "navDiscover", "navExperiments", "navGetStarted", "navInfo", "navInfra", "navIntegrations", "navJudgements", "navManage", "navMaps", "navModels", "navNotebooks", "navNotifications", "navOverview", "navQuerySets", "navReports", "navSecurityCases", "navSecurityFindings", "navServiceMap", "navServices", "navSlos", "navThreatIntel", "navTicketing", "navUi", "navSearchConfigurationsln"]).isRequired, PropTypes.string.isRequired, PropTypes.elementType.isRequired]),
  /**
     * The side of the badge the icon should sit
     */
  iconSide: PropTypes.oneOf(["left", "right"]),
  /**
     * Accepts either our palette colors (primary, success ..etc) or a hex value `#FFFFFF`, `#000`.
     * **`secondary` color is DEPRECATED, use `success` instead**
     */
  color: PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.oneOf(["default", "primary", "secondary", "success", "accent", "warning", "danger", "text", "subdued", "ghost", "inherit"]).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,
  /**
     * 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
};
function getColorContrast(textColor, color) {
  var contrastValue = chroma.contrast(textColor, color);
  return contrastValue;
}
function setTextColor(bgColor) {
  var textColor = isColorDark.apply(void 0, _toConsumableArray(chroma(bgColor).rgb())) ? colorGhost : colorInk;
  return textColor;
}
function handleInvalidColor(color) {
  var isNamedColor = color && COLORS.includes(color) || color === 'hollow';
  var isValidColorString = color && chromaValid(parseColor(color) || '');
  if (!isNamedColor && !isValidColorString) {
    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, "."));
  }
}