40 lines
993 B
TypeScript
40 lines
993 B
TypeScript
import { useEffect } from 'react'
|
|
|
|
export function useKeyboardShortcuts(): void {
|
|
useEffect(() => {
|
|
const handleKeyDown = (e: KeyboardEvent): void => {
|
|
if (e.key === '/' && !isInputFocused()) {
|
|
e.preventDefault()
|
|
focusSearchInput()
|
|
}
|
|
}
|
|
|
|
document.addEventListener('keydown', handleKeyDown)
|
|
return () => {
|
|
document.removeEventListener('keydown', handleKeyDown)
|
|
}
|
|
}, [])
|
|
}
|
|
|
|
function isInputFocused(): boolean {
|
|
const { activeElement } = document
|
|
if (!activeElement) {
|
|
return false
|
|
}
|
|
const tagName = activeElement.tagName.toLowerCase()
|
|
return (
|
|
tagName === 'input' ||
|
|
tagName === 'textarea' ||
|
|
activeElement.getAttribute('contenteditable') === 'true' ||
|
|
activeElement.getAttribute('role') === 'textbox'
|
|
)
|
|
}
|
|
|
|
function focusSearchInput(): void {
|
|
const searchInput = document.querySelector<HTMLInputElement>('input[role="search"]')
|
|
if (searchInput) {
|
|
searchInput.focus()
|
|
searchInput.select()
|
|
}
|
|
}
|