Skip to content

Commit c929b53

Browse files
Merge pull request #1275 from matiastucci/main
Try to prevent events firing incorrectly when using `useKey: true`
2 parents 3e86321 + b2ad010 commit c929b53

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

packages/react-hotkeys-hook/src/lib/validators.ts

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,21 @@ export const isHotkeyMatchingKeyboardEvent = (e: KeyboardEvent, hotkey: Hotkey,
8989

9090
const mappedCode = mapCode(code)
9191

92-
if (useKey && keys?.length === 1 && keys.includes(producedKey.toLowerCase())) {
93-
return true
92+
if (useKey) {
93+
if (keys?.length === 1 && keys.includes(producedKey.toLowerCase())) {
94+
if (!ignoreModifiers) {
95+
if (alt !== altKey) return false
96+
if (shift !== shiftKey) return false
97+
if (mod) {
98+
if (!metaKey && !ctrlKey) return false
99+
} else {
100+
if (meta !== metaKey) return false
101+
if (ctrl !== ctrlKey) return false
102+
}
103+
}
104+
return true
105+
}
106+
return false
94107
}
95108

96109
if (

packages/react-hotkeys-hook/src/test/useHotkeys.test.tsx

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1732,4 +1732,28 @@ test('Should trigger only produced key hotkeys', async () => {
17321732
await user.keyboard('Y')
17331733
expect(callbackZ).toHaveBeenCalledTimes(1)
17341734
expect(callbackY).toHaveBeenCalledTimes(2)
1735-
})
1735+
})
1736+
1737+
test('Should trigger only produced key hotkeys with Dvorak layout', async () => {
1738+
const callbackDWithUseKey = vi.fn()
1739+
1740+
renderHook(() => useHotkeys('h', callbackDWithUseKey, { useKey: true }))
1741+
1742+
const keyDownEventUSLayout = createEvent.keyDown(document, {
1743+
key: 'h',
1744+
code: 'KeyH',
1745+
keyCode: 72
1746+
})
1747+
1748+
fireEvent(document, keyDownEventUSLayout)
1749+
1750+
const keyDownEventDvorakLayout = createEvent.keyDown(document, {
1751+
key: 'd',
1752+
code: 'KeyH',
1753+
keyCode: 68
1754+
})
1755+
1756+
fireEvent(document, keyDownEventDvorakLayout)
1757+
1758+
expect(callbackDWithUseKey).toHaveBeenCalledTimes(1)
1759+
})

0 commit comments

Comments
 (0)