Liferay.Loader.define("layout-content-page-editor-web@2.0.110/page_editor/app/components/ShortcutManager", ['module', 'exports', 'require', 'frontend-js-metal-web$metal-dom', 'frontend-js-react-web$react', '../config/constants/keycodes', '../config/constants/moveItemDirections', '../selectors/selectCanUpdatePageStructure', '../store/index', '../thunks/deleteItem', '../thunks/duplicateItem', '../thunks/moveItem', '../thunks/redo', '../thunks/undo', '../utils/canBeDuplicated', '../utils/canBeRemoved', '../utils/canBeSaved', './Controls', './SaveFragmentCompositionModal'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    function _typeof(obj) {
      "@babel/helpers - typeof";
      if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
        _typeof = function _typeof(obj) {
          return typeof obj;
        };
      } else {
        _typeof = function _typeof(obj) {
          return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
      }return _typeof(obj);
    }

    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = ShortcutManager;

    var _metalDom = require("frontend-js-metal-web$metal-dom");

    var _react = _interopRequireWildcard(require("frontend-js-react-web$react"));

    var _keycodes = require("../config/constants/keycodes");

    var _moveItemDirections = require("../config/constants/moveItemDirections");

    var _selectCanUpdatePageStructure = _interopRequireDefault(require("../selectors/selectCanUpdatePageStructure"));

    var _index = require("../store/index");

    var _deleteItem = _interopRequireDefault(require("../thunks/deleteItem"));

    var _duplicateItem = _interopRequireDefault(require("../thunks/duplicateItem"));

    var _moveItem = _interopRequireDefault(require("../thunks/moveItem"));

    var _redo = _interopRequireDefault(require("../thunks/redo"));

    var _undo = _interopRequireDefault(require("../thunks/undo"));

    var _canBeDuplicated = _interopRequireDefault(require("../utils/canBeDuplicated"));

    var _canBeRemoved = _interopRequireDefault(require("../utils/canBeRemoved"));

    var _canBeSaved = _interopRequireDefault(require("../utils/canBeSaved"));

    var _Controls = require("./Controls");

    var _SaveFragmentCompositionModal = _interopRequireDefault(require("./SaveFragmentCompositionModal"));

    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { default: obj };
    }

    function _getRequireWildcardCache() {
      if (typeof WeakMap !== "function") return null;var cache = new WeakMap();_getRequireWildcardCache = function _getRequireWildcardCache() {
        return cache;
      };return cache;
    }

    function _interopRequireWildcard(obj) {
      if (obj && obj.__esModule) {
        return obj;
      }if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
        return { default: obj };
      }var cache = _getRequireWildcardCache();if (cache && cache.has(obj)) {
        return cache.get(obj);
      }var newObj = {};var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;for (var key in obj) {
        if (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;
    }

    function _slicedToArray(arr, i) {
      return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
    }

    function _nonIterableRest() {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }

    function _iterableToArrayLimit(arr, i) {
      if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
        return;
      }var _arr = [];var _n = true;var _d = false;var _e = undefined;try {
        for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
          _arr.push(_s.value);if (i && _arr.length === i) break;
        }
      } catch (err) {
        _d = true;_e = err;
      } finally {
        try {
          if (!_n && _i["return"] != null) _i["return"]();
        } finally {
          if (_d) throw _e;
        }
      }return _arr;
    }

    function _arrayWithHoles(arr) {
      if (Array.isArray(arr)) return arr;
    }

    var ctrlOrMeta = function ctrlOrMeta(event) {
      return event.ctrlKey && !event.metaKey || !event.ctrlKey && event.metaKey;
    };

    var isEditableField = function isEditableField(element) {
      return !!(0, _metalDom.closest)(element, '.page-editor__editable');
    };

    var isEditingEditableField = function isEditingEditableField() {
      return !!document.activeElement.getAttribute('contenteditable');
    };

    var isInteractiveElement = function isInteractiveElement(element) {
      return ['INPUT', 'OPTION', 'SELECT', 'TEXTAREA'].includes(element.tagName) || !!(0, _metalDom.closest)(element, '.cke_editable') || !!(0, _metalDom.closest)(element, '.alloy-editor-container');
    };

    var isWithinIframe = function isWithinIframe() {
      return window.top !== window.self;
    };

    function ShortcutManager() {
      var activeItemId = (0, _Controls.useActiveItemId)();
      var dispatch = (0, _index.useDispatch)();
      var selectItem = (0, _Controls.useSelectItem)();
      var canUpdatePageStructure = (0, _index.useSelector)(_selectCanUpdatePageStructure.default);

      var _useState = (0, _react.useState)(false),
          _useState2 = _slicedToArray(_useState, 2),
          openSaveModal = _useState2[0],
          setOpenSaveModal = _useState2[1];

      var state = (0, _index.useSelector)(function (state) {
        return state;
      });
      var fragmentEntryLinks = state.fragmentEntryLinks,
          layoutData = state.layoutData,
          segmentsExperienceId = state.segmentsExperienceId,
          widgets = state.widgets;
      var activeItem = layoutData.items[activeItemId];

      var keymapRef = (0, _react.useRef)(null);
      keymapRef.current = {
        duplicate: {
          action: function duplicate() {
            dispatch((0, _duplicateItem.default)({
              itemId: activeItemId,
              segmentsExperienceId: segmentsExperienceId,
              selectItem: selectItem
            }));
          },
          canBeExecuted: function canBeExecuted() {
            return canUpdatePageStructure && !!layoutData.items[activeItemId] && (0, _canBeDuplicated.default)(fragmentEntryLinks, layoutData.items[activeItemId], layoutData, widgets);
          },
          isKeyCombination: function isKeyCombination(event) {
            return ctrlOrMeta(event) && event.keyCode === _keycodes.D_KEYCODE;
          }
        },
        move: {
          action: function move(event) {
            var itemId = activeItem.itemId,
                parentId = activeItem.parentId;
            var parentItem = layoutData.items[parentId];
            var numChildren = parentItem.children.length;
            var currentPosition = parentItem.children.indexOf(itemId);
            var direction = event.keyCode === _keycodes.ARROW_UP_KEYCODE ? _moveItemDirections.MOVE_ITEM_DIRECTIONS.UP : _moveItemDirections.MOVE_ITEM_DIRECTIONS.DOWN;

            if (direction === _moveItemDirections.MOVE_ITEM_DIRECTIONS.UP && currentPosition === 0 || direction === _moveItemDirections.MOVE_ITEM_DIRECTIONS.DOWN && currentPosition === numChildren - 1) {
              return;
            }

            var position;

            if (direction === _moveItemDirections.MOVE_ITEM_DIRECTIONS.UP) {
              position = currentPosition - 1;
            } else if (direction === _moveItemDirections.MOVE_ITEM_DIRECTIONS.DOWN) {
              position = currentPosition + 1;
            }

            dispatch((0, _moveItem.default)({
              itemId: itemId,
              parentItemId: parentId,
              position: position,
              segmentsExperienceId: segmentsExperienceId
            }));
          },
          canBeExecuted: function canBeExecuted(event) {
            return canUpdatePageStructure && !!layoutData.items[activeItemId] && !isEditableField(event.target) && !isInteractiveElement(event.target);
          },
          isKeyCombination: function isKeyCombination(event) {
            return event.keyCode === _keycodes.ARROW_UP_KEYCODE || event.keyCode === _keycodes.ARROW_DOWN_KEYCODE;
          }
        },
        remove: {
          action: function remove() {
            dispatch((0, _deleteItem.default)({
              itemId: activeItemId,
              selectItem: selectItem,
              store: state
            }));
          },
          canBeExecuted: function canBeExecuted(event) {
            return canUpdatePageStructure && !!layoutData.items[activeItemId] && (0, _canBeRemoved.default)(layoutData.items[activeItemId], layoutData) && !isEditableField(event.target) && !isInteractiveElement(event.target);
          },
          isKeyCombination: function isKeyCombination(event) {
            return event.keyCode === _keycodes.BACKSPACE_KEYCODE;
          }
        },
        save: {
          action: function save() {
            setOpenSaveModal(true);
          },
          canBeExecuted: function canBeExecuted() {
            return canUpdatePageStructure && !!layoutData.items[activeItemId] && (0, _canBeSaved.default)(layoutData.items[activeItemId], layoutData);
          },
          isKeyCombination: function isKeyCombination(event) {
            return ctrlOrMeta(event) && event.keyCode === _keycodes.S_KEYCODE;
          }
        },
        undo: {
          action: function undo(event) {
            if (event.shiftKey) {
              dispatch((0, _redo.default)({
                store: state
              }));
            } else {
              dispatch((0, _undo.default)({
                store: state
              }));
            }
          },
          canBeExecuted: function canBeExecuted(event) {
            return (isEditableField(event.target) || !isInteractiveElement(event.target)) && !isWithinIframe() && !isEditingEditableField();
          },
          isKeyCombination: function isKeyCombination(event) {
            return ctrlOrMeta(event) && event.keyCode === _keycodes.Z_KEYCODE && !event.altKey;
          }
        }
      };
      (0, _react.useEffect)(function () {
        var onKeyDown = function onKeyDown(event) {
          var shortcut = Object.values(keymapRef.current).find(function (shortcut) {
            return shortcut.isKeyCombination(event) && shortcut.canBeExecuted(event);
          });

          if (shortcut) {
            event.stopPropagation();
            event.preventDefault();
            shortcut.action(event);
          }
        };

        window.addEventListener('keydown', onKeyDown, true);
        return function () {
          window.removeEventListener('keydown', onKeyDown, true);
        };
      }, []);
      return (/*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, openSaveModal && /*#__PURE__*/_react.default.createElement(_SaveFragmentCompositionModal.default, {
          onCloseModal: function onCloseModal() {
            return setOpenSaveModal(false);
          }
        }))
      );
    }
    //# sourceMappingURL=ShortcutManager.js.map
  }
});
//# sourceMappingURL=ShortcutManager.js.map