UNPKG

@elastic/eui

Version:

Elastic UI Component Library

215 lines (211 loc) 19.1 kB
var _excluded = ["className", "iconType", "iconSize", "color", "isDisabled", "disabled", "hasAriaDisabled", "href", "type", "display", "target", "rel", "size", "buttonRef", "isSelected", "isLoading"], _excluded2 = ["ref"]; 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 _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 from 'react'; import PropTypes from "prop-types"; import classNames from 'classnames'; import { getSecureRelForTarget, useCombinedRefs, useEuiMemoizedStyles } from '../../../services'; import { useEuiDisabledElement } from '../../../services/hooks/useEuiDisabledElement'; import { EuiIcon } from '../../icon'; import { EuiLoadingSpinner } from '../../loading'; import { useEuiButtonColorCSS, useEuiButtonFocusCSS } from '../../../global_styling/mixins/_button'; import { isButtonDisabled } from '../button_display/_button_display'; import { euiButtonIconStyles } from './button_icon.styles'; import { jsx as ___EmotionJSX } from "@emotion/react"; export var SIZES = ['xs', 's', 'm']; export var DISPLAYS = ['base', 'empty', 'fill']; export var EuiButtonIcon = function EuiButtonIcon(_ref) { var className = _ref.className, iconType = _ref.iconType, _ref$iconSize = _ref.iconSize, iconSize = _ref$iconSize === void 0 ? 'm' : _ref$iconSize, _ref$color = _ref.color, color = _ref$color === void 0 ? 'primary' : _ref$color, _isDisabled = _ref.isDisabled, disabled = _ref.disabled, _ref$hasAriaDisabled = _ref.hasAriaDisabled, hasAriaDisabled = _ref$hasAriaDisabled === void 0 ? false : _ref$hasAriaDisabled, href = _ref.href, _ref$type = _ref.type, type = _ref$type === void 0 ? 'button' : _ref$type, _ref$display = _ref.display, display = _ref$display === void 0 ? 'empty' : _ref$display, target = _ref.target, rel = _ref.rel, _ref$size = _ref.size, size = _ref$size === void 0 ? 'xs' : _ref$size, buttonRef = _ref.buttonRef, isSelected = _ref.isSelected, isLoading = _ref.isLoading, rest = _objectWithoutProperties(_ref, _excluded); var isDisabled = isButtonDisabled({ isDisabled: _isDisabled || disabled, href: href, isLoading: isLoading }); var _useEuiDisabledElemen = useEuiDisabledElement({ isDisabled: isDisabled, hasAriaDisabled: hasAriaDisabled, onKeyDown: rest.onKeyDown }), disabledRef = _useEuiDisabledElemen.ref, disabledButtonProps = _objectWithoutProperties(_useEuiDisabledElemen, _excluded2); var setCombinedRef = useCombinedRefs([disabledRef, buttonRef]); var ariaHidden = rest['aria-hidden']; var isAriaHidden = ariaHidden === 'true' || ariaHidden === true; if (!rest['aria-label'] && !rest['aria-labelledby'] && !isAriaHidden) { console.warn("EuiButtonIcon requires aria-label or aria-labelledby to be specified because icon-only\n buttons are screen-reader-inaccessible without them."); } var buttonColorStyles = useEuiButtonColorCSS({ display: display }); var buttonFocusStyle = useEuiButtonFocusCSS(); var styles = useEuiMemoizedStyles(euiButtonIconStyles); var cssStyles = [styles.euiButtonIcon, styles[size], buttonColorStyles[isDisabled ? 'disabled' : color], buttonFocusStyle, isDisabled && styles.isDisabled]; var classes = classNames('euiButtonIcon', className); // Add an icon to the button if one exists. var buttonIcon; if (iconType && !isLoading) { buttonIcon = ___EmotionJSX(EuiIcon, { className: "euiButtonIcon__icon", type: iconType, size: iconSize, "aria-hidden": "true", color: "inherit" // forces the icon to inherit its parent color }); } if (iconType && isLoading) { // `original` size doesn't exist in `EuiLoadingSpinner` // when the `iconSize` is `original` we don't pass any size to the `EuiLoadingSpinner` // so it gets the default size var loadingSize = iconSize === 'original' ? undefined : iconSize; // When the button is disabled the text gets gray // and in some buttons the background gets a light gray // for better contrast we want to change the border of the spinner // to have the same color of the text. This way we ensure the borders // are always visible. The default spinner color could be very light. var loadingSpinnerColor = isDisabled ? { border: 'currentcolor' } : undefined; buttonIcon = ___EmotionJSX(EuiLoadingSpinner, { size: loadingSize, color: loadingSpinnerColor }); } // <a> elements don't respect the `disabled` attribute. So if we're disabled, we'll just pretend // this is a button and piggyback off its disabled styles. if (href && !isDisabled) { var secureRel = getSecureRelForTarget({ href: href, target: target, rel: rel }); return ___EmotionJSX("a", _extends({ css: cssStyles, tabIndex: isAriaHidden ? -1 : undefined, className: classes, href: href, target: target, rel: secureRel, ref: setCombinedRef }, rest), buttonIcon); } var buttonType; return ___EmotionJSX("button", _extends({ css: cssStyles, tabIndex: isAriaHidden ? -1 : undefined, disabled: isDisabled, className: classes, "aria-pressed": isSelected, type: type, ref: setCombinedRef }, rest, disabledButtonProps), buttonIcon); }; EuiButtonIcon.propTypes = { type: PropTypes.any, href: PropTypes.string, onClick: PropTypes.func, 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", "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.string.isRequired, PropTypes.elementType.isRequired]).isRequired, /** * Any of the named color palette options. * * Do not use the following colors for standalone buttons directly, * they exist to serve other components: * - accent * - warning * - neutral * - risk */ color: PropTypes.any, "aria-label": PropTypes.string, "aria-labelledby": PropTypes.string, /** * Overall size of button. * Matches the sizes of other EuiButtons */ /** * Overall size of button. * Matches the sizes of other EuiButtons */ size: PropTypes.any, /** * Size of the icon only. * This will not affect the overall size of the button */ iconSize: PropTypes.any, /** * Applies the boolean state as the `aria-pressed` property to create a toggle button. * *Only use when the readable text does not change between states.* */ /** * Applies the boolean state as the `aria-pressed` property to create a toggle button. * *Only use when the readable text does not change between states.* */ isSelected: PropTypes.bool, /** * Sets the display style for matching other EuiButton types. * `base` is equivalent to a typical EuiButton * `fill` is equivalent to a filled EuiButton * `empty` (default) is equivalent to an EuiButtonEmpty */ /** * Sets the display style for matching other EuiButton types. * `base` is equivalent to a typical EuiButton * `fill` is equivalent to a filled EuiButton * `empty` (default) is equivalent to an EuiButtonEmpty */ display: PropTypes.any, /** * Disables the button and changes the icon to a loading spinner */ /** * Disables the button and changes the icon to a loading spinner */ isLoading: PropTypes.bool, className: PropTypes.string, "data-test-subj": PropTypes.string, css: PropTypes.any, /** * Controls the disabled behavior via the native `disabled` attribute. */ isDisabled: PropTypes.bool, /** * NOTE: Beta feature, may be changed or removed in the future * * Changes the native `disabled` attribute to `aria-disabled` to preserve focusability. * This results in a semantically disabled button without the default browser handling of the disabled state. * * Use e.g. when a disabled button should have a tooltip. */ hasAriaDisabled: PropTypes.bool, buttonRef: PropTypes.any };