"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.Alert = void 0;

var _propTypes = _interopRequireDefault(require("prop-types"));

var _analytics = require("../analytics");

var _react = _interopRequireDefault(require("react"));

var _flags = require("../flags");

var _classnames = _interopRequireDefault(require("classnames"));

var _uniqueId = _interopRequireDefault(require("lodash/uniqueId"));

var _Icons = require("../Icons");

var _i18n = require("../i18n");

var _excluded = ["children", "className", "autoFocus", "heading", "headingId", "headingLevel", "hideIcon", "alertRef", "role", "variation", "weight", "analytics", "analyticsLabelOverride"];

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _extends() { _extends = Object.assign || 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 _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, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

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 } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || 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 : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var Alert = /*#__PURE__*/function (_React$PureComponent) {
  _inherits(Alert, _React$PureComponent);

  var _super = _createSuper(Alert);

  // Alert class properties
  function Alert(props) {
    var _this;

    _classCallCheck(this, Alert);

    _this = _super.call(this, props);

    _defineProperty(_assertThisInitialized(_this), "alertTextRef", void 0);

    _defineProperty(_assertThisInitialized(_this), "focusRef", void 0);

    _defineProperty(_assertThisInitialized(_this), "headingId", void 0);

    _defineProperty(_assertThisInitialized(_this), "a11yLabelId", void 0);

    _defineProperty(_assertThisInitialized(_this), "eventHeadingText", void 0);

    _this.alertTextRef = null;
    _this.focusRef = null;
    _this.headingId = _this.props.headingId || (0, _uniqueId.default)('alert_');
    _this.a11yLabelId = _this.props.a11yLabelId || (0, _uniqueId.default)('alert_a11y_label_');

    if (process.env.NODE_ENV !== 'production') {
      if (!props.heading && !props.children) {
        console.warn("Empty <Alert> components are not allowed, please use the 'heading' prop or include children.");
      }
    }

    return _this;
  }

  _createClass(Alert, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      // Automatically set focus on alert element when `autoFocus` prop is used
      if (this.props.autoFocus && this.focusRef) {
        this.focusRef.focus();
      }

      var _this$props = this.props,
          analytics = _this$props.analytics,
          analyticsLabelOverride = _this$props.analyticsLabelOverride,
          variation = _this$props.variation;

      if ((0, _flags.alertSendsAnalytics)() && analytics !== false) {
        /* Send analytics event for `error`, `warn`, `success` alert variations */
        if (variation) {
          var heading = this.props.heading || this.props.children;
          var eventHeadingText;

          if (analyticsLabelOverride) {
            eventHeadingText = analyticsLabelOverride;
          } else if (typeof heading === 'string') {
            eventHeadingText = heading.substring(0, _analytics.MAX_LENGTH);
          } else {
            var eventHeadingTextElement = this.alertTextRef && this.alertTextRef.getElementsByClassName('ds-c-alert__heading')[0] || this.alertTextRef && this.alertTextRef.getElementsByClassName('ds-c-alert__body')[0];
            eventHeadingText = eventHeadingTextElement && eventHeadingTextElement.textContent ? eventHeadingTextElement.textContent.substring(0, _analytics.MAX_LENGTH) : '';
          }

          (0, _analytics.sendLinkEvent)({
            event_name: 'alert_impression',
            event_type: _analytics.EventCategory.UI_INTERACTION,
            ga_eventAction: 'alert impression',
            ga_eventCategory: _analytics.EventCategory.UI_COMPONENTS,
            ga_eventLabel: eventHeadingText,
            heading: eventHeadingText,
            type: variation
          });
        }
      }
    }
  }, {
    key: "heading",
    value: function heading() {
      var _this$props2 = this.props,
          headingLevel = _this$props2.headingLevel,
          heading = _this$props2.heading;

      if (heading) {
        var Heading = "h".concat(headingLevel);
        return /*#__PURE__*/_react.default.createElement(Heading, {
          className: "ds-c-alert__heading"
        }, heading);
      }
    } // getting proper icon for alert variation

  }, {
    key: "getIcon",
    value: function getIcon() {
      var iconClass = 'ds-c-alert__icon';
      var _this$props3 = this.props,
          hideIcon = _this$props3.hideIcon,
          variation = _this$props3.variation;

      if (hideIcon) {
        return null;
      }

      switch (variation) {
        case 'error':
          return /*#__PURE__*/_react.default.createElement(_Icons.AlertCircleIcon, {
            className: iconClass
          });

        case 'success':
          return /*#__PURE__*/_react.default.createElement(_Icons.CheckCircleIcon, {
            className: iconClass
          });

        case 'warn':
          return /*#__PURE__*/_react.default.createElement(_Icons.WarningIcon, {
            className: iconClass
          });

        default:
          return /*#__PURE__*/_react.default.createElement(_Icons.InfoCircleIcon, {
            className: iconClass
          });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props4 = this.props,
          children = _this$props4.children,
          className = _this$props4.className,
          autoFocus = _this$props4.autoFocus,
          heading = _this$props4.heading,
          headingId = _this$props4.headingId,
          headingLevel = _this$props4.headingLevel,
          hideIcon = _this$props4.hideIcon,
          alertRef = _this$props4.alertRef,
          role = _this$props4.role,
          variation = _this$props4.variation,
          weight = _this$props4.weight,
          analytics = _this$props4.analytics,
          analyticsLabelOverride = _this$props4.analyticsLabelOverride,
          alertProps = _objectWithoutProperties(_this$props4, _excluded);

      var classes = (0, _classnames.default)('ds-c-alert', hideIcon && 'ds-c-alert--hide-icon', variation && "ds-c-alert--".concat(variation), weight && "ds-c-alert--".concat(weight), className);

      var a11yLabel = /*#__PURE__*/_react.default.createElement("span", {
        className: "ds-c-alert__a11y-label ds-u-visibility--screen-reader",
        id: this.a11yLabelId
      }, (0, _i18n.t)("alert.".concat(variation !== null && variation !== void 0 ? variation : 'defaultLabel')), ":", ' ');

      return /*#__PURE__*/_react.default.createElement("div", _extends({
        className: classes,
        ref: function ref(_ref) {
          _this2.alertTextRef = _ref;

          if (autoFocus) {
            _this2.focusRef = _ref;
          } else if (alertRef) {
            alertRef(_ref);
          }
        },
        tabIndex: alertRef || autoFocus ? -1 : null,
        role: role,
        "aria-labelledby": heading ? this.headingId : this.a11yLabelId
      }, alertProps), this.getIcon(), /*#__PURE__*/_react.default.createElement("div", {
        className: "ds-c-alert__body",
        id: this.headingId
      }, heading ? /*#__PURE__*/_react.default.createElement("div", {
        className: "ds-c-alert__header ds-c-alert__heading"
      }, a11yLabel, this.heading()) : a11yLabel, children));
    }
  }]);

  return Alert;
}(_react.default.PureComponent);

exports.Alert = Alert;

_defineProperty(Alert, "propTypes", {
  /**
     * Access a reference to the `alert` `div` element
     */
  alertRef: _propTypes.default.func,

  /**
     * Analytics events tracking is enabled by default. Set this value to `false` to disable tracking for this component instance.
     */
  analytics: _propTypes.default.bool,

  /**
     * An override for the dynamic content sent to analytics services. By default this content comes from the heading.
     *
     * In cases where this component’s heading may contain **sensitive information**, use this prop to override what is sent to analytics.
     */
  analyticsLabelOverride: _propTypes.default.string,

  /**
     * Sets the focus on Alert during the first mount
     */
  autoFocus: _propTypes.default.bool,

  /**
     * The alert's body content
     */
  children: _propTypes.default.node,
  className: _propTypes.default.string,

  /**
     * Text for the alert heading
     */
  heading: _propTypes.default.string,

  /**
     * Optional id used to link the `aria-labelledby` attribute to the heading. If not provided, a unique id will be automatically generated and used.
     */
  headingId: _propTypes.default.string,

  /**
     * Heading type to override default `<h2>`.
     */
  headingLevel: _propTypes.default.oneOf(['1', '2', '3', '4', '5', '6']),

  /**
     * Boolean to hide the `Alert` icon
     */
  hideIcon: _propTypes.default.bool,

  /**
     * ARIA `role`, defaults to 'region'
     */
  role: _propTypes.default.oneOf(['alert', 'alertdialog', 'region', 'status']),

  /**
     * A string corresponding to the `Alert` weight classes (`lightweight`)
     */
  weight: _propTypes.default.oneOf(['lightweight']),

  /**
     * A string corresponding to the `Alert` variation classes (`error`, `warn`, `success`)
     */
  variation: _propTypes.default.oneOf(['error', 'warn', 'success'])
});

_defineProperty(Alert, "defaultProps", {
  role: 'region',
  headingLevel: '2'
});

var _default = Alert;
exports.default = _default;