import { useEffect } from "react"; import { useNavigate } from "react-router-dom"; import type { CurrentUser } from "../api/client"; import { visibleNav, isGroup } from "../layout/nav"; import { GO_SHORTCUTS, SHOW_SHORTCUTS_EVENT } from "../layout/shortcuts"; /** Whether the keyboard is typing into something, in which case a letter is a letter and not a shortcut. */ function isTyping(target: EventTarget | null): boolean { const el = target as HTMLElement | null; if (!el || !el.tagName) return false; return el.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(el.tagName); } /** * Page shortcuts for anyone signed in: "g" then a letter goes to a page they are allowed to see, "/" jumps to the table's * search box, "j" and "k" move down and up the table's rows (Enter then opens the one you are on), "?" shows the list. Ignored while typing, while a dialog is open, and with Ctrl/Alt/Cmd held (those are the * browser's and the command palette's). */ export function useShortcuts(user: CurrentUser): void { const navigate = useNavigate(); useEffect(() => { const allowed = new Set(["/", "/wall"]); for (const entry of visibleNav(user.role)) { if (isGroup(entry)) entry.items.forEach((i) => allowed.add(i.to)); else allowed.add(entry.to); } let waitingForSecondKey = false; let timer: ReturnType | null = null; const reset = () => { waitingForSecondKey = false; if (timer) clearTimeout(timer); timer = null; }; function onKeyDown(e: KeyboardEvent) { if (e.ctrlKey || e.metaKey || e.altKey || isTyping(e.target)) return; if (document.querySelector('[role="dialog"][aria-modal="true"]')) return; if (waitingForSecondKey) { reset(); const hit = GO_SHORTCUTS.find((s) => s.key === e.key.toLowerCase()); if (hit && allowed.has(hit.to)) { e.preventDefault(); navigate(hit.to); } return; } if (e.key === "j" || e.key === "k") { const rows = [...document.querySelectorAll("tr.row-clickable")].filter((r) => r.offsetParent !== null); if (rows.length === 0) return; const current = (document.activeElement as HTMLElement | null)?.closest("tr.row-clickable") ?? null; const at = current ? rows.indexOf(current) : -1; const next = e.key === "j" ? rows[Math.min(at + 1, rows.length - 1)] : rows[Math.max(at - 1, 0)]; e.preventDefault(); next.focus(); next.scrollIntoView({ block: "nearest" }); } else if (e.key === "g") { waitingForSecondKey = true; timer = setTimeout(reset, 1200); } else if (e.key === "[") { e.preventDefault(); window.dispatchEvent(new Event("toggle-sidebar")); } else if (e.key === "?") { e.preventDefault(); window.dispatchEvent(new Event(SHOW_SHORTCUTS_EVENT)); } else if (e.key === "/") { const box = document.querySelector(".table-search input"); if (box) { e.preventDefault(); box.focus(); box.select(); } } } window.addEventListener("keydown", onKeyDown); return () => { window.removeEventListener("keydown", onKeyDown); reset(); }; }, [user.role, navigate]); }