Skip to content

Commit 0867637

Browse files
committed
fix(core): allow passing key combination as string
1 parent f0b5f67 commit 0867637

File tree

1 file changed

+22
-13
lines changed

1 file changed

+22
-13
lines changed

packages/core/src/composables/useKeyPress.ts

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { ref, watch } from 'vue'
22
import type { KeyFilter, KeyPredicate, MaybeRefOrGetter } from '@vueuse/core'
33
import { onKeyStroke, toValue, useEventListener } from '@vueuse/core'
44
import { useWindow } from './useWindow'
5-
import { isBoolean, isFunction } from '~/utils'
5+
import { isBoolean, isFunction, isString } from '~/utils'
66

77
export function isInputDOMNode(event: KeyboardEvent): boolean {
88
const target = (event.composedPath?.()?.[0] || event.target) as HTMLElement
@@ -20,18 +20,27 @@ function wasModifierPressed(event: KeyboardEvent) {
2020
return event.ctrlKey || event.metaKey || event.shiftKey
2121
}
2222

23-
function createKeyPredicate(keyFilter: string[], pressedKeys: Set<string>): KeyPredicate {
24-
return (event: KeyboardEvent) =>
25-
keyFilter.some((key) => {
26-
const keyCombination = key.split('+').map((k) => k.trim().toLowerCase())
23+
function isKeyMatch(pressedKey: string, keyToMatch: string, pressedKeys: Set<string>) {
24+
const keyCombination = keyToMatch.split('+').map((k) => k.trim().toLowerCase())
2725

28-
if (keyCombination.length === 1) {
29-
return event.key === key
30-
} else {
31-
pressedKeys.add(event.key.toLowerCase())
32-
return keyCombination.every((key) => pressedKeys.has(key))
33-
}
34-
})
26+
if (keyCombination.length === 1) {
27+
return pressedKey === keyToMatch
28+
} else {
29+
pressedKeys.add(pressedKey.toLowerCase())
30+
return keyCombination.every((key) => pressedKeys.has(key))
31+
}
32+
}
33+
34+
function createKeyPredicate(keyFilter: string | string[], pressedKeys: Set<string>): KeyPredicate {
35+
return (event: KeyboardEvent) => {
36+
// if the keyFilter is an array of multiple keys, we need to check each possible key combination
37+
if (Array.isArray(keyFilter)) {
38+
return keyFilter.some((key) => isKeyMatch(event.key, key, pressedKeys))
39+
}
40+
41+
// if the keyFilter is a string, we need to check if the key matches the string
42+
return isKeyMatch(event.key, keyFilter, pressedKeys)
43+
}
3544
}
3645

3746
/**
@@ -67,7 +76,7 @@ export function useKeyPress(keyFilter: MaybeRefOrGetter<KeyFilter | null>, onCha
6776
return
6877
}
6978

70-
if (Array.isArray(unrefKeyFilter)) {
79+
if (Array.isArray(unrefKeyFilter) || (isString(unrefKeyFilter) && unrefKeyFilter.includes('+'))) {
7180
unrefKeyFilter = createKeyPredicate(unrefKeyFilter, pressedKeys)
7281
}
7382

0 commit comments

Comments
 (0)