"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ColorPaletteArrowKeyNavigationProvider = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = _interopRequireWildcard(require("react"));
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); }
/**
 * This component is a wrapper for color picker which listens to keydown events of children
 * and handles arrow key navigation
 */
var ColorPaletteArrowKeyNavigationProvider = exports.ColorPaletteArrowKeyNavigationProvider = function ColorPaletteArrowKeyNavigationProvider(_ref) {
  var children = _ref.children,
    selectedRowIndex = _ref.selectedRowIndex,
    selectedColumnIndex = _ref.selectedColumnIndex,
    isOpenedByKeyboard = _ref.isOpenedByKeyboard,
    isPopupPositioned = _ref.isPopupPositioned,
    handleClose = _ref.handleClose,
    closeOnTab = _ref.closeOnTab,
    editorRef = _ref.editorRef,
    ignoreEscapeKey = _ref.ignoreEscapeKey,
    popupsMountPoint = _ref.popupsMountPoint;
  var wrapperRef = (0, _react.useRef)(null);
  var currentSelectedColumnIndex = (0, _react.useRef)(selectedColumnIndex === -1 ? 0 : selectedColumnIndex);
  var currentSelectedRowIndex = (0, _react.useRef)(selectedRowIndex === -1 ? 0 : selectedRowIndex);
  var element = popupsMountPoint ? popupsMountPoint : editorRef.current;
  var _useState = (0, _react.useState)(element),
    _useState2 = (0, _slicedToArray2.default)(_useState, 1),
    listenerTargetElement = _useState2[0];
  var incrementRowIndex = function incrementRowIndex(rowElements, columnElements) {
    if (currentSelectedRowIndex.current === rowElements.length - 1) {
      currentSelectedRowIndex.current = 0;
    } else {
      currentSelectedRowIndex.current = currentSelectedRowIndex.current + 1;
    }
  };
  var decrementRowIndex = function decrementRowIndex(rowElements, columnElements) {
    if (currentSelectedRowIndex.current === 0) {
      currentSelectedRowIndex.current = rowElements.length - 1;
    } else {
      currentSelectedRowIndex.current = currentSelectedRowIndex.current - 1;
    }
  };
  (0, _react.useLayoutEffect)(function () {
    var incrementColumnIndex = function incrementColumnIndex(rowElements, columnElements) {
      if (currentSelectedColumnIndex.current === columnElements.length - 1) {
        incrementRowIndex(rowElements, columnElements);
        currentSelectedColumnIndex.current = 0;
      } else {
        currentSelectedColumnIndex.current = currentSelectedColumnIndex.current + 1;
      }
    };
    var decrementColumnIndex = function decrementColumnIndex(rowElements, columnElements) {
      if (currentSelectedColumnIndex.current === 0) {
        decrementRowIndex(rowElements, columnElements);
        currentSelectedColumnIndex.current = columnElements.length - 1;
      } else {
        currentSelectedColumnIndex.current = currentSelectedColumnIndex.current - 1;
      }
    };
    var focusColorSwatch = function focusColorSwatch() {
      var _focusableElements$cu;
      var colorSwatchesRowElements = getColorSwatchesRows(wrapperRef === null || wrapperRef === void 0 ? void 0 : wrapperRef.current);
      var currentSelectedColorSwatchRowElement = colorSwatchesRowElements[currentSelectedRowIndex.current];
      var focusableElements = getFocusableElements(currentSelectedColorSwatchRowElement);
      if (!focusableElements || (focusableElements === null || focusableElements === void 0 ? void 0 : focusableElements.length) === 0) {
        return;
      }
      (_focusableElements$cu = focusableElements[currentSelectedColumnIndex.current]) === null || _focusableElements$cu === void 0 || _focusableElements$cu.focus();
    };

    /**
     * To handle the key events on the list
     * @param event
     */
    var handleKeyDown = function handleKeyDown(event) {
      if (event.key === 'Tab' && closeOnTab) {
        // Ignored via go/ees005
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        handleClose(event);
        return;
      }
      var colorSwatchesRowElements = getColorSwatchesRows(wrapperRef === null || wrapperRef === void 0 ? void 0 : wrapperRef.current);
      var currentSelectedColorSwatchRowElement = colorSwatchesRowElements[currentSelectedRowIndex.current];
      var focusableElements = getFocusableElements(currentSelectedColorSwatchRowElement);
      switch (event.key) {
        case 'ArrowDown':
          incrementRowIndex(colorSwatchesRowElements, focusableElements);
          focusColorSwatch();
          event.preventDefault();
          break;
        case 'ArrowUp':
          decrementRowIndex(colorSwatchesRowElements, focusableElements);
          focusColorSwatch();
          event.preventDefault();
          break;
        case 'ArrowLeft':
          decrementColumnIndex(colorSwatchesRowElements, focusableElements);
          focusColorSwatch();
          event.preventDefault();
          break;
        case 'ArrowRight':
          incrementColumnIndex(colorSwatchesRowElements, focusableElements);
          focusColorSwatch();
          event.preventDefault();
          break;
        case 'Escape':
          if (!ignoreEscapeKey) {
            // Ignored via go/ees005
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            handleClose(event);
          }
          break;
        default:
          return;
      }
    };

    // Ignored via go/ees005
    // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners
    listenerTargetElement && listenerTargetElement.addEventListener('keydown', handleKeyDown);
    // set focus to current selected color swatch if only opened by keyboard
    if (isOpenedByKeyboard && isPopupPositioned) {
      // Using timeout because, we need to wait till color palette is rendered
      //  and visible on screen, then only focus color swatch, otherwise focus will be
      //  moved to body
      setTimeout(function () {
        focusColorSwatch();
      });
    }
    return function () {
      // Ignored via go/ees005
      // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners
      listenerTargetElement && listenerTargetElement.removeEventListener('keydown', handleKeyDown);
    };
  }, [currentSelectedColumnIndex, isOpenedByKeyboard, isPopupPositioned, wrapperRef, handleClose, closeOnTab, ignoreEscapeKey, listenerTargetElement]);
  return (
    /*#__PURE__*/
    // eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop -- Ignored via go/DSP-18766
    _react.default.createElement("div", {
      className: "custom-key-handler-wrapper",
      ref: wrapperRef
    }, children)
  );
};
function getColorSwatchesRows(rootNode) {
  if (!rootNode) {
    return [];
  }
  var colorSwatchesRowElements = rootNode.querySelectorAll('div[role=radiogroup]') || [];
  return Array.from(colorSwatchesRowElements);
}
function getFocusableElements(rootNode) {
  if (!rootNode) {
    return [];
  }
  var focusableModalElements = rootNode.querySelectorAll('button[role=radio]:not([disabled])') || [];
  return Array.from(focusableModalElements);
}