file-keys.ts
This file
Path
apps/web/src/features/code/file-keys.ts
74 lines · 1.8 KiB · TypeScript
Last changed by
Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72
History of this fileTake it
Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 1–2why, one step back1import { useEffect, useRef } from "react";2Finish the Control room: every page passes axe and a keyboard walk in both schemesoscabrielbefore adoption3fd50a5
line 3why, one step back3import { inField, intentOf, useKeys } from "../shared/keys.tsx";Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 4–42why, one step back45export const stepFrom = (6 paths: readonly string[],7 current: string | undefined,8 step: 1 | -19): string | undefined => {10 const at = current === undefined ? -1 : paths.indexOf(current);1112 if (at === -1) {13 return step === 1 ? paths[0] : paths.at(-1);14 }1516 return paths[Math.min(Math.max(at + step, 0), paths.length - 1)];17};1819export const useCodeFileKeys = (20 paths: readonly string[],21 current: string | undefined,22 onMove: (path: string) => void23) => {24 const on = useKeys()?.on ?? true;25 const latest = useRef({ current, on, onMove, paths });2627 useEffect(() => {28 latest.current = { current, on, onMove, paths };29 });3031 useEffect(() => {32 const onKey = (event: KeyboardEvent) => {33 const now = latest.current;3435 if (event.defaultPrevented || event.repeat) {36 return;37 }3839 const intent = intentOf(40 {41 altKey: event.altKey,42 ctrlKey: event.ctrlKey,Finish the Control room: every page passes axe and a keyboard walk in both schemesoscabrielbefore adoption3fd50a5
line 43why, one step back43 inField: inField(event),Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 44–65why, one step back44 key: event.key,45 metaKey: event.metaKey,46 },47 now.on48 );4950 if (intent?.kind !== "nextFile" && intent?.kind !== "previousFile") {51 return;52 }5354 const next = stepFrom(55 now.paths,56 now.current,57 intent.kind === "nextFile" ? 1 : -158 );5960 if (next !== undefined && next !== now.current) {61 event.preventDefault();62 now.onMove(next);63 }64 };65Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72
lines 66–67why, one step back66 // Captured, to run before the tree's own keys, which take letters to find a67 // row.Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 68–74why, one step back68 document.addEventListener("keydown", onKey, { capture: true });6970 return () => {71 document.removeEventListener("keydown", onKey, { capture: true });72 };73 }, []);74};