vim.ts 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { Dispatch, useEffect } from 'react';
  2. export const Keys = {
  3. tab: 'Tab',
  4. enter: 'Enter',
  5. esc: 'Escape',
  6. space: ' ',
  7. colon: ':',
  8. question: '?',
  9. '1': '1',
  10. C: 'c',
  11. J: 'j',
  12. K: 'k',
  13. };
  14. const availableKeys = Object.values(Keys);
  15. export const ActionTypeKeyPressed = '@@vim/KEY_PRESSED';
  16. export type ActionKeyPressed = {
  17. type: typeof ActionTypeKeyPressed;
  18. key: string;
  19. };
  20. export function useVimBindings(dispatch: Dispatch<ActionKeyPressed>, skip = false): void {
  21. useEffect(() => {
  22. if (skip) {
  23. return (): void => {
  24. // pass
  25. };
  26. }
  27. const listener = (event: KeyboardEvent): void => {
  28. if (!availableKeys.includes(event.key)) {
  29. return;
  30. }
  31. event.preventDefault();
  32. const action: ActionKeyPressed = { type: ActionTypeKeyPressed, key: event.key };
  33. dispatch(action);
  34. };
  35. window.addEventListener('keydown', listener);
  36. return (): void => {
  37. window.removeEventListener('keydown', listener);
  38. };
  39. }, [dispatch, skip]);
  40. }