All files / src/hooks useAppKeyboard.ts

75% Statements 15/20
37.5% Branches 3/8
75% Functions 6/8
80% Lines 12/15

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                                    88x         22x                   22x 22x 1x 1x 1x 1x 1x 1x     22x 22x      
import { useEffect, useMemo } from 'react'
 
interface KeyboardActions {
  onQuickOpen: () => void
  onCreateNote: () => void
  onSave: () => void
  onTrashNote: (path: string) => void
  onArchiveNote: (path: string) => void
  activeTabPathRef: React.MutableRefObject<string | null>
  handleCloseTabRef: React.MutableRefObject<(path: string) => void>
}
 
type ShortcutHandler = () => void
 
export function useAppKeyboard({
  onQuickOpen, onCreateNote, onSave, onTrashNote, onArchiveNote,
  activeTabPathRef, handleCloseTabRef,
}: KeyboardActions) {
  const withActiveTab = (fn: (path: string) => void): ShortcutHandler => () => {
    const path = activeTabPathRef.current
    if (path) fn(path)
  }
 
  const keyMap = useMemo((): Record<string, ShortcutHandler> => ({
    p: onQuickOpen,
    n: onCreateNote,
    s: onSave,
    e: withActiveTab(onArchiveNote),
    w: withActiveTab((path) => handleCloseTabRef.current(path)),
    Backspace: withActiveTab(onTrashNote),
    Delete: withActiveTab(onTrashNote),
  }), [onQuickOpen, onCreateNote, onSave, onTrashNote, onArchiveNote, activeTabPathRef, handleCloseTabRef])
 
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      const mod = e.metaKey || e.ctrlKey
      Iif (!mod) return
      const handler = keyMap[e.key]
      Eif (handler) {
        e.preventDefault()
        handler()
      }
    }
    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [keyMap])
}