File size: 1,520 Bytes
1e92f2d |
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 |
import { useEffect } from 'react'
import { getActiveElement } from '../components/errors/dev-tools-indicator/utils'
export function useShortcuts(
shortcuts: Record<string, () => void>,
rootRef: React.RefObject<HTMLElement | null>
) {
useEffect(() => {
function handleKeyDown(e: KeyboardEvent) {
if (isFocusedOnElement(rootRef)) return
const keys = []
if (e.metaKey) keys.push('Meta')
if (e.ctrlKey) keys.push('Control')
if (e.altKey) keys.push('Alt')
if (e.shiftKey) keys.push('Shift')
if (
e.key !== 'Meta' &&
e.key !== 'Control' &&
e.key !== 'Alt' &&
e.key !== 'Shift'
) {
keys.push(e.code)
}
const shortcut = keys.join('+')
if (shortcuts[shortcut]) {
e.preventDefault()
shortcuts[shortcut]()
}
}
window.addEventListener('keydown', handleKeyDown)
return () => window.removeEventListener('keydown', handleKeyDown)
}, [rootRef, shortcuts])
}
export function isFocusedOnElement(
rootRef: React.RefObject<HTMLElement | null>
) {
const el = getActiveElement(rootRef.current)
if (!el) return false
if (
el.contentEditable === 'true' ||
el.tagName === 'INPUT' ||
el.tagName === 'TEXTAREA' ||
el.tagName === 'SELECT' ||
el.dataset['shortcut-recorder'] === 'true'
) {
// It's okay to trigger global keybinds from readonly inputs
if (el.hasAttribute('readonly')) {
return false
}
return true
}
return false
}
|