"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

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

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

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

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

var _predicate = require("../../services/predicate");

var _context_menu = require("../context_menu");

var _popover = require("../popover");

var _button = require("../button");

var _tool_tip = require("../tool_tip");

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

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } /*
                                                                                                                                                                                                                                                                                                                                      * SPDX-License-Identifier: Apache-2.0
                                                                                                                                                                                                                                                                                                                                      *
                                                                                                                                                                                                                                                                                                                                      * The OpenSearch Contributors require contributions made to
                                                                                                                                                                                                                                                                                                                                      * this file be licensed under the Apache-2.0 license or a
                                                                                                                                                                                                                                                                                                                                      * compatible open source license.
                                                                                                                                                                                                                                                                                                                                      *
                                                                                                                                                                                                                                                                                                                                      * Modifications Copyright OpenSearch Contributors. See
                                                                                                                                                                                                                                                                                                                                      * GitHub history for details.
                                                                                                                                                                                                                                                                                                                                      */ /*
                                                                                                                                                                                                                                                                                                                                          * Licensed to Elasticsearch B.V. under one or more contributor
                                                                                                                                                                                                                                                                                                                                          * license agreements. See the NOTICE file distributed with
                                                                                                                                                                                                                                                                                                                                          * this work for additional information regarding copyright
                                                                                                                                                                                                                                                                                                                                          * ownership. Elasticsearch B.V. licenses this file to you under
                                                                                                                                                                                                                                                                                                                                          * the Apache License, Version 2.0 (the "License"); you may
                                                                                                                                                                                                                                                                                                                                          * not use this file except in compliance with the License.
                                                                                                                                                                                                                                                                                                                                          * You may obtain a copy of the License at
                                                                                                                                                                                                                                                                                                                                          *
                                                                                                                                                                                                                                                                                                                                          *    http://www.apache.org/licenses/LICENSE-2.0
                                                                                                                                                                                                                                                                                                                                          *
                                                                                                                                                                                                                                                                                                                                          * Unless required by applicable law or agreed to in writing,
                                                                                                                                                                                                                                                                                                                                          * software distributed under the License is distributed on an
                                                                                                                                                                                                                                                                                                                                          * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
                                                                                                                                                                                                                                                                                                                                          * KIND, either express or implied.  See the License for the
                                                                                                                                                                                                                                                                                                                                          * specific language governing permissions and limitations
                                                                                                                                                                                                                                                                                                                                          * under the License.
                                                                                                                                                                                                                                                                                                                                          */

function actionIsCustomItemAction(action) {
  return action.hasOwnProperty('render');
}

