terra-alert
Version:
The Terra Alert component is a notification banner that can be rendered in your application when there is information that you want to bring to the user's attention. The Alert component supports a number of built-in notification types that render with pre
264 lines (262 loc) • 15.2 kB
JavaScript
;
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", {
value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _reactIntl = require("react-intl");
var _classnames = _interopRequireDefault(require("classnames"));
var _bind = _interopRequireDefault(require("classnames/bind"));
var _uuid = require("uuid");
var _terraResponsiveElement = _interopRequireDefault(require("terra-responsive-element"));
var _terraButton = _interopRequireDefault(require("terra-button"));
var _terraVisuallyHiddenText = _interopRequireDefault(require("terra-visually-hidden-text"));
var _terraIcon = require("terra-icon");
var _terraThemeContext = _interopRequireDefault(require("terra-theme-context"));
var _AlertModule = _interopRequireDefault(require("./Alert.module.scss"));
var _excluded = ["action", "children", "customIcon", "customColorClass", "disableAlertActionFocus", "onDismiss", "intl", "id", "role", "title", "titleID", "type"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
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 _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 _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
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(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
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 = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }
var cx = _bind.default.bind(_AlertModule.default);
var AlertTypes = {
ALERT: 'alert',
ERROR: 'error',
WARNING: 'warning',
UNSATISFIED: 'unsatisfied',
UNVERIFIED: 'unverified',
ADVISORY: 'advisory',
INFO: 'info',
SUCCESS: 'success',
CUSTOM: 'custom'
};
var propTypes = {
/**
* An action element to be added to the action section of the notification banner to give the user an easy way
* to accomplish a task to resolve the notification.
*/
action: _propTypes.default.element,
/**
* Child Nodes providing the message content for the notification banner. Can contain text and HTML.
*/
children: _propTypes.default.node,
/**
* The icon to be used for a notification banner of type custom. This will not be used for any other notification types.
*/
customIcon: _propTypes.default.element,
/**
* Sets an author-defined class, to control the status bar color to be used for a notification banner of type custom.
*
* 
* Adding `var(--my-app...` CSS variables is required for proper re-themeability when creating custom color styles _(see included examples)_.
*/
customColorClass: _propTypes.default.string,
/**
* Disables the focus shift to Alert Notification Banners when action element is present.
*/
disableAlertActionFocus: _propTypes.default.bool,
/**
* Callback function triggered when Dismiss button is clicked. The presence of this prop will cause the Dismiss button to be included on the notification banner.
*/
onDismiss: _propTypes.default.func,
/**
* The unique ID of the alert that is used to identify the alert title and message content.
* These IDs can be used to associate action elements with the alert via aria-describedby, in the format
* `alert-title-${id}`.
* */
id: _propTypes.default.string,
/**
* @private
* intl object programmatically imported through injectIntl from react-intl.
* */
intl: _propTypes.default.shape({
formatMessage: _propTypes.default.func
}).isRequired,
/**
* The ARIA role attribute of the notification banner. If not provided, notification banner of type _alert_ will default to role `"alert"`,
* all other notification banner types will use the role of `"status"`.
*/
role: _propTypes.default.string,
/**
* The optional custom title for the notification banner which will be bolded.
* Overrides the provided default title for all notification types (excludes `custom`).
* Title should be provided for `custom` notification banners.
*/
title: _propTypes.default.string,
/**
* The unique ID that is used to identify the alert title.
* */
titleID: _propTypes.default.string,
/**
* The type of notification banner to be rendered. One of `alert`, `error`, `warning`, `unsatisfied`, `unverified`, `advisory`,
* `info`, `success`, or `custom`.
* A default title is provided for all notification types except `custom`.
*/
type: _propTypes.default.oneOf([AlertTypes.ALERT, AlertTypes.ERROR, AlertTypes.WARNING, AlertTypes.UNSATISFIED, AlertTypes.UNVERIFIED, AlertTypes.ADVISORY, AlertTypes.INFO, AlertTypes.SUCCESS, AlertTypes.CUSTOM])
};
var defaultProps = {
customColorClass: 'custom-default-color',
disableAlertActionFocus: false,
type: AlertTypes.ALERT
};
var getAlertIcon = function getAlertIcon(type, customIcon) {
switch (type) {
case AlertTypes.ALERT:
return /*#__PURE__*/_react.default.createElement("span", {
className: cx('icon')
}, /*#__PURE__*/_react.default.createElement(_terraIcon.IconAlert, null));
case AlertTypes.ERROR:
return /*#__PURE__*/_react.default.createElement("span", {
className: cx('icon')
}, /*#__PURE__*/_react.default.createElement(_terraIcon.IconError, null));
case AlertTypes.WARNING:
return /*#__PURE__*/_react.default.createElement("span", {
className: cx('icon')
}, /*#__PURE__*/_react.default.createElement(_terraIcon.IconWarning, null));
case AlertTypes.UNSATISFIED:
return /*#__PURE__*/_react.default.createElement("span", {
className: cx('icon', 'unsatisfied-icon')
}, /*#__PURE__*/_react.default.createElement(_terraIcon.IconGapChecking, null));
case AlertTypes.UNVERIFIED:
return /*#__PURE__*/_react.default.createElement("span", {
className: cx('icon', 'unverified-icon')
}, /*#__PURE__*/_react.default.createElement(_terraIcon.IconDiamondSymbol, null));
case AlertTypes.ADVISORY:
return null;
case AlertTypes.INFO:
return /*#__PURE__*/_react.default.createElement("span", {
className: cx('icon')
}, /*#__PURE__*/_react.default.createElement(_terraIcon.IconInformation, null));
case AlertTypes.SUCCESS:
return /*#__PURE__*/_react.default.createElement("span", {
className: cx('icon')
}, /*#__PURE__*/_react.default.createElement(_terraIcon.IconSuccess, null));
case AlertTypes.CUSTOM:
return /*#__PURE__*/_react.default.createElement("span", {
className: cx('icon')
}, customIcon);
default:
return null;
}
};
var Alert = function Alert(_ref) {
var action = _ref.action,
children = _ref.children,
customIcon = _ref.customIcon,
customColorClass = _ref.customColorClass,
disableAlertActionFocus = _ref.disableAlertActionFocus,
onDismiss = _ref.onDismiss,
intl = _ref.intl,
id = _ref.id,
role = _ref.role,
title = _ref.title,
titleID = _ref.titleID,
type = _ref.type,
customProps = _objectWithoutProperties(_ref, _excluded);
var theme = _react.default.useContext(_terraThemeContext.default);
var _useState = (0, _react.useState)(),
_useState2 = _slicedToArray(_useState, 2),
isNarrow = _useState2[0],
setIsNarrow = _useState2[1];
var alertBodyRef = (0, _react.useRef)(null);
var defaultTitle = type === AlertTypes.CUSTOM ? '' : intl.formatMessage({
id: "Terra.alert.".concat(type)
});
var defaultRole = type === AlertTypes.ALERT ? 'alert' : 'status';
var isAlert = role === 'alert' || defaultRole === 'alert';
var alertClassNames = (0, _classnames.default)(cx('alert-base', type, {
narrow: isNarrow
}, {
wide: !isNarrow
}, theme.className), customProps.className, _defineProperty({}, "".concat(customColorClass), customColorClass && type === AlertTypes.CUSTOM));
var bodyClassNameForParent = cx('body', {
'body-std': !isNarrow || isNarrow && !onDismiss && !action
}, {
'body-narrow': isNarrow && (onDismiss || action)
});
var focusContainerClassName = cx('focus-container');
var contentContainerClassName = cx('content-container');
var alertId = id || (0, _uuid.v4)();
var alertTitleId = titleID || "alert-title-".concat(alertId);
var alertMessageId = "alert-message-".concat(alertId);
var dismissButtonAriaDescribedBy = title || defaultTitle ? alertTitleId : alertMessageId;
var dismissButton;
if (onDismiss) {
dismissButton = /*#__PURE__*/_react.default.createElement(_terraButton.default, {
"aria-describedby": dismissButtonAriaDescribedBy,
text: intl.formatMessage({
id: 'Terra.alert.dismiss'
}),
onClick: onDismiss
});
}
var actionsSection;
if (onDismiss || action) {
var actionsClassName = cx('actions', {
'actions-custom': type === AlertTypes.CUSTOM
});
actionsSection = /*#__PURE__*/_react.default.createElement("div", {
className: actionsClassName
}, action, dismissButton);
}
var alertSectionClassName = cx('section', {
'section-custom': type === AlertTypes.CUSTOM
});
var alertMessageContent = /*#__PURE__*/_react.default.createElement("div", {
id: alertMessageId,
className: alertSectionClassName
}, (title || defaultTitle) && /*#__PURE__*/_react.default.createElement("strong", {
id: alertTitleId,
className: cx('title')
}, title && defaultTitle && /*#__PURE__*/_react.default.createElement(_terraVisuallyHiddenText.default, {
text: "".concat(defaultTitle, ",")
}), title || defaultTitle), children);
(0, _react.useEffect)(function () {
var _alertBodyRef$current;
// if the notification is an alert with an action element, focus the alert
if (isAlert && action && !disableAlertActionFocus && alertBodyRef !== null && alertBodyRef !== void 0 && (_alertBodyRef$current = alertBodyRef.current) !== null && _alertBodyRef$current !== void 0 && _alertBodyRef$current.focus) {
alertBodyRef.current.focus();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return /*#__PURE__*/_react.default.createElement(_terraResponsiveElement.default, {
onChange: function onChange(value) {
var showNarrowAlert = value === 'tiny';
if (showNarrowAlert !== isNarrow) {
setIsNarrow(showNarrowAlert);
}
}
}, /*#__PURE__*/_react.default.createElement("div", _extends({
role: role || defaultRole,
id: id
}, customProps, {
className: alertClassNames
}), /*#__PURE__*/_react.default.createElement("div", {
className: bodyClassNameForParent
}, /*#__PURE__*/_react.default.createElement("div", {
className: focusContainerClassName,
ref: alertBodyRef,
tabIndex: "-1"
}), /*#__PURE__*/_react.default.createElement("div", {
className: contentContainerClassName
}, getAlertIcon(type, customIcon), alertMessageContent)), actionsSection));
};
Alert.propTypes = propTypes;
Alert.defaultProps = defaultProps;
Alert.Opts = {};
Alert.Opts.Types = AlertTypes;
var _default = exports.default = (0, _reactIntl.injectIntl)(Alert);