All files / src/hooks useKeyboardHandlers.ts

44.12% Statements 15/34
0% Branches 0/10
28.57% Functions 2/7
44.12% Lines 15/34

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 671x   1x 1x               1x 1x   1x 10x 10x             10x   10x     10x   10x     10x     10x                             10x                              
import * as React from "react";
import { TSetData } from "../components";
import { deleteSelectedItems } from "../utils";
import { useWindowEvent } from "./useWindowEvent";
 
export interface IUseKeyboardHandlersArgs {
  setIsSpaceHeld: React.Dispatch<React.SetStateAction<boolean>>;
  setData: TSetData;
  getIsCanvasFocused(): boolean;
}
 
const keyDownHandlerMap = new Map<string, (evt: KeyboardEvent) => void>();
const keyUpHandlerMap = new Map<string, (evt: KeyboardEvent) => void>();
 
export const useKeyboardHandlers = (args: IUseKeyboardHandlersArgs) => {
  React.useMemo(() => {
    const spaceKeyDownHandler = (evt: KeyboardEvent) => {
      if (evt.repeat) {
        return;
      }
 
      args.setIsSpaceHeld.call(null, true);
    };
    keyDownHandlerMap.set(" ", spaceKeyDownHandler);
 
    const deleteKeyDownHandler = () => {
      deleteSelectedItems(args.setData.bind(null));
    };
    keyDownHandlerMap.set("Delete", deleteKeyDownHandler);
 
    const spaceKeyUpHandler = (evt: KeyboardEvent) => {
      args.setIsSpaceHeld.call(null, false);
    };
    keyUpHandlerMap.set(" ", spaceKeyUpHandler);
  }, []);
 
  useWindowEvent("keydown", (evt: KeyboardEvent) => {
    if (!args.getIsCanvasFocused()) {
      return;
    }
 
    evt.preventDefault();
    evt.stopPropagation();
 
    const handler = keyDownHandlerMap.get(evt.key);
 
    if (handler) {
      handler.call(null, evt);
    }
  });
 
  useWindowEvent("keyup", (evt: KeyboardEvent) => {
    if (!args.getIsCanvasFocused()) {
      return;
    }
 
    evt.preventDefault();
    evt.stopPropagation();
 
    const handler = keyUpHandlerMap.get(evt.key);
 
    if (handler) {
      handler.call(null, evt);
    }
  });
};