Skip to content

Commit

Permalink
[@mantine/hooks] use-hotkeys: Fix + sign not being supported (synta…
Browse files Browse the repository at this point in the history
…x: `shift+[plus]`) (#7123)
  • Loading branch information
rtivital committed Nov 16, 2024
1 parent bd40d73 commit 0cdab90
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 1 deletion.
1 change: 1 addition & 0 deletions apps/mantine.dev/src/pages/hooks/use-hotkeys.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ document.body.addEventListener(
- `ctrl+shift+X` – handles multiple modifiers
- `alt + shift + L` – you can use whitespace inside hotkey
- `ArrowLeft` – you can use special keys using [this format](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values)
- `shift + [plus]` – you can use `[plus]` to detect `+` key

## Types

Expand Down
20 changes: 20 additions & 0 deletions packages/@mantine/hooks/src/use-hotkeys/parse-hotkey.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,24 @@ describe('@mantine/hooks/use-hot-key/parse-hotkey', () => {
)
).toBe(false);
});

it('parses [plus] key correctly', () => {
expect(parseHotkey('ctrl+[plus]')).toMatchObject({
alt: false,
ctrl: true,
meta: false,
mod: false,
shift: false,
key: '+',
});

expect(parseHotkey('ctrl+[plus]+shift+alt+[plus]')).toMatchObject({
alt: true,
ctrl: true,
meta: false,
mod: false,
shift: true,
key: '+',
});
});
});
4 changes: 3 additions & 1 deletion packages/@mantine/hooks/src/use-hotkeys/parse-hotkey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export type KeyboardModifiers = {
meta: boolean;
mod: boolean;
shift: boolean;
plus: boolean;
};

export type Hotkey = KeyboardModifiers & {
Expand All @@ -24,6 +25,7 @@ export function parseHotkey(hotkey: string): Hotkey {
meta: keys.includes('meta'),
mod: keys.includes('mod'),
shift: keys.includes('shift'),
plus: keys.includes('[plus]'),
};

const reservedKeys = ['alt', 'ctrl', 'meta', 'shift', 'mod'];
Expand All @@ -32,7 +34,7 @@ export function parseHotkey(hotkey: string): Hotkey {

return {
...modifiers,
key: freeKey,
key: freeKey === '[plus]' ? '+' : freeKey,
};
}

Expand Down
7 changes: 7 additions & 0 deletions packages/@mantine/hooks/src/use-hotkeys/use-hotkeys.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,11 @@ describe('@mantine/hooks/use-hotkey', () => {
dispatchEvent({ metaKey: true, altKey: true, key: 'P' });
expect(handler).not.toHaveBeenCalled();
});

it('correctly handles [plus] key', () => {
const handler = jest.fn();
renderHook(() => useHotkeys([['shift+[plus]', handler]]));
dispatchEvent({ shiftKey: true, key: '+' });
expect(handler).toHaveBeenCalled();
});
});

0 comments on commit 0cdab90

Please sign in to comment.