Skip to content

Commit

Permalink
fix(useHotKey): validate event keys as case-insensitive by default
Browse files Browse the repository at this point in the history
Signed-off-by: Maksim Sukharev <[email protected]>
  • Loading branch information
Antreesy committed Dec 11, 2024
1 parent c67b40c commit 85cb275
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
1 change: 1 addition & 0 deletions docs/composables/useHotKey.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ where:
- `ctrl`: whether the Ctrl key (Cmd key on MacOS) should be pressed (default: `false`)
- `alt`: whether the Alt key should be pressed (default: `false`)
- `shift`: whether the Shift key should be pressed (should be explicitly defined as `true`|`false` if needed)
- `caseSensitive`: whether specific case should be listened, e.g. only 'd' and not 'D' (default: `false`)
- `stopCallback`: a callback to stop listening to the event

### Playground
Expand Down
38 changes: 36 additions & 2 deletions src/composables/useHotKey/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,48 @@ export function useHotKey(keysOrFilter, callback = () => {}, options = {}) {
return () => {}
}

const stopKeyDown = onKeyStroke(keysOrFilter, eventHandler(callback, options), {
/**
* Validates event key to expected key
* FIXME should support any languages / key codes
*
* @param {KeyboardEvent} event keyboard event
* @param {string} key expected key
* @return {boolean} whether it satisfies expected value or not
*/
const validateKeyEvent = (event, key) => {
if (options.caseSensitive) {
return event.key === key
}
return event.key.toLowerCase() === key.toLowerCase()
}

/**
* Filter function for the listener
* see https://github.com/vueuse/vueuse/blob/v11.3.0/packages/core/onKeyStroke/index.ts#L21-L32
*
* @param {KeyboardEvent} event keyboard event
* @return {boolean} whether it satisfies expected value or not
*/
const keyFilter = (event) => {
if (typeof keysOrFilter === 'function') {
return keysOrFilter(event)
} else if (typeof keysOrFilter === 'string') {
return validateKeyEvent(event, keysOrFilter)
} else if (Array.isArray(keysOrFilter)) {
return keysOrFilter.some(key => validateKeyEvent(event, key))
} else {
return true
}
}

const stopKeyDown = onKeyStroke(keyFilter, eventHandler(callback, options), {
eventName: 'keydown',
dedupe: true,
passive: !options.prevent,
})

const stopKeyUp = options.push
? onKeyStroke(keysOrFilter, eventHandler(callback, options), {
? onKeyStroke(keyFilter, eventHandler(callback, options), {
eventName: 'keyup',
passive: !options.prevent,
})
Expand Down

0 comments on commit 85cb275

Please sign in to comment.