diff --git a/docs/src/docs/hooks/use-hotkeys.mdx b/docs/src/docs/hooks/use-hotkeys.mdx index 8044d5ec8d7..61d378a8e3f 100644 --- a/docs/src/docs/hooks/use-hotkeys.mdx +++ b/docs/src/docs/hooks/use-hotkeys.mdx @@ -44,6 +44,20 @@ which should be used with `onKeyDown`: +With `getHotkeyHandler` you can also add events to any dom node using `.addEventListener`: + +```tsx +import { getHotkeyHandler } from '@mantine/hooks'; + +document.body.addEventListener( + 'keydown', + getHotkeyHandler([ + ['mod+Enter', () => console.log('Submit')], + ['mod+S', () => console.log('Save')], + ]) +); +``` + ## Supported formats - `mod+S` – detects `⌘+S` on macOS and `Ctrl+S` on Windows @@ -54,5 +68,7 @@ which should be used with `onKeyDown`: ## Definition ```tsx -function useHotkeys(hotKeyItem: Array<[hotkey: string, handler: (event: KeyboardEvent) => void]>): void; +function useHotkeys( + hotKeyItem: Array<[hotkey: string, handler: (event: KeyboardEvent) => void]> +): void; ``` diff --git a/src/mantine-hooks/src/use-hotkeys/parse-hotkey.ts b/src/mantine-hooks/src/use-hotkeys/parse-hotkey.ts index d787445c9de..8fe5d67aee3 100644 --- a/src/mantine-hooks/src/use-hotkeys/parse-hotkey.ts +++ b/src/mantine-hooks/src/use-hotkeys/parse-hotkey.ts @@ -75,14 +75,15 @@ export function getHotkeyMatcher(hotkey: string): CheckHotkeyMatch { return (event) => isExactHotkey(parseHotkey(hotkey), event); } -type HotkeyItem = [string, (event: React.KeyboardEvent) => void]; +type HotkeyItem = [string, (event: React.KeyboardEvent | KeyboardEvent) => void]; export function getHotkeyHandler(hotkeys: HotkeyItem[]) { - return (event: React.KeyboardEvent) => { + return (event: React.KeyboardEvent | KeyboardEvent) => { + const _event = 'nativeEvent' in event ? event.nativeEvent : event; hotkeys.forEach(([hotkey, handler]) => { - if (getHotkeyMatcher(hotkey)(event.nativeEvent)) { + if (getHotkeyMatcher(hotkey)(_event)) { event.preventDefault(); - handler(event); + handler(_event); } }); };