"use strict";

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); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.checkValidColor = exports.TYPES = exports.SIZES = exports.EuiAvatar = exports.CASING = void 0;
var _react = _interopRequireDefault(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _classnames = _interopRequireDefault(require("classnames"));
var _color = require("../../services/color");
var _services = require("../../services");
var _icon = require("../icon");
var _avatar = require("./avatar.styles");
var _react2 = require("@emotion/react");
var _excluded = ["className", "color", "imageUrl", "initials", "initialsLength", "iconType", "iconSize", "iconColor", "name", "size", "type", "isDisabled", "style"],
  _excluded2 = ["casing"];
/*
 * 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.
 */
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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(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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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 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; }
var SIZES = ['s', 'm', 'l', 'xl'];
exports.SIZES = SIZES;
var TYPES = ['space', 'user'];
exports.TYPES = TYPES;
var CASING = ['capitalize', 'uppercase', 'lowercase', 'none'];

/**
 * The avatar can only display one type of content,
 * initials, or image, or iconType
 */
exports.CASING = CASING;
var EuiAvatar = function EuiAvatar(_ref) {
  var _classNames;
  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);
  var _props$casing = props.casing,
    casing = _props$casing === void 0 ? type === 'space' ? 'none' : 'uppercase' : _props$casing,
    rest = _objectWithoutProperties(props, _excluded2);
  var euiTheme = (0, _services.useEuiTheme)();
  var styles = (0, _avatar.euiAvatarStyles)(euiTheme);
  var visColors = (0, _services.euiPaletteColorBlindBehindText)();
  var isPlain = color === 'plain';
  var isSubdued = color === 'subdued';
  var classes = (0, _classnames.default)('euiAvatar', (_classNames = {}, _defineProperty(_classNames, "euiAvatar--".concat(size), size), _defineProperty(_classNames, "euiAvatar--".concat(type), type), _defineProperty(_classNames, 'euiAvatar-isDisabled', isDisabled), _classNames), className);
  var cssStyles = [styles.euiAvatar, styles[type], styles[size], styles[casing], isPlain && styles.plain, isSubdued && styles.subdued, isDisabled && styles.isDisabled];
  checkValidInitials(initials);
  var avatarStyle = _objectSpread({}, style);
  var iconCustomColor = iconColor;
  var isNamedColor = color === 'plain' || color === 'subdued' || color === null;
  if (!isNamedColor) {
    checkValidColor(color);
    var assignedColor = color || visColors[Math.floor(name.length % visColors.length)];
    var textColor = _color.isColorDark.apply(void 0, _toConsumableArray((0, _color.hexToRgb)(assignedColor))) ? '#FFFFFF' : '#000000';
    avatarStyle.backgroundColor = assignedColor;
    avatarStyle.color = textColor;

    // Allow consumers to let the icons keep their default color (like app icons)
    // when passing `iconColor = null`, otherwise continue to pass on `iconColor` or adjust with textColor
    iconCustomColor = iconColor || iconColor === null ? iconColor : textColor;
  }
  if (imageUrl) {
    avatarStyle.backgroundImage = "url(".concat(imageUrl, ")");
  }
  var content;
  if (!imageUrl && !iconType) {
    // Create the initials
    var calculatedInitials = (0, _services.toInitials)(name, initialsLength, initials);
    content = (0, _react2.jsx)("span", {
      "aria-hidden": "true"
    }, calculatedInitials);
  } else if (iconType) {
    content = (0, _react2.jsx)(_icon.EuiIcon, {
      className: "euiAvatar__icon",
      size: iconSize || size,
      type: iconType,
      color: iconCustomColor === null ? undefined : iconCustomColor
    });
  }
  return (0, _react2.jsx)("div", _extends({
    css: cssStyles,
    className: classes,
    style: avatarStyle,
    "aria-label": isDisabled ? undefined : name,
    role: isDisabled ? 'presentation' : 'img',
    title: name
  }, rest), content);
};

// TODO: Migrate to a service
exports.EuiAvatar = EuiAvatar;
EuiAvatar.propTypes = {
  className: _propTypes.default.string,
  "aria-label": _propTypes.default.string,
  "data-test-subj": _propTypes.default.string,
  css: _propTypes.default.any,
  /**
         * Custom initials (max 2 characters).
         * By default will take the first character (of each word).
         */
  initials: _propTypes.default.string,
  /**
         * Specify how many characters to show (1 or 2).
         * By default, will show based on number of words (max first 2).
         */
  initialsLength: _propTypes.default.oneOf([1, 2]),
  /**
         * Path to an image to display instead of initials
         */
  imageUrl: _propTypes.default.string,
  /**
       * Any EUI glyph, logo or custom icon to display instead of initials
       */
  iconType: _propTypes.default.oneOfType([_propTypes.default.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", "grabOmnidirectional", "gradient", "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", "palette", "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", "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", "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.default.string.isRequired, _propTypes.default.elementType.isRequired]),
  /**
       * Manually change icon size
       */
  iconSize: _propTypes.default.any,
  /**
       * Manually change icon color
       */
  iconColor: _propTypes.default.oneOfType([_propTypes.default.oneOfType([_propTypes.default.string.isRequired, _propTypes.default.any.isRequired]).isRequired, _propTypes.default.oneOf([null])]),
  /**
       * Full name of avatar for title attribute and calculating initial if not provided
       */
  name: _propTypes.default.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.default.oneOfType([_propTypes.default.string.isRequired, _propTypes.default.oneOf(["plain", "subdued", null])]),
  /**
       * The type of avatar mainly controlling the shape.
       * `user` = circle
       * `space` = rounded square
       */
  type: _propTypes.default.any,
  size: _propTypes.default.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.default.any,
  /**
       * Grays out the avatar to simulate being disabled
       */
  isDisabled: _propTypes.default.bool
};
var checkValidColor = function checkValidColor(color) {
  var validHex = color && (0, _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');
  }
};
exports.checkValidColor = checkValidColor;
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.');
  }
}