var CollapsedItemActions = /*#__PURE__*/function (_Component) {
  (0, _inherits2.default)(CollapsedItemActions, _Component);

  var _super = _createSuper(CollapsedItemActions);

  function CollapsedItemActions() {
    var _this;

    (0, _classCallCheck2.default)(this, CollapsedItemActions);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "popoverDiv", null);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "state", {
      popoverOpen: false
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "togglePopover", function () {
      _this.setState(function (prevState) {
        return {
          popoverOpen: !prevState.popoverOpen
        };
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "closePopover", function () {
      _this.setState({
        popoverOpen: false
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onPopoverBlur", function () {
      // you must be asking... WTF? I know... but this timeout is
      // required to make sure we process the onBlur events after the initial
      // event cycle. Reference:
      // https://medium.com/@jessebeach/dealing-with-focus-and-blur-in-a-composite-widget-in-react-90d3c3b49a9b
      window.requestAnimationFrame(function () {
        if (!_this.popoverDiv.contains(document.activeElement) && _this.props.onBlur) {
          _this.props.onBlur();
        }
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "registerPopoverDiv", function (popoverDiv) {
      if (!_this.popoverDiv) {
        _this.popoverDiv = popoverDiv;

        _this.popoverDiv.addEventListener('focusout', _this.onPopoverBlur);
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onClickItem", function (onClickAction) {
      _this.closePopover();

      if (onClickAction) {
        onClickAction();
      }
    });
    return _this;
  }

  (0, _createClass2.default)(CollapsedItemActions, [{
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      if (this.popoverDiv) {
        this.popoverDiv.removeEventListener('focusout', this.onPopoverBlur);
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props = this.props,
          actions = _this$props.actions,
          itemId = _this$props.itemId,
          item = _this$props.item,
          actionEnabled = _this$props.actionEnabled,
          onFocus = _this$props.onFocus,
          className = _this$props.className;
      var isOpen = this.state.popoverOpen;
      var allDisabled = true;
      var controls = actions.reduce(function (controls, action, index) {
        var key = "action_".concat(itemId, "_").concat(index);
        var available = action.available ? action.available(item) : true;

        if (!available) {
          return controls;
        }

        var enabled = actionEnabled(action);
        allDisabled = allDisabled && !enabled;

        if (actionIsCustomItemAction(action)) {
          var customAction = action;
          var actionControl = customAction.render(item, enabled);
          var actionControlOnClick = actionControl && actionControl.props && actionControl.props.onClick;
          controls.push( /*#__PURE__*/_react.default.createElement(_context_menu.OuiContextMenuItem, {
            key: key,
            onClick: function onClick() {
              return _this2.onClickItem(actionControlOnClick ? function () {
                return actionControlOnClick(item);
              } : undefined);
            }
          }, actionControl));
        } else {
          var _onClick = action.onClick,
              name = action.name,
              href = action.href,
              target = action.target,
              dataTestSubj = action['data-test-subj'];
          var buttonIcon = action.icon;
          var icon;

          if (buttonIcon) {
            icon = (0, _predicate.isString)(buttonIcon) ? buttonIcon : buttonIcon(item);
          }

          var buttonContent = typeof name === 'function' ? name(item) : name;
          controls.push( /*#__PURE__*/_react.default.createElement(_context_menu.OuiContextMenuItem, {
            key: key,
            disabled: !enabled,
            href: href,
            target: target,
            icon: icon,
            "data-test-subj": dataTestSubj,
            onClick: function onClick() {
              return _this2.onClickItem(_onClick ? function () {
                return _onClick(item);
              } : undefined);
            }
          }, buttonContent));
        }

        return controls;
      }, []);

      var popoverButton = /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
        token: "ouiCollapsedItemActions.allActions",
        default: "All actions"
      }, function (allActions) {
        return /*#__PURE__*/_react.default.createElement(_button.OuiButtonIcon, {
          className: className,
          "aria-label": allActions,
          iconType: "boxesHorizontal",
          color: "text",
          isDisabled: allDisabled,
          onClick: _this2.togglePopover.bind(_this2),
          onFocus: onFocus,
          "data-test-subj": "ouiCollapsedItemActionsButton"
        });
      });

      var withTooltip = !allDisabled && /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
        token: "ouiCollapsedItemActions.allActions",
        default: "All actions"
      }, function (allActions) {
        return /*#__PURE__*/_react.default.createElement(_tool_tip.OuiToolTip, {
          content: allActions,
          delay: "long"
        }, popoverButton);
      });

      return /*#__PURE__*/_react.default.createElement(_popover.OuiPopover, {
        className: className,
        popoverRef: this.registerPopoverDiv,
        id: "".concat(itemId, "-actions"),
        isOpen: isOpen,
        button: withTooltip || popoverButton,
        closePopover: this.closePopover,
        panelPaddingSize: "none",
        anchorPosition: "leftCenter"
      }, /*#__PURE__*/_react.default.createElement(_context_menu.OuiContextMenuPanel, {
        items: controls
      }));
    }
  }]);
  return CollapsedItemActions;
}(_react.Component);

exports.CollapsedItemActions = CollapsedItemActions;
CollapsedItemActions.propTypes = {
  actions: _propTypes.default.arrayOf(_propTypes.default.oneOfType([_propTypes.default.shape({
    /**
       * The type of action
       */
    type: _propTypes.default.oneOfType([_propTypes.default.oneOf(["button"]), _propTypes.default.oneOf(["icon"]).isRequired]),

    /**
       * Defines the color of the button
       */
    color: _propTypes.default.oneOfType([_propTypes.default.oneOfType([_propTypes.default.oneOf(["primary", "danger", "text", "ghost", "success", "warning"]).isRequired, _propTypes.default.func.isRequired]), _propTypes.default.oneOfType([_propTypes.default.oneOf(["accent", "danger", "ghost", "primary", "subdued", "success", "text", "warning"]).isRequired, _propTypes.default.func.isRequired])]),

    /**
       * The display name of the action (will be the button caption)
       */

    /**
       * The display name of the action (will be the button caption)
       */
    name: _propTypes.default.oneOfType([_propTypes.default.node.isRequired, _propTypes.default.func.isRequired]).isRequired,

    /**
       * Describes the action (will be the button title)
       */

    /**
       * Describes the action (will be the button title)
       */
    description: _propTypes.default.string.isRequired,

    /**
       * A handler function to execute the action
       */

    /**
       * A handler function to execute the action
       */
    onClick: _propTypes.default.func,
    href: _propTypes.default.string,
    target: _propTypes.default.string,

    /**
       * A callback function that determines whether the action is available
       */

    /**
       * A callback function that determines whether the action is available
       */
    available: _propTypes.default.func,

    /**
       * A callback function that determines whether the action is enabled
       */

    /**
       * A callback function that determines whether the action is enabled
       */
    enabled: _propTypes.default.func,
    isPrimary: _propTypes.default.bool,
    "data-test-subj": _propTypes.default.string,

    /**
       * Associates an icon with the button
       */
    icon: _propTypes.default.oneOfType([_propTypes.default.oneOf(["accessibility", "addDataApp", "advancedSettingsApp", "aggregate", "alert", "analyzeEvent", "annotation", "anomalyDetection", "apmApp", "apmTrace", "apps", "appSearchApp", "arrowDown", "arrowLeft", "arrowRight", "arrowUp", "asterisk", "auditbeatApp", "beaker", "bell", "bellSlash", "bolt", "bookOpen", "boxesHorizontal", "boxesVertical", "branch", "broom", "brush", "bug", "bullseye", "calendar", "canvasApp", "codeApp", "chatLeft", "chatRight", "check", "checkInCircleEmpty", "checkInCircleFilled", "cheer", "classificationJob", "clock", "cloudDrizzle", "cloudStormy", "cloudSunny", "color", "compass", "compute", "console", "consoleApp", "continuityAbove", "continuityAboveBelow", "continuityBelow", "continuityWithin", "controlsHorizontal", "controlsVertical", "copy", "copyClipboard", "createAdvancedJob", "createMultiMetricJob", "createPopulationJob", "createSingleMetricJob", "cross", "crossClusterReplicationApp", "crosshairs", "crossInACircleFilled", "crossInCircleEmpty", "crossInCircleFilled", "currency", "cut", "dashboard", "dashboardApp", "database", "dataVisualizer", "devToolsApp", "discoverApp", "document", "documentation", "documentEdit", "documents", "dot", "download", "dockedBottom", "dockedDetached", "dockedLeft", "dockedRight", "dockedTakeover", "dockedTop", "editorAlignCenter", "editorAlignLeft", "editorAlignRight", "editorBold", "editorCodeBlock", "editorComment", "editorDistributeHorizontal", "editorDistributeVertical", "editorHeading", "editorItalic", "editorItemAlignLeft", "editorItemAlignBottom", "editorItemAlignCenter", "editorItemAlignMiddle", "editorItemAlignRight", "editorItemAlignTop", "editorLink", "editorOrderedList", "editorPositionBottomLeft", "editorPositionBottomRight", "editorPositionTopLeft", "editorPositionTopRight", "editorRedo", "editorStrike", "editorTable", "editorUnderline", "editorUndo", "editorUnorderedList", "email", "empty", "emsApp", "eql", "eraser", "exit", "expand", "expandMini", "exportAction", "eye", "eyeClosed", "faceHappy", "faceNeutral", "faceSad", "filebeatApp", "filter", "flag", "fold", "folderCheck", "folderClosed", "folderExclamation", "folderOpen", "frameNext", "framePrevious", "fullScreen", "fullScreenExit", "function", "functionAdd", "gear", "gisApp", "glasses", "globe", "grab", "grabHorizontal", "graphApp", "grid", "grokApp", "heart", "heartbeatApp", "heatmap", "help", "history", "home", "iInCircle", "image", "importAction", "indexClose", "indexEdit", "indexFlush", "indexManagementApp", "indexMapping", "indexOpen", "indexPatternApp", "indexRollupApp", "indexRuntime", "indexSettings", "inputOutput", "inspect", "integrationGeneral", "integrationObservability", "integrationSearch", "integrationSecurity", "invert", "ip", "keyboardShortcut", "kqlField", "kqlFunction", "kqlOperand", "kqlSelector", "kqlValue", "layers", "lensApp", "lineChart", "link", "list", "listAdd", "lock", "lockOpen", "logsApp", "logoAerospike", "logoApache", "logoAppSearch", "logoAWS", "logoAWSMono", "logoAzure", "logoAzureMono", "logoBeats", "logoBusinessAnalytics", "logoCeph", "logoCloud", "logoCloudEnterprise", "logoCode", "logoCodesandbox", "logoCouchbase", "logoDocker", "logoDropwizard", "logoElastic", "logoElasticsearch", "logoElasticStack", "logoEnterpriseSearch", "logoEtcd", "logoGCP", "logoGCPMono", "logoGithub", "logoGmail", "logoGolang", "logoGoogleG", "logoHAproxy", "logoIBM", "logoIBMMono", "logoKafka", "logoKibana", "logoKubernetes", "logoLogging", "logoLogstash", "logoMaps", "logoMemcached", "logoMetrics", "logoMongodb", "logoMySQL", "logoNginx", "logoObservability", "logoOpenSearch", "logoOsquery", "logoPhp", "logoPostgres", "logoPrometheus", "logoRabbitmq", "logoRedis", "logoSecurity", "logoSiteSearch", "logoSketch", "logoSlack", "logoUptime", "logoWebhook", "logoWindows", "logoWorkplaceSearch", "logstashFilter", "logstashIf", "logstashInput", "logstashOutput", "logstashQueue", "machineLearningApp", "magnet", "magnifyWithMinus", "magnifyWithPlus", "managementApp", "mapMarker", "memory", "menu", "menuDown", "menuLeft", "menuRight", "menuUp", "merge", "metricbeatApp", "metricsApp", "minimize", "minus", "minusInCircle", "minusInCircleFilled", "mobile", "monitoringApp", "moon", "nested", "node", "notebookApp", "number", "offline", "online", "outlierDetectionJob", "package", "packetbeatApp", "pageSelect", "pagesSelect", "partial", "paperClip", "pause", "pencil", "percent", "pin", "pinFilled", "pipelineApp", "play", "playFilled", "plus", "plusInCircle", "plusInCircleFilled", "polygon", "popout", "power", "pulse", "push", "questionInCircle", "quote", "radar", "radius", "recent", "recentlyViewedApp", "redeploy", "refresh", "regressionJob", "reporter", "reportingApp", "returnKey", "rocket", "save", "savedObjectsApp", "scale", "search", "searchProfilerApp", "securityAnalyticsApp", "securityApp", "securitySignal", "securitySignalDetected", "securitySignalResolved", "shard", "share", "snowflake", "sortable", "sortDown", "sortLeft", "sortRight", "sortUp", "spacesApp", "sparkleFilled", "sqlApp", "starEmpty", "starEmptySpace", "starFilled", "starFilledSpace", "starMinusEmpty", "starMinusFilled", "starPlusEmpty", "starPlusFilled", "stats", "stop", "stopFilled", "stopSlash", "storage", "string", "submodule", "swatchInput", "symlink", "tableOfContents", "tableDensityExpanded", "tableDensityCompact", "tableDensityNormal", "tag", "tear", "temperature", "thumbsDown", "thumbsUp", "timeline", "timelionApp", "timeslider", "training", "trash", "upgradeAssistantApp", "uptimeApp", "undeploy", "unfold", "unlink", "user", "users", "usersRolesApp", "vector", "videoPlayer", "visArea", "visAreaStacked", "visBarHorizontal", "visBarHorizontalStacked", "visBarVertical", "visBarVerticalStacked", "visBuilder", "visBuilderSavedObject", "visGauge", "visGoal", "visLine", "visMapCoordinate", "visMapRegion", "visMetric", "visPie", "visQueryDQL", "visQueryPPL", "visQueryPromQL", "visQuerySQL", "visTable", "visTagCloud", "visText", "visTimelion", "visualizeApp", "visVega", "visVisualBuilder", "watchesApp", "wordWrap", "wordWrapDisabled", "workplaceSearchApp", "wrench", "tokenClass", "tokenProperty", "tokenEnum", "tokenVariable", "tokenMethod", "tokenAnnotation", "tokenException", "tokenInterface", "tokenParameter", "tokenField", "tokenElement", "tokenFunction", "tokenBoolean", "tokenString", "tokenArray", "tokenNumber", "tokenConstant", "tokenObject", "tokenEvent", "tokenKey", "tokenNull", "tokenStruct", "tokenPackage", "tokenOperator", "tokenEnumMember", "tokenRepo", "tokenSymbol", "tokenFile", "tokenModule", "tokenNamespace", "tokenDate", "tokenIP", "tokenNested", "tokenAlias", "tokenShape", "tokenGeo", "tokenRange", "tokenBinary", "tokenJoin", "tokenPercolator", "tokenFlattened", "tokenRankFeature", "tokenRankFeatures", "tokenKeyword", "tokenCompletionSuggester", "tokenDenseVector", "tokenText", "tokenTokenCount", "tokenSearchType", "tokenHistogram", "wsAnalytics", "wsEssentials", "wsObservability", "wsSearch", "wsSecurityAnalytics", "wsSelector"]).isRequired, _propTypes.default.func.isRequired])
  }).isRequired, _propTypes.default.shape({
    /**
       * The function that renders the action. Note that the returned node is expected to have `onFocus` and `onBlur` functions
       */
    render: _propTypes.default.func.isRequired,

    /**
       * A callback that defines whether the action is available
       */
    available: _propTypes.default.func,

    /**
       * A callback that defines whether the action is enabled
       */
    enabled: _propTypes.default.func,
    isPrimary: _propTypes.default.bool
  }).isRequired]).isRequired).isRequired,
  item: _propTypes.default.any.isRequired,
  itemId: _propTypes.default.oneOfType([_propTypes.default.string.isRequired, _propTypes.default.number.isRequired]).isRequired,
  actionEnabled: _propTypes.default.func.isRequired,
  className: _propTypes.default.string,
  onFocus: _propTypes.default.func,
  onBlur: _propTypes.default.func
};