"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.EuiTabbedContent = exports.AUTOFOCUS = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _services = require("../../../services");
var _tabs = require("../tabs");
var _tab = require("../tab");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) { "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); } return f; })(e, t); }
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); }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) { ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } } return n; }, _extends.apply(null, arguments); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) { o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) { if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } } return t; }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) { n[e] = r[e]; } return n; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _createSuper(t) { var r = _isNativeReflectConstruct(); return function () { var e, o = _getPrototypeOf(t); if (r) { var s = _getPrototypeOf(this).constructor; e = Reflect.construct(o, arguments, s); } else e = o.apply(this, arguments); return _possibleConstructorReturn(this, e); }; }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
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); } /*
 * 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.
 */
/**
 * Marked as const so type is `['initial', 'selected']` instead of `string[]`
 */
var AUTOFOCUS = ['initial', 'selected'];
exports.AUTOFOCUS = AUTOFOCUS;
var EuiTabbedContent = /*#__PURE__*/function (_Component) {
  _inherits(EuiTabbedContent, _Component);
  var _super = _createSuper(EuiTabbedContent);
  function EuiTabbedContent(props) {
    var _this;
    _classCallCheck(this, EuiTabbedContent);
    _this = _super.call(this, props);
    _defineProperty(_assertThisInitialized(_this), "rootId", (0, _services.htmlIdGenerator)()());
    _defineProperty(_assertThisInitialized(_this), "tabsRef", /*#__PURE__*/(0, _react.createRef)());
    _defineProperty(_assertThisInitialized(_this), "focusTab", function () {
      var targetTab = _this.tabsRef.current.querySelector("#".concat(_this.state.selectedTabId));
      targetTab.focus();
    });
    _defineProperty(_assertThisInitialized(_this), "initializeFocus", function () {
      if (!_this.state.inFocus && _this.props.autoFocus === 'selected') {
        // Must wait for setState to finish before calling `.focus()`
        // as the focus call triggers a blur on the first tab
        _this.setState({
          inFocus: true
        }, function () {
          _this.focusTab();
        });
      }
    });
    // todo: figure out type for blurEvent
    _defineProperty(_assertThisInitialized(_this), "removeFocus", function (blurEvent) {
      // only set inFocus to false if the wrapping div doesn't contain the now-focusing element
      var currentTarget = blurEvent.currentTarget;
      var relatedTarget = blurEvent.relatedTarget;
      if (currentTarget.contains(relatedTarget) === false) {
        _this.setState({
          inFocus: false
        });
      }
    });
    _defineProperty(_assertThisInitialized(_this), "onTabClick", function (selectedTab) {
      var _this$props = _this.props,
        onTabClick = _this$props.onTabClick,
        externalSelectedTab = _this$props.selectedTab;
      if (onTabClick) {
        onTabClick(selectedTab);
      }

      // Only track selection state if it's not controlled externally.
      _this.setState(function (prevState) {
        return {
          selectedTabId: externalSelectedTab ? prevState.selectedTabId : selectedTab.id,
          preservedTabsId: [].concat(_toConsumableArray(prevState.preservedTabsId), [selectedTab.id])
        };
      });
    });
    var initialSelectedTab = props.initialSelectedTab,
      _selectedTab = props.selectedTab,
      tabs = props.tabs; // Only track selection state if it's not controlled externally.
    var selectedTabId;
    if (!_selectedTab) {
      selectedTabId = initialSelectedTab && initialSelectedTab.id || tabs[0].id;
    }
    var preservedTabsId = [];
    preservedTabsId.push(_selectedTab ? _selectedTab.id : initialSelectedTab && initialSelectedTab.id || tabs[0].id);
    _this.state = {
      selectedTabId: selectedTabId,
      preservedTabsId: preservedTabsId,
      inFocus: false
    };
    return _this;
  }
  _createClass(EuiTabbedContent, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      // IE11 doesn't support the `relatedTarget` event property for blur events
      // but does add it for focusout. React doesn't support `onFocusOut` so here we are.
      if (this.tabsRef.current) {
        // Current short-term solution for event listener (see https://github.com/elastic/oui/pull/2717)
        this.tabsRef.current.addEventListener('focusout', this.removeFocus);
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      if (this.tabsRef.current) {
        // Current short-term solution for event listener (see https://github.com/elastic/oui/pull/2717)
        this.tabsRef.current.removeEventListener('focusout', this.removeFocus);
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;
      var _this$props2 = this.props,
        className = _this$props2.className,
        display = _this$props2.display,
        expand = _this$props2.expand,
        initialSelectedTab = _this$props2.initialSelectedTab,
        onTabClick = _this$props2.onTabClick,
        externalSelectedTab = _this$props2.selectedTab,
        size = _this$props2.size,
        tabs = _this$props2.tabs,
        autoFocus = _this$props2.autoFocus,
        preserveTabContent = _this$props2.preserveTabContent,
        rest = _objectWithoutProperties(_this$props2, ["className", "display", "expand", "initialSelectedTab", "onTabClick", "selectedTab", "size", "tabs", "autoFocus", "preserveTabContent"]); // Allow the consumer to control tab selection.
      var selectedTab = externalSelectedTab || tabs.find(function (tab) {
        return tab.id === _this2.state.selectedTabId;
      });
      var _ref = selectedTab,
        selectedTabContent = _ref.content,
        selectedTabId = _ref.id;
      return /*#__PURE__*/_react.default.createElement("div", _extends({
        className: className
      }, rest), /*#__PURE__*/_react.default.createElement(_tabs.EuiTabs, {
        ref: this.tabsRef,
        expand: expand,
        display: display,
        size: size,
        onFocus: this.initializeFocus
      }, tabs.map(function (tab) {
        var id = tab.id,
          name = tab.name,
          content = tab.content,
          tabProps = _objectWithoutProperties(tab, ["id", "name", "content"]);
        var props = _objectSpread(_objectSpread({
          key: id,
          id: id
        }, tabProps), {}, {
          onClick: function onClick() {
            return _this2.onTabClick(tab);
          },
          isSelected: tab === selectedTab,
          'aria-controls': "".concat(_this2.rootId)
        });
        return /*#__PURE__*/_react.default.createElement(_tab.EuiTab, props, name);
      })), !preserveTabContent && /*#__PURE__*/_react.default.createElement("div", {
        role: "tabpanel",
        id: "".concat(this.rootId),
        "aria-labelledby": selectedTabId
      }, selectedTabContent), preserveTabContent && tabs.map(function (tab) {
        var id = tab.id,
          content = tab.content;
        if (_this2.state.preservedTabsId.includes(id)) {
          return /*#__PURE__*/_react.default.createElement("div", {
            key: id,
            role: "tabpanel",
            id: id,
            "aria-labelledby": id,
            style: id === selectedTabId ? undefined : {
              display: 'none'
            }
          }, content);
        }
      }));
    }
  }]);
  return EuiTabbedContent;
}(_react.Component);
exports.EuiTabbedContent = EuiTabbedContent;
_defineProperty(EuiTabbedContent, "defaultProps", {
  autoFocus: 'initial',
  preserveTabContent: false
});
EuiTabbedContent.propTypes = {
  className: _propTypes.default.string,
  "aria-label": _propTypes.default.string,
  "data-test-subj": _propTypes.default.string,
  /**
       * When tabbing into the tabs, set the focus on `initial` for the first tab,
       * or `selected` for the currently selected tab. Best use case is for inside of
       * overlay content like popovers or flyouts.
       */
  autoFocus: _propTypes.default.oneOf(["initial", "selected"]),
  /**
       * Choose `default` or alternative `condensed` display styles
       */
  display: _propTypes.default.oneOf(["condensed", "default"]),
  /**
       * Evenly stretches each tab to fill the horizontal space
       */
  expand: _propTypes.default.bool,
  /**
       * Use this prop to set the initially selected tab while letting the tabbed content component
       * control selection state internally
       */
  initialSelectedTab: _propTypes.default.shape({
    id: _propTypes.default.string.isRequired,
    name: _propTypes.default.node.isRequired,
    content: _propTypes.default.node.isRequired
  }),
  onTabClick: _propTypes.default.func,
  /**
       * Use this prop if you want to control selection state within the owner component
       */
  selectedTab: _propTypes.default.shape({
    id: _propTypes.default.string.isRequired,
    name: _propTypes.default.node.isRequired,
    content: _propTypes.default.node.isRequired
  }),
  size: _propTypes.default.oneOf(["s", "m", "l"]),
  /**
       * Each tab needs id and content properties, so we can associate it with its panel for accessibility.
       * The name property (a node) is also required to display to the user.
       */
  tabs: _propTypes.default.arrayOf(_propTypes.default.shape({
    id: _propTypes.default.string.isRequired,
    name: _propTypes.default.node.isRequired,
    content: _propTypes.default.node.isRequired
  }).isRequired).isRequired,
  /**
       * Use this prop to allow tab content stay in dom, if the tab has been selected.
       */
  preserveTabContent: _propTypes.default.bool
};