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 = ["className", "color", "imageUrl", "initials", "initialsLength", "iconType", "iconSize", "iconColor", "name", "size", "type", "isDisabled", "style"],
  _excluded2 = ["casing"];
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 _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 _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], 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 React, { useMemo } from 'react';
import PropTypes from "prop-types";
import classNames from 'classnames';
import { warnIfContrastBelowMin, wcagContrastMin } from '../../services/color/contrast';
import { isColorDark, hexToRgb, isValidHex, useEuiPaletteColorBlindBehindText } from '../../services/color';
import { toInitials, useEuiMemoizedStyles, useEuiTheme } from '../../services';
import { EuiIcon } from '../icon';
import { euiAvatarStyles } from './avatar.styles';
import { jsx as ___EmotionJSX } from "@emotion/react";
export var SIZES = ['s', 'm', 'l', 'xl'];
export var TYPES = ['space', 'user'];
export var CASING = ['capitalize', 'uppercase', 'lowercase', 'none'];

/**
 * The avatar can only display one type of content,
 * initials, or image, or iconType
 */

export var EuiAvatar = function EuiAvatar(_ref) {
  var className = _ref.className,
    color = _ref.color,
    imageUrl = _ref.imageUrl,
    initials = _ref.initials,
    initialsLength = _ref.initialsLength,
    iconType = _ref.iconType,
    iconSize = _ref.iconSize,
    iconColor = _ref.iconColor,
    name = _ref.name,
    _ref$size = _ref.size,
    size = _ref$size === void 0 ? 'm' : _ref$size,
    _ref$type = _ref.type,
    type = _ref$type === void 0 ? 'user' : _ref$type,
    _ref$isDisabled = _ref.isDisabled,
    isDisabled = _ref$isDisabled === void 0 ? false : _ref$isDisabled,
    style = _ref.style,
    props = _objectWithoutProperties(_ref, _excluded);
  checkValidInitials(initials);
  var _props$casing = props.casing,
    casing = _props$casing === void 0 ? type === 'space' ? 'none' : 'uppercase' : _props$casing,
    rest = _objectWithoutProperties(props, _excluded2);
  var _useEuiTheme = useEuiTheme(),
    highContrastMode = _useEuiTheme.highContrastMode,
    euiTheme = _useEuiTheme.euiTheme;
  var visColors = useEuiPaletteColorBlindBehindText();
  var isPlain = color === 'plain';
  var isSubdued = color === 'subdued';
  var isNamedColor = isPlain || isSubdued || color === null;
  var isForcedColors = highContrastMode === 'forced';
  var classes = classNames('euiAvatar', _defineProperty(_defineProperty(_defineProperty({}, "euiAvatar--".concat(size), size), "euiAvatar--".concat(type), type), 'euiAvatar-isDisabled', isDisabled), className);
  var styles = useEuiMemoizedStyles(euiAvatarStyles);
  var cssStyles = [styles.euiAvatar, styles[type], styles[size], styles[casing], isPlain && styles.plain, isSubdued && styles.subdued, isDisabled && styles.isDisabled];
  var avatarStyle = useMemo(function () {
    if (imageUrl) {
      return {
        backgroundImage: "url(".concat(imageUrl, ")")
      };
    }
    if (!isNamedColor) {
      checkValidColor(color);
      var assignedColor = color || visColors[Math.floor(name.length % visColors.length)];
      var textColor = isColorDark.apply(void 0, _toConsumableArray(hexToRgb(assignedColor))) ? '#FFFFFF' : '#000000';
      warnIfContrastBelowMin(textColor, assignedColor, wcagContrastMin);
      return {
        backgroundColor: assignedColor,
        color: textColor
      };
    }
  }, [imageUrl, color, isNamedColor, name.length, visColors]);
  var highContrastBorder = useMemo(
  // Render a border since background-colors are ignored in Windows forced contrast themes
  function () {
    return isForcedColors ? {
      border: euiTheme.border.thin
    } : undefined;
  }, [isForcedColors, euiTheme]);
  var iconCustomColor = useMemo(function () {
    // Force icons to single colors in forced high contrast mode
    if (isForcedColors) return euiTheme.colors.fullShade;
    // `null` allows icons to keep their default color (e.g. app icons)
    if (iconColor === null) return undefined;
    // Otherwise continue to pass on `iconColor`
    if (iconColor) return iconColor;
    // Fall back to the adjusted text color if it exists
    return avatarStyle === null || avatarStyle === void 0 ? void 0 : avatarStyle.color;
  }, [iconColor, avatarStyle === null || avatarStyle === void 0 ? void 0 : avatarStyle.color, isForcedColors, euiTheme]);
  return ___EmotionJSX("div", _extends({
    css: cssStyles,
    className: classes,
    style: _objectSpread(_objectSpread(_objectSpread({}, style), avatarStyle), highContrastBorder),
    "aria-label": isDisabled ? undefined : name,
    role: isDisabled ? 'presentation' : 'img',
    title: name
  }, rest), !imageUrl && (iconType ? ___EmotionJSX(EuiIcon, {
    className: "euiAvatar__icon",
    size: iconSize || size,
    type: iconType,
    color: iconCustomColor
  }) : ___EmotionJSX("span", {
    "aria-hidden": "true"
  }, toInitials(name, initialsLength, initials))));
};

