grungnet/src/contexts/KeyboardContext.tsx

97 lines
2.5 KiB
TypeScript
Raw Permalink Normal View History

import React, { useEffect, useState, useContext } from "react";
import { EventEmitter } from "events";
2021-08-05 00:51:07 -04:00
const keyboardEmitter = new EventEmitter();
keyboardEmitter.setMaxListeners(100);
const KeyboardContext = React.createContext({ keyEmitter: keyboardEmitter });
export function KeyboardProvider({ children }: { children: React.ReactNode }) {
2021-08-05 00:51:07 -04:00
const [keyEmitter] = useState(keyboardEmitter);
useEffect(() => {
2021-06-02 03:49:31 -04:00
function handleKeyDown(event: Event) {
// Ignore text input
if (
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLTextAreaElement
) {
return;
}
keyEmitter.emit("keyDown", event);
}
2021-06-02 03:49:31 -04:00
function handleKeyUp(event: Event) {
// Ignore text input
if (
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLTextAreaElement
) {
return;
}
keyEmitter.emit("keyUp", event);
}
document.body.addEventListener("keydown", handleKeyDown);
document.body.addEventListener("keyup", handleKeyUp);
document.body.tabIndex = 1;
return () => {
document.body.removeEventListener("keydown", handleKeyDown);
document.body.removeEventListener("keyup", handleKeyUp);
document.body.tabIndex = 0;
};
}, [keyEmitter]);
return (
<KeyboardContext.Provider value={{ keyEmitter }}>
{children}
</KeyboardContext.Provider>
);
}
export function useKeyboard(
onKeyDown?: (event: KeyboardEvent) => void,
onKeyUp?: (event: KeyboardEvent) => void
) {
const context = useContext(KeyboardContext);
if (context === undefined) {
throw new Error("useKeyboard must be used within a KeyboardProvider");
}
const { keyEmitter } = context;
useEffect(() => {
if (onKeyDown) {
keyEmitter.on("keyDown", onKeyDown);
}
if (onKeyUp) {
keyEmitter.on("keyUp", onKeyUp);
}
return () => {
if (onKeyDown) {
keyEmitter.off("keyDown", onKeyDown);
}
if (onKeyUp) {
keyEmitter.off("keyUp", onKeyUp);
}
};
});
}
2021-03-18 22:29:07 -04:00
/**
* Handler to handle a blur event. Useful when using a shortcut that uses the Alt or Cmd
* @param {FocusEvent} onBlur
*/
2021-06-02 03:49:31 -04:00
export function useBlur(onBlur: EventListenerOrEventListenerObject) {
2021-03-18 22:29:07 -04:00
useEffect(() => {
if (onBlur) {
window.addEventListener("blur", onBlur);
}
return () => {
if (onBlur) {
window.removeEventListener("blur", onBlur);
}
};
});
}
export default KeyboardContext;