Skip to content

Commit

Permalink
[@mantine/hooks] use-hotkeys: Add option to use getHotkeyHandler with…
Browse files Browse the repository at this point in the history
… .addEventListener events (#1952)
  • Loading branch information
rtivital committed Aug 13, 2022
1 parent d52e46f commit 882aebb
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
18 changes: 17 additions & 1 deletion docs/src/docs/hooks/use-hotkeys.mdx
Expand Up @@ -44,6 +44,20 @@ which should be used with `onKeyDown`:

<Demo data={HooksDemos.useHotkeysDemo} />

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
Expand All @@ -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;
```
9 changes: 5 additions & 4 deletions src/mantine-hooks/src/use-hotkeys/parse-hotkey.ts
Expand Up @@ -75,14 +75,15 @@ export function getHotkeyMatcher(hotkey: string): CheckHotkeyMatch {
return (event) => isExactHotkey(parseHotkey(hotkey), event);
}

type HotkeyItem = [string, (event: React.KeyboardEvent<HTMLElement>) => void];
type HotkeyItem = [string, (event: React.KeyboardEvent<HTMLElement> | KeyboardEvent) => void];

export function getHotkeyHandler(hotkeys: HotkeyItem[]) {
return (event: React.KeyboardEvent<HTMLElement>) => {
return (event: React.KeyboardEvent<HTMLElement> | 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);
}
});
};
Expand Down

0 comments on commit 882aebb

Please sign in to comment.