import { useMenu } from "../../hooks/useMenu";
import { useHotkey } from "../../hooks/useHotkey";
import { FEAGlobals } from "../../../common/Globals";
import { useDeepEffect } from "../../hooks/useDeepEffect";
/**
 * A component that registers a custom hotkeys pattern for opening and closing the menu.
 * This component is used privately by <MenuShell>
 *
 * Note that a design decision was made to keep registry of "close" hotkeys simple.
 * We *could* have written extra logic so that the close hotkey is only registered
 * when the window is open but that seems unnecessary. Instead, every menu is always
 * registered with its hotkey. The net effect is that every menu will dispatch a CLOSE_MENU
 * action when "escape" is called. This creates a lot of dispatches but results in no operations
 * since all the other menus will already be closed. This was preferable over the potential
 * complication of logic that registers/unregisters a close hotkey with every menu open/close.
 * @param {string[]} [open] - An array of key names for opening the menu.
 * @param {string[]} [close] - An optional key-chord (e.g. ["ctrl","H"]) which will close the menu. Use this for instance when you want the same key-chord to toggle a menu open and closed. Note that the escape key will always close the menu.
 */
export const MenuHotKey = ({ open, close }) => {
    const { openMenu, closeMenu, isMenuActive } = useMenu();
    useHotkey(open, openMenu);
    function hotkeyHandler() {
        if (!isMenuActive())
            return;
        closeMenu();
        // Once menu closes, return focus to the component that launched the menu
        FEAGlobals.finsembleWindow.bringToFront(null, (err) => {
            if (err) {
                FEAGlobals.FSBL.Clients.Logger.system.error("failed to bringToFront, error:", err);
            }
            FEAGlobals.finsembleWindow.focus();
        });
    }
    useDeepEffect(() => {
        // Don't add a handler for the escape key because it is already handled automatically by MenuPortal.tsx
        const isEscape = (close === null || close === void 0 ? void 0 : close.length) === 1 && ["escape", "esc"].includes(close[0].toLowerCase());
        if (close && (close === null || close === void 0 ? void 0 : close.length) > 0 && !isEscape) {
            FEAGlobals.FSBL.Clients.HotkeyClient.addGlobalHotkey(close, hotkeyHandler);
            return () => {
                FEAGlobals.FSBL.Clients.HotkeyClient.removeGlobalHotkey(close, hotkeyHandler);
            };
        }
    }, [close]);
    return null;
};
//# sourceMappingURL=MenuHotKey.js.map