94 lines
2.6 KiB
TypeScript
94 lines
2.6 KiB
TypeScript
"use client";
|
|
|
|
import * as React from "react";
|
|
import { useRouter } from "next/navigation";
|
|
|
|
export interface ShortcutMap {
|
|
[sequence: string]: string;
|
|
}
|
|
|
|
const SEQUENCE_TIMEOUT_MS = 800;
|
|
|
|
export function useKeyboardShortcuts(shortcuts: ShortcutMap) {
|
|
const router = useRouter();
|
|
const [pendingKey, setPendingKey] = React.useState<string | null>(null);
|
|
const pendingKeyRef = React.useRef<string | null>(null);
|
|
const timeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
const shortcutsRef = React.useRef(shortcuts);
|
|
shortcutsRef.current = shortcuts;
|
|
|
|
const firstKeys = React.useMemo(() => {
|
|
const keys = new Set<string>();
|
|
for (const seq of Object.keys(shortcuts)) {
|
|
const first = seq.split(" ")[0];
|
|
if (first) keys.add(first);
|
|
}
|
|
return keys;
|
|
}, [shortcuts]);
|
|
const firstKeysRef = React.useRef(firstKeys);
|
|
firstKeysRef.current = firstKeys;
|
|
|
|
React.useEffect(() => {
|
|
const handleKeyDown = (e: KeyboardEvent) => {
|
|
if (
|
|
(e.target instanceof HTMLElement && e.target.isContentEditable) ||
|
|
e.target instanceof HTMLInputElement ||
|
|
e.target instanceof HTMLTextAreaElement ||
|
|
e.target instanceof HTMLSelectElement
|
|
) {
|
|
return;
|
|
}
|
|
|
|
const key = e.key.toLowerCase();
|
|
|
|
if (key === "escape") {
|
|
pendingKeyRef.current = null;
|
|
setPendingKey(null);
|
|
if (timeoutRef.current) {
|
|
clearTimeout(timeoutRef.current);
|
|
timeoutRef.current = null;
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (pendingKeyRef.current === null) {
|
|
if (firstKeysRef.current.has(key)) {
|
|
pendingKeyRef.current = key;
|
|
setPendingKey(key);
|
|
timeoutRef.current = setTimeout(() => {
|
|
pendingKeyRef.current = null;
|
|
setPendingKey(null);
|
|
timeoutRef.current = null;
|
|
}, SEQUENCE_TIMEOUT_MS);
|
|
return;
|
|
}
|
|
} else {
|
|
const sequence = `${pendingKeyRef.current} ${key}`;
|
|
const target = shortcutsRef.current[sequence];
|
|
|
|
pendingKeyRef.current = null;
|
|
setPendingKey(null);
|
|
if (timeoutRef.current) {
|
|
clearTimeout(timeoutRef.current);
|
|
timeoutRef.current = null;
|
|
}
|
|
|
|
if (target) {
|
|
e.preventDefault();
|
|
router.push(target);
|
|
return;
|
|
}
|
|
}
|
|
};
|
|
|
|
document.addEventListener("keydown", handleKeyDown);
|
|
return () => {
|
|
document.removeEventListener("keydown", handleKeyDown);
|
|
if (timeoutRef.current) {
|
|
clearTimeout(timeoutRef.current);
|
|
}
|
|
};
|
|
}, [router]);
|
|
|
|
return { pendingKey };
|
|
}
|