@elastic/eui
Version:
Elastic UI Component Library
212 lines (207 loc) • 21.3 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.checkValidColor = exports.TYPES = exports.SIZES = exports.EuiAvatar = exports.CASING = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _classnames = _interopRequireDefault(require("classnames"));
var _contrast = require("../../services/color/contrast");
var _color = require("../../services/color");
var _services = require("../../services");
var _icon = require("../icon");
var _tool_tip = require("../tool_tip");
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 _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
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) { (0, _defineProperty2.default)(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; }
var SIZES = exports.SIZES = ['s', 'm', 'l', 'xl'];
var TYPES = exports.TYPES = ['space', 'user'];
var CASING = exports.CASING = ['capitalize', 'uppercase', 'lowercase', 'none'];
/**
* The avatar can only display one type of content,
* initials, or image, or iconType
*/
var EuiAvatar = exports.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 = (0, _objectWithoutProperties2.default)(_ref, _excluded);
checkValidInitials(initials);
var _props$casing = props.casing,
casing = _props$casing === void 0 ? type === 'space' ? 'none' : 'uppercase' : _props$casing,
rest = (0, _objectWithoutProperties2.default)(props, _excluded2);
var _useEuiTheme = (0, _services.useEuiTheme)(),
highContrastMode = _useEuiTheme.highContrastMode,
euiTheme = _useEuiTheme.euiTheme;
var visColors = (0, _color.useEuiPaletteColorBlindBehindText)();
var isPlain = color === 'plain';
var isSubdued = color === 'subdued';
var isNamedColor = isPlain || isSubdued || color === null;
var isForcedColors = highContrastMode === 'forced';
var classes = (0, _classnames.default)('euiAvatar', (0, _defineProperty2.default)((0, _defineProperty2.default)((0, _defineProperty2.default)({}, "euiAvatar--".concat(size), size), "euiAvatar--".concat(type), type), 'euiAvatar-isDisabled', isDisabled), className);
var styles = (0, _services.useEuiMemoizedStyles)(_avatar.euiAvatarStyles);
var cssStyles = [styles.euiAvatar, styles[type], styles[size], styles[casing], isPlain && styles.plain, isSubdued && styles.subdued, isDisabled && styles.isDisabled];
var tooltipCssStyles = [styles.tooltip[type]];
var avatarStyle = (0, _react.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 = _color.isColorDark.apply(void 0, (0, _toConsumableArray2.default)((0, _color.hexToRgb)(assignedColor))) ? '#FFFFFF' : '#000000';
(0, _contrast.warnIfContrastBelowMin)(textColor, assignedColor, _contrast.wcagContrastMin);
return {
backgroundColor: assignedColor,
color: textColor
};
}
}, [imageUrl, color, isNamedColor, name.length, visColors]);
var highContrastBorder = (0, _react.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 = (0, _react.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]);
var avatarNode = (0, _react2.jsx)("div", (0, _extends2.default)({
css: cssStyles,
className: classes,
style: _objectSpread(_objectSpread(_objectSpread({}, style), avatarStyle), highContrastBorder),
"aria-label": isDisabled ? undefined : name,
role: isDisabled ? 'presentation' : 'img'
}, rest), !imageUrl && (iconType ? (0, _react2.jsx)(_icon.EuiIcon, {
className: "euiAvatar__icon",
size: iconSize || size,
type: iconType,
color: iconCustomColor,
"aria-hidden": true
}) : (0, _react2.jsx)("span", {
"aria-hidden": "true"
}, (0, _services.toInitials)(name, initialsLength, initials))));
// `EuiAvatar` is not interactive so we don't need to add a `tabIndex`.
// It already has `aria-label`, the tooltip is only visual.
return name ? (0, _react2.jsx)(_tool_tip.EuiToolTip, {
content: name,
anchorProps: {
css: tooltipCssStyles
},
disableScreenReaderOutput: true
}, avatarNode) : avatarNode;
};
// TODO: Migrate to a service
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", "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", "logoVectorDB", "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", "significantEvents", "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.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 the avatar. Used as the accessible label (`aria-label`),
* tooltip content and used to derive initials when `initials` is 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 = exports.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');
}
};
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.');
}
}