import { useEffect } from "react"; import { editingCellContext } from "../context/EditorContext"; import { selectionContext } from "../context/SelectionContext"; import { useSelectionUtils } from "./useSelectionUtils"; const keyMapping: { [key: string]: "left" | "right" | "up" | "down" } = { ArrowLeft: "left", ArrowRight: "right", ArrowUp: "up", ArrowDown: "down", }; export const useSelectionKeyHandlers = () => { const setSelection = selectionContext.useSetter(); const setEditingCell = editingCellContext.useSetter(); const { offsetSelection, offsetShiftSelection } = useSelectionUtils(); useEffect(() => { const changeSelection = ( shiftKey: boolean, mapping: "left" | "right" | "up" | "down" ) => { setEditingCell(null); if (shiftKey) { setSelection( (selection) => selection && offsetShiftSelection(selection, mapping) ); } else { setSelection( (selection) => selection && offsetSelection(selection, mapping) ); } }; const listener = (e: KeyboardEvent) => { const mapping = keyMapping[e.key]; if (!mapping) { return; } e.preventDefault(); changeSelection(e.shiftKey, mapping); }; window.addEventListener("keydown", listener); return () => window.removeEventListener("keydown", listener); }, []); };