'use strict';

var _extends = require('@babel/runtime/helpers/extends');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
var _createClass = require('@babel/runtime/helpers/createClass');
var _possibleConstructorReturn = require('@babel/runtime/helpers/possibleConstructorReturn');
var _getPrototypeOf = require('@babel/runtime/helpers/getPrototypeOf');
var _inherits = require('@babel/runtime/helpers/inherits');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var omit = require('../../../../node_modules/lodash-es/omit.js');
require('core-js/modules/es.array.concat.js');
require('core-js/modules/es.array.filter.js');
require('core-js/modules/es.array.find-index.js');
require('core-js/modules/es.array.includes.js');
require('core-js/modules/es.array.map.js');
require('core-js/modules/es.object.to-string.js');
require('core-js/modules/es.reflect.construct.js');
var React = require('react');
var PropTypes = require('prop-types');
var react = require('@carbon/react');
var classnames = require('classnames');
var Button = require('../../../Button/Button.js');
var Settings = require('../../../../constants/Settings.js');
var TablePropTypes = require('../../TablePropTypes.js');
var index = require('../../../OverflowMenu/index.js');
var tableUtilities = require('../../tableUtilities.js');
var RowActionsError = require('./RowActionsError.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var _extends__default = /*#__PURE__*/_interopDefault(_extends);
var _objectWithoutProperties__default = /*#__PURE__*/_interopDefault(_objectWithoutProperties);
var _classCallCheck__default = /*#__PURE__*/_interopDefault(_classCallCheck);
var _createClass__default = /*#__PURE__*/_interopDefault(_createClass);
var _possibleConstructorReturn__default = /*#__PURE__*/_interopDefault(_possibleConstructorReturn);
var _getPrototypeOf__default = /*#__PURE__*/_interopDefault(_getPrototypeOf);
var _inherits__default = /*#__PURE__*/_interopDefault(_inherits);
var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var React__default = /*#__PURE__*/_interopDefault(React);
var PropTypes__default = /*#__PURE__*/_interopDefault(PropTypes);
var classnames__default = /*#__PURE__*/_interopDefault(classnames);

var _excluded = ["id", "labelText", "iconDescription"];
function _callSuper(t, o, e) { return o = _getPrototypeOf__default.default(o), _possibleConstructorReturn__default.default(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf__default.default(t).constructor) : o.apply(t, e)); }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
var iotPrefix = Settings.settings.iotPrefix;
var propTypes = {
  /** Unique id for each row, passed back for each click */
  id: PropTypes__default.default.string.isRequired,
  /** Unique id for the table */
  tableId: PropTypes__default.default.string.isRequired,
  /** Array with all the actions to render */
  actions: TablePropTypes.RowActionPropTypes,
  /** Callback called if a row action is clicked */
  onApplyRowAction: PropTypes__default.default.func.isRequired,
  /** translated text for more actions */
  overflowMenuAria: PropTypes__default.default.string,
  /** Is a row action actively running */
  isRowActionRunning: PropTypes__default.default.bool,
  /** row action error out */
  rowActionsError: TablePropTypes.RowActionErrorPropTypes,
  onClearError: PropTypes__default.default.func,
  /** I18N label for in progress */
  inProgressText: PropTypes__default.default.string,
  /** I18N label for action failed */
  actionFailedText: PropTypes__default.default.string,
  // eslint-disable-line react/require-default-props
  /** I18N label for learn more */
  learnMoreText: PropTypes__default.default.string,
  // eslint-disable-line react/require-default-props
  /** I18N label for dismiss */
  dismissText: PropTypes__default.default.string,
  // eslint-disable-line react/require-default-props
  /** `true` to make this menu item a divider. */
  hasDivider: PropTypes__default.default.bool,
  /** `true` to make this menu item a "danger button". */
  isDelete: PropTypes__default.default.bool,
  /** `true` hides all the normal actions/statuses and shows the singleRowEditButtons */
  showSingleRowEditButtons: PropTypes__default.default.bool,
  singleRowEditButtons: PropTypes__default.default.element,
  /**
   * Direction of document. Passed in at Table
   */
  langDir: PropTypes__default.default.oneOf(['ltr', 'rtl']),
  /**
   * the size passed to the table to set row height
   */
  size: PropTypes__default.default.oneOf(['xs', 'sm', 'md', 'lg', 'xl'])
};
var defaultProps = {
  actions: null,
  isRowActionRunning: false,
  rowActionsError: null,
  overflowMenuAria: 'More actions',
  inProgressText: 'In progress',
  onClearError: null,
  hasDivider: false,
  isDelete: false,
  showSingleRowEditButtons: false,
  singleRowEditButtons: null,
  langDir: 'ltr',
  size: undefined
};
var RowActionsCell = /*#__PURE__*/function (_React$Component) {
  function RowActionsCell() {
    var _this;
    _classCallCheck__default.default(this, RowActionsCell);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _callSuper(this, RowActionsCell, [].concat(args));
    _defineProperty__default.default(_this, "state", {
      isOpen: false
    });
    _defineProperty__default.default(_this, "handleOpen", function () {
      var isOpen = _this.state.isOpen;
      if (!isOpen) {
        _this.setState({
          isOpen: true
        });
      }
    });
    _defineProperty__default.default(_this, "handleClose", function () {
      var isOpen = _this.state.isOpen;
      if (isOpen) {
        _this.setState({
          isOpen: false
        });
      }
    });
    _defineProperty__default.default(_this, "onClick", function (e, id, action, onApplyRowAction) {
      onApplyRowAction(action, id);
      e.preventDefault();
      e.stopPropagation();
      _this.handleClose();
    });
    return _this;
  }
  _inherits__default.default(RowActionsCell, _React$Component);
  return _createClass__default.default(RowActionsCell, [{
    key: "render",
    value: function render() {
      var _this2 = this;
      var _this$props = this.props,
        id = _this$props.id,
        tableId = _this$props.tableId,
        actions = _this$props.actions,
        onApplyRowAction = _this$props.onApplyRowAction,
        overflowMenuAria = _this$props.overflowMenuAria,
        actionFailedText = _this$props.actionFailedText,
        learnMoreText = _this$props.learnMoreText,
        dismissText = _this$props.dismissText,
        isRowActionRunning = _this$props.isRowActionRunning,
        rowActionsError = _this$props.rowActionsError,
        onClearError = _this$props.onClearError,
        inProgressText = _this$props.inProgressText,
        showSingleRowEditButtons = _this$props.showSingleRowEditButtons,
        singleRowEditButtons = _this$props.singleRowEditButtons,
        langDir = _this$props.langDir,
        size = _this$props.size;
      var isOpen = this.state.isOpen;
      var visibleActions = actions ? actions.filter(function (action) {
        return !action.hidden;
      }) : [];
      var overflowActions = visibleActions.filter(function (action) {
        return action.isOverflow;
      });
      var hasOverflow = overflowActions.length > 0;
      var firstSelectableItemIndex = overflowActions.findIndex(function (action) {
        return !action.disabled;
      });
      return showSingleRowEditButtons ? /*#__PURE__*/React__default.default.createElement(react.TableCell, {
        key: "".concat(id, "-single-row-edit-buttons"),
        className: "".concat(iotPrefix, "--row-actions-cell--table-cell")
      }, singleRowEditButtons) : actions ? /*#__PURE__*/React__default.default.createElement(react.TableCell, {
        key: "".concat(id, "-row-actions-cell"),
        className: "".concat(iotPrefix, "--row-actions-cell--table-cell")
      }, /*#__PURE__*/React__default.default.createElement("div", {
        className: "".concat(iotPrefix, "--row-actions-container")
      }, /*#__PURE__*/React__default.default.createElement("div", {
        "data-testid": "row-action-container-background",
        className: classnames__default.default("".concat(iotPrefix, "--row-actions-container__background"), _defineProperty__default.default({}, "".concat(iotPrefix, "--row-actions-container__background--overflow-menu-open"), isOpen)),
        onClick: function onClick(evt) {
          return evt.stopPropagation();
        }
      }, rowActionsError ? /*#__PURE__*/React__default.default.createElement(RowActionsError, {
        actionFailedText: actionFailedText,
        learnMoreText: learnMoreText,
        dismissText: dismissText,
        rowActionsError: rowActionsError,
        onClearError: onClearError
      }) : isRowActionRunning ? /*#__PURE__*/React__default.default.createElement(React.Fragment, null, /*#__PURE__*/React__default.default.createElement(react.Loading, {
        small: true,
        withOverlay: false
      }), inProgressText) : /*#__PURE__*/React__default.default.createElement(React.Fragment, null, visibleActions.filter(function (action) {
        return !action.isOverflow;
      }).map(function (_ref) {
        var actionId = _ref.id,
          labelText = _ref.labelText,
          iconDescription = _ref.iconDescription,
          others = _objectWithoutProperties__default.default(_ref, _excluded);
        var buttonProps = omit(others, ['isOverflow', 'isDelete', 'isEdit', 'hasDivider']);
        return /*#__PURE__*/React__default.default.createElement(Button, _extends__default.default({}, buttonProps, {
          iconDescription: labelText || iconDescription,
          key: "".concat(tableId, "-").concat(id, "-row-actions-button-").concat(actionId),
          testId: "".concat(tableId, "-").concat(id, "-row-actions-button-").concat(actionId),
          kind: "ghost",
          hasIconOnly: !labelText,
          tooltipPosition: "left",
          tooltipAlignment: "end",
          size: "sm",
          onClick: function onClick(e) {
            return _this2.onClick(e, id, actionId, onApplyRowAction);
          }
        }), labelText);
      }), hasOverflow ? /*#__PURE__*/React__default.default.createElement(index.OverflowMenu, {
        id: "".concat(tableId, "-").concat(id, "-row-actions-cell-overflow"),
        "data-testid": "".concat(tableId, "-").concat(id, "-row-actions-cell-overflow"),
        flipped: langDir === 'ltr',
        ariaLabel: overflowMenuAria,
        onClick: function onClick(event) {
          return event.stopPropagation();
        },
        iconDescription: overflowMenuAria,
        onOpen: this.handleOpen,
        onClose: this.handleClose
        // compact or xs rows need the `sm` overflow menu, everything else is default (md)
        ,
        size: ['compact', 'xs'].includes(size) ? 'sm' : 'md',
        className: "".concat(iotPrefix, "--row-actions-cell--overflow-menu"),
        selectorPrimaryFocus: ".".concat(iotPrefix, "--action-overflow-item--initialFocus"),
        useAutoPositioning: true,
        align: "top-right"
      }, overflowActions.map(function (action, actionIndex) {
        return /*#__PURE__*/React__default.default.createElement(react.OverflowMenuItem, {
          className: classnames__default.default("".concat(iotPrefix, "--action-overflow-item"), _defineProperty__default.default({}, "".concat(iotPrefix, "--action-overflow-item--initialFocus"), actionIndex === firstSelectableItemIndex)),
          "data-testid": "".concat(tableId, "-").concat(id, "-row-actions-cell-overflow-menu-item-").concat(action.id),
          key: "".concat(id, "-row-actions-button-").concat(action.id),
          onClick: function onClick(e) {
            return _this2.onClick(e, id, action.id, onApplyRowAction);
          },
          requireTitle: !action.renderIcon,
          hasDivider: action.hasDivider,
          isDelete: action.isDelete,
          itemText: tableUtilities.renderTableOverflowItemText({
            action: action,
            className: "".concat(iotPrefix, "--row-actions-cell--overflow-menu-content")
          }),
          disabled: action.disabled
        });
      })) : null)))) : null;
    }
  }]);
}(React__default.default.Component);
RowActionsCell.propTypes = propTypes;
RowActionsCell.defaultProps = defaultProps;
RowActionsCell.__docgenInfo = {
  "description": "",
  "methods": [{
    "name": "handleOpen",
    "docblock": null,
    "modifiers": [],
    "params": [],
    "returns": null
  }, {
    "name": "handleClose",
    "docblock": null,
    "modifiers": [],
    "params": [],
    "returns": null
  }, {
    "name": "onClick",
    "docblock": null,
    "modifiers": [],
    "params": [{
      "name": "e",
      "type": null
    }, {
      "name": "id",
      "type": null
    }, {
      "name": "action",
      "type": null
    }, {
      "name": "onApplyRowAction",
      "type": null
    }],
    "returns": null
  }],
  "displayName": "RowActionsCell",
  "props": {
    "actions": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "Array with all the actions to render",
      "type": {
        "name": "custom",
        "raw": "RowActionPropTypes"
      },
      "required": false
    },
    "isRowActionRunning": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "Is a row action actively running",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "rowActionsError": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "row action error out",
      "type": {
        "name": "custom",
        "raw": "RowActionErrorPropTypes"
      },
      "required": false
    },
    "overflowMenuAria": {
      "defaultValue": {
        "value": "'More actions'",
        "computed": false
      },
      "description": "translated text for more actions",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "inProgressText": {
      "defaultValue": {
        "value": "'In progress'",
        "computed": false
      },
      "description": "I18N label for in progress",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "onClearError": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "hasDivider": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "`true` to make this menu item a divider.",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "isDelete": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "`true` to make this menu item a \"danger button\".",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "showSingleRowEditButtons": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "`true` hides all the normal actions/statuses and shows the singleRowEditButtons",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "singleRowEditButtons": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "element"
      },
      "required": false
    },
    "langDir": {
      "defaultValue": {
        "value": "'ltr'",
        "computed": false
      },
      "description": "Direction of document. Passed in at Table",
      "type": {
        "name": "enum",
        "value": [{
          "value": "'ltr'",
          "computed": false
        }, {
          "value": "'rtl'",
          "computed": false
        }]
      },
      "required": false
    },
    "size": {
      "defaultValue": {
        "value": "undefined",
        "computed": true
      },
      "description": "the size passed to the table to set row height",
      "type": {
        "name": "enum",
        "value": [{
          "value": "'xs'",
          "computed": false
        }, {
          "value": "'sm'",
          "computed": false
        }, {
          "value": "'md'",
          "computed": false
        }, {
          "value": "'lg'",
          "computed": false
        }, {
          "value": "'xl'",
          "computed": false
        }]
      },
      "required": false
    },
    "id": {
      "description": "Unique id for each row, passed back for each click",
      "type": {
        "name": "string"
      },
      "required": true
    },
    "tableId": {
      "description": "Unique id for the table",
      "type": {
        "name": "string"
      },
      "required": true
    },
    "onApplyRowAction": {
      "description": "Callback called if a row action is clicked",
      "type": {
        "name": "func"
      },
      "required": true
    },
    "actionFailedText": {
      "description": "I18N label for action failed",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "learnMoreText": {
      "description": "I18N label for learn more",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "dismissText": {
      "description": "I18N label for dismiss",
      "type": {
        "name": "string"
      },
      "required": false
    }
  }
};
var RowActionsCell$1 = RowActionsCell;

module.exports = RowActionsCell$1;