// TODO: Migrate to a service
EuiAvatar.propTypes = {
  className: PropTypes.string,
  "aria-label": PropTypes.string,
  "data-test-subj": PropTypes.string,
  css: PropTypes.any,
  /**
         * Custom initials (max 2 characters).
         * By default will take the first character (of each word).
         */
  initials: PropTypes.string,
  /**
         * Specify how many characters to show (1 or 2).
         * By default, will show based on number of words (max first 2).
         */
  initialsLength: PropTypes.oneOf([1, 2]),
  /**
         * Path to an image to display instead of initials
         */
  imageUrl: PropTypes.string,
  /**
       * Any EUI glyph, logo or custom icon to display instead of initials
       */
  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", "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", "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]),
  /**
       * Manually change icon size
       */
  iconSize: PropTypes.any,
  /**
       * Manually change icon color
       */
  iconColor: PropTypes.oneOfType([PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.any.isRequired]).isRequired, PropTypes.oneOf([null])]),
  /**
       * Full name of avatar for title attribute and calculating initial if not provided
       */
  name: PropTypes.string.isRequired,
  /**
       * Accepts hex values like `#FFFFFF`, `#000` otherwise a viz palette color will be assigned.
       * Or pass `'plain'` for an empty shade, `'subdued'` for a light gray shade or `null` to remove entirely and the text/icon color will `inherit`
       */
  color: PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.oneOf(["plain", "subdued", null])]),
  /**
       * The type of avatar mainly controlling the shape.
       * `user` = circle
       * `space` = rounded square
       */
  type: PropTypes.any,
  size: PropTypes.any,
  /**
       * Sets the letter casing of the displayed initials.
       * Defaults to `uppercase` for `type="user"` avatars.
       * Defaults to `none` (uses the existing casing of the passed `name` or `initials`) for `type="space"` avatars.
       * @default uppercase
       */
  casing: PropTypes.any,
  /**
       * Grays out the avatar to simulate being disabled
       */
  isDisabled: PropTypes.bool
};
export var checkValidColor = function checkValidColor(color) {
  var validHex = color && isValidHex(color) || color === 'plain' || color === 'subdued';
  if (color && !validHex) {
    throw new Error('EuiAvatar needs to pass a valid color. This can either be a three ' + 'or six character hex value');
  }
};
function checkValidInitials(initials) {
  // Must be a string of 1 or 2 characters
  if (initials && initials.length > 2) {
    console.warn('EuiAvatar only accepts a max of 2 characters for the initials as a string. It is displaying only the first 2 characters.');
  }
}