@elastic/eui
Version:
Elastic UI Component Library
191 lines (189 loc) • 16.3 kB
JavaScript
var _excluded = ["className", "id", "isDisabled", "isIconOnly", "isSelected", "label", "name", "onChange", "size", "value", "color", "element", "type"];
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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
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; }
/*
* 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 classNames from 'classnames';
import PropTypes from "prop-types";
import React from 'react';
import { useEuiTheme } from '../../../services';
import { useEuiButtonColorCSS } from '../../../themes/amsterdam/global_styling/mixins/button';
import { useInnerText } from '../../inner_text';
import { EuiButtonDisplay } from '../button_display/_button_display';
import { euiButtonGroupButtonStyles, _compressedButtonFocusColor, _uncompressedButtonFocus } from './button_group_button.styles';
import { jsx as ___EmotionJSX } from "@emotion/react";
export var EuiButtonGroupButton = function EuiButtonGroupButton(_ref) {
var className = _ref.className,
id = _ref.id,
isDisabled = _ref.isDisabled,
isIconOnly = _ref.isIconOnly,
_ref$isSelected = _ref.isSelected,
isSelected = _ref$isSelected === void 0 ? false : _ref$isSelected,
label = _ref.label,
name = _ref.name,
_onChange = _ref.onChange,
size = _ref.size,
value = _ref.value,
_ref$color = _ref.color,
_color = _ref$color === void 0 ? 'primary' : _ref$color,
_ref$element = _ref.element,
_element = _ref$element === void 0 ? 'button' : _ref$element,
_ref$type = _ref.type,
type = _ref$type === void 0 ? 'button' : _ref$type,
rest = _objectWithoutProperties(_ref, _excluded);
// Force element to be a button if disabled
var element = isDisabled ? 'button' : _element;
var elementProps = {};
var singleInput;
if (element === 'label') {
singleInput = ___EmotionJSX("input", {
className: "euiScreenReaderOnly",
name: name,
checked: isSelected,
disabled: isDisabled,
value: value,
type: "radio",
onChange: function onChange() {
return _onChange(id, value);
},
"data-test-subj": id
});
} else {
elementProps = {
'data-test-subj': id,
isSelected: isSelected,
type: type,
onClick: function onClick() {
return _onChange(id);
}
};
}
var isCompressed = size === 'compressed';
var color = isDisabled ? 'disabled' : _color;
var display = isSelected ? 'fill' : isCompressed ? 'empty' : 'base';
var euiTheme = useEuiTheme();
var buttonColorStyles = useEuiButtonColorCSS({
display: display
})[color];
var focusColorStyles = isCompressed ? _compressedButtonFocusColor(euiTheme, color) : _uncompressedButtonFocus(euiTheme);
var styles = euiButtonGroupButtonStyles(euiTheme);
var cssStyles = [styles.euiButtonGroupButton, isIconOnly && styles.iconOnly, styles[size], !isCompressed && styles.uncompressed, isDisabled && isSelected ? styles.disabledAndSelected : buttonColorStyles, !isDisabled && focusColorStyles];
var contentStyles = [styles.content.euiButtonGroupButton__content, isCompressed && styles.content.compressed];
var textStyles = [isIconOnly ? styles.text.euiButtonGroupButton__iconOnly : styles.text.euiButtonGroupButton__text];
var buttonClasses = classNames('euiButtonGroupButton', {
'euiButtonGroupButton-isSelected': isSelected,
'euiButtonGroupButton-isIconOnly': isIconOnly
}, className);
/**
* Because the selected buttons also increase their text weight to 'bold',
* we don't want the whole button size to shift when selected, so we determine
* the base width of the button via the `euiTextShift()` method in SASS.
*/
var _useInnerText = useInnerText(),
_useInnerText2 = _slicedToArray(_useInnerText, 2),
buttonTextRef = _useInnerText2[0],
innerText = _useInnerText2[1];
return ___EmotionJSX(EuiButtonDisplay, _extends({
css: cssStyles,
className: buttonClasses,
element: element,
isDisabled: isDisabled,
size: size === 'compressed' ? 's' : size,
contentProps: {
css: contentStyles
},
textProps: {
css: textStyles,
ref: buttonTextRef,
'data-text': innerText
},
title: innerText
}, elementProps, rest), singleInput, label);
};
EuiButtonGroupButton.propTypes = {
/**
* Each option must have a unique `id` for maintaining selection
*/
id: PropTypes.string.isRequired,
/**
* Each option must have a `label` even for icons which will be applied as the `aria-label`
*/
label: PropTypes.node.isRequired,
isDisabled: PropTypes.bool,
/**
* The value of the radio input for 'single'.
*/
/**
* The value of the radio input.
*/
value: PropTypes.oneOfType([PropTypes.any, PropTypes.string]),
/**
* The type of the underlying HTML button
*/
type: PropTypes.oneOf(["button", "submit", "reset"]),
/**
* Any `type` accepted by EuiIcon
*/
iconType: PropTypes.oneOfType([PropTypes.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", "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", "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", "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.string.isRequired, PropTypes.elementType.isRequired]),
/**
* Can only be one side `left` or `right`
*/
iconSide: PropTypes.oneOfType([PropTypes.any.isRequired, PropTypes.oneOf([undefined])]),
isLoading: PropTypes.bool,
/**
* Object of props passed to the <span/> wrapping the content's text/children only (not icon)
*/
textProps: PropTypes.shape({
className: PropTypes.string,
"aria-label": PropTypes.string,
"data-test-subj": PropTypes.string,
css: PropTypes.any,
ref: PropTypes.any,
"data-text": PropTypes.string
}),
iconSize: PropTypes.any,
className: PropTypes.string,
"aria-label": PropTypes.string,
"data-test-subj": PropTypes.string,
css: PropTypes.any,
/**
* Element to display based on single or multi
*/
element: PropTypes.oneOf(["button", "label"]).isRequired,
/**
* Styles the selected button to look selected (usually with `fill`)
*/
isSelected: PropTypes.bool,
/**
* Name of the whole group for 'single'.
*/
name: PropTypes.string,
/**
* Inherit from EuiButtonGroup
*/
color: PropTypes.any.isRequired,
/**
* Inherit from EuiButtonGroup
*/
size: PropTypes.oneOf(["s", "m", "compressed"]).isRequired,
/**
* Inherit from EuiButtonGroup
*/
isIconOnly: PropTypes.bool.isRequired,
/**
* Inherit from EuiButtonGroup
*/
onChange: PropTypes.func.isRequired
};