"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useSideNavToggleKeyboardShortcut = useSideNavToggleKeyboardShortcut;
var _react = require("react");
var _bindEventListener = require("bind-event-listener");
var _useStableRef = _interopRequireDefault(require("@atlaskit/ds-lib/use-stable-ref"));
var _openLayerObserver = require("@atlaskit/layering/experimental/open-layer-observer");
var _platformFeatureFlags = require("@atlaskit/platform-feature-flags");
var _isSideNavShortcutEnabledContext = require("./is-side-nav-shortcut-enabled-context");
var _useToggleSideNav = require("./use-toggle-side-nav");
/**
 * Binds the keyboard shortcut to toggle the side nav.
 */
function useSideNavToggleKeyboardShortcut(_ref) {
  var canToggleWithShortcut = _ref.canToggleWithShortcut;
  var openLayerObserver = (0, _openLayerObserver.useOpenLayerObserver)();
  var toggleVisibilityByShortcut = (0, _useToggleSideNav.useToggleSideNav)({
    trigger: 'keyboard'
  });
  var canToggleWithShortcutStableRef = (0, _useStableRef.default)(canToggleWithShortcut);
  var isSideNavShortcutEnabled = (0, _isSideNavShortcutEnabledContext.useIsSideNavShortcutEnabled)();
  (0, _react.useEffect)(function () {
    if (!(0, _platformFeatureFlags.fg)('navx-full-height-sidebar')) {
      return;
    }
    if (!isSideNavShortcutEnabled) {
      return;
    }
    return (0, _bindEventListener.bind)(window, {
      type: 'keydown',
      listener: function listener(event) {
        if (event.ctrlKey && event.key === '[') {
          if (canToggleWithShortcutStableRef.current && !canToggleWithShortcutStableRef.current()) {
            // Return early if the callback returns false.
            // If the callback is not provided, we assume the shortcut is enabled.
            return;
          }
          if (event.repeat) {
            // Ignore repeated keydown events from holding down the keys
            return;
          }
          if (openLayerObserver.getCount({
            type: 'modal'
          }) > 0) {
            // Return early if there are any open modals
            return;
          }
          toggleVisibilityByShortcut();
        }
      }
    });
  }, [canToggleWithShortcutStableRef, openLayerObserver, toggleVisibilityByShortcut, isSideNavShortcutEnabled]);
}