Socket
Socket
Sign inDemoInstall

terra-button

Package Overview
Dependencies
Maintainers
7
Versions
146
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

terra-button - npm Package Compare versions

Comparing version 3.68.0 to 3.68.1

5

CHANGELOG.md

@@ -5,2 +5,7 @@ # Changelog

## 3.68.1 - (August 25, 2023)
* Fixed
* Reverted change from functional component to class component to fix an issue with passing refs into the component.
## 3.68.0 - (August 11, 2023)

@@ -7,0 +12,0 @@

397

lib/Button.js
"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); }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {

@@ -8,3 +8,3 @@ value: true

exports.default = exports.ButtonVariants = exports.ButtonTypes = void 0;
var _react = _interopRequireWildcard(require("react"));
var _react = _interopRequireDefault(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));

@@ -16,15 +16,21 @@ var _classnames = _interopRequireDefault(require("classnames"));

var _ButtonModule = _interopRequireDefault(require("./Button.module.scss"));
var _excluded = ["href", "icon", "isBlock", "isCompact", "isDisabled", "isIconOnly", "isReversed", "onBlur", "onClick", "onFocus", "onKeyDown", "onKeyUp", "onMouseDown", "refCallback", "text", "title", "type", "variant"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _excluded = ["icon", "isBlock", "isCompact", "isDisabled", "isIconOnly", "isReversed", "text", "type", "variant", "href", "onClick", "onMouseDown", "onBlur", "onFocus", "onKeyDown", "onKeyUp", "refCallback", "title"];
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
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 _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; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
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 _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var cx = _bind.default.bind(_ButtonModule.default);

@@ -136,172 +142,229 @@ var ButtonVariants = {

};
var Button = function Button(_ref) {
var href = _ref.href,
icon = _ref.icon,
isBlock = _ref.isBlock,
isCompact = _ref.isCompact,
isDisabled = _ref.isDisabled,
isIconOnly = _ref.isIconOnly,
isReversed = _ref.isReversed,
onBlur = _ref.onBlur,
onClick = _ref.onClick,
onFocus = _ref.onFocus,
onKeyDown = _ref.onKeyDown,
onKeyUp = _ref.onKeyUp,
onMouseDown = _ref.onMouseDown,
refCallback = _ref.refCallback,
text = _ref.text,
title = _ref.title,
type = _ref.type,
variant = _ref.variant,
customProps = _objectWithoutProperties(_ref, _excluded);
var theme = (0, _react.useContext)(_terraThemeContext.default);
var Button = /*#__PURE__*/function (_React$Component) {
_inherits(Button, _React$Component);
var _super = _createSuper(Button);
function Button(props) {
var _this;
_classCallCheck(this, Button);
_this = _super.call(this, props);
_this.state = {
active: false,
focused: false
};
_this.handleKeyDown = _this.handleKeyDown.bind(_assertThisInitialized(_this));
_this.handleKeyUp = _this.handleKeyUp.bind(_assertThisInitialized(_this));
_this.handleOnBlur = _this.handleOnBlur.bind(_assertThisInitialized(_this));
_this.handleFocus = _this.handleFocus.bind(_assertThisInitialized(_this));
_this.handleMouseDown = _this.handleMouseDown.bind(_assertThisInitialized(_this));
_this.handleClick = _this.handleClick.bind(_assertThisInitialized(_this));
_this.shouldShowFocus = true;
return _this;
}
_createClass(Button, [{
key: "handleOnBlur",
value: function handleOnBlur(event) {
this.setState({
focused: false
});
if (this.props.onBlur) {
this.props.onBlur(event);
}
}
}, {
key: "handleClick",
value: function handleClick(event) {
// See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Button#Clicking_and_focus
// Button on Firefox, Safari and IE running on OS X does not receive focus when clicked.
// This will put focus on the button when clicked if it is not currently the active element.
if (document.activeElement !== event.currentTarget) {
this.shouldShowFocus = false;
event.currentTarget.focus();
this.shouldShowFocus = true;
}
if (this.props.onClick) {
this.props.onClick(event);
}
}
}, {
key: "handleKeyDown",
value: function handleKeyDown(event) {
// Add active state to FF browsers
if (event.nativeEvent.keyCode === KeyCode.KEY_SPACE) {
this.setState({
active: true
});
// We need to manually control active state for FF compatibility
var _useState = (0, _react.useState)(false),
_useState2 = _slicedToArray(_useState, 2),
isActive = _useState2[0],
setIsActive = _useState2[1];
// Follow href on space keydown when rendered as an anchor tag
if (this.props.href) {
// Prevent window scrolling
event.preventDefault();
window.location.href = this.props.href;
}
}
// We manually control focus behaviors for keyboard events.
var _useState3 = (0, _react.useState)(false),
_useState4 = _slicedToArray(_useState3, 2),
isFocused = _useState4[0],
setIsFocused = _useState4[1];
(0, _react.useEffect)(function () {
// Disabling button does not trigger onBlur, we need to manually unfocus
if (isDisabled) {
setIsFocused(false);
// Add focus styles for keyboard navigation
if (event.nativeEvent.keyCode === KeyCode.KEY_SPACE || event.nativeEvent.keyCode === KeyCode.KEY_RETURN) {
this.setState({
focused: true
});
}
if (this.props.onKeyDown) {
this.props.onKeyDown(event);
}
}
}, [isDisabled]);
var handleOnBlur = function handleOnBlur(event) {
setIsFocused(false);
if (onBlur) {
onBlur(event);
}, {
key: "handleKeyUp",
value: function handleKeyUp(event) {
// Remove active state from FF broswers
if (event.nativeEvent.keyCode === KeyCode.KEY_SPACE) {
this.setState({
active: false
});
}
// Apply focus styles for keyboard navigation
if (event.nativeEvent.keyCode === KeyCode.KEY_TAB) {
this.setState({
focused: true
});
}
if (this.props.onKeyUp) {
this.props.onKeyUp(event);
}
}
};
var handleClick = function handleClick(event) {
// See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Button#Clicking_and_focus
// Button on Firefox, Safari and IE running on OS X does not receive focus when clicked.
// This will put focus on the button when clicked if it is not currently the active element.
if (document.activeElement !== event.currentTarget) {
event.currentTarget.focus();
setIsFocused(false);
}, {
key: "handleFocus",
value: function handleFocus(event) {
if (this.shouldShowFocus) {
this.setState({
focused: true
});
}
if (this.props.onFocus) {
this.props.onFocus(event);
}
}
if (onClick) {
onClick(event);
}, {
key: "handleMouseDown",
value: function handleMouseDown(event) {
if (this.props.onMouseDown) {
this.props.onMouseDown(event);
}
// See https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/focus#Notes
// If you call HTMLElement.focus() from a mousedown event handler, you must call event.preventDefault() to keep the focus from leaving the HTMLElement.
// Otherwise, when you click on the button again, focus would leave the button and onBlur would get called causing the document.activeElement would no longer be the focused button.
event.preventDefault();
}
};
var handleKeyDown = function handleKeyDown(event) {
// Add active state to FF browsers
if (event.keyCode === KeyCode.KEY_RETURN) {
setIsFocused(true);
}
if (event.keyCode === KeyCode.KEY_SPACE) {
setIsActive(true);
setIsFocused(true);
// Follow href on space keydown when rendered as an anchor tag
}, {
key: "render",
value: function render() {
var _this$props = this.props,
icon = _this$props.icon,
isBlock = _this$props.isBlock,
isCompact = _this$props.isCompact,
isDisabled = _this$props.isDisabled,
isIconOnly = _this$props.isIconOnly,
isReversed = _this$props.isReversed,
text = _this$props.text,
type = _this$props.type,
variant = _this$props.variant,
href = _this$props.href,
onClick = _this$props.onClick,
onMouseDown = _this$props.onMouseDown,
onBlur = _this$props.onBlur,
onFocus = _this$props.onFocus,
onKeyDown = _this$props.onKeyDown,
onKeyUp = _this$props.onKeyUp,
refCallback = _this$props.refCallback,
title = _this$props.title,
customProps = _objectWithoutProperties(_this$props, _excluded);
var theme = this.context;
var buttonClasses = (0, _classnames.default)(cx(['button', variant, {
'is-disabled': isDisabled
}, {
block: isBlock
}, {
compact: isCompact
}, {
'is-active': this.state.active && !isDisabled
}, {
'is-focused': this.state.focused && !isDisabled
}, theme.className]), customProps.className);
var buttonLabelClasses = cx(['button-label', {
'text-and-icon': icon && !isIconOnly && variant !== 'utility'
}, {
'icon-only': isIconOnly || variant === 'utility'
}, {
'text-only': !icon
}]);
var buttonTextClasses = cx([{
'text-first': icon && isReversed
}]);
var iconClasses = cx(['icon', {
'icon-first': !isIconOnly && variant !== 'utility' && !isReversed
}]);
var buttonText = !isIconOnly && variant !== 'utility' ? /*#__PURE__*/_react.default.createElement("span", {
className: buttonTextClasses
}, text) : null;
var buttonIcon = null;
if (icon) {
var iconSvgClasses = icon.props.className ? "".concat(icon.props.className, " ").concat(cx('icon-svg')) : cx('icon-svg');
var cloneIcon = /*#__PURE__*/_react.default.cloneElement(icon, {
className: iconSvgClasses
});
buttonIcon = /*#__PURE__*/_react.default.createElement("span", {
className: iconClasses
}, cloneIcon);
}
var buttonTitle = title;
if (isIconOnly || variant === 'utility') {
buttonTitle = icon && icon.props.a11yLabel ? icon.props.a11yLabel : title || text;
}
var buttonLabel = /*#__PURE__*/_react.default.createElement("span", {
className: buttonLabelClasses
}, isReversed ? buttonText : buttonIcon, isReversed ? buttonIcon : buttonText);
var ariaLabel = customProps['aria-label'];
if (isIconOnly || variant === 'utility') {
ariaLabel = icon && icon.props.a11yLabel ? icon.props.a11yLabel : ariaLabel || text;
}
var ComponentType = 'button';
if (href) {
// Prevent window scrolling
event.preventDefault();
window.location.href = href;
ComponentType = 'a';
customProps.role = 'button';
}
return /*#__PURE__*/_react.default.createElement(ComponentType, _extends({}, customProps, {
className: buttonClasses,
type: type,
disabled: isDisabled,
tabIndex: isDisabled ? '-1' : customProps.tabIndex,
"aria-disabled": isDisabled,
"aria-label": ariaLabel,
onKeyDown: this.handleKeyDown,
onKeyUp: this.handleKeyUp,
onBlur: this.handleOnBlur,
title: buttonTitle,
onClick: this.handleClick,
onMouseDown: this.handleMouseDown,
onFocus: this.handleFocus,
href: href,
ref: refCallback
}), buttonLabel);
}
if (onKeyDown) {
onKeyDown(event);
}], [{
key: "getDerivedStateFromProps",
value: function getDerivedStateFromProps(nextProps, prevState) {
if (prevState.focused && nextProps.isDisabled) {
return {
focused: false
};
}
return null;
}
};
var handleKeyUp = function handleKeyUp(event) {
// Remove active state from FF broswers
if (event.keyCode === KeyCode.KEY_SPACE) {
setIsActive(false);
}
if (onKeyUp) {
onKeyUp(event);
}
};
var handleMouseDown = function handleMouseDown(event) {
if (onMouseDown) {
onMouseDown(event);
}
// See https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/focus#Notes
// If you call HTMLElement.focus() from a mousedown event handler, you must call event.preventDefault() to keep the focus from leaving the HTMLElement.
// Otherwise, when you click on the button again, focus would leave the button and onBlur would get called causing the document.activeElement would no longer be the focused button.
event.preventDefault();
};
var handleFocus = function handleFocus(event) {
setIsFocused(true);
if (onFocus) {
onFocus(event);
}
};
var buttonClasses = (0, _classnames.default)(cx(['button', variant, {
'is-disabled': isDisabled
}, {
block: isBlock
}, {
compact: isCompact
}, {
'is-active': isActive && !isDisabled
}, {
'is-focused': isFocused && !isDisabled
}, theme.className]), customProps.className);
var isIconOnlyClass = isIconOnly || variant === ButtonVariants.UTILITY;
var buttonLabelClasses = cx(['button-label', {
'text-and-icon': icon && !isIconOnlyClass
}, {
'icon-only': isIconOnlyClass
}, {
'text-only': !icon
}]);
var buttonTextClasses = cx([{
'text-first': icon && isReversed
}]);
var iconClasses = cx(['icon', {
'icon-first': !isIconOnlyClass && !isReversed
}]);
var buttonText = !isIconOnlyClass ? /*#__PURE__*/_react.default.createElement("span", {
className: buttonTextClasses
}, text) : null;
var buttonIcon = null;
if (icon) {
var iconSvgClasses = icon.props.className ? "".concat(icon.props.className, " ").concat(cx('icon-svg')) : cx('icon-svg');
var cloneIcon = /*#__PURE__*/_react.default.cloneElement(icon, {
className: iconSvgClasses
});
buttonIcon = /*#__PURE__*/_react.default.createElement("span", {
className: iconClasses
}, cloneIcon);
}
var buttonTitle = title;
var ariaLabel = customProps['aria-label'];
if (isIconOnlyClass) {
ariaLabel = icon && icon.props.a11yLabel ? icon.props.a11yLabel : ariaLabel || text;
buttonTitle = icon && icon.props.a11yLabel ? icon.props.a11yLabel : title || text;
}
var ComponentType = href ? 'a' : 'button';
return /*#__PURE__*/_react.default.createElement(ComponentType, _extends({}, customProps, {
"aria-disabled": isDisabled,
"aria-label": ariaLabel,
className: buttonClasses,
disabled: isDisabled,
href: href,
onBlur: handleOnBlur,
onClick: handleClick,
onFocus: handleFocus,
onKeyDown: handleKeyDown,
onKeyUp: handleKeyUp,
onMouseDown: handleMouseDown,
ref: refCallback,
role: href ? 'button' : customProps.role,
tabIndex: isDisabled ? '-1' : customProps.tabIndex,
title: buttonTitle,
type: type
}), /*#__PURE__*/_react.default.createElement("span", {
className: buttonLabelClasses
}, isReversed ? buttonText : buttonIcon, isReversed ? buttonIcon : buttonText));
};
return Button;
}(_react.default.Component);
Button.propTypes = propTypes;
Button.defaultProps = defaultProps;
Button.contextType = _terraThemeContext.default;
Button.Opts = {};

@@ -308,0 +371,0 @@ Button.Opts.Types = ButtonTypes;

{
"name": "terra-button",
"main": "lib/Button.js",
"version": "3.68.0",
"version": "3.68.1",
"description": "The terra-button component provides users a way to trigger actions in the UI.",

@@ -47,3 +47,3 @@ "repository": {

},
"gitHead": "40c1ccb1e04ea40a8109b0d7154bae240e933bac"
"gitHead": "3516dfe03d27f2c63edc2bf9d61a0661e5025296"
}

@@ -1,2 +0,2 @@

import React, { useContext, useEffect, useState } from 'react';
import React from 'react';
import PropTypes from 'prop-types';

@@ -118,47 +118,32 @@ import classNames from 'classnames';

const Button = ({
href,
icon,
isBlock,
isCompact,
isDisabled,
isIconOnly,
isReversed,
onBlur,
onClick,
onFocus,
onKeyDown,
onKeyUp,
onMouseDown,
refCallback,
text,
title,
type,
variant,
...customProps
}) => {
const theme = useContext(ThemeContext);
class Button extends React.Component {
constructor(props) {
super(props);
this.state = { active: false, focused: false };
this.handleKeyDown = this.handleKeyDown.bind(this);
this.handleKeyUp = this.handleKeyUp.bind(this);
this.handleOnBlur = this.handleOnBlur.bind(this);
this.handleFocus = this.handleFocus.bind(this);
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleClick = this.handleClick.bind(this);
// We need to manually control active state for FF compatibility
const [isActive, setIsActive] = useState(false);
this.shouldShowFocus = true;
}
// We manually control focus behaviors for keyboard events.
const [isFocused, setIsFocused] = useState(false);
useEffect(() => {
// Disabling button does not trigger onBlur, we need to manually unfocus
if (isDisabled) {
setIsFocused(false);
static getDerivedStateFromProps(nextProps, prevState) {
if (prevState.focused && nextProps.isDisabled) {
return { focused: false };
}
}, [isDisabled]);
return null;
}
const handleOnBlur = (event) => {
setIsFocused(false);
handleOnBlur(event) {
this.setState({ focused: false });
if (onBlur) {
onBlur(event);
if (this.props.onBlur) {
this.props.onBlur(event);
}
};
}
const handleClick = (event) => {
handleClick(event) {
// See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Button#Clicking_and_focus

@@ -168,50 +153,66 @@ // Button on Firefox, Safari and IE running on OS X does not receive focus when clicked.

if (document.activeElement !== event.currentTarget) {
this.shouldShowFocus = false;
event.currentTarget.focus();
setIsFocused(false);
this.shouldShowFocus = true;
}
if (onClick) {
onClick(event);
if (this.props.onClick) {
this.props.onClick(event);
}
};
}
const handleKeyDown = (event) => {
handleKeyDown(event) {
// Add active state to FF browsers
if (event.keyCode === KeyCode.KEY_RETURN) {
setIsFocused(true);
}
if (event.nativeEvent.keyCode === KeyCode.KEY_SPACE) {
this.setState({ active: true });
if (event.keyCode === KeyCode.KEY_SPACE) {
setIsActive(true);
setIsFocused(true);
// Follow href on space keydown when rendered as an anchor tag
if (href) {
if (this.props.href) {
// Prevent window scrolling
event.preventDefault();
window.location.href = href;
window.location.href = this.props.href;
}
}
if (onKeyDown) {
onKeyDown(event);
// Add focus styles for keyboard navigation
if (event.nativeEvent.keyCode === KeyCode.KEY_SPACE || event.nativeEvent.keyCode === KeyCode.KEY_RETURN) {
this.setState({ focused: true });
}
};
const handleKeyUp = (event) => {
if (this.props.onKeyDown) {
this.props.onKeyDown(event);
}
}
handleKeyUp(event) {
// Remove active state from FF broswers
if (event.keyCode === KeyCode.KEY_SPACE) {
setIsActive(false);
if (event.nativeEvent.keyCode === KeyCode.KEY_SPACE) {
this.setState({ active: false });
}
if (onKeyUp) {
onKeyUp(event);
// Apply focus styles for keyboard navigation
if (event.nativeEvent.keyCode === KeyCode.KEY_TAB) {
this.setState({ focused: true });
}
};
const handleMouseDown = (event) => {
if (onMouseDown) {
onMouseDown(event);
if (this.props.onKeyUp) {
this.props.onKeyUp(event);
}
}
handleFocus(event) {
if (this.shouldShowFocus) {
this.setState({ focused: true });
}
if (this.props.onFocus) {
this.props.onFocus(event);
}
}
handleMouseDown(event) {
if (this.props.onMouseDown) {
this.props.onMouseDown(event);
}
// See https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/focus#Notes

@@ -221,82 +222,74 @@ // If you call HTMLElement.focus() from a mousedown event handler, you must call event.preventDefault() to keep the focus from leaving the HTMLElement.

event.preventDefault();
};
}
const handleFocus = (event) => {
setIsFocused(true);
if (onFocus) {
onFocus(event);
}
};
const buttonClasses = classNames(
cx([
'button',
render() {
const {
icon,
isBlock,
isCompact,
isDisabled,
isIconOnly,
isReversed,
text,
type,
variant,
{ 'is-disabled': isDisabled },
{ block: isBlock },
{ compact: isCompact },
{ 'is-active': isActive && !isDisabled },
{ 'is-focused': isFocused && !isDisabled },
theme.className,
]),
customProps.className,
);
href,
onClick,
onMouseDown,
onBlur,
onFocus,
onKeyDown,
onKeyUp,
refCallback,
title,
...customProps
} = this.props;
const isIconOnlyClass = isIconOnly || variant === ButtonVariants.UTILITY;
const theme = this.context;
const buttonLabelClasses = cx([
'button-label',
{ 'text-and-icon': icon && !isIconOnlyClass },
{ 'icon-only': isIconOnlyClass },
{ 'text-only': !icon },
]);
const buttonClasses = classNames(
cx([
'button',
variant,
{ 'is-disabled': isDisabled },
{ block: isBlock },
{ compact: isCompact },
{ 'is-active': this.state.active && !isDisabled },
{ 'is-focused': this.state.focused && !isDisabled },
theme.className,
]),
customProps.className,
);
const buttonTextClasses = cx([
{ 'text-first': icon && isReversed },
]);
const buttonLabelClasses = cx([
'button-label',
{ 'text-and-icon': icon && !isIconOnly && variant !== 'utility' },
{ 'icon-only': isIconOnly || variant === 'utility' },
{ 'text-only': !icon },
]);
const iconClasses = cx([
'icon',
{ 'icon-first': !isIconOnlyClass && !isReversed },
]);
const buttonTextClasses = cx([
{ 'text-first': icon && isReversed },
]);
const buttonText = !isIconOnlyClass ? <span className={buttonTextClasses}>{text}</span> : null;
const iconClasses = cx([
'icon',
{ 'icon-first': (!isIconOnly && variant !== 'utility') && !isReversed },
]);
let buttonIcon = null;
if (icon) {
const iconSvgClasses = icon.props.className ? `${icon.props.className} ${cx('icon-svg')}` : cx('icon-svg');
const cloneIcon = React.cloneElement(icon, { className: iconSvgClasses });
buttonIcon = <span className={iconClasses}>{cloneIcon}</span>;
}
const buttonText = !isIconOnly && variant !== 'utility' ? <span className={buttonTextClasses}>{text}</span> : null;
let buttonTitle = title;
let ariaLabel = customProps['aria-label'];
let buttonIcon = null;
if (icon) {
const iconSvgClasses = icon.props.className ? `${icon.props.className} ${cx('icon-svg')}` : cx('icon-svg');
const cloneIcon = React.cloneElement(icon, { className: iconSvgClasses });
buttonIcon = <span className={iconClasses}>{cloneIcon}</span>;
}
if (isIconOnlyClass) {
ariaLabel = (icon && icon.props.a11yLabel) ? icon.props.a11yLabel : ariaLabel || text;
buttonTitle = (icon && icon.props.a11yLabel) ? icon.props.a11yLabel : title || text;
}
let buttonTitle = title;
if (isIconOnly || variant === 'utility') {
buttonTitle = (icon && icon.props.a11yLabel) ? icon.props.a11yLabel : title || text;
}
const ComponentType = href ? 'a' : 'button';
return (
<ComponentType
{...customProps}
aria-disabled={isDisabled}
aria-label={ariaLabel}
className={buttonClasses}
disabled={isDisabled}
href={href}
onBlur={handleOnBlur}
onClick={handleClick}
onFocus={handleFocus}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
onMouseDown={handleMouseDown}
ref={refCallback}
role={href ? 'button' : customProps.role}
tabIndex={isDisabled ? '-1' : customProps.tabIndex}
title={buttonTitle}
type={type}
>
const buttonLabel = (
<span className={buttonLabelClasses}>

@@ -306,8 +299,43 @@ {isReversed ? buttonText : buttonIcon}

</span>
</ComponentType>
);
};
);
let ariaLabel = customProps['aria-label'];
if (isIconOnly || variant === 'utility') {
ariaLabel = (icon && icon.props.a11yLabel) ? icon.props.a11yLabel : ariaLabel || text;
}
let ComponentType = 'button';
if (href) {
ComponentType = 'a';
customProps.role = 'button';
}
return (
<ComponentType
{...customProps}
className={buttonClasses}
type={type}
disabled={isDisabled}
tabIndex={isDisabled ? '-1' : customProps.tabIndex}
aria-disabled={isDisabled}
aria-label={ariaLabel}
onKeyDown={this.handleKeyDown}
onKeyUp={this.handleKeyUp}
onBlur={this.handleOnBlur}
title={buttonTitle}
onClick={this.handleClick}
onMouseDown={this.handleMouseDown}
onFocus={this.handleFocus}
href={href}
ref={refCallback}
>
{buttonLabel}
</ComponentType>
);
}
}
Button.propTypes = propTypes;
Button.defaultProps = defaultProps;
Button.contextType = ThemeContext;

@@ -314,0 +342,0 @@ Button.Opts = {};

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc