"use strict";

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

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

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

var _reactAriaModal = _interopRequireDefault(require("react-aria-modal"));

var _Button = _interopRequireDefault(require("../Button/Button"));

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

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

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

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

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

var _excluded = ["actions", "actionsClassName", "analytics", "analyticsLabelOverride", "ariaCloseLabel", "children", "className", "closeButtonSize", "closeButtonText", "closeButtonVariation", "closeIcon", "closeText", "escapeExits", "escapeExitDisabled", "headerClassName", "heading", "onExit", "size", "title"];

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 _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 = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

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; }

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; }

var Dialog = function Dialog(props) {
  var _ref;

  if (process.env.NODE_ENV !== 'production') {
    if (props.title) {
      console.warn("[Deprecated]: Please remove the 'title' prop in <Dialog>, use 'heading' instead. This prop has been renamed and will be removed in a future release.");
    }

    if (props.escapeExitDisabled) {
      console.warn("[Deprecated]: Please remove the 'escapeExitDisabled' prop in <Dialog>, use 'escapeExits' instead. This prop has been renamed and will be removed in a future release.");
    }

    if (props.closeText) {
      console.warn("[Deprecated]: Please remove the 'closeText' prop in <Dialog>, use 'closeButtonText' instead. This prop has been renamed and will be removed in a future release.");
    }
  }

  var actions = props.actions,
      actionsClassName = props.actionsClassName,
      analytics = props.analytics,
      analyticsLabelOverride = props.analyticsLabelOverride,
      ariaCloseLabel = props.ariaCloseLabel,
      children = props.children,
      className = props.className,
      closeButtonSize = props.closeButtonSize,
      closeButtonText = props.closeButtonText,
      closeButtonVariation = props.closeButtonVariation,
      closeIcon = props.closeIcon,
      closeText = props.closeText,
      escapeExits = props.escapeExits,
      escapeExitDisabled = props.escapeExitDisabled,
      headerClassName = props.headerClassName,
      heading = props.heading,
      onExit = props.onExit,
      size = props.size,
      title = props.title,
      modalProps = _objectWithoutProperties(props, _excluded);

  var dialogClassNames = (0, _classnames.default)('ds-c-dialog', 'ds-base', className, size && "ds-c-dialog--".concat(size));
  var headerClassNames = (0, _classnames.default)('ds-c-dialog__header', headerClassName);
  var actionsClassNames = (0, _classnames.default)('ds-c-dialog__actions', actionsClassName); // TODO: remove after deprecating 'escapeExitDiabled' prop

  var escapeExitsProp = escapeExitDisabled ? !escapeExitDisabled : escapeExits;

  function sendDialogEvent(content, eventAttributes) {
    if (!(0, _flags.dialogSendsAnalytics)() || analytics === false) {
      return;
    }

    var eventHeadingText = analyticsLabelOverride !== null && analyticsLabelOverride !== void 0 ? analyticsLabelOverride : content;

    if (!eventHeadingText) {
      console.error('No content found for Dialog analytics event');
      return;
    }

    (0, _analytics.sendLinkEvent)(_objectSpread({
      event_type: _analytics.EventCategory.UI_INTERACTION,
      ga_eventCategory: _analytics.EventCategory.UI_COMPONENTS,
      ga_eventLabel: eventHeadingText,
      heading: eventHeadingText
    }, eventAttributes));
  }

  var _useAnalyticsContent = (0, _analytics.useAnalyticsContent)({
    componentName: 'Dialog',
    onMount: function onMount(content) {
      sendDialogEvent(content, {
        event_name: 'modal_impression',
        ga_eventAction: 'modal impression'
      });
    },
    onUnmount: function onUnmount(content) {
      sendDialogEvent(content, {
        event_name: 'modal_closed',
        ga_eventAction: 'closed modal'
      });
    }
  }),
      _useAnalyticsContent2 = _slicedToArray(_useAnalyticsContent, 1),
      headingRef = _useAnalyticsContent2[0];

  return /*#__PURE__*/_react.default.createElement(_reactAriaModal.default, _extends({
    dialogClass: dialogClassNames // TODO: remove 'escapeExits' after deprecating 'escapeExitDiabled' prop so that 'escapeExits' will pass via the 'modalProps' spread operator
    ,
    escapeExits: escapeExitsProp,
    focusDialog: true,
    includeDefaultStyles: false,
    onExit: onExit,
    titleId: "dialog-title dialog-content",
    underlayClass: "ds-c-dialog-wrap"
  }, modalProps), /*#__PURE__*/_react.default.createElement("div", {
    role: "document"
  }, /*#__PURE__*/_react.default.createElement("header", {
    className: headerClassNames,
    role: "banner"
  }, // TODO: make heading required after removing title
  (title || heading) && /*#__PURE__*/_react.default.createElement("h1", {
    className: "ds-h2",
    id: "dialog-title",
    ref: headingRef
  }, heading), /*#__PURE__*/_react.default.createElement(_Button.default, {
    "aria-label": ariaCloseLabel !== null && ariaCloseLabel !== void 0 ? ariaCloseLabel : (0, _i18n.t)('dialog.ariaCloseLabel'),
    className: "ds-c-dialog__close",
    onClick: onExit,
    size: closeButtonSize,
    variation: closeButtonVariation
  }, closeIcon, // TODO: remove closeText support once fully deprecated
  (_ref = closeText !== null && closeText !== void 0 ? closeText : closeButtonText) !== null && _ref !== void 0 ? _ref : (0, _i18n.t)('dialog.closeButtonText'))), /*#__PURE__*/_react.default.createElement("main", {
    role: "main",
    className: "ds-c-dialog__body"
  }, /*#__PURE__*/_react.default.createElement("div", {
    id: "dialog-content"
  }, children), actions && /*#__PURE__*/_react.default.createElement("div", {
    className: actionsClassNames
  }, actions))));
};

exports.Dialog = Dialog;
Dialog.propTypes = {
  children: _propTypes.default.node,

  /**
     * If `true`, the modal will receive a role of `alertdialog`, instead of its
     * default `dialog`. The `alertdialog` role should only be used when an
     * alert, error, or warning occurs.
     */
  alert: _propTypes.default.bool,

  /**
     * 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,

  /**
     * Buttons or other HTML to be rendered in the "actions" bar
     * at the bottom of the dialog.
     */
  actions: _propTypes.default.node,

  /**
     * Additional classes to be added to the actions container.
     */
  actionsClassName: _propTypes.default.string,

  /**
     * Aria label for the close button
     */
  ariaCloseLabel: _propTypes.default.string,

  /**
     * Additional classes to be added to the root dialog element.
     */
  className: _propTypes.default.string,

  /**
     * Size of the close button. See [Button component]({{root}}/components/button/#components.button.react)
     */
  closeButtonSize: _propTypes.default.oneOf(['small', 'big']),

  /**
     * For internationalization purposes, the text for the "Close" button must be
     * passed in as a prop.
     */
  closeButtonText: _propTypes.default.node,

  /**
     * The icon to display as part of the close button
     */
  closeIcon: _propTypes.default.node,

  /**
     * @hide-prop [Deprecated] This prop has been renamed to `closeButtonText`
     * @hide-prop The text for the "Close" button
     */
  closeText: _propTypes.default.node,

  /**
     * @hide-prop [Deprecated] This prop has been renamed to `escapeExits`.
     * @hide-prop Disable exiting the dialog when a user presses the Escape key.
     */
  escapeExitDisabled: _propTypes.default.bool,

  /**
     * Additional classes to be added to the header, which wraps the heading and
     * close button.
     */
  headerClassName: _propTypes.default.string,

  /**
     * The Dialog's heading, to be rendered in the header alongside the close button.
     */
  heading: _propTypes.default.node,

  /**
     * The Dialog's size parameter.
     */
  size: _propTypes.default.oneOf(['narrow', 'wide', 'full']),

  /**
     * @hide-prop [Deprecated] This prop has been renamed to `heading`.
     */
  title: _propTypes.default.node,

  /**
     * Allow additional AriaModal props to be passed to Dialog
     */
  additional_props: _propTypes.default.shape({
    children: _propTypes.default.node
  })
};
Dialog.defaultProps = {
  closeButtonVariation: 'ghost',
  closeIcon: /*#__PURE__*/_react.default.createElement(_Icons.CloseIcon, null),
  escapeExits: true,
  escapeExitDisabled: false,
  underlayClickExits: false
};
var _default = Dialog;
exports.default = _default;