Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix repeat bug #928

Merged
merged 3 commits into from
Jan 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 16 additions & 6 deletions documentation/docs/documentation/advanced-usage.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,24 @@ This section described advanced functionalities of the hook.

**🚧 This section is under construction 🚧**

## Listening on `keyUp`
## Using typescript types to reference key names
Sometimes we might get confused if we need to listen to `ArrowLeft` or `LeftArrow` to listen to the left arrow key.
To avoid this confusion, we can use the typescript types provided by the `ts-key-now` library.

## Retrieve pressed hotkey
You add the library to your project by running:

## Enable hotkeys on input fields
```bash
npm install ts-key-now
```

## The `contentEditable` prop
Then you can import the types and use them in your code:

## Using the `filter` option
```ts
import { Key } from 'ts-key-enum'

## `filter` vs `enabled`
useHotkeys(Key.Backspace, () => {
console.log(`delete`)
})
```

See https://gitlab.com/nfriend/ts-key-enum/-/blob/master/Key.enum.d.ts for the full list of available keys.
3 changes: 2 additions & 1 deletion src/parseHotkeys.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Hotkey, KeyboardModifiers, Keys } from './types'

const reservedModifierKeywords = ['shift', 'alt', 'meta', 'mod']
const reservedModifierKeywords = ['shift', 'alt', 'meta', 'mod', 'ctrl']

