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 _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 _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 { keysOf } from '../common';
import classNames from 'classnames';
import { isColorDark, hexToRgb, isValidHex } from '../../services/color';
import { ouiPaletteColorBlindBehindText, toInitials } from '../../services';
import { OuiIcon } from '../icon';
var sizeToClassNameMap = {
  s: 'ouiAvatar--s',
  m: 'ouiAvatar--m',
  l: 'ouiAvatar--l',
  xl: 'ouiAvatar--xl'
};
export var SIZES = keysOf(sizeToClassNameMap);
var typeToClassNameMap = {
  space: 'ouiAvatar--space',
  user: 'ouiAvatar--user'
};
export var TYPES = keysOf(typeToClassNameMap);

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

export var OuiAvatar = function OuiAvatar(_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,
    rest = _objectWithoutProperties(_ref, ["className", "color", "imageUrl", "initials", "initialsLength", "iconType", "iconSize", "iconColor", "name", "size", "type", "isDisabled", "style"]);
  var visColors = ouiPaletteColorBlindBehindText();
  var classes = classNames('ouiAvatar', sizeToClassNameMap[size], typeToClassNameMap[type], {
    'ouiAvatar-isDisabled': isDisabled,
    'ouiAvatar--plain': color === 'plain'
  }, className);
  checkValidInitials(initials);
  var avatarStyle = style || {};
  var iconCustomColor = iconColor;
  var isNamedColor = color === 'plain' || color === null;
  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';
    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 = toInitials(name, initialsLength, initials);
    content = /*#__PURE__*/React.createElement("span", {
      "aria-hidden": "true"
    }, calculatedInitials);
  } else if (iconType) {
    content = /*#__PURE__*/React.createElement(OuiIcon, {
      className: "ouiAvatar__icon",
      size: iconSize || size,
      type: iconType,
      "aria-label": name,
      color: iconCustomColor === null ? undefined : iconCustomColor
    });
  }
  return /*#__PURE__*/React.createElement("div", _extends({
    className: classes,
    style: avatarStyle,
    "aria-label": name,
    title: name
  }, rest), content);
};

// TODO: Migrate to a service
OuiAvatar.propTypes = {
  className: PropTypes.string,
  "aria-label": PropTypes.string,
  "data-test-subj": PropTypes.string,
  /**
         * 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 OUI glyph, logo or custom icon to display instead of initials
       */
  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]),
  /**
       * Manually change icon size
       */
  iconSize: PropTypes.oneOf(["original", "s", "m", "l", "xl", "xxl"]),
  /**
       * Manually change icon color
       */
  iconColor: PropTypes.oneOfType([PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.oneOf(["default", "primary", "secondary", "success", "accent", "warning", "danger", "text", "subdued", "ghost", "inherit"]).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 or `null` to remove entirely and the text/icon color will `inherit`
       */
  color: PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.oneOf(["plain", null])]),
  /**
       * The type of avatar mainly controlling the shape.
       * `user` = circle
       * `space` = rounded square
       */
  type: PropTypes.oneOf(["space", "user"]),
  size: PropTypes.oneOf(["s", "m", "l", "xl"]),
  /**
       * Grays out the avatar to simulate being disabled
       */
  isDisabled: PropTypes.bool
};
export var checkValidColor = function checkValidColor(color) {
  var validHex = color && isValidHex(color) || color === 'plain';
  if (color && !validHex) {
    throw new Error('OuiAvatar 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('OuiAvatar only accepts a max of 2 characters for the initials as a string. It is displaying only the first 2 characters.');
  }
}

/* OUI -> EUI Aliases: Build-Time */
/* OUI -> EUI Aliases: Build-Time */export { EuiAvatar } from '../../eui_components/avatar/avatar';