"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _classnames = _interopRequireDefault(require("classnames"));
var _reactMeasure = _interopRequireDefault(require("react-measure"));
var _constants = require("../../constants");
var _Icon = _interopRequireWildcard(require("../Icon"));
var _Label = _interopRequireDefault(require("../Label"));
var _Dropdown = _interopRequireDefault(require("../Dropdown"));
var _Menu = _interopRequireWildcard(require("../Menu"));
var _Tab = _interopRequireDefault(require("./Tab"));
var _ResponsiveContext = _interopRequireDefault(require("../ResponsiveContext"));
var _utils = require("../utils");
var _jsxRuntime = require("react/jsx-runtime");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

const ADDON_LEFT_PADDING = 5;
const MIN_ADDON_WIDTH_DEFAULT = 150;
const COLLAPSED_SEARCH_WIDTH = 60;

/**
 * `Tabs` component is a content area with a group of individual [Tab](#!/Tab) elements, each displaying different content
 * in the same screen area. `Tabs` are used when you have too much content to display in one place at the same time, so
 * the content is broken into logical groups and each group is displayed under its own [Tab](#!/Tab) that serves both as a
 * group name and a navigation button.
 * @since 0.0.35
 */
class Tabs extends _react.Component {
  constructor() {
    super(...arguments);
    (0, _defineProperty2.default)(this, "state", {
      active: this.props.active || 1,
      collapsedLength: 0,
      compact: false,
      searching: false,
      monospacedWidth: null
    });
    (0, _defineProperty2.default)(this, "widths", null);
    (0, _defineProperty2.default)(this, "checkAdaptive", () => {
      let {
        compact,
        searching,
        collapsedLength
      } = this.state;
      const {
        addonMinWidth: addonMinWidthProp,
        search,
        monospaced
      } = this.props;
      const {
        widths,
        addon
      } = this;
      let monospacedWidth = null;
      const getMonospacedWidth = () => monospacedWidth;
      if (!widths) {
        return;
      }
      const addonMinWidth = ADDON_LEFT_PADDING + (addonMinWidthProp || (search ? search.props.minWidth : MIN_ADDON_WIDTH_DEFAULT));
      const searchWidth = compact && search ? COLLAPSED_SEARCH_WIDTH + ADDON_LEFT_PADDING : 0;
      const {
        more,
        container,
        margin
      } = widths;
      let tabs = widths.tabs.slice();
      const tabsNumber = tabs.length;
      let lastTabIndex = tabsNumber - 1 - collapsedLength;
      if (monospaced) {
        monospacedWidth = tabs.slice(0, lastTabIndex + 1).reduce((max, tab) => tab > max ? tab : max, 0);
        tabs = tabs.map(getMonospacedWidth);
      }
      const getListWidth = () => {
        let listWidth = monospaced ? margin * Math.max(0, tabsNumber - 1 - Math.max(0, collapsedLength - 1)) : 0;
        for (let i = 0; i <= lastTabIndex; ++i) {
          listWidth += tabs[i];
        }
        if (collapsedLength) {
          listWidth += more;
        }
        return listWidth;
      };
      let spaceForAddon = container - getListWidth();
      if (addon && !collapsedLength && !compact && spaceForAddon <= addonMinWidth) {
        compact = true;
      }
      let freeSpace = spaceForAddon - searchWidth;
      if (freeSpace <= 0) {
        // collapse
        for (let i = lastTabIndex; i >= 0; --i) {
          let width = tabs[i];
          if (monospaced && widths.tabs[i] === monospacedWidth) {
            monospacedWidth = widths.tabs.slice(0, lastTabIndex).reduce((max, tab) => tab > max ? tab : max, 0);
            tabs = tabs.map(getMonospacedWidth);
            width += (widths.tabs[i] - monospacedWidth) * lastTabIndex;
          }
          if (collapsedLength === 0) {
            width -= more;
          }
          freeSpace += width;
          ++collapsedLength;
          --lastTabIndex;
          if (freeSpace > 0) {
            break;
          }
        }
      } else {
        // expand
        for (let i = lastTabIndex + 1; i < tabsNumber; ++i) {
          let width = tabs[i];
          if (monospaced && widths.tabs[i] > monospacedWidth) {
            monospacedWidth = widths.tabs[i];
            tabs = tabs.map(getMonospacedWidth);
            width = monospacedWidth + (monospacedWidth - width) * (lastTabIndex + 1);
          }
          if (collapsedLength === 1) {
            width -= more;
          }
          if (freeSpace <= width) {
            break;
          }
          freeSpace -= width;
          --collapsedLength;
          ++lastTabIndex;
        }
      }
      if (collapsedLength || compact) {
        spaceForAddon = container - getListWidth();
        if (collapsedLength) {
          compact = true;
        } else if (spaceForAddon >= addonMinWidth) {
          compact = false;
          searching = false;
        }
      }
      const newState = {
        compact,
        searching,
        collapsedLength,
        monospacedWidth
      };
      const keys = Object.keys(newState);
      for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        if (JSON.stringify(newState[key]) === JSON.stringify(this.state[key])) {
          delete newState[key];
        }
      }
      if (Object.keys(newState).length) {
        this.setState(newState, () => {
          if (typeof newState.collapsedLength !== 'undefined' && this.state.collapsedLength !== newState.collapsedLength) {
            this.checkAdaptive();
          }
        });
      }
    });
    (0, _defineProperty2.default)(this, "handleStartSearching", () => {
      this.setState({
        searching: true
      });
    });
    (0, _defineProperty2.default)(this, "handleCancelSearching", () => {
      this.setState({
        searching: false
      }, this.checkAdaptive);
    });
    (0, _defineProperty2.default)(this, "handleResize", () => {
      const {
        baseClassName
      } = this.props;
      if (this.tabsnavRef) {
        const tabElements = this.tabsnavRef.querySelectorAll(`.${baseClassName}__tab-list--fake .${baseClassName}__tab`);
        const more = tabElements[tabElements.length - 1];
        const tabs = Array.prototype.slice.call(tabElements, 0, -1).map(el => el.offsetWidth);
        this.widths = {
          tabs,
          more: more.offsetWidth,
          container: this.tabsnavRef.offsetWidth,
          margin: more.offsetWidth - more.querySelector(`.${baseClassName}__link`).offsetWidth
        };
      }
      this.checkAdaptive();
    });
    (0, _defineProperty2.default)(this, "handleAddonResize", contentRect => {
      this.addon = contentRect.bounds;
      this.checkAdaptive();
    });
    (0, _defineProperty2.default)(this, "renderTabItem", (tab, index, tabMode) => {
      const {
        baseClassName
      } = this.props;
      const {
        monospacedWidth,
        active
      } = this.state;
      if (!tab || tab.type !== _Tab.default) {
        return null;
      }
      const {
        title,
        label,
        icon,
        onActivate,
        onClose,
        component: Tag = 'a',
        ...tabProps
      } = tab.props;
      const selected = index + 1 === active;
      const key = index.toString();
      const tabIcon = _Icon.default.create(icon, {
        size: _Icon.ICON_SIZE_16,
        className: `${baseClassName}__tab-icon`
      });
      const tabLabel = this.renderTabLabel(tabMode, label);
      const tabClose = this.renderTabClose(tabMode, onClose);
      const handleClick = () => this.onClick(index + 1);
      tabProps.tabIndex = tabProps.tabIndex || 0;
      tabProps.onKeyDown = (0, _utils.wrapFunction)(tabProps.onKeyDown, e => {
        if (e.key === 'Enter') {
          e.currentTarget.click();
        }
      });
      if (tabMode === 'menu-item') {
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Menu.MenuItem, {
          icon: tabIcon,
          label: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_react.Fragment, {
            children: [tabLabel, tabClose]
          }),
          active: selected,
          onClick: handleClick,
          className: `${baseClassName}__menu-item`,
          component: Tag,
          ...tabProps,
          children: title
        }, key);
      }
      return /*#__PURE__*/(0, _jsxRuntime.jsx)("li", {
        className: (0, _classnames.default)(`${baseClassName}__tab`, selected && `${baseClassName}__tab--selected`, tabClose && `${baseClassName}__tab--closable`),
        role: "presentation",
        children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(Tag, {
          className: `${baseClassName}__link`,
          role: "tab",
          "aria-selected": selected || null,
          style: {
            width: monospacedWidth
          },
          onClick: handleClick,
          ...tabProps,
          children: [tabIcon, /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
            className: `${baseClassName}__tab-title`,
            children: title
          }), tabLabel, tabClose]
        })
      }, key);
    });
  }
  static getDerivedStateFromProps(props, state) {
    const {
      active
    } = props;
    const {
      prevActive
    } = state;
    const nextState = {};
    if (active && active !== prevActive) {
      nextState.active = active;
    }
    nextState.prevActive = active;
    return nextState;
  }
  componentDidUpdate() {
    if (!this.widths || this.props.children.length !== this.widths.tabs.length) {
      setTimeout(() => this.handleResize(), 0);
    }
  }
  onClick(active) {
    this.setState({
      active
    });
    const tab = this.props.children[active - 1];
    const {
      onActivate
    } = tab.props;
    if (onActivate) {
      onActivate();
    }
  }
  renderTabLabel(tabMode, label) {
    const {
      baseClassName
    } = this.props;
    if (typeof label === 'string') {
      return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Label.default, {
        className: `${baseClassName}__${tabMode}-label`,
        intent: "danger",
        children: label
      });
    }
    if ( /*#__PURE__*/(0, _react.isValidElement)(label)) {
      return /*#__PURE__*/(0, _react.cloneElement)(label, {
        className: (0, _classnames.default)(`${baseClassName}__${tabMode}-label`, label.props.className)
      });
    }
    return null;
  }
  renderTabClose(tabMode, onClose) {
    const {
      baseClassName
    } = this.props;
    if (typeof onClose === 'function') {
      return /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
        className: `${baseClassName}__${tabMode}-close`,
        type: "button",
        onClick: e => {
          e.preventDefault();
          e.stopPropagation();
          onClose(e);
        },
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Icon.default, {
          className: `${baseClassName}__${tabMode}-close-icon`,
          name: "cross-mark"
        })
      });
    }
    return null;
  }
  renderFakeTabs() {
    const {
      baseClassName,
      children
    } = this.props;
    const childrenCount = _react.Children.count(children);
    if (!childrenCount) {
      return null;
    }
    return /*#__PURE__*/(0, _jsxRuntime.jsxs)("ul", {
      className: (0, _classnames.default)(`${baseClassName}__tab-list`, `${baseClassName}__tab-list--fake`),
      children: [_react.Children.map(children, tab => {
        if (!tab || tab.type !== _Tab.default) {
          return null;
        }
        const {
          title,
          label,
          icon,
          onActivate,
          onClose,
          ...tabProps
        } = tab.props;
        const iconBlock = _Icon.default.create(icon, {
          size: _Icon.ICON_SIZE_16,
          className: `${baseClassName}__tab-icon`
        });
        const closeBlock = this.renderTabClose('tab', onClose);
        return /*#__PURE__*/(0, _jsxRuntime.jsxs)("li", {
          className: (0, _classnames.default)(`${baseClassName}__tab`, closeBlock && `${baseClassName}__tab--closable`),
          children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("a", {
            className: `${baseClassName}__link`,
            tabIndex: "-1",
            style: tabProps.style,
            children: [iconBlock, /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
              className: `${baseClassName}__tab-title`,
              children: title
            }), this.renderTabLabel('tab', label)]
          }), closeBlock]
        }, title);
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)("li", {
        className: (0, _classnames.default)(`${baseClassName}__tab`, `${baseClassName}__tab--more`),
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)("a", {
          className: `${baseClassName}__link`,
          tabIndex: "-1",
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Icon.default, {
            name: "three-dots-horizontal"
          })
        })
      })]
    });
  }
  createTabItems() {
    const {
      children
    } = this.props;
    const {
      collapsedLength
    } = this.state;
    const visibleItems = [];
    const hiddenItems = [];
    const lastTabIndex = _react.Children.count(children) - 1 - collapsedLength;
    _react.Children.forEach(children, (child, index) => {
      const hidden = index > lastTabIndex;
      const tabMode = hidden ? 'menu-item' : 'tab';
      (hidden ? hiddenItems : visibleItems).push(this.renderTabItem(child, index, tabMode));
    });
    return {
      visibleItems,
      hiddenItems
    };
  }
  renderTabList() {
    const {
      baseClassName,
      children
    } = this.props;
    const {
      active
    } = this.state;
    if (!_react.Children.toArray(children).length) {
      return null;
    }
    const {
      visibleItems,
      hiddenItems
    } = this.createTabItems();
    const moreSelected = active > visibleItems.length;
    return /*#__PURE__*/(0, _jsxRuntime.jsxs)("ul", {
      className: `${baseClassName}__tab-list`,
      role: "tablist",
      children: [visibleItems, hiddenItems.length > 0 && /*#__PURE__*/(0, _jsxRuntime.jsx)("li", {
        ref: ref => this.moreTabsRef = ref,
        className: (0, _classnames.default)(`${baseClassName}__tab`, moreSelected && `${baseClassName}__tab--selected`, `${baseClassName}__tab--more`),
        role: "presentation",
        "aria-selected": moreSelected || null,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Dropdown.default, {
          className: `${baseClassName}__dropdown`,
          menu: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Menu.default, {
            children: hiddenItems
          }),
          menuPlacement: "bottom-end",
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)("a", {
            className: `${baseClassName}__link`,
            role: "tab",
            tabIndex: "0",
            "aria-selected": moreSelected || null,
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Icon.default, {
              name: "three-dots-horizontal"
            })
          })
        })
      })]
    });
  }
  renderSearchBar(searchProps) {
    const {
      baseClassName,
      search
    } = this.props;
    const {
      compact
    } = this.state;
    const clone = /*#__PURE__*/(0, _react.cloneElement)(search, searchProps);
    if (compact) {
      return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: `${baseClassName}__search`,
        children: clone
      });
    }
    return clone;
  }
  render() {
    const {
      baseClassName,
      className,
      addon,
      placeholder,
      children,
      active,
      addonMinWidth,
      monospaced,
      search,
      ...props
    } = this.props;
    const {
      compact,
      searching
    } = this.state;
    const childrenCount = _react.Children.count(children);
    if (!childrenCount) {
      return null;
    }
    let addonBlock = addon || placeholder;
    const addonProps = {};
    let searchBlock = null;
    if (search) {
      const searchProps = {
        collapsable: compact,
        onExpand: this.handleStartSearching,
        onCollapse: this.handleCancelSearching
      };
      if (compact) {
        if (searching) {
          searchProps.maxWidth = null;
          searchProps.minWidth = null;
          searchProps.autoFocus = true;
          searchProps.responsive = false;
        } else {
          searchProps.onSearch = this.handleStartSearching;
        }
        searchBlock = this.renderSearchBar(searchProps);
      } else if (addonBlock) {
        searchProps.key = 1;
        addonBlock = [this.renderSearchBar(searchProps), /*#__PURE__*/(0, _react.cloneElement)(addonBlock, {
          key: 2
        })];
      } else {
        addonProps.style = {
          maxWidth: search.props.maxWidth
        };
        addonBlock = this.renderSearchBar(searchProps);
      }
    }
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_ResponsiveContext.default.Provider, {
      value: compact,
      children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: (0, _classnames.default)(baseClassName, className),
        ...props,
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactMeasure.default, {
          onResize: this.handleResize,
          innerRef: ref => this.tabsnavRef = ref,
          children: _ref => {
            let {
              measureRef
            } = _ref;
            return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
              className: (0, _classnames.default)(`${baseClassName}__nav`, compact && `${baseClassName}__nav--compact`, searching && `${baseClassName}__nav--searching`, search && `${baseClassName}__nav--search`),
              ref: measureRef,
              children: [this.renderTabList(), /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactMeasure.default, {
                onResize: this.handleResize,
                children: _ref2 => {
                  let {
                    measureRef: ref
                  } = _ref2;
                  return /*#__PURE__*/(0, _react.cloneElement)(this.renderFakeTabs(), {
                    ref
                  });
                }
              }), searchBlock, addonBlock && /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactMeasure.default, {
                onResize: this.handleAddonResize,
                bounds: true,
                children: _ref3 => {
                  let {
                    measureRef: ref
                  } = _ref3;
                  return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
                    className: `${baseClassName}__addon`,
                    ref: ref,
                    ...addonProps,
                    children: addonBlock
                  });
                }
              })]
            });
          }
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          className: `${baseClassName}__tab-panel`,
          role: "tabpanel",
          children: _react.Children.map(children, (tab, index) => index + 1 === this.state.active ? tab : null)
        })]
      })
    });
  }
}
Tabs.propTypes = {
  /**
   * Number of active tab
   * @since 0.0.35
   */
  active: _propTypes.default.number,
  /**
   * Addon for search bar, dropdown etc.
   * @since 0.0.58
   */
  addon: _propTypes.default.element,
  /**
   * Placeholder for search bar, dropdown etc.
   *
   * @deprecated Do not use! Use `addon` instead!
   * @since 0.0.42
   */
  placeholder: _propTypes.default.element,
  /**
   * Minimum add-on width in pixels
   * @since 0.0.58
   */
  addonMinWidth: _propTypes.default.number,
  /**
   * Monospaced version of tabs (all visible tabs as wide as widest of them)
   * @since 0.0.58
   */
  monospaced: _propTypes.default.bool,
  /**
   * [SearchBar](#!/SearchBar) element
   * @since 0.0.58
   */
  search: _propTypes.default.element,
  /**
   * [Tabs](#!/Tab)
   * @since 0.0.47
   */
  children: _propTypes.default.oneOfType([_propTypes.default.arrayOf(_propTypes.default.element), _propTypes.default.element]),
  /**
   * @ignore
   */
  className: _propTypes.default.string,
  /**
   * @ignore
   */
  baseClassName: _propTypes.default.string
};
Tabs.defaultProps = {
  active: null,
  addon: null,
  placeholder: null,
  addonMinWidth: null,
  monospaced: null,
  search: null,
  children: null,
  className: null,
  baseClassName: `${_constants.CLS_PREFIX}tabs`
};
var _default = exports.default = Tabs;