import { onMounted, onUnmounted } from 'vue'

type ShortcutHandler = (e: KeyboardEvent) => void

interface Shortcut {
  key: string
  meta?: boolean
  shift?: boolean
  handler: ShortcutHandler
}

export function useKeyboardShortcuts(shortcuts: Shortcut[]) {
  function onKeydown(e: KeyboardEvent) {
    for (const s of shortcuts) {
      const metaMatch = s.meta ? (e.metaKey || e.ctrlKey) : true
      const shiftMatch = s.shift ? e.shiftKey : !e.shiftKey
      if (e.key === s.key && metaMatch && shiftMatch) {
        e.preventDefault()
        s.handler(e)
        return
      }
    }
  }

  onMounted(() => document.addEventListener('keydown', onKeydown))
  onUnmounted(() => document.removeEventListener('keydown', onKeydown))
}
