"use strict";

var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ToolbarArrowKeyNavigationProvider = exports.KeyDownHandlerContext = void 0;
var _react = _interopRequireWildcard(require("react"));
var _react2 = require("@emotion/react");
var _messages = require("../../messages");
var _ui = require("../../ui");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
/** @jsx jsx */
/* eslint-disable no-console */

/*
 **  The context is used to handle the keydown events of submenus.
 **  Because the keyboard navigation is explicitly managed for main toolbar items
 **  Few key presses such as Tab,Arrow Right/Left need ot be handled here via context
 */
var KeyDownHandlerContext = exports.KeyDownHandlerContext = /*#__PURE__*/_react.default.createContext({
  handleArrowLeft: function handleArrowLeft() {},
  handleArrowRight: function handleArrowRight() {},
  handleTab: function handleTab() {}
});
var centeredToolbarContainer = (0, _react2.css)({
  display: 'flex',
  width: '100%',
  alignItems: 'center'
});

/**
 * This component is a wrapper of main toolbar which listens to keydown events of children
 * and handles left/right arrow key navigation for all focusable elements
 * @param
 * @returns
 */
var ToolbarArrowKeyNavigationProvider = exports.ToolbarArrowKeyNavigationProvider = function ToolbarArrowKeyNavigationProvider(_ref) {
  var children = _ref.children,
    editorView = _ref.editorView,
    childComponentSelector = _ref.childComponentSelector,
    handleEscape = _ref.handleEscape,
    disableArrowKeyNavigation = _ref.disableArrowKeyNavigation,
    isShortcutToFocusToolbar = _ref.isShortcutToFocusToolbar,
    editorAppearance = _ref.editorAppearance,
    useStickyToolbar = _ref.useStickyToolbar,
    intl = _ref.intl;
  var wrapperRef = (0, _react.useRef)(null);
  var selectedItemIndex = (0, _react.useRef)(0);
  var incrementIndex = (0, _react.useCallback)(function (list) {
    var index = 0;
    if (document.activeElement) {
      index = list.indexOf(document.activeElement);
      index = (index + 1) % list.length;
    }
    selectedItemIndex.current = index;
  }, []);
  var decrementIndex = (0, _react.useCallback)(function (list) {
    var index = 0;
    if (document.activeElement) {
      index = list.indexOf(document.activeElement);
      index = (list.length + index - 1) % list.length;
    }
    selectedItemIndex.current = index;
  }, []);
  var handleArrowRight = function handleArrowRight() {
    var _filteredFocusableEle;
    var filteredFocusableElements = getFilteredFocusableElements(wrapperRef === null || wrapperRef === void 0 ? void 0 : wrapperRef.current);
    incrementIndex(filteredFocusableElements);
    (_filteredFocusableEle = filteredFocusableElements[selectedItemIndex.current]) === null || _filteredFocusableEle === void 0 || _filteredFocusableEle.focus();
  };
  var handleArrowLeft = function handleArrowLeft() {
    var _filteredFocusableEle2;
    var filteredFocusableElements = getFilteredFocusableElements(wrapperRef === null || wrapperRef === void 0 ? void 0 : wrapperRef.current);
    decrementIndex(filteredFocusableElements);
    (_filteredFocusableEle2 = filteredFocusableElements[selectedItemIndex.current]) === null || _filteredFocusableEle2 === void 0 || _filteredFocusableEle2.focus();
  };
  var handleTab = function handleTab() {
    var _filteredFocusableEle3;
    var filteredFocusableElements = getFilteredFocusableElements(wrapperRef === null || wrapperRef === void 0 ? void 0 : wrapperRef.current);
    (_filteredFocusableEle3 = filteredFocusableElements[selectedItemIndex.current]) === null || _filteredFocusableEle3 === void 0 || _filteredFocusableEle3.focus();
  };
  var handleTabLocal = function handleTabLocal() {
    var filteredFocusableElements = getFilteredFocusableElements(wrapperRef === null || wrapperRef === void 0 ? void 0 : wrapperRef.current);
    filteredFocusableElements.forEach(function (element) {
      element.setAttribute('tabindex', '-1');
    });
    filteredFocusableElements[selectedItemIndex.current].setAttribute('tabindex', '0');
  };
  var focusAndScrollToElement = function focusAndScrollToElement(element) {
    var scrollToElement = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
    if (scrollToElement) {
      element === null || element === void 0 || element.scrollIntoView({
        behavior: 'smooth',
        block: 'center',
        inline: 'nearest'
      });
    }
    element.focus();
  };
  var submenuKeydownHandleContext = {
    handleArrowLeft: handleArrowLeft,
    handleArrowRight: handleArrowRight,
    handleTab: handleTab
  };
  (0, _react.useLayoutEffect)(function () {
    if (!wrapperRef.current || disableArrowKeyNavigation) {
      return;
    }
    var element = wrapperRef.current;

    /**
     * To handle the key events on the list
     * @param event
     */
    var handleKeyDown = function handleKeyDown(event) {
      var _document$querySelect, _document$querySelect2, _wrapperRef$current;
      // To trap the focus inside the horizontal toolbar for left and right arrow keys
      var targetElement = event.target;

      // To filter out the events outside the child component
      if (!targetElement.closest("".concat(childComponentSelector))) {
        return;
      }

      // The key events are from child components such as dropdown menus / popups are ignored
      if ((_document$querySelect = document.querySelector('[data-role="droplistContent"], [data-test-id="color-picker-menu"], [data-emoji-picker-container="true"]')) !== null && _document$querySelect !== void 0 && _document$querySelect.contains(targetElement) || (_document$querySelect2 = document.querySelector('[data-test-id="color-picker-menu"]')) !== null && _document$querySelect2 !== void 0 && _document$querySelect2.contains(targetElement) || event.key === 'ArrowUp' || event.key === 'ArrowDown' || disableArrowKeyNavigation) {
        return;
      }
      var menuWrapper = document.querySelector('.menu-key-handler-wrapper');
      if (menuWrapper) {
        // if menu wrapper exists, then a menu is open and arrow keys will be handled by MenuArrowKeyNavigationProvider
        return;
      }
      var filteredFocusableElements = getFilteredFocusableElements(wrapperRef === null || wrapperRef === void 0 ? void 0 : wrapperRef.current);
      if (!filteredFocusableElements || (filteredFocusableElements === null || filteredFocusableElements === void 0 ? void 0 : filteredFocusableElements.length) === 0) {
        return;
      }

      // This is kind of hack to reset the current focused toolbar item
      // to handle some use cases such as Tab in/out of main toolbar
      if (!((_wrapperRef$current = wrapperRef.current) !== null && _wrapperRef$current !== void 0 && _wrapperRef$current.contains(targetElement))) {
        selectedItemIndex.current = -1;
      } else {
        selectedItemIndex.current = filteredFocusableElements.indexOf(targetElement) > -1 ? filteredFocusableElements.indexOf(targetElement) : selectedItemIndex.current;
      }

      // do not scroll to focused element for sticky toolbar when navigating with arrows to avoid unnesessary scroll jump
      var allowScrollToElement = !(editorAppearance === 'comment' && !!useStickyToolbar);
      switch (event.key) {
        case 'ArrowRight':
          incrementIndex(filteredFocusableElements);
          focusAndScrollToElement(filteredFocusableElements[selectedItemIndex.current], allowScrollToElement);
          event.preventDefault();
          break;
        case 'ArrowLeft':
          decrementIndex(filteredFocusableElements);
          focusAndScrollToElement(filteredFocusableElements[selectedItemIndex.current], allowScrollToElement);
          event.preventDefault();
          break;
        case 'Tab':
          handleTabLocal();
          break;
        case 'Escape':
          handleEscape(event);
          break;
        default:
      }
    };
    var globalKeyDownHandler = function globalKeyDownHandler(event) {
      // To focus the first element in the toolbar
      if (isShortcutToFocusToolbar(event)) {
        var _filteredFocusableEle4, _filteredFocusableEle5;
        var filteredFocusableElements = getFilteredFocusableElements(wrapperRef === null || wrapperRef === void 0 ? void 0 : wrapperRef.current);
        (_filteredFocusableEle4 = filteredFocusableElements[0]) === null || _filteredFocusableEle4 === void 0 || _filteredFocusableEle4.focus();
        (_filteredFocusableEle5 = filteredFocusableElements[0]) === null || _filteredFocusableEle5 === void 0 || _filteredFocusableEle5.scrollIntoView({
          behavior: 'smooth',
          block: 'center',
          inline: 'nearest'
        });
      }
    };
    element === null || element === void 0 || element.addEventListener('keydown', handleKeyDown);
    var editorViewDom = editorView === null || editorView === void 0 ? void 0 : editorView.dom;
    if (isShortcutToFocusToolbar) {
      editorViewDom === null || editorViewDom === void 0 || editorViewDom.addEventListener('keydown', globalKeyDownHandler);
    }
    return function () {
      element === null || element === void 0 || element.removeEventListener('keydown', handleKeyDown);
      if (isShortcutToFocusToolbar) {
        editorViewDom === null || editorViewDom === void 0 || editorViewDom.removeEventListener('keydown', globalKeyDownHandler);
      }
    };
  }, [selectedItemIndex, wrapperRef, editorView, disableArrowKeyNavigation, handleEscape, childComponentSelector, incrementIndex, decrementIndex, isShortcutToFocusToolbar, editorAppearance, useStickyToolbar]);
  return (0, _react2.jsx)("div", {
    css: editorAppearance === 'comment' && centeredToolbarContainer,
    className: "custom-key-handler-wrapper",
    ref: wrapperRef,
    role: "toolbar",
    "aria-label": intl.formatMessage(_messages.fullPageMessages.toolbarLabel),
    "aria-controls": _ui.EDIT_AREA_ID
  }, (0, _react2.jsx)(KeyDownHandlerContext.Provider, {
    value: submenuKeydownHandleContext
  }, children));
};
function getFocusableElements(rootNode) {
  if (!rootNode) {
    return [];
  }
  var focusableModalElements = rootNode.querySelectorAll('a[href], button:not([disabled]), textarea, input, select, div[tabindex="-1"], div[tabindex="0"]') || [];
  return Array.from(focusableModalElements);
}
function getFilteredFocusableElements(rootNode) {
  // The focusable elements from child components such as dropdown menus / popups are ignored
  return getFocusableElements(rootNode).filter(function (elm) {
    var style = window.getComputedStyle(elm);
    // ignore invisible element to avoid losing focus
    var isVisible = style.visibility !== 'hidden' && style.display !== 'none';
    return !elm.closest('[data-role="droplistContent"]') && !elm.closest('[data-emoji-picker-container="true"]') && !elm.closest('[data-test-id="color-picker-menu"]') && !elm.closest('.scroll-buttons') && isVisible;
  });
}