Spaces:
Sleeping
Sleeping
File size: 1,349 Bytes
6fc49c1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | import { useEffect } from "react";
interface Opts {
onCode: () => void;
onNext: () => void;
onPrev: () => void;
enabled?: boolean;
}
/**
* Global keybinds:
* Cmd/Ctrl + Enter — Code the current note
* j / ArrowDown — Select next HCC candidate
* k / ArrowUp — Select previous HCC candidate
*
* Ignored while the user is typing into an editable control so it doesn't
* fight with the textarea.
*/
export function useKeybinds({ onCode, onNext, onPrev, enabled = true }: Opts) {
useEffect(() => {
if (!enabled) return;
function handler(e: KeyboardEvent) {
const target = e.target as HTMLElement | null;
const inEditable =
!!target &&
(target.tagName === "INPUT" ||
target.tagName === "TEXTAREA" ||
target.isContentEditable);
if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
e.preventDefault();
onCode();
return;
}
if (inEditable) return;
if (e.key === "j" || e.key === "ArrowDown") {
e.preventDefault();
onNext();
} else if (e.key === "k" || e.key === "ArrowUp") {
e.preventDefault();
onPrev();
}
}
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [onCode, onNext, onPrev, enabled]);
}
|