"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports["default"] = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _react = _interopRequireDefault(require("react"));
var _ComposerSidebarSt = require("./ComposerSidebar.st.css.js");
var _constants = require("./constants");
var _Box = _interopRequireDefault(require("../Box"));
var _ToggleButton = _interopRequireDefault(require("../ToggleButton"));
var _Text = _interopRequireDefault(require("../Text"));
var _excluded = ["label", "id", "icon", "disabled", "sectionTitle"];
var _jsxFileName = "/home/builduser/work/57e038ea7326c1ec/packages/wix-design-system/dist/cjs/ComposerSidebar/ComposerSidebar.jsx";
function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2["default"])(o), (0, _possibleConstructorReturn2["default"])(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2["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 isItemEnabled = function isItemEnabled(item) {
  return !item.disabled;
};
var getNextEnabledIndex = function getNextEnabledIndex(items, currentIndex, direction) {
  var len = items.length;
  var next = (currentIndex + direction + len) % len;
  var steps = 0;
  while (steps < len && !isItemEnabled(items[next])) {
    next = (next + direction + len) % len;
    steps++;
  }
  return steps < len ? next : currentIndex;
};
var getFirstEnabledIndex = function getFirstEnabledIndex(items) {
  for (var i = 0; i < items.length; i++) {
    if (isItemEnabled(items[i])) return i;
  }
  return -1;
};
var getLastEnabledIndex = function getLastEnabledIndex(items) {
  for (var i = items.length - 1; i >= 0; i--) {
    if (isItemEnabled(items[i])) return i;
  }
  return -1;
};
var getPreferredFocusIndex = function getPreferredFocusIndex(items, selectedIndex) {
  if (items.length === 0) return -1;
  var preferred = Math.min(selectedIndex, items.length - 1);
  return isItemEnabled(items[preferred]) ? preferred : getFirstEnabledIndex(items);
};

/** ComposerSidebar */
var ComposerSidebar = /*#__PURE__*/function (_React$PureComponent) {
  function ComposerSidebar() {
    var _this;
    (0, _classCallCheck2["default"])(this, ComposerSidebar);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _callSuper(this, ComposerSidebar, [].concat(args));
    _this.state = {
      focusedIndex: null
    };
    _this._sectionContainerRef = /*#__PURE__*/_react["default"].createRef();
    _this._itemRefs = {};
    _this._getSelectedIndex = function () {
      var _this$props = _this.props,
        items = _this$props.items,
        selectedId = _this$props.selectedId;
      if (selectedId == null) return 0;
      var index = items.findIndex(function (item) {
        return item.id === selectedId;
      });
      return index >= 0 ? index : 0;
    };
    _this._getEffectiveFocusedIndex = function () {
      var items = _this.props.items;
      var focusedIndex = _this.state.focusedIndex;
      if (items.length === 0) return -1;
      if (focusedIndex !== null) return focusedIndex;
      return getPreferredFocusIndex(items, _this._getSelectedIndex());
    };
    _this._handleKeyDown = function (e) {
      var items = _this.props.items;
      if (items.length === 0) return;
      var effectiveIndex = _this._getEffectiveFocusedIndex();
      var currentIndex = effectiveIndex >= 0 ? effectiveIndex : getFirstEnabledIndex(items);
      var nextIndex = currentIndex;
      switch (e.key) {
        case 'ArrowDown':
          nextIndex = getNextEnabledIndex(items, currentIndex, 1);
          break;
        case 'ArrowUp':
          nextIndex = getNextEnabledIndex(items, currentIndex, -1);
          break;
        case 'Home':
          nextIndex = getFirstEnabledIndex(items);
          break;
        case 'End':
          nextIndex = getLastEnabledIndex(items);
          break;
        default:
          return;
      }
      if (nextIndex !== -1 && nextIndex !== currentIndex && isItemEnabled(items[nextIndex])) {
        _this.setState({
          focusedIndex: nextIndex
        }, function () {
          var _itemEl$querySelector;
          var itemEl = _this._itemRefs[nextIndex];
          itemEl == null || itemEl.querySelector == null || (_itemEl$querySelector = itemEl.querySelector('button')) == null || _itemEl$querySelector.focus();
        });
        e.preventDefault();
      }
    };
    _this._handleFocusOut = function (e) {
      var container = _this._sectionContainerRef.current;
      if (!container) return;
      var relatedTarget = e.relatedTarget;
      if (!relatedTarget || container.contains(relatedTarget)) return;
      _this.setState({
        focusedIndex: null
      });
    };
    _this._renderSection = function (_ref) {
      var _ref$section = _ref.section,
        sectionItems = _ref$section.items,
        sectionTitle = _ref$section.sectionTitle,
        _ref$showSectionTitle = _ref.showSectionTitles,
        showSectionTitles = _ref$showSectionTitle === void 0 ? false : _ref$showSectionTitle;
      var _this$props2 = _this.props,
        selectedId = _this$props2.selectedId,
        labelPlacement = _this$props2.labelPlacement;
      return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, showSectionTitles ? /*#__PURE__*/_react["default"].createElement(_Text["default"], {
        className: _ComposerSidebarSt.classes.title,
        size: "small",
        weight: "bold",
        ellipsis: true,
        __self: _this,
        __source: {
          fileName: _jsxFileName,
          lineNumber: 174,
          columnNumber: 11
        }
      }, sectionTitle !== null && sectionTitle !== void 0 ? sectionTitle : 'Undefined') : null, /*#__PURE__*/_react["default"].createElement("ul", {
        role: "menu",
        "data-hook": "composer-sidebar-items-container",
        "data-selected-id": selectedId,
        "data-label-placement": labelPlacement,
        className: _ComposerSidebarSt.classes.itemsContainer,
        __self: _this,
        __source: {
          fileName: _jsxFileName,
          lineNumber: 178,
          columnNumber: 9
        }
      }, sectionItems.map(function (item) {
        return _this._renderItem(item);
      })));
    };
    _this._renderSections = function (sections) {
      var _this$props3 = _this.props,
        labelPlacement = _this$props3.labelPlacement,
        size = _this$props3.size,
        width = _this$props3.width;
      var withSections = sections.length > 1 || sections.length === 1 && sections[0].sectionTitle;
      return /*#__PURE__*/_react["default"].createElement("div", {
        ref: _this._sectionContainerRef,
        role: withSections ? 'menu' : undefined,
        direction: "vertical",
        onKeyDown: _this._handleKeyDown,
        onBlur: _this._handleFocusOut,
        className: (0, _ComposerSidebarSt.st)(_ComposerSidebarSt.classes.sectionContainer, {
          withSections: withSections,
          labelPlacement: labelPlacement,
          size: size
        }),
        style: width ? {
          width: width
        } : undefined,
        __self: _this,
        __source: {
          fileName: _jsxFileName,
          lineNumber: 198,
          columnNumber: 7
        }
      }, withSections ? sections.map(function (section, index) {
        return /*#__PURE__*/_react["default"].createElement("div", {
          key: index,
          role: "menuitem",
          className: _ComposerSidebarSt.classes.section,
          __self: _this,
          __source: {
            fileName: _jsxFileName,
            lineNumber: 213,
            columnNumber: 15
          }
        }, _this._renderSection({
          section: section,
          showSectionTitles: true
        }));
      }) : _this._renderSection({
        section: sections[0]
      }));
    };
    _this._separateToSections = function (items) {
      var sectionTitles = Array.from(new Set(items.map(function (_ref2) {
        var sectionTitle = _ref2.sectionTitle;
        return sectionTitle ? sectionTitle : undefined;
      })));
      var sections = sectionTitles.map(function (sectionTitle) {
        return {
          sectionTitle: sectionTitle,
          items: items.filter(function (_ref3) {
            var itemSectionTitle = _ref3.sectionTitle;
            return !sectionTitle && !itemSectionTitle || sectionTitle === itemSectionTitle;
          })
        };
      });
      return sections;
    };
    return _this;
  }
  (0, _inherits2["default"])(ComposerSidebar, _React$PureComponent);
  return (0, _createClass2["default"])(ComposerSidebar, [{
    key: "_renderItem",
    value: function _renderItem(item) {
      var _this2 = this;
      var _this$props4 = this.props,
        items = _this$props4.items,
        selectedId = _this$props4.selectedId,
        labelPlacement = _this$props4.labelPlacement,
        size = _this$props4.size,
        onClick = _this$props4.onClick,
        className = _this$props4.className,
        labelTooltipProps = _this$props4.labelTooltipProps,
        ellipsis = _this$props4.ellipsis;
      var label = item.label,
        id = item.id,
        icon = item.icon,
        disabled = item.disabled,
        sectionTitle = item.sectionTitle,
        rest = (0, _objectWithoutProperties2["default"])(item, _excluded);
      var itemIndex = items.findIndex(function (i) {
        return i.id === id;
      });
      var selected = selectedId === id;
      var onClickHandler = item.onClick || onClick;
      var effectiveFocusedIndex = this._getEffectiveFocusedIndex();
      var isFocused = effectiveFocusedIndex === itemIndex;
      return /*#__PURE__*/_react["default"].createElement("li", {
        ref: function ref(el) {
          _this2._itemRefs[itemIndex] = el;
        },
        role: "menuitem",
        "data-hook": "composer-sidebar-item-container-".concat(id),
        key: "sidebar-item-".concat(id),
        "data-section-title": sectionTitle,
        className: (0, _ComposerSidebarSt.st)(_ComposerSidebarSt.classes.item, {
          labelPlacement: labelPlacement,
          size: size
        }, className),
        __self: this,
        __source: {
          fileName: _jsxFileName,
          lineNumber: 132,
          columnNumber: 7
        }
      }, /*#__PURE__*/_react["default"].createElement(_ToggleButton["default"], (0, _extends2["default"])({}, rest, {
        tabIndex: isFocused ? 0 : -1,
        onFocus: function onFocus() {
          return _this2.setState({
            focusedIndex: itemIndex
          });
        },
        className: (0, _ComposerSidebarSt.st)(_ComposerSidebarSt.classes.sidebarItemButton, {
          labelPlacement: labelPlacement,
          size: size
        }),
        dataHook: "composer-sidebar-item-".concat(id),
        onClick: function onClick(e) {
          return onClickHandler(e, {
            id: id,
            label: label
          });
        },
        shape: "round",
        size: size,
        border: true,
        skin: "inverted",
        labelEllipsis: ellipsis,
        disabled: disabled,
        selected: selected,
        labelValue: label,
        labelPlacement: labelPlacement,
        tooltipProps: labelTooltipProps,
        __self: this,
        __source: {
          fileName: _jsxFileName,
          lineNumber: 142,
          columnNumber: 9
        }
      }), icon));
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props5 = this.props,
        items = _this$props5.items,
        className = _this$props5.className,
        dataHook = _this$props5.dataHook,
        labelPlacement = _this$props5.labelPlacement,
        width = _this$props5.width;
      var sections = this._separateToSections(items);
      return /*#__PURE__*/_react["default"].createElement(_Box["default"], {
        height: "100%",
        maxHeight: "100%",
        width: width,
        className: (0, _ComposerSidebarSt.st)(_ComposerSidebarSt.classes.root, {
          labelPlacement: labelPlacement
        }, className),
        dataHook: dataHook || _constants.dataHooks.composerSidebarContainer,
        __self: this,
        __source: {
          fileName: _jsxFileName,
          lineNumber: 249,
          columnNumber: 7
        }
      }, sections.length ? this._renderSections(sections) : null);
    }
  }]);
}(_react["default"].PureComponent);
ComposerSidebar.displayName = 'ComposerSidebar';
ComposerSidebar.defaultProps = {
  labelPlacement: 'end',
  selectedId: null,
  items: [],
  size: 'medium',
  onClick: function onClick() {},
  labelTooltipProps: {
    placement: 'right'
  },
  ellipsis: true
};
var _default = exports["default"] = ComposerSidebar;