Files
pihkaal-me/app/composables/useKeyDown.ts

45 lines
1.1 KiB
TypeScript

import { mapCodeToNDS } from "~/utils/input";
export type KeyDownCallback = (params: {
key: string;
ndsButton: string | null;
repeated: boolean;
}) => void;
export const useKeyDown = (
callback: KeyDownCallback,
// the confirmation modal's own buttons rely on useKeyDown, so this is opt-in
options: { ignoreWhenModalOpen?: boolean } = {},
) => {
const app = useAppStore();
const confirmationModal = useConfirmationModal();
const handleKeyDown = (event: KeyboardEvent) => {
if (app.lagModalOpen) return;
if (options.ignoreWhenModalOpen && confirmationModal.isOpen) return;
const ndsButton = mapCodeToNDS(event.code);
if (
ndsButton &&
document.activeElement &&
document.activeElement !== document.body
) {
(document.activeElement as HTMLElement).blur();
}
callback({
key: ndsButton ? `NDS_${ndsButton}` : event.key,
ndsButton,
repeated: event.repeat,
});
};
onMounted(() => {
window.addEventListener("keydown", handleKeyDown);
});
onUnmounted(() => {
window.removeEventListener("keydown", handleKeyDown);
});
};