const mappedKeys: Record<string, string> = {
esc: 'escape',
Expand Down Expand Up @@ -52,6 +52,7 @@ export function parseHotkey(hotkey: string, combinationKey: string = '+'): Hotke

const modifiers: KeyboardModifiers = {
alt: keys.includes('alt'),
ctrl: keys.includes('ctrl') || keys.includes('control'),
shift: keys.includes('shift'),
meta: keys.includes('meta'),
mod: keys.includes('mod'),
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export type RefType<T> = T | null

export type KeyboardModifiers = {
alt?: boolean
ctrl?: boolean
meta?: boolean
shift?: boolean
mod?: boolean
Expand Down
6 changes: 4 additions & 2 deletions src/useHotkeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,10 @@ export default function useHotkeys<T extends HTMLElement>(
const hotkey = parseHotkey(key, memoisedOptions?.combinationKey)

if (isHotkeyMatchingKeyboardEvent(e, hotkey, memoisedOptions?.ignoreModifiers) || hotkey.keys?.includes('*')) {
if (isKeyUp && hasTriggeredRef.current) return

if (isKeyUp && hasTriggeredRef.current) {
return
}

maybePreventDefault(e, hotkey, memoisedOptions?.preventDefault)

if (!isHotkeyEnabled(e, hotkey, memoisedOptions?.enabled)) {
Expand Down
20 changes: 10 additions & 10 deletions src/validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,23 +47,19 @@ export function isScopeActive(activeScopes: string[], scopes?: Scopes): boolean
}

export const isHotkeyMatchingKeyboardEvent = (e: KeyboardEvent, hotkey: Hotkey, ignoreModifiers: boolean = false): boolean => {
const { alt, meta, mod, shift, keys } = hotkey
const { key: pressedKeyUppercase, code } = e

const altKey = isHotkeyPressed('alt')
const shiftKey = isHotkeyPressed('shift')
const metaKey = isHotkeyPressed('meta')
const ctrlKey = isHotkeyPressed('ctrl')
const { alt, meta, mod, shift, ctrl, keys } = hotkey
const { key: pressedKeyUppercase, code, ctrlKey, metaKey, shiftKey, altKey } = e

const keyCode = mapKey(code)
const pressedKey = pressedKeyUppercase.toLowerCase()

if (!ignoreModifiers) {
if (altKey !== alt && pressedKey !== 'alt') {
// We check the pressed keys for compatibility with the keyup event. In keyup events the modifier flags are not set.
if (alt === !altKey && (alt && pressedKey !== 'alt')) {
return false
}

if (shiftKey !== shift && pressedKey !== 'shift') {
if (shift === !shiftKey && (shift && pressedKey !== 'shift')) {
return false
}

Expand All @@ -73,7 +69,11 @@ export const isHotkeyMatchingKeyboardEvent = (e: KeyboardEvent, hotkey: Hotkey,
return false
}
} else {
if (metaKey !== meta && ctrlKey !== meta) {
if (meta === !metaKey && (meta && pressedKey !== 'meta')) {
return false
}

if (ctrl === !ctrlKey && (ctrl && pressedKey !== 'ctrl')) {
return false
}
}
Expand Down
32 changes: 20 additions & 12 deletions tests/useHotkeys.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -766,6 +766,7 @@ test('should pass keyboard event and hotkey object to callback', async () => {
expect(callback).toHaveBeenCalledWith(expect.any(KeyboardEvent), {
keys: ['a'],
shift: false,
ctrl: false,
alt: false,
meta: false,
mod: false,
Expand All @@ -784,26 +785,28 @@ test('should set shift to true in hotkey object if listening to shift', async ()
expect(callback).toHaveBeenCalledWith(expect.any(KeyboardEvent), {
keys: ['a'],
shift: true,
ctrl: false,
alt: false,
meta: false,
mod: false,
})
})

test('should set meta to true in hotkey object if listening to meta', async () => {
test('should set ctrl to true in hotkey object if listening to ctrl', async () => {
const user = userEvent.setup()
const callback = jest.fn()

renderHook(() => useHotkeys('meta+a', callback))
renderHook(() => useHotkeys('ctrl+a', callback))

await user.keyboard('{Meta>}A{/Control}')
await user.keyboard('{Control>}A{/Control}')

expect(callback).toHaveBeenCalledTimes(1)
expect(callback).toHaveBeenCalledWith(expect.any(KeyboardEvent), {
keys: ['a'],
shift: false,
ctrl: true,
alt: false,
meta: true,
meta: false,
mod: false,
})
})
Expand All @@ -820,45 +823,48 @@ test('should set alt to true in hotkey object if listening to alt', async () =>
expect(callback).toHaveBeenCalledWith(expect.any(KeyboardEvent), {
keys: ['a'],
shift: false,
ctrl: false,
alt: true,
meta: false,
mod: false,
})
})

test('should set meta to true in hotkey object if listening to meta', async () => {
test('should set mod to true in hotkey object if listening to mod', async () => {
const user = userEvent.setup()
const callback = jest.fn()

renderHook(() => useHotkeys('meta+a', callback))
renderHook(() => useHotkeys('mod+a', callback))

await user.keyboard('{Meta>}A{/Meta}')

expect(callback).toHaveBeenCalledTimes(1)
expect(callback).toHaveBeenCalledWith(expect.any(KeyboardEvent), {
keys: ['a'],
shift: false,
ctrl: false,
alt: false,
meta: true,
mod: false,
meta: false,
mod: true,
})
})

test('should set mod to true in hotkey object if listening to mod', async () => {
test('should set meta to true in hotkey object if listening to meta', async () => {
const user = userEvent.setup()
const callback = jest.fn()

renderHook(() => useHotkeys('mod+a', callback))
renderHook(() => useHotkeys('meta+a', callback))

await user.keyboard('{Meta>}A{/Meta}')

expect(callback).toHaveBeenCalledTimes(1)
expect(callback).toHaveBeenCalledWith(expect.any(KeyboardEvent), {
keys: ['a'],
shift: false,
ctrl: false,
alt: false,
meta: false,
mod: true,
meta: true,
mod: false,
})
})

Expand All @@ -875,6 +881,7 @@ test('should set multiple modifiers to true in hotkey object if listening to mul
keys: ['a'],
shift: true,
alt: false,
ctrl: false,
meta: false,
mod: true,
})
Expand Down Expand Up @@ -973,6 +980,7 @@ test('should call preventDefault option function with hotkey and keyboard event'
keys: ['a'],
shift: false,
alt: false,
ctrl: false,
meta: false,
mod: false,
})
Expand